CT401 – Computer Programming

Tribhuvan University · Institute of Engineering · BE Year I / Part I

Access the notes here (Syllabus based on IOE)



Contents [Old Question Set-wise]



Contents [Most repeated questions; Chapter-wise]

OLD QUESTION SET WITH THEIR SOLUTIONS

082 Shrawan 082 Baishakh 081 Bhadra 081 Baishakh 080 Bhadra 080 Baishakh 079 Bhadra 078 Bhadra 078 Kartik 076 Chaitra 076 Ashwin 075 Chaitra

Set 1 | 082 Shrawan | Batch Out

Computer Programming [CT401]
Define instruction and program. Discuss in brief about different generation of programming languages.
082 Shrawan [1+3]

Instruction

An instruction is a basic command given to a computer to perform a specific operation such as arithmetic, data transfer, or logical comparison. It is the smallest unit of a program that the processor can execute.

Program

A program is a set of instructions written in a programming language that directs a computer to perform a specific task or solve a problem. It is executed sequentially (or conditionally) by the CPU.

Generations of Programming Languages

GenerationNameDescriptionExample
1GLMachine LanguageBinary instructions (0s and 1s) directly understood by CPU. Machine-dependent, very fast but difficult to write and debug.10110000 01100001
2GLAssembly LanguageUses mnemonics (MOV, ADD) instead of binary. Requires assembler to convert to machine code. Still hardware-dependent.MOV AX, 01H
3GLHigh-Level LanguageEnglish-like syntax, machine-independent. Requires compiler or interpreter. Easy to learn and use.C, C++, FORTRAN, Java
4GLVery High-Level LanguageCloser to human language. Used for database queries, report generation. Less coding required.SQL, MATLAB, Python
5GLNatural / AI LanguageBased on solving problems using constraints. Used in AI and expert systems. Programmer defines what to solve, not how.Prolog, LISP
Explain the importance of problem analysis in software development. Write an algorithm and draw a flowchart to test whether a number entered by user is even or not.
082 Shrawan [1+3]

Importance of Problem Analysis

Problem analysis is the first and most critical step in software development. Its importance includes:

  • Clearly defines the input, output, and constraints of the problem.
  • Helps identify the correct approach before coding begins, saving time and effort.
  • Reduces errors and rework during later stages.
  • Forms the basis for writing algorithms, flowcharts, and test cases.
  • Ensures the final software actually solves the intended problem.

Algorithm – Check Even or Odd

Step 1: Start
Step 2: Read a number N from the user
Step 3: If N MOD 2 = 0, go to Step 4, else go to Step 5
Step 4: Print "N is Even", go to Step 6
Step 5: Print "N is Odd"
Step 6: Stop

Flowchart – Check Even or Odd

Start Read N N MOD 2 = 0 ? Yes Even No Odd Stop
What is an expression? What are the types of expression?
082 Shrawan [2+2]

Expression

An expression is a combination of operands (variables, constants) and operators that evaluates to a single value. Every expression has a type determined by its operands and operators.

a + b        // evaluates to sum
x > y        // evaluates to true or false
a = 5        // assignment expression

Types of Expression

TypeDescriptionExample
ArithmeticInvolves arithmetic operators; evaluates to a numeric valuea + b, x * 2 - 1
RelationalCompares two values; evaluates to true (1) or false (0)a > b, x == y
LogicalCombines relational expressions using logical operatorsa > 0 && b > 0
AssignmentAssigns a value to a variable; returns assigned valuex = 5, a += 3
BitwiseOperates on bits of integer operandsa & b, x | y, ~a
Conditional (Ternary)Returns one of two values based on conditiona > b ? a : b
CommaEvaluates multiple expressions; returns last valuex = (a=1, b=2, a+b)
Explain about input and output function available in C with syntax and example of each part.
082 Shrawan [2+2+2]

Formatted Input/Output

printf() – Displays formatted output to the screen.

Syntax:  printf("format string", variable_list);
Example: printf("Sum = %d", a + b);

scanf() – Reads formatted input from the keyboard.

Syntax:  scanf("format string", &variable_list);
Example: scanf("%d %f", &n, &x);

Unformatted Input/Output

getchar() / putchar() – Reads/writes a single character.

char c;
c = getchar();   // reads one character
putchar(c);      // prints one character

gets() / puts() – Reads/writes a string.

char name[50];
gets(name);      // reads a string (until newline)
puts(name);      // prints string followed by newline

Format Specifiers

SpecifierData Type
%dInteger
%fFloat
%cCharacter
%sString
%lfDouble
Compare nested if with else if ladder structure along with their flowchart.
082 Shrawan [4]

Nested if

An if statement inside another if statement. Used when a condition depends on another condition being true first.

if (condition1) {
    if (condition2) {
        // executes when both condition1 and condition2 are true
    } else {
        // executes when condition1 true, condition2 false
    }
} else {
    // executes when condition1 is false
}

else if Ladder

A series of if-else if conditions checked one by one. Used for multi-way branching where conditions are mutually exclusive.

if (condition1) {
    // block 1
} else if (condition2) {
    // block 2
} else if (condition3) {
    // block 3
} else {
    // default block
}

Comparison

FeatureNested ifelse if Ladder
Structureif inside another ifSequential if-else if chain
Use caseDependent conditionsIndependent, mutually exclusive conditions
ReadabilityCan become complex with deep nestingMore readable for multiple conditions
ExecutionInner if checked only if outer if is trueEach condition checked in sequence until one is true
Defaultelse for each levelSingle final else handles all unmatched cases
Write a program to check whether a number entered by the user is prime or composite.
082 Shrawan [4]

C Program – Prime or Composite

#include <stdio.h>
int main() {
    int n, i, flag = 0;
    printf("Enter a number: ");
    scanf("%d", &n);

    if (n <= 1) {
        printf("%d is neither prime nor composite.\n", n);
        return 0;
    }

    for (i = 2; i <= n / 2; i++) {
        if (n % i == 0) {
            flag = 1;
            break;
        }
    }

    if (flag == 1)
        printf("%d is a Prime number.\n", n);
    else
        printf("%d is a Composite number.\n", n);

    return 0;
}

Output

Enter a number: 13
13 is a Prime number.

Enter a number: 12
12 is a Composite number.
What do you mean by "call by value and call by reference"? Explain it with suitable example.
082 Shrawan [4]

Call by Value

In call by value, a copy of the actual argument is passed to the function. Changes made inside the function do NOT affect the original variable.

#include <stdio.h>
void square(int x) {
    x = x * x;   // only local copy is changed
    printf("Inside: %d\n", x);
}
int main() {
    int a = 5;
    square(a);
    printf("Outside: %d\n", a);  // a remains 5
    return 0;
}
// Output:
// Inside: 25
// Outside: 5

Call by Reference

In call by reference, the address of the actual argument is passed. Changes made inside the function DO affect the original variable.

#include <stdio.h>
void square(int *x) {
    *x = (*x) * (*x);  // original variable is changed
    printf("Inside: %d\n", *x);
}
int main() {
    int a = 5;
    square(&a);
    printf("Outside: %d\n", a);  // a is now 25
    return 0;
}
// Output:
// Inside: 25
// Outside: 25

Comparison

FeatureCall by ValueCall by Reference
What is passedCopy of valueAddress of variable
Original affected?NoYes
MemoryExtra copy createdNo extra copy
SafetySafer (no side effects)Risk of unintended changes
Write a program to display the factorial of an integer entered by the user using the concept of recursive function.
082 Shrawan [4]

C Program – Factorial Using Recursion

#include <stdio.h>

int factorial(int n) {
    if (n == 0 || n == 1)
        return 1;             // base case
    return n * factorial(n - 1); // recursive call
}

int main() {
    int n;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    printf("Factorial of %d = %d\n", n, factorial(n));
    return 0;
}

Output

Enter a positive integer: 5
Factorial of 5 = 120

Recursive Trace (n=5)

factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
= 120
Write a program to reverse a string without using string handling function.
082 Shrawan [4]

C Program – Reverse a String

#include <stdio.h>
int main() {
    char str[100], rev[100];
    int i, len = 0;

    printf("Enter a string: ");
    scanf("%s", str);

    // Find length manually
    while (str[len] != '\0')
        len++;

    // Copy in reverse
    for (i = 0; i < len; i++)
        rev[i] = str[len - 1 - i];
    rev[len] = '\0';

    printf("Reversed string: %s\n", rev);
    return 0;
}

Output

Enter a string: HELLO
Reversed string: OLLEH
Write a program to display the largest and smallest number among 10 numbers entered by the user.
082 Shrawan [6]

C Program – Largest and Smallest among 10 Numbers

#include <stdio.h>
int main() {
    int a[10], i, max, min;

    printf("Enter 10 numbers:\n");
    for (i = 0; i < 10; i++) {
        printf("Number %d: ", i + 1);
        scanf("%d", &a[i]);
    }

    max = a[0];
    min = a[0];

    for (i = 1; i < 10; i++) {
        if (a[i] > max)
            max = a[i];
        if (a[i] < min)
            min = a[i];
    }

    printf("Largest number  = %d\n", max);
    printf("Smallest number = %d\n", min);

    return 0;
}

Output

Enter 10 numbers:
Number 1: 4
Number 2: 7
... (10 inputs)
Largest number  = 98
Smallest number = 2
What is structure? Why is it necessary? Write a program to add two distances given in feet and inch format using structure.
082 Shrawan [1+1+6]

Structure

A structure is a user-defined data type in C that groups variables of different data types under a single name. Each variable inside a structure is called a member.

struct Student {
    int roll;
    char name[50];
    float marks;
};

Why is it Necessary?

Structures are necessary because they allow related data of different types to be stored and managed together as a single unit. Without structures, each piece of related information would need to be stored in separate variables, making programs harder to manage, read, and maintain. They are especially useful for representing real-world entities like students, employees, or distances.

C Program – Add Two Distances (feet and inches)

#include <stdio.h>

struct Distance {
    int feet;
    float inch;
};

int main() {
    struct Distance d1, d2, sum;

    printf("Enter first distance:\n");
    printf("Feet: ");  scanf("%d", &d1.feet);
    printf("Inch: ");  scanf("%f", &d1.inch);

    printf("Enter second distance:\n");
    printf("Feet: ");  scanf("%d", &d2.feet);
    printf("Inch: ");  scanf("%f", &d2.inch);

    sum.feet = d1.feet + d2.feet;
    sum.inch = d1.inch + d2.inch;

    // Convert excess inches to feet
    if (sum.inch >= 12.0) {
        sum.feet += (int)(sum.inch / 12);
        sum.inch  = sum.inch - (int)(sum.inch / 12) * 12;
    }

    printf("\nSum = %d feet %.2f inches\n", sum.feet, sum.inch);
    return 0;
}

Output

Enter first distance:
Feet: 5
Inch: 9.5
Enter second distance:
Feet: 3
Inch: 4.8

Sum = 9 feet 2.30 inches
Explain pointer arithmetic with suitable example.
082 Shrawan [4]

Pointer Arithmetic

Pointer arithmetic refers to arithmetic operations performed on pointer variables. Since pointers hold memory addresses, arithmetic on them moves the pointer by multiples of the size of the data type they point to.

Valid Pointer Operations

OperationDescription
ptr++Move pointer to next element (adds sizeof(type))
ptr--Move pointer to previous element
ptr + nMove pointer n elements forward
ptr - nMove pointer n elements backward
ptr1 - ptr2Number of elements between two pointers
#include <stdio.h>
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *ptr = arr;   // ptr points to arr[0]

    printf("ptr   = %d (address: %u)\n", *ptr, ptr);
    ptr++;
    printf("ptr++ = %d (address: %u)\n", *ptr, ptr);
    ptr += 2;
    printf("ptr+2 = %d (address: %u)\n", *ptr, ptr);

    return 0;
}
// Output (assuming int = 4 bytes):
// ptr   = 10 (address: 1000)
// ptr++ = 20 (address: 1004)
// ptr+2 = 40 (address: 1012)

Each increment moves the pointer by 4 bytes (size of int), not just 1 byte.

Write a program to display sum, difference, and product of two numbers using the concept of pointer.
082 Shrawan [4]

C Program – Sum, Difference, Product Using Pointers

#include <stdio.h>
int main() {
    int a, b;
    int *p1, *p2;

    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    p1 = &a;
    p2 = &b;

    printf("Sum        = %d\n", *p1 + *p2);
    printf("Difference = %d\n", *p1 - *p2);
    printf("Product    = %d\n", *p1 * *p2);

    return 0;
}

Output

Enter two numbers: 8 3
Sum        = 11
Difference = 5
Product    = 24
Differentiate between console I/O and file I/O. A file named "employee.txt" stores employee name, employee id and employee salary. Write a program to display the detail of all employees having salary greater than 50000.
082 Shrawan [2+6]

Console I/O vs File I/O

FeatureConsole I/OFile I/O
DefinitionInput/output via keyboard and screenInput/output via files stored on disk
Functionsscanf(), printf(), gets(), puts()fscanf(), fprintf(), fgets(), fputs()
PersistenceData lost when program endsData persists on disk after program ends
SpeedSlower (user interaction)Faster for large data
CapacityLimited (user input)Can handle large amounts of data
File pointerNot requiredRequires FILE* pointer

C Program – Display Employees with Salary > 50000

#include <stdio.h>
int main() {
    FILE *fp;
    char name[50];
    int id;
    float salary;
    int found = 0;

    fp = fopen("employee.txt", "r");
    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    printf("Employees with salary > 50000:\n");
    printf("%-20s %-10s %-10s\n", "Name", "ID", "Salary");
    printf("--------------------------------------\n");

    while (fscanf(fp, "%s %d %f", name, &id, &salary) != EOF) {
        if (salary > 50000) {
            printf("%-20s %-10d %-10.2f\n", name, id, salary);
            found = 1;
        }
    }

    if (!found)
        printf("No employees found with salary > 50000.\n");

    fclose(fp);
    return 0;
}

Sample employee.txt

Ram       101  45000
Sita      102  60000
Hari      103  75000
Gita      104  30000

Output

Employees with salary > 50000:
Name                 ID         Salary
--------------------------------------
Sita                 102        60000.00
Hari                 103        75000.00
List down the key differences between C and FORTRAN. How are one-dimensional and two-dimensional array declared in FORTRAN? Write a program in FORTRAN to read and compute the transpose of any matrix.
★ Repeated 082 Shrawan · 081 Baishakh · 080 Baishakh · 080 Bhadra · 079 Bhadra · 078 Bhadra [2+4+6]

C vs FORTRAN Key Differences

BasisCFORTRAN
Full NameC Programming LanguageFORmula TRANslation
PurposeGeneral purpose / systems programmingScientific and numerical computing
Array IndexStarts at 0Starts at 1 (default)
String Handlingchar arrays with '\0'CHARACTER data type
Case SensitiveYesNo (case-insensitive)
PointersExplicit pointer supportLimited pointer support
I/Oprintf / scanfREAD / WRITE with FORMAT
Comments// or /* */C or ! at start of line (F77/F90)

Array Declaration in FORTRAN

C --- 1D Array ---
      INTEGER A(10)        ! Array of 10 integers (index 1 to 10)
      REAL    X(5)         ! Array of 5 real numbers

C --- 2D Array ---
      INTEGER MAT(3,4)     ! 3 rows, 4 columns
      REAL    B(10,10)     ! 10x10 matrix

FORTRAN Program – Matrix Transpose

      PROGRAM TRANSPOSE
      INTEGER A(10,10), T(10,10), M, N, I, J

C     Read dimensions
      WRITE(*,*) 'Enter number of rows and columns:'
      READ(*,*) M, N

C     Read matrix elements
      WRITE(*,*) 'Enter matrix elements row by row:'
      DO 10 I = 1, M
        DO 10 J = 1, N
          READ(*,*) A(I,J)
   10 CONTINUE

C     Compute transpose: T(I,J) = A(J,I)
      DO 20 I = 1, N
        DO 30 J = 1, M
          T(I,J) = A(J,I)
   30   CONTINUE
   20 CONTINUE

C     Display transpose
      WRITE(*,*) 'Transpose of the matrix:'
      DO 40 I = 1, N
        DO 50 J = 1, M
          WRITE(*,100) T(I,J)
   50   CONTINUE
        WRITE(*,*)
   40 CONTINUE

  100 FORMAT(I5,$)
      STOP
      END

Set 2 | 082 Baishakh | Back

Computer Programming [CT401]
Differentiate between system software and application software.
2082 Baishakh [2]

System Software vs Application Software

BasisSystem SoftwareApplication Software
DefinitionSoftware that manages and controls hardware to provide a platform for other softwareSoftware designed to perform specific tasks for the end user
PurposeManages computer resources and hardwareFulfills specific user needs or tasks
InteractionInteracts directly with hardwareInteracts with system software, not hardware directly
DependencyCan run independently of application softwareDepends on system software to run
ExamplesOS (Windows, Linux), Device Drivers, CompilersMS Word, VLC, Chrome, Games
User interactionMinimal direct interaction with usersDesigned primarily for user interaction
Why C programming language is most commonly used in simulation?
2082 Baishakh [2]

Why C is Commonly Used in Simulation

C is widely used in simulation for the following reasons:

  • High Performance: C is a compiled language that produces fast, efficient machine code, critical for real-time simulations.
  • Low-level Memory Control: C allows direct memory management using pointers, enabling fine-tuned control over data structures needed in complex simulations.
  • Portability: C programs can run on virtually any hardware platform, making simulations portable across systems.
  • Rich Library Support: C provides extensive mathematical and I/O libraries suitable for scientific simulations.
  • Close to Hardware: C can directly interact with hardware resources, making it suitable for embedded and hardware-level simulations.
  • Deterministic Behavior: C gives predictable execution timing, which is important for time-critical simulations.
What do you understand by testing and debugging?
2082 Baishakh [2]

Testing

Testing is the process of executing a program with various inputs to verify that it produces the correct and expected output. The goal is to detect errors, verify functionality, and ensure the program meets its requirements. Testing does not fix errors — it only identifies them.

Types: Unit testing, Integration testing, System testing, Black-box testing, White-box testing.

Debugging

Debugging is the process of finding, analyzing, and fixing the errors (bugs) discovered during testing. It involves locating the exact source of the error in the code and correcting it so the program runs as expected.

Difference

TestingDebugging
Identifies that an error existsFinds and fixes the exact error
Done by testers or usersDone by developers/programmers
Comes before debuggingFollows testing
Write an algorithm and draw a flowchart to find the sum of first n natural numbers where the value of n is entered by the user.
2082 Baishakh [4]

Algorithm – Sum of First N Natural Numbers

Step 1: Start
Step 2: Read N from the user
Step 3: Set sum = 0, i = 1
Step 4: If i > N, go to Step 7
Step 5: sum = sum + i, i = i + 1
Step 6: Go to Step 4
Step 7: Print sum
Step 8: Stop

Flowchart

Start Read N sum=0, i=1 i <= N ? Yes sum = sum + i i = i + 1 No Print sum Stop
Define precedence and associativity of operators with examples.
2082 Baishakh [2]

Operator Precedence

Precedence determines the order in which operators are evaluated when an expression has more than one operator. Operators with higher precedence are evaluated first.

int x = 2 + 3 * 4;
// * has higher precedence than +
// Evaluated as: 2 + (3 * 4) = 2 + 12 = 14
Precedence (High to Low)Operators
1 (Highest)() [] -> .
2++ -- ! ~ (unary)
3* / %
4+ -
5< <= > >=
6== !=
7&&
8||
9 (Lowest)= += -= *= /=

Operator Associativity

Associativity determines the direction of evaluation when two operators have the same precedence. It can be left-to-right or right-to-left.

// Left-to-right (most operators):
int x = 10 - 3 - 2;   // = (10 - 3) - 2 = 5

// Right-to-left (assignment, unary):
int a, b, c;
a = b = c = 5;         // = c=5, then b=5, then a=5
Define keywords. List down the rules for writing identifiers in C.
2082 Baishakh [2]

Keywords

Keywords are reserved words in C that have predefined meanings and cannot be used as identifiers (variable names, function names, etc.). C has 32 keywords.

int, float, char, double, void, if, else, for, while, do,
switch, case, break, continue, return, struct, union,
typedef, enum, sizeof, static, extern, auto, register,
const, volatile, signed, unsigned, short, long, goto, default

Rules for Writing Identifiers in C

  • An identifier can contain letters (A-Z, a-z), digits (0-9), and underscore (_) only.
  • An identifier must begin with a letter or underscore, not a digit.
  • Identifiers are case-sensitive (e.g., sum and Sum are different).
  • Keywords cannot be used as identifiers.
  • There is no limit on the length, but only the first 31 characters are significant (ANSI C).
  • No spaces or special characters (@, #, $, etc.) are allowed.
Valid:   sum, _count, total1, MAX_SIZE
Invalid: 1total (starts with digit), int (keyword), my-var (hyphen)
Differentiate between unformatted and formatted input/output in C.
2082 Baishakh [4]

Formatted vs Unformatted I/O

BasisFormatted I/OUnformatted I/O
DefinitionData is read/written in a specific human-readable format using format specifiersData is read/written as raw characters without any formatting
Functionsprintf(), scanf()getchar(), putchar(), gets(), puts()
Format specifiersRequired (%d, %f, %c, %s)Not required
Data typesHandles multiple data typesHandles only characters and strings
FlexibilityMore flexible, supports field width and precisionLess flexible
Exampleprintf("Value = %d", x);putchar('A'); gets(str);

Examples

// Formatted I/O
int n;
float x;
scanf("%d %f", &n, &x);
printf("n=%d, x=%.2f", n, x);

// Unformatted I/O
char c, str[50];
c = getchar();       // reads one character
putchar(c);          // prints one character
gets(str);           // reads a string
puts(str);           // prints a string
Write a program in C to check whether a number entered by the user is prime or composite.
★ Repeated 2082 Baishakh · 082 Shrawan [5]

C Program – Prime or Composite

#include <stdio.h>
int main() {
    int n, i, flag = 0;
    printf("Enter a number: ");
    scanf("%d", &n);

    if (n <= 1) {
        printf("%d is neither prime nor composite.\n", n);
        return 0;
    }

    for (i = 2; i <= n / 2; i++) {
        if (n % i == 0) {
            flag = 1;
            break;
        }
    }

    if (flag == 0)
        printf("%d is a Prime number.\n", n);
    else
        printf("%d is a Composite number.\n", n);

    return 0;
}

Output

Enter a number: 17
17 is a Prime number.

Enter a number: 9
9 is a Composite number.
Write a program in C to display the following pattern:
            *
         * * *
      * * * * *
   * * * * * * *
* * * * * * * * *
2082 Baishakh [5]

C Program – Star Pattern (Triangle)

#include <stdio.h>
int main() {
    int i, j, n = 5;

    for (i = 1; i <= n; i++) {
        // Print leading spaces
        for (j = i; j < n; j++) {
            printf("  ");
        }
        // Print stars
        for (j = 1; j <= (2 * i - 1); j++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}

Output

        *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *
Define functions and classify it. List down the advantages of using functions in the program.
2082 Baishakh [2]

Function

A function is a self-contained block of code that performs a specific task. It can be called multiple times from anywhere in the program. Every C program has at least one function: main().

Classification of Functions

TypeDescriptionExample
Library FunctionsBuilt-in functions provided by C standard libraryprintf(), sqrt(), strlen()
User-defined FunctionsFunctions defined by the programmerint add(int a, int b) { ... }

User-defined functions are further classified by return type and arguments:

  • No argument, no return value
  • With argument, no return value
  • No argument, with return value
  • With argument, with return value

Advantages of Using Functions

  • Modularity: Program is divided into smaller, manageable modules.
  • Reusability: A function can be called multiple times, avoiding code repetition.
  • Readability: Makes the program easier to read and understand.
  • Easy Debugging: Errors can be isolated and fixed in individual functions.
  • Reduced Complexity: Breaks a complex problem into simpler sub-problems.
Write a program in C to display nth term of a Fibonacci sequence using recursive function. The value of n is entered by the user.
2082 Baishakh [6]

C Program – nth Fibonacci Term Using Recursion

#include <stdio.h>

int fibonacci(int n) {
    if (n == 0) return 0;       // base case
    if (n == 1) return 1;       // base case
    return fibonacci(n - 1) + fibonacci(n - 2); // recursive call
}

int main() {
    int n;
    printf("Enter the value of n: ");
    scanf("%d", &n);
    printf("The %dth Fibonacci term = %d\n", n, fibonacci(n));
    return 0;
}

Output

Enter the value of n: 7
The 7th Fibonacci term = 13

Recursive Trace (n=5)

fibonacci(5)
= fibonacci(4) + fibonacci(3)
= (fibonacci(3) + fibonacci(2)) + (fibonacci(2) + fibonacci(1))
= ... = 3 + 2 = 5

Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21 … (index starts at 0)

Define 1D and 2D array. Write a program in C to display the transpose of a m × n matrix entered by the user.
2082 Baishakh [2+4]

1D Array

A 1D (one-dimensional) array is a linear collection of elements of the same data type stored in contiguous memory locations, accessed using a single index.

int a[5] = {10, 20, 30, 40, 50};
// accessed as a[0], a[1], ..., a[4]

2D Array

A 2D (two-dimensional) array is an array of arrays that represents data in rows and columns (like a matrix), accessed using two indices: row and column.

int mat[3][4];   // 3 rows, 4 columns
// accessed as mat[i][j]

C Program – Transpose of m×n Matrix

#include <stdio.h>
int main() {
    int a[10][10], t[10][10], m, n, i, j;

    printf("Enter rows and columns: ");
    scanf("%d %d", &m, &n);

    printf("Enter matrix elements:\n");
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &a[i][j]);

    // Compute transpose
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            t[j][i] = a[i][j];

    printf("Transpose matrix:\n");
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++)
            printf("%4d", t[i][j]);
        printf("\n");
    }
    return 0;
}

Output

Enter rows and columns: 2 3
Enter matrix elements:
1 2 3
4 5 6
Transpose matrix:
   1   4
   2   5
   3   6
Write a program in C to calculate the length of a string entered by the user without using the library function.
2082 Baishakh [4]

C Program – String Length Without Library Function

#include <stdio.h>
int main() {
    char str[100];
    int len = 0;

    printf("Enter a string: ");
    scanf("%s", str);

    while (str[len] != '\0')
        len++;

    printf("Length of string = %d\n", len);
    return 0;
}

Output

Enter a string: HELLO
Length of string = 5

The loop counts characters until the null terminator '\0' is reached, which marks the end of the string.

Define nested structure. Write a program in C to input the name, roll, marks and address of n students from the user and display the entered details in the order of marks.
2082 Baishakh [2+6]

Nested Structure

A nested structure is a structure that contains another structure as one of its members. This allows grouping of related sub-data within a larger structure.

struct Address {
    char city[50];
    char district[50];
};

struct Student {
    char name[50];
    int roll;
    float marks;
    struct Address addr;   // nested structure
};

C Program – Student Details Sorted by Marks

#include <stdio.h>
#include <string.h>

struct Address {
    char city[50];
    char district[50];
};

struct Student {
    char name[50];
    int roll;
    float marks;
    struct Address addr;
};

int main() {
    int n, i, j;
    struct Student s[50], temp;

    printf("Enter number of students: ");
    scanf("%d", &n);

    for (i = 0; i < n; i++) {
        printf("\nStudent %d:\n", i + 1);
        printf("Name: ");    scanf("%s", s[i].name);
        printf("Roll: ");    scanf("%d", &s[i].roll);
        printf("Marks: ");   scanf("%f", &s[i].marks);
        printf("City: ");    scanf("%s", s[i].addr.city);
        printf("District: ");scanf("%s", s[i].addr.district);
    }

    // Sort by marks (descending) using bubble sort
    for (i = 0; i < n - 1; i++)
        for (j = 0; j < n - i - 1; j++)
            if (s[j].marks < s[j + 1].marks) {
                temp = s[j];
                s[j] = s[j + 1];
                s[j + 1] = temp;
            }

    printf("\n%-15s %-6s %-8s %-15s %-15s\n",
           "Name", "Roll", "Marks", "City", "District");
    printf("--------------------------------------------------------------\n");
    for (i = 0; i < n; i++)
        printf("%-15s %-6d %-8.2f %-15s %-15s\n",
               s[i].name, s[i].roll, s[i].marks,
               s[i].addr.city, s[i].addr.district);

    return 0;
}
Define pointers. List out the importance of pointer in C Programming.
2082 Baishakh [1+2]

Pointer

A pointer is a variable that stores the memory address of another variable. It is declared using the * operator and the address-of operator & is used to get the address of a variable.

int a = 10;
int *p = &a;   // p stores address of a
printf("%d", *p);  // *p dereferences to get value: 10

Importance of Pointers in C

  • Dynamic Memory Allocation: Pointers enable runtime memory allocation using malloc(), calloc(), realloc(), and free().
  • Call by Reference: Allows functions to modify the actual variables of the caller.
  • Array Handling: Arrays are internally represented as pointers; pointer arithmetic enables efficient array traversal.
  • String Handling: Strings in C are character pointers; pointer operations simplify string processing.
  • Data Structures: Pointers are essential for building linked lists, trees, stacks, and queues.
  • Efficiency: Passing pointers to functions is more memory-efficient than passing large structures by value.
Write a program in C to sort n numbers entered by the user in ascending order using the concept of pointer.
2082 Baishakh [5]

C Program – Sort N Numbers Using Pointer (Bubble Sort)

#include <stdio.h>

void bubbleSort(int *arr, int n) {
    int i, j, temp;
    for (i = 0; i < n - 1; i++)
        for (j = 0; j < n - i - 1; j++)
            if (*(arr + j) > *(arr + j + 1)) {
                temp = *(arr + j);
                *(arr + j) = *(arr + j + 1);
                *(arr + j + 1) = temp;
            }
}

int main() {
    int n, i;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d numbers:\n", n);
    for (i = 0; i < n; i++)
        scanf("%d", arr + i);   // using pointer notation

    bubbleSort(arr, n);

    printf("Sorted in ascending order:\n");
    for (i = 0; i < n; i++)
        printf("%d ", *(arr + i));
    printf("\n");

    return 0;
}

Output

Enter number of elements: 5
Enter 5 numbers:
40 10 30 50 20
Sorted in ascending order:
10 20 30 40 50
Differentiate between text file and binary file. Write a program in C to copy the contents of a file "source.txt" into "destination.txt".
2082 Baishakh [2+6]

Text File vs Binary File

BasisText FileBinary File
StorageData stored as human-readable ASCII charactersData stored in binary (0s and 1s) format
ReadabilityCan be opened and read in any text editorNot human-readable; requires special program
End of line'\n' is translated to OS-specific newlineNo translation; stored as-is
End of fileEOF marked by special character (Ctrl+Z)EOF determined by file size
SizeGenerally larger due to ASCII representationMore compact and efficient
Mode"r", "w", "a""rb", "wb", "ab"
Example.txt, .csv, .html.exe, .jpg, .mp3

C Program – Copy source.txt to destination.txt

#include <stdio.h>
int main() {
    FILE *src, *dest;
    char ch;

    src = fopen("source.txt", "r");
    if (src == NULL) {
        printf("Error: Cannot open source.txt\n");
        return 1;
    }

    dest = fopen("destination.txt", "w");
    if (dest == NULL) {
        printf("Error: Cannot create destination.txt\n");
        fclose(src);
        return 1;
    }

    while ((ch = fgetc(src)) != EOF)
        fputc(ch, dest);

    printf("File copied successfully.\n");

    fclose(src);
    fclose(dest);
    return 0;
}

Output

File copied successfully.
Describe the structure of a FORTRAN program. List down the data types available in FORTRAN. Write a program in FORTRAN to determine whether the number entered by the user is negative, zero or positive using the concept of Arithmetic IF.
2082 Baishakh [2+2+6]

Structure of a FORTRAN Program

      PROGRAM program_name       ! Program header (optional in F77)
C     Declaration section
      [data type declarations]

C     Executable section
      [statements]

C     Subprogram section (optional)
      [SUBROUTINE / FUNCTION definitions]

      STOP
      END
  • PROGRAM statement: Optional header naming the program.
  • Declaration section: All variables and arrays declared before use.
  • Executable section: Contains READ, WRITE, arithmetic, and control statements.
  • STOP: Terminates execution.
  • END: Marks the physical end of the program unit.
  • Column 1 is for C (comment); columns 2–5 for statement labels; column 6 for continuation; columns 7–72 for statements.

Data Types in FORTRAN

Data TypeDescriptionExample
INTEGERWhole numbersINTEGER N, COUNT
REALSingle-precision floating pointREAL X, PRICE
DOUBLE PRECISIONDouble-precision floating pointDOUBLE PRECISION D
COMPLEXComplex numbers (real + imaginary)COMPLEX Z
LOGICALBoolean values (.TRUE. / .FALSE.)LOGICAL FLAG
CHARACTERCharacter stringsCHARACTER*20 NAME

FORTRAN Program – Negative, Zero, or Positive Using Arithmetic IF

      PROGRAM ARITH_IF
      REAL N

      WRITE(*,*) 'Enter a number:'
      READ(*,*) N

C     Arithmetic IF: IF (expression) label1, label2, label3
C     Jumps to label1 if expression < 0
C     Jumps to label2 if expression = 0
C     Jumps to label3 if expression > 0

      IF (N) 10, 20, 30

   10 WRITE(*,*) 'The number is Negative.'
      GO TO 40

   20 WRITE(*,*) 'The number is Zero.'
      GO TO 40

   30 WRITE(*,*) 'The number is Positive.'

   40 STOP
      END

Output

Enter a number:
-5
The number is Negative.

Enter a number:
0
The number is Zero.

Enter a number:
8
The number is Positive.

Note: Arithmetic IF syntax — IF (expr) L1, L2, L3 — branches to L1 if expr < 0, L2 if expr = 0, L3 if expr > 0. It is unique to FORTRAN.

Set 3 | 081 Bhadra | Back

Computer Programming [CT401]
Differentiate between system software and application software. What are the basic steps needed to be followed for developing a software? Explain.
081 Bhadra [2+4]

System Software vs Application Software [2]

BasisSystem SoftwareApplication Software
DefinitionSoftware that manages hardware and provides a platform for other softwareSoftware designed to perform specific tasks for end users
PurposeManages computer resourcesFulfills specific user needs
InteractionDirectly interacts with hardwareInteracts via system software
DependencyRuns independentlyDepends on system software
ExamplesOS (Windows, Linux), Device Drivers, CompilersMS Word, Chrome, VLC, Games
User InteractionMinimal direct interactionDesigned primarily for user interaction

Basic Steps for Software Development [4]

Software development follows the Software Development Life Cycle (SDLC):

  1. Problem Analysis / Requirement Gathering: Identify and define what the software must do. Gather requirements from stakeholders. Produce a Requirements Specification Document (SRS).
  2. System Design: Plan the overall architecture, data structures, algorithms, and interfaces. Includes high-level (HLD) and low-level design (LLD).
  3. Coding / Implementation: Translate the design into actual source code using a suitable programming language (C, Java, Python, etc.).
  4. Testing & Debugging: Execute the program with various inputs to detect errors (testing), then locate and fix them (debugging). Includes unit, integration, and system testing.
  5. Documentation: Prepare user manuals, technical documentation, and inline code comments to help future developers and users.
  6. Maintenance: After deployment, fix bugs reported by users, update features, and adapt the software to new environments.
PhaseOutput
Requirement AnalysisSRS document
DesignArchitecture & flowcharts
CodingSource code
TestingTest reports, bug list
DocumentationUser/technical manuals
MaintenanceUpdated software
Define operator and keyword in C. Write an algorithm and draw the flowchart to calculate the factorial of a positive integer.
081 Bhadra [2+6]

Operator [1]

An operator is a symbol that instructs the compiler to perform a specific mathematical, relational, logical, or bitwise operation on operands.

int x = 5 + 3;   // + is the arithmetic operator
int y = (x > 3); // > is the relational operator

Types: Arithmetic (+, -, *, /, %), Relational (<, >, ==, !=), Logical (&&, ||, !), Assignment (=, +=), Bitwise (&, |, ^), Increment/Decrement (++, --), Conditional (?:), sizeof.

Keyword [1]

A keyword is a reserved word in C with a predefined meaning that cannot be used as an identifier. C has 32 keywords.

int, float, char, double, void, if, else, for, while, do,
switch, case, break, continue, return, struct, union,
typedef, enum, sizeof, static, extern, auto, register,
const, volatile, signed, unsigned, short, long, goto, default

Algorithm – Factorial of a Positive Integer [3]

Step 1: Start
Step 2: Read N from user
Step 3: If N < 0, print "Invalid" and goto Step 8
Step 4: Set fact = 1, i = 1
Step 5: If i > N, goto Step 7
Step 6: fact = fact * i,  i = i + 1,  goto Step 5
Step 7: Print fact
Step 8: Stop

Flowchart [3]

Start Read N fact=1, i=1 i <= N ? Yes fact = fact * i i = i + 1 No Print fact Stop
Write syntax and example of the following: i) getch()   ii) gets()   iii) printf()   iv) scanf()
081 Bhadra [6]

i) getch()

Syntax: int getch(void);  — Header: <conio.h>

Reads a single character from the keyboard without echoing it on screen and without waiting for Enter.

#include <stdio.h>
#include <conio.h>
int main() {
    char ch;
    printf("Press any key: ");
    ch = getch();          // reads char without displaying
    printf("\nYou pressed: %c", ch);
    return 0;
}

ii) gets()

Syntax: char *gets(char *str);  — Header: <stdio.h>

Reads a full line (including spaces) from stdin into str until a newline or EOF is encountered. The newline is replaced with '\0'.

#include <stdio.h>
int main() {
    char name[50];
    printf("Enter full name: ");
    gets(name);            // reads string with spaces
    printf("Hello, %s!\n", name);
    return 0;
}

iii) printf()

Syntax: int printf(const char *format, ...);  — Header: <stdio.h>

Formatted output function. Prints data to stdout using format specifiers (%d, %f, %c, %s, etc.).

#include <stdio.h>
int main() {
    int age = 20;
    float gpa = 3.85;
    char name[] = "Alice";
    printf("Name: %s, Age: %d, GPA: %.2f\n", name, age, gpa);
    // Output: Name: Alice, Age: 20, GPA: 3.85
    return 0;
}

iv) scanf()

Syntax: int scanf(const char *format, ...);  — Header: <stdio.h>

Formatted input function. Reads data from stdin and stores them at the given addresses. Returns the number of items successfully read.

#include <stdio.h>
int main() {
    int n;
    float x;
    char name[30];
    printf("Enter name, number, float: ");
    scanf("%s %d %f", name, &n, &x);
    printf("%s %d %.2f\n", name, n, x);
    return 0;
}
FunctionHeaderPurposeType
getch()conio.hRead single char, no echoUnformatted Input
gets()stdio.hRead full line with spacesUnformatted Input
printf()stdio.hFormatted output to stdoutFormatted Output
scanf()stdio.hFormatted input from stdinFormatted Input
Differentiate between do loop and while loop in C. Write a program to check whether a given N-digit positive number is Armstrong or not. [Hint: 1634 = 1⁴+6⁴+3⁴+4⁴ = 1634
081 Bhadra [3+5]

do-while vs while Loop [3]

Basiswhile loopdo-while loop
Condition CheckChecked before loop body executes (entry-controlled)Checked after loop body executes (exit-controlled)
Minimum ExecutionsMay execute 0 times if condition is false initiallyExecutes at least once regardless of condition
Syntaxwhile(cond){ ... }do{ ... }while(cond);
SemicolonNo semicolon after conditionSemicolon required after while(cond)
Use CaseWhen iterations may be 0 (pre-check needed)When at least one iteration is guaranteed (e.g., menu)
// while loop
int i = 5;
while (i < 5) { printf("%d", i); i++; }  // prints nothing

// do-while loop
int j = 5;
do { printf("%d", j); j++; } while (j < 5); // prints 5 once

C Program – Armstrong Number Check (N-digit) [5]

An Armstrong (Narcissistic) number of N digits satisfies: sum of each digit raised to the power N equals the original number.

#include <stdio.h>
#include <math.h>

int main() {
    long long num, temp, orig;
    int digit, n = 0;
    double sum = 0;

    printf("Enter a positive number: ");
    scanf("%lld", &num);
    orig = num;
    temp = num;

    // Count digits
    while (temp != 0) {
        n++;
        temp /= 10;
    }

    temp = num;
    // Calculate sum of digits^n
    while (temp != 0) {
        digit = temp % 10;
        sum += pow(digit, n);
        temp /= 10;
    }

    if ((long long)sum == orig)
        printf("%lld is an Armstrong number.\n", orig);
    else
        printf("%lld is NOT an Armstrong number.\n", orig);

    return 0;
}

Output

Enter a positive number: 1634
1634 is an Armstrong number.

Enter a positive number: 153
153 is an Armstrong number.    [1³+5³+3³ = 1+125+27 = 153]

Enter a positive number: 100
100 is NOT an Armstrong number.
Explain how array can be passed to the function. Write a program to read and sort the N elements of a 1-D array in ascending order and display the sorted elements.
081 Bhadra [2+5]

Passing Array to a Function [2]

In C, an array is always passed to a function by reference (by address) — the function receives a pointer to the first element. This means changes inside the function affect the original array.

// Syntax
return_type function_name(data_type arr[], int size);
// OR equivalently:
return_type function_name(data_type *arr, int size);
  • The array name itself is a pointer to its first element.
  • The size must be passed separately since it is not automatically known.
  • There is no & operator needed — the array name already holds the address.
  • Multi-dimensional arrays require all dimensions except the first: void f(int a[][4], int r).

C Program – Read and Sort 1-D Array (Bubble Sort) [5]

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int i, j, temp;
    for (i = 0; i < n - 1; i++) {
        for (j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                temp    = arr[j];
                arr[j]  = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

void display(int arr[], int n) {
    int i;
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

int main() {
    int n, arr[100];
    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    bubbleSort(arr, n);   // array passed by reference

    printf("Sorted array (ascending): ");
    display(arr, n);

    return 0;
}

Output

Enter number of elements: 6
Enter 6 elements:
45 12 78 3 56 23
Sorted array (ascending): 3 12 23 45 56 78
Write a program to find the length of a string without using string handling function.
081 Bhadra [3]

C Program – String Length Without Library Function

#include <stdio.h>

int main() {
    char str[200];
    int len = 0;

    printf("Enter a string: ");
    gets(str);                    // reads full line with spaces

    while (str[len] != '\0')     // count until null terminator
        len++;

    printf("Length of \"%s\" = %d\n", str, len);
    return 0;
}

Output

Enter a string: Hello World
Length of "Hello World" = 11

Enter a string: COMPUTER
Length of "COMPUTER" = 8

The loop increments len for every character until '\0' (null terminator) is found, which marks the end of the string in C. This replicates the behaviour of strlen() from <string.h>.

Explain function prototyping. Write a program to find the Fibonacci series up to n terms using concept of recursive function.
081 Bhadra [2+5]

Function Prototyping [2]

A function prototype is a declaration of a function that specifies its name, return type, and parameter types before its actual definition. It tells the compiler about the function so it can perform type checking during compilation.

// Prototype (declaration) — usually before main()
int add(int a, int b);      // return type + name + parameter types

int main() {
    int result = add(3, 5); // compiler checks types using prototype
    return 0;
}

// Definition (actual body)
int add(int a, int b) {
    return a + b;
}

Why needed?

  • Allows functions to be defined after main() without error.
  • Enables the compiler to validate argument types and count at the call site.
  • Required when functions are defined in separate files.
  • Improves code readability by listing all functions at the top.

C Program – Fibonacci Series Using Recursion [5]

#include <stdio.h>

// Function prototype
int fibonacci(int n);

int main() {
    int n, i;
    printf("Enter number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci series: ");
    for (i = 0; i < n; i++)
        printf("%d ", fibonacci(i));
    printf("\n");

    return 0;
}

// Recursive function definition
int fibonacci(int n) {
    if (n == 0) return 0;          // base case
    if (n == 1) return 1;          // base case
    return fibonacci(n-1) + fibonacci(n-2); // recursive case
}

Output

Enter number of terms: 8
Fibonacci series: 0 1 1 2 3 5 8 13

Recursive Trace (n=5)

fibonacci(5) = fibonacci(4) + fibonacci(3)
             = (fibonacci(3) + fibonacci(2)) + (fibonacci(2) + fibonacci(1))
             = ((fibonacci(2)+fibonacci(1)) + (fibonacci(1)+fibonacci(0)))
               + ((fibonacci(1)+fibonacci(0)) + 1)
             = ((1+1)+1+0) + (1+0+1) = 3 + 2 = 5  ✓
What do you mean by nested structure? Explain. Write a program to demonstrate the use of '.' and '->' operator in structure.
081 Bhadra [3+5]

Nested Structure [3]

A nested structure is a structure that contains another structure as one of its members. This allows logically related sub-data to be grouped within a larger structure.

struct Date {
    int day, month, year;
};

struct Student {
    char name[50];
    int roll;
    struct Date dob;    // nested structure — Date inside Student
};

Accessing nested members:

struct Student s;
s.dob.day   = 15;       // dot operator chained
s.dob.month = 8;
s.dob.year  = 2003;
printf("%s born on %d/%d/%d", s.name, s.dob.day, s.dob.month, s.dob.year);

Dot (.) vs Arrow (->) Operator [2]

OperatorUsed WithSyntax
. (dot)Structure variablevar.member
-> (arrow)Structure pointerptr->member (equivalent to (*ptr).member)

C Program Demonstrating Both Operators [3]

#include <stdio.h>
#include <string.h>

struct Address {
    char city[50];
    char zip[10];
};

struct Employee {
    int  id;
    char name[50];
    float salary;
    struct Address addr;   // nested structure
};

int main() {
    // Using dot operator with a structure variable
    struct Employee e1;
    e1.id = 101;
    strcpy(e1.name, "Ramesh Sharma");
    e1.salary = 45000.00;
    strcpy(e1.addr.city, "Kathmandu");
    strcpy(e1.addr.zip, "44600");

    printf("=== Using dot (.) operator ===\n");
    printf("ID     : %d\n",   e1.id);
    printf("Name   : %s\n",   e1.name);
    printf("Salary : %.2f\n", e1.salary);
    printf("City   : %s\n",   e1.addr.city);
    printf("ZIP    : %s\n",   e1.addr.zip);

    // Using arrow operator with a structure pointer
    struct Employee e2;
    struct Employee *ptr = &e2;

    ptr->id = 202;
    strcpy(ptr->name, "Sunita Thapa");
    ptr->salary = 52000.00;
    strcpy(ptr->addr.city, "Pokhara");
    strcpy(ptr->addr.zip, "33700");

    printf("\n=== Using arrow (->) operator ===\n");
    printf("ID     : %d\n",   ptr->id);
    printf("Name   : %s\n",   ptr->name);
    printf("Salary : %.2f\n", ptr->salary);
    printf("City   : %s\n",   ptr->addr.city);
    printf("ZIP    : %s\n",   ptr->addr.zip);

    return 0;
}

Output

=== Using dot (.) operator ===
ID     : 101
Name   : Ramesh Sharma
Salary : 45000.00
City   : Kathmandu
ZIP    : 44600

=== Using arrow (->) operator ===
ID     : 202
Name   : Sunita Thapa
Salary : 52000.00
City   : Pokhara
ZIP    : 33700
Write a program to illustrate the concept of pointer arithmetic.
081 Bhadra [4]

Pointer Arithmetic – Concept

Pointer arithmetic involves performing arithmetic operations on pointer variables. The operations are scaled automatically by the size of the data type the pointer points to.

  • Increment (++): Moves pointer to the next element (adds sizeof(type) bytes).
  • Decrement (--): Moves pointer to the previous element.
  • Addition (ptr + n): Moves pointer forward by n elements.
  • Subtraction (ptr - n): Moves pointer backward by n elements.
  • Difference (ptr1 - ptr2): Gives number of elements between two pointers.

C Program – Pointer Arithmetic

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *ptr = arr;         // ptr points to first element
    int i, n = 5;

    printf("Array traversal using pointer arithmetic:\n");

    // Using ptr++ to traverse
    for (i = 0; i < n; i++) {
        printf("arr[%d] = %d  (address: %u)\n", i, *ptr, ptr);
        ptr++;              // moves to next int (adds 4 bytes)
    }

    // Reset pointer
    ptr = arr;

    // Pointer + integer
    printf("\nptr + 2 points to: %d\n", *(ptr + 2));  // arr[2] = 30
    printf("ptr + 4 points to: %d\n", *(ptr + 4));  // arr[4] = 50

    // Difference between two pointers
    int *p1 = &arr[1];
    int *p2 = &arr[4];
    printf("\nElements between p1(arr[1]) and p2(arr[4]): %ld\n", p2 - p1);

    // Pointer comparison
    if (p2 > p1)
        printf("p2 is ahead of p1 in memory.\n");

    return 0;
}

Output (addresses may vary)

Array traversal using pointer arithmetic:
arr[0] = 10  (address: 6422280)
arr[1] = 20  (address: 6422284)
arr[2] = 30  (address: 6422288)
arr[3] = 40  (address: 6422292)
arr[4] = 50  (address: 6422296)

ptr + 2 points to: 30
ptr + 4 points to: 50

Elements between p1(arr[1]) and p2(arr[4]): 3
p2 is ahead of p1 in memory.

Each increment adds 4 bytes (size of int), demonstrating that pointer arithmetic is type-aware.

Differentiate between text file and binary file. Write a program to read positive integers from users and write all the odd integers to ODD.txt and all even integers to EVEN.txt.
081 Bhadra [3+3]

Text File vs Binary File [3]

BasisText FileBinary File
Storage FormatData stored as human-readable ASCII charactersData stored in binary (0s and 1s) as in memory
ReadabilityReadable in any text editor (Notepad, vim)Not human-readable; requires special program
Newline'\n' translated to OS-specific line endingNo translation; data stored as-is
EOFMarked by special character (Ctrl+Z on Windows)Determined by file size
SizeLarger; numbers stored digit-by-digitCompact; numbers stored as raw bytes
Open Mode"r", "w", "a""rb", "wb", "ab"
Functionsfprintf(), fscanf(), fgets(), fputs()fread(), fwrite()
Examples.txt, .csv, .html.exe, .jpg, .mp3, .bin

C Program – Separate Odd and Even to Files [3]

#include <stdio.h>

int main() {
    FILE *odd_fp, *even_fp;
    int n, num;

    odd_fp  = fopen("ODD.txt",  "w");
    even_fp = fopen("EVEN.txt", "w");

    if (odd_fp == NULL || even_fp == NULL) {
        printf("Error opening files!\n");
        return 1;
    }

    printf("How many integers to enter? ");
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {
        printf("Enter positive integer %d: ", i + 1);
        scanf("%d", &num);

        if (num <= 0) {
            printf("Skipping non-positive number.\n");
            continue;
        }

        if (num % 2 != 0)
            fprintf(odd_fp,  "%d\n", num);  // write odd to ODD.txt
        else
            fprintf(even_fp, "%d\n", num);  // write even to EVEN.txt
    }

    fclose(odd_fp);
    fclose(even_fp);

    printf("\nOdd numbers written to ODD.txt\n");
    printf("Even numbers written to EVEN.txt\n");
    return 0;
}

Sample Run

How many integers to enter? 6
Enter positive integer 1: 7
Enter positive integer 2: 12
Enter positive integer 3: 3
Enter positive integer 4: 8
Enter positive integer 5: 15
Enter positive integer 6: 4

Odd numbers written to ODD.txt
Even numbers written to EVEN.txt
ODD.txt contents:   7   EVEN.txt contents: 12
                    3                      8
                    15                     4
Explain how Arithmetic IF statement works in FORTRAN. Write a program in FORTRAN to check whether a given n-digit positive number is a palindrome or not. [Hint: a palindrome number is a number that remains same when its digits are reversed]
081 Bhadra [3+6]

Arithmetic IF Statement in FORTRAN [3]

The Arithmetic IF is a three-way branching statement unique to FORTRAN. It evaluates an arithmetic expression and transfers control to one of three labeled statements depending on whether the result is negative, zero, or positive.

      IF (arithmetic_expression) label1, label2, label3
ConditionBranches To
expression < 0label1
expression = 0label2
expression > 0label3
C     Example: classify X
      IF (X) 10, 20, 30
   10 WRITE(*,*) 'Negative'
      GOTO 40
   20 WRITE(*,*) 'Zero'
      GOTO 40
   30 WRITE(*,*) 'Positive'
   40 CONTINUE

The arithmetic IF is a FORTRAN 77 feature; modern FORTRAN (90+) prefers IF-THEN-ELSE constructs.

FORTRAN Program – Palindrome Number Check [6]

A number is a palindrome if it reads the same forwards and backwards (e.g., 121, 1221, 12321).

      PROGRAM PALINDROME
      INTEGER N, ORIG, REV, DIGIT, TEMP

      WRITE(*,*) 'Enter a positive integer:'
      READ(*,*)  N

C     Store original number
      ORIG = N
      REV  = 0
      TEMP = N

C     Reverse the number
   10 IF (TEMP) 30, 30, 20
   20 DIGIT = MOD(TEMP, 10)
      REV   = REV * 10 + DIGIT
      TEMP  = TEMP / 10
      GOTO 10

C     Check palindrome
   30 IF (ORIG - REV) 40, 50, 40

   40 WRITE(*,*) ORIG, ' is NOT a Palindrome.'
      GOTO 60

   50 WRITE(*,*) ORIG, ' is a Palindrome.'

   60 STOP
      END

Output

Enter a positive integer:
12321
       12321 is a Palindrome.

Enter a positive integer:
1234
       1234 is NOT a Palindrome.

Enter a positive integer:
1221
       1221 is a Palindrome.

Explanation

  • Statement 10: IF (TEMP) 30, 30, 20 — if TEMP ≤ 0 go to 30 (loop ends), else go to 20 (continue reversing).
  • Statement 30: IF (ORIG - REV) 40, 50, 40 — if difference is non-zero → not palindrome (40), if zero → palindrome (50).
  • Each iteration extracts the last digit and builds the reversed number.
Write short notes on:   i) Call by value vs call by reference method in functions   ii) break vs continue in loop termination
081 Bhadra [2×4]
i) Call by Value vs Call by Reference
BasisCall by ValueCall by Reference
What is passedCopy of actual argumentAddress (pointer) of variable
Original valueNot modifiedCan be modified
MemoryExtra memory for copyNo copy; same memory
SafetySafer; protects originalLess safe; original can change
Use caseWhen original must be preservedWhen function must modify original
// Call by Value
void inc(int x) { x++; }   // local copy changed
int a=5; inc(a);  // a still 5

// Call by Reference
void inc(int *x) { (*x)++; }
int a=5; inc(&a); // a becomes 6
ii) break vs continue
Basisbreakcontinue
ActionExits (terminates) the loop immediatelySkips remaining body; goes to next iteration
Loop statusLoop endsLoop continues
Used infor, while, do-while, switchfor, while, do-while
EffectJumps to statement after loop/switchJumps to condition check (while/do-while) or update (for)
// break example
for (i=1; i<=10; i++) {
    if (i==5) break;  // stops at 5
    printf("%d ", i); // prints 1 2 3 4
}

// continue example
for (i=1; i<=5; i++) {
    if (i==3) continue; // skip 3
    printf("%d ", i);   // prints 1 2 4 5
}

Set 4 | 081 Baishakh | Back

Computer Programming [CT401]
Discuss about compilation process in C. Draw a flowchart to calculate the sum of digits contained in a number entered by the user.
2081 Baishakh [4+4]

Compilation Process in C

The compilation process converts human-readable C source code into an executable machine code through the following stages:

StageToolDescription
1. Source CodeProgrammer writes code in a .c file (e.g., program.c)
2. Pre-processingPreprocessor (cpp)Handles #include, #define, #ifdef directives; expands macros; removes comments. Produces .i file.
3. CompilationCompiler (cc1)Converts preprocessed code into assembly language (.s file). Performs syntax and semantic checks.
4. AssemblyAssembler (as)Converts assembly code into machine code (object file .o). Code is not yet executable.
5. LinkingLinker (ld)Combines object file(s) with library files (e.g., stdio) to produce the final executable (.exe or a.out).
6. Loading & ExecutionLoader / OSLoads the executable into memory and begins execution.
Source (.c)
   → Preprocessor → .i
   → Compiler     → .s (assembly)
   → Assembler    → .o (object)
   → Linker       → .exe / a.out (executable)

Flowchart – Sum of Digits

Start Read N sum = 0 N > 0 ? Yes rem = N % 10 sum = sum + rem N = N / 10 No Print sum Stop
Explain about declaring variables and constants in C and FORTRAN.
2081 Baishakh [4+4]

Variables and Constants in C

A variable is a named memory location whose value can change during program execution. A constant is a fixed value that cannot be changed once defined.

/* Variable Declaration in C */
int age;              // declare
int age = 20;         // declare and initialize
float price = 9.99;
char grade = 'A';
int a, b, c;          // multiple variables
/* Constants in C */
// Method 1: #define (macro constant)
#define PI 3.14159
#define MAX 100

// Method 2: const keyword
const float PI = 3.14159;
const int MAX = 100;
FeatureVariable (C)Constant (C)
ValueCan changeFixed, cannot change
Declarationdata_type name;const data_type name = value; or #define
MemoryAllocated in RAM#define: no memory; const: stored in memory

Variables and Constants in FORTRAN

In FORTRAN, variables are declared by specifying the data type before the variable name. Constants are defined using the PARAMETER statement.

C     Variable Declaration in FORTRAN
      INTEGER COUNT, N
      REAL    PRICE, TOTAL
      CHARACTER*20 NAME
      LOGICAL FLAG
      DOUBLE PRECISION X
C     Constants in FORTRAN using PARAMETER
      REAL PI
      PARAMETER (PI = 3.14159)

      INTEGER MAX
      PARAMETER (MAX = 100)

C     Implicit typing (FORTRAN default):
C     Variables starting with I-N are INTEGER
C     All others are REAL (unless declared otherwise)
FeatureCFORTRAN
Variable declarationint x; float y;INTEGER X / REAL Y
Constant definition#define or constPARAMETER statement
Implicit typingNot supportedSupported (I–N = INTEGER)
Case sensitivityCase-sensitiveCase-insensitive
Write a syntax to use else-if ladder and do-while in C. Write a program in C to generate the given pattern using concept of loop control:
                      1
                2   4
          3   6   9
  4   8  12  16
2081 Baishakh [2+4]

else-if Ladder Syntax

if (condition1) {
    // block 1
} else if (condition2) {
    // block 2
} else if (condition3) {
    // block 3
} else {
    // default block
}

do-while Syntax

do {
    // loop body (executes at least once)
} while (condition);

C Program – Number Pattern

#include <stdio.h>
int main() {
    int rows; // Total number of rows
    int i, j, s;
    printf ("Enter the number of rows: ");
    scanf ("%d",&rows);
    for (i = 1; i <= rows; i++) {
        
        // 1. Print leading spaces for right alignment
        // Each number + space takes roughly 3-4 characters
        for (s = 1; s <= (rows - i); s++) {
            printf("    "); 
        }

        // 2. Print the multiples of i
        for (j = 1; j <= i; j++) {
            // %3d ensures each number takes up 3 spaces for alignment
            printf("%4d", i * j);
        }

        // 3. Move to the next line
        printf("\n");
    }

    return 0;
}
Write a program using recursive function to compute xy and explain how this program works.
2081 Baishakh [4+4]

C Program – xy Using Recursion

#include <stdio.h>

int power(int x, int y) {
    if (y == 0)
        return 1;              // base case: x^0 = 1
    return x * power(x, y - 1); // recursive case
}

int main() {
    int x, y;
    printf("Enter base (x): ");
    scanf("%d", &x);
    printf("Enter exponent (y): ");
    scanf("%d", &y);
    printf("%d ^ %d = %d\n", x, y, power(x, y));
    return 0;
}

Output

Enter base (x): 2
Enter exponent (y): 5
2 ^ 5 = 32

How the Program Works

The recursive function uses two rules:

  • Base case: When y == 0, return 1 (any number to the power 0 is 1). This stops the recursion.
  • Recursive case: power(x, y) = x * power(x, y-1). The function calls itself with a reduced exponent each time.
power(2, 5)
= 2 * power(2, 4)
= 2 * 2 * power(2, 3)
= 2 * 2 * 2 * power(2, 2)
= 2 * 2 * 2 * 2 * power(2, 1)
= 2 * 2 * 2 * 2 * 2 * power(2, 0)
= 2 * 2 * 2 * 2 * 2 * 1
= 32

Each call is pushed onto the call stack until the base case is reached, after which values are returned and multiplied as the stack unwinds.

Explain about "toupper()" and "tolower()" function used in C. Write a C program to read the name of N countries and display the name of these countries in alphabetical order.
2081 Baishakh [2+6]

toupper() and tolower()

Both functions are defined in <ctype.h> and operate on individual characters.

FunctionSyntaxDescription
toupper()int toupper(int c)Converts a lowercase letter to uppercase. If the character is not a lowercase letter, it is returned unchanged.
tolower()int tolower(int c)Converts an uppercase letter to lowercase. If the character is not uppercase, it is returned unchanged.
#include <ctype.h>
char c = 'a';
printf("%c", toupper(c));  // Output: A

char d = 'Z';
printf("%c", tolower(d));  // Output: z

C Program – Sort N Country Names Alphabetically

#include <stdio.h>
#include <string.h>

int main() {
    int n, i, j;
    char countries[50][50], temp[50];

    printf("Enter number of countries: ");
    scanf("%d", &n);

    printf("Enter country names:\n");
    for (i = 0; i < n; i++) {
        printf("Country %d: ", i + 1);
        scanf("%s", countries[i]);
    }

    // Bubble sort alphabetically
    for (i = 0; i < n - 1; i++)
        for (j = 0; j < n - i - 1; j++)
            if (strcmp(countries[j], countries[j + 1]) > 0) {
                strcpy(temp, countries[j]);
                strcpy(countries[j], countries[j + 1]);
                strcpy(countries[j + 1], temp);
            }

    printf("\nCountries in alphabetical order:\n");
    for (i = 0; i < n; i++)
        printf("%s\n", countries[i]);

    return 0;
}

Output

Enter number of countries: 4
Country 1: Nepal
Country 2: India
Country 3: China
Country 4: Bhutan

Countries in alphabetical order:
Bhutan
China
India
Nepal
Discuss about the initialization and declaration of pointers with examples. Write down about pointer arithmetic.
2081 Baishakh [2+6]

Declaration of Pointers

A pointer is declared by placing an asterisk (*) before the variable name. The data type specifies what type of variable the pointer will point to.

data_type *pointer_name;

int    *p;     // pointer to integer
float  *fp;    // pointer to float
char   *cp;    // pointer to character
double *dp;    // pointer to double

Initialization of Pointers

A pointer is initialized by assigning it the address of a variable using the address-of operator (&). A pointer should never be used without initialization (it would be a dangling/wild pointer).

int a = 10;
int *p = &a;      // p now holds address of a

printf("%d", a);   // prints value: 10
printf("%u", p);   // prints address: e.g. 1000
printf("%d", *p);  // dereference: prints value 10

*p = 25;           // changes a to 25 via pointer
printf("%d", a);   // prints: 25
// NULL pointer (safe initialization when no target yet)
int *ptr = NULL;

Pointer Arithmetic

Arithmetic on pointers moves the pointer by multiples of the size of the data type it points to.

OperationEffect (int pointer, 4 bytes)
ptr++Address increases by 4 (moves to next int)
ptr--Address decreases by 4 (moves to previous int)
ptr + nAddress increases by n × 4
ptr - nAddress decreases by n × 4
ptr1 - ptr2Number of elements between two pointers
#include <stdio.h>
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *ptr = arr;

    printf("%d\n", *ptr);      // 10  (address 1000)
    ptr++;
    printf("%d\n", *ptr);      // 20  (address 1004)
    ptr += 2;
    printf("%d\n", *ptr);      // 40  (address 1012)
    return 0;
}

Note: Multiplication, division, and addition of two pointers are not valid pointer operations.

Write a program in C (16-bit compiler) to create a structure named "karmachari" with members: ID_Number (6-digit), Name and salary of 40,000 employees. Create a function named "search()" where the user inputs a value of salary within the records, if found display the records.
2081 Baishakh [8]

C Program – Karmachari Structure with Search by Salary

#include <stdio.h>
#include <string.h>

#define MAX 10   /* Use 40000 in real case; reduced for demo */

struct karmachari {
    long  ID_Number;
    char  Name[50];
    float salary;
};

struct karmachari emp[MAX];

void search(int n, float target) {
    int i, found = 0;
    printf("\nRecords with salary = %.2f:\n", target);
    printf("%-12s %-20s %-10s\n", "ID Number", "Name", "Salary");
    printf("------------------------------------------\n");
    for (i = 0; i < n; i++) {
        if (emp[i].salary == target) {
            printf("%-12ld %-20s %-10.2f\n",
                   emp[i].ID_Number,
                   emp[i].Name,
                   emp[i].salary);
            found = 1;
        }
    }
    if (!found)
        printf("No records found with that salary.\n");
}

int main() {
    int n, i;
    float searchSal;

    printf("Enter number of employees (max %d): ", MAX);
    scanf("%d", &n);

    for (i = 0; i < n; i++) {
        printf("\nEmployee %d:\n", i + 1);
        printf("ID Number (6-digit): ");
        scanf("%ld", &emp[i].ID_Number);
        printf("Name: ");
        scanf("%s", emp[i].Name);
        printf("Salary: ");
        scanf("%f", &emp[i].salary);
    }

    printf("\nEnter salary to search: ");
    scanf("%f", &searchSal);

    search(n, searchSal);

    return 0;
}

Sample Output

Enter number of employees (max 10): 3

Employee 1:
ID Number (6-digit): 100001
Name: RamBahadur
Salary: 45000

Employee 2:
ID Number (6-digit): 100002
Name: SitaDevi
Salary: 62000

Employee 3:
ID Number (6-digit): 100003
Name: HariPrasad
Salary: 45000

Enter salary to search: 45000

Records with salary = 45000.00:
ID Number    Name                 Salary
------------------------------------------
100001       RamBahadur           45000.00
100003       HariPrasad           45000.00

Note: In a 16-bit compiler (Turbo C), int is 2 bytes so long is used for 6-digit IDs. For 40,000 records, set #define MAX 40000.

Write a program in C to write all the prime numbers within the range n1 to n2 into a first file, copy the content of first file into second file and display the content of second file. Your first file name should be "Source" and second file name should be "Destination".
2081 Baishakh [8]

C Program – Primes to File, Copy, and Display

#include <stdio.h>

int isPrime(int n) {
    int i;
    if (n < 2) return 0;
    for (i = 2; i <= n / 2; i++)
        if (n % i == 0) return 0;
    return 1;
}

int main() {
    int n1, n2, i;
    char ch;
    FILE *src, *dest;

    printf("Enter range n1 and n2: ");
    scanf("%d %d", &n1, &n2);

    /* Step 1: Write primes to Source file */
    src = fopen("Source.txt", "w");
    if (src == NULL) {
        printf("Error creating Source file.\n");
        return 1;
    }
    for (i = n1; i <= n2; i++)
        if (isPrime(i))
            fprintf(src, "%d\n", i);
    fclose(src);
    printf("Prime numbers written to Source.txt\n");

    /* Step 2: Copy Source to Destination */
    src  = fopen("Source.txt",      "r");
    dest = fopen("Destination.txt", "w");
    if (src == NULL || dest == NULL) {
        printf("Error opening files.\n");
        return 1;
    }
    while ((ch = fgetc(src)) != EOF)
        fputc(ch, dest);
    fclose(src);
    fclose(dest);
    printf("Content copied to Destination.txt\n");

    /* Step 3: Display Destination file */
    dest = fopen("Destination.txt", "r");
    if (dest == NULL) {
        printf("Error opening Destination file.\n");
        return 1;
    }
    printf("\nContents of Destination.txt:\n");
    while ((ch = fgetc(dest)) != EOF)
        putchar(ch);
    fclose(dest);

    return 0;
}

Sample Output (n1=10, n2=30)

Enter range n1 and n2: 10 30
Prime numbers written to Source.txt
Content copied to Destination.txt

Contents of Destination.txt:
11
13
17
19
23
29
Write a program in FORTRAN to display Fibonacci sequence upto nth term. Read n from the user. [Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13 …….]
★ Repeated 2081 Baishakh · 082 Shrawan [8]

FORTRAN Program – Fibonacci Sequence

      PROGRAM FIBONACCI
      INTEGER N, I, A, B, TEMP
      WRITE(*,*) 'Enter the number of terms:'
      READ(*,*) N

      A = 0
      B = 1

      WRITE(*,*) 'Fibonacci sequence:'
      DO 10 I = 1, N
        WRITE(*,100) A
        TEMP = A + B
        A = B
        B = TEMP
   10 CONTINUE

  100 FORMAT(I5)
      STOP
      END

Output (for n = 8)

Fibonacci sequence:
    0
    1
    1
    2
    3
    5
    8
   13
Compare switch statement with user defined function. Write a program in C to find the transpose of NXN matrix.
2081 Baishakh [3+5]

switch Statement vs User Defined Function

Basisswitch StatementUser Defined Function
PurposeMulti-way branching based on a single integer/char expressionA reusable block of code performing a specific task
ReusabilityNot reusable; executes inlineCan be called multiple times from anywhere
Return valueDoes not return a valueCan return a value using return statement
ParametersNo parametersCan accept arguments
ComplexitySuitable for simple selection logicSuitable for complex, repeatable tasks
Example useMenu selection, day namesSorting, factorial, searching
// switch example
switch (day) {
    case 1: printf("Monday"); break;
    case 2: printf("Tuesday"); break;
    default: printf("Other");
}

// User defined function example
int add(int a, int b) { return a + b; }
result = add(3, 5);

C Program – Transpose of N×N Matrix

#include <stdio.h>
#define MAX 10

void transpose(int a[][MAX], int t[][MAX], int n) {
    int i, j;
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            t[j][i] = a[i][j];
}

void printMatrix(int m[][MAX], int n) {
    int i, j;
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++)
            printf("%4d", m[i][j]);
        printf("\n");
    }
}

int main() {
    int a[MAX][MAX], t[MAX][MAX], n, i, j;

    printf("Enter size of matrix (N): ");
    scanf("%d", &n);

    printf("Enter %dx%d matrix elements:\n", n, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &a[i][j]);

    transpose(a, t, n);

    printf("\nOriginal Matrix:\n");
    printMatrix(a, n);

    printf("\nTranspose Matrix:\n");
    printMatrix(t, n);

    return 0;
}

Output

Enter size of matrix (N): 3
Enter 3x3 matrix elements:
1 2 3
4 5 6
7 8 9

Original Matrix:
   1   2   3
   4   5   6
   7   8   9

Transpose Matrix:
   1   4   7
   2   5   8
   3   6   9

Set 5 | 080 Bhadra | Regurlar

Computer Programming [CT401]
Write about generation of Computer Programming with example. Draw a flowchart to calculate the area of triangle, where the values of three sides are read from the user. [Hint: Area = √s(s−a)(s−b)(s−c) and s = (a+b+c)/2]
2080 Bhadra [4+4]

Generations of Programming Languages

GenerationNameDescriptionExample
1GLMachine LanguageBinary instructions (0s and 1s) directly executed by CPU. Machine-dependent, fastest but hardest to write.10110000 01100001
2GLAssembly LanguageUses mnemonics instead of binary. Requires an assembler. Still hardware-dependent.MOV AX, 01H
3GLHigh-Level LanguageEnglish-like syntax, machine-independent. Requires compiler or interpreter.C, C++, Java, FORTRAN
4GLVery High-Level LanguageCloser to human language. Handles database queries and reports with less code.SQL, MATLAB, Python
5GLNatural / AI LanguageUses constraints and logic; programmer defines what to solve, not how.Prolog, LISP

Flowchart – Area of Triangle (Heron's Formula)

Start Read a, b, c s = (a+b+c) / 2 area = sqrt( s(s-a)(s-b)(s-c)) area > 0 ? Yes No Print area Invalid triangle Stop
What are the fundamental data types in C? Explain about precedence and associativity of an operator with examples.
2080 Bhadra [2+2]

Fundamental Data Types in C

Data TypeSize (32-bit)RangeExample
int4 bytes-2,147,483,648 to 2,147,483,647int age = 20;
float4 bytes3.4E-38 to 3.4E+38 (~6 decimal digits)float pi = 3.14;
double8 bytes1.7E-308 to 1.7E+308 (~15 decimal digits)double x = 3.14159;
char1 byte-128 to 127 (or 0–255 unsigned)char c = 'A';
void0 bytesNo valuevoid main()

Operator Precedence

Precedence determines the order in which operators are evaluated. Higher precedence operators are evaluated first.

int x = 2 + 3 * 4;
// * has higher precedence than +
// Evaluated as 2 + (3*4) = 14, NOT (2+3)*4 = 20

Operator Associativity

When operators have equal precedence, associativity decides the direction of evaluation.

// Left-to-right (most operators):
int x = 10 - 3 - 2;   // = (10-3)-2 = 5

// Right-to-left (assignment, unary):
int a, b, c;
a = b = c = 5;         // c=5, then b=5, then a=5
Write down the output of following segment of a C program:
void main()
{
  int n=90;
  printf("%10d\n",n);
  printf("%-2d\n",n);
  printf("%c\n",'A');
  printf("%-10d\n",n);
  getch();
}
2080 Bhadra [4]

Program Code

void main() {
    int n = 90;
    printf("%10d\n", n);    // right-justify in 10-char field
    printf("%-2d\n",  n);   // left-justify in min 2-char field
    printf("%c\n",  'A');   // print character A
    printf("%-10d\n", n);   // left-justify in 10-char field
    getch();
}

Output

        90
90
A
90        

Explanation

StatementExplanationOutput
printf("%10d\n", n)Right-justify 90 in width 10 → 8 spaces then "90"" 90"
printf("%-2d\n", n)Left-justify in min width 2; "90" is 2 chars so no padding"90"
printf("%c\n", 'A')%c prints character 'A'"A"
printf("%-10d\n", n)Left-justify 90 in width 10 → "90" then 8 spaces"90 "
Compare else-if ladder with switch statement. Write a program to check whether the entered number is palindrome or not. [Hint: Palindrome number example is 12321]
★ Repeated 2080 Bhadra · 2081 Bhadra [4+4]

else-if Ladder vs switch Statement

Basiselse-if Ladderswitch Statement
Expression typeAny relational or logical expressionOnly integer or character constant
ConditionCan test ranges and complex conditionsTests equality to constant values only
ReadabilityHarder to read with many conditionsCleaner for discrete constant values
Fall-throughNo fall-throughFall-through occurs without break
DefaultFinal else blockdefault case
Float supportYesNo
SpeedEvaluates each condition sequentiallyFaster with jump table for many cases

C Program – Palindrome Number Check

#include <stdio.h>
int main() {
    int n, original, reversed = 0, remainder, temp;

    printf("Enter a number: ");
    scanf("%d", &n);

    original = n;
    temp = n;

    while (temp != 0) {
        remainder = temp % 10;
        reversed  = reversed * 10 + remainder;
        temp      = temp / 10;
    }

    if (original == reversed)
        printf("%d is a Palindrome number.\n", original);
    else
        printf("%d is NOT a Palindrome number.\n", original);

    return 0;
}

Output

Enter a number: 12321
12321 is a Palindrome number.

Enter a number: 12345
12345 is NOT a Palindrome number.
Write the syntax of function prototypes for passing 1D and 2D array into user defined function in C. Write a program in C to read the elements of 2D array of any dimension. Add all the columns of that array using user defined function. Store the result in 1D array and display the same.
2080 Bhadra [2+6]

Syntax – Passing Arrays to Functions

// 1D Array prototype:
return_type functionName(data_type arrayName[], int size);
// or equivalently using pointer:
return_type functionName(data_type *arrayName, int size);

// Example:
void display(int arr[], int n);

// 2D Array prototype (column size MUST be specified):
return_type functionName(data_type arrayName[][COLS], int rows, int cols);

// Example:
void printMatrix(int mat[][10], int rows, int cols);

C Program – Column Sums Stored in 1D Array

#include <stdio.h>
#define MAX 10

void colSum(int mat[][MAX], int result[], int rows, int cols) {
    int i, j;
    for (j = 0; j < cols; j++) {
        result[j] = 0;
        for (i = 0; i < rows; i++)
            result[j] += mat[i][j];
    }
}

int main() {
    int mat[MAX][MAX], result[MAX];
    int rows, cols, i, j;

    printf("Enter rows and columns: ");
    scanf("%d %d", &rows, &cols);

    printf("Enter matrix elements:\n");
    for (i = 0; i < rows; i++)
        for (j = 0; j < cols; j++) {
            printf("mat[%d][%d]: ", i, j);
            scanf("%d", &mat[i][j]);
        }

    colSum(mat, result, rows, cols);

    printf("\nColumn sums:\n");
    for (j = 0; j < cols; j++)
        printf("Column %d sum = %d\n", j + 1, result[j]);

    return 0;
}

Output

Enter rows and columns: 2 3
mat[0][0]: 1  mat[0][1]: 2  mat[0][2]: 3
mat[1][0]: 4  mat[1][1]: 5  mat[1][2]: 6

Column sums:
Column 1 sum = 5
Column 2 sum = 7
Column 3 sum = 9
Write a C program (16-bit compiler) to read name, roll-number (must be a six-digit number) and marks obtained in five subjects of N students using structure. Display the details of all students as well as the total marks and percentage obtained by each student.
2080 Bhadra [8]

C Program – Student Records with Total and Percentage

#include <stdio.h>

struct Student {
    char  name[50];
    long  roll;          /* long for 6-digit roll in 16-bit compiler */
    float marks[5];
    float total;
    float percentage;
};

int main() {
    int n, i, j;
    struct Student s[50];

    printf("Enter number of students: ");
    scanf("%d", &n);

    for (i = 0; i < n; i++) {
        printf("\nStudent %d:\n", i + 1);
        printf("Name: ");
        scanf("%s", s[i].name);
        printf("Roll Number (6-digit): ");
        scanf("%ld", &s[i].roll);

        s[i].total = 0;
        for (j = 0; j < 5; j++) {
            printf("Marks in Subject %d: ", j + 1);
            scanf("%f", &s[i].marks[j]);
            s[i].total += s[i].marks[j];
        }
        s[i].percentage = s[i].total / 5.0;
    }

    printf("\n%-15s %-10s", "Name", "Roll");
    for (j = 0; j < 5; j++) printf(" Sub%d", j + 1);
    printf(" %8s %10s\n", "Total", "Percentage");
    printf("---------------------------------------------------------------\n");

    for (i = 0; i < n; i++) {
        printf("%-15s %-10ld", s[i].name, s[i].roll);
        for (j = 0; j < 5; j++) printf(" %4.1f", s[i].marks[j]);
        printf(" %8.2f %9.2f%%\n", s[i].total, s[i].percentage);
    }

    return 0;
}

Sample Output

Name            Roll        Sub1 Sub2 Sub3 Sub4 Sub5    Total Percentage
---------------------------------------------------------------
RamSharma       100001      75.0 80.0 65.0 90.0 70.0   380.00     76.00%
SitaDevi        100002      88.0 72.0 91.0 85.0 78.0   414.00     82.80%

Note: In a 16-bit compiler (Turbo C), int is 2 bytes (max 32767), so long is used for 6-digit roll numbers. For 32-bit compilers, int suffices.

Compare call by value and call by reference with example.
★ Repeated 2080 Bhadra · 082 Shrawan · 2082 Baishakh [4]

Call by Value vs Call by Reference

FeatureCall by ValueCall by Reference
What is passedA copy of the actual valueThe address of the variable
Original affected?No — changes stay localYes — changes reflect in caller
MemoryExtra memory for copyNo extra copy; same memory used
SafetySafer; no side effectsRisk of unintended modification
Syntaxvoid f(int x)void f(int *x)
// Call by Value — original unchanged
void sqVal(int x) {
    x = x * x;
    printf("Inside: %d\n", x);
}
int main() {
    int a = 5;
    sqVal(a);
    printf("Outside: %d\n", a);  // still 5
}

// Call by Reference — original modified
void sqRef(int *x) {
    *x = (*x) * (*x);
    printf("Inside: %d\n", *x);
}
int main() {
    int a = 5;
    sqRef(&a);
    printf("Outside: %d\n", a);  // now 25
}
Write the output of the pointer program: int a=10, *ptr1, **ptr2; ptr1=&a; ptr2=&ptr1; with printf statements using addresses 6422296 (a), 6422292 (ptr1), 6422280 (ptr2). Then **ptr2=20; printf("%d", a);
2080 Bhadra [4]

Memory Layout

VariableValue StoredAddress
a106422296
ptr16422296 (address of a)6422292
ptr26422292 (address of ptr1)6422280

Line-by-Line Output

#include <stdio.h>
int main() {
    int a = 10, *ptr1, **ptr2;
    ptr1 = &a;
    ptr2 = &ptr1;

    printf("%d\t%d\n", &a, &a);
    // &a = 6422296   &a = 6422296
    // Output: 6422296    6422296

    printf("%d\t%d\n", &ptr1, ptr1);
    // &ptr1 = 6422292  ptr1 = 6422296
    // Output: 6422292    6422296

    printf("%d\t%d\n", *ptr1, *ptr2);
    // *ptr1 = value at 6422296 = 10
    // *ptr2 = value at 6422292 = 6422296 (address of a)
    // Output: 10    6422296

    **ptr2 = 20;
    // *ptr2 = ptr1, *ptr1 = a → a becomes 20

    printf("%d", a);
    // Output: 20

    return 0;
}

Final Output

6422296    6422296
6422292    6422296
10         6422296
20

Note: The original question uses &&a which is invalid in standard C. The correct interpretation based on the table given is that the first printf prints &a and &a (address of a) twice. The output above reflects that correction.

Write the concept of string handling functions. Write a program in C to concatenate two strings without using string handling functions.
2080 Bhadra [2+6]

String Handling Functions in C

C provides built-in string functions through <string.h> that operate on null-terminated character arrays.

FunctionSyntaxDescription
strlen()int strlen(char *s)Returns length of string (excluding '\0')
strcpy()char* strcpy(char *dest, char *src)Copies src string into dest
strcat()char* strcat(char *dest, char *src)Appends src to end of dest
strcmp()int strcmp(char *s1, char *s2)Compares two strings; returns 0 if equal
strupr()char* strupr(char *s)Converts string to uppercase
strlwr()char* strlwr(char *s)Converts string to lowercase
strrev()char* strrev(char *s)Reverses a string

C Program – Concatenate Two Strings Without Library Function

#include <stdio.h>
int main() {
    char s1[100], s2[50];
    int i = 0, j = 0;

    printf("Enter first string:  ");
    scanf("%s", s1);
    printf("Enter second string: ");
    scanf("%s", s2);

    // Find end of s1
    while (s1[i] != '\0')
        i++;

    // Append characters of s2 to s1
    while (s2[j] != '\0') {
        s1[i] = s2[j];
        i++;
        j++;
    }
    s1[i] = '\0';   // null-terminate

    printf("Concatenated string: %s\n", s1);
    return 0;
}

Output

Enter first string:  Hello
Enter second string: World
Concatenated string: HelloWorld
Write a program in C to create a structure book using its members: Name, Price and Author. Read one record from the user "book.txt". Read back the information from "book.txt" and display it.
2080 Bhadra [8]

C Program – Book Structure with File Read/Write

#include <stdio.h>
#include <string.h>

struct Book {
    char  name[100];
    float price;
    char  author[50];
};

int main() {
    struct Book b, b2;
    FILE *fp;

    /* Read record from user */
    printf("Enter book name:   ");
    scanf(" %[^\n]", b.name);
    printf("Enter price:       ");
    scanf("%f", &b.price);
    printf("Enter author name: ");
    scanf(" %[^\n]", b.author);

    /* Write to book.txt */
    fp = fopen("book.txt", "w");
    if (fp == NULL) {
        printf("Error creating file.\n");
        return 1;
    }
    fprintf(fp, "%s\n%.2f\n%s\n", b.name, b.price, b.author);
    fclose(fp);
    printf("Record saved to book.txt\n");

    /* Read back from book.txt */
    fp = fopen("book.txt", "r");
    if (fp == NULL) {
        printf("Error reading file.\n");
        return 1;
    }
    fgets(b2.name,   sizeof(b2.name),   fp);
    fscanf(fp, "%f\n", &b2.price);
    fgets(b2.author, sizeof(b2.author), fp);
    fclose(fp);

    /* Remove trailing newlines */
    b2.name[strcspn(b2.name, "\n")]     = '\0';
    b2.author[strcspn(b2.author, "\n")] = '\0';

    printf("\n--- Book Details from book.txt ---\n");
    printf("Name   : %s\n",   b2.name);
    printf("Price  : %.2f\n", b2.price);
    printf("Author : %s\n",   b2.author);

    return 0;
}

Sample Output

Enter book name:   Computer Programming
Enter price:       550.00
Enter author name: Yashavant Kanetkar
Record saved to book.txt

--- Book Details from book.txt ---
Name   : Computer Programming
Price  : 550.00
Author : Yashavant Kanetkar
Compare about the control structures available in C and FORTRAN.
★ Repeated 2080 Bhadra · 082 Shrawan [4+4]

Control Structures in C

TypeConstructDescription
Conditionalif, if-else, else-ifExecutes block based on condition
Multi-wayswitch-caseSelects branch based on integer/char value
LoopforCounter-controlled pre-test loop
LoopwhileCondition-controlled pre-test loop
Loopdo-whilePost-test loop (executes at least once)
Jumpbreak / continueExit loop / skip to next iteration
JumpgotoUnconditional jump to a label
// C example:
for (i = 1; i <= 5; i++) printf("%d ", i);
if (x > 0) printf("Positive"); else printf("Non-positive");

Control Structures in FORTRAN

TypeConstructDescription
ConditionalLogical IFSingle-line conditional execution
ConditionalIF-THEN-ELSE-END IFBlock conditional (FORTRAN 77+)
ConditionalArithmetic IFThree-way branch: negative/zero/positive
Multi-wayIF-ELSE IF ladderMultiple conditions (no switch available)
LoopDO loopCounter-controlled loop with labels
LoopDO WHILECondition-controlled loop (FORTRAN 77+)
JumpGO TO / Computed GO TOUnconditional / indexed jump
C     FORTRAN example:
      DO 10 I = 1, 5
        WRITE(*,*) I
   10 CONTINUE
      IF (X .GT. 0) THEN
        WRITE(*,*) 'Positive'
      END IF

Key Differences

FeatureCFORTRAN
Switch/Multi-wayswitch-case availableNo switch; uses IF-ELSE IF ladder
Loop typesfor, while, do-whileDO loop, DO WHILE only
Loop controlbreak, continueNo direct equivalent in FORTRAN 77
Condition operators==, !=, >, <.EQ., .NE., .GT., .LT., .GE., .LE.
Arithmetic IFNot availableUnique 3-way branch statement
Write a program in FORTRAN to sort an array of 100 numbers in ascending order.
2080 Bhadra [8]

FORTRAN Program – Sort 100 Numbers in Ascending Order (Bubble Sort)

      PROGRAM SORT100
      INTEGER A(100), N, I, J, TEMP
      N = 100

C     Read 100 numbers from user
      WRITE(*,*) 'Enter 100 numbers:'
      DO 10 I = 1, N
        READ(*,*) A(I)
   10 CONTINUE

C     Bubble Sort — ascending order
      DO 30 I = 1, N - 1
        DO 20 J = 1, N - I
          IF (A(J) .GT. A(J + 1)) THEN
            TEMP     = A(J)
            A(J)     = A(J + 1)
            A(J + 1) = TEMP
          END IF
   20   CONTINUE
   30 CONTINUE

C     Display sorted array
      WRITE(*,*) 'Sorted numbers in ascending order:'
      DO 40 I = 1, N
        WRITE(*,100) A(I)
   40 CONTINUE

  100 FORMAT(I6)
      STOP
      END

How It Works

The outer DO loop (label 30) runs N−1 passes. The inner DO loop (label 20) compares adjacent elements A(J) and A(J+1) and swaps them if A(J) > A(J+1). After each pass, the largest unsorted element rises to its correct final position. After N−1 passes the entire array is sorted in ascending order.

Set 6 | 080 Baishakh | Back

Computer Programming [CT401]
How is an application software different from system software? Explain with examples.
★ Repeated 2080 Baishakh · 2082 Baishakh · 2081 Bhadra [4]

System Software vs Application Software

BasisSystem SoftwareApplication Software
DefinitionSoftware that manages hardware resources and provides a platform for running other softwareSoftware designed to perform specific tasks directly for the end user
PurposeControls and coordinates computer hardwareFulfills specific user needs or tasks
InteractionInteracts directly with hardwareInteracts through system software
DependencyCan run independentlyDepends on system software to run
User interactionMinimal direct user interactionDesigned primarily for user interaction
ExamplesWindows, Linux, macOS, Compilers, Device Drivers, BIOSMS Word, Chrome, VLC, Photoshop, Games
DevelopmentWritten in low-level or system languages (C, Assembly)Written in high-level languages (C, Java, Python)
How is code in source file is converted to the executable file? Explain with key steps involved.
★ Repeated 2080 Baishakh · 2081 Baishakh [4]

Source Code to Executable: Compilation Process

StepToolInputOutputDescription
1. Pre-processingPreprocessor (cpp)program.cprogram.iExpands #include, #define macros; removes comments; processes conditional directives
2. CompilationCompiler (cc1)program.iprogram.sTranslates C code to assembly language; performs syntax and semantic checks; reports errors
3. AssemblyAssembler (as)program.sprogram.oConverts assembly instructions to machine code (object file); not yet executable
4. LinkingLinker (ld)program.o + librariesprogram.exe / a.outCombines object file(s) with standard library files; resolves external references; produces final executable
5. LoadingOS Loaderprogram.exeRunning processLoads executable into RAM; allocates memory; begins execution at main()
Source (.c)
   → Preprocessor  → .i  (expanded source)
   → Compiler      → .s  (assembly code)
   → Assembler     → .o  (object / machine code)
   → Linker        → .exe / a.out  (executable)
   → Loader        → Running program in memory
How is constant different than a variable?
2080 Baishakh [2]

Variable vs Constant

BasisVariableConstant
DefinitionA named memory location whose value can change during executionA fixed value that cannot be changed once defined
ValueCan be modified at any point in the programRemains fixed throughout program execution
Declarationint x = 5; (value can be reassigned)const int X = 5; or #define X 5
MemoryAllocated in RAM; value stored and can be overwritten#define: no memory; const: stored in read-only area
PurposeStores values that change (e.g., counters, inputs)Stores fixed values (e.g., PI, MAX_SIZE)
int count = 0;          // variable — can change
count = count + 1;      // valid

const float PI = 3.14;  // constant
PI = 3.15;              // ERROR: cannot modify a constant
#define MAX 100         // macro constant
Write a C program to read an integer 'd' from the user. If 'd' is the radius of a circular ground in meters, then this program should calculate and display the area of the circle in square meter.
2080 Baishakh [6]

C Program – Area of Circle

#include <stdio.h>
#define PI 3.14159

int main() {
    int d;
    float area;

    printf("Enter the radius of the circular ground (in meters): ");
    scanf("%d", &d);

    area = PI * d * d;

    printf("Area of the circular ground = %.2f square meters\n", area);

    return 0;
}

Output

Enter the radius of the circular ground (in meters): 7
Area of the circular ground = 153.94 square meters

Formula used: Area = π × r² where r = d (radius).

What are formatted input/output functions? Explain each in detail with examples.
2080 Baishakh [2+4]

Formatted I/O Functions

Formatted I/O functions in C allow reading and writing data in a specific, human-readable format using format specifiers (e.g., %d, %f, %s). They are defined in <stdio.h>.

printf() – Formatted Output

Displays formatted output to the standard output (screen).

Syntax:  int printf(const char *format, arg1, arg2, ...);

Example:
  int age = 20;
  float gpa = 3.85;
  char name[] = "Ram";
  printf("Name: %s, Age: %d, GPA: %.2f\n", name, age, gpa);
  // Output: Name: Ram, Age: 20, GPA: 3.85

// Width and alignment:
  printf("%10d\n", 42);    // Output: "        42"  (right-justified)
  printf("%-10d\n", 42);   // Output: "42        "  (left-justified)
  printf("%08.2f\n", 3.14);// Output: "00003.14"    (zero-padded)

scanf() – Formatted Input

Reads formatted input from the standard input (keyboard). The address-of operator (&) must be used for all variables except strings.

Syntax:  int scanf(const char *format, &arg1, &arg2, ...);

Example:
  int n;
  float x;
  char name[50];
  printf("Enter name, integer and float: ");
  scanf("%s %d %f", name, &n, &x);
  printf("Name=%s, n=%d, x=%.2f\n", name, n, x);

// scanf returns the number of successfully read items
// Returns EOF on end of file or error

Common Format Specifiers

SpecifierData TypeExample
%d or %iintprintf("%d", 42);
%ffloat / doubleprintf("%.2f", 3.14);
%ccharprintf("%c", 'A');
%sstring (char array)printf("%s", "Hello");
%lfdouble (in scanf)scanf("%lf", &x);
%ldlong intprintf("%ld", 1000000L);
%eScientific notationprintf("%e", 12345.6);
%oOctalprintf("%o", 8);
%xHexadecimalprintf("%x", 255);
Differentiate between library function and user defined functions. Provide relevant examples.
2080 Baishakh [3]

Library Function vs User Defined Function

BasisLibrary FunctionUser Defined Function
DefinitionPre-written functions provided by C standard librariesFunctions written by the programmer for specific tasks
AvailabilityAvailable by including appropriate header filesMust be declared, defined, and called by programmer
Code visibilitySource code not visible; only declaration in headerFull source code written and visible
ModificationCannot be modifiedCan be modified as needed
Header requiredYes (#include <stdio.h>, <math.h>, etc.)No special header; prototype declared by user
Examplesprintf(), scanf(), sqrt(), strlen(), pow()int add(int a, int b), void display()
// Library function:
#include <math.h>
double result = sqrt(25.0);   // returns 5.0

// User defined function:
int add(int a, int b) {
    return a + b;
}
int sum = add(3, 4);          // returns 7
What is a function prototype? Write a C program to find sum of first 10 natural numbers using recursion.
2080 Baishakh [1+4]

Function Prototype

A function prototype is a declaration of a function that informs the compiler about the function's name, return type, and parameter types before the function is actually defined. It enables forward referencing — calling a function before its full definition.

// Prototype syntax:
return_type function_name(param_type1, param_type2, ...);

// Example:
int add(int, int);         // prototype

int main() {
    printf("%d", add(3, 4));  // valid — compiler knows signature
}
int add(int a, int b) { return a + b; }  // definition later

C Program – Sum of First 10 Natural Numbers Using Recursion

#include <stdio.h>

int sumN(int n) {
    if (n == 0)
        return 0;           // base case
    return n + sumN(n - 1); // recursive case
}

int main() {
    int result = sumN(10);
    printf("Sum of first 10 natural numbers = %d\n", result);
    return 0;
}

Output

Sum of first 10 natural numbers = 55

Recursive Trace

sumN(10) = 10 + sumN(9)
         = 10 + 9 + sumN(8)
         = 10 + 9 + 8 + ... + sumN(1)
         = 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sumN(0)
         = 10 + 9 + ... + 1 + 0 = 55
Write a program to read marks of 48 students in a class and display the second highest mark.
2080 Baishakh [5]

C Program – Second Highest Mark Among 48 Students

#include <stdio.h>
#define N 48

int main() {
    float marks[N];
    float highest, second;
    int i;

    printf("Enter marks of %d students:\n", N);
    for (i = 0; i < N; i++) {
        printf("Student %d: ", i + 1);
        scanf("%f", &marks[i]);
    }

    /* Initialize highest and second highest */
    if (marks[0] > marks[1]) {
        highest = marks[0];
        second  = marks[1];
    } else {
        highest = marks[1];
        second  = marks[0];
    }

    /* Find highest and second highest */
    for (i = 2; i < N; i++) {
        if (marks[i] > highest) {
            second  = highest;
            highest = marks[i];
        } else if (marks[i] > second && marks[i] != highest) {
            second = marks[i];
        }
    }

    printf("\nHighest mark        = %.2f\n", highest);
    printf("Second highest mark = %.2f\n", second);

    return 0;
}

Sample Output

Enter marks of 48 students:
Student 1: 78
Student 2: 95
...
Student 48: 88

Highest mark        = 98.00
Second highest mark = 95.00
How can we copy one string to another string without using any string handling function?
2080 Baishakh [5]

C Program – Copy String Without Library Function

To copy a string manually, we traverse the source string character by character and copy each character to the destination string until the null terminator '\0' is reached, then append '\0' to the destination.

#include <stdio.h>

int main() {
    char source[100], dest[100];
    int i = 0;

    printf("Enter a string to copy: ");
    scanf("%s", source);

    /* Copy character by character */
    while (source[i] != '\0') {
        dest[i] = source[i];
        i++;
    }
    dest[i] = '\0';   /* null-terminate the destination */

    printf("Source string      : %s\n", source);
    printf("Destination string : %s\n", dest);

    return 0;
}

Output

Enter a string to copy: KATHMANDU
Source string      : KATHMANDU
Destination string : KATHMANDU

The loop runs until source[i] == '\0'. Each character at index i is copied to dest[i]. Finally, dest[i] = '\0' ensures the destination is properly null-terminated.

What do you mean by array of structure? Write a program to create a structure named "Student" having members Roll, Name, Address and Marks. Use this structure to read the information of 48 students in a class and display the information of only those students whose marks is between 50 and 70.
2080 Baishakh [2+8]

Array of Structure

An array of structure is a collection where each element of the array is a structure variable. It is used to store multiple records of the same type (e.g., 48 students). It combines the power of arrays (multiple elements) with structures (grouped, heterogeneous data).

struct Student s[48];   // array of 48 Student structure variables
// Access: s[0].roll, s[1].name, s[i].marks, etc.

C Program – Display Students with Marks Between 50 and 70

#include <stdio.h>
#define N 48

struct Student {
    int  roll;
    char name[50];
    char address[100];
    float marks;
};

int main() {
    struct Student s[N];
    int i, found = 0;

    /* Read data for all students */
    for (i = 0; i < N; i++) {
        printf("\nStudent %d:\n", i + 1);
        printf("Roll    : "); scanf("%d",   &s[i].roll);
        printf("Name    : "); scanf("%s",    s[i].name);
        printf("Address : "); scanf("%s",    s[i].address);
        printf("Marks   : "); scanf("%f",   &s[i].marks);
    }

    /* Display students with marks between 50 and 70 */
    printf("\n\nStudents with marks between 50 and 70:\n");
    printf("%-6s %-15s %-20s %-8s\n", "Roll", "Name", "Address", "Marks");
    printf("--------------------------------------------------\n");

    for (i = 0; i < N; i++) {
        if (s[i].marks >= 50 && s[i].marks <= 70) {
            printf("%-6d %-15s %-20s %-8.2f\n",
                   s[i].roll, s[i].name, s[i].address, s[i].marks);
            found = 1;
        }
    }

    if (!found)
        printf("No students found with marks between 50 and 70.\n");

    return 0;
}

Sample Output

Students with marks between 50 and 70:
Roll   Name            Address              Marks
--------------------------------------------------
3      RamBahadur      Kathmandu            65.00
7      SitaDevi        Pokhara              58.50
12     HariPrasad      Lalitpur             70.00
What are pointer arithmetic? Explain with example. Write a C program that uses pointer to read m×n matrix from user. Pass it to a function that finds the transpose of the matrix.
2080 Baishakh [4+4]

Pointer Arithmetic

Pointer arithmetic involves performing arithmetic operations on pointer variables. Since a pointer stores a memory address, arithmetic on it moves the pointer by multiples of the size of the data type it points to.

OperationEffect (for int*, size=4 bytes)
ptr++Address increases by 4 (next int)
ptr--Address decreases by 4 (previous int)
ptr + nAddress increases by n × 4
ptr - nAddress decreases by n × 4
ptr1 - ptr2Number of elements between two pointers
#include <stdio.h>
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *ptr = arr;             // points to arr[0]

    printf("%d\n", *ptr);       // 10  (address: 1000)
    ptr++;
    printf("%d\n", *ptr);       // 20  (address: 1004)
    ptr += 2;
    printf("%d\n", *ptr);       // 40  (address: 1012)
    return 0;
}

C Program – Matrix Transpose Using Pointer

#include <stdio.h>
#define MAX 10

void transpose(int (*mat)[MAX], int (*trans)[MAX], int m, int n) {
    int i, j;
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            *(*(trans + j) + i) = *(*(mat + i) + j);
}

void printMatrix(int (*mat)[MAX], int rows, int cols) {
    int i, j;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++)
            printf("%4d", *(*(mat + i) + j));
        printf("\n");
    }
}

int main() {
    int mat[MAX][MAX], trans[MAX][MAX];
    int m, n, i, j;

    printf("Enter rows (m) and columns (n): ");
    scanf("%d %d", &m, &n);

    printf("Enter matrix elements:\n");
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            scanf("%d", *(mat + i) + j);

    transpose(mat, trans, m, n);

    printf("\nOriginal Matrix (%dx%d):\n", m, n);
    printMatrix(mat, m, n);

    printf("\nTranspose Matrix (%dx%d):\n", n, m);
    printMatrix(trans, n, m);

    return 0;
}

Output

Enter rows (m) and columns (n): 2 3
Enter matrix elements:
1 2 3
4 5 6

Original Matrix (2x3):
   1   2   3
   4   5   6

Transpose Matrix (3x2):
   1   4
   2   5
   3   6
How is a binary file different than a text file? Write the syntax and use of fseek() and rewind() functions in C.
2080 Baishakh [2+2]

Binary File vs Text File

BasisText FileBinary File
StorageData stored as human-readable ASCII charactersData stored in binary (0s and 1s) format
ReadabilityCan be opened in any text editorNot human-readable; requires special program
Newline'\n' translated to OS newline (e.g., \r\n)No translation; stored exactly as-is
EOFMarked by special EOF character (Ctrl+Z)Determined by file size
SizeLarger (ASCII representation)Compact and efficient
Open mode"r", "w", "a""rb", "wb", "ab"
Example.txt, .csv, .html.exe, .jpg, .mp3, .dat

fseek()

Moves the file pointer to a specific position within a file.

Syntax:  int fseek(FILE *fp, long offset, int origin);

Parameters:
  fp      — pointer to the FILE
  offset  — number of bytes to move from origin
  origin  — starting position:
             SEEK_SET (0) — beginning of file
             SEEK_CUR (1) — current position
             SEEK_END (2) — end of file

Example:
  fseek(fp, 0, SEEK_SET);    // move to start of file
  fseek(fp, 10, SEEK_CUR);   // move 10 bytes forward from current
  fseek(fp, -5, SEEK_END);   // move 5 bytes before end of file

rewind()

Resets the file pointer to the beginning of the file. Equivalent to fseek(fp, 0, SEEK_SET).

Syntax:  void rewind(FILE *fp);

Example:
  FILE *fp = fopen("data.txt", "r");
  // ... read some data ...
  rewind(fp);       // go back to start to read again
  // ... read from beginning again ...
Write a C program to read the name, year_of_release, and language of 3 movies. Save the movie data of all 'English' language movies in a data file.
2080 Baishakh [4]

C Program – Save English Movies to File

#include <stdio.h>
#include <string.h>
#define N 3

struct Movie {
    char name[100];
    int  year;
    char language[30];
};

int main() {
    struct Movie m[N];
    int i, saved = 0;
    FILE *fp;

    /* Read movie data from user */
    for (i = 0; i < N; i++) {
        printf("\nMovie %d:\n", i + 1);
        printf("Name           : "); scanf(" %[^\n]", m[i].name);
        printf("Year of Release: "); scanf("%d", &m[i].year);
        printf("Language       : "); scanf("%s", m[i].language);
    }

    /* Write English movies to file */
    fp = fopen("english_movies.txt", "w");
    if (fp == NULL) {
        printf("Error creating file.\n");
        return 1;
    }

    fprintf(fp, "%-30s %-6s %-15s\n", "Movie Name", "Year", "Language");
    fprintf(fp, "---------------------------------------------\n");

    for (i = 0; i < N; i++) {
        /* Case-insensitive comparison using strcasecmp or manual check */
        char lang[30];
        int j;
        for (j = 0; m[i].language[j]; j++)
            lang[j] = (m[i].language[j] >= 'a') ?
                      m[i].language[j] - 32 : m[i].language[j];
        lang[j] = '\0';

        if (strcmp(lang, "ENGLISH") == 0) {
            fprintf(fp, "%-30s %-6d %-15s\n",
                    m[i].name, m[i].year, m[i].language);
            saved++;
        }
    }

    fclose(fp);

    if (saved > 0)
        printf("\n%d English movie(s) saved to english_movies.txt\n", saved);
    else
        printf("\nNo English movies found.\n");

    return 0;
}

Sample Run

Movie 1:
Name           : Inception
Year of Release: 2010
Language       : English

Movie 2:
Name           : Devdas
Year of Release: 2002
Language       : Hindi

Movie 3:
Name           : Interstellar
Year of Release: 2014
Language       : English

2 English movie(s) saved to english_movies.txt

english_movies.txt content

Movie Name                     Year   Language
---------------------------------------------
Inception                      2010   English
Interstellar                   2014   English
What is the use of FORMAT statement? Explain I and F format with example. Write a program in FORTRAN to read a number from user and check whether it is a prime number or not.
★ Repeated 2080 Baishakh · 082 Shrawan [4+4]

FORMAT Statement

The FORMAT statement in FORTRAN controls the exact layout of input/output data. It specifies field widths, decimal places, spacing, and data types. It is referenced by a statement label in READ or WRITE statements.

      WRITE(*,100) X
  100 FORMAT(...)    ! FORMAT referenced by label 100

I Format (Integer)

Used for integer input/output. Syntax: Iw where w is the total field width.

      INTEGER N
      N = 42
      WRITE(*,100) N
  100 FORMAT(I5)
C     Output:    42   (right-justified in 5-character field)

F Format (Floating Point)

Used for real number input/output. Syntax: Fw.d where w is total field width and d is decimal places.

      REAL X
      X = 3.14159
      WRITE(*,200) X
  200 FORMAT(F8.3)
C     Output:    3.142  (8 chars wide, 3 decimal places)

FORTRAN Program – Prime Number Check

      PROGRAM PRIME
      INTEGER N, I, FLAG
      WRITE(*,*) 'Enter a number:'
      READ(*,*) N

      FLAG = 0

      IF (N .LE. 1) THEN
        FLAG = 1
      END IF

      DO 10 I = 2, N / 2
        IF (MOD(N, I) .EQ. 0) THEN
          FLAG = 1
        END IF
   10 CONTINUE

      IF (FLAG .EQ. 0) THEN
        WRITE(*,100) N
  100   FORMAT(I6, ' is a prime number.')
      ELSE
        WRITE(*,200) N
  200   FORMAT(I6, ' is not a prime number.')
      END IF

      STOP
      END

Output

Enter a number:
7
     7 is a prime number.

Enter a number:
9
     9 is not a prime number.
Short Note: While and do-while statement.
2080 Baishakh [2]

while Statement

A pre-test loop that checks the condition before executing the loop body. If the condition is false initially, the body never executes.

Syntax:
while (condition) {
    // body
}

Example:
int i = 1;
while (i <= 5) {
    printf("%d ", i);  // prints: 1 2 3 4 5
    i++;
}

do-while Statement

A post-test loop that executes the body first and then checks the condition. The body always executes at least once.

Syntax:
do {
    // body
} while (condition);

Example:
int i = 1;
do {
    printf("%d ", i);  // prints: 1 2 3 4 5
    i++;
} while (i <= 5);

Key Difference

Featurewhiledo-while
Condition checkBefore loop body (pre-test)After loop body (post-test)
Minimum executions0 (may never run)At least 1
SemicolonNo semicolon after conditionSemicolon required after while(cond);
Short Note: String manipulation in C.
2080 Baishakh [2]

String Manipulation in C

In C, a string is a null-terminated character array (char str[]). C provides string manipulation functions through <string.h>.

FunctionSyntaxPurposeExample
strlen()int strlen(char *s)Returns string length (excluding '\0')strlen("Hello") → 5
strcpy()char* strcpy(char *d, char *s)Copies source to destinationstrcpy(d, "Hi")
strcat()char* strcat(char *d, char *s)Appends source to end of destinationstrcat("Hello", " World")
strcmp()int strcmp(char *s1, char *s2)Compares two strings; 0 if equalstrcmp("abc", "abc") → 0
strrev()char* strrev(char *s)Reverses the string in-placestrrev("Hello") → "olleH"
strupr()char* strupr(char *s)Converts to uppercasestrupr("hello") → "HELLO"
strlwr()char* strlwr(char *s)Converts to lowercasestrlwr("HELLO") → "hello"
#include <stdio.h>
#include <string.h>
int main() {
    char s1[50] = "Hello";
    char s2[50] = "World";
    printf("Length : %d\n",   strlen(s1));       // 5
    printf("Compare: %d\n",   strcmp(s1, s2));   // negative (H < W)
    strcat(s1, s2);
    printf("Concat : %s\n",   s1);               // HelloWorld
    return 0;
}

Set 7 | 079 Bhadra | Regular

Computer Programming [CT401]
Differentiate between system software and application software. Provide relevant examples for each of them.
★ Repeated 2079 Bhadra · 2080 Baishakh · 2082 Baishakh · 2081 Bhadra [4]

System Software vs Application Software

BasisSystem SoftwareApplication Software
DefinitionSoftware that manages hardware resources and provides a platform for running other softwareSoftware designed to perform specific tasks for the end user
PurposeControls and coordinates hardware operationsFulfills specific user needs
InteractionInteracts directly with hardwareInteracts through system software
DependencyCan run independentlyDepends on system software to run
Development langLow-level: C, AssemblyHigh-level: Java, Python, C++
User interactionMinimal direct user interactionPrimarily designed for user interaction
ExamplesWindows, Linux, macOS, Compilers, Device Drivers, BIOSMS Word, Chrome, VLC, Photoshop, Games
List the steps involved in solving a problem using a computer. Why do we need an algorithm before writing program code?
2079 Bhadra [2+2]

Steps in Solving a Problem Using a Computer

StepDescription
1. Problem AnalysisClearly understand the problem, identify inputs, expected outputs, and constraints.
2. Algorithm DesignDevelop a step-by-step logical solution independent of any programming language.
3. FlowchartDraw a graphical representation of the algorithm using standard symbols.
4. CodingTranslate the algorithm into a programming language (e.g., C, Python).
5. CompilationConvert source code to executable; compiler detects syntax errors.
6. Testing & DebuggingRun the program with various inputs; locate and fix logical/runtime errors.
7. DocumentationWrite user manuals and add comments in code for future reference.
8. MaintenanceUpdate and improve the software after deployment.

Why We Need an Algorithm Before Writing Code

  • Clarity: An algorithm provides a clear, language-independent plan before coding begins, reducing confusion.
  • Error prevention: Logical errors are easier to detect and fix in an algorithm than in code.
  • Efficiency: Saves time — redesigning an algorithm is much faster than rewriting code.
  • Communication: Algorithms can be understood by anyone regardless of programming knowledge.
  • Correctness: Ensures the solution is logically sound before investing time in coding.
Define tokens in C programming language. How are variables declared as constant? Explain with example.
2079 Bhadra [2+2]

Tokens in C

A token is the smallest individual unit of a C program that is meaningful to the compiler. Every C program is made up of tokens.

Token TypeDescriptionExample
KeywordsReserved words with predefined meaningint, float, if, while, return
IdentifiersNames given to variables, functions, arrayscount, sum, main, area
ConstantsFixed values that do not change10, 3.14, 'A', "Hello"
StringsSequence of characters in double quotes"Nepal", "Hello World"
OperatorsSymbols that perform operations+, -, *, /, %, ==, &&
Special SymbolsPunctuation and delimiters{ } ( ) [ ] ; , #

Declaring Variables as Constants

In C, a variable can be made constant (read-only) using two methods:

// Method 1: const keyword
// Declares a typed constant; stored in memory but read-only
const float PI = 3.14159;
const int MAX = 100;
PI = 3.15;    // ERROR: cannot modify a const variable

// Method 2: #define preprocessor directive
// Replaces identifier with value before compilation; no memory allocated
#define PI 3.14159
#define MAX 100

// Example program:
#include <stdio.h>
#define GRAVITY 9.8

int main() {
    const int DAYS = 7;
    printf("Gravity = %.1f m/s^2\n", GRAVITY);
    printf("Days in a week = %d\n", DAYS);
    return 0;
}
Write the output of the following C program (Input string: KATHmanDU):
 char str1[50],
 str2[50] = {'N','E','P','A','L'};
 scanf("%[A-Z]", str1);
 printf("%s\n", str1);
 printf("%.0.5s\n", str2);
 printf("%.5.3s\n", str2);
 printf("%-0.3s", str2);
2079 Bhadra [6]

Code and Analysis

#include <stdio.h>
int main() {
    char str1[50], str2[50] = {'N', 'E', 'P', 'A', 'L'};

    scanf("%[A-Z]", str1);
    // %[A-Z] reads only uppercase letters, stops at first non-uppercase
    // Input: KATHmanDU → reads "KATH" (stops at 'm' which is lowercase)

    printf("%s\n",     str1);       // Line 1
    printf("%.0.5s\n", str2);       // Line 2 — non-standard: prints nothing or compiler-specific
    printf("%.5.3s\n", str2);       // Line 3 — non-standard format
    printf("%-0.3s",   str2);       // Line 4
    return 0;
}

Output Explanation

StatementFormat SpecifierExplanationOutput
printf("%s\n", str1)%sPrints str1 which contains "KATH" (stops at lowercase 'm')KATH
printf("%.0.5s\n", str2)%.0.5sNon-standard. Most compilers treat %.0s as print 0 chars of string → empty line(empty)
printf("%.5.3s\n", str2)%.5.3sNon-standard. Last precision .3 applies → prints first 3 chars: "NEP"NEP
printf("%-0.3s", str2)%-0.3sLeft-justify, print max 3 chars → "NEP" left-alignedNEP

Final Output

KATH

NEP
NEP

Note: %.0.5s and %.5.3s are non-standard format specifiers. Behavior may differ across compilers. In Turbo C / standard GCC, the last precision value typically takes effect.

How are break and continue statements used to jump out from the loop? Write a program to evaluate the following series until the term value becomes less than 10−6: cos(x) = 1 − x²/2! + x⁴/4! − x⁶/6! + x⁸/8! − ···
2079 Bhadra [4+6]

break and continue Statements

StatementActionUse case
breakImmediately terminates the nearest enclosing loop or switch and transfers control to the statement after itExit loop early when a condition is met
continueSkips the remainder of the current loop iteration and jumps to the next iteration's condition checkSkip specific values without terminating the loop
// break example: stop when i == 4
for (i = 1; i <= 10; i++) {
    if (i == 4) break;
    printf("%d ", i);   // Output: 1 2 3
}

// continue example: skip even numbers
for (i = 1; i <= 6; i++) {
    if (i % 2 == 0) continue;
    printf("%d ", i);   // Output: 1 3 5
}

C Program – cos(x) Series Until Term < 10⁻⁶

#include <stdio.h>
#include <math.h>

int main() {
    double x, term, cosine;
    int n;

    printf("Enter value of x (in radians): ");
    scanf("%lf", &x);

    cosine = 1.0;       /* first term: x^0/0! = 1 */
    term   = 1.0;
    n      = 1;

    while (1) {
        /* Next term: multiply previous term by -x^2 / (2n)(2n-1) */
        term = term * (-x * x) / ((2 * n) * (2 * n - 1));

        if (fabs(term) < 1e-6)
            break;      /* stop when term is negligibly small */

        cosine += term;
        n++;
    }

    printf("cos(%.4lf) = %.6lf\n", x, cosine);
    printf("Math library cos = %.6lf\n", cos(x));

    return 0;
}
/* compile with: gcc program.c -lm */

Output

Enter value of x (in radians): 1.0
cos(1.0000) = 0.540302
Math library cos = 0.540302

The break statement exits the infinite while(1) loop as soon as the absolute value of the current term drops below 10⁻⁶, ensuring sufficient precision.

Write a syntax of function declaration, function definition and function call in C programming. Can a main function be called recursively in C? Justify your opinion.
2079 Bhadra [3+1]

Function Declaration (Prototype)

Declares the function signature to the compiler before the function is defined or called.

Syntax:  return_type function_name(param_type1, param_type2, ...);

Example: int add(int, int);
         void display(void);
         float area(float, float);

Function Definition

Contains the actual body of the function — the statements that execute when the function is called.

Syntax:
return_type function_name(param_type1 param1, param_type2 param2) {
    // body
    return value;   /* omit if void */
}

Example:
int add(int a, int b) {
    return a + b;
}

Function Call

Invokes the function from main() or another function.

Syntax:  variable = function_name(arg1, arg2, ...);
         function_name(arg1, arg2);   /* if void */

Example:
int result = add(3, 5);   /* result = 8 */
display();                /* void function call */

Can main() be Called Recursively?

Yes — in C, main() can technically be called recursively. Unlike C++, the C standard does not explicitly forbid it. However:

  • Each recursive call pushes a new stack frame, and without a base case it causes a stack overflow.
  • It is considered bad practice and is never used in real programs.
  • A proper base case can prevent infinite recursion:
#include <stdio.h>
int count = 0;
int main() {
    count++;
    if (count < 3) {
        printf("Call %d\n", count);
        main();   // recursive call to main (legal in C)
    }
    return 0;
}
// Output: Call 1  Call 2
Explain the use of recursive function with a suitable example.
2079 Bhadra [4]

Recursive Function

A recursive function is a function that calls itself during its execution. Every recursive function must have:

  • Base case: A condition that stops the recursion (prevents infinite calls).
  • Recursive case: The function calling itself with a modified argument, moving toward the base case.
/* Factorial using recursion */
#include <stdio.h>

int factorial(int n) {
    if (n == 0 || n == 1)   /* base case */
        return 1;
    return n * factorial(n - 1);  /* recursive case */
}

int main() {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    printf("%d! = %d\n", n, factorial(n));
    return 0;
}

Output

Enter a number: 5
5! = 120

Call Stack Trace (n=5)

factorial(5) = 5 * factorial(4)
             = 5 * 4 * factorial(3)
             = 5 * 4 * 3 * factorial(2)
             = 5 * 4 * 3 * 2 * factorial(1)
             = 5 * 4 * 3 * 2 * 1
             = 120

Each call is pushed onto the call stack. When the base case n==1 is reached, values unwind back through the stack multiplying at each level.

Differentiate between array and string. Explain how to declare and use multi-dimensional arrays in C.
2079 Bhadra [3+2]

Array vs String

BasisArrayString
DefinitionA collection of elements of the same data type stored in contiguous memoryA character array terminated by a null character '\0'
Data typeCan be int, float, char, etc.Always char type
TerminatorNo special terminatorMust end with '\0'
Declarationint a[5]; float b[10];char str[20]; or char str[] = "Hello";
I/OElement-by-element with scanf/printfEntire string with %s or gets()/puts()
FunctionsNo special librarystring.h: strlen, strcpy, strcat, etc.

Multi-Dimensional Arrays in C

A multi-dimensional array is an array of arrays. The most common is the 2D array (matrix).

/* Declaration syntax */
data_type array_name[size1][size2]...[sizeN];

/* 2D Array declaration */
int mat[3][4];          /* 3 rows, 4 columns */
float grid[5][5];

/* Declaration with initialization */
int a[2][3] = { {1, 2, 3}, {4, 5, 6} };

/* Accessing elements */
a[0][0] = 1;  a[0][1] = 2;  a[1][2] = 6;

/* Reading and printing a 2D array */
#include <stdio.h>
int main() {
    int mat[3][3], i, j;

    printf("Enter 3x3 matrix:\n");
    for (i = 0; i < 3; i++)
        for (j = 0; j < 3; j++)
            scanf("%d", &mat[i][j]);

    printf("Matrix:\n");
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++)
            printf("%4d", mat[i][j]);
        printf("\n");
    }
    return 0;
}

3D arrays can be declared as int cube[2][3][4]; and accessed as cube[i][j][k].

Write a C program to read a string from the user. Pass the string to a function and sort the alphabets in descending order. For example, if the user entered "exam" then the program should display "xmea".
2079 Bhadra [5]

C Program – Sort String Characters in Descending Order

#include <stdio.h>
#include <string.h>

void sortDescending(char str[]) {
    int len = strlen(str);
    int i, j;
    char temp;

    /* Bubble sort in descending order */
    for (i = 0; i < len - 1; i++) {
        for (j = 0; j < len - i - 1; j++) {
            if (str[j] < str[j + 1]) {   /* swap if left < right */
                temp      = str[j];
                str[j]    = str[j + 1];
                str[j + 1] = temp;
            }
        }
    }
}

int main() {
    char str[100];

    printf("Enter a string: ");
    scanf("%s", str);

    sortDescending(str);

    printf("Sorted in descending order: %s\n", str);
    return 0;
}

Output

Enter a string: exam
Sorted in descending order: xmea

Enter a string: Nepal
Sorted in descending order: plonea

Note: Sorting is based on ASCII values. Uppercase letters (65–90) have lower ASCII values than lowercase (97–122), so mixed-case strings sort uppercase after lowercase in descending order.

What is the meaning of data type used in pointer declaration? Define a function in your program to swap two integers using pass by reference.
2079 Bhadra [1+3]

Data Type in Pointer Declaration

When declaring a pointer, the data type specifies the type of variable the pointer points to. It determines:

  • How many bytes to read/write when the pointer is dereferenced (e.g., int* reads 4 bytes, char* reads 1 byte).
  • The step size for pointer arithmeticptr++ on an int* advances by 4 bytes; on a char* by 1 byte.
int    *p;   // p points to int;    *p reads 4 bytes
char   *c;   // c points to char;   *c reads 1 byte
float  *f;   // f points to float;  *f reads 4 bytes
double *d;   // d points to double; *d reads 8 bytes
void   *v;   // generic pointer — cannot be dereferenced directly

C Program – Swap Two Integers Using Pass by Reference

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x, y;
    printf("Enter two integers: ");
    scanf("%d %d", &x, &y);

    printf("Before swap: x = %d, y = %d\n", x, y);
    swap(&x, &y);
    printf("After swap : x = %d, y = %d\n", x, y);

    return 0;
}

Output

Enter two integers: 10 20
Before swap: x = 10, y = 20
After swap : x = 20, y = 10
Write a program to find the frequency of a number in array. Explain the relation of pointer and array using this program.
2079 Bhadra [4]

C Program – Frequency of a Number Using Pointer

#include <stdio.h>

int frequency(int *arr, int n, int key) {
    int i, count = 0;
    for (i = 0; i < n; i++) {
        if (*(arr + i) == key)   /* pointer notation */
            count++;
    }
    return count;
}

int main() {
    int arr[100], n, key, i;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++)
        scanf("%d", arr + i);    /* arr+i is address of arr[i] */

    printf("Enter the number to search: ");
    scanf("%d", &key);

    int freq = frequency(arr, n, key);
    printf("Frequency of %d = %d\n", key, freq);

    return 0;
}

Output

Enter number of elements: 6
Enter 6 elements:
3 5 3 7 3 8
Enter the number to search: 3
Frequency of 3 = 3

Pointer–Array Relationship

In C, the name of an array is a constant pointer to its first element. Therefore arr and &arr[0] hold the same address. The following equivalences always hold:

Array notationPointer notationMeaning
arr[i]*(arr + i)Value at index i
&arr[i]arr + iAddress of element i
arr[0]*arrFirst element

In the program above, arr + i is used in scanf and *(arr + i) in the comparison — both are equivalent to arr[i] and &arr[i] respectively.

Write the purpose and syntax of fopen() and fclose() function. WAP to create a structure book with its member name, price and author. Read 10 records from user, write it to a file named "book.dat". Read information from book.dat file, search author name "Gotterfried". If found copy the records to a file "gotterfried.dat".
2079 Bhadra [3+7]

fopen()

Opens a file and returns a FILE pointer. Returns NULL if the file cannot be opened.

Syntax:  FILE* fopen(const char *filename, const char *mode);

Modes:
  "r"  — open for reading (file must exist)
  "w"  — open for writing (creates new or truncates)
  "a"  — open for appending
  "rb" — read binary
  "wb" — write binary

Example:
  FILE *fp = fopen("data.txt", "w");
  if (fp == NULL) { printf("Error!"); }

fclose()

Closes an open file, flushes the buffer, and releases the FILE pointer.

Syntax:  int fclose(FILE *fp);
         Returns 0 on success, EOF on failure.

Example:  fclose(fp);

C Program – Book Structure, Write/Read/Search/Copy

#include <stdio.h>
#include <string.h>
#define N 10

struct Book {
    char  name[100];
    float price;
    char  author[50];
};

int main() {
    struct Book b;
    int i, found = 0;
    FILE *fp, *fp2;

    /* Step 1: Read N records and write to book.dat (binary) */
    fp = fopen("book.dat", "wb");
    if (fp == NULL) { printf("Error creating book.dat\n"); return 1; }

    printf("Enter details of %d books:\n", N);
    for (i = 0; i < N; i++) {
        printf("\nBook %d:\n", i + 1);
        printf("Name   : "); scanf(" %[^\n]", b.name);
        printf("Price  : "); scanf("%f",      &b.price);
        printf("Author : "); scanf(" %[^\n]", b.author);
        fwrite(&b, sizeof(struct Book), 1, fp);
    }
    fclose(fp);
    printf("\nRecords saved to book.dat\n");

    /* Step 2: Read from book.dat, search "Gotterfried", copy matches */
    fp  = fopen("book.dat",        "rb");
    fp2 = fopen("gotterfried.dat", "wb");
    if (fp == NULL || fp2 == NULL) {
        printf("Error opening files.\n");
        return 1;
    }

    printf("\nSearching for author 'Gotterfried'...\n");
    while (fread(&b, sizeof(struct Book), 1, fp) == 1) {
        if (strcmp(b.author, "Gotterfried") == 0) {
            fwrite(&b, sizeof(struct Book), 1, fp2);
            printf("Found: %s by %s (Rs %.2f)\n", b.name, b.author, b.price);
            found++;
        }
    }
    fclose(fp);
    fclose(fp2);

    if (found)
        printf("\n%d record(s) copied to gotterfried.dat\n", found);
    else
        printf("No records found for author 'Gotterfried'.\n");

    return 0;
}

Sample Output

Records saved to book.dat

Searching for author 'Gotterfried'...
Found: Data Structures by Gotterfried (Rs 750.00)

1 record(s) copied to gotterfried.dat
What are the data types available in FORTRAN? Write a program in FORTRAN to check a number is palindrome or not.
★ Repeated 2079 Bhadra · 2081 Bhadra [3+5]

Data Types in FORTRAN

Data TypeDescriptionDeclaration Example
INTEGERWhole numbers (positive, negative, zero)INTEGER N, COUNT
REALSingle-precision floating-point numbersREAL X, PRICE
DOUBLE PRECISIONDouble-precision floating-point (more digits)DOUBLE PRECISION D
COMPLEXComplex numbers with real and imaginary partsCOMPLEX Z
LOGICALBoolean values: .TRUE. or .FALSE.LOGICAL FLAG
CHARACTERCharacter strings of fixed lengthCHARACTER*20 NAME

Implicit typing: By default, variables starting with I–N are INTEGER; all others are REAL. This can be overridden with explicit declarations or IMPLICIT NONE.

FORTRAN Program – Palindrome Check

      PROGRAM PALINDROME
      INTEGER N, ORIGINAL, REVERSED, REMAINDER, TEMP

      WRITE(*,*) 'Enter a positive number:'
      READ(*,*) N

      ORIGINAL = N
      REVERSED = 0
      TEMP     = N

C     Reverse the digits using DO WHILE
   10 IF (TEMP .GT. 0) THEN
        REMAINDER = MOD(TEMP, 10)
        REVERSED  = REVERSED * 10 + REMAINDER
        TEMP      = TEMP / 10
        GO TO 10
      END IF

C     Compare original with reversed using Arithmetic IF
      IF (ORIGINAL - REVERSED) 20, 30, 20

   20 WRITE(*,100) ORIGINAL
  100 FORMAT(I8, ' is NOT a palindrome.')
      GO TO 40

   30 WRITE(*,200) ORIGINAL
  200 FORMAT(I8, ' is a palindrome.')

   40 STOP
      END

Output

Enter a positive number:
12321
   12321 is a palindrome.

Enter a positive number:
12345
   12345 is NOT a palindrome.
Short Note: Associativity in C.
2079 Bhadra [2]

Associativity in C

Associativity determines the direction of evaluation when two or more operators of the same precedence appear in an expression. It can be left-to-right or right-to-left.

AssociativityOperatorsExample & Result
Left-to-Right+, -, *, /, %, <, >, ==, &&, ||10 - 3 - 2 = (10-3)-2 = 5
Right-to-Left=, +=, -=, *=, unary -, !, ~, ++, --a = b = c = 5 → c=5, b=5, a=5
/* Left-to-right example */
int x = 20 / 4 / 2;   // = (20/4)/2 = 5/2 = 2

/* Right-to-left example (assignment) */
int a, b, c;
a = b = c = 10;        // c=10, b=10, a=10

/* Right-to-left (unary) */
int n = 5;
int m = -n;            // unary minus applied right-to-left: m = -5

/* Mixed: same precedence */
int y = 2 * 3 * 4;    // left-to-right: (2*3)*4 = 24
Short Note: Entry and exit control loop.
2079 Bhadra [2]

Entry Control Loop (Pre-test Loop)

In an entry control loop, the condition is checked before the loop body executes. If the condition is false initially, the body never executes (zero iterations possible).

// C entry control loops: for and while

for (i = 1; i <= 5; i++)
    printf("%d ", i);   // Output: 1 2 3 4 5

int n = 0;
while (n > 0)
    printf("Never executes");   // condition false from start

Exit Control Loop (Post-test Loop)

In an exit control loop, the loop body executes first and the condition is checked after. The body always executes at least once regardless of the condition.

// C exit control loop: do-while

int n = 0;
do {
    printf("Executes once even though n=0\n");
} while (n > 0);
// Output: Executes once even though n=0

Comparison

FeatureEntry Control (for / while)Exit Control (do-while)
Condition checkedBefore body (pre-test)After body (post-test)
Minimum executions0 (may never run)At least 1
Use caseWhen execution count may be 0When body must run at least once (e.g., menus)

Set 8 | 078 Bhadra | Regular

Computer Programming [CT401]
What is a program? Explain different types of programming language in brief.
2078 Bhadra [1+3]

What is a Program?

A program is a set of instructions written in a programming language that a computer can execute to perform a specific task or solve a problem. Programs are stored in memory and executed by the CPU.

Types of Programming Languages

TypeDescriptionExamples
Machine Language (1st Gen) Consists of binary code (0s and 1s) directly understood by the CPU. Fastest execution but very difficult to write and understand. Binary instructions: 10110000 01100001
Assembly Language (2nd Gen) Uses symbolic mnemonics (ADD, MOV, SUB) instead of binary. Requires an assembler to convert to machine code. Machine-dependent. MOV AX, 01H; ADD AX, BX
High-Level Language (3rd Gen) Uses English-like syntax, easy to read and write. Machine-independent. Requires compiler or interpreter to translate. C, C++, Java, Python, FORTRAN
4th Generation Language (4GL) Closer to human language; designed for specific purposes like database querying. Requires less code to accomplish tasks. SQL, MATLAB, R
5th Generation Language (5GL) Based on artificial intelligence and natural language constraints. Used in AI and expert systems. Prolog, LISP, OPS5
What is an algorithm? Explain how does algorithm and flowchart helps in computer programming.
2078 Bhadra [1+3]

What is an Algorithm?

An algorithm is a finite, ordered set of well-defined, unambiguous instructions that solve a problem or perform a computation in a finite amount of time. It is language-independent and serves as a blueprint for writing a program.

Properties of a good algorithm: Input, Output, Definiteness, Finiteness, Effectiveness.

How Algorithm Helps in Programming

  • Planning: Provides a clear logical plan before writing any code, reducing guesswork.
  • Error Detection: Logical errors are easier to identify and fix at the algorithm stage than in code.
  • Language Independence: Can be implemented in any programming language.
  • Efficiency: Helps choose the best approach before investing time in coding.
  • Documentation: Serves as documentation for future reference and maintenance.

How Flowchart Helps in Programming

  • Visual Representation: Provides a graphical view of the logic using standard symbols (oval, rectangle, diamond, parallelogram), making it easy to understand.
  • Communication: Helps explain program logic to non-programmers and team members.
  • Debugging: Easier to trace and identify logical errors visually before coding.
  • Sequence Clarity: Shows the order of execution and decision-making flow clearly.
  • Blueprint for Coding: Acts as a direct guide for writing structured code with correct control flow.
Explain Ternary operator in C with an example. Define following terms: (i) Preprocessor directives (ii) Keywords
2078 Bhadra [2+2]

Ternary Operator in C

The ternary operator (also called the conditional operator) is the only operator in C that takes three operands. It is a shorthand for the if-else statement.

Syntax:  condition ? expression_if_true : expression_if_false;

Example:
#include <stdio.h>
int main() {
    int a = 10, b = 20, max;

    max = (a > b) ? a : b;   /* if a > b, max = a; else max = b */
    printf("Maximum = %d\n", max);   /* Output: Maximum = 20 */

    /* Nested ternary */
    int n = 0;
    char *result = (n > 0) ? "Positive" : (n < 0) ? "Negative" : "Zero";
    printf("%s\n", result);   /* Output: Zero */
    return 0;
}

(i) Preprocessor Directives

Preprocessor directives are instructions processed by the C preprocessor before actual compilation begins. They begin with the # symbol and do not end with a semicolon.

DirectivePurpose
#includeIncludes header files (e.g., #include <stdio.h>)
#defineDefines macros/constants (e.g., #define PI 3.14)
#ifdef / #ifndefConditional compilation
#undefUndefines a previously defined macro

(ii) Keywords

Keywords are reserved words in C that have a predefined meaning to the compiler. They cannot be used as variable names or identifiers. C has 32 keywords.

Examples of C keywords:
int    float    double   char     void
if     else     while    for      do
switch case     break    continue return
struct union    typedef  sizeof   const
auto   static   extern   register goto
Write the output of the following C program (Input: 123456    789):
 int a,b;
 double c = 123.55667788;
 char str[] = "I enjoy programming";
 scanf("%3d%2d", &a, &b);
 printf("a = %5\n b=%-7d",a,b);
 printf("\n%u%10.7s",str);
 printf("\n%u%10.3f",c);
 printf("\n%u%-10.6f",c);
2078 Bhadra [4]

Code Analysis

#include <stdio.h>
int main() {
    int a, b;
    double c = 123.55667788;
    char str[] = "I enjoy programming";

    scanf("%3d%2d", &a, &b);
    // Input: 123456   789
    // %3d reads first 3 digits → a = 123
    // %2d reads next 2 digits → b = 45
    // (remaining "6   789" is left in buffer)

    printf("a = %5\n b=%-7d", a, b);
    // %5 is invalid (no type), likely prints "a = " then nothing / garbage
    // %-7d prints b=45 left-justified in 7-char field → "45     "

    printf("\n%u%10.7s", str);
    // %u with char array prints the address of str (varies per run)
    // %10.7s prints first 7 chars of str right-justified in 10 chars
    // First 7 chars of "I enjoy programming" = "I enjoy"
    // Printed as: "   I enjoy" (3 spaces + 7 chars)

    printf("\n%u%10.3f", c);
    // %u again prints address (varies)
    // %10.3f: prints c=123.55667788 rounded to 3 decimal places
    //         in field width 10 → "   123.557"

    printf("\n%u%-10.6f", c);
    // %u prints address (varies)
    // %-10.6f: prints c to 6 decimal places, left-justified in 10 chars
    //          → "123.556677"

    return 0;
}

Output Explanation

StatementFormatExplanationOutput
scanf("%3d%2d", &a, &b)a = 123 (first 3 digits), b = 45 (next 2 digits)a=123, b=45
printf("a = %5\n b=%-7d",a,b)%5 (invalid), %-7d%5 without type is invalid; b=45 left-justified in 7 charsa = [?]
b=45     
printf("\n%u%10.7s",str)%u, %10.7sAddress of str + first 7 chars right-padded in 10-width field[addr]   I enjoy
printf("\n%u%10.3f",c)%u, %10.3fAddress + c formatted to 3 decimals in width 10[addr]   123.557
printf("\n%u%-10.6f",c)%u, %-10.6fAddress + c to 6 decimals left-aligned in width 10[addr]123.556677

Note: %u used with a char array or double is undefined behavior — it prints the address or garbage. The exact address values vary per run/machine. %5 without a type specifier is also invalid.

Write the difference between formatted I/O and unformatted I/O functions in C-programming. Write the syntax for following functions: (i) getche() (ii) getchar() (iii) scanf()
2078 Bhadra [2+4]

Formatted I/O vs Unformatted I/O

BasisFormatted I/OUnformatted I/O
DefinitionReads/writes data in a specific format using format specifiersReads/writes raw characters or strings without format control
Format specifiersUses %d, %f, %c, %s etc.Does not use format specifiers
Data typeCan handle int, float, double, char, stringHandles only characters and strings
Functionsprintf(), scanf(), fprintf(), fscanf()getchar(), putchar(), gets(), puts(), getche(), getch()
Headerstdio.hstdio.h / conio.h
FlexibilityHighly flexible with width, precision controlLimited — no formatting options

(i) getche()

Reads a single character from the keyboard with echo (character is displayed on screen) and returns it immediately without waiting for Enter. Defined in conio.h (Turbo C / Windows).

Syntax:  int getche(void);

Example:
#include <conio.h>
char ch = getche();   /* reads one char, echoes it, returns immediately */

(ii) getchar()

Reads a single character from standard input (keyboard). Waits for the user to press Enter. The character is echoed on screen. Defined in stdio.h.

Syntax:  int getchar(void);

Example:
#include <stdio.h>
char ch = getchar();   /* waits for Enter, then reads one char */

(iii) scanf()

Reads formatted input from standard input according to the format string. Returns the number of items successfully read.

Syntax:  int scanf(const char *format, address_list);

Example:
#include <stdio.h>
int n;
float x;
char name[50];
scanf("%d", &n);           /* read integer */
scanf("%f", &x);           /* read float */
scanf("%s", name);         /* read string (no & needed for arrays) */
scanf("%d %f", &n, &x);   /* read multiple values */
What do you mean by iteration? Explain the operation of break and continue statement with a suitable example.
2078 Bhadra [1+3]

Iteration

Iteration refers to the repeated execution of a block of statements as long as a given condition is true. In C, iteration is implemented using loop constructs: for, while, and do-while. Each repeated execution of the loop body is called one iteration.

break Statement

The break statement immediately terminates the nearest enclosing loop (or switch) and transfers control to the first statement after the loop.

#include <stdio.h>
int main() {
    int i;
    for (i = 1; i <= 10; i++) {
        if (i == 5)
            break;       /* exit loop when i equals 5 */
        printf("%d ", i);
    }
    printf("\nLoop ended.");
    return 0;
}
/* Output: 1 2 3 4
   Loop ended. */

continue Statement

The continue statement skips the remaining statements in the current iteration and jumps to the condition check of the next iteration. The loop does not terminate.

#include <stdio.h>
int main() {
    int i;
    for (i = 1; i <= 10; i++) {
        if (i % 2 == 0)
            continue;    /* skip even numbers */
        printf("%d ", i);
    }
    return 0;
}
/* Output: 1 3 5 7 9 */

Difference

StatementActionLoop continues?
breakExits the loop entirelyNo
continueSkips current iteration, moves to nextYes
Write a C program to check whether an entered word is a palindrome or not without using library function.
2078 Bhadra [6]

C Program – Palindrome Check Without Library Function

#include <stdio.h>

/* Custom string length function */
int strLen(char str[]) {
    int len = 0;
    while (str[len] != '\0')
        len++;
    return len;
}

int main() {
    char word[100];
    int i, len, isPalin = 1;

    printf("Enter a word: ");
    scanf("%s", word);

    len = strLen(word);

    /* Compare characters from both ends */
    for (i = 0; i < len / 2; i++) {
        if (word[i] != word[len - 1 - i]) {
            isPalin = 0;
            break;
        }
    }

    if (isPalin)
        printf("\"%s\" is a palindrome.\n", word);
    else
        printf("\"%s\" is NOT a palindrome.\n", word);

    return 0;
}

Output

Enter a word: madam
"madam" is a palindrome.

Enter a word: hello
"hello" is NOT a palindrome.

Enter a word: racecar
"racecar" is a palindrome.

Logic Explanation

StepDescription
1. Find lengthCustom strLen() counts characters until '\0'
2. Compare endsCompare word[0] with word[len-1], word[1] with word[len-2], etc.
3. Mismatch foundIf any pair differs, set isPalin = 0 and break
4. ResultIf isPalin remains 1 after the loop, the word is a palindrome
What do you mean by a function header? Explain the function parameters and its types.
2078 Bhadra [1+3]

Function Header

A function header (also called function prototype or function signature) is the first line of a function definition that specifies its return type, name, and parameter list — without the function body.

Syntax:  return_type function_name(parameter_list)

Example:
int add(int a, int b)       /* function header */
{
    return a + b;            /* function body */
}

The function header tells the compiler: what the function returns, what it is named, and what arguments it accepts.

Function Parameters

Parameters are variables listed in the function header that receive values when the function is called. There are two types:

TypeDescription
Formal ParametersVariables declared in the function definition that receive the passed values. Exist only within the function scope.
Actual Parameters (Arguments)The real values or variables passed to the function at the time of calling.

Parameter Passing Methods

MethodDescriptionExample
Pass by Value A copy of the actual value is passed. Changes inside the function do NOT affect the original variable. void show(int x) { x = 10; } — original unchanged
Pass by Reference (Pointer) The address of the variable is passed. Changes inside the function AFFECT the original variable. void change(int *x) { *x = 10; } — original modified
/* Example demonstrating both */
#include <stdio.h>

void byValue(int n) {
    n = 100;   /* does not affect original */
}

void byReference(int *n) {
    *n = 100;  /* modifies original */
}

int main() {
    int a = 5, b = 5;
    byValue(a);
    byReference(&b);
    printf("a = %d\n", a);   /* Output: a = 5  (unchanged) */
    printf("b = %d\n", b);   /* Output: b = 100 (changed) */
    return 0;
}
Write a C program to calculate the sum of digits of a given number unless the sum becomes a single digit using recursion. [Hint: 9785 => 29 => 11 => 2]
2078 Bhadra [4]

C Program – Repeated Digit Sum Using Recursion

#include <stdio.h>

/* Calculates sum of digits of n */
int digitSum(int n) {
    if (n == 0)
        return 0;
    return (n % 10) + digitSum(n / 10);
}

/* Recursively reduces until single digit */
int singleDigit(int n) {
    if (n < 10)
        return n;            /* base case: already single digit */
    int sum = digitSum(n);
    printf("%d => ", sum);
    return singleDigit(sum); /* recursive case */
}

int main() {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);

    printf("%d => ", n);
    int result = singleDigit(n);
    printf("%d\n", result);
    printf("Single digit result: %d\n", result);

    return 0;
}

Output

Enter a number: 9785
9785 => 29 => 11 => 2
Single digit result: 2

Enter a number: 999
999 => 27 => 9
Single digit result: 9

Trace for 9785

singleDigit(9785)
  digitSum(9785) = 9+7+8+5 = 29
  singleDigit(29)
    digitSum(29) = 2+9 = 11
    singleDigit(11)
      digitSum(11) = 1+1 = 2
      singleDigit(2) → 2 < 10, return 2 ✓
What is an array? Why is it necessary in C programming?
2078 Bhadra [1+2]

What is an Array?

An array is a collection of a fixed number of elements of the same data type stored in contiguous memory locations, accessed using a common name and an index.

/* Declaration syntax */
data_type array_name[size];

int marks[5];                          /* array of 5 integers */
float temp[10];                        /* array of 10 floats */
int scores[5] = {90, 85, 78, 92, 88}; /* initialized array */

/* Accessing elements */
scores[0] = 90;   scores[1] = 85;   /* index starts from 0 */

Why Arrays are Necessary in C

ReasonExplanation
Handling Multiple ValuesWithout arrays, storing 100 student marks would require 100 separate variables. Arrays reduce this to one declaration: int marks[100];
Loop-based ProcessingArrays can be traversed using loops, enabling batch operations like sum, average, search, and sort efficiently.
Contiguous MemoryElements are stored sequentially, allowing fast indexed access in O(1) time.
Passing to FunctionsAn entire collection can be passed to a function using the array name (as a pointer).
Matrix Operations2D arrays are essential for matrix representation and mathematical operations.
Write a program which displays the following pattern:
H
HE
HEL
HELL
HELLO
HELL
HEL
HE
H
2078 Bhadra [5]

C Program – Diamond String Pattern

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "HELLO";
    int len = strlen(str);   /* len = 5 */
    int i, j;

    /* Upper half: print increasing number of characters */
    for (i = 1; i <= len; i++) {
        for (j = 0; j < i; j++)
            printf("%c", str[j]);
        printf("\n");
    }

    /* Lower half: print decreasing number of characters (skip full row) */
    for (i = len - 1; i >= 1; i--) {
        for (j = 0; j < i; j++)
            printf("%c", str[j]);
        printf("\n");
    }

    return 0;
}

Output

H
HE
HEL
HELL
HELLO
HELL
HEL
HE
H

Logic

PartLoopCharacters Printed
Upper half (including middle)i = 1 to 51, 2, 3, 4, 5 characters
Lower halfi = 4 down to 14, 3, 2, 1 characters
Is there any relation between array and pointer? If yes, show the relation between array and pointer with a suitable example.
2078 Bhadra [1+3]

Relation Between Array and Pointer

Yes, arrays and pointers are closely related in C. The name of an array is a constant pointer to its first element. That is, arr is equivalent to &arr[0] — both hold the address of the first element.

Key Equivalences

Array NotationPointer NotationMeaning
arr&arr[0]Address of first element
arr[i]*(arr + i)Value of element at index i
&arr[i]arr + iAddress of element at index i
arr[0]*arrFirst element's value

C Program Demonstrating the Relation

#include <stdio.h>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr = arr;   /* ptr points to first element of arr */
    int i;

    printf("Using array notation:\n");
    for (i = 0; i < 5; i++)
        printf("arr[%d] = %d\n", i, arr[i]);

    printf("\nUsing pointer notation:\n");
    for (i = 0; i < 5; i++)
        printf("*(ptr + %d) = %d\n", i, *(ptr + i));

    printf("\nAddresses:\n");
    for (i = 0; i < 5; i++)
        printf("&arr[%d] = %p  |  ptr+%d = %p\n", i, &arr[i], i, ptr+i);

    printf("\nDirect comparison:\n");
    printf("arr    = %p\n", arr);
    printf("&arr[0]= %p\n", &arr[0]);
    printf("ptr    = %p\n", ptr);

    return 0;
}

Output

Using array notation:
arr[0] = 10   arr[1] = 20   arr[2] = 30   arr[3] = 40   arr[4] = 50

Using pointer notation:
*(ptr+0) = 10  *(ptr+1) = 20  *(ptr+2) = 30  *(ptr+3) = 40  *(ptr+4) = 50

arr = 0x7ffd1234   &arr[0] = 0x7ffd1234   ptr = 0x7ffd1234

Note: While a pointer variable can be reassigned (ptr++), the array name is a constant pointer and cannot be incremented (arr++ is illegal).

What is structure? Write a program to read a structure named "Faculty" having StaffID, Name, Address and ServiceYear as member. Where ServiceYear is another structure having DurationInYear as member. Now display the details of those faculties whose service duration is more than 10 and less than 30 years.
2078 Bhadra [1+7]

What is a Structure?

A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. Each variable in a structure is called a member.

Syntax:
struct structure_name {
    data_type member1;
    data_type member2;
    ...
};

struct Student {
    int rollNo;
    char name[50];
    float marks;
};

C Program – Nested Structure: Faculty

#include <stdio.h>
#define N 5

/* Inner structure */
struct ServiceYear {
    int durationInYear;
};

/* Outer structure with nested ServiceYear */
struct Faculty {
    int    staffID;
    char   name[50];
    char   address[100];
    struct ServiceYear serviceYear;
};

int main() {
    struct Faculty f[N];
    int i;

    /* Input */
    for (i = 0; i < N; i++) {
        printf("\nEnter details of Faculty %d:\n", i + 1);
        printf("Staff ID        : ");
        scanf("%d", &f[i].staffID);
        printf("Name            : ");
        scanf(" %[^\n]", f[i].name);
        printf("Address         : ");
        scanf(" %[^\n]", f[i].address);
        printf("Service Duration (years): ");
        scanf("%d", &f[i].serviceYear.durationInYear);
    }

    /* Display faculties with service duration > 10 and < 30 */
    printf("\n--- Faculty with service duration between 10 and 30 years ---\n");
    printf("%-10s %-20s %-30s %-10s\n", "Staff ID", "Name", "Address", "Duration");
    printf("----------------------------------------------------------------------\n");

    int found = 0;
    for (i = 0; i < N; i++) {
        int dur = f[i].serviceYear.durationInYear;
        if (dur > 10 && dur < 30) {
            printf("%-10d %-20s %-30s %-10d\n",
                   f[i].staffID, f[i].name, f[i].address, dur);
            found++;
        }
    }

    if (found == 0)
        printf("No faculty found with service duration between 10 and 30 years.\n");

    return 0;
}

Sample Output

--- Faculty with service duration between 10 and 30 years ---
Staff ID   Name                 Address                        Duration
----------------------------------------------------------------------
1001       Ram Sharma           Kathmandu                      15
1003       Sita Rai             Pokhara                        22
Why do we need file handling? Write different modes of file opening.
2078 Bhadra [1+3]

Why We Need File Handling

Data stored in variables and arrays exists only during program execution (in RAM) and is lost when the program ends. File handling allows us to store data permanently on disk so it can be retrieved later.

  • Permanent Storage: Data persists beyond the program's lifetime.
  • Large Data Processing: Files can hold thousands of records that cannot fit in memory at once.
  • Data Sharing: Files can be shared between different programs.
  • Record Keeping: Essential for databases, logs, reports, and billing systems.
  • Input/Output Redirection: Input can be read from files and output directed to files instead of the console.

File Opening Modes in C

ModeDescriptionFile must exist?
"r"Open for reading only. File must exist; returns NULL if not found.Yes
"w"Open for writing. Creates a new file or truncates (empties) existing file.No
"a"Open for appending. Data is written at the end. Creates file if not found.No
"r+"Open for both reading and writing. File must exist.Yes
"w+"Open for reading and writing. Creates new or truncates existing.No
"a+"Open for reading and appending. Creates file if not found.No
"rb"Open binary file for reading only.Yes
"wb"Open binary file for writing (create/truncate).No
"ab"Open binary file for appending.No
"rb+" / "r+b"Open binary file for reading and writing.Yes
FILE *fp = fopen("data.txt", "r");   /* open for reading */
if (fp == NULL)
    printf("File not found!");
fclose(fp);
What is the purpose of fseek and write a program to write the name, roll no, and age of five students into a disk file name "STUDENT.DAT".
2078 Bhadra [6]

Purpose of fseek()

fseek() is used to move the file position indicator (cursor) to a specified location within a file, enabling random access to any record without reading all previous records.

Syntax:  int fseek(FILE *fp, long offset, int origin);

Parameters:
  fp     — file pointer
  offset — number of bytes to move (can be negative)
  origin — starting position:
           SEEK_SET (0) → from beginning of file
           SEEK_CUR (1) → from current position
           SEEK_END (2) → from end of file

Examples:
  fseek(fp, 0, SEEK_SET);              /* go to beginning */
  fseek(fp, 0, SEEK_END);              /* go to end */
  fseek(fp, sizeof(struct), SEEK_SET); /* jump to 2nd record */
  fseek(fp, -sizeof(struct), SEEK_CUR);/* go back one record */

C Program – Write 5 Student Records to STUDENT.DAT

#include <stdio.h>
#define N 5

struct Student {
    char name[50];
    int  rollNo;
    int  age;
};

int main() {
    struct Student s[N];
    int i;
    FILE *fp;

    /* Input student data */
    printf("Enter details of %d students:\n", N);
    for (i = 0; i < N; i++) {
        printf("\nStudent %d:\n", i + 1);
        printf("Name    : ");
        scanf(" %[^\n]", s[i].name);
        printf("Roll No : ");
        scanf("%d", &s[i].rollNo);
        printf("Age     : ");
        scanf("%d", &s[i].age);
    }

    /* Write to STUDENT.DAT in binary mode */
    fp = fopen("STUDENT.DAT", "wb");
    if (fp == NULL) {
        printf("Error: Cannot create STUDENT.DAT\n");
        return 1;
    }

    for (i = 0; i < N; i++)
        fwrite(&s[i], sizeof(struct Student), 1, fp);

    fclose(fp);
    printf("\nData successfully written to STUDENT.DAT\n");

    /* Verify: Read back and display */
    fp = fopen("STUDENT.DAT", "rb");
    if (fp == NULL) { printf("Cannot open file.\n"); return 1; }

    printf("\n--- Records in STUDENT.DAT ---\n");
    printf("%-5s %-20s %-5s\n", "Roll", "Name", "Age");
    printf("------------------------------\n");

    struct Student temp;
    while (fread(&temp, sizeof(struct Student), 1, fp) == 1)
        printf("%-5d %-20s %-5d\n", temp.rollNo, temp.name, temp.age);

    fclose(fp);
    return 0;
}

Sample Output

Data successfully written to STUDENT.DAT

--- Records in STUDENT.DAT ---
Roll  Name                 Age
------------------------------
101   Ram Sharma           20
102   Sita Rai             21
103   Hari Thapa           19
104   Gita Poudel          22
105   Mohan KC             20
Describe X format and T format in FORTRAN. Differentiate between unconditional goto and computed goto in FORTRAN. Write a program in FORTRAN to sort elements of a 1D array in ascending as well as descending order.
2078 Bhadra [2+2+6]

X Format in FORTRAN

The X format descriptor is used to insert horizontal blank spaces in output or skip characters in input.

Syntax:  nX    (where n = number of spaces)

Example:
      WRITE(*,100) 10, 20
  100 FORMAT(I3, 5X, I3)
C     Output: " 10     20"  (5 spaces between the two numbers)

C     In READ, nX skips n characters in input:
      READ(*,200) A, B
  200 FORMAT(F5.2, 3X, F5.2)
C     Skips 3 characters between the two float fields

T Format in FORTRAN

The T format descriptor (Tab) moves the output/input position to an absolute column number, like a tab stop.

Syntax:  Tn    (where n = column number, starting from 1)

Example:
      WRITE(*,300) 'NAME', 'AGE', 'CITY'
  300 FORMAT(T1, A4, T10, A3, T20, A4)
C     NAME starts at col 1, AGE at col 10, CITY at col 20

      WRITE(*,400) 'Ram', 25, 'Kathmandu'
  400 FORMAT(T1, A10, T12, I5, T20, A15)
C     Fields positioned at absolute columns

Difference: Unconditional GOTO vs Computed GOTO

FeatureUnconditional GOTOComputed GOTO
SyntaxGO TO labelGO TO (L1, L2, L3, ...), expression
DestinationAlways jumps to the same fixed labelJumps to one of several labels based on the value of an integer expression
ConditionNo condition — always transfersDepends on integer value (1=L1, 2=L2, ...)
FlexibilityLess flexibleMore flexible — acts like a switch/case
ExampleGO TO 50GO TO (10, 20, 30), I
C     Unconditional GOTO:
      GO TO 100     ! always jumps to statement 100
  100 WRITE(*,*) 'Arrived here'

C     Computed GOTO (jumps to 10 if I=1, 20 if I=2, 30 if I=3):
      I = 2
      GO TO (10, 20, 30), I
   10 WRITE(*,*) 'ONE'
      GO TO 40
   20 WRITE(*,*) 'TWO'     ! this executes
      GO TO 40
   30 WRITE(*,*) 'THREE'
   40 CONTINUE

FORTRAN Program – Sort 1D Array (Ascending & Descending)

      PROGRAM SORTARRAY
      INTEGER N, I, J, TEMP
      INTEGER ARR(20)

      WRITE(*,*) 'Enter number of elements (max 20):'
      READ(*,*)  N

      WRITE(*,*) 'Enter', N, 'elements:'
      DO 10 I = 1, N
          READ(*,*) ARR(I)
   10 CONTINUE

C     Bubble Sort - Ascending Order
      DO 30 I = 1, N-1
          DO 20 J = 1, N-I
              IF (ARR(J) .GT. ARR(J+1)) THEN
                  TEMP     = ARR(J)
                  ARR(J)   = ARR(J+1)
                  ARR(J+1) = TEMP
              END IF
   20     CONTINUE
   30 CONTINUE

      WRITE(*,*) 'Ascending Order:'
      DO 40 I = 1, N
          WRITE(*,'(I5)',ADVANCE='NO') ARR(I)
   40 CONTINUE
      WRITE(*,*)

C     Reverse the array for Descending Order
      DO 50 I = 1, N/2
          TEMP         = ARR(I)
          ARR(I)       = ARR(N+1-I)
          ARR(N+1-I)   = TEMP
   50 CONTINUE

      WRITE(*,*) 'Descending Order:'
      DO 60 I = 1, N
          WRITE(*,'(I5)',ADVANCE='NO') ARR(I)
   60 CONTINUE
      WRITE(*,*)

      STOP
      END

Output

Enter number of elements (max 20):
5
Enter 5 elements:
40 10 30 20 50

Ascending Order:
   10   20   30   40   50
Descending Order:
   50   40   30   20   10

Set 9 | 078 Kartik | Back

Computer Programming [CT401]
Discuss the recent software trends. Explain in details about the features that a software should include.
2078 Kartik [2+2]

Recent Software Trends

TrendDescription
Artificial Intelligence & MLAI/ML is being integrated into almost all software — from recommendation engines to smart assistants (e.g., ChatGPT, GitHub Copilot).
Cloud ComputingSoftware is deployed on cloud platforms (AWS, Azure, GCP) enabling scalability, remote access, and reduced hardware dependency.
Internet of Things (IoT)Software now communicates with embedded devices — smart home, wearables, industrial sensors.
DevOps & CI/CDContinuous Integration and Continuous Deployment pipelines speed up software delivery and reliability.
Mobile-first DevelopmentSoftware is increasingly designed for smartphones first, with cross-platform frameworks like Flutter and React Native.
Cybersecurity FocusSecurity is built into software from the start (DevSecOps), with end-to-end encryption and zero-trust models.
Agile & MicroservicesLarge monolithic applications are broken into small, independent microservices for flexibility and easier maintenance.

Features a Software Should Include

FeatureDescription
FunctionalityThe software must perform all intended tasks correctly and completely as per user requirements.
ReliabilityShould work consistently without failure under expected conditions. Minimal downtime and error rate.
UsabilityUser-friendly interface that requires minimal training. Intuitive navigation and clear feedback.
EfficiencyOptimal use of system resources (CPU, memory, disk) while delivering fast response times.
MaintainabilityCode should be easy to read, modify, and debug. Well-documented and modular design.
PortabilityAbility to run on different hardware, operating systems, or environments with minimal changes.
SecurityProtection against unauthorized access, data breaches, and vulnerabilities.
ScalabilityAbility to handle increased load (users, data) without degradation in performance.
List out the general rules for flowcharting. What are the errors that might occur during debugging?
2078 Kartik [2+2]

General Rules for Flowcharting

  • Start and End with Terminal Symbol: Every flowchart must begin and end with an oval (terminal) symbol labeled START and STOP/END.
  • Use Standard Symbols: Use universally accepted symbols — oval (start/end), rectangle (process), diamond (decision), parallelogram (input/output), arrows (flow direction).
  • Flow Direction: The flow should generally go from top to bottom and left to right. Arrows must clearly show direction.
  • One Entry, One Exit: Each symbol (except decision) should have only one entry and one exit point.
  • Decision Symbols: The diamond must have exactly two exits — Yes/True and No/False — clearly labeled.
  • Avoid Crossing Lines: Flow lines should not cross each other. Use connectors (circle) if the chart spans multiple pages.
  • Keep it Simple: Each process box should contain one clear action. Avoid cramming multiple steps.
  • Consistency: Use consistent symbol sizes and label all symbols clearly.

Errors That Might Occur During Debugging

Error TypeDescriptionExample
Syntax ErrorViolation of grammar rules of the programming language. Detected by the compiler.Missing semicolon, unmatched parentheses: printf("Hello"
Logical ErrorProgram compiles and runs but produces wrong output due to incorrect logic.Using + instead of * in a multiplication formula
Runtime ErrorError that occurs during execution, causing the program to crash or behave unexpectedly.Division by zero, accessing out-of-bounds array index
Semantic ErrorCode is syntactically correct but has unintended meaning.Assigning wrong data type or using uninitialized variable
Linker ErrorOccurs when the linker cannot find the definition of a referenced function or variable.Calling a function that is declared but never defined
What are pre-processor directives? Explain compilation process with suitable block diagram.
2078 Kartik [1+3]

Preprocessor Directives

Preprocessor directives are instructions processed by the C preprocessor before actual compilation begins. They start with the # symbol and do not end with a semicolon. They perform tasks like file inclusion, macro substitution, and conditional compilation.

DirectivePurposeExample
#includeIncludes a header file into the source code#include <stdio.h>
#defineDefines a macro or constant#define PI 3.14159
#ifdef / #ifndefConditional compilation#ifdef DEBUG ... #endif
#undefUndefines a previously defined macro#undef PI
#pragmaMachine-specific or compiler-specific instructions#pragma warning(disable:4996)

Compilation Process in C

The compilation process converts C source code into an executable program through the following stages:

+------------------+
|  Source Code     |  (.c file written by programmer)
|  (program.c)     |
+------------------+
        |
        v  [PREPROCESSOR]
+------------------+
| Preprocessed     |  Expands #include, #define, macros
| Source Code      |  Removes comments
+------------------+
        |
        v  [COMPILER]
+------------------+
| Assembly Code    |  Converts C code to assembly language
| (program.asm)    |  Checks syntax and semantic errors
+------------------+
        |
        v  [ASSEMBLER]
+------------------+
| Object Code      |  Converts assembly to machine code (binary)
| (program.obj)    |  Not yet executable (unresolved references)
+------------------+
        |
        v  [LINKER]
+------------------+
| Executable File  |  Links object code with library files
| (program.exe)    |  Resolves all function references
+------------------+
        |
        v  [LOADER]
+------------------+
|  Execution       |  Loads program into RAM and runs it
|  (Output)        |
+------------------+

Summary of Stages

StageToolInputOutput
1. PreprocessingPreprocessor.c fileExpanded .c file
2. CompilationCompilerExpanded .cAssembly (.asm)
3. AssemblyAssembler.asm fileObject file (.obj)
4. LinkingLinker.obj + librariesExecutable (.exe)
5. LoadingLoader/OS.exe fileProgram in memory (runs)
Why do we need to analyse the problem before solving it? Define tokens, expression and identifiers.
2078 Kartik [1+3]

Why We Need to Analyse a Problem Before Solving It

Problem analysis is the first and most critical step in programming. Without it, we risk writing code that solves the wrong problem or is inefficient.

  • Clear Understanding: Helps fully understand what the problem is asking — inputs, outputs, and constraints.
  • Choosing the Right Approach: Allows selection of the best algorithm or data structure before writing any code.
  • Avoiding Rework: Errors caught during analysis are far cheaper to fix than errors found after coding.
  • Efficient Solution: Analysis helps identify edge cases, special conditions, and performance requirements.
  • Better Planning: Leads to a clear algorithm and flowchart, making coding systematic and less error-prone.

Tokens

A token is the smallest individual unit in a C program that is meaningful to the compiler. Every C program is made up of tokens.

Types of tokens in C: Keywords, Identifiers, Constants, Strings, Operators, Special Symbols.

Example: int sum = a + b;
Tokens: int | sum | = | a | + | b | ;
        (keyword)(id)(op)(id)(op)(id)(special)

Expression

An expression is a combination of variables, constants, and operators that evaluates to a single value. Expressions can be arithmetic, relational, logical, or assignment-based.

Examples:
a + b          /* arithmetic expression — evaluates to sum */
a > b          /* relational expression — evaluates to 1 or 0 */
a && b         /* logical expression */
x = 5 * 2     /* assignment expression — evaluates to 10 */
++i            /* unary expression */

Identifiers

An identifier is a name given by the programmer to variables, functions, arrays, or other user-defined entities. Identifiers must follow these rules:

  • Can contain letters (A–Z, a–z), digits (0–9), and underscore (_).
  • Must begin with a letter or underscore (not a digit).
  • Cannot be a keyword (e.g., int, float are not valid identifiers).
  • Case-sensitive: sum and Sum are different identifiers.
  • No special characters like @, #, $ are allowed.
Valid identifiers:    sum, _count, marks2, firstName, MAX_SIZE
Invalid identifiers:  2marks (starts with digit), int (keyword), my-name (hyphen)
What is the control statement? Write down the classification of control statements.
2078 Kartik [1+2]

Control Statement

A control statement is a statement that determines the order in which other statements are executed in a program. By default, C executes statements sequentially. Control statements alter this flow based on conditions or loops.

Classification of Control Statements

CategoryStatementsDescription
Conditional / Decision-Making if, if-else, if-else if ladder, nested if, switch-case Execute a block of code only when a specified condition is true. Choose between alternate paths.
Looping / Iteration while, do-while, for Repeatedly execute a block of statements as long as a condition holds true.
Jump / Transfer break, continue, goto, return Transfer control to another part of the program unconditionally or based on a condition.
/* Quick Examples */

/* Conditional */
if (a > b) printf("a is greater");
else       printf("b is greater");

/* Looping */
for (i = 1; i <= 5; i++)
  printf("%d ", i);   /* prints: 1 2 3 4 5 */

/* Jump */
for (i = 0; i < 10; i++) {
  if (i == 5) break;     /* exit loop at i=5 */
  if (i % 2 == 0) continue;  /* skip even numbers */
  printf("%d ", i);
}
Write down the syntax for the following functions: (i) printf()   (ii) scanf()   (iii) getchar()   (iv) getch()
2078 Kartik [4×1]

(i) printf()

Prints formatted output to the standard output (screen). Defined in stdio.h.

Syntax:  int printf(const char *format, argument_list);

Examples:
printf("Hello World\n");            /* prints a string */
printf("a = %d\n", a);             /* prints integer */
printf("x = %5.2f\n", x);         /* prints float with width and precision */
printf("%s is %d years old\n", name, age);

(ii) scanf()

Reads formatted input from the standard input (keyboard). Returns number of successfully read items. Defined in stdio.h.

Syntax:  int scanf(const char *format, address_list);

Examples:
scanf("%d", &n);              /* read integer */
scanf("%f", &x);              /* read float */
scanf("%s", name);            /* read string (array, no & needed) */
scanf("%d %f", &n, &x);      /* read multiple values */

(iii) getchar()

Reads a single character from standard input. Waits for the Enter key to be pressed. Character is echoed on screen. Defined in stdio.h.

Syntax:  int getchar(void);

Example:
#include <stdio.h>
char ch;
ch = getchar();    /* user types a char and presses Enter */
printf("You entered: %c", ch);

(iv) getch()

Reads a single character from the keyboard without echo (character is NOT displayed on screen) and returns immediately without waiting for Enter. Defined in conio.h (Turbo C/Windows).

Syntax:  int getch(void);

Example:
#include <conio.h>
char ch;
ch = getch();   /* reads immediately, no echo, no Enter needed */

Comparison Table

FunctionHeaderEcho?Waits for Enter?Type
printf()stdio.hFormatted Output
scanf()stdio.hYesYesFormatted Input
getchar()stdio.hYesYesUnformatted Input
getch()conio.hNoNoUnformatted Input
Write the output of the following C program:
char ch='G'; int g=10; float gravity=9.81; printf("%d%d%%f\n"); printf("%10d\n",g); printf("%3c\n",ch); printf("%3f\n",gravity); printf("%-10.1f%d\n",gravity,g);
2078 Kartik [3×1]

Given Program

#include <stdio.h>
int main() {
  char ch = 'G';
  int g = 10;
  float gravity = 9.81;

  printf("%d%d%%f\n");         /* line 1 */
  printf("%10d\n", g);         /* line 2 */
  printf("%3c\n", ch);         /* line 3 */
  printf("%3f\n", gravity);    /* line 4 */
  printf("%-10.1f%d\n", gravity, g);  /* line 5 */
  return 0;
}

Output Analysis

StatementFormat ExplanationOutput
printf("%d%d%%f\n"); %d%d with no arguments — undefined behavior (garbage values); %% prints literal %; then literal f [garbage][garbage]%f
printf("%10d\n", g); %10d — print g=10 right-aligned in a field of width 10         10
printf("%3c\n", ch); %3c — print ch='G' right-aligned in field of width 3 (2 spaces + G)   G
printf("%3f\n", gravity); %3f — print gravity=9.81 with default 6 decimal places; width 3 is less than the number's width so it's ignored 9.810000
printf("%-10.1f%d\n", gravity, g); %-10.1f — left-align gravity to 1 decimal in width 10; then %d prints g=10 9.8       10

Final Output

[garbage values]%f
      10
G
9.810000
9.8       10

Note: Line 1 (printf("%d%d%%f\n")) invokes undefined behavior since no arguments are supplied for %d%d. On most compilers, garbage values or 0 are printed.

Define and write syntax of the following: (i) gets()    (ii) putchar()    (iii) scanf()
2078 Kartik [3]

(i) gets()

gets() reads a line of characters from standard input (keyboard) into a character array until a newline (\n) or EOF is encountered. The newline is replaced by a null character (\0). Defined in stdio.h.

Note: gets() is considered unsafe (no bounds checking); use fgets() in modern C.

Syntax:  char *gets(char *str);

Example:
#include <stdio.h>
char name[50];
printf("Enter name: ");
gets(name);           /* reads full line including spaces */
printf("Hello, %s\n", name);

(ii) putchar()

putchar() writes a single character to the standard output (screen). It returns the character written, or EOF on error. Defined in stdio.h.

Syntax:  int putchar(int character);

Example:
#include <stdio.h>
char ch = 'A';
putchar(ch);         /* prints: A */
putchar('\n');       /* prints a newline */
putchar(65);         /* prints: A (ASCII 65) */

(iii) scanf()

scanf() reads formatted input from standard input according to the format string. Returns the number of items successfully read. Defined in stdio.h.

Syntax:  int scanf(const char *format, address_list);

Example:
#include <stdio.h>
int n;
float x;
char name[50];
scanf("%d", &n);             /* read integer */
scanf("%f", &x);             /* read float */
scanf("%s", name);           /* read string (no & for arrays) */
scanf("%d %f", &n, &x);     /* read multiple values at once */
Why do we need loop for programming? Write a program to evaluate the following series: cos(x) = 1 − x²/2! + x⁴/4! − x⁶/6! + ......... + n terms
2078 Kartik [2+4]

Why We Need Loops in Programming

  • Repetition: Loops allow a block of code to execute multiple times without writing it repeatedly.
  • Efficiency: Tasks like summing 1000 numbers or printing a table would be impractical without loops.
  • Series Evaluation: Mathematical series with many terms are naturally expressed as loops.
  • Array Processing: Loops are essential for traversing, searching, and sorting arrays.
  • User-Driven Repetition: Loops allow programs to repeat actions based on user input or conditions.
  • Reduced Code Size: Loops dramatically reduce the amount of code needed to perform repetitive tasks.

C Program – cos(x) Series Using Loop

#include <stdio.h>

int main() {
  int n, i;
  double x, term, cosVal;

  printf("Enter value of x (in radians): ");
  scanf("%lf", &x);
  printf("Enter number of terms: ");
  scanf("%d", &n);

  cosVal = 0.0;
  term   = 1.0;   /* first term is 1 (x^0 / 0!) */

  for (i = 1; i <= n; i++) {
      cosVal += term;
      /* Next term = -term * x^2 / ((2i-1) * 2i) */
      term = -term * x * x / ((2 * i - 1) * (2 * i));
  }

  printf("\ncos(%.2f) = %.6f\n", x, cosVal);
  return 0;
}

Output

Enter value of x (in radians): 0
Enter number of terms: 5
cos(0.00) = 1.000000

Enter value of x (in radians): 1.5708
Enter number of terms: 10
cos(1.57) = 0.000007   (approximately 0, since cos(π/2) ≈ 0)

Series Logic

Term Number (i)ExpressionSign
11 (= x⁰/0!)+
2x²/2!
3x⁴/4!+
4x⁶/6!
nx^(2n-2) / (2n-2)!alternating

Each new term is derived from the previous: term_new = -term_prev × x² / ((2i-1) × 2i)

Why do we need to declare a function? Define formal parameter and actual parameter. Evaluate the following series using recursive function: 1, 11, 111, 1111, 11111, ....... n terms
2078 Kartik [2+2+4]

Why We Need to Declare a Function

A function declaration (prototype) informs the compiler about the function's return type, name, and parameter types before it is defined or called.

  • Forward Reference: Allows calling a function before its definition appears in the source file.
  • Type Checking: The compiler verifies that the correct number and types of arguments are passed.
  • Modularity: Promotes structured programming by separating tasks into reusable units.
  • Avoiding Errors: Without a prototype, the compiler may assume wrong return types, leading to bugs.
/* Function declaration (prototype) */
int add(int a, int b);   /* declared before main() */

int main() {
  printf("%d\n", add(3, 4));   /* called here */
  return 0;
}

int add(int a, int b) {   /* defined after main() */
  return a + b;
}

Formal Parameter vs Actual Parameter

BasisFormal ParameterActual Parameter
DefinitionVariable declared in the function definition that receives valuesActual values or variables passed when calling the function
LocationIn the function header/definitionIn the function call
ScopeLocal to the functionExists in the calling function
MemoryAllocated when function is called, freed when it returnsExists in the caller's memory space
Examplevoid show(int x, int y) — x and y are formalshow(a, b) — a and b are actual

C Program – Series 1, 11, 111, 1111... Using Recursion

#include <stdio.h>

/* Returns the nth term: 1, 11, 111, 1111, ... */
long long nthTerm(int n) {
  if (n == 1)
      return 1;                        /* base case: 1st term is 1 */
  return nthTerm(n - 1) * 10 + 1;     /* e.g., 11 = 1*10+1, 111 = 11*10+1 */
}

/* Recursively prints and sums all terms */
long long seriesSum(int n) {
  if (n == 0)
      return 0;
  long long term = nthTerm(n);
  printf("Term %d = %lld\n", n, term);
  return term + seriesSum(n - 1);
}

int main() {
  int n;
  printf("Enter number of terms: ");
  scanf("%d", &n);

  printf("\nSeries:\n");
  long long sum = seriesSum(n);
  printf("\nSum of %d terms = %lld\n", n, sum);
  return 0;
}

Output

Enter number of terms: 5

Series:
Term 5 = 11111
Term 4 = 1111
Term 3 = 111
Term 2 = 11
Term 1 = 1

Sum of 5 terms = 12345

Recursive Trace for n=4

nthTerm(1) = 1
nthTerm(2) = 1 * 10 + 1 = 11
nthTerm(3) = 11 * 10 + 1 = 111
nthTerm(4) = 111 * 10 + 1 = 1111
Define an array of string with an example. Distinguish between array and pointer.
2078 Kartik [2+2]

Array of Strings

An array of strings is a two-dimensional character array where each row stores one string (character array). It is used to store multiple strings under a single variable name.

Syntax:  char array_name[rows][max_length];

Example:
char fruits[5][20] = {"Apple", "Banana", "Mango", "Orange", "Grape"};

/* Accessing and printing */
#include <stdio.h>
int main() {
  char fruits[5][20] = {"Apple", "Banana", "Mango", "Orange", "Grape"};
  int i;
  for (i = 0; i < 5; i++)
      printf("%s\n", fruits[i]);
  return 0;
}
/* Output:
  Apple
  Banana
  Mango
  Orange
  Grape
*/

Here, fruits[0] stores "Apple", fruits[1] stores "Banana", etc. Each string can hold up to 19 characters plus the null terminator '\0'.

Difference Between Array and Pointer

BasisArrayPointer
DefinitionA collection of elements of the same type stored in contiguous memoryA variable that stores the memory address of another variable
Declarationint arr[5];int *ptr;
Memory AllocationAllocated at compile time (static)Can be allocated dynamically at runtime
ReassignmentArray name is a constant pointer; cannot be reassigned (arr++ is illegal)Pointer can be reassigned to point to different locations (ptr++ is valid)
Sizesizeof(arr) returns total bytes of the arraysizeof(ptr) returns size of the pointer (4 or 8 bytes)
InitializationCan be initialized at declaration: int arr[] = {1,2,3};Must be assigned an address: ptr = arr;
Accessing elementsarr[i]*(ptr + i) or ptr[i]
Write a C program to insert an element to a desired position to an array using function. The new element to be inserted and desired position should be given by user.
2078 Kartik [6]

C Program – Insert Element at Desired Position Using Function

#include <stdio.h>

#define MAX 100

/* Function to display the array */
void display(int arr[], int n) {
  int i;
  printf("Array: ");
  for (i = 0; i < n; i++)
      printf("%d ", arr[i]);
  printf("\n");
}

/* Function to insert element at given position */
int insertElement(int arr[], int n, int element, int pos) {
  int i;

  /* Validate position (1-based indexing) */
  if (pos < 1 || pos > n + 1) {
      printf("Invalid position! Position must be between 1 and %d.\n", n + 1);
      return n;   /* array unchanged */
  }

  /* Shift elements to the right from the end to pos */
  for (i = n; i >= pos; i--)
      arr[i] = arr[i - 1];

  /* Insert the new element at position (convert to 0-based) */
  arr[pos - 1] = element;

  return n + 1;   /* new size */
}

int main() {
  int arr[MAX], n, element, pos;

  printf("Enter number of elements: ");
  scanf("%d", &n);

  printf("Enter %d elements:\n", n);
  int i;
  for (i = 0; i < n; i++)
      scanf("%d", &arr[i]);

  printf("\nBefore insertion: ");
  display(arr, n);

  printf("\nEnter the element to insert: ");
  scanf("%d", &element);
  printf("Enter the position to insert at (1 to %d): ", n + 1);
  scanf("%d", &pos);

  n = insertElement(arr, n, element, pos);

  printf("\nAfter insertion: ");
  display(arr, n);

  return 0;
}

Output

Enter number of elements: 5
Enter 5 elements:
10 20 30 40 50

Before insertion: Array: 10 20 30 40 50

Enter the element to insert: 25
Enter the position to insert at (1 to 6): 3

After insertion: Array: 10 20 25 30 40 50

Logic Explanation

StepDescription
1. Validate positionPosition must be between 1 and n+1 (inclusive)
2. Shift rightAll elements from position pos to n are shifted one place to the right
3. InsertNew element placed at arr[pos-1] (0-based)
4. Update sizeReturn n+1 as the new array size
Define a void pointer with an appropriate example.
2078 Kartik [2]

Void Pointer

A void pointer (also called a generic pointer) is a special type of pointer declared with the void keyword. It can hold the address of any data type (int, float, char, struct, etc.) without needing to specify the type at declaration. However, it cannot be dereferenced directly — it must be cast to the appropriate type before accessing the value.

Syntax:  void *pointer_name;

/* Key Properties:
  - Can point to any data type
  - Cannot be dereferenced without casting
  - Cannot use pointer arithmetic without casting
  - Commonly used in generic functions (like malloc, memcpy)
*/

Example

#include <stdio.h>

int main() {
  int    inum = 42;
  float  fnum = 3.14;
  char   ch   = 'A';

  void *vptr;   /* void pointer */

  /* Point to int */
  vptr = &inum;
  printf("Integer value: %d\n", *(int *)vptr);    /* cast to int* before dereferencing */

  /* Point to float */
  vptr = &fnum;
  printf("Float value: %.2f\n", *(float *)vptr);  /* cast to float* */

  /* Point to char */
  vptr = &ch;
  printf("Char value: %c\n", *(char *)vptr);      /* cast to char* */

  return 0;
}
/* Output:
  Integer value: 42
  Float value: 3.14
  Char value: A
*/

Use Case: malloc() returns a void * so it can allocate memory for any type: int *p = (int *) malloc(5 * sizeof(int));

Write a C program that uses pointer to represent two 2-D array of size m×n and p×q respectively. Find the product of these two matrices if possible otherwise display a message "Calculation cannot be performed" using function.
2078 Kartik [6]

C Program – Matrix Multiplication Using Pointers

#include <stdio.h>
#include <stdlib.h>

#define MAX 10

/* Function to read matrix */
void readMatrix(int (*mat)[MAX], int rows, int cols, char name) {
  int i, j;
  printf("Enter elements of Matrix %c (%dx%d):\n", name, rows, cols);
  for (i = 0; i < rows; i++)
      for (j = 0; j < cols; j++)
          scanf("%d", *(mat + i) + j);   /* pointer notation */
}

/* Function to display matrix */
void displayMatrix(int (*mat)[MAX], int rows, int cols) {
  int i, j;
  for (i = 0; i < rows; i++) {
      for (j = 0; j < cols; j++)
          printf("%5d", *(*(mat + i) + j));   /* pointer dereference */
      printf("\n");
  }
}

/* Function to multiply matrices */
void multiplyMatrix(int (*A)[MAX], int (*B)[MAX], int (*C)[MAX],
                  int m, int n, int p, int q) {
  int i, j, k;

  /* Matrix multiplication is possible only if n == p */
  if (n != p) {
      printf("Calculation cannot be performed!\n");
      printf("(Columns of A = %d) != (Rows of B = %d)\n", n, p);
      return;
  }

  /* Initialize result matrix C to 0 */
  for (i = 0; i < m; i++)
      for (j = 0; j < q; j++)
          *(*(C + i) + j) = 0;

  /* Multiply: C[i][j] = sum of A[i][k] * B[k][j] */
  for (i = 0; i < m; i++)
      for (j = 0; j < q; j++)
          for (k = 0; k < n; k++)
              *(*(C + i) + j) += *(*(A + i) + k) * *(*(B + k) + j);

  printf("\nProduct Matrix C (%dx%d):\n", m, q);
  displayMatrix(C, m, q);
}

int main() {
  int A[MAX][MAX], B[MAX][MAX], C[MAX][MAX];
  int m, n, p, q;

  printf("Enter dimensions of Matrix A (rows cols): ");
  scanf("%d %d", &m, &n);
  printf("Enter dimensions of Matrix B (rows cols): ");
  scanf("%d %d", &p, &q);

  readMatrix(A, m, n, 'A');
  readMatrix(B, p, q, 'B');

  printf("\nMatrix A (%dx%d):\n", m, n);
  displayMatrix(A, m, n);
  printf("\nMatrix B (%dx%d):\n", p, q);
  displayMatrix(B, p, q);

  multiplyMatrix(A, B, C, m, n, p, q);

  return 0;
}

Sample Output (Possible Case: 2×3 × 3×2)

Matrix A (2x3):    Matrix B (3x2):
1  2  3            7  8
4  5  6            9 10
                  11 12

Product Matrix C (2x2):
  58   64
139  154

Sample Output (Impossible Case: 2×3 × 2×3)

Calculation cannot be performed!
(Columns of A = 3) != (Rows of B = 2)
Discuss about nested structure with a suitable example. Create a structure called "student" with data member name, address and id.pass structure to function and sort the information of student on the basis of alphabetical order of "name" and display the result in main() function.
2078 Kartik [2+6]

Nested Structure

A nested structure is a structure that contains another structure as one of its members. This allows grouping of related data hierarchically, making complex real-world entities easier to model.

/* Example of Nested Structure */
struct Date {
  int day, month, year;
};

struct Employee {
  int empID;
  char name[50];
  struct Date birthDate;   /* nested structure */
  float salary;
};

struct Employee e;
e.empID        = 101;
e.birthDate.day   = 15;    /* accessing nested member */
e.birthDate.month = 8;
e.birthDate.year  = 1995;

C Program – Student Structure, Pass to Function, Sort by Name

#include <stdio.h>
#include <string.h>

#define N 5

struct Student {
  int  id;
  char name[50];
  char address[100];
};

/* Function to sort students alphabetically by name (Bubble Sort) */
void sortByName(struct Student s[], int n) {
  int i, j;
  struct Student temp;
  for (i = 0; i < n - 1; i++) {
      for (j = 0; j < n - i - 1; j++) {
          if (strcmp(s[j].name, s[j+1].name) > 0) {
              temp    = s[j];
              s[j]    = s[j+1];
              s[j+1]  = temp;
          }
      }
  }
}

/* Function to display students */
void display(struct Student s[], int n) {
  int i;
  printf("\n%-5s %-20s %-30s\n", "ID", "Name", "Address");
  printf("------------------------------------------------------\n");
  for (i = 0; i < n; i++)
      printf("%-5d %-20s %-30s\n", s[i].id, s[i].name, s[i].address);
}

int main() {
  struct Student s[N];
  int i;

  /* Input */
  for (i = 0; i < N; i++) {
      printf("\nEnter details of Student %d:\n", i + 1);
      printf("ID      : ");
      scanf("%d", &s[i].id);
      printf("Name    : ");
      scanf(" %[^\n]", s[i].name);
      printf("Address : ");
      scanf(" %[^\n]", s[i].address);
  }

  printf("\nBefore Sorting:");
  display(s, N);

  /* Sort by name */
  sortByName(s, N);

  printf("\nAfter Sorting (Alphabetical by Name):");
  display(s, N);

  return 0;
}

Sample Output

Before Sorting:
ID    Name                 Address
------------------------------------------------------
3     Ram Sharma           Kathmandu
1     Hari Thapa           Pokhara
5     Anita Rai            Biratnagar
2     Sita Poudel          Chitwan
4     Bishnu KC            Butwal

After Sorting (Alphabetical by Name):
ID    Name                 Address
------------------------------------------------------
5     Anita Rai            Biratnagar
4     Bishnu KC            Butwal
1     Hari Thapa           Pokhara
3     Ram Sharma           Kathmandu
2     Sita Poudel          Chitwan
Write a C program to create a new file named "employee.dat" which consist the information of 10 employees. Employee information includes empName, salary and post. Read the file back to search the word "manager".
2078 Kartik [6]

C Program – Write Employee Data and Search "manager"

#include <stdio.h>
#include <string.h>

#define N 10

struct Employee {
  char empName[50];
  float salary;
  char post[30];
};

int main() {
  struct Employee emp[N];
  int i;
  FILE *fp;

  /* ---- Input employee records ---- */
  printf("Enter details of %d employees:\n", N);
  for (i = 0; i < N; i++) {
      printf("\nEmployee %d:\n", i + 1);
      printf("Name   : ");
      scanf(" %[^\n]", emp[i].empName);
      printf("Salary : ");
      scanf("%f", &emp[i].salary);
      printf("Post   : ");
      scanf(" %[^\n]", emp[i].post);
  }

  /* ---- Write to employee.dat (binary mode) ---- */
  fp = fopen("employee.dat", "wb");
  if (fp == NULL) {
      printf("Error: Cannot create employee.dat\n");
      return 1;
  }
  for (i = 0; i < N; i++)
      fwrite(&emp[i], sizeof(struct Employee), 1, fp);
  fclose(fp);
  printf("\nData written to employee.dat successfully.\n");

  /* ---- Read back and search for "manager" (case-insensitive) ---- */
  fp = fopen("employee.dat", "rb");
  if (fp == NULL) {
      printf("Error: Cannot open employee.dat\n");
      return 1;
  }

  struct Employee temp;
  int found = 0;
  printf("\n--- Employees with post 'manager' ---\n");
  printf("%-5s %-20s %-12s %-15s\n", "No.", "Name", "Salary", "Post");
  printf("----------------------------------------------\n");

  i = 1;
  while (fread(&temp, sizeof(struct Employee), 1, fp) == 1) {
      /* Convert post to lowercase for case-insensitive comparison */
      char postLower[30];
      int k;
      for (k = 0; temp.post[k]; k++)
          postLower[k] = (temp.post[k] >= 'A' && temp.post[k] <= 'Z')
                          ? temp.post[k] + 32 : temp.post[k];
      postLower[k] = '\0';

      if (strstr(postLower, "manager") != NULL) {
          printf("%-5d %-20s %-12.2f %-15s\n", i, temp.empName, temp.salary, temp.post);
          found++;
      }
      i++;
  }
  fclose(fp);

  if (found == 0)
      printf("No employee found with post 'manager'.\n");
  else
      printf("\nTotal manager(s) found: %d\n", found);

  return 0;
}

Sample Output

Data written to employee.dat successfully.

--- Employees with post 'manager' ---
No.  Name                 Salary       Post
----------------------------------------------
2    Sita Rai             75000.00     Manager
7    Ram Thapa            82000.00     Senior Manager

Total manager(s) found: 2

Key Functions Used

FunctionPurpose
fopen("employee.dat", "wb")Create/open file for binary writing
fwrite()Write a struct record to the file
fopen("employee.dat", "rb")Open file for binary reading
fread()Read one struct record at a time
strstr()Search for substring "manager" in the post field
fclose()Close the file after operations
Explain different format types used in FORTRAN. Mention different data types used in FORTRAN.
2078 Kartik [3+2]

Format Types Used in FORTRAN

In FORTRAN, the FORMAT statement controls how data is read from input or written to output. Format descriptors specify the type, width, and precision of each field.

DescriptorTypeSyntaxDescriptionExample
I Integer Iw Integer in field of width w I5 → right-justified integer in 5 columns
F Real (Fixed) Fw.d Floating-point with w total width, d decimal places F8.3 → e.g., " 12.345"
E Real (Scientific) Ew.d Exponential (scientific) notation E12.4 → e.g., " 0.1235E+02"
A Character Aw or A Character string of width w A10 → 10-character string field
L Logical Lw Logical value (.TRUE. or .FALSE.) in width w L3 → prints T or F
X Blank/Space nX Insert n blank spaces in output or skip n chars in input 5X → 5 blank spaces
T Tab Tn Move to absolute column n (tabbing) T15 → position cursor at column 15
/ Newline / Move to next record (new line) FORMAT(I5 / F8.2) → two lines
C     FORMAT Examples:
    WRITE(*,100) 42, 3.14159, 'Hello'
100 FORMAT(I5, F8.3, 5X, A5)
C     Output: "   42   3.142     Hello"

    WRITE(*,200) 'Name', 'Score'
200 FORMAT(T1, A10, T15, A5)
C     Output: "Name          Score" (tabbed at columns 1 and 15)

Data Types Used in FORTRAN

Data TypeKeywordDescriptionExample
Integer INTEGER Whole numbers (positive, negative, zero). Default 4 bytes. INTEGER N; N = 100
Real REAL Single-precision floating-point numbers. Default 4 bytes. REAL X; X = 3.14
Double Precision DOUBLE PRECISION Double-precision floating-point (8 bytes). More accurate than REAL. DOUBLE PRECISION PI; PI = 3.14159265358979
Complex COMPLEX Complex numbers with real and imaginary parts. COMPLEX Z; Z = (3.0, 4.0) → 3+4i
Logical LOGICAL Boolean values: .TRUE. or .FALSE. LOGICAL FLAG; FLAG = .TRUE.
Character CHARACTER String of characters with specified length. CHARACTER*20 NAME; NAME = 'Ram Sharma'
C     FORTRAN Data Type Declaration Examples:
    INTEGER    COUNT, I, J
    REAL       TEMP, RATE
    DOUBLE PRECISION  RESULT
    COMPLEX    Z1, Z2
    LOGICAL    FLAG
    CHARACTER*30  FNAME, LNAME

Set 10 | 076 Chaitra | Regular

Computer Programming [CT401]
What are different types of computer software? What do you mean by high level and low level programming languages? Along with the block diagram explain the steps involved during compilation of a source code.
2076 Chaitra [2+2+4]

Types of Computer Software

CategoryDescriptionExamples
System Software Manages and controls hardware; provides a platform for other software to run Operating System (Windows, Linux), Device Drivers, BIOS, Firmware
Application Software Designed to help users perform specific tasks MS Word, Excel, VLC Player, Chrome, Photoshop
Programming Software / Tools Used by developers to create, debug, and maintain programs Compilers, Interpreters, Assemblers, IDEs (VS Code, Dev-C++)
Utility Software Performs maintenance tasks for the computer system Antivirus, Disk Cleaner, File Compressor (WinZip), Backup tools
Embedded Software Software embedded within hardware devices for specific functions Washing machine controller, ATM software, Microwave firmware

High Level vs Low Level Programming Languages

BasisHigh Level LanguageLow Level Language
DefinitionCloser to human language; uses English-like syntaxCloser to machine language; uses binary or mnemonics
Types3GL (C, Java, Python), 4GL (SQL), 5GL (Prolog)Machine Language (1GL), Assembly Language (2GL)
ReadabilityEasy to read, write and understandDifficult to read and understand
Machine DependencyMachine-independent; portable across platformsMachine-dependent; specific to hardware
Execution SpeedSlower (needs translation)Faster (directly or near-directly executed)
TranslatorCompiler or InterpreterAssembler (for Assembly); none for Machine Language
ExamplesC, C++, Java, Python, FORTRANBinary code (00110001), MOV AX, BX

Steps in Compilation of Source Code (Block Diagram)

+-------------------------+
|   Source Code (.c)      |  Written by programmer in high-level language
+-------------------------+
             |
             v  [PREPROCESSOR]
+-------------------------+
|  Preprocessed Code      |  - Expands #include, #define macros
|  (Expanded Source)      |  - Removes comments
+-------------------------+
             |
             v  [COMPILER]
+-------------------------+
|  Assembly Code (.asm)   |  - Translates HLL to assembly
|                         |  - Checks syntax and semantic errors
+-------------------------+
             |
             v  [ASSEMBLER]
+-------------------------+
|  Object Code (.obj)     |  - Converts assembly to binary machine code
|                         |  - Unresolved external references remain
+-------------------------+
             |
             v  [LINKER]
+-------------------------+
|  Executable File (.exe) |  - Links object code with libraries
|                         |  - Resolves all function/variable references
+-------------------------+
             |
             v  [LOADER]
+-------------------------+
|  Program in Memory      |  - OS loads executable into RAM
|  (Execution / Output)   |  - CPU executes instructions
+-------------------------+
StageToolInputOutput
PreprocessingPreprocessor.c fileExpanded source
CompilationCompilerExpanded sourceAssembly (.asm)
AssemblyAssembler.asmObject file (.obj)
LinkingLinker.obj + librariesExecutable (.exe)
LoadingLoader.exeRunning program
Explain different types of error that usually appears during the programming. Define preprocessing directive and explain its type with example. Write the algorithm and draw the flowchart to find the reverse of a given number.
2076 Chaitra [2+2+4]

Types of Errors in Programming

Error TypeDescriptionWhen DetectedExample
Syntax ErrorViolation of grammar rules of the languageCompile timeMissing ;, unmatched {, wrong keyword
Logical ErrorProgram runs but gives wrong result due to incorrect logicRuntime (by testing)Using + instead of *
Runtime ErrorError that occurs during execution, crashing the programRuntimeDivision by zero, null pointer dereference
Semantic ErrorSyntactically correct code with unintended meaningCompile/RuntimeUsing uninitialized variable, wrong type
Linker ErrorLinker cannot resolve references to functions or variablesLink timeCalling undefined function

Preprocessing Directives

Preprocessing directives are instructions beginning with # that are processed by the C preprocessor before compilation. They do not end with a semicolon.

DirectiveTypePurposeExample
#includeFile InclusionIncludes header/library files#include <stdio.h>
#defineMacro DefinitionDefines constants or macros#define PI 3.14159
#undefMacro RemovalUndefines a previously defined macro#undef PI
#ifdef / #ifndefConditional CompilationCompiles code block only if macro is/isn't defined#ifdef DEBUG ... #endif
#if / #else / #endifConditional CompilationConditional inclusion of code sections#if MAX > 100 ... #endif
#pragmaSpecial InstructionsCompiler-specific directives#pragma once

Algorithm – Reverse of a Given Number

Algorithm: REVERSE_NUMBER
Step 1: START
Step 2: Read the number N
Step 3: Set rev = 0
Step 4: WHILE N > 0 do:
           a. digit = N mod 10
           b. rev   = rev * 10 + digit
           c. N     = N / 10  (integer division)
Step 5: Print rev
Step 6: STOP

Flowchart – Reverse of a Given Number

          +----------+
          |  START   |
          +----------+
               |
               v
     +------------------+
     |  Read number N   |
     +------------------+
               |
               v
     +------------------+
     |    rev = 0        |
     +------------------+
               |
               v
     +--------------------+
     |  Is N > 0 ?        |---No----> +--------------+
     +--------------------+           | Print rev    |
               | Yes                  +--------------+
               v                              |
     +------------------------+               v
     | digit = N % 10         |          +--------+
     | rev   = rev * 10+digit |          |  STOP  |
     | N     = N / 10         |          +--------+
     +------------------------+
               |
               +-----(loop back to "Is N > 0?")

Example Trace: N = 1234

IterationNdigitrev
1123444
2123343
3122432
4114321
504321 (stop)
Why are formatted output important in C language? Write a program to print all the roots (Even imaginary roots) of quadratic equation.
2076 Chaitra [3+5]

Importance of Formatted Output in C

  • Precision Control: Format specifiers like %.2f allow exact control over decimal places, making numeric output readable (e.g., displaying currency as 1234.56).
  • Field Width Control: Width specifiers like %10d align columns in tabular output, essential for reports and tables.
  • Data Type Flexibility: Different specifiers (%d, %f, %c, %s, %e) allow the same function (printf) to output any data type correctly.
  • Left/Right Alignment: The - flag (e.g., %-10s) enables left-aligned text for better readability.
  • Scientific Notation: %e or %g formats large/small numbers in scientific notation for engineering/scientific applications.
  • Clean User Interface: Formatted output makes programs produce professional, user-friendly output rather than raw unaligned data.

C Program – All Roots of Quadratic Equation (Including Imaginary)

Quadratic equation: ax² + bx + c = 0
Discriminant: D = b² - 4ac

  • If D > 0: Two distinct real roots
  • If D = 0: Two equal real roots
  • If D < 0: Two complex (imaginary) roots
#include <stdio.h>
#include <math.h>

int main() {
    double a, b, c, D;
    double root1, root2, realPart, imagPart;

    printf("Enter coefficients a, b, c of ax^2 + bx + c = 0:\n");
    printf("a = "); scanf("%lf", &a);
    printf("b = "); scanf("%lf", &b);
    printf("c = "); scanf("%lf", &c);

    if (a == 0) {
        printf("Not a quadratic equation (a cannot be 0).\n");
        return 1;
    }

    D = b * b - 4 * a * c;

    printf("\nDiscriminant D = %.4f\n", D);

    if (D > 0) {
        /* Two distinct real roots */
        root1 = (-b + sqrt(D)) / (2 * a);
        root2 = (-b - sqrt(D)) / (2 * a);
        printf("Two distinct real roots:\n");
        printf("  Root 1 = %+.4f\n", root1);
        printf("  Root 2 = %+.4f\n", root2);
    }
    else if (D == 0) {
        /* Two equal real roots */
        root1 = -b / (2 * a);
        printf("Two equal real roots:\n");
        printf("  Root 1 = Root 2 = %+.4f\n", root1);
    }
    else {
        /* Two complex / imaginary roots */
        realPart = -b / (2 * a);
        imagPart = sqrt(-D) / (2 * a);
        printf("Two complex (imaginary) roots:\n");
        printf("  Root 1 = %+.4f + %.4fi\n", realPart,  imagPart);
        printf("  Root 2 = %+.4f - %.4fi\n", realPart,  imagPart);
    }

    return 0;
}

Sample Outputs

/* Case 1: Two real roots — a=1, b=-5, c=6 */
D = 1.0000
Root 1 = +3.0000
Root 2 = +2.0000

/* Case 2: Equal roots — a=1, b=-4, c=4 */
D = 0.0000
Root 1 = Root 2 = +2.0000

/* Case 3: Imaginary roots — a=1, b=2, c=5 */
D = -16.0000
Root 1 = -1.0000 + 2.0000i
Root 2 = -1.0000 - 2.0000i
Explain the importance of a switch case statement. Compare switch-case with if-else ladder. Write a program to find sum of numbers from 1 to 100 which are exactly divisible by 5 and not by 3.
2076 Chaitra [2+2+4]

Importance of switch-case Statement

  • Multiple Branching: Efficiently handles multiple fixed choices for a single variable/expression, replacing a long chain of if-else if blocks.
  • Readability: Code is cleaner and easier to understand when dealing with menu-driven programs or category-based decisions.
  • Performance: The compiler often optimizes switch-case into a jump table, making it faster than equivalent if-else chains for many cases.
  • Default Handling: The default case gracefully handles unexpected input without requiring an extra else condition.
  • Fall-through: Without break, execution falls through to the next case — useful when multiple cases share the same action.

Comparison: switch-case vs if-else ladder

Basisswitch-caseif-else ladder
Expression typeWorks only with integer or character constantsWorks with any Boolean condition (ranges, floats, strings)
ReadabilityCleaner for multiple fixed valuesCan become complex and hard to read for many conditions
SpeedFaster (jump table optimization)Slower (each condition evaluated sequentially)
Duplicate caseDuplicate case values not allowedAny overlapping conditions can be used
Range checkCannot directly check ranges (a < x < b)Can check ranges and complex conditions easily
DefaultHas default keywordUses final else block
Use caseMenu selection, day/month name, grade displayRange-based logic, complex conditions

C Program – Sum of Numbers (1–100) Divisible by 5 but NOT by 3

#include <stdio.h>

int main() {
    int i, sum = 0;

    for (i = 1; i <= 100; i++) {
        /* Divisible by 5 AND NOT divisible by 3 */
        if (i % 5 == 0 && i % 3 != 0) {
            sum += i;
            printf("%d ", i);   /* print qualifying numbers */
        }
    }

    printf("\n\nSum of numbers (divisible by 5, not by 3) from 1 to 100 = %d\n", sum);
    return 0;
}

Output

5 10 20 25 35 40 50 55 65 70 80 85 95 100

Sum of numbers (divisible by 5, not by 3) from 1 to 100 = 635

Note: Numbers like 15, 30, 45, 60, 75, 90 are excluded because they are divisible by both 5 and 3.

How is function declared? Why is function prototype necessary? Write recursive function segment that returns the sum of numbers from 1 to n given by the user.
2076 Chaitra [2+1+5]

How a Function is Declared

A function declaration (also called a prototype) tells the compiler the function's return type, name, and the types of its parameters — without the function body. It ends with a semicolon.

Syntax:  return_type function_name(parameter_type_list);

Examples:
int    add(int a, int b);         /* returns int, takes two ints */
float  average(float arr[], int n); /* returns float */
void   display(void);              /* no return, no parameters */
double power(double base, int exp);

/* Function Declaration vs Definition */
int add(int a, int b);          /* declaration (prototype) */

int add(int a, int b) {         /* definition (has body) */
    return a + b;
}

Why Function Prototype is Necessary

  • Forward Reference: Allows calling a function before its definition appears in the file. Without a prototype, the compiler doesn't know the function exists.
  • Type Checking: The compiler verifies that the correct number and types of arguments are passed, catching type mismatches at compile time.
  • Return Type Enforcement: Without a prototype, the compiler assumes int return type by default, which can cause errors for functions returning other types.
  • Better Error Messages: The compiler can provide meaningful error messages when calls don't match the prototype.
  • Multi-file Projects: In large projects, header files contain prototypes so other source files can use functions defined elsewhere.

Recursive Function – Sum of 1 to n

#include <stdio.h>

/* Function prototype */
int sumRecursive(int n);

int main() {
    int n, result;
    printf("Enter a positive integer n: ");
    scanf("%d", &n);

    if (n < 1) {
        printf("Please enter a positive integer.\n");
        return 1;
    }

    result = sumRecursive(n);
    printf("Sum of numbers from 1 to %d = %d\n", n, result);
    return 0;
}

/* Recursive function: sum of 1 to n */
int sumRecursive(int n) {
    if (n == 1)
        return 1;           /* base case */
    return n + sumRecursive(n - 1);   /* recursive case */
}

Output

Enter a positive integer n: 5
Sum of numbers from 1 to 5 = 15

Enter a positive integer n: 10
Sum of numbers from 1 to 10 = 55

Recursive Trace for n = 5

sumRecursive(5)
  = 5 + sumRecursive(4)
      = 4 + sumRecursive(3)
          = 3 + sumRecursive(2)
              = 2 + sumRecursive(1)
                  = 1              ← base case
              = 2 + 1 = 3
          = 3 + 3 = 6
      = 4 + 6 = 10
  = 5 + 10 = 15  ✓
How can you pass one dimensional array to function and what does name of an array in function call represents? Write a program to find the largest and smallest element of an array using a single function and display the result in calling function.
2076 Chaitra [3+5]

Passing 1D Array to a Function

In C, a 1D array is passed to a function by passing the name of the array, which acts as a pointer to its first element. The size must also be passed separately since the function doesn't know the array's size on its own.

/* Method 1: Using array notation */
void display(int arr[], int n) { ... }

/* Method 2: Using pointer notation (equivalent) */
void display(int *arr, int n) { ... }

/* Calling the function */
int marks[5] = {90, 85, 78, 92, 88};
display(marks, 5);   /* 'marks' is passed — no & needed */

What does the Array Name Represent in a Function Call?

The name of an array in a function call represents the address of the first element of the array (i.e., &arr[0]). It is a constant pointer. This means:

  • The function receives the base address, not a copy of the array.
  • Any changes made to array elements inside the function affect the original array (pass by reference effect).
  • display(marks, 5) is equivalent to display(&marks[0], 5).

C Program – Find Largest and Smallest Using a Single Function

#include <stdio.h>

/* Single function to find both largest and smallest */
/* Results returned via pointer parameters */
void findLargestSmallest(int arr[], int n, int *largest, int *smallest) {
    int i;
    *largest  = arr[0];
    *smallest = arr[0];

    for (i = 1; i < n; i++) {
        if (arr[i] > *largest)
            *largest = arr[i];
        if (arr[i] < *smallest)
            *smallest = arr[i];
    }
}

int main() {
    int arr[100], n, largest, smallest;
    int i;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    /* Pass array to function */
    findLargestSmallest(arr, n, &largest, &smallest);

    /* Display result in calling (main) function */
    printf("\nArray elements: ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);

    printf("\nLargest  element = %d\n", largest);
    printf("Smallest element = %d\n", smallest);

    return 0;
}

Output

Enter number of elements: 6
Enter 6 elements:
45 12 78 34 90 5

Array elements: 45 12 78 34 90 5
Largest  element = 90
Smallest element = 5
Explain how a structure can be defined and structure variables can be declared in C. Write a program that reads name, roll numbers, program and marks obtained in five subjects by students until the user enters 'e' and display the student detail and total marks obtained by each student.
2076 Chaitra [3+5]

Defining a Structure and Declaring Structure Variables

A structure is a user-defined data type that groups variables of different types under a single name using the struct keyword.

/* Syntax: Structure Definition */
struct structure_name {
    data_type member1;
    data_type member2;
    ...
};

/* Method 1: Declare variable separately */
struct Point {
    int x;
    int y;
};
struct Point p1, p2;   /* variable declaration */

/* Method 2: Declare at definition */
struct Rectangle {
    float length;
    float width;
} r1, r2;

/* Method 3: Using typedef for convenience */
typedef struct {
    char name[50];
    int age;
} Person;
Person p;   /* no 'struct' keyword needed */

/* Accessing members using dot operator */
p1.x = 10;
p1.y = 20;
p.age = 25;

C Program – Student Records Until User Enters 'e'

#include <stdio.h>
#include <string.h>

#define MAX 100
#define SUBJECTS 5

struct Student {
    char name[50];
    int  rollNo;
    char program[30];
    float marks[SUBJECTS];
    float total;
};

int main() {
    struct Student s[MAX];
    int count = 0, i, j;
    char choice;

    printf("=== Student Record Entry ===\n");
    printf("Press 'e' to stop entering records.\n\n");

    while (1) {
        printf("Enter details for Student %d:\n", count + 1);

        printf("  Name    : ");
        scanf(" %[^\n]", s[count].name);

        /* Check if user wants to exit */
        if (strcmp(s[count].name, "e") == 0 || strcmp(s[count].name, "E") == 0)
            break;

        printf("  Roll No : ");
        scanf("%d", &s[count].rollNo);

        printf("  Program : ");
        scanf(" %[^\n]", s[count].program);

        s[count].total = 0;
        for (j = 0; j < SUBJECTS; j++) {
            printf("  Marks in Subject %d: ", j + 1);
            scanf("%f", &s[count].marks[j]);
            s[count].total += s[count].marks[j];
        }

        count++;

        printf("Press 'e' then Enter to stop, or press Enter to continue: ");
        scanf(" %c", &choice);
        if (choice == 'e' || choice == 'E')
            break;

        printf("\n");
    }

    /* Display all student details */
    printf("\n============================================================\n");
    printf("                   STUDENT DETAILS                         \n");
    printf("============================================================\n");
    printf("%-4s %-15s %-6s %-12s %-6s %-6s %-6s %-6s %-6s %-8s\n",
           "No.", "Name", "Roll", "Program",
           "S1", "S2", "S3", "S4", "S5", "Total");
    printf("------------------------------------------------------------\n");

    for (i = 0; i < count; i++) {
        printf("%-4d %-15s %-6d %-12s ",
               i+1, s[i].name, s[i].rollNo, s[i].program);
        for (j = 0; j < SUBJECTS; j++)
            printf("%-6.1f ", s[i].marks[j]);
        printf("%-8.1f\n", s[i].total);
    }
    printf("============================================================\n");
    printf("Total students entered: %d\n", count);

    return 0;
}

Sample Output

============================================================
                   STUDENT DETAILS
============================================================
No.  Name            Roll   Program      S1     S2     S3     S4     S5     Total
------------------------------------------------------------
1    Ram Sharma      101    BCE          78.0   85.0   90.0   72.0   88.0   413.0
2    Sita Rai        102    BCT          92.0   76.0   81.0   89.0   95.0   433.0
============================================================
Total students entered: 2
What is pointer? Discuss its relationship with an array. Write a function program that behaves strcpy() function using pointer as argument.
2076 Chaitra [1+2+5]

What is a Pointer?

A pointer is a variable that stores the memory address of another variable rather than a direct value. Pointers enable dynamic memory allocation, efficient array manipulation, and passing variables by reference.

Syntax:  data_type *pointer_name;

int   x   = 10;
int  *ptr  = &x;    /* ptr holds address of x */

printf("%d\n",  x);     /* prints value: 10      */
printf("%p\n", ptr);    /* prints address of x   */
printf("%d\n", *ptr);   /* dereference: prints 10 */

*ptr = 25;              /* changes x to 25 via pointer */

Relationship Between Pointer and Array

In C, an array name is a constant pointer to its first element. Array subscript notation and pointer arithmetic are interchangeable.

Array NotationPointer NotationMeaning
arr&arr[0]Address of first element
arr[i]*(arr + i)Value at index i
&arr[i]arr + iAddress of element i
*arrarr[0]First element's value
int arr[4] = {10, 20, 30, 40};
int *ptr = arr;

/* Both notations are equivalent */
printf("%d\n", arr[2]);        /* 30 */
printf("%d\n", *(ptr + 2));    /* 30 */
printf("%d\n", *(arr + 2));    /* 30 */
printf("%d\n", ptr[2]);        /* 30 */

/* Difference: pointer can be incremented, array name cannot */
ptr++;     /* valid: ptr now points to arr[1] */
/* arr++; is ILLEGAL — arr is a constant pointer */

Custom strcpy() Using Pointers

#include <stdio.h>

/* Custom strcpy using pointer arguments */
void myStrcpy(char *dest, const char *src) {
    /* Copy each character from src to dest until null terminator */
    while (*src != '\0') {
        *dest = *src;   /* copy character */
        dest++;         /* advance destination pointer */
        src++;          /* advance source pointer */
    }
    *dest = '\0';       /* append null terminator to destination */
}

int main() {
    char source[100], destination[100];

    printf("Enter source string: ");
    scanf(" %[^\n]", source);

    /* Before copy */
    printf("\nBefore myStrcpy:\n");
    printf("  source      = \"%s\"\n", source);
    printf("  destination = \"%s\" (empty)\n", destination);

    myStrcpy(destination, source);

    /* After copy */
    printf("\nAfter myStrcpy:\n");
    printf("  source      = \"%s\"\n", source);
    printf("  destination = \"%s\"\n", destination);

    return 0;
}

Output

Enter source string: Hello Nepal

Before myStrcpy:
  source      = "Hello Nepal"
  destination = "" (empty)

After myStrcpy:
  source      = "Hello Nepal"
  destination = "Hello Nepal"

Pointer-by-Pointer Trace for "Hi"

Step*src*destAction
1'H''H'Copy 'H', advance both
2'i''i'Copy 'i', advance both
3'\0'Exit loop, write '\0' to dest
Explain different modes in opening file. Write a program to read a string, write it into a file and display the content of the file into a screen.
2076 Chaitra [4+4]

File Opening Modes in C

The fopen() function is used to open a file. It takes the filename and a mode string as arguments and returns a FILE * pointer (or NULL on failure).

Syntax:  FILE *fp = fopen("filename", "mode");
ModeDescriptionFile Exists?File Missing?
"r"Open for reading onlyOpens normallyReturns NULL
"w"Open for writing only (truncates/creates)Truncated (emptied)New file created
"a"Open for appending (writes at end)Appends at endNew file created
"r+"Open for reading and writingOpens normallyReturns NULL
"w+"Open for reading and writing (truncates/creates)TruncatedNew file created
"a+"Open for reading and appendingAppends at endNew file created
"rb"Open binary file for readingOpens normallyReturns NULL
"wb"Open binary file for writingTruncatedNew file created
"ab"Open binary file for appendingAppendsNew file created

C Program – Read String, Write to File, Display File Content

#include <stdio.h>
#include <string.h>

int main() {
    char str[500];
    char filename[] = "output.txt";
    FILE *fp;
    char ch;

    /* Step 1: Read a string from user */
    printf("Enter a string to write to file:\n");
    scanf(" %[^\n]", str);

    /* Step 2: Write the string to the file */
    fp = fopen(filename, "w");   /* open in write mode */
    if (fp == NULL) {
        printf("Error: Cannot create file '%s'\n", filename);
        return 1;
    }
    fprintf(fp, "%s\n", str);   /* write string to file */
    fclose(fp);
    printf("\nString successfully written to '%s'.\n", filename);

    /* Step 3: Read the file and display its content */
    fp = fopen(filename, "r");   /* open in read mode */
    if (fp == NULL) {
        printf("Error: Cannot open file '%s'\n", filename);
        return 1;
    }

    printf("\nContent of '%s':\n", filename);
    printf("-----------------------------\n");
    while ((ch = fgetc(fp)) != EOF)
        putchar(ch);            /* print each character to screen */
    printf("-----------------------------\n");

    fclose(fp);
    return 0;
}

Output

Enter a string to write to file:
Hello! This is Computer Programming CT401.

String successfully written to 'output.txt'.

Content of 'output.txt':
-----------------------------
Hello! This is Computer Programming CT401.
-----------------------------

Key Functions Used

FunctionPurpose
fopen(name, mode)Opens a file in the given mode; returns FILE pointer
fprintf(fp, format, ...)Writes formatted data to the file
fgetc(fp)Reads one character from the file
fclose(fp)Closes the file and flushes the buffer
EOFEnd-of-file marker returned by fgetc when file ends
Explain different data types available in FORTRAN. Write a program in FORTRAN to check whether a number given by user is palindrome or not.
2076 Chaitra [2+6]

Data Types in FORTRAN

Data TypeKeywordSizeDescriptionExample
Integer INTEGER 4 bytes (default) Stores whole numbers (positive, negative, zero). No decimal point. INTEGER N; N = 100
Real REAL 4 bytes Single-precision floating-point number. About 6–7 significant digits. REAL X; X = 3.14
Double Precision DOUBLE PRECISION 8 bytes Double-precision floating-point. About 15–16 significant digits. More accurate than REAL. DOUBLE PRECISION PI; PI = 3.14159265358979D0
Complex COMPLEX 8 bytes Stores complex numbers with real and imaginary parts. COMPLEX Z; Z = (3.0, 4.0) — represents 3+4i
Logical LOGICAL 4 bytes Stores Boolean values: .TRUE. or .FALSE. LOGICAL FLAG; FLAG = .TRUE.
Character CHARACTER 1 byte per char Stores strings/characters. Length specified with *n. CHARACTER*20 NAME; NAME = 'Ram Sharma'
C     FORTRAN Data Type Declaration Examples:
      INTEGER      COUNT, I, J, N
      REAL         TEMP, RATE, AREA
      DOUBLE PRECISION   RESULT, PI
      COMPLEX      Z1, Z2
      LOGICAL      FLAG, FOUND
      CHARACTER*30 FNAME, LNAME
      CHARACTER*1  GRADE

FORTRAN Program – Palindrome Check for a Number

      PROGRAM PALINDROME
C     Check if a number entered by user is palindrome

      INTEGER N, ORIG, REV, DIGIT

      WRITE(*,*) 'Enter a positive integer:'
      READ(*,*)  N

      ORIG = N
      REV  = 0

C     Reverse the number
   10 IF (N .GT. 0) THEN
          DIGIT = MOD(N, 10)
          REV   = REV * 10 + DIGIT
          N     = N / 10
          GO TO 10
      END IF

C     Compare original with reversed
      IF (ORIG .EQ. REV) THEN
          WRITE(*,*) ORIG, ' is a PALINDROME.'
      ELSE
          WRITE(*,*) ORIG, ' is NOT a palindrome.'
      END IF

      STOP
      END

Output

Enter a positive integer:
12321
12321 is a PALINDROME.

Enter a positive integer:
1234
1234 is NOT a palindrome.

Logic Trace for N = 121

IterationNDIGIT (N mod 10)REV
112111
212212
311121
40stop

ORIG = 121 = REV = 121 → PALINDROME

Set 11 | 076 Ashwin | Back

Computer Programming [CT401]

Set 12 | 0775 Chaitra | Regular/Back

Computer Programming [CT401]

CHAPTERWISE MOST REPEATED QUESTIONS WITH THEIR SOLUTIONS

Repeated ★ Very Repeated

Unit 1: Programming Languages & Problem Solving

Algorithm · Flowchart · Generations of Languages · Software Development Steps
Define instruction and program. Discuss different generations of programming languages.
★ Very Repeated 082 Shrawan · 078 Bhadra · 075 Ashwin · 074 Chaitra · 073 Shrawan · 072 Kartik · 071 Chaitra · 070 Chaitra [1+3] or [1+4]

Instruction

An instruction is a single operation command that directs the computer to perform a specific task (e.g., add two numbers, store a value in memory).

Program

A program is a finite, ordered set of instructions written in a programming language that directs the computer to solve a specific problem.

Generations of Programming Languages

GenerationNameExampleFeatures
1GLMachine Language0101 1001...Binary (0s & 1s); directly executed by CPU; machine-dependent; very fast but hard to write
2GLAssembly LanguageMOV AX, 5Mnemonic codes; needs assembler to convert; machine-dependent; faster than high-level
3GLHigh-Level LanguageC, FORTRAN, PascalHuman-readable; needs compiler/interpreter; machine-independent; portable
4GLVery High-Level LanguageSQL, MATLABDomain-specific; minimal code for complex tasks; used in databases and reports
5GLAI / Natural LanguageProlog, LISPBased on logic/constraints; used in AI and expert systems
Explain the importance of problem analysis in software development. Write an algorithm and draw a flowchart to test whether a number is even or not.
★ Very Repeated 082 Shrawan · 075 Ashwin · 075 Chaitra · 068 Chaitra [1+3]

Importance of Problem Analysis

  • Clearly defines the problem to be solved, avoiding ambiguity
  • Identifies required inputs, outputs, and constraints before coding
  • Reduces development time and cost by catching issues early
  • Serves as the foundation for algorithm design
  • Prevents misunderstanding between developers and clients

Algorithm – Check Even or Odd

1 START
2 INPUT a number N
3 IF (N mod 2 == 0) THEN
     PRINT "N is EVEN"
4 ELSE
     PRINT "N is ODD"
5 END IF
6 STOP

Flowchart

[START]

[INPUT N]

◇ N % 2 == 0 ?
↙ YES        NO ↘
[Print EVEN]    [Print ODD]
↘               ↙
[STOP]
In flowcharts: Oval = Start/Stop, Parallelogram = I/O, Rectangle = Process, Diamond = Decision
What are the basic steps needed to develop a software / solve a problem using a computer?
★ Repeated 081 Bhadra · 080 Baishakh · 079 Bhadra · 078 Bhadra · 070 Ashad · 069 Ashad [4] or [2+4]

Steps to Solve a Problem Using Computer

  1. Problem Analysis: Understand the problem, identify inputs, outputs, and constraints
  2. Algorithm Design: Design a step-by-step solution (algorithm or flowchart)
  3. Coding: Write the program in a suitable programming language
  4. Compilation: Convert source code to machine code using a compiler
  5. Testing & Debugging: Run the program with test data; find and fix errors (bugs)
  6. Documentation: Write user manuals, comments, and technical docs
  7. Maintenance: Update and improve the program over time
Remember as: PA → AD → C → C → T&D → D → M
Differentiate between system software and application software.
★ Very Repeated 082 Baishakh · 081 Bhadra · 080 Baishakh · 079 Bhadra · 078 Bhadra [2] or [4]
BasisSystem SoftwareApplication Software
DefinitionManages hardware and provides platform for other softwarePerforms specific tasks for end-users
ExamplesOS (Windows, Linux), Device Drivers, CompilersMS Word, Photoshop, Games, Web Browser
PurposeControls computer resourcesSolves user problems
User InteractionRuns in background, minimal direct interactionDirectly used by end-users
DependencyCan run without application softwareDepends on system software to run
LanguageWritten in low-level/system languages (C, Assembly)Written in high-level languages
What is an algorithm? What are the advantages of flowchart design? Write algorithm and flowchart to find sum of first N natural numbers.
★ Repeated 082 Baishakh · 076 Ashwin · 073 Chaitra · 068 Shrawan [2+2] or [2+3+3]

Algorithm Definition

An algorithm is a finite, ordered, and unambiguous set of instructions designed to solve a specific problem in a finite amount of time and resources.

Properties of a Good Algorithm: Finite, Definite, Input, Output, Effective

Advantages of Flowchart

  • Provides a visual representation – easier to understand
  • Helps identify logic errors before coding
  • Serves as documentation for future reference
  • Simplifies communication between team members
  • Makes debugging and modification easier

Algorithm – Sum of First N Natural Numbers

1 START
2 INPUT N
3 SET sum = 0, i = 1
4 WHILE i <= N DO
    sum = sum + i
    i = i + 1
5 END WHILE
6 PRINT sum
7 STOP

Flowchart

[START] → [INPUT N] → [sum=0, i=1]

◇ i <= N ?
YES → [sum = sum+i] → [i = i+1] → (back to diamond)
NO ↓
[PRINT sum] → [STOP]
Explain compilation process in C (steps from source code to executable).
081 Baishakh · 080 Baishakh · 075 Chaitra · 074 Chaitra · 073 Shrawan · 069 Chaitra [4]

Compilation Process in C

Source Code (.c file)
   ↓ Preprocessor – handles #include, #define, macros
Expanded Source Code
   ↓ Compiler – checks syntax, converts to assembly
Assembly Code (.asm / .s)
   ↓ Assembler – converts to machine code
Object Code (.obj / .o)
   ↓ Linker – links object files + library files
Executable File (.exe)
  • Preprocessor: Processes directives (#include, #define). Replaces macros. Removes comments.
  • Compiler: Checks syntax errors. Converts C code to Assembly language.
  • Assembler: Converts assembly to binary object code (machine code).
  • Linker: Combines object files with library files (like stdio.h implementations) to create the final executable.
Define testing and debugging. / Discuss types of errors in programming.
082 Baishakh · 078 Kartik · 076 Chaitra · 074 Chaitra · 073 Shrawan [2] or [2+4]

Testing

Testing is the process of running a program with various input data to check whether the output is correct and the program behaves as expected.

Debugging

Debugging is the process of identifying, locating, and fixing errors (bugs) in a program.

Types of Errors

Error TypeDescriptionExample
Syntax ErrorViolation of language grammar rules; detected by compilerMissing semicolon, wrong keyword
Runtime ErrorOccurs during execution; causes program to crashDivision by zero, null pointer
Logical ErrorProgram runs but gives wrong output; hardest to findUsing + instead of *, wrong condition
Semantic ErrorSyntactically correct but wrong meaningint age = "twenty";

Unit 2: C Basics – Data Types, Operators & I/O

Expressions · Formatted/Unformatted I/O · Precedence & Associativity · Keywords
What is an expression? What are the types of expressions in C?
★ Repeated 082 Shrawan · 075 Chaitra · 072 Chaitra [2+2]

Expression

An expression is a combination of operands (variables, constants) and operators that evaluates to a single value. Every expression has a type and a value.

Types of Expressions

TypeDescriptionExample
ArithmeticProduces a numeric valuea + b * c
RelationalCompares two values; produces 0 or 1a > b, x == y
LogicalCombines boolean conditionsa && b, !x
AssignmentAssigns value to a variablex = 5, a += 3
Conditional (Ternary)Selects value based on conditiona > b ? a : b
BitwiseOperates on individual bitsa & b, x | y
CommaEvaluates multiple expressions left to right(a=5, b=10, a+b)
Explain input and output functions available in C with syntax and example (printf, scanf, getch, getche, getchar, gets, puts, putchar).
★ Very Repeated 082 Shrawan · 081 Bhadra · 078 Kartik · 076 Ashwin · 075 Ashwin · 074 Chaitra · 072 Chaitra · 068 Chaitra [2+2+2] or [4+4]

Formatted I/O Functions

FunctionSyntaxDescription
printf()printf("format", vars);Formatted output to screen. Supports %d, %f, %s, %c etc.
scanf()scanf("format", &vars);Reads formatted input. Uses & for non-string variables.

Unformatted I/O Functions

FunctionSyntaxDescription
getch()ch = getch();Reads single char; no echo; no Enter needed. (conio.h)
getche()ch = getche();Reads single char; echoes it; no Enter needed. (conio.h)
getchar()ch = getchar();Reads single char; echoes; waits for Enter. (stdio.h)
putchar()putchar(ch);Prints a single character to screen.
gets()gets(str);Reads a full string including spaces until Enter. (deprecated)
puts()puts(str);Prints string and adds newline automatically.

Example

#include <stdio.h>
int main() {
    int age;
    char name[50];
    printf("Enter name: ");
    scanf("%s", name);      // reads one word
    printf("Enter age: ");
    scanf("%d", &age);
    printf("Name: %s, Age: %d\n", name, age);
    return 0;
}
Define precedence and associativity of operators with examples.
★ Repeated 082 Baishakh · 080 Bhadra · 072 Kartik [2] or [3]

Operator Precedence

Operator precedence determines the order in which operators are evaluated in an expression when multiple operators are present.

Example: In 2 + 3 * 4, multiplication has higher precedence than addition, so result = 2 + 12 = 14 (not 20).

Operator Associativity

Associativity determines the order of evaluation when two operators of the same precedence appear in an expression.

  • Left-to-Right: Most operators (+, -, *, /) — evaluated left first: 8 - 3 - 2 = (8-3)-2 = 3
  • Right-to-Left: Assignment (=), unary operators — a = b = 5a = (b = 5)

Precedence Table (High to Low)

PrecedenceOperatorsAssociativity
1 (Highest)() [] . ->Left to Right
2! ~ ++ -- (unary) * &Right to Left
3* / %Left to Right
4+ -Left to Right
5< <= > >=Left to Right
6== !=Left to Right
7&&Left to Right
8||Left to Right
9 (Lowest)= += -= *= /=Right to Left
Differentiate between formatted and unformatted input/output in C.
★ Repeated 082 Baishakh · 078 Bhadra · 076 Ashwin · 072 Kartik · 069 Chaitra [4]
BasisFormatted I/OUnformatted I/O
DefinitionInput/output with specific format specifiersInput/output without format specifiers
Functionsprintf(), scanf(), fprintf(), fscanf()getch(), getche(), getchar(), gets(), puts(), putchar()
Data TypesCan handle int, float, char, string with %d, %f, %c, %sMainly handles single characters or strings
ControlFull control over format, width, precisionNo format control
Headerstdio.hstdio.h, conio.h
Exampleprintf("%5.2f", x);ch = getch();
printf() with %5.2f means: minimum width 5, 2 decimal places for float.

Unit 3: Control Statements & Loops

if-else · Nested if · else-if ladder · switch · while · do-while · for · break · continue
Compare nested if with else-if ladder structure along with their flowcharts.
★ Repeated 082 Shrawan · 081 Bhadra (else-if vs switch) · 080 Bhadra · 075 Chaitra · 068 Chaitra [4]
BasisNested ifelse-if Ladder
Structureif inside another if; forms tree structureif followed by multiple else-if; linear chain
UseFor multi-level conditions depending on each otherFor mutually exclusive conditions (one OR another)
ReadabilityBecomes complex with deep nestingMore readable for multiple choices

Nested if Example

if (a > 0) {
    if (a % 2 == 0)
        printf("Positive Even");
    else
        printf("Positive Odd");
} else {
    printf("Negative");
}

else-if Ladder Example

if (marks >= 90)      printf("A+");
else if (marks >= 80) printf("A");
else if (marks >= 70) printf("B");
else if (marks >= 60) printf("C");
else                   printf("Fail");

Flowcharts

Nested if:
◇ Condition 1? → YES → ◇ Condition 2? → YES → [Action A]
                                  → NO → [Action B]
→ NO → [Action C]

else-if Ladder:
◇ Cond 1? → YES → [Action 1]
NO ↓
◇ Cond 2? → YES → [Action 2]
NO ↓
[Default Action]
Write a program to check whether a number entered by the user is prime or composite.
★ Very Repeated 082 Shrawan · 082 Baishakh · 081 Bhadra · 080 Baishakh · 079 Bhadra · 075 Ashwin · 074 Ashwin [4] or [5]
#include <stdio.h>
int main() {
    int n, i, isPrime = 1;
    printf("Enter a number: ");
    scanf("%d", &n);

    if (n <= 1) {
        isPrime = 0;  // 0 and 1 are not prime
    } else {
        for (i = 2; i * i <= n; i++) {
            if (n % i == 0) {
                isPrime = 0;
                break;
            }
        }
    }

    if (isPrime)
        printf("%d is PRIME\n", n);
    else
        printf("%d is COMPOSITE\n", n);

    return 0;
}
We check divisors only up to √n because if n has a factor greater than √n, the other factor must be less than √n.
Write an algorithm / program to check whether a number is Armstrong or not. [Hint: 1634 = 1⁴+6⁴+3⁴+4⁴]
081 Bhadra · 075 Ashwin · 073 Shrawan · 071 Chaitra [2+2+2] or [5]

An Armstrong number (Narcissistic number) is a number where the sum of each digit raised to the power of the total number of digits equals the number itself. E.g., 153 = 1³+5³+3³ = 153.

#include <stdio.h>
#include <math.h>
int main() {
    int n, temp, digit, digits = 0, sum = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    temp = n;
    // Count digits
    while (temp != 0) { digits++; temp /= 10; }
    temp = n;
    // Sum of (each digit)^digits
    while (temp != 0) {
        digit = temp % 10;
        sum += (int)pow(digit, digits);
        temp /= 10;
    }
    if (sum == n)
        printf("%d is an Armstrong number\n", n);
    else
        printf("%d is NOT an Armstrong number\n", n);
    return 0;
}
Explain break and continue statements with example. / Compare while and do-while loop.
★ Repeated 081 Bhadra · 079 Bhadra · 078 Bhadra · 078 Kartik · 072 Kartik · 071 Shawan [2] or [3+7]

break Statement

Immediately exits the loop or switch statement. Program continues after the loop.

for (i=1; i<=10; i++) {
    if (i == 5) break;   // exits when i=5
    printf("%d ", i);    // prints 1 2 3 4
}

continue Statement

Skips the rest of the current loop iteration and moves to the next iteration.

for (i=1; i<=5; i++) {
    if (i == 3) continue; // skips i=3
    printf("%d ", i);     // prints 1 2 4 5
}

while vs do-while

whiledo-while
Entry-controlled loopExit-controlled loop
Condition checked before executionCondition checked after execution
Body may execute 0 timesBody executes at least once
while (cond) { body; }do { body; } while (cond);

Unit 4: Functions & Recursion

Call by Value · Call by Reference · Recursive Functions · Function Prototyping
What do you mean by "call by value" and "call by reference"? Explain with suitable example.
★ Most Repeated 082 Shrawan · 081 Baishakh · 075 Ashwin · 075 Chaitra · 074 Ashwin · 073 Chaitra · 072 Chaitra · 071 Shawan · 071 Chaitra · 070 Chaitra · 069 Ashad · 068 Chaitra · 067 Ashadh [4] or [6]
BasisCall by ValueCall by Reference
What is passedCopy of the actual valueAddress (reference) of the variable
Effect on originalOriginal variable NOT changedOriginal variable IS changed
HowNormal parametersPointer parameters (using & and *)
MemoryExtra memory for copyNo extra memory (uses same location)

Call by Value Example

void change(int x) {
    x = 100;  // only local copy is changed
}
int main() {
    int a = 10;
    change(a);
    printf("%d", a);  // Output: 10 (unchanged)
    return 0;
}

Call by Reference Example (swap)

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}
int main() {
    int a = 5, b = 10;
    swap(&a, &b);
    printf("a=%d b=%d", a, b);  // Output: a=10 b=5
    return 0;
}
Write a program to display factorial of an integer entered by the user using recursive function.
★ Very Repeated 082 Shrawan · 081 Baishakh (algorithm+flowchart) · 080 Baishakh · 079 Bhadra · 078 Bhadra [4] or [6]
#include <stdio.h>

long long factorial(int n) {
    if (n == 0 || n == 1)   // base case
        return 1;
    return n * factorial(n - 1);  // recursive call
}

int main() {
    int n;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    printf("Factorial of %d = %lld\n", n, factorial(n));
    return 0;
}
Trace: factorial(4) = 4×factorial(3) = 4×3×factorial(2) = 4×3×2×factorial(1) = 4×3×2×1 = 24
Write a program to display nth term of a Fibonacci sequence using recursive function.
★ Repeated 082 Baishakh · 081 Baishakh · 080 Baishakh · 078 Bhadra · 075 Chaitra · 073 Chaitra [6]
#include <stdio.h>

int fib(int n) {
    if (n == 0) return 0;    // base case
    if (n == 1) return 1;    // base case
    return fib(n-1) + fib(n-2);  // recursive case
}

int main() {
    int n;
    printf("Enter n: ");
    scanf("%d", &n);
    printf("Fibonacci(%d) = %d\n", n, fib(n));
    /* To print full series: */
    printf("Series: ");
    for(int i=0; i<=n; i++)
        printf("%d ", fib(i));
    return 0;
}
Series: 0 1 1 2 3 5 8 13 21 34 ...
Explain function prototyping. / Define functions and classify them. List advantages of using functions.
082 Baishakh · 081 Bhadra · 080 Baishakh · 080 Bhadra · 078 Bhadra · 076 Chaitra · 073 Shrawan [2] or [2+5]

Function Prototype (Declaration)

A function prototype declares the function's name, return type, and parameter types to the compiler before the function is actually defined (used). This allows calling the function before its definition.

/* Syntax */
return_type function_name(parameter_type_list);

/* Example */
int add(int, int);     // prototype

int main() {
    printf("%d", add(3,4));  // called before definition
}

int add(int a, int b) {  // definition
    return a + b;
}

Classification of Functions

  • Library Functions: Pre-defined in C libraries (printf, scanf, sqrt)
  • User-defined Functions: Written by programmer for specific tasks

Advantages of Using Functions

  • Avoids code repetition (reusability)
  • Makes programs modular and easier to manage
  • Easier debugging – test each function independently
  • Improves readability and maintainability
  • Enables team programming (divide tasks)

Unit 5: Arrays & Strings

1D Array · 2D Array · Matrix Operations · String Functions · String without Library Functions
Write a program to reverse a string without using string handling function.
★ Repeated 082 Shrawan · 082 Baishakh · 081 Bhadra · 075 Chaitra · 074 Chaitra · 071 Chaitra [4]
#include <stdio.h>

int main() {
    char str[100];
    int i, len = 0;
    printf("Enter a string: ");
    gets(str);

    // Find length manually
    while (str[len] != '\0') len++;

    // Print in reverse
    printf("Reversed: ");
    for (i = len - 1; i >= 0; i--)
        printf("%c", str[i]);
    printf("\n");

    return 0;
}
The question asks WITHOUT string functions (no strlen, strrev). We manually find length and print backwards.
Write a program to display the largest and smallest number among 10 numbers entered by the user.
★ Repeated 082 Shrawan · 076 Chaitra · 075 Chaitra · 074 Ashwin · 073 Shrawan [6]
#include <stdio.h>
int main() {
    int a[10], i, max, min;
    printf("Enter 10 numbers:\n");
    for (i = 0; i < 10; i++)
        scanf("%d", &a[i]);

    max = min = a[0];
    for (i = 1; i < 10; i++) {
        if (a[i] > max) max = a[i];
        if (a[i] < min) min = a[i];
    }
    printf("Largest  = %d\n", max);
    printf("Smallest = %d\n", min);
    return 0;
}
Write a program to calculate the length of a string without using string handling (library) function.
★ Repeated 082 Baishakh · 081 Bhadra · 080 Baishakh · 075 Ashwin · 074 Chaitra [4] or [3]
#include <stdio.h>
int main() {
    char str[100];
    int len = 0;
    printf("Enter string: ");
    gets(str);
    while (str[len] != '\0')
        len++;
    printf("Length = %d\n", len);
    return 0;
}
Write a program to display the transpose of a matrix.
★ Repeated 082 Baishakh · 081 Baishakh · 080 Baishakh · 079 Bhadra · 076 Ashwin · 074 Chaitra · 073 Chaitra [2+4] or [5]
#include <stdio.h>
int main() {
    int m, n, i, j, a[10][10];
    printf("Enter rows and columns: ");
    scanf("%d %d", &m, &n);
    printf("Enter matrix elements:\n");
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &a[i][j]);

    printf("Transpose:\n");
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++)
            printf("%d\t", a[j][i]);  // note: a[j][i]
        printf("\n");
    }
    return 0;
}
Transpose swaps rows and columns: element at [i][j] goes to [j][i].

Unit 6: Structures

Defining Structures · Nested Structures · Array of Structures · Passing Structures to Functions
What is structure? Why is it necessary? Write a program to add two distances given in feet and inch format using structure.
★ Very Repeated 082 Shrawan · 075 Ashwin · 074 Ashwin (complex number) · 073 Chaitra · 072 Chaitra · 071 Shawan [1+1+6] or [2+6]

Structure Definition

A structure is a user-defined data type in C that allows grouping of different data types under a single name. Unlike arrays (which store same-type elements), structures can store elements of different types.

Why Necessary?

  • Groups related data of different types together (e.g., student: name, roll, marks)
  • Makes code more organized and readable
  • Allows passing multiple related items as a single unit to functions
  • Represents real-world entities naturally

Program – Add Two Distances (feet and inches)

#include <stdio.h>

struct Distance {
    int feet;
    float inch;
};

int main() {
    struct Distance d1, d2, sum;

    printf("Enter d1 (feet inch): ");
    scanf("%d %f", &d1.feet, &d1.inch);
    printf("Enter d2 (feet inch): ");
    scanf("%d %f", &d2.feet, &d2.inch);

    sum.feet = d1.feet + d2.feet;
    sum.inch = d1.inch + d2.inch;

    // Carry over excess inches
    if (sum.inch >= 12.0) {
        sum.feet += 1;
        sum.inch -= 12.0;
    }
    printf("Sum = %d feet %.2f inches\n", sum.feet, sum.inch);
    return 0;
}
Define nested structure. Write a program using nested structure (student name, roll, marks, address in order of marks).
082 Baishakh · 081 Bhadra · 080 Bhadra · 079 Bhadra · 078 Bhadra · 072 Chaitra [2+6] or [3+5]

Nested Structure

A nested structure is a structure that contains another structure as one of its members. It allows modeling complex hierarchical data relationships.

#include <stdio.h>
#include <string.h>

struct Address {
    char city[50];
    char district[50];
};

struct Student {
    char name[50];
    int roll;
    float marks;
    struct Address addr;  // nested structure
};

int main() {
    int n, i, j;
    printf("Enter number of students: ");
    scanf("%d", &n);
    struct Student s[n];

    for (i = 0; i < n; i++) {
        printf("Name: "); scanf("%s", s[i].name);
        printf("Roll: "); scanf("%d", &s[i].roll);
        printf("Marks: "); scanf("%f", &s[i].marks);
        printf("City: "); scanf("%s", s[i].addr.city);
    }

    // Bubble sort by marks (descending)
    struct Student temp;
    for (i = 0; i < n-1; i++) {
        for (j = 0; j < n-i-1; j++) {
            if (s[j].marks < s[j+1].marks) {
                temp = s[j]; s[j] = s[j+1]; s[j+1] = temp;
            }
        }
    }

    printf("\nStudents in order of marks:\n");
    for (i = 0; i < n; i++)
        printf("%s\t%d\t%.2f\t%s\n", s[i].name, s[i].roll, s[i].marks, s[i].addr.city);
    return 0;
}

Unit 7: Pointers

Pointer Arithmetic · Pointer and Array Relation · Pointers to Functions
Explain pointer arithmetic with suitable example.
★ Very Repeated 082 Shrawan · 082 Baishakh · 081 Bhadra · 080 Baishakh · 080 Bhadra · 079 Bhadra · 075 Chaitra · 072 Chaitra · 070 Chaitra · 069 Ashad [4] or [2+3]

Pointer Arithmetic

Pointer arithmetic allows performing mathematical operations on pointers. The operations are scaled by the size of the data type being pointed to.

OperationDescription
ptr++Moves pointer to next element (adds sizeof(type) bytes)
ptr--Moves pointer to previous element
ptr + nPoints to nth element ahead
ptr2 - ptr1Number of elements between two pointers
*ptrDereference: access the value at pointer address
#include <stdio.h>
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *ptr = arr;   // ptr points to arr[0]

    printf("*ptr     = %d\n", *ptr);       // 10
    ptr++;
    printf("After ++ = %d\n", *ptr);       // 20
    printf("ptr+2    = %d\n", *(ptr+2));   // 40

    // If int is 4 bytes: address increases by 4 each step
    printf("Address: %u\n", (unsigned)ptr);
    printf("Next:    %u\n", (unsigned)(ptr+1));  // +4
    return 0;
}
Valid operations: ptr+n, ptr-n, ptr++, ptr--, ptr1-ptr2. NOT valid: ptr1+ptr2, ptr*n, ptr/n.
Write a program to display sum, difference, and product of two numbers using concept of pointer.
082 Shrawan [4]
#include <stdio.h>
int main() {
    int a, b, *p1, *p2;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    p1 = &a;  p2 = &b;
    printf("Sum        = %d\n", *p1 + *p2);
    printf("Difference = %d\n", *p1 - *p2);
    printf("Product    = %d\n", *p1 * *p2);
    return 0;
}

Unit 8: File Handling

Console I/O vs File I/O · Text vs Binary Files · fopen · fclose · fprintf · fscanf · fseek
Differentiate between console I/O and file I/O. A file "employee.txt" stores name, id, and salary. Write a program to display employees with salary > 50000.
★ Repeated 082 Shrawan · 075 Ashwin · 074 Ashwin · 073 Shrawan [2+6] or [8]

Console I/O vs File I/O

BasisConsole I/OFile I/O
MediumKeyboard (input) and Screen (output)Files on disk (permanent storage)
Functionsprintf(), scanf(), getch()fprintf(), fscanf(), fread(), fwrite()
PersistenceData lost when program endsData saved permanently
SpeedSlower (depends on user)Faster for large data
RequiresNo file opening/closingfopen() and fclose() required

Program

#include <stdio.h>
int main() {
    FILE *fp;
    char name[50];
    int id;
    float salary;

    fp = fopen("employee.txt", "r");
    if (fp == NULL) {
        printf("File not found!\n");
        return 1;
    }

    printf("Employees with salary > 50000:\n");
    while (fscanf(fp, "%s %d %f", name, &id, &salary) != EOF) {
        if (salary > 50000)
            printf("Name: %s, ID: %d, Salary: %.2f\n", name, id, salary);
    }
    fclose(fp);
    return 0;
}
File modes: "r"=read, "w"=write (creates/overwrites), "a"=append, "r+"=read+write
Differentiate between text file and binary file. Write a program to copy contents of "source.txt" to "destination.txt".
★ Repeated 082 Baishakh · 081 Bhadra · 080 Baishakh · 080 Bhadra · 079 Bhadra · 074 Chaitra [2+6] or [3+3]
BasisText FileBinary File
StorageStores data as readable ASCII charactersStores data in binary (0s and 1s)
ReadabilityCan be opened in any text editorNot human-readable; looks like garbage
SizeUsually largerSmaller, more efficient
Functionsfprintf(), fscanf(), fgets(), fputs()fread(), fwrite()
New Line'\n' converted to OS-specific (CRLF on Windows)No conversion; stored as-is
Extension.txt, .csv.bin, .dat, .exe

Copy File Program

#include <stdio.h>
int main() {
    FILE *src, *dest;
    char ch;

    src  = fopen("source.txt", "r");
    dest = fopen("destination.txt", "w");

    if (src == NULL || dest == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    while ((ch = fgetc(src)) != EOF)
        fputc(ch, dest);

    printf("File copied successfully!\n");
    fclose(src);
    fclose(dest);
    return 0;
}

Unit 9: FORTRAN

Structure · Data Types · Arrays · Arithmetic IF · Logical IF · DO Loop · Goto
List key differences between C and FORTRAN. How are 1D and 2D arrays declared in FORTRAN? Write a FORTRAN program to read and compute the transpose of a matrix.
★ Repeated 082 Shrawan · 081 Baishakh · 080 Baishakh · 080 Bhadra · 079 Bhadra · 078 Bhadra [2+4+6] or [2+2+6]

C vs FORTRAN Key Differences

BasisCFORTRAN
Full NameC Programming LanguageFORmula TRANslation
PurposeGeneral purpose / systemsScientific and numerical computing
Array IndexStarts at 0Starts at 1 (default)
String Handlingchar arrays with '\0'CHARACTER data type
Case SensitiveYesNo (case-insensitive)
PointersExplicit pointer supportLimited pointer support
I/Oprintf/scanfREAD/WRITE with FORMAT
Comments// or /* */C or ! at start of line (in F77/F90)

Array Declaration in FORTRAN

C 1D Array:
      INTEGER A(10)        ! Array of 10 integers (index 1 to 10)
      REAL X(5)            ! Array of 5 reals

C 2D Array:
      INTEGER MAT(3,4)     ! 3 rows, 4 columns
      REAL B(10,10)        ! 10x10 matrix

FORTRAN Program – Transpose

      PROGRAM TRANSPOSE
      INTEGER A(10,10), T(10,10), M, N, I, J
      WRITE(*,*) 'Enter rows and columns:'
      READ(*,*) M, N
      WRITE(*,*) 'Enter matrix elements:'
      DO 10 I = 1, M
        DO 10 J = 1, N
          READ(*,*) A(I,J)
   10 CONTINUE

      WRITE(*,*) 'Transpose matrix:'
      DO 20 I = 1, N
        DO 30 J = 1, M
          T(I,J) = A(J,I)
          WRITE(*,100) T(I,J)
   30   CONTINUE
        WRITE(*,*)
   20 CONTINUE
  100 FORMAT(I5,$)
      STOP
      END
Explain Arithmetic IF statement in FORTRAN. Write a program to determine whether a number is negative, zero, or positive using Arithmetic IF.
★ Repeated 082 Baishakh · 081 Bhadra · 080 Baishakh · 076 Ashwin · 074 Chaitra · 073 Chaitra · 071 Chaitra [2+2+6] or [3+6]

Arithmetic IF Statement

The Arithmetic IF evaluates an arithmetic expression and branches to one of three labels based on whether the result is negative, zero, or positive.

Syntax: IF (expression) label1, label2, label3

  • Goes to label1 if expression < 0
  • Goes to label2 if expression = 0
  • Goes to label3 if expression > 0

FORTRAN Program

      PROGRAM NUMCHECK
      INTEGER N
      WRITE(*,*) 'Enter a number:'
      READ(*,*) N
      IF (N) 10, 20, 30
   10 WRITE(*,*) 'Number is NEGATIVE'
      GOTO 40
   20 WRITE(*,*) 'Number is ZERO'
      GOTO 40
   30 WRITE(*,*) 'Number is POSITIVE'
   40 STOP
      END

Logical IF (for comparison)

Syntax: IF (logical expression) statement — executes statement only if true.

      IF (N .LT. 0) WRITE(*,*) 'Negative'
      IF (N .EQ. 0) WRITE(*,*) 'Zero'
      IF (N .GT. 0) WRITE(*,*) 'Positive'

FORTRAN relational operators: .EQ. .NE. .LT. .LE. .GT. .GE.

Write a FORTRAN program to check whether a number is palindrome or not.
081 Bhadra · 080 Baishakh · 079 Bhadra · 078 Bhadra · 076 Chaitra · 076 Ashwin (sort) · 075 Chaitra · 073 Chaitra · 072 Kartik [3+6] or [2+6]
      PROGRAM PALINDROME
      INTEGER N, TEMP, REV, DIGIT
      WRITE(*,*) 'Enter a number:'
      READ(*,*) N
      TEMP = N
      REV = 0
   10 IF (TEMP .EQ. 0) GOTO 20
      DIGIT = MOD(TEMP, 10)
      REV = REV * 10 + DIGIT
      TEMP = TEMP / 10
      GOTO 10
   20 IF (REV .EQ. N) THEN
         WRITE(*,*) N, 'is PALINDROME'
      ELSE
         WRITE(*,*) N, 'is NOT a palindrome'
      END IF
      STOP
      END
Palindrome numbers: 121, 1331, 12321 – same when reversed.
Describe the structure of a FORTRAN program. List down the data types available in FORTRAN.
★ Repeated 082 Baishakh · 081 Bhadra · 075 Chaitra · 074 Chaitra · 069 Chaitra · 068 Chaitra [2+2] or [5]

Structure of a FORTRAN Program

      PROGRAM program_name         ← Program heading
C     Comment line                ← Comments (C in column 1)
C     Declaration section:
      INTEGER/REAL/CHARACTER...   ← Variable declarations
C     Executable section:
      READ (*,*)  ...             ← Input
      [computation statements]    ← Processing
      WRITE (*,*) ...             ← Output
      STOP                        ← Stop execution
      END                         ← End of program

FORTRAN is column-based: Columns 1-5 = statement labels; Column 6 = continuation character; Columns 7-72 = statements.

Data Types in FORTRAN

Data TypeDeclarationExample
IntegerINTEGER XWhole numbers
RealREAL XFloating point (single precision)
Double PrecisionDOUBLE PRECISION XHigher precision float
ComplexCOMPLEX ZComplex numbers (a+bi)
LogicalLOGICAL FLAG.TRUE. or .FALSE.
CharacterCHARACTER*20 NAMEString of characters
FORTRAN uses implicit typing: variables starting with I-N are INTEGER; others are REAL (unless declared otherwise). Use IMPLICIT NONE to disable this.
Write a program in FORTRAN to display Fibonacci sequence upto nth term. Read n from the user. [Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13 …….]
★ Repeated 081 Baishakh [8]

FORTRAN Program – Fibonacci Sequence

      PROGRAM FIBONACCI
      INTEGER N, I, A, B, TEMP
      WRITE(*,*) 'Enter the number of terms:'
      READ(*,*) N

      A = 0
      B = 1

      WRITE(*,*) 'Fibonacci sequence:'
      DO 10 I = 1, N
        WRITE(*,100) A
        TEMP = A + B
        A = B
        B = TEMP
   10 CONTINUE

  100 FORMAT(I5)
      STOP
      END

Output (for n = 8)

Fibonacci sequence:
    0
    1
    1
    2
    3
    5
    8
   13
Compare about the control structures available in C and FORTRAN.
080 Bhadra [4+4]

Control Structures in C

TypeConstructDescription
Conditionalif, if-else, else ifExecutes block based on condition
Multi-wayswitch-caseSelects branch based on value of expression
LoopforCounter-controlled iteration
LoopwhilePre-test condition loop
Loopdo-whilePost-test condition loop (executes at least once)
JumpbreakExits loop or switch immediately
JumpcontinueSkips current iteration, continues loop
JumpgotoUnconditional jump to a label
/* Example: for loop in C */
for (i = 1; i <= 10; i++) {
    printf("%d\n", i);
}

Control Structures in FORTRAN

TypeConstructDescription
ConditionalIF (logical IF)Single-line conditional execution
ConditionalIF-THEN-ELSE-END IFBlock conditional (FORTRAN 77+)
Multi-wayIF-ELSE IF ladderMultiple condition checking (no switch)
LoopDO loopCounter-controlled iteration with label
LoopDO WHILECondition-controlled loop (FORTRAN 77+)
JumpGO TOUnconditional jump to a statement label
JumpComputed GO TOJumps to one of several labels based on index
StopSTOPTerminates program execution
C     Example: DO loop in FORTRAN
      DO 10 I = 1, 10
        WRITE(*,*) I
   10 CONTINUE

C     Example: IF-THEN-ELSE in FORTRAN
      IF (A .GT. B) THEN
        WRITE(*,*) 'A is greater'
      ELSE
        WRITE(*,*) 'B is greater'
      END IF

Key Differences

FeatureCFORTRAN
Switch/Multi-wayswitch-case availableNo switch; uses IF-ELSE IF ladder
Loop syntaxfor, while, do-whileDO loop and DO WHILE only
Loop controlbreak, continueNo direct equivalent in FORTRAN 77
Gotogoto (rarely used)GO TO with statement labels (common in F77)
Condition syntax==, !=, >, <.EQ., .NE., .GT., .LT., .GE., .LE.
What is the use of FORMAT statement? Explain I and F format with example. Write a program in FORTRAN to read a number from user and check whether it is a prime number or not.
080 Baishakh [4+4]

FORMAT Statement

The FORMAT statement in FORTRAN is used to specify the exact layout and appearance of input/output data. It controls how data is read from or written to a device by defining field widths, decimal places, spacing, and data types. It is always used with READ and WRITE statements via a statement label.

      WRITE(*,100) X
  100 FORMAT(...)       ! FORMAT is referenced by label 100

I Format (Integer)

Used for integer input/output. Syntax: Iw where w is the total field width.

      INTEGER N
      N = 42
      WRITE(*,100) N
  100 FORMAT(I5)
C     Output:    42   (right-justified in 5 character wide field)

F Format (Floating Point)

Used for real (floating-point) input/output. Syntax: Fw.d where w is total field width and d is number of decimal places.

      REAL X
      X = 3.14159
      WRITE(*,200) X
  200 FORMAT(F8.3)
C     Output:    3.142  (8 chars wide, 3 decimal places)

FORTRAN Program – Prime Number Check

      PROGRAM PRIME
      INTEGER N, I, FLAG
      WRITE(*,*) 'Enter a number:'
      READ(*,*) N

      FLAG = 0
      IF (N .LE. 1) THEN
        FLAG = 1
      END IF

      DO 10 I = 2, N/2
        IF (MOD(N, I) .EQ. 0) THEN
          FLAG = 1
        END IF
   10 CONTINUE

      IF (FLAG .EQ. 0) THEN
        WRITE(*,*) N, 'is a prime number.'
      ELSE
        WRITE(*,*) N, 'is not a prime number.'
      END IF

      STOP
      END

Output (for n = 7)

Enter a number:
7
7 is a prime number.
CT401 Computer Programming – Complete Study Guide  |  Tribhuvan University, IOE  |  All Rights Reserved - Er. Ayan Siddiquie  |  All years 2067–2082
Get In Touch