2080

CSC115 · TU past paper

C Programming 2080 question paper

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

Tap a question to open its answer.

  1. 110 marksUser defined functionsAnswer

    Define structure and nested structure. Write a program to find out whether the $n^{th}$ term of the Fibonacci series is a prime number or not. Read the value of $n$ from the user and display the result in the main function. Use separate user-defined function to (i) generate $n^{th}$ term and (ii) to check whether that number is prime or not.[3+7]

    Structure, Nested Structure, and Fibonacci Prime Program


    (a) Definitions

    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;
        ...
    };
    

    Example:

    struct Student {
        int roll;
        char name[20];
        float marks;
    };
    

    Nested Structure

    A nested structure is a structure that contains another structure as its member. That is, one structure is defined or declared inside another structure.

    Syntax:

    struct Inner {
        data_type member1;
    };
    
    struct Outer {
        data_type member;
        struct Inner obj;   /* nested structure member */
    };
    

    Example:

    struct Date {
        int day;
        int month;
        int year;
    };
    
    struct Student {
        int roll;
        char name[20];
        struct Date dob;    /* nested structure */
    };
    

    Here, struct Date is nested inside struct Student. The member dob is accessed as s.dob.day, s.dob.month, etc.


    (b) Program

    Problem Analysis

    • Read n from the user in main().
    • Call function fibonacci(n) to find the nth term of the Fibonacci series.
    • Call function isPrime(num) to check whether that term is prime or not.
    • Display the result in main().

    Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, ... The 1st term = 0, 2nd term = 1, 3rd term = 1, and so on.


    Complete Program

    #include <stdio.h>
    #include <conio.h>
    
    /* Function to generate the nth term of Fibonacci series */
    int fibonacci(int n)
    {
        int first = 0, second = 1, next, i;
    
        if (n == 1)
            return 0;
        if (n == 2)
            return 1;
    
        for (i = 3; i <= n; i++)
        {
            next = first + second;
            first = second;
            second = next;
        }
        return next;
    }
    
    /* Function to check whether a number is prime or not */
    /* Returns 1 if prime, 0 if not prime */
    int isPrime(int num)
    {
        int i;
    
        if (num <= 1)
            return 0;   /* 0 and 1 are not prime */
    
        for (i = 2; i <= num / 2; i++)
        {
            if (num % i == 0)
                return 0;   /* divisible, so not prime */
        }
        return 1;   /* prime */
    }
    
    /* Main function */
    void main()
    {
        int n, term, result;
    
        clrscr();
    
        printf("Enter the value of n: ");
        scanf("%d", &n);
    
        /* Generate nth Fibonacci term */
        term = fibonacci(n);
        printf("\nThe %dth term of Fibonacci series is: %d\n", n, term);
    
        /* Check if the term is prime */
        result = isPrime(term);
    
        if (result == 1)
            printf("%d is a PRIME number.\n", term);
        else
            printf("%d is NOT a prime number.\n", term);
    
        getch();
    }
    

    Sample Output

    Enter the value of n: 7
    
    The 7th term of Fibonacci series is: 8
    8 is NOT a prime number.
    
    Enter the value of n: 5
    
    The 5th term of Fibonacci series is: 3
    3 is a PRIME number.
    

    Fibonacci Series Reference Table

    nFibonacci Term
    10
    21
    31
    42
    53
    65
    78
    813

    Key Points

    FunctionPurposeReturn Type
    fibonacci(n)Returns the nth Fibonacci termint
    isPrime(num)Returns 1 if prime, 0 if notint
    main()Reads input, calls both functions, displays resultvoid
  2. 210 marksPointers and ArraysAnswer

    Explain the relation to array and pointer.Differentiate between call by value and call by reference with a suitable program.[2+8]

    Relation Between Array and Pointer, and Call by Value vs Call by Reference


    (a) Relation Between Array and Pointer

    In C, there is a strong relationship between arrays and pointers. Any operation that can be achieved by array subscripting can also be done with pointers.

    Key Points:

    • An array name is itself an address (a constant pointer to the first element of the array).
    • Pointers and arrays are almost synonymous in terms of how they are used to access memory.
    • The pointer version of array operations is generally faster but harder to understand for beginners.

    Illustration:

    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr = arr;   // ptr points to the first element of arr
    
    Array NotationPointer NotationMeaning
    arr[0]*ptrFirst element
    arr[1]*(ptr + 1)Second element
    arr[i]*(ptr + i)i-th element
    &arr[i]ptr + iAddress of i-th element

    Important Difference:

    • A pointer is a variable (its value can be changed).
    • An array name is a constant pointer (it always points to the first element and cannot be reassigned).

    (b) Difference Between Call by Value and Call by Reference

    Definition:

    Call by Value: In call by value, a copy of the actual argument is passed to the formal parameter. The called function works on this copy, so any changes made inside the function do not affect the original variable.

    Call by Reference: In call by reference, the address (reference) of the actual argument is passed to the function. The called function works directly on the original data using pointers, so changes made inside the function do affect the original variable.


    Comparison Table:

    FeatureCall by ValueCall by Reference
    What is passedCopy of the valueAddress of the variable
    Effect on original dataNo change in original variableOriginal variable gets modified
    MemorySeparate memory for formal parameterFormal parameter refers to same memory
    Return valuesCan return only one valueCan effectively return multiple values
    SafetySafer (original data protected)Less safe (original data can be changed)
    SpeedSlightly slower (copy is made)Slightly faster (no copy made)
    Mechanism usedNormal variablesPointers

    Program Demonstrating Both:

    #include<stdio.h>
    #include<conio.h>
    
    /* Function prototypes */
    void callByValue(int x);
    void callByReference(int *x);
    
    void main()
    {
        int a = 15;
        int b = 15;
    
        clrscr();
    
        /* Demonstrating Call by Value */
        printf("--- Call by Value ---\n");
        printf("Before calling function, a = %d\n", a);
        callByValue(a);
        printf("After calling function, a = %d\n\n", a);
    
        /* Demonstrating Call by Reference */
        printf("--- Call by Reference ---\n");
        printf("Before calling function, b = %d\n", b);
        callByReference(&b);
        printf("After calling function, b = %d\n", b);
    
        getch();
    }
    
    /* Call by Value: works on a copy */
    void callByValue(int x)
    {
        x = x + 5;
        printf("Inside callByValue function, x = %d\n", x);
    }
    
    /* Call by Reference: works on original via pointer */
    void callByReference(int *x)
    {
        *x = *x + 5;
        printf("Inside callByReference function, *x = %d\n", *x);
    }
    

    Output:

    --- Call by Value ---
    Before calling function, a = 15
    Inside callByValue function, x = 20
    After calling function, a = 15
    
    --- Call by Reference ---
    Before calling function, b = 15
    Inside callByReference function, *x = 20
    After calling function, b = 20
    

    Explanation of Output:

    • In Call by Value: a remains 15 after the function call because only a copy (x) was modified inside the function. The original variable a is not affected.

    • In Call by Reference: b becomes 20 after the function call because the address of b was passed (&b). Inside the function, *x directly modifies the original variable b. The original variable b is affected.


    Summary: Use call by value when you want to protect the original data. Use call by reference when you want the function to modify the original variable or when you need to return multiple values from a function.

  3. 310 marksArray of structureAnswer

    Differentiate between source code and object code.Create a structure named Book which remembers Book_Name, Price and Author. Then, make the list of top 10 records of book and print the name of authors having the price of book greater than 1000.[3+7]

    Answer

    (a) Difference Between Source Code and Object Code

    BasisSource CodeObject Code
    DefinitionThe program written by a programmer in a high-level language (e.g., C) that is human-readableThe machine-level code generated by the compiler after translating the source code
    ReadabilityEasily readable and understandable by humansNot directly readable by humans; consists of binary/machine instructions
    File ExtensionStored as .c (in C language)Stored as .obj or .o file
    ProcessingCannot be directly executed by the CPUPassed to the linker to produce an executable file
    Error DetectionSyntax errors are detected at this stage during compilationNo syntax errors; errors at this stage are linking errors
    GenerationWritten manually by the programmerAutomatically generated by the compiler

    Flow (from notes):

    source.c --> Compiler --> source.obj --> Linker --> source.exe --> Output
    

    (b) Structure Book with Top 10 Records

    Problem Analysis

    • Define a structure Book with fields: Book_Name, Price, Author
    • Store 10 book records
    • Print the names of authors whose book price is greater than 1000

    Program

    #include <stdio.h>
    #include <conio.h>
    
    /* Define the structure Book */
    struct Book {
        char Book_Name[50];
        float Price;
        char Author[50];
    };
    
    void main() {
        int i;
    
        /* Declare an array of 10 Book structures */
        struct Book books[10];
    
        clrscr();
    
        /* Input 10 book records */
        printf("Enter details of 10 books:\n");
        for (i = 0; i < 10; i++) {
            printf("\n--- Book %d ---\n", i + 1);
    
            printf("Enter Book Name  : ");
            scanf(" %[^\n]", books[i].Book_Name);
    
            printf("Enter Author Name: ");
            scanf(" %[^\n]", books[i].Author);
    
            printf("Enter Price      : ");
            scanf("%f", &books[i].Price);
        }
    
        /* Print authors whose book price is greater than 1000 */
        printf("\n\nAuthors with Book Price greater than 1000:\n");
        printf("--------------------------------------------\n");
    
        for (i = 0; i < 10; i++) {
            if (books[i].Price > 1000) {
                printf("Author: %s  |  Book: %s  |  Price: %.2f\n",
                       books[i].Author,
                       books[i].Book_Name,
                       books[i].Price);
            }
        }
    
        getch();
    }
    

    Sample Output

    Enter details of 10 books:
    
    --- Book 1 ---
    Enter Book Name  : Let Us C
    Enter Author Name: Yashavant Kanetkar
    Enter Price      : 850
    
    --- Book 2 ---
    Enter Book Name  : The C Programming Language
    Enter Author Name: Dennis Ritchie
    Enter Price      : 1200
    
    --- Book 3 ---
    Enter Book Name  : Data Structures
    Enter Author Name: Seymour Lipschutz
    Enter Price      : 1500
    ...
    
    Authors with Book Price greater than 1000:
    --------------------------------------------
    Author: Dennis Ritchie   |  Book: The C Programming Language  |  Price: 1200.00
    Author: Seymour Lipschutz|  Book: Data Structures             |  Price: 1500.00
    

    Explanation of Key Steps

    1. Structure Declaration: struct Book is defined with three members:

      • Book_Name[50] -- stores the title
      • Price -- stores the price as float
      • Author[50] -- stores the author name
    2. Array of Structures: struct Book books[10] creates a list of 10 book records.

    3. Input Loop: A for loop runs from i = 0 to i < 10 to accept all 10 records using scanf.

    4. Condition Check: A second for loop checks if (books[i].Price > 1000) and prints the author name if the condition is true.

  4. 45 marksInput Output Operations in FileAnswer

    Describe the different types of I/O functions used in file handling with syntax. [5]

    File handling in C provides several categories of I/O functions to read from and write to files. These are defined in <stdio.h. --- Used to read/write a single character at a time. Writes a single character to a specified file and increm...

  5. 55 marksTypes of ArrayAnswer

    Write a program to read P*Q matrix of integers and find the largest integer of each row and display it. [5]

    A two-dimensional array is declared as datatype arrayname[row][col]. Processing requires a nested loop where the outer loop corresponds to rows and the inner loop corresponds to columns. Each element can be accessed as a[i][j]. --- 1. St...

  6. 65 marksNested and Recursive FunctionAnswer

    Write a program to calculate the factorial of a given number using recursion. [5]

    A recursive function is a function that calls itself. It must have: 1. Base condition (stopping condition) -- when n == 0, return 1 2. Recursive call -- each call must move closer to the base condition $$n! = \begin{cases} 1 & \text{if }...

  7. 75 marksCharacter Array and StringsAnswer

    Write a program to check whether the entered word is palindrome or not. [5]

    A palindrome is a word (or string) that reads the same forwards and backwards. For example: madam, level, racecar are palindromes. 1. Accept a word (string) from the user. 2. Copy the original string into another variable. 3. Reverse the...

  8. 85 marksUser defined functionsAnswer

    Write a program to compute the sum of first 10 even numbers using function. [5]

    The first 10 even numbers are: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. A separate function evenSum() is defined to compute and return their sum, which is then called from main(). --- --- Iteration i sum (before) sum (after) count -----------...

  9. 95 marksDynamic Memory AllocationAnswer

    What is dynamic memory allocation? Explain with a suitable program. [5]

    Dynamic Memory Allocation

    Definition

    The process of allocating memory at the time of execution (runtime) is called dynamic memory allocation. Unlike static memory allocation where the size is fixed at compile time, dynamic memory allocation allows a program to request and release memory as needed during execution.

    Problems with static allocation (e.g., int emp[100];):

    • If fewer values are stored, memory is wasted
    • If more values are needed, we cannot store them

    Dynamic memory allocation solves both problems. Memory is accessed through pointers, and the functions are available in stdlib.h / alloc.h.


    Key Functions

    FunctionPurpose
    malloc()Allocates a block of memory of specified size
    calloc()Allocates memory and initializes to zero
    realloc()Resizes previously allocated memory
    free()Releases dynamically allocated memory

    Syntax of malloc():

    pointer_variable = (datatype *) malloc(specified_size);
    

    Example Program

    The following program dynamically allocates memory for n integers entered by the user, stores them, and displays them.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int *ptr;
        int n, i;
    
        printf("Enter number of elements: ");
        scanf("%d", &n);
    
        /* Dynamically allocate memory for n integers */
        ptr = (int *) malloc(n * sizeof(int));
    
        /* Check if memory was allocated successfully */
        if (ptr == NULL) {
            printf("Memory allocation failed!\n");
            return 1;
        }
    
        /* Input values */
        printf("Enter %d integers:\n", n);
        for (i = 0; i < n; i++) {
            scanf("%d", &ptr[i]);
        }
    
        /* Display values */
        printf("You entered:\n");
        for (i = 0; i < n; i++) {
            printf("%d ", ptr[i]);
        }
        printf("\n");
    
        /* Release the allocated memory */
        free(ptr);
    
        return 0;
    }
    

    Sample Output

    Enter number of elements: 4
    Enter 4 integers:
    10 20 30 40
    You entered:
    10 20 30 40
    

    Key Points

    • malloc(n * sizeof(int)) allocates exactly the memory needed at runtime
    • The pointer ptr is used to access the dynamically allocated memory block
    • free(ptr) releases the memory back to the system after use
    • If allocation fails, malloc() returns NULL, which should always be checked
  10. 105 marksInitialization of arrayAnswer

    Write a program to initialize an array of dimension 10 and sort the numbers within the array in ascending order. [5]

    The program initializes an array of dimension 10, reads values from the user, and sorts them in ascending order using Bubble Sort. Bubble Sort Logic: Compare adjacent elements; if the left element is greater than the right, swap them. Re...

  11. 115 marksNumericalDecision Making and LoopingAnswer

    Trace the output

    #include <conio.h>
    #include <stdio.h>
    void main() {
    int i = 0, k;
    for (k = 5; k >= 0; k--) {
    i = i + k;
    }
    printf("%d\t", i);
    getch();
    }
    

    [5]

    Initial value: $i = 0$ --- The loop starts at $k = 5$, decrements by 1 each pass, and continues while $k \geq 0$. Iteration $k$ Condition $k \geq 0$ $i = i + k$ New $i$ ------------------------------------------------------------ 1 5 Tru...

  12. 125 marksArithmetic operatorAnswer

    List different types of operators and explain any three of them. [5]

    An operator specifies an operation to be performed on an operand. The variables and constants can be joined by various operators to form expressions. An operand is a data item on which an operator acts. --- C includes the following types...