2081

BIT102 · TU past paper

C Programming 2081 question paper

The complete TU 2081 exam paper for C Programming (BIT102), all 12 questions with solved model answers written to the mark scheme.

Tap a question to open its answer.

  1. 110 marksLoop control statementsAnswer

    What is loop? Differentiate between break and continue statement.Write a program to find sum of first N natural numbers.[6+4]

    Loop, Break vs Continue, and Sum of N Natural Numbers


    What is a Loop?

    A loop is a control structure that allows repeated execution of a block of statements as long as a given condition remains true. Loops are used to avoid writing the same code multiple times.

    Types of Loops in C:

    Loop TypeDescription
    for loopUsed when the number of iterations is known
    while loopEntry-controlled; checks condition before executing
    do-while loopExit-controlled; executes at least once

    Difference Between break and continue Statement

    Featurebreakcontinue
    FunctionTerminates the entire loop immediatelySkips the current iteration only
    Control TransferTransfers control outside the loopTransfers control to the loop's condition check
    Effect on LoopLoop stops completelyLoop continues with next iteration
    Use CaseExit loop when a condition is metSkip specific values during iteration

    Example of break:

    for(int i = 1; i <= 10; i++) {
        if(i == 5)
            break;       // loop ends when i reaches 5
        printf("%d ", i);
    }
    // Output: 1 2 3 4
    

    Example of continue:

    for(int i = 1; i <= 10; i++) {
        if(i == 5)
            continue;    // skips i=5, loop keeps running
        printf("%d ", i);
    }
    // Output: 1 2 3 4 6 7 8 9 10
    

    Conclusion: break exits the loop entirely, while continue only skips the current iteration and the loop keeps running.


    Program to Find Sum of First N Natural Numbers

    The sum of first N natural numbers means adding all integers from 1 to N.

    #include <stdio.h>
    
    int main() {
        int n, i, sum = 0;
    
        printf("Enter the value of N: ");
        scanf("%d", &n);
    
        for(i = 1; i <= n; i++) {
            sum = sum + i;   // accumulate sum
        }
    
        printf("Sum of first %d natural numbers = %d\n", n, sum);
    
        return 0;
    }
    

    Sample Output:

    Enter the value of N: 5
    Sum of first 5 natural numbers = 15
    

    Explanation (Dry Run for N = 5):

    Iterationisum = sum + i
    110 + 1 = 1
    221 + 2 = 3
    333 + 3 = 6
    446 + 4 = 10
    5510 + 5 = 15

    The for loop runs from i = 1 to i = N, adding each value of i to the variable sum. After the loop ends, the final sum is displayed.

  2. 210 marksSimilarity between arrays and pointersAnswer

    What is pointer? How it differs from array?Write a program to add two 2D matrices.[4+6]

    Pointer vs Array and 2D Matrix Addition


    What is a Pointer? (4 marks)

    A pointer is a variable that stores the memory address of another variable rather than storing a data value directly.

    Declaration syntax:

    data_type *pointer_name;
    

    Example:

    int x = 10;
    int *ptr;
    ptr = &x;   // ptr holds the address of x
    printf("%d", *ptr);  // prints 10 (dereferencing)
    
    • & operator gives the address of a variable
    • * operator dereferences a pointer (accesses value at that address)

    How Pointer Differs from Array

    FeaturePointerArray
    DefinitionVariable that stores address of another variableCollection of elements of same data type stored in contiguous memory
    MemoryStores only an address (typically 4 or 8 bytes)Allocates memory for all elements at once
    AssignmentCan be reassigned to point to different variablesArray name is a constant pointer; cannot be reassigned
    InitializationMust be explicitly assigned an address before useMemory is allocated at declaration
    ArithmeticPointer arithmetic moves to next memory locationArray index directly accesses elements
    sizeofReturns size of pointer variable itselfReturns total size of all elements
    Dynamic memoryCan use malloc()/calloc() for dynamic allocationSize is fixed at compile time (static)

    Example showing difference:

    int arr[5] = {1, 2, 3, 4, 5};
    int *ptr = arr;
    
    // arr = ptr;  // ERROR: array name is constant
    ptr = ptr + 1;  // VALID: pointer can be moved
    

    Program to Add Two 2D Matrices (6 marks)

    #include <stdio.h>
    
    int main() {
        int r, c, i, j;
    
        // Input dimensions
        printf("Enter number of rows: ");
        scanf("%d", &r);
        printf("Enter number of columns: ");
        scanf("%d", &c);
    
        int A[r][c], B[r][c], C[r][c];
    
        // Input matrix A
        printf("\nEnter elements of Matrix A (%dx%d):\n", r, c);
        for (i = 0; i < r; i++) {
            for (j = 0; j < c; j++) {
                printf("A[%d][%d]: ", i, j);
                scanf("%d", &A[i][j]);
            }
        }
    
        // Input matrix B
        printf("\nEnter elements of Matrix B (%dx%d):\n", r, c);
        for (i = 0; i < r; i++) {
            for (j = 0; j < c; j++) {
                printf("B[%d][%d]: ", i, j);
                scanf("%d", &B[i][j]);
            }
        }
    
        // Add matrices A and B, store result in C
        for (i = 0; i < r; i++) {
            for (j = 0; j < c; j++) {
                C[i][j] = A[i][j] + B[i][j];
            }
        }
    
        // Display result matrix C
        printf("\nResultant Matrix C = A + B:\n");
        for (i = 0; i < r; i++) {
            for (j = 0; j < c; j++) {
                printf("%d\t", C[i][j]);
            }
            printf("\n");
        }
    
        return 0;
    }
    

    Sample Output

    Enter number of rows: 2
    Enter number of columns: 2
    
    Enter elements of Matrix A (2x2):
    A[0][0]: 1
    A[0][1]: 2
    A[1][0]: 3
    A[1][1]: 4
    
    Enter elements of Matrix B (2x2):
    B[0][0]: 5
    B[0][1]: 6
    B[1][0]: 7
    B[1][1]: 8
    
    Resultant Matrix C = A + B:
    6    8
    10   12
    

    Logic Explanation

    For two matrices A and B of same dimension (r x c):

    $$C[i][j] = A[i][j] + B[i][j]$$

    where i ranges from 0 to r-1 and j ranges from 0 to c-1.

    Note: Matrix addition is only possible when both matrices have the same number of rows and columns.

  3. 310 marksString definition and declarationAnswer

    What is string?Explain any three string function in "string.h" header file in C with example.Write a program to check whether a word is palindrome or not.[2+3+5]

    String, String Functions, and Palindrome Check


    1. What is String? [2 marks]

    A string in C is a sequence of characters stored in a character array and terminated by a null character (\0). C does not have a built-in string data type; instead, strings are represented as arrays of type char.

    Declaration:

    char name[] = "Hello";
    // Stored as: H e l l o \0
    

    The null character \0 marks the end of the string and is automatically added when a string literal is used.


    2. Three String Functions in string.h [3 marks]

    i) strlen() - String Length

    Returns the number of characters in a string, excluding the null character.

    #include <stdio.h>
    #include <string.h>
    int main() {
        char str[] = "Hello";
        printf("Length = %d", strlen(str));  // Output: 5
        return 0;
    }
    

    ii) strcpy() - String Copy

    Copies the content of one string (source) into another string (destination).

    #include <stdio.h>
    #include <string.h>
    int main() {
        char src[] = "Nepal";
        char dest[20];
        strcpy(dest, src);
        printf("Copied string: %s", dest);  // Output: Nepal
        return 0;
    }
    

    iii) strcmp() - String Compare

    Compares two strings lexicographically.

    • Returns 0 if both strings are equal
    • Returns a negative value if first string is less than second
    • Returns a positive value if first string is greater than second
    #include <stdio.h>
    #include <string.h>
    int main() {
        char s1[] = "apple";
        char s2[] = "apple";
        if (strcmp(s1, s2) == 0)
            printf("Strings are equal");   // Output: Strings are equal
        else
            printf("Strings are not equal");
        return 0;
    }
    

    3. Program to Check Whether a Word is Palindrome or Not [5 marks]

    Logic: A word is a palindrome if it reads the same forwards and backwards. Example: "madam", "level", "racecar"

    We compare the string with its reverse. If they are equal, it is a palindrome.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char word[100], rev[100];
        int len, i, j;
        int isPalindrome = 1;  // Assume true initially
    
        printf("Enter a word: ");
        scanf("%s", word);
    
        len = strlen(word);
    
        // Reverse the word manually
        for (i = 0, j = len - 1; i < len; i++, j--) {
            rev[i] = word[j];
        }
        rev[len] = '\0';  // Add null terminator
    
        // Compare original and reversed word
        if (strcmp(word, rev) == 0) {
            printf("\"%s\" is a Palindrome.\n", word);
        } else {
            printf("\"%s\" is NOT a Palindrome.\n", word);
        }
    
        return 0;
    }
    

    Sample Output:

    Case 1:

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

    Case 2:

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

    Explanation of Key Steps:

    StepDescription
    strlen(word)Finds the length of the entered word
    Reverse loopCopies characters from end to start into rev[]
    rev[len] = '\0'Properly terminates the reversed string
    strcmp(word, rev)Compares original and reversed; returns 0 if equal
  4. 45 marksConversion specifiersAnswer

    What are conversion specifiers? Explain the compilation of C program in brief. [2+3]

    --- Conversion specifiers are special format codes used inside printf() and scanf() functions to specify the type and format of data to be printed or read. They always begin with a percent sign (%). Specifier Data Type Example ----------...

  5. 55 marksStoring and displaying structure dataAnswer

    What is structure? Write a program to read roll, name and marks of 10 students using structure and then display all records. [1+4]

    Structure in C

    What is 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 inside a structure is called a member or field.

    Syntax:

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

    Program: Read and Display Records of 10 Students

    #include <stdio.h>
    
    // Define the structure
    struct Student {
        int roll;
        char name[50];
        float marks;
    };
    
    int main() {
        struct Student s[10];
        int i;
    
        // Read records of 10 students
        printf("Enter details of 10 students:\n");
        for (i = 0; i < 10; i++) {
            printf("\nStudent %d:\n", i + 1);
            printf("Enter Roll No : ");
            scanf("%d", &s[i].roll);
            printf("Enter Name    : ");
            scanf(" %s", s[i].name);
            printf("Enter Marks   : ");
            scanf("%f", &s[i].marks);
        }
    
        // Display all records
        printf("\n\n--- Student Records ---\n");
        printf("%-10s %-20s %-10s\n", "Roll No", "Name", "Marks");
        printf("----------------------------------------\n");
        for (i = 0; i < 10; i++) {
            printf("%-10d %-20s %-10.2f\n", s[i].roll, s[i].name, s[i].marks);
        }
    
        return 0;
    }
    

    Sample Output

    Enter details of 10 students:
    
    Student 1:
    Enter Roll No : 1
    Enter Name    : Ram
    Enter Marks   : 85.5
    ...
    
    --- Student Records ---
    Roll No    Name                 Marks
    ----------------------------------------
    1          Ram                  85.50
    2          Sita                 90.00
    ...
    

    Key Points

    FeatureDescription
    Keywordstruct
    MembersCan be of different data types
    Array of structuresstruct Student s[10] stores 10 students
    Member accessUsing dot operator (.)
  6. 65 marksIf else ladderAnswer

    Explain if else ladder with syntax and semantic. Write a program to find largest among 3 different numbers. [2+3]

    --- - The conditions are evaluated from top to bottom, one by one. - As soon as a condition evaluates to true, the corresponding block of statements is executed, and the rest of the ladder is skipped. - If none of the conditions is true,...

  7. 75 marksLoop control statementsAnswer

    Write a program to check whether a given number is Armstrong number or not. [5]

    An Armstrong number (also called a narcissistic number) is a number that equals the sum of its own digits each raised to the power of the number of digits. Example: - 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓ - 371 = 3³ + 7³ + 1³ = 27 + ...

  8. 85 marksOperator precedence and associativityAnswer

    What is operator precedence? Explain assignment and logical operator. [1+4]

    Operator Precedence, Assignment and Logical Operators


    Operator Precedence [1 mark]

    Operator precedence defines the order (priority) in which operators are evaluated in an expression when multiple operators appear together. An operator with higher precedence is evaluated before an operator with lower precedence.

    Example:

    2 + 3 * 4  =  2 + 12  =  14
    

    Here, * has higher precedence than +, so multiplication is performed first.


    Assignment Operator [2 marks]

    The assignment operator is used to assign a value to a variable. The basic assignment operator is =.

    Syntax:

    variable = expression;
    

    Simple Assignment

    OperatorExampleMeaning
    =a = 5Assigns 5 to a

    Compound Assignment Operators

    These combine an arithmetic operation with assignment:

    OperatorExampleEquivalent To
    +=a += 5a = a + 5
    -=a -= 5a = a - 5
    *=a *= 5a = a * 5
    /=a /= 5a = a / 5
    %=a %= 5a = a % 5

    Key Points:

    • Assignment is right-to-left associative
    • Multiple assignments are possible: a = b = c = 10; (assigns 10 to all)
    • The right-hand side is evaluated first, then assigned to the left-hand side variable

    Logical Operators [2 marks]

    Logical operators are used to combine or negate boolean/conditional expressions. They return either true (1) or false (0).

    Types of Logical Operators

    OperatorNameExampleResult
    &&Logical ANDa && bTrue only if both a and b are true
    ||Logical ORa || bTrue if at least one of a or b is true
    !Logical NOT!aTrue if a is false, and vice versa

    Truth Tables

    AND (&&)

    ABA && B
    000
    010
    100
    111

    OR (||)

    ABA || B
    000
    011
    101
    111

    NOT (!)

    A!A
    01
    10

    Example in C:

    int a = 5, b = 10, c = 0;
    
    if (a > 0 && b > 0)       // true && true = true
        printf("Both positive");
    
    if (a > 0 || c > 0)       // true || false = true
        printf("At least one positive");
    
    if (!c)                    // !0 = true
        printf("c is zero");
    

    Key Points:

    • && and || use short-circuit evaluation: if the result is determined from the first operand, the second is not evaluated
    • ! is a unary operator (operates on one operand)
    • Logical operators are commonly used in if, while, and for conditions
  9. 95 marksCall by reference for swappingAnswer

    Explain call by reference of a function with suitable example. [5]

    Call by reference is a method of passing arguments to a function where the address (reference) of the actual argument is passed to the formal parameter of the function. Any changes made to the formal parameter inside the function directl...

  10. 105 marksFile handling and file operationsAnswer

    Write a program to write N numbers in file "number.txt" and then read it and display only even numbers. [5]

    Program: Write N Numbers to File and Display Even Numbers

    C Program

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        FILE *fp;
        int i, n, num;
    
        // Step 1: Get N from user
        printf("Enter how many numbers to write: ");
        scanf("%d", &n);
    
        // Step 2: Open file for writing
        fp = fopen("number.txt", "w");
        if (fp == NULL) {
            printf("Error opening file for writing!\n");
            exit(1);
        }
    
        // Step 3: Write N numbers to file
        printf("Enter %d numbers:\n", n);
        for (i = 0; i < n; i++) {
            scanf("%d", &num);
            fprintf(fp, "%d\n", num);
        }
    
        fclose(fp);
        printf("Numbers written to file successfully.\n");
    
        // Step 4: Open file for reading
        fp = fopen("number.txt", "r");
        if (fp == NULL) {
            printf("Error opening file for reading!\n");
            exit(1);
        }
    
        // Step 5: Read and display only even numbers
        printf("\nEven numbers from file:\n");
        while (fscanf(fp, "%d", &num) != EOF) {
            if (num % 2 == 0) {
                printf("%d\n", num);
            }
        }
    
        fclose(fp);
        return 0;
    }
    

    Sample Output

    Enter how many numbers to write: 6
    Enter 6 numbers:
    3 8 15 22 7 10
    
    Numbers written to file successfully.
    
    Even numbers from file:
    8
    22
    10
    

    Key Points

    StepOperationFunction Used
    1Open file for writingfopen("number.txt", "w")
    2Write numbers to filefprintf(fp, "%d\n", num)
    3Close file after writingfclose(fp)
    4Open file for readingfopen("number.txt", "r")
    5Read numbers from filefscanf(fp, "%d", &num)
    6Check even conditionnum % 2 == 0

    Note: Always check if fopen() returns NULL to handle file errors, and always call fclose() after file operations to release resources.

  11. 115 marksBasic data types and their rangesAnswer

    What is constant? Explain basic data types in C programming along with their range. [1+4]

    Constants and Basic Data Types in C Programming


    What is a Constant? [1 Mark]

    A constant is a fixed value that does not change during the execution of a program. Once defined, its value remains the same throughout the program.

    Example:

    const int x = 10;   // x is always 10
    #define PI 3.14159  // PI is always 3.14159
    

    Basic Data Types in C Programming [4 Marks]

    C provides several fundamental (basic) data types to store different kinds of data. These are:


    1. int (Integer Type)

    • Used to store whole numbers (positive, negative, or zero).
    • No decimal point.
    TypeSizeRange
    int2 or 4 bytes-32,768 to 32,767 (2 bytes) / -2,147,483,648 to 2,147,483,647 (4 bytes)
    short int2 bytes-32,768 to 32,767
    long int4 bytes-2,147,483,648 to 2,147,483,647
    unsigned int2 or 4 bytes0 to 65,535 (2 bytes) / 0 to 4,294,967,295 (4 bytes)
    int age = 20;
    

    2. float (Floating Point Type)

    • Used to store real numbers (numbers with decimal points).
    • Single precision.
    TypeSizeRange
    float4 bytes3.4 x 10^-38 to 3.4 x 10^+38 (6 decimal digits precision)
    float price = 99.99;
    

    3. double (Double Precision Float)

    • Used to store large real numbers with more precision than float.
    TypeSizeRange
    double8 bytes1.7 x 10^-308 to 1.7 x 10^+308 (15 decimal digits precision)
    long double10 bytes3.4 x 10^-4932 to 1.1 x 10^+4932
    double pi = 3.14159265358979;
    

    4. char (Character Type)

    • Used to store a single character (letter, digit, or symbol).
    • Stored as its ASCII value internally.
    TypeSizeRange
    char1 byte-128 to 127 (signed)
    unsigned char1 byte0 to 255
    char grade = 'A';
    

    Summary Table

    Data TypeSizeRange
    int2/4 bytes-32,768 to 32,767 / -2,147,483,648 to 2,147,483,647
    float4 bytes3.4e-38 to 3.4e+38
    double8 bytes1.7e-308 to 1.7e+308
    char1 byte-128 to 127

    Note: The exact size may vary depending on the compiler and system architecture (32-bit or 64-bit).

  12. 125 marksUnion definition and initializationAnswer

    Write short notes on: a) Union b) Switch statement [0+2.5+2.5]

    A union is a user-defined data type in C that allows storing different data types in the same memory location. All members of a union share the same memory space, and the size of the union is equal to the size of its largest member. Synt...