2078

BIT102 · TU past paper

C Programming 2078 question paper

The complete TU 2078 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 marksOperator precedence and associativityAnswer

    What is an expression and operator? Discuss operator associativity in C.Write a program to find factorial of a given integer using recursion.[5+5]

    Expression, Operator, Operator Associativity in C + Factorial Using Recursion


    (a) Expression and Operator

    Expression

    An expression in C is a valid combination of operands (variables, constants) and operators that evaluates to a single value.

    Examples:

    ExpressionType
    a + b * cArithmetic expression
    x > yRelational expression
    a = 10Assignment expression
    a && bLogical expression

    Operator

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

    Types of Operators in C:

    TypeOperatorsExample
    Arithmetic+, -, *, /, %a + b
    Relational<, >, <=, >=, ==, !=a > b
    Logical&&, ||, !a && b
    Assignment=, +=, -=, *=a = 5
    Unary++, --, -a++
    Bitwise&, |, ^, ~a & b
    Conditional? :a>b ? a : b

    Operator Associativity

    Associativity defines the direction of evaluation when two or more operators of the same precedence appear in a single expression. It resolves ambiguity in such expressions.

    There are two types:

    • Left to Right (L to R): Evaluation proceeds from left side to right side
    • Right to Left (R to L): Evaluation proceeds from right side to left side

    Associativity Table:

    Operator TypeOperatorsAssociativity
    Unary++, --, !, - (unary)Right to Left
    Arithmetic (high)*, /, %Left to Right
    Arithmetic (low)+, -Left to Right
    Relational<, >, <=, >=Left to Right
    Equality==, !=Left to Right
    Logical AND&&Left to Right
    Logical OR||Left to Right
    Assignment=, +=, -=, *=Right to Left

    Example 1 (Left to Right):

    10 - 4 - 2
    = (10 - 4) - 2    // Left to Right
    = 6 - 2
    = 4
    

    Example 2 (Right to Left):

    a = b = c = 5;
    // Evaluated as: a = (b = (c = 5))
    // c = 5 first, then b = 5, then a = 5
    

    Conclusion: Associativity ensures that expressions with operators of equal precedence are evaluated in a well-defined, unambiguous order.


    (b) Program to Find Factorial Using Recursion

    Concept of Recursion

    Recursion is a programming technique where a function calls itself repeatedly to solve a smaller sub-problem, until a base condition is reached that stops further calls.

    Factorial Definition:

    factorial(n) = n × factorial(n-1),   for n > 1
    factorial(0) = 1                      (base case)
    factorial(1) = 1                      (base case)
    

    C Program

    #include <stdio.h>
    
    // Recursive function to calculate factorial
    int factorial(int n) {
        if (n == 0 || n == 1)       // Base condition
            return 1;
        else
            return n * factorial(n - 1);  // Recursive call
    }
    
    int main() {
        int num;
        printf("Enter a positive integer: ");
        scanf("%d", &num);
    
        if (num < 0)
            printf("Factorial is not defined for negative numbers.");
        else
            printf("Factorial of %d = %d\n", num, factorial(num));
    
        return 0;
    }
    

    Sample Output

    Enter a positive integer: 5
    Factorial of 5 = 120
    

    Trace of Recursive Calls for n = 5

    factorial(5)
      = 5 × factorial(4)
            = 4 × factorial(3)
                  = 3 × factorial(2)
                        = 2 × factorial(1)
                              = 1  (base case)
                        = 2 × 1 = 2
                  = 3 × 2 = 6
            = 4 × 6 = 24
      = 5 × 24 = 120
    

    Final Result: 5! = 120


    Key Point: Every recursive function must have a base case to prevent infinite recursion and stack overflow.

  2. 210 marksRules for naming valid identifiersAnswer

    What is an Identifier and Keyword? Explain the rules for naming valid Identifiers in C with example.Write a program to convert a given string to lowercase without using any library functions.[5+5]

    Identifiers and Keywords in C

    Identifiers

    An identifier is a name given to various program elements such as variables, functions, arrays, structures, and user-defined types. Identifiers are used to uniquely identify a program element within its scope.

    Example:

    int age;          // 'age' is an identifier
    float salary;     // 'salary' is an identifier
    void display();   // 'display' is an identifier
    

    Keywords

    A keyword is a reserved word that has a predefined meaning in the C language. Keywords cannot be used as identifiers. C has 32 keywords.

    Examples of Keywords:

    intfloatcharif
    elsewhileforreturn
    voidstructswitchbreak

    Rules for Naming Valid Identifiers in C

    1. Letters, digits, and underscore only: An identifier can only contain alphabets (A-Z, a-z), digits (0-9), and underscore ( _ ).

    2. Must begin with a letter or underscore: An identifier cannot start with a digit.

    3. No spaces allowed: Spaces are not permitted inside an identifier.

    4. Keywords not allowed: Reserved keywords cannot be used as identifiers.

    5. Case sensitive: Age and age are treated as different identifiers.

    6. No special characters: Characters like @, #, $, !, etc. are not allowed.

    7. Length: Typically, the first 31 characters are significant (as per ANSI C standard).

    Examples:

    IdentifierValid/InvalidReason
    ageValidStarts with letter
    _salaryValidStarts with underscore
    total_marksValidLetters and underscore
    var1ValidLetter followed by digit
    1varInvalidStarts with digit
    my varInvalidContains space
    intInvalidReserved keyword
    my@nameInvalidSpecial character @

    Program to Convert a String to Lowercase Without Library Functions

    #include <stdio.h>
    
    int main() {
        char str[100];
        int i;
    
        printf("Enter a string: ");
        gets(str);   /* read the string */
    
        /* Convert each character to lowercase */
        for (i = 0; str[i] != '\0'; i++) {
            /* Check if character is uppercase (A=65, Z=90 in ASCII) */
            if (str[i] >= 'A' && str[i] <= 'Z') {
                /* Add 32 to convert uppercase to lowercase */
                str[i] = str[i] + 32;
            }
        }
    
        printf("Lowercase string: %s\n", str);
    
        return 0;
    }
    

    Sample Output:

    Enter a string: Hello WORLD
    Lowercase string: hello world
    

    Logic Explanation:

    • In ASCII, uppercase letters range from 65 ('A') to 90 ('Z').
    • Lowercase letters range from 97 ('a') to 122 ('z').
    • The difference between any uppercase letter and its lowercase equivalent is 32.
    • So, adding 32 to an uppercase character converts it to lowercase.
    • For example: 'A' (65) + 32 = 97 = 'a'
    • Characters that are already lowercase or non-alphabetic are left unchanged.
  3. 310 marksBasic data types and their rangesAnswer

    What different data types available in C along with their respective range?Write a program to check whether a given integer is palindrome or not.[5+5]

    Data Types in C with Their Ranges

    (a) Data Types in C

    A data type defines the type of data a variable can hold, the amount of memory allocated, and the operations that can be performed on it.

    Primary (Fundamental) Data Types in C

    Data TypeSizeRange
    char1 byte-128 to 127
    unsigned char1 byte0 to 255
    int2 or 4 bytes-32,768 to 32,767 (2 bytes) / -2,147,483,648 to 2,147,483,647 (4 bytes)
    unsigned int2 or 4 bytes0 to 65,535 (2 bytes) / 0 to 4,294,967,295 (4 bytes)
    short int2 bytes-32,768 to 32,767
    long int4 bytes-2,147,483,648 to 2,147,483,647
    unsigned long int4 bytes0 to 4,294,967,295
    float4 bytes3.4E-38 to 3.4E+38 (6 decimal digits precision)
    double8 bytes1.7E-308 to 1.7E+308 (15 decimal digits precision)
    long double10 bytes3.4E-4932 to 1.1E+4932
    void0 bytesNo value

    Classification of Data Types

    Data Types in C
    ├── Primary (Basic)
    │   ├── int
    │   ├── char
    │   ├── float
    │   ├── double
    │   └── void
    ├── Derived
    │   ├── Array
    │   ├── Pointer
    │   └── Function
    └── User Defined
        ├── struct
        ├── union
        └── enum
    

    (b) Program to Check Palindrome Integer

    Concept

    A number is called a palindrome if it reads the same forwards and backwards.

    • Example: 121, 1331, 12321 are palindromes
    • Example: 123, 456 are NOT palindromes

    Algorithm

    1. Read the integer n
    2. Store original number in original
    3. Reverse the digits of n to get reversed
    4. If original == reversed, it is a palindrome
    5. Otherwise, it is not a palindrome

    C Program

    #include <stdio.h>
    
    int main() {
        int n, original, reversed = 0, remainder;
    
        printf("Enter an integer: ");
        scanf("%d", &n);
    
        original = n;
    
        /* Handle negative numbers - negative numbers are not palindromes */
        if (n < 0) {
            printf("%d is NOT a palindrome.\n", n);
            return 0;
        }
    
        /* Reverse the digits of the number */
        while (n != 0) {
            remainder = n % 10;       /* Extract last digit */
            reversed = reversed * 10 + remainder;  /* Build reversed number */
            n = n / 10;               /* Remove last digit */
        }
    
        /* Check if original and reversed are equal */
        if (original == reversed) {
            printf("%d is a PALINDROME.\n", original);
        } else {
            printf("%d is NOT a PALINDROME.\n", original);
        }
    
        return 0;
    }
    

    Dry Run / Trace (for n = 121)

    Iterationnremainder (n%10)reversed
    Start121-0
    1st1210*10+1 = 1
    2nd121*10+2 = 12
    3rd0112*10+1 = 121
    • original = 121, reversed = 121
    • Since 121 == 121, it is a PALINDROME

    Sample Output

    Enter an integer: 121
    121 is a PALINDROME.
    
    Enter an integer: 123
    123 is NOT a PALINDROME.
    
  4. 45 marksBreak and continue statementsAnswer

    How break statement is different from continue statement. Explain with examples? [5]

    The break statement is used to immediately terminate the loop (or switch) in which it appears. When break is executed, the program control jumps to the first statement after the loop. Output: The loop stops completely when i == 5. --- Th...

  5. 55 marksBasic structure of C programAnswer

    What is the basic structure of a C program? Explain each part. [5]

    Basic Structure of a C Program


    Basic Structure of a C Program

    A C program is organized into several distinct sections. Below is the general template:

    /* Documentation Section */
    // Program description, author, date
    
    /* Link Section (Header Files) */
    #include <stdio.h>
    #include <conio.h>
    
    /* Definition Section (Macros/Constants) */
    #define PI 3.14159
    
    /* Global Declaration Section */
    int globalVar;
    
    /* Main Function */
    int main()
    {
        /* Local Declaration */
        int a, b;
    
        /* Executable Statements */
        printf("Hello, World!\n");
    
        return 0;
    }
    
    /* User-Defined Functions */
    void myFunction()
    {
        // function body
    }
    

    Explanation of Each Part

    1. Documentation Section

    • Contains comments about the program such as program name, author, date, and purpose.
    • Written using /* ... */ (multi-line) or // (single-line).
    • Ignored by the compiler; meant for human readability.
    • Contains preprocessor directives that include standard library header files.
    • Syntax: #include <filename.h>
    • Example: #include <stdio.h> includes standard input/output functions like printf() and scanf().
    • These are processed before compilation.

    3. Definition Section

    • Used to define symbolic constants or macros using #define.
    • Example: #define PI 3.14159
    • The preprocessor replaces every occurrence of PI with 3.14159 before compilation.

    4. Global Declaration Section

    • Variables declared here are global variables, accessible throughout the entire program.
    • Declared outside all functions.
    • They retain their value for the entire lifetime of the program.

    5. Main Function main()

    • Every C program must have exactly one main() function -- it is the entry point of execution.
    • Contains two parts:
      • Local Declaration: Variables declared inside main(), accessible only within it.
      • Executable Statements: The actual logic -- assignments, function calls, loops, etc.
    • Returns an integer value to the operating system (return 0 indicates successful execution).

    6. User-Defined Functions

    • Functions written by the programmer to perform specific tasks.
    • Defined after (or before) main().
    • Promotes modularity and code reusability.

    Summary Table

    SectionPurpose
    DocumentationComments and program description
    Link SectionIncludes header/library files
    Definition SectionDefines constants and macros
    Global DeclarationDeclares global variables
    main() FunctionEntry point; contains program logic
    User-Defined FunctionsCustom functions for specific tasks
  6. 65 marksMulti-dimensional arraysAnswer

    What do you mean by multi-dimensional array? Write a program to display the sum of two mxn matrices. [5]

    Multi-Dimensional Array

    Definition

    A multi-dimensional array is an array that has more than one dimension (index). It can be thought of as an array of arrays. The most common form is the two-dimensional (2D) array, which represents data in rows and columns (like a matrix).

    General syntax in C:

    data_type array_name[size1][size2]...[sizeN];
    

    For a 2D array (matrix):

    int matrix[m][n];  // m rows and n columns
    

    Elements are accessed using two indices: matrix[i][j] where i is the row index and j is the column index.


    Program to Display the Sum of Two M x N Matrices

    #include <stdio.h>
    
    int main() {
        int m, n, i, j;
        int A[10][10], B[10][10], C[10][10];
    
        // Input dimensions
        printf("Enter number of rows (m): ");
        scanf("%d", &m);
        printf("Enter number of columns (n): ");
        scanf("%d", &n);
    
        // Input elements of matrix A
        printf("\nEnter elements of Matrix A (%dx%d):\n", m, n);
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                printf("A[%d][%d]: ", i, j);
                scanf("%d", &A[i][j]);
            }
        }
    
        // Input elements of matrix B
        printf("\nEnter elements of Matrix B (%dx%d):\n", m, n);
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                printf("B[%d][%d]: ", i, j);
                scanf("%d", &B[i][j]);
            }
        }
    
        // Calculate sum: C = A + B
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                C[i][j] = A[i][j] + B[i][j];
            }
        }
    
        // Display the result matrix C
        printf("\nSum Matrix C = A + B:\n");
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                printf("%d\t", C[i][j]);
            }
            printf("\n");
        }
    
        return 0;
    }
    

    Sample Output

    Enter number of rows (m): 2
    Enter number of columns (n): 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
    
    Sum Matrix C = A + B:
    6    8
    10   12
    

    Key Points

    ConceptDetail
    Declarationint A[10][10] declares a 2D array
    AccessA[i][j] accesses element at row i, column j
    Nested loopsOuter loop for rows, inner loop for columns
    Addition ruleC[i][j] = A[i][j] + B[i][j] for each element
  7. 75 marksFile creation and copyingAnswer

    Write a program to create a file "duplicate" that contains the exact copy of file "original". [5]

    --- Step Description ------------------- fopen("original", "r") Opens the source file "original" in read mode fopen("duplicate", "w") Creates/opens the destination file "duplicate" in write mode NULL check Verifies files opened successfu...

  8. 85 marksFormatted input outputAnswer

    Explain any four input/output functions used in C language with suitable example [5]

    --- C language provides several built-in I/O functions through the header file <stdio.h (Standard Input/Output Header). --- Used to display/print output to the standard output (screen). Syntax: Example: Output: My age is 20 --- Used to r...

  9. 95 marksPattern generation using arraysAnswer

    Write a program to generate the following pattern of integers.

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

    [5]

    Pattern Generation Program

    Pattern Analysis

    Looking at the pattern carefully:

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

    Each row i prints numbers from 1 to i, then back from i-1 to 1.


    C Program

    #include <stdio.h>
    
    int main() {
        int n, i, j;
    
        printf("Enter the number of rows: ");
        scanf("%d", &n);
    
        for (i = 1; i <= n; i++) {
            /* Print increasing part: 1 to i */
            for (j = 1; j <= i; j++) {
                printf("%d ", j);
            }
    
            /* Print decreasing part: i-1 down to 1 */
            for (j = i - 1; j >= 1; j--) {
                printf("%d ", j);
            }
    
            printf("\n");
        }
    
        return 0;
    }
    

    Output (for n = 5)

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

    Step-by-Step Explanation

    Row (i)Increasing PartDecreasing PartFull Row
    11(none)1
    21 211 2 1
    31 2 32 11 2 3 2 1
    41 2 3 43 2 11 2 3 4 3 2 1
    51 2 3 4 54 3 2 11 2 3 4 5 4 3 2 1

    Logic Summary:

    • Outer loop controls the row number i from 1 to n
    • First inner loop prints j from 1 to i (ascending)
    • Second inner loop prints j from i-1 to 1 (descending)
    • Total numbers in row i = 2i - 1
  10. 105 marksFinding smallest element using pointersAnswer

    Write a program to find smallest element of an array using a pointer. [5]

    --- --- Concept Description ------ ptr = arr Pointer assigned the base address of the array ptr Dereferences pointer to get the value at that address ptr++ Moves pointer to the next array element (next memory location) smallest Stores th...

  11. 115 marksStoring and displaying structure dataAnswer

    Write a program to store and display basic information (Roll, name, address, email. and phone) of students of using a structure. [5]

    Program to Store and Display Student Information Using Structure

    Concept

    A structure in C is a user-defined data type that groups related variables of different data types under a single name.


    C Program

    #include <stdio.h>
    #include <string.h>
    
    // Define the structure
    struct Student {
        int roll;
        char name[50];
        char address[100];
        char email[50];
        char phone[15];
    };
    
    int main() {
        int i, n;
    
        printf("Enter number of students: ");
        scanf("%d", &n);
    
        // Declare an array of structures
        struct Student s[n];
    
        // Input student information
        for (i = 0; i < n; i++) {
            printf("\n--- Enter details for Student %d ---\n", i + 1);
    
            printf("Roll Number : ");
            scanf("%d", &s[i].roll);
    
            printf("Name        : ");
            getchar();  // clear input buffer
            fgets(s[i].name, sizeof(s[i].name), stdin);
            s[i].name[strcspn(s[i].name, "\n")] = '\0';  // remove newline
    
            printf("Address     : ");
            fgets(s[i].address, sizeof(s[i].address), stdin);
            s[i].address[strcspn(s[i].address, "\n")] = '\0';
    
            printf("Email       : ");
            fgets(s[i].email, sizeof(s[i].email), stdin);
            s[i].email[strcspn(s[i].email, "\n")] = '\0';
    
            printf("Phone       : ");
            fgets(s[i].phone, sizeof(s[i].phone), stdin);
            s[i].phone[strcspn(s[i].phone, "\n")] = '\0';
        }
    
        // Display student information
        printf("\n========== Student Information ==========\n");
        for (i = 0; i < n; i++) {
            printf("\nStudent %d:\n", i + 1);
            printf("  Roll Number : %d\n",   s[i].roll);
            printf("  Name        : %s\n",   s[i].name);
            printf("  Address     : %s\n",   s[i].address);
            printf("  Email       : %s\n",   s[i].email);
            printf("  Phone       : %s\n",   s[i].phone);
        }
    
        return 0;
    }
    

    Sample Output

    Enter number of students: 2
    
    --- Enter details for Student 1 ---
    Roll Number : 101
    Name        : Ram Sharma
    Address     : Kathmandu
    Email       : [email protected]
    Phone       : 9841000001
    
    --- Enter details for Student 2 ---
    Roll Number : 102
    Name        : Sita Thapa
    Address     : Pokhara
    Email       : [email protected]
    Phone       : 9841000002
    
    ========== Student Information ==========
    
    Student 1:
      Roll Number : 101
      Name        : Ram Sharma
      Address     : Kathmandu
      Email       : [email protected]
      Phone       : 9841000001
    
    Student 2:
      Roll Number : 102
      Name        : Sita Thapa
      Address     : Pokhara
      Email       : [email protected]
      Phone       : 9841000002
    

    Key Points

    FeatureDetail
    struct StudentUser-defined structure with 5 members
    struct Student s[n]Array of structures to store multiple students
    s[i].rollDot operator used to access structure members
    fgets()Used to read strings with spaces
  12. 125 marksComments and escape sequencesAnswer

    Write Short Notes on: a) Escape Sequence Write Short Notes on: b) Null Pointer [2.5+2.5]

    --- An escape sequence is a combination of characters that begins with a backslash () followed by one or more characters. It is used to represent certain special, non-printable, or reserved characters within a string or character litera...