2079

BIT102 · TU past paper

C Programming 2079 question paper

The complete TU 2079 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 marksFile creation and copyingAnswer

    List the advantages and disadvantages of global variable. Assume the two data files "numl.txt" and "num2.txt" containing integers. Merge these two files to the third file named " file3.txt". Here, the integers of " file3.t-xt" must be written in sorted order.[10]

    Global Variables & File Merging Program

    Part A: Advantages and Disadvantages of Global Variables

    A global variable is a variable declared outside all functions, making it accessible to every function in the program.


    Advantages

    #AdvantageExplanation
    1Universal AccessibilityAny function can read or modify the variable without receiving it as a parameter
    2Reduced Parameter PassingFunction signatures stay simple; no need to pass shared data repeatedly
    3Easy Data SharingMultiple functions can communicate through a common variable
    4PersistenceThe variable retains its value for the entire lifetime of the program
    5Convenient for ConstantsUseful for program-wide constants or configuration values

    Disadvantages

    #DisadvantageExplanation
    1Uncontrolled AccessAny function can accidentally overwrite the value, causing hard-to-find bugs
    2Namespace PollutionLarge programs with many globals risk naming conflicts
    3Reduced ModularityFunctions depend on external state, making them difficult to reuse
    4Violates Data HidingAll data is exposed, breaking the principle of encapsulation
    5Difficult DebuggingTracking which function changed the value requires checking the entire program

    Part B: Merge Two Files into a Third File in Sorted Order

    Logic / Algorithm

    1. Open num1.txt and read all integers into array a[]
    2. Open num2.txt and read all integers into array b[]
    3. Copy both arrays into a combined array c[]
    4. Sort c[] using Bubble Sort (ascending order)
    5. Open file3.txt for writing
    6. Write every element of sorted c[] into file3.txt
    7. Close all files
    

    Complete C Program

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        FILE *f1, *f2, *f3;
        int a[100], b[100], c[200];
        int n1 = 0, n2 = 0;
        int i, j, k = 0, temp;
    
        /* ---- Step 1: Read integers from num1.txt ---- */
        f1 = fopen("num1.txt", "r");
        if (f1 == NULL)
        {
            printf("Error: Cannot open num1.txt\n");
            exit(1);
        }
        while (fscanf(f1, "%d", &a[n1]) != EOF)
        {
            n1++;
        }
        fclose(f1);
    
        /* ---- Step 2: Read integers from num2.txt ---- */
        f2 = fopen("num2.txt", "r");
        if (f2 == NULL)
        {
            printf("Error: Cannot open num2.txt\n");
            exit(1);
        }
        while (fscanf(f2, "%d", &b[n2]) != EOF)
        {
            n2++;
        }
        fclose(f2);
    
        /* ---- Step 3: Combine both arrays into c[] ---- */
        for (i = 0; i < n1; i++)
            c[k++] = a[i];
    
        for (i = 0; i < n2; i++)
            c[k++] = b[i];
    
        /* ---- Step 4: Sort c[] using Bubble Sort ---- */
        for (i = 0; i < k - 1; i++)
        {
            for (j = 0; j < k - i - 1; j++)
            {
                if (c[j] > c[j + 1])
                {
                    /* Swap */
                    temp    = c[j];
                    c[j]    = c[j + 1];
                    c[j + 1] = temp;
                }
            }
        }
    
        /* ---- Step 5: Write sorted integers to file3.txt ---- */
        f3 = fopen("file3.txt", "w");
        if (f3 == NULL)
        {
            printf("Error: Cannot open file3.txt\n");
            exit(1);
        }
        for (i = 0; i < k; i++)
        {
            fprintf(f3, "%d\n", c[i]);
        }
        fclose(f3);
    
        printf("Merged and sorted successfully into file3.txt\n");
        return 0;
    }
    

    Dry Run Example

    num1.txt contains: 5 2 8 num2.txt contains: 3 1 7

    StepArray State
    After readinga[] = {5, 2, 8}, b[] = {3, 1, 7}
    After combiningc[] = {5, 2, 8, 3, 1, 7}
    After Bubble Sortc[] = {1, 2, 3, 5, 7, 8}
    Written to file3.txt1 2 3 5 7 8 (one per line)

    Key File Handling Functions Used

    FunctionPurpose
    fopen(name, "r")Open file for reading
    fopen(name, "w")Open file for writing
    fscanf(fp, "%d", &x)Read an integer from file
    fprintf(fp, "%d\n", x)Write an integer to file
    fclose(fp)Close the file and flush buffer
    exit(1)Terminate program on error

    Conclusion

    Global variables simplify data sharing but reduce modularity and security, so they should be used carefully. The file merging program demonstrates practical use of fopen(), fscanf(), fprintf() and fclose(), while the bubble sort applied to the combined array guarantees that every integer read from num1.txt and num2.txt is written into file3.txt in ascending order.

  2. 210 marksNested structuresAnswer

    How nested Structure is defined and initialized? Explain with an example.Write a program, using structure, to input records of 10 students. Members include name, roll number, marks obtained in math, C program and English. Display the records of students who have passed in C Program.[4+6]

    (a) Nested Structure - Definition and Initialization A nested structure is a structure that contains another structure as one of its members. In other words, when a struct variable (or definition) is used as a member inside another struc...

  3. 310 marksComparison of while and do whileAnswer

    When do we use for loop and while loop? Compare the while and do while loop with suitable example.Write a program to find average, minimum and maximum age in a class of 20 students.[4+6]

    --- Use a for loop when: - The number of iterations is known in advance - You have a clear initialization, condition, and increment/decrement - Iterating over arrays, ranges, or fixed counts Example: Use a while loop when: - The number o...

  4. 45 marksFlowchart designAnswer

    What do you mean by flowchart? Draw a Flowchart to find the largest among three numbers entered by user. [5]

    Flowchart

    Definition

    A flowchart is a diagrammatic or pictorial representation of an algorithm or a step-by-step solution to a given problem. It uses standard geometric symbols connected by arrows (flow lines) to show the sequence of steps, decisions, and operations required to solve a problem.

    Common Flowchart Symbols

    SymbolShapePurpose
    TerminalOval / Rounded RectangleStart / Stop
    Input/OutputParallelogramRead / Print data
    ProcessRectangleArithmetic / Assignment operations
    DecisionDiamondYes/No or True/False condition
    Flow LinesArrowsDirection of flow

    Flowchart to Find the Largest Among Three Numbers

    Problem: Read three numbers A, B, and C from the user and find the largest among them.

            +----------+
            |  START   |
            +----------+
                 |
                 v
       +------------------+
       |  Read A, B, C    |
       +------------------+
                 |
                 v
           +------------+
           |   Is A > B? |
           +------------+
           /             \
         YES              NO
          |                |
          v                v
      +--------+       +--------+
      |Is A > C?|      |Is B > C?|
      +--------+       +--------+
      /        \       /        \
    YES         NO   YES         NO
     |           |    |           |
     v           v    v           v
    +---+      +---+ +---+      +---+
    | A |      | C | | B |      | C |
    |is |      |is | |is |      |is |
    |Lar|      |Lar| |Lar|      |Lar|
    |gest      |gest |gest      |gest
    +---+      +---+ +---+      +---+
      \           \    /           /
       \           \  /           /
        \           \/           /
         \     +----------+     /
          \    |  Print   |    /
           +-->| Largest  |<--+
               +----------+
                    |
                    v
               +--------+
               |  STOP  |
               +--------+
    

    Clean Step-by-Step Logic

    START
      |
      Read A, B, C
      |
      Is A > B?
      ├── YES --> Is A > C?
      │           ├── YES --> Print "A is Largest"
      │           └── NO  --> Print "C is Largest"
      |
      └── NO  --> Is B > C?
                  ├── YES --> Print "B is Largest"
                  └── NO  --> Print "C is Largest"
      |
    STOP
    

    Example Trace

    ABCA > B?Next CheckResult
    1058YESA > C? (10>8) YESA = 10 is Largest
    396NOB > C? (9>6) YESB = 9 is Largest
    4611NOB > C? (6>11) NOC = 11 is Largest
  5. 55 marksSimilarity between arrays and pointersAnswer

    Why array and pointer is similar? Write a program to show the similarity between an array and pointer. [5]

    In C, arrays and pointers are closely related because: 1. Array name is a pointer: The name of an array acts as a constant pointer to the first element (base address) of the array. 2. Same memory access: Both arrays and pointers can be u...

  6. 65 marksTwo-dimensional arraysAnswer

    Write a program to find the sum of diagonal elements of n*n matrix. [5]

    For an n×n matrix, there are two diagonals: - Principal (Main) Diagonal: elements where row index == column index → a[i][i] - Secondary (Anti) Diagonal: elements where row + column = n-1 → a[i][n-1-i] Note: If an element lies on both dia...

  7. 75 marksBasic data types and their rangesAnswer

    How keyword is different from Variables? Discuss Basic data types with its ranges. [5]

    Aspect Keywords Variables ----------------------------- Definition Reserved words predefined by the programming language Named memory locations used to store data Purpose Have special meaning and perform specific functions in the languag...

  8. 85 marksOperator precedence and associativityAnswer

    What is operator associativity? Explain conditional and Logical operators in brief. [5]

    Operator associativity defines the order in which operators of the same precedence are evaluated in an expression when they appear together. There are two types: Type Direction Example Operators ------------------------------------ Left-...

  9. 95 marksArrays as function argumentsAnswer

    Write a program with a function that takes an array as an argument and returns its sum to the main function. [5]

    --- --- Concept Description ------ Function argument arr[] passes the array by reference (address); size passes the count by value Return value return sum; sends the computed sum back to main() Function declaration Prototype int arraySum...

  10. 105 marksFile inclusionAnswer

    How do you include a file to another file? Illustrate with an example. [5]

    In C programming, the include preprocessor directive is used to include the contents of one file into another file. This is handled by the C preprocessor before actual compilation begins. When the preprocessor encounters include, it repl...

  11. 115 marksPattern generation using arraysAnswer

    Write a program to display the following pattern using the string "NEPAL". NNNNENENENEPNEPNEPNEPANEPANEPANEPALNEPALNEPAL[5]

    The pattern reaches us as the run-on string NNNNENENENEPNEPNEPNEPANEPANEPANEPALNEPALNEPAL, so the first job is to break it back into rows. Splitting it into consecutive prefixes of "NEPAL" gives and joining these five rows back together ...

  12. 125 marksMacros and macro vs functionAnswer

    Write short notes on: a) Macro vs Function Write short notes on: b) Break vs Continue [2.5+2.5]

    Feature Macro Function --------- Definition Defined using define preprocessor directive Defined using return type, name, and body Processing Handled by preprocessor (before compilation) Handled by compiler at compile/run time Execution I...