2081.2

BIT102 · TU past paper

C Programming 2081.2 question paper

The complete TU 2081.2 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 marksOdd loopsAnswer

    Define odd loop. What do you mean by goto and label? Write a program to generate the following pattern.

    1
    2 2
    3 3 3
    4 4 4 4
    

    [10]

    Answer: Odd Loop, Goto & Label, and Pattern Program


    A. Odd Loop

    An odd loop is a loop in which the number of iterations is not known in advance at compile time. The loop continues or terminates based on a condition that is evaluated at runtime, often depending on user input or some external event.

    Key Characteristics:

    • The exact number of repetitions is unpredictable before execution
    • The loop termination depends on a runtime condition
    • Common in interactive programs (e.g., "do you want to continue?")

    Example:

    #include <stdio.h>
    int main() {
        char ch = 'y';
        int data;
        while (ch == 'y') {
            printf("Enter a number: ");
            scanf("%d", &data);
            printf("You entered: %d\n", data);
            printf("Continue? (y/n): ");
            scanf(" %c", &ch);
        }
        return 0;
    }
    

    Here, the loop may run 1 time or 100 times depending on user response.


    B. Goto and Label

    goto Statement

    goto is an unconditional branching statement in C that transfers program control directly to a specified labeled statement, without evaluating any condition.

    Syntax:

    goto label_name;
    

    Label

    A label is a user-defined identifier followed by a colon (:) that marks a specific position in the program to which control can be transferred using goto.

    Syntax:

    label_name:
        statement;
    

    Key Points:

    • The goto and its corresponding label must be in the same function
    • It causes an unconditional jump to the labeled statement
    • Overuse of goto leads to spaghetti code (unstructured, hard to read/debug)
    • Generally avoided in modern structured programming

    Example:

    #include <stdio.h>
    int main() {
        printf("Hello\n");
        goto skip;
        printf("This line is skipped\n");   // never executes
        skip:
        printf("World\n");
        return 0;
    }
    

    Output:

    Hello
    World
    

    C. Program to Generate the Pattern

    Required Pattern:

    1
    2 2
    3 3 3
    4 4 4 4
    5 5 5 5 5
    

    (The pattern shows each number i printed exactly i times on row i)

    Program in C:

    #include <stdio.h>
    int main() {
        int i, j;
        for (i = 1; i <= 5; i++) {
            for (j = 1; j <= i; j++) {
                printf("%d ", i);
            }
            printf("\n");
        }
        return 0;
    }
    

    Explanation:

    ComponentPurpose
    Outer loop i (1 to 5)Controls the row number
    Inner loop j (1 to i)Controls how many times i is printed
    printf("%d ", i)Prints the current row number
    printf("\n")Moves to the next line after each row

    Dry Run:

    ij runsOutput
    1j = 11
    2j = 1, 22 2
    3j = 1, 2, 33 3 3
    4j = 1, 2, 3, 44 4 4 4
    5j = 1, 2, 3, 4, 55 5 5 5 5

    Final Output:

    1
    2 2
    3 3 3
    4 4 4 4
    5 5 5 5 5
    

    Conclusion:

    • An odd loop handles unknown iteration counts at runtime
    • goto provides unconditional jump to a label within the same function, but should be used sparingly
    • Nested for loops are the standard and efficient approach for generating number patterns like the one above
  2. 210 marksCall by reference for swappingAnswer

    When do we need external function?Illustrate the process of swapping the value of two variables using the concept of pass by value and pass by reference.[3+7]

    External Functions, Pass by Value and Pass by Reference


    When Do We Need External Functions? [3 Marks]

    We need external functions in the following situations:

    1. Code Reusability: When the same block of code needs to be used in multiple programs or multiple source files, we define it as an external function so it can be called from anywhere without rewriting.

    2. Large Program Management: When a program becomes too large to manage in a single file, it is split into multiple source files. Functions defined in one file and used in another are external functions. The extern keyword is used to declare such functions.

    3. Modular Programming: When we want to divide a program into independent modules (separate .c files), each module may contain functions that are needed by other modules. These are accessed as external functions.

    In short: External functions are needed when a function defined in one source file must be accessed and used in another source file, enabling multi-file, modular program development.


    Swapping Two Variables [7 Marks]

    Concept Overview

    MethodDescription
    Pass by ValueA copy of the variable is passed. Changes inside the function do NOT affect the original variables.
    Pass by ReferenceThe address (pointer) of the variable is passed. Changes inside the function DO affect the original variables.

    1. Swapping Using Pass by Value

    #include <stdio.h>
    
    void swap(int a, int b) {
        int temp;
        temp = a;
        a = b;
        b = temp;
        printf("Inside function: a = %d, b = %d\n", a, b);
    }
    
    int main() {
        int x = 10, y = 20;
        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:

    Before swap: x = 10, y = 20
    Inside function: a = 20, b = 10
    After swap: x = 10, y = 20
    

    Explanation:

    main()                  swap(a, b)
    -------                 ----------
    x = 10  ---copy--->    a = 10
    y = 20  ---copy--->    b = 20
    
    Inside swap:
    temp = a = 10
    a = b = 20
    b = temp = 10
    
    But x and y in main() remain UNCHANGED
    because only copies were passed.
    

    Conclusion: Pass by value fails to swap the original variables. The swap happens only on local copies.


    2. Swapping Using Pass by Reference

    #include <stdio.h>
    
    void swap(int *a, int *b) {
        int temp;
        temp = *a;
        *a = *b;
        *b = temp;
    }
    
    int main() {
        int x = 10, y = 20;
        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:

    Before swap: x = 10, y = 20
    After swap: x = 20, y = 10
    

    Explanation (Step by Step):

    main() memory:
    x = 10  (address: 1000)
    y = 20  (address: 1004)
    
    Call: swap(&x, &y)
      --> a = 1000 (pointer to x)
      --> b = 1004 (pointer to y)
    
    Inside swap():
    Step 1: temp = *a  --> temp = 10
    Step 2: *a   = *b  --> value at 1000 = 20  (x becomes 20)
    Step 3: *b   = temp --> value at 1004 = 10  (y becomes 10)
    
    Back in main():
    x = 20, y = 10  (ACTUALLY SWAPPED)
    

    Conclusion: Pass by reference successfully swaps the original variables because the function works directly on the memory addresses of x and y.


    Key Difference Summary

    FeaturePass by ValuePass by Reference
    What is passedCopy of valueAddress of variable
    Original variable changed?NoYes
    Swap successful?NoYes
    Syntaxswap(x, y)swap(&x, &y)
    Parameter typeint a, int bint *a, int *b
  3. 310 marksFgets and fgetc functionsAnswer

    Differentiate between fgets() and fgetc(). What is the task of typedef? Write a program to define a structure Book with data members name, price and author. Display the names of the book having price greater than 1000.[10]

    Feature fgets() fgetc() --------- Purpose Reads a string (line) from a file Reads a single character from a file Syntax fgets(str, n, fp) fgetc(fp) Return Type Returns char (pointer to string) Returns int (character as integer) Parameter...

  4. 45 marksFlowchart designAnswer

    Write an algorithm and flowchart to test whether the given integer is odd or even. [5]

    --- Problem: Given an integer N, determine whether it is odd or even. Step 1: START Step 2: Read the integer N Step 3: Check if N MOD 2 = 0 (i.e., divide N by 2 and check the remainder) Step 4: If the remainder is 0, then print "N is Eve...

  5. 55 marksTokens and statementsAnswer

    Define token. Describe any three types of statements. [5]

    A token is the smallest meaningful unit in a programming language that the lexical analyzer (scanner) recognizes during the compilation process. Tokens are the basic building blocks of a program, produced by breaking the source code into...

  6. 65 marksString functions from string.hAnswer

    List any five types of functions for string manipulation with their uses. [5]

    --- S.N. Function Use / Purpose ------------------------------- 1 strlen() Returns the length of a string (number of characters excluding null character \0) 2 strcpy() Copies one string into another string 3 strcat() Concatenates (joins/...

  7. 75 marksType conversion and castingAnswer

    What is the task of sizeof and comma operator? Discuss about type conversion. [5]

    --- The sizeof operator is a compile-time unary operator that returns the size (in bytes) of a variable or data type. Syntax: Tasks of sizeof: - Determines the number of bytes occupied by a data type or variable in memory. - Helps write ...

  8. 85 marksDifferences between structure and unionAnswer

    What is union? Differentiate between pointer and array. [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. ...

  9. 95 marksComparison of switch and if else ladderAnswer

    Differentiate between switch statement and if else if ladder. [5]

    A series of if, else if, and else blocks used to test multiple conditions sequentially. Syntax: --- A multi-way branching statement that tests a variable against a list of constant values (cases). Syntax: --- Feature Switch Statement If-...

  10. 105 marksLogical operatorsAnswer

    Give any two types of logical operators. What are formatted and unformatted I/O means? [5]

    Note: No specific reference notes were found for this topic. The answer below is based on standard C programming curriculum as taught in TU BSc CSIT. --- Logical operators are used to combine or negate conditional expressions and return ...

  11. 115 marksPreprocessor directivesAnswer

    Define pre-processor. How do you pass pointer as argument? [5]

    Pre-processor and Passing Pointer as Argument


    Pre-processor

    A pre-processor is a program (or phase of compilation) that processes the source code before it is passed to the compiler. It handles directives that begin with the # symbol.

    Key features:

    • It performs text substitution and file inclusion
    • It does not understand C syntax; it works purely on text
    • Pre-processor directives are not C statements (no semicolon needed)

    Common pre-processor directives:

    DirectivePurpose
    #includeIncludes header/source files
    #defineDefines macros/constants
    #undefUndefines a macro
    #ifdef / #ifndefConditional compilation
    #endifEnds conditional block

    Example:

    #include <stdio.h>
    #define PI 3.14159
    

    Passing Pointer as Argument

    When a pointer is passed as an argument to a function, the function receives the address of the variable. This allows the function to directly modify the original variable (call by reference).

    Syntax

    return_type function_name(data_type *pointer_parameter);
    

    How it works

    1. Declare a variable and obtain its address using &
    2. Pass the address to the function
    3. Inside the function, use * (dereference operator) to access/modify the value

    Example: Swap two numbers using pointers

    #include <stdio.h>
    
    // Function that accepts pointers as arguments
    void swap(int *a, int *b) {
        int temp;
        temp = *a;   // store value at address a
        *a = *b;     // assign value at b to address a
        *b = temp;   // assign temp to address b
    }
    
    int main() {
        int x = 10, y = 20;
    
        printf("Before swap: x = %d, y = %d\n", x, y);
    
        swap(&x, &y);   // passing addresses of x and y
    
        printf("After swap: x = %d, y = %d\n", x, y);
    
        return 0;
    }
    

    Output

    Before swap: x = 10, y = 20
    After swap: x = 20, y = 10
    

    Key Points

    • &x passes the address of x to the function
    • *a inside the function dereferences the pointer to access the actual value
    • Changes made inside the function reflect in the original variables
    • This is the basis of call by reference in C

    Note: Passing pointers as arguments is more efficient for large data structures (like arrays and structures) since it avoids copying the entire data.

  12. 125 marksTwo-dimensional arraysAnswer

    Write a program to add two 3×3 matrices. [5]

    --- Step Description ------------------- Step 1 Declare three 3x3 integer arrays: A, B, and C Step 2 Use nested for loops to read elements of matrix A Step 3 Use nested for loops to read elements of matrix B Step 4 Add corresponding elem...