CSC115 · TU past paper
C Programming 2081 question paper
The complete TU 2081 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 marksIntroduction to ArrayHideAnswer
What are the characteristics of array?Write a program to input age of 500 persons and display the following: a) Average age b) Age between 25 to 30[2+8]
Characteristics of Array and Program for Age Analysis
Characteristics of Array [2 marks]
An array is a collection of similar data type elements stored in contiguous memory locations. Its main characteristics are:
- Homogeneous Elements: All elements in an array must be of the same data type (e.g., all int, all float).
- Contiguous Memory Allocation: Array elements are stored in consecutive memory locations.
- Index/Subscript Based Access: Each element is accessed using an index starting from 0 (lower bound = 0, upper bound = size - 1).
- Fixed Size: The size of an array is fixed at the time of declaration and cannot be changed during execution.
- Random Access: Any element can be directly accessed using its index in constant time.
- Single Variable Name: Multiple values are stored under one variable name with different indices.
Program to Input Age of 500 Persons [8 marks]
#include<stdio.h> #include<conio.h> void main() { int age[500], i; int count = 0; /* count of persons with age between 25 to 30 */ float sum = 0, average; clrscr(); /* Input age of 500 persons */ for(i = 0; i < 500; i++) { printf("Enter age of person %d: ", i + 1); scanf("%d", &age[i]); } /* Calculate sum and count persons with age between 25 to 30 */ for(i = 0; i < 500; i++) { sum = sum + age[i]; if(age[i] >= 25 && age[i] <= 30) { count++; } } /* a) Calculate average age */ average = sum / 500; printf("\n--- Results ---\n"); /* Display average age */ printf("\na) Average Age = %.2f", average); /* b) Display ages between 25 to 30 */ printf("\n\nb) Ages between 25 to 30:\n"); for(i = 0; i < 500; i++) { if(age[i] >= 25 && age[i] <= 30) { printf("Person %d : %d years\n", i + 1, age[i]); } } printf("\nTotal persons with age between 25 to 30: %d", count); getch(); }
Explanation of the Program
Step Description Declaration int age[500]declares an integer array of size 500 to store agesInput Loop A forloop runs fromi=0toi<500to input all 500 agesSum Calculation Each age is added to sumto find totalCondition Check age[i] >= 25 && age[i] <= 30checks if age falls in the rangeAverage average = sum / 500gives the average ageOutput Average is displayed and ages in range 25-30 are printed with person number
Sample Output
--- Results --- a) Average Age = 35.46 b) Ages between 25 to 30: Person 3 : 27 years Person 7 : 25 years Person 12 : 30 years ... Total persons with age between 25 to 30: 85 - 210 marksPassing Arguments by AddressHideAnswer
Differentiate between library function and user defined function.Write a program to swap two values using call by reference concept.[2+8]
Difference Between Library Function and User Defined Function + Swap Using Call by Reference
(a) Difference Between Library Function and User Defined Function
As per the course notes, C programs have two types of functions: Library Functions and User Defined Functions.
S.N. Library Function User Defined Function 1. A predefined function stored in a header file or preprocessor directive. Not predefined; it is defined by the programmer according to need. 2. Programmer can simply use this function by including the respective header file. Programmer has to declare, define, and call this function by themselves. 3. Program is usually short as the programmer does not have to define the function. Program is usually lengthy as the programmer has to define the function. 4. Program development time is faster. Program development time is usually slower. 5. Program will be simple. Program will be complex. 6. Requires a header file to use it (e.g., #include<stdio.h>).Requires a function prototype to use it. Examples:
- Library functions:
printf(),scanf(),sqrt(),strlen() - User defined functions: any function written by the programmer for a specific task
(b) Program to Swap Two Values Using Call by Reference
Concept: Call by Reference
In call by reference, instead of passing the actual values to the function, the addresses (pointers) of the variables are passed. This means any changes made inside the function directly affect the original variables in the calling function.
Program
#include<stdio.h> #include<conio.h> /* Function prototype (declaration) */ void swap(int *a, int *b); int main() { int x, y; printf("Enter first value : "); scanf("%d", &x); printf("Enter second value : "); scanf("%d", &y); printf("\nBefore Swap: x = %d, y = %d\n", x, y); /* Passing addresses of x and y - Call by Reference */ swap(&x, &y); printf("After Swap: x = %d, y = %d\n", x, y); getch(); return 0; } /* Function definition */ void swap(int *a, int *b) { int temp; temp = *a; /* temp stores value at address a */ *a = *b; /* value at address a = value at address b */ *b = temp; /* value at address b = temp */ }
Step-by-Step Explanation
Step Statement What Happens 1 swap(&x, &y)Addresses of xandyare passed to the function2 int *a, int *bPointer aholds address ofx; pointerbholds address ofy3 temp = *atempgets the value stored at addressa(i.e., value ofx)4 *a = *bValue at address a(i.e.,x) is replaced by value at addressb(i.e.,y)5 *b = tempValue at address b(i.e.,y) is replaced bytemp(originalx)
Sample Output
Enter first value : 10 Enter second value : 20 Before Swap: x = 10, y = 20 After Swap: x = 20, y = 10
Key Point
In call by reference, the function works with the actual memory locations of the variables. Therefore, the swap is reflected back in
main(), unlike call by value where only copies are passed and the original values remain unchanged. - Library functions:
- 310 marksArithmetic operatorHideAnswer
List different types of operators.Explain any four of them[2+8]
Types of Operators in C
List of Operators [2 marks]
An operator is a symbol that specifies an operation to be performed on operands. C includes the following types of operators:
- Arithmetic Operator
- Assignment Operator
- Increment and Decrement Operator
- Relational Operator
- Logical Operator
- Conditional Operator
- Comma Operator
- Sizeof Operator
- Bitwise Operator
Explanation of Any Four Operators [8 marks]
1. Arithmetic Operators
Arithmetic operators are used for numeric calculations. They are of two types:
i. Unary Arithmetic Operators - operate on a single operand.
Operator Meaning Example + Unary plus +a - Unary minus (negation) -a ii. Binary Arithmetic Operators - operate on two operands.
Operator Meaning Example Result (a=10, b=3) + Addition a + b 13 - Subtraction a - b 7 * Multiplication a * b 30 / Division a / b 3 % Modulus (remainder) a % b 1 Example:
int a = 10, b = 3; printf("%d", a % b); // Output: 1 printf("%d", a / b); // Output: 3
2. Relational Operators
Relational operators are used to compare two values or expressions. The result of a relational operation is either true (1) or false (0).
Operator Meaning Example (a=5, b=3) Result > Greater than a > b 1 (true) < Less than a < b 0 (false) >= Greater than or equal to a >= 5 1 (true) <= Less than or equal to a <= b 0 (false) == Equal to a == b 0 (false) != Not equal to a != b 1 (true) Example:
int a = 5, b = 3; if (a > b) printf("a is greater"); // Output: a is greater
3. Increment and Decrement Operators
These operators are used to increase or decrease the value of a variable by 1. They are of two types:
i. Prefix (operator written before operand)
++x: value is incremented first, then used in expression.--x: value is decremented first, then used in expression.
ii. Postfix (operator written after operand)
x++: value is used in expression first, then incremented.x--: value is used in expression first, then decremented.
Example:
int x = 5, y; y = ++x; // x becomes 6 first, then y = 6 printf("%d %d", x, y); // Output: 6 6 x = 5; y = x++; // y = 5 first, then x becomes 6 printf("%d %d", x, y); // Output: 6 5
4. Logical Operators
Logical operators are used to combine two or more relational expressions and return a true (1) or false (0) result. They are commonly used in decision-making.
Operator Meaning Example Result (a=5, b=3, c=0) && Logical AND a>b && b>c 1 (both true) || Logical OR a>b || b<c 1 (at least one true) ! Logical NOT !c 1 (negation of 0) Truth Table for AND (&&):
Condition 1 Condition 2 Result True (1) True (1) True (1) True (1) False (0) False (0) False (0) True (1) False (0) False (0) False (0) False (0) Example:
int a = 5, b = 3, c = 0; if (a > b && b > c) printf("Both conditions true"); // Output: Both conditions true if (!c) printf("c is zero"); // Output: c is zero
Summary: Operators are fundamental building blocks in C programming. Arithmetic operators perform calculations, relational operators compare values, increment/decrement operators modify values by 1, and logical operators combine conditions for decision-making.
- 45 marksStructure of C programHideAnswer
Explain the basic structure of C Programming. [5]
Every C program follows a standard, well-defined structure. Understanding this structure is essential before writing any C program. --- - Contains comments that describe the purpose of the program, author name, date, etc. - Comments are ...
- 55 marksFormatted I/OHideAnswer
Describe different formatted input and output functions. Why do we use them? [4+1]
Formatted input and output means that data is entered and displayed in a particular format. Through format specifications, better presentation of results can be obtained. Formatted I/O functions allow reading and writing data in a struct...
- 65 marksNumericalDecision Making and LoopingHideAnswer
Write a program to display first 50 prime numbers. [5]
Program to Display First 50 Prime Numbers
Given Data
- Required output: first 50 prime numbers
- Marks: 5
Concept
A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. To generate the first 50 primes, we test successive integers starting from 2, counting each prime until 50 are found.
Program (C)
#include<stdio.h> #include<conio.h> void main() { int num, i, count, primeCount; clrscr(); primeCount = 0; /* number of primes found so far */ num = 2; /* start from smallest prime */ printf("First 50 Prime Numbers are:\n"); while(primeCount < 50) { count = 0; /* 0 = prime, 1 = not prime */ for(i = 2; i <= num/2; i++) /* check divisors up to num/2 */ { if(num % i == 0) { count = 1; break; } } if(count == 0) /* num is prime */ { printf("%d\t", num); primeCount++; } num++; } getch(); }Note: an inner loop written as
i < numis logically correct, it simply checks more divisors than necessary. Usingi <= num/2(ori*i <= num) is more efficient, and both give the same correct output.Sample Output
First 50 Prime Numbers are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229Verification of Output
Counting the listed primes: 5 rows of 10 = 50 primes. The 50th prime is $229$, which is correct.
Explanation
Part Purpose primeCount < 50Loop continues until exactly 50 primes are found Inner forloopTests whether numhas any divisornum % i == 0Marks numas compositecount == 0Indicates numis primeprimeCount++Records each prime found - 75 marksNumericalDecision Making and LoopingHideAnswer
Write a program to display the following series up to 25 terms but do not print the 7th term. 2×3, 3×5, 4×7, 5×9... [5]
Program to Display Series Up to 25 Terms (Skipping the 7th Term)
STEP 1 - Given Data
- Series: $2\times3,; 3\times5,; 4\times7,; 5\times9,\ldots$
- Number of terms: 25
- Condition: Do not print the 7th term
STEP 2 - Solve
Pattern Analysis
Term ($i$) Expression First Factor Second Factor 1 $2\times3$ 2 3 2 $3\times5$ 3 5 3 $4\times7$ 4 7 4 $5\times9$ 5 9 - First factor $a = i + 1$
- Second factor $b = 2i + 1$
Verification for $i=4$: $a=5$, $b=9$ → $5\times9$. Correct.
C Program
#include <stdio.h> int main() { int i, a, b; printf("Series: 2x3, 3x5, 4x7, 5x9 ... up to 25 terms\n"); printf("(7th term is skipped)\n\n"); for(i = 1; i <= 25; i++) { if(i == 7) /* Skip the 7th term */ continue; a = i + 1; /* First factor */ b = 2 * i + 1; /* Second factor */ printf("Term %d: %d x %d = %d\n", i, a, b, a * b); } return 0; }Sample Output
Series: 2x3, 3x5, 4x7, 5x9 ... up to 25 terms (7th term is skipped) Term 1: 2 x 3 = 6 Term 2: 3 x 5 = 15 Term 3: 4 x 7 = 28 Term 4: 5 x 9 = 45 Term 5: 6 x 11 = 66 Term 6: 7 x 13 = 91 Term 8: 9 x 17 = 153 Term 9: 10 x 19 = 190 ... Term 25: 26 x 51 = 1326Verification of Skipped Term
7th term would be: $a = 8,; b = 15 \Rightarrow 8\times15 = 120$ - this is skipped by the
continuestatement.Key Points
- A
forloop iterates $i = 1$ to $25$ (25 terms). if(i == 7) continue;skips only the 7th term.- Formulas: $a = i+1$, $b = 2i+1$.
The program above uses standard C in place of the non-standard Turbo C constructs (
void main(),conio.h,clrscr()andgetch()); the logic, formulas and output are identical. - 85 marksNested and Recursive FunctionHideAnswer
Demonstrate the use of recursive function with a suitable example. [5]
A recursive function is a function that calls itself during its own execution. Each recursive call works on a smaller version of the problem until a base condition (terminating condition) is reached, which stops further recursion. --- Co...
- 95 marksArray of structureHideAnswer
Create a structure called STUDENT with data members SID, name, address, CGPA. Write a program to initialize the value of 100 students and display the information of those students whose address is "KTM" and CGPA is between 3.5 to 4. [5]
--- Part Description ------------------- struct STUDENT Defines the structure with members SID, name, address, CGPA struct STUDENT st[100] Declares an array of structures to hold 100 student records First for loop Reads and initializes d...
- 105 marksOpening and closing of FileHideAnswer
Explain different file opening modes. [5]
When working with files in C, a file must be opened before any I/O operations can be performed on it. The fopen() function is used to open a file, and it requires a mode string that specifies how the file should be accessed. Syntax: --- ...
- 115 marksGraphics FunctionHideAnswer
Write a program to draw two shapes of your choice using graphics function. [5]
Program to Draw Two Shapes Using Graphics Functions
Answer
The two shapes chosen are a Circle and a Rectangle, both drawn using standard graphics functions from
graphics.h.
Program
#include<stdio.h> #include<conio.h> #include<graphics.h> void main() { int gd = DETECT, gm; /* Initialize the graphics mode */ initgraph(&gd, &gm, "c:\\tc\\bgi"); /* Shape 1: Draw a Circle center at (200, 150) with radius 80 */ setcolor(WHITE); circle(200, 150, 80); /* Shape 2: Draw a Rectangle top-left corner at (350, 100) bottom-right corner at (550, 250) */ setcolor(WHITE); rectangle(350, 100, 550, 250); getch(); /* Close the graphics mode */ closegraph(); }
Explanation of Each Step
Step Description int gd = DETECT, gm;Declares graphics driver and mode variables. DETECTauto-detects the driver.initgraph(&gd, &gm, "c:\\tc\\bgi")Initializes the graphics system and opens a graphics window. The path points to the BGI driver files. setcolor(WHITE)Sets the current drawing color to white. circle(200, 150, 80)Draws a circle with center at pixel (200, 150) and radius 80 pixels. rectangle(350, 100, 550, 250)Draws a rectangle with top-left corner at (350, 100) and bottom-right corner at (550, 250). getch()Waits for a key press so the output window stays visible. closegraph()Closes the graphics mode and returns to text mode.
Output
+------------------------------------------+ | | | ( Circle ) [ Rectangle ] | | drawn at drawn at | | (200,150) (350,100) to | | r = 80 (550,250) | | | +------------------------------------------+Note: The pixel origin (0, 0) is at the top-left corner of the screen. All coordinates are measured in pixels from this origin.
- 125 marksLocal and Global VariableHideAnswer
Write short notes on: a) Global variable b) Debugging Debugging [2.5+2.5]
--- Definition: Global variables are variables that are defined outside any function in a C program. Since they are declared outside all functions, they are accessible and can be modified by all functions in the program. Key Characterist...