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.
- 110 marksDecision Making and LoopingHideAnswer
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):
- The condition is evaluated first.
- If the condition is true, the loop body executes.
- After executing the body, control goes back to step 1.
- 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]
Feature While Loop Do-While Loop Type Entry-controlled loop Exit-controlled loop Condition check Checked before loop body executes Checked after loop body executes Minimum executions 0 times (if condition is false initially) At least 1 time (body executes before check) Syntax while(condition){ }do{ } while(condition);Semicolon No semicolon after condition Semicolon required after while(condition);Use case When execution depends on condition being true first When 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:
whileloop: body executes 0 timesdo-whileloop: body executes 1 time
4. Program to Find Sum and Average of First N Natural Numbers [4 marks]
Algorithm:
- Start
- Read the value of n
- Initialize sum = 0, i = 1
- While i <= n, do:
- sum = sum + i
- i = i + 1
- Calculate average = sum / n
- Display sum and average
- 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.00Verification (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. - 210 marksTypes of ArrayHideAnswer
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...
- 310 marksArray of structureHideAnswer
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]
Feature Structure Union Keyword structunionMemory Allocation Each member gets its own separate memory All members share the same memory Total Size Sum of sizes of all members Size of the largest member only Access All members can be accessed and used simultaneously Only one member can hold a value at a time Usage When all members are needed at the same time When 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
coursewith Members [2 marks]struct course { char name[50]; char code[10]; int credit_hour; };namestores the course namecodestores the course codecredit_hourstores 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
forloop reads data for all 5 courses. - A second
forloop with anifcondition filters and displays only those courses wherecredit_hour > 3.
- 45 marksAlgorithms and FlowchartHideAnswer
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 ----------...
- 55 marksData typesHideAnswer
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, anddouble. 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.,
chartakes 1 byte,inttakes 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
intvariable cannot store a decimal value accurately). - Operations: They determine what operations are valid on a variable (e.g., arithmetic on
intandfloat, character operations onchar). - 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 Type Size (bytes) Range Use int2 -32768 to 32767 Whole numbers float4 3.4E-38 to 3.4E+38 Decimal numbers char1 -128 to 127 Single characters Note: The size and range shown above are for a 16-bit machine. Values may vary on machines with different word sizes.
- Memory allocation: Different data types occupy different amounts of memory (e.g.,
- 65 marksI/O operationsHideAnswer
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 likescanf()andprintf().
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
Function Purpose 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 characterExample:
#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
Function Purpose 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 stringExample:
#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
Feature Unformatted I/O Formatted I/O Format specifier Not required Required ( %d,%f, etc.)Functions getchar(),putchar(),gets(),puts()scanf(),printf()Data type handled Characters and strings only Any data type Complexity Simple More 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.
- 75 marksDecision Making and LoopingHideAnswer
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
Step Description Read nUser inputs how many primes are needed primeCount = 0Tracks how many primes have been printed num = 2Candidate number starts at 2 Inner forloopChecks divisibility of numfrom 2 tonum-1count == 0If no divisor found, numis prime; print it and incrementprimeCountnum++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.
- 85 marksUser defined functionsHideAnswer
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...
- 91 marksFunction Returning pointersHideAnswer
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 ...
- 105 marksInput Output Operations in FileHideAnswer
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...
- 115 marksGraphics FunctionHideAnswer
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() ...
- 125 marksCompilation and ExecutionHideAnswer
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 -------------------------...