Browse papers
A

Section A: Long Answer Questions

Attempt all / any as specified.

4 questions
1long12 marks

(a) Describe the basic structure of a C program, clearly explaining the role of preprocessor directives, the main() function, declarations, and statements. (b) What is meant by a token in C? List and briefly explain the different categories of tokens. (c) Differentiate between the storage classes auto, static, extern, and register with respect to their scope, lifetime, and default initial value.

(a) Basic Structure of a C Program

#include <stdio.h>      /* preprocessor directive */
#define PI 3.14159      /* preprocessor directive */

int global = 0;         /* global declaration */

int main(void) {        /* main() function */
    int r = 5;          /* declaration */
    float area;
    area = PI * r * r;  /* statement */
    printf("%f", area); /* statement */
    return 0;
}
  • Preprocessor directives (lines beginning with #) are processed before compilation. #include inserts header files (e.g. <stdio.h> for I/O prototypes) and #define creates symbolic constants/macros.
  • main() function is the mandatory entry point; program execution begins and ends here. It returns an int status to the OS.
  • Declarations introduce variables/functions with their data types and reserve storage, e.g. int r;.
  • Statements are the executable instructions (assignments, function calls, control statements) terminated by a semicolon ;.

(b) Tokens in C

A token is the smallest individual (indivisible) unit of a C program that is meaningful to the compiler. The compiler's lexical analyzer breaks the source into tokens. The six categories are:

  1. Keywords — reserved words with fixed meaning, e.g. int, for, while, return.
  2. Identifiers — user-defined names for variables, functions, arrays, e.g. sum, main.
  3. Constants — fixed values, e.g. 10, 3.14, 'A'.
  4. Strings — sequences of characters in double quotes, e.g. "hello".
  5. Operators — symbols performing operations, e.g. +, -, *, ==, &&.
  6. Special symbols / punctuators{ } ( ) [ ] ; , # etc.

(c) Storage Classes

Storage classScopeLifetimeDefault initial valueStorage
autoLocal (block)Until block exitsGarbage (undefined)Memory (stack)
staticLocal (block) but value retained; or file scopeWhole program0 (zero)Memory
externGlobal (across files)Whole program0 (zero)Memory
registerLocal (block)Until block exitsGarbage (undefined)CPU register (request)
  • static preserves a variable's value between function calls; extern declares a global defined elsewhere; register is a hint to keep the variable in a CPU register for fast access (so its address cannot be taken).
program-structuredata-typesfunctions
2long12 marks

(a) Distinguish between call by value and call by reference with a suitable example for each. (b) Write a C program using a recursive function to compute the factorial of a number entered by the user, and explain how the recursion unwinds for an input of 4. (c) How does passing a one-dimensional array to a function differ from passing an ordinary variable?

(a) Call by Value vs Call by Reference

Call by value: a copy of the actual argument is passed; changes inside the function do not affect the original.

void inc(int x){ x = x + 1; }   /* original unchanged */
int a = 5; inc(a);  /* a is still 5 */

Call by reference: the address of the argument is passed (via a pointer); the function can modify the original.

void inc(int *x){ *x = *x + 1; } /* original changed */
int a = 5; inc(&a); /* a becomes 6 */

(b) Recursive Factorial

#include <stdio.h>
long fact(int n){
    if (n <= 1) return 1;        /* base case */
    return n * fact(n - 1);      /* recursive case */
}
int main(){
    int n; printf("Enter n: "); scanf("%d", &n);
    printf("Factorial = %ld", fact(n));
    return 0;
}

Unwinding for n = 4 (calls stack up, then return values combine):

fact(4) = 4 * fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1            (base case)
=> fact(2) = 2*1 = 2
=> fact(3) = 3*2 = 6
=> fact(4) = 4*6 = 24

Result = 24.

(c) Passing an Array vs an Ordinary Variable

An ordinary variable is passed by value (a copy). An array name decays to a pointer to its first element, so passing an array effectively passes its base address — the function works on the original array (call by reference behaviour). Therefore changes to array elements inside the function persist, and the array size is not carried automatically (it must be passed separately).

functionsrecursionarrays
3long12 marks

(a) What is a pointer? Explain the relationship between arrays and pointers with reference to how the expression a[i] is evaluated by the compiler. (b) Write a C program that reads a string from the user and counts the number of vowels, consonants, and digits in it using pointer notation (do not use array subscripting). (c) Explain the meaning of the declaration int *p[10]; and how it differs from int (*p)[10];.

(a) Pointers and Arrays

A pointer is a variable that stores the memory address of another variable, e.g. int *p; p = &x;.

The name of an array is a constant pointer to its first element, so a is equivalent to &a[0]. For an array a, the compiler evaluates the subscript expression as:

a[i](a+i)a[i] \equiv *(a + i)

The address is computed as base_address + i * sizeof(element), and the value at that address is fetched. This is why a[i], *(a+i), *(i+a) and i[a] are all equivalent.

(b) Vowels, Consonants, Digits using Pointers

#include <stdio.h>
#include <ctype.h>
int main(){
    char str[100], *p;
    int v=0, c=0, d=0;
    printf("Enter string: ");
    gets(str);              /* or fgets(str,100,stdin) */
    p = str;
    while(*p != '\0'){
        char ch = tolower(*p);
        if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') v++;
        else if(ch>='a' && ch<='z') c++;
        else if(*p>='0' && *p<='9') d++;
        p++;                /* pointer arithmetic, no subscript */
    }
    printf("Vowels=%d Consonants=%d Digits=%d", v, c, d);
    return 0;
}

(c) int *p[10]; vs int (*p)[10];

  • int *p[10];[] has higher precedence than *, so p is an array of 10 pointers to int. It holds 10 separate int* values.
  • int (*p)[10]; — the parentheses bind * first, so p is a single pointer to an array of 10 ints. p holds one address; *p is the whole array of 10 ints (commonly used for 2-D arrays).
pointersarraysstrings
4long12 marks

(a) Define a structure named Student containing fields for roll number, name, and marks in three subjects. Write a C program that reads records of n students, computes the total and average marks of each, and writes the records to a file named student.dat. (b) Explain the difference between a structure and a union in terms of memory allocation, giving a suitable diagram. (c) Differentiate between text mode and binary mode of opening a file.

(a) Student Structure + File Writing

#include <stdio.h>
struct Student {
    int roll;
    char name[30];
    float marks[3];
    float total, avg;
};
int main(){
    int n, i;
    struct Student s;
    FILE *fp = fopen("student.dat", "wb");
    printf("Enter number of students: "); scanf("%d", &n);
    for(i=0; i<n; i++){
        printf("Roll, Name, 3 marks: ");
        scanf("%d %s %f %f %f", &s.roll, s.name,
              &s.marks[0], &s.marks[1], &s.marks[2]);
        s.total = s.marks[0] + s.marks[1] + s.marks[2];
        s.avg   = s.total / 3.0;
        fwrite(&s, sizeof(s), 1, fp);
    }
    fclose(fp);
    printf("Records written to student.dat");
    return 0;
}

(b) Structure vs Union (Memory)

A structure allocates separate memory for each member, so its size is (at least) the sum of all members. A union allocates a single shared block equal to its largest member; all members overlap and only one is valid at a time.

For { int a; char c; } on a 4-byte-int system:

Structure (size = 4 + 1 = 5+ bytes, members separate):
  | a (4 bytes) | c (1) |

Union (size = 4 bytes, members overlap):
  | a / c share the SAME 4 bytes |

(c) Text Mode vs Binary Mode

AspectText mode ("r","w")Binary mode ("rb","wb")
DataHuman-readable charactersRaw bytes as in memory
Newline\n may be translated to \r\n (Windows)No translation
EOFCtrl-Z may mark end (some systems)No special char
UsePlain text filesImages, fwrite/fread records
structuresunionsfile-handling
B

Section B: Short Answer Questions

Attempt all / any as specified.

7 questions
5short8 marks

(a) Explain operator precedence and associativity with an example. Evaluate the expression a = 5 + 3 * 2 - 8 / 4 % 3 step by step, showing the value of a. (b) What is the difference between i++ and ++i? Determine the output of the following code:

int i = 5, j;
j = i++ + ++i;
printf("%d %d", i, j);

(a) Operator Precedence and Associativity

Precedence decides which operator is applied first when several appear in one expression; associativity (left-to-right or right-to-left) decides the order among operators of equal precedence. In 2 + 3 * 4, * (higher precedence) is done first giving 2 + 12 = 14.

Evaluate a = 5 + 3 * 2 - 8 / 4 % 3 (*, /, % are equal precedence, evaluated left-to-right; +, - lower):

32=63 * 2 = 6 8/4=28 / 4 = 2 2%3=22 \,\%\, 3 = 2 5+62=95 + 6 - 2 = 9

a = 9.

(b) i++ vs ++i

  • i++ (post-increment): uses the current value first, then increments.
  • ++i (pre-increment): increments first, then uses the new value.

Trace of the code (i = 5):

j = i++ + ++i;
  • i++ yields 5, and i becomes 6.
  • ++i makes i become 7, and yields 7.
  • j = 5 + 7 = 12.

Final: i = 7, j = 12. Output: 7 12.

(Note: such mixing of side effects on one variable is technically unspecified; on the common GCC implementation the result is 7 12.)

operatorsexpressions
6short8 marks

(a) Differentiate between the while loop and the do-while loop with a flowchart for each. (b) Write a C program using a switch statement that takes a single character operator (+, -, *, /) and two operands from the user and performs the corresponding arithmetic operation, handling division by zero appropriately.

(a) while vs do-while

while (entry-controlled)do-while (exit-controlled)
Condition tested before bodyCondition tested after body
Body may execute 0 timesBody executes at least once
while(cond){ ... }do{ ... }while(cond);

Flowchart (while): Start → test condition? → if true, execute body → loop back to test; if false → exit.

Flowchart (do-while): Start → execute body → test condition? → if true, loop back to body; if false → exit. (The body box precedes the decision diamond, guaranteeing one pass.)

(b) Calculator using switch

#include <stdio.h>
int main(){
    char op; float a, b;
    printf("Enter operand1 operator operand2: ");
    scanf("%f %c %f", &a, &op, &b);
    switch(op){
        case '+': printf("%.2f", a + b); break;
        case '-': printf("%.2f", a - b); break;
        case '*': printf("%.2f", a * b); break;
        case '/':
            if(b == 0)
                printf("Error: division by zero");
            else
                printf("%.2f", a / b);
            break;
        default: printf("Invalid operator");
    }
    return 0;
}
control-statements
7short8 marks

(a) Write a C program to read a 3x3 matrix and find the transpose of the matrix, displaying both the original and the transposed matrix. (b) Explain any four standard string-handling library functions in C with their syntax and a one-line description of each.

(a) Transpose of a 3x3 Matrix

#include <stdio.h>
int main(){
    int a[3][3], i, j;
    printf("Enter 9 elements:\n");
    for(i=0;i<3;i++)
        for(j=0;j<3;j++)
            scanf("%d", &a[i][j]);

    printf("Original matrix:\n");
    for(i=0;i<3;i++){
        for(j=0;j<3;j++) printf("%d ", a[i][j]);
        printf("\n");
    }
    printf("Transpose:\n");
    for(i=0;i<3;i++){
        for(j=0;j<3;j++) printf("%d ", a[j][i]); /* swap indices */
        printf("\n");
    }
    return 0;
}

The transpose is obtained by printing a[j][i] in place of a[i][j] (rows become columns).

(b) Four Standard String Functions (<string.h>)

FunctionSyntaxDescription
strlenstrlen(str)Returns the length (number of characters, excluding '\0').
strcpystrcpy(dest, src)Copies string src into dest.
strcatstrcat(dest, src)Appends (concatenates) src to the end of dest.
strcmpstrcmp(s1, s2)Compares two strings; returns 0 if equal, <0 or >0 otherwise.
arraysstrings
8short8 marks

(a) Differentiate between printf() and scanf() functions, explaining the meaning of the format specifiers %d, %f, %c, and %s. (b) What will be the output of the following program? Justify your answer.

#include <stdio.h>
int main() {
    int a = 10;
    float b = 3;
    printf("%d\n", a / (int)b);
    printf("%.2f\n", a / b);
    return 0;
}

(a) printf() vs scanf()

  • printf() is an output function that sends formatted data to the standard output (screen).
  • scanf() is an input function that reads formatted data from the standard input (keyboard) and stores it at the addresses (&var) supplied.

Format specifiers:

SpecifierMeaning
%dsigned decimal integer
%ffloating-point number (float/double)
%csingle character
%sstring (array of characters)

(b) Output of the Program

int a = 10; float b = 3;
printf("%d\n", a / (int)b);  /* line 1 */
printf("%.2f\n", a / b);     /* line 2 */
  • Line 1: (int)b is 3, so a / (int)b = 10 / 3. Both operands are int, so integer division gives 3. Output: 3.
  • Line 2: a / b is int / float; a is promoted to 10.0, so 10.0 / 3 = 3.3333..., printed to 2 decimals as 3.33. Output: 3.33.

Output:

3
3.33
data-typesprogram-structure
9short8 marks

(a) What is dynamic memory allocation? Explain the use of malloc(), calloc(), and free() with their syntax. (b) Write a C program that dynamically allocates memory for an array of n integers entered by the user, finds the largest element, and frees the allocated memory before exiting.

(a) Dynamic Memory Allocation

Dynamic memory allocation is the process of requesting memory from the heap at run time (rather than at compile time), allowing the program to use exactly as much memory as needed. The functions are declared in <stdlib.h>:

FunctionSyntaxPurpose
mallocptr = (int*)malloc(n * sizeof(int));Allocates a single block of n*size bytes; memory is uninitialised (garbage).
callocptr = (int*)calloc(n, sizeof(int));Allocates memory for n elements and initialises every byte to 0.
freefree(ptr);Releases previously allocated memory back to the heap.

All return a void* (NULL on failure).

(b) Largest Element with Dynamic Array

#include <stdio.h>
#include <stdlib.h>
int main(){
    int n, i, *arr, max;
    printf("Enter n: "); scanf("%d", &n);
    arr = (int*)malloc(n * sizeof(int));
    if(arr == NULL){ printf("Allocation failed"); return 1; }
    for(i=0;i<n;i++){
        printf("Element %d: ", i+1);
        scanf("%d", &arr[i]);
    }
    max = arr[0];
    for(i=1;i<n;i++)
        if(arr[i] > max) max = arr[i];
    printf("Largest element = %d", max);
    free(arr);        /* release memory */
    return 0;
}
pointersfunctions
10short8 marks

(a) List and explain the different file opening modes (r, w, a, r+, w+, a+) used with fopen(). (b) Write a C program that opens an existing text file, reads it character by character, copies its contents to another file, and counts the total number of lines in the file.

(a) File Opening Modes with fopen()

ModeMeaning
rOpen existing file for reading only. Fails (returns NULL) if file does not exist.
wOpen for writing. Creates the file; if it exists, its contents are erased.
aOpen for appending. Writes go to the end; creates the file if absent.
r+Open existing file for reading and writing (file must exist).
w+Create/truncate file for reading and writing.
a+Open for reading and appending; writes always go to the end.

(b) Copy File and Count Lines

#include <stdio.h>
int main(){
    FILE *in = fopen("source.txt", "r");
    FILE *out = fopen("dest.txt", "w");
    int ch, lines = 0;
    if(in == NULL || out == NULL){
        printf("File error"); return 1;
    }
    while((ch = fgetc(in)) != EOF){
        fputc(ch, out);          /* copy char */
        if(ch == '\n') lines++;  /* count newline */
    }
    fclose(in); fclose(out);
    printf("Copied. Total lines = %d", lines);
    return 0;
}

fgetc returns int so that EOF (a value outside unsigned char) can be detected correctly.

file-handling
11short6 marks

Write a C program to generate and display the first n terms of the Fibonacci series, where n is entered by the user, using an iterative approach. Briefly explain how the same result could be achieved using recursion.

Fibonacci Series (Iterative)

The Fibonacci series is 0,1,1,2,3,5,8,0, 1, 1, 2, 3, 5, 8, \dots where each term is the sum of the two preceding terms: Fn=Fn1+Fn2F_n = F_{n-1} + F_{n-2}, with F0=0, F1=1F_0 = 0,\ F_1 = 1.

#include <stdio.h>
int main(){
    int n, i;
    long a = 0, b = 1, next;
    printf("Enter n: "); scanf("%d", &n);
    for(i = 0; i < n; i++){
        printf("%ld ", a);
        next = a + b;   /* compute next term */
        a = b;
        b = next;
    }
    return 0;
}

For n = 7 the output is: 0 1 1 2 3 5 8.

Using Recursion

Define a function that returns the k-th term directly from the recurrence:

long fib(int k){
    if(k == 0) return 0;        /* base case */
    if(k == 1) return 1;        /* base case */
    return fib(k-1) + fib(k-2); /* recursive case */
}

Calling fib(0), fib(1), ..., fib(n-1) in a loop prints the same series. The recursive version is conceptually closer to the mathematical definition but is less efficient (O(2n)O(2^n)) because it recomputes overlapping sub-terms, whereas the iterative version runs in O(n)O(n) time.

functionsrecursioncontrol-statements

Frequently asked questions

Where can I find the BE Computer Engineering (IOE, TU) Computer Programming in C (IOE, CT 401) question paper 2078?
The full BE Computer Engineering (IOE, TU) Computer Programming in C (IOE, CT 401) 2078 (regular) question paper is available free on Kekkei. You can read every question online and attempt the paper under timed exam conditions.
Does the Computer Programming in C (IOE, CT 401) 2078 paper come with solutions?
Yes. Every question on this Computer Programming in C (IOE, CT 401) past paper includes a step-by-step solution, plus instant AI feedback when you attempt it on Kekkei.
How many marks is the BE Computer Engineering (IOE, TU) Computer Programming in C (IOE, CT 401) 2078 paper?
The BE Computer Engineering (IOE, TU) Computer Programming in C (IOE, CT 401) 2078 paper carries 80 full marks and is meant to be completed in 180 minutes, across 11 questions.
Is practising this Computer Programming in C (IOE, CT 401) past paper free?
Yes — reading and attempting this Computer Programming in C (IOE, CT 401) past paper on Kekkei is completely free.