2077

CSC115 · TU past paper

C Programming 2077 question paper

The complete TU 2077 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 marksDecision Making and LoopingAnswer

    What do you mean by looping?Explain while loop with suitable example.Compare while loop with do while loop.Write a program to find sum and average of first n natural numbers.[1+3+2+4]

    Looping, While Loop, Comparison with Do-While, and Sum/Average of First N Natural Numbers


    1. What is Looping? [1 mark]

    Looping (also called iteration) is a programming concept that allows a set of statements to be executed repeatedly as long as a given condition remains true. Instead of writing the same code multiple times, a loop executes it automatically for the required number of times.

    Loops are used to:

    • Repeat a block of code a fixed number of times
    • Process data until a condition is met
    • Reduce code length and redundancy

    2. While Loop with Example [3 marks]

    Definition

    The while loop is an entry-controlled loop, meaning the condition is checked before executing the body of the loop. If the condition is false at the very beginning, the loop body is never executed.

    Syntax

    while (condition)
    {
        // body of the loop
        // increment / decrement statement
    }
    

    How it works (Execution Steps):

    1. The condition is evaluated first.
    2. If the condition is true, the loop body executes.
    3. After executing the body, control goes back to step 1.
    4. If the condition is false, the loop terminates and control passes to the next statement after the loop.

    Flowchart Description:

    Start --> Check Condition --> [False] --> Exit Loop
                   |
                [True]
                   |
             Execute Body
                   |
             Update Variable
                   |
             (back to Check Condition)
    

    Example: Print numbers 1 to 5

    #include<stdio.h>
    #include<conio.h>
    
    void main()
    {
        int i = 1;          /* initialization */
        clrscr();
    
        while (i <= 5)      /* condition */
        {
            printf("%d\n", i);
            i++;            /* increment */
        }
    
        getch();
    }
    

    Output:

    1
    2
    3
    4
    5
    

    3. Comparison: While Loop vs Do-While Loop [2 marks]

    FeatureWhile LoopDo-While Loop
    TypeEntry-controlled loopExit-controlled loop
    Condition checkChecked before loop body executesChecked after loop body executes
    Minimum executions0 times (if condition is false initially)At least 1 time (body executes before check)
    Syntaxwhile(condition){ }do{ } while(condition);
    SemicolonNo semicolon after conditionSemicolon required after while(condition);
    Use caseWhen execution depends on condition being true firstWhen the loop body must run at least once

    Syntax Comparison:

    While Loop:

    while (condition)
    {
        // statements
    }
    

    Do-While Loop:

    do
    {
        // statements
    } while (condition);
    

    Key Difference Example:

    If the condition is false from the start:

    • while loop: body executes 0 times
    • do-while loop: body executes 1 time

    4. Program to Find Sum and Average of First N Natural Numbers [4 marks]

    Algorithm:

    1. Start
    2. Read the value of n
    3. Initialize sum = 0, i = 1
    4. While i <= n, do:
      • sum = sum + i
      • i = i + 1
    5. Calculate average = sum / n
    6. Display sum and average
    7. Stop

    Program:

    #include<stdio.h>
    #include<conio.h>
    
    void main()
    {
        int i, n, sum;
        float average;
    
        clrscr();
    
        /* Input */
        printf("Enter the value of n: ");
        scanf("%d", &n);
    
        /* Initialize */
        sum = 0;
        i = 1;
    
        /* While loop to calculate sum */
        while (i <= n)
        {
            sum = sum + i;
            i++;
        }
    
        /* Calculate average */
        average = (float) sum / n;
    
        /* Output */
        printf("Sum of first %d natural numbers = %d\n", n, sum);
        printf("Average of first %d natural numbers = %.2f\n", n, average);
    
        getch();
    }
    

    Sample Output (for n = 5):

    Enter the value of n: 5
    Sum of first 5 natural numbers = 15
    Average of first 5 natural numbers = 3.00
    

    Verification (n = 5):

    • Natural numbers: 1, 2, 3, 4, 5
    • Sum = 1 + 2 + 3 + 4 + 5 = 15
    • Average = 15 / 5 = 3.00

    Note: (float) is used to cast the integer sum to float so that the average is computed as a decimal value, not an integer.

  2. 210 marksTypes of ArrayAnswer

    What are the benefits of using arrays?Compare one dimensional array with two dimensional array.Write a program to find transpose of a matrix.[2+2+6]

    --- (a) Benefits of Using Arrays An array is a collection of elements of the same data type stored in contiguous memory locations under a single variable name. Benefits of using arrays: 1. Easy data management: Multiple values of the sam...

  3. 310 marksArray of structureAnswer

    What is structure?How is it different from union?Create a structure named course with name, code and credit_hour as its member.Write a program using this structure to read data of 5 courses and display data of those courses with credit_hour greater than 3.[1+2+2+5]

    Structure in C: Definition, Difference from Union, and Program


    1. What is a Structure? [1 mark]

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

    2. Difference Between Structure and Union [2 marks]

    FeatureStructureUnion
    Keywordstructunion
    Memory AllocationEach member gets its own separate memoryAll members share the same memory
    Total SizeSum of sizes of all membersSize of the largest member only
    AccessAll members can be accessed and used simultaneouslyOnly one member can hold a value at a time
    UsageWhen all members are needed at the same timeWhen only one member is needed at a time (saves memory)

    Example:

    struct S { int a; float b; };   // size = sizeof(int) + sizeof(float) = 6 bytes
    union U  { int a; float b; };   // size = sizeof(float) = 4 bytes (largest member)
    

    3. Structure Named course with Members [2 marks]

    struct course {
        char name[50];
        char code[10];
        int credit_hour;
    };
    
    • name stores the course name
    • code stores the course code
    • credit_hour stores the number of credit hours

    4. Complete Program: Read 5 Courses and Display Those with credit_hour > 3 [5 marks]

    #include<stdio.h>
    #include<conio.h>
    
    struct course {
        char name[50];
        char code[10];
        int credit_hour;
    };
    
    void main() {
        struct course c[5];
        int i;
        clrscr();
    
        /* Reading data for 5 courses */
        for(i = 0; i < 5; i++) {
            printf("\nEnter details for Course %d:\n", i + 1);
    
            printf("Enter Course Name: ");
            scanf("%s", c[i].name);
    
            printf("Enter Course Code: ");
            scanf("%s", c[i].code);
    
            printf("Enter Credit Hour: ");
            scanf("%d", &c[i].credit_hour);
        }
    
        /* Displaying courses with credit_hour greater than 3 */
        printf("\n\nCourses with Credit Hour greater than 3:\n");
        printf("------------------------------------------\n");
        printf("Name\t\tCode\t\tCredit Hour\n");
        printf("------------------------------------------\n");
    
        for(i = 0; i < 5; i++) {
            if(c[i].credit_hour > 3) {
                printf("%s\t\t%s\t\t%d\n", c[i].name, c[i].code, c[i].credit_hour);
            }
        }
    
        getch();
    }
    

    Sample Output:

    Enter details for Course 1:
    Enter Course Name: Mathematics
    Enter Course Code: MTH101
    Enter Credit Hour: 3
    
    Enter details for Course 2:
    Enter Course Name: Physics
    Enter Course Code: PHY101
    Enter Credit Hour: 4
    
    Enter details for Course 3:
    Enter Course Name: C_Programming
    Enter Course Code: CSC101
    Enter Credit Hour: 5
    ...
    
    Courses with Credit Hour greater than 3:
    ------------------------------------------
    Name            Code            Credit Hour
    ------------------------------------------
    Physics         PHY101          4
    C_Programming   CSC101          5
    

    Key Points:

    • struct course c[5] declares an array of structures to hold data of 5 courses.
    • The dot operator (.) is used to access structure members (e.g., c[i].name).
    • A for loop reads data for all 5 courses.
    • A second for loop with an if condition filters and displays only those courses where credit_hour > 3.
  4. 45 marksAlgorithms and FlowchartAnswer

    Explain flowchart with example. What are the benefits of using flowchart? What are the benefits of using flowchart? [3+2]

    (a) Flowchart with Example A flowchart is a diagram that represents an algorithm using standard symbols connected by arrows. It shows the flow of control from start to end in a visual, step-by-step manner. Symbol Shape Purpose ----------...

  5. 55 marksData typesAnswer

    What is data type? Why do we need it in programming? Explain any three basic data types with example. [1+1+3]

    Data Types in C Programming

    What is a Data Type? [1 mark]

    A data type defines the type of data that a variable can store, the amount of memory it occupies, and the range of values it can hold. In C, there are four fundamental data types: int, char, float, and double. The storage representation of these data types is different in memory.


    Why Do We Need Data Types in Programming? [1 mark]

    Data types are needed in programming for the following reasons:

    • Memory allocation: Different data types occupy different amounts of memory (e.g., char takes 1 byte, int takes 2 bytes). Specifying a data type tells the compiler how much memory to reserve.
    • Data validity: They ensure that only appropriate values are stored in a variable (e.g., an int variable cannot store a decimal value accurately).
    • Operations: They determine what operations are valid on a variable (e.g., arithmetic on int and float, character operations on char).
    • Type safety: They help the compiler detect errors when incompatible data is used.

    Three Basic Data Types with Examples [3 marks]

    1. int (Integer Data Type)

    • Used to store whole numbers (positive, negative, or zero).
    • On a 16-bit machine, it occupies 2 bytes of memory.
    • Range: -32768 to 32767 (for signed int).

    Example:

    #include <stdio.h>
    int main() {
        int age = 20;
        printf("Age = %d", age);
        return 0;
    }
    

    Output:

    Age = 20
    

    2. float (Floating Point Data Type)

    • Used to store single precision floating point numbers (numbers with decimal points).
    • Occupies 4 bytes of memory.
    • Range: 3.4E-38 to 3.4E+38.

    Example:

    #include <stdio.h>
    int main() {
        float price = 99.50;
        printf("Price = %.2f", price);
        return 0;
    }
    

    Output:

    Price = 99.50
    

    3. char (Character Data Type)

    • Used to store a single character (letter, digit, or symbol).
    • Occupies 1 byte of memory.
    • Range: -128 to 127 (for signed char), or 0 to 255 (for unsigned char).
    • Characters are stored internally as their ASCII values.

    Example:

    #include <stdio.h>
    int main() {
        char grade = 'A';
        printf("Grade = %c", grade);
        return 0;
    }
    

    Output:

    Grade = A
    

    Summary Table

    Data TypeSize (bytes)RangeUse
    int2-32768 to 32767Whole numbers
    float43.4E-38 to 3.4E+38Decimal numbers
    char1-128 to 127Single characters

    Note: The size and range shown above are for a 16-bit machine. Values may vary on machines with different word sizes.

  6. 65 marksI/O operationsAnswer

    What do you mean by unformatted I/O? Explain. [5]

    Unformatted I/O in C

    Definition

    Unformatted I/O refers to input/output functions in C that read or write data without any format specification. These functions do not require a format string (like %d, %f, etc.) and deal with raw characters or strings directly. They are simpler and faster than formatted I/O functions like scanf() and printf().


    Key Characteristics

    • No format specifiers are used.
    • They work directly with characters and strings.
    • They are declared in the header file <stdio.h>.
    • They are mainly used for simple character-level or string-level input and output.

    Unformatted I/O Functions in C

    1. Character Input/Output Functions

    FunctionPurpose
    getchar()Reads a single character from standard input (keyboard)
    putchar()Writes a single character to standard output (screen)

    Syntax:

    char ch;
    ch = getchar();   // reads one character
    putchar(ch);      // prints one character
    

    Example:

    #include <stdio.h>
    int main() {
        char ch;
        ch = getchar();    // user types a character
        putchar(ch);       // prints that character
        return 0;
    }
    

    2. String Input/Output Functions

    FunctionPurpose
    gets()Reads a string (including spaces) from standard input
    puts()Writes a string to standard output followed by a newline

    Syntax:

    char name[50];
    gets(name);     // reads a full line as string
    puts(name);     // prints the string
    

    Example:

    #include <stdio.h>
    int main() {
        char name[50];
        gets(name);     // reads string with spaces
        puts(name);     // prints string and moves to new line
        return 0;
    }
    

    Difference: Unformatted vs Formatted I/O

    FeatureUnformatted I/OFormatted I/O
    Format specifierNot requiredRequired (%d, %f, etc.)
    Functionsgetchar(), putchar(), gets(), puts()scanf(), printf()
    Data type handledCharacters and strings onlyAny data type
    ComplexitySimpleMore flexible

    Summary

    Unformatted I/O functions are used when the program needs to handle raw characters or strings without worrying about data types or format specifiers. They are straightforward, easy to use, and suitable for simple input/output operations in C programs.

  7. 75 marksDecision Making and LoopingAnswer

    Write a program to display first n prime numbers. [5]

    Program to Display First N Prime Numbers

    Concept

    A prime number is a number greater than 1 that has no divisors other than 1 and itself. To display the first N prime numbers, we use a nested loop:

    • The outer loop counts how many primes have been found so far.
    • The inner loop checks whether each candidate number is prime.

    Program

    #include<stdio.h>
    #include<conio.h>
    
    void main()
    {
        int n, num, i, count, primeCount;
    
        clrscr();
    
        printf("Enter how many prime numbers to display: ");
        scanf("%d", &n);
    
        printf("First %d prime numbers are:\n", n);
    
        primeCount = 0;   /* counts how many primes found so far */
        num = 2;          /* start checking from 2 (smallest prime) */
    
        while(primeCount < n)
        {
            count = 0;    /* count of divisors */
    
            /* Check if num is prime */
            for(i = 2; i < num; i++)
            {
                if(num % i == 0)
                {
                    count++;   /* num has a divisor, not prime */
                    break;
                }
            }
    
            /* If no divisors found, it is prime */
            if(count == 0)
            {
                printf("%d\n", num);
                primeCount++;
            }
    
            num++;   /* move to next candidate */
        }
    
        getch();
    }
    

    Sample Output

    Enter how many prime numbers to display: 5
    First 5 prime numbers are:
    2
    3
    5
    7
    11
    

    Explanation of Key Steps

    StepDescription
    Read nUser inputs how many primes are needed
    primeCount = 0Tracks how many primes have been printed
    num = 2Candidate number starts at 2
    Inner for loopChecks divisibility of num from 2 to num-1
    count == 0If no divisor found, num is prime; print it and increment primeCount
    num++Move to the next candidate number

    Note: The nested loop structure follows the concept of nesting of loops as described in the course notes, where one loop is written inside the body of another loop.

  8. 85 marksUser defined functionsAnswer

    Write a program to find product of two integers using your own function. [5]

    A user-defined function is a function created by the programmer to perform a specific task. Here, we create a separate function called product() that takes two integers as parameters and returns their product. --- --- --- Part Descriptio...

  9. 91 marksFunction Returning pointersAnswer

    Define pointer. How do you return pointers from functions? Explain with example. [1]

    A pointer is a variable that stores the memory address of another variable. Instead of holding a data value directly, it holds the location (address) where the data is stored in memory. Syntax: Example: int p; declares p as a pointer to ...

  10. 105 marksInput Output Operations in FileAnswer

    Explain different file I/O functions with example. [5]

    File I/O functions allow a C program to read data from and write data to files stored on disk. These functions are declared in the header file <stdio.h. --- These functions read or write one character at a time. Writes a single character...

  11. 115 marksGraphics FunctionAnswer

    Write a program to draw a circle using graphics function. [5]

    To draw a circle in C using graphics, we use the built-in circle() function from the graphics.h library. The program follows these steps: 1. Initialize the graphics driver and mode using initgraph() 2. Draw the circle using the circle() ...

  12. 125 marksCompilation and ExecutionAnswer

    Write short notes on: Compilation and execution, Operator precedence and associativity. [5]

    --- A computer only understands machine language (binary). Source code written in C (a high-level language) must be converted before it can run. This conversion happens in the following stages: Stage Description -------------------------...