CSC115 · TU past paper
C Programming 2075 question paper
The complete TU 2075 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 is looping statement?Discuss different looping statements with suitable example of each.[2+8]
Looping Statements in C
Definition of Looping Statement [2 marks]
A looping statement (also called an iterative statement) is a control structure that allows a block of statements to be executed repeatedly as long as a given condition remains true. Looping avoids writing the same code multiple times and is used when a task needs to be performed a fixed or variable number of times.
As per the notes, iterative statements in C include:
forwhiledo...while
Types of Looping Statements [8 marks]
1.
whileLoopSyntax:
while (condition) { // body of loop }How it works:
- The condition is checked before executing the body.
- If the condition is
true, the body executes. - If the condition is
falseat the start, the body is never executed. - It is called an entry-controlled loop.
Example: Print numbers 1 to 5
#include<stdio.h> void main() { int i = 1; while (i <= 5) { printf("%d\n", i); i++; } }Output:
1 2 3 4 5
2.
do...whileLoopSyntax:
do { // body of loop } while (condition);How it works:
- The body is executed first, then the condition is checked.
- The body executes at least once even if the condition is false.
- It is called an exit-controlled loop.
Example: Print numbers 1 to 5
#include<stdio.h> void main() { int i = 1; do { printf("%d\n", i); i++; } while (i <= 5); }Output:
1 2 3 4 5Key difference from
while: Even ifistarts at 6, the body runs once before checking the condition.
3.
forLoopSyntax:
for (initialization; condition; increment/decrement) { // body of loop }How it works:
- Initialization: Executed once at the beginning (e.g.,
i = 1). - Condition: Checked before each iteration; if false, loop ends.
- Increment/Decrement: Executed after each iteration.
- It is also an entry-controlled loop and is preferred when the number of iterations is known in advance.
Example: Find the sum of first 10 natural numbers
#include<stdio.h> void main() { int i, sum = 0; for (i = 1; i <= 10; i++) { sum = sum + i; } printf("Sum = %d", sum); }Output:
Sum = 55
Comparison Table
Feature whiledo...whileforType Entry-controlled Exit-controlled Entry-controlled Condition checked Before body After body Before body Minimum executions 0 1 0 Best used when Iterations unknown Must run at least once Iterations known
Summary
Looping statements are essential in C programming to perform repetitive tasks efficiently. The
forloop is used when the number of iterations is known; thewhileloop is used when the condition is checked before execution; and thedo...whileloop guarantees at least one execution of the loop body. - 210 marksIntroduction to ArrayHideAnswer
Define array?What are the benefits of using array?Write a program to add two matrices using array.[1+2+7]
Array: Definition, Benefits, and Matrix Addition Program
1. Definition of Array [1 mark]
An array is a collection of similar (same data type) elements stored in contiguous memory locations, referred to by a single variable name and accessed using an index (subscript).
Syntax:
data_type array_name[size];Example:
int marks[5]; /* declares an array of 5 integers */
2. Benefits of Using Array [2 marks]
Benefit Explanation Organized Storage Multiple values of the same type are stored under one variable name, keeping data organized. Easy Access Any element can be directly accessed using its index, e.g., arr[2].Less Code Instead of declaring many separate variables, a single array declaration handles all values. Loop Friendly Arrays work efficiently with loops to process large amounts of data quickly. Supports 2D Data Two-dimensional arrays allow representation of matrices and tables naturally.
3. Program to Add Two Matrices Using Array [7 marks]
Logic:
- Take two matrices A and B of the same size (r x c).
- Add corresponding elements:
C[i][j] = A[i][j] + B[i][j] - Display the resultant matrix C.
Program:
#include<stdio.h> #include<conio.h> void main() { int A[10][10], B[10][10], C[10][10]; int i, j, r, c; clrscr(); /* Input: number of rows and columns */ printf("Enter number of rows: "); scanf("%d", &r); printf("Enter number of columns: "); scanf("%d", &c); /* Input elements of Matrix A */ printf("\nEnter elements of Matrix A:\n"); for(i = 0; i < r; i++) { for(j = 0; j < c; j++) { printf("A[%d][%d] = ", i, j); scanf("%d", &A[i][j]); } } /* Input elements of Matrix B */ printf("\nEnter elements of Matrix B:\n"); for(i = 0; i < r; i++) { for(j = 0; j < c; j++) { printf("B[%d][%d] = ", i, j); scanf("%d", &B[i][j]); } } /* Addition of two matrices */ for(i = 0; i < r; i++) { for(j = 0; j < c; j++) { C[i][j] = A[i][j] + B[i][j]; } } /* Display the resultant matrix C */ printf("\nResultant Matrix after Addition:\n"); for(i = 0; i < r; i++) { for(j = 0; j < c; j++) { printf("%d\t", C[i][j]); } printf("\n"); } getch(); }
Sample Output:
Enter number of rows: 2 Enter number of columns: 2 Enter elements of Matrix A: A[0][0] = 1 A[0][1] = 2 A[1][0] = 3 A[1][1] = 4 Enter elements of Matrix B: B[0][0] = 5 B[0][1] = 6 B[1][0] = 7 B[1][1] = 8 Resultant Matrix after Addition: 6 8 10 12
Explanation of Key Steps:
Step Description int A[10][10]Declares a 2D array to store matrix elements Nested forloop for inputReads each element row by row using scanfC[i][j] = A[i][j] + B[i][j]Adds corresponding elements of both matrices Nested forloop for outputDisplays the result matrix in proper row-column format using printfand\t - 310 marksConcept of FileHideAnswer
Why do we need data files?What are the different file opening modes?Write a program that reads data from a file "input.txt" and writes to "output.txt" file.[2+3+5]
Data Files, File Opening Modes, and File Copy Program
(a) Why Do We Need Data Files?
When a program runs, all data is stored in main memory (RAM), which is volatile -- it is lost when the program ends or the computer is switched off. Data files solve this problem by providing permanent storage on secondary storage devices (hard disk, etc.).
Reasons we need data files:
- Persistence: Data stored in files remains even after the program terminates.
- Large data handling: Files allow processing of data too large to fit in memory at once.
- Data sharing: Multiple programs can read from and write to the same file.
- Reusability: Data entered once can be reused many times without re-entering.
- Record keeping: Files allow maintaining logs, reports, and databases permanently.
(b) Different File Opening Modes
As per the notes, the file opening modes used in C are:
Mode Description "r"Open existing file for reading only. File must exist. Previous data is not erased. "w"Open file for writing. Creates new file if it does not exist. Erases existing data if file exists. "a"Open file for appending. Creates new file if it does not exist. New data is added at the end; existing data is not erased. "r+"Open existing file for reading and writing (update mode). File must exist. Data is not erased. "w+"Open file for writing and reading. Creates new file if not exists. Erases existing data if file exists. "a+"Open file for appending and reading. Creates new file if not exists. Cannot modify existing data. "rb"Open binary file for reading. "wb"Open binary file for writing. "ab"Open binary file for appending. "rb+"Open binary file for reading and writing. "wb+"Create binary file for reading and writing. "ab+"Open binary file for appending and reading.
(c) Program to Read from "input.txt" and Write to "output.txt"
Approach:
- Open
input.txtin"r"(read) mode. - Open
output.txtin"w"(write) mode. - Read characters one by one from
input.txtusingfgetc(). - Write each character to
output.txtusingfputc(). - Close both files after the operation.
#include <stdio.h> #include <stdlib.h> int main() { FILE *fp_in, *fp_out; char ch; /* Open input.txt for reading */ fp_in = fopen("input.txt", "r"); if (fp_in == NULL) { printf("Error: Cannot open input.txt\n"); exit(1); } /* Open output.txt for writing */ fp_out = fopen("output.txt", "w"); if (fp_out == NULL) { printf("Error: Cannot open output.txt\n"); fclose(fp_in); exit(1); } /* Read from input.txt and write to output.txt character by character */ while ((ch = fgetc(fp_in)) != EOF) { fputc(ch, fp_out); } printf("Data successfully copied from input.txt to output.txt\n"); /* Close both files */ fclose(fp_in); fclose(fp_out); return 0; }
Explanation of Key Steps:
Step Code Purpose Open input file fopen("input.txt", "r")Opens file for reading Open output file fopen("output.txt", "w")Opens/creates file for writing NULL check if (fp_in == NULL)Checks if file opened successfully Read character fgetc(fp_in)Reads one character from input file and advances file pointer Write character fputc(ch, fp_out)Writes one character to output file EOF check != EOFStops reading when end of file is reached Close files fclose()Releases file resources
Sample Output:
Data successfully copied from input.txt to output.txtThe contents of
input.txtwill be completely copied intooutput.txt. - 45 marksBreak and ContinueHideAnswer
What is break statement ? Discuss with example. How the break statement is different from continue statement? [1+0.5+3.5]
--- The break statement is a jump statement used inside loops (for, while, do...while) and switch statements. When a break statement is encountered, the execution of the entire loop or switch case is immediately terminated, and the contr...
- 55 marksConditional StatementsHideAnswer
Write a program to check whether a number entered is even or odd. [5]
When a number is divided by 2: - If the remainder is 0, the number is even - If the remainder is not 0, the number is odd The modulus operator % is used to find the remainder. --- --- Line Description ------------------- include<stdio.h ...
- 65 marksDecision Making and LoopingHideAnswer
Write a program to calculate sum of first 10 odd numbers. [5]
The first 10 odd numbers are: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 We use a for loop to iterate through numbers and check whether each number is odd using the condition num % 2 != 0. We keep a count of how many odd numbers have been found a...
- 75 marksStructure of a C programHideAnswer
What is preprocessor directive? Discuss #define derivative with example. [1.5+3.5]
Preprocessor Directive and #define Directive
What is a Preprocessor Directive? [1.5 marks]
A preprocessor directive is an instruction given to the C preprocessor -- a program that processes the source code before actual compilation begins. Preprocessor directives tell the preprocessor to perform specific operations such as file inclusion, macro substitution, or conditional compilation.
Key characteristics:
- All preprocessor directives begin with the
#(hash) symbol. - They are not C statements, so they do not end with a semicolon (
;). - They are processed before the compiler translates the source code into object code.
- They appear at the top of the program, in the preprocessor directives section of the C program structure.
Common preprocessor directives:
Directive Purpose #includeIncludes a header file #defineDefines a macro or symbolic constant #undefUndefines a macro #ifdef/#ifndefConditional compilation
The
#defineDirective [3.5 marks]The
#definedirective is used to define macros in C. A macro is a name (identifier) that is replaced by a value or expression throughout the program by the preprocessor before compilation.Syntax:
#define MACRO_NAME replacement_textThe preprocessor replaces every occurrence of
MACRO_NAMEin the source code withreplacement_textbefore the compiler processes the file.
Types of
#defineUsage:
1. Symbolic Constants (Object-like Macros)
Used to define constant values. This improves readability and maintainability of the program -- if the value needs to change, it only needs to be changed in one place.
Example:
#include <stdio.h> #define PI 3.14159 #define MAX 100 int main() { float radius, area; printf("Enter radius: "); scanf("%f", &radius); area = PI * radius * radius; printf("Area of circle = %.2f\n", area); return 0; }Output (for radius = 5):
Area of circle = 78.54Here, every occurrence of
PIis replaced by3.14159before compilation.
2. Function-like Macros (Macros with Parameters)
#definecan also define macros that accept arguments, similar to functions but handled by the preprocessor.Syntax:
#define MACRO_NAME(parameter) expressionExample:
#include <stdio.h> #define SQUARE(x) ((x) * (x)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) int main() { int num = 5; printf("Square of %d = %d\n", num, SQUARE(num)); printf("Maximum of 10 and 20 = %d\n", MAX(10, 20)); return 0; }Output:
Square of 5 = 25 Maximum of 10 and 20 = 20Note: Parentheses around parameters in macros are important to avoid operator precedence errors. For example,
SQUARE(2+3)without parentheses would give2+3*2+3 = 11(wrong), but with parentheses((2+3)*(2+3)) = 25(correct).
Important Points about
#define:Point Detail No memory allocation Macros are just text substitution; no variable is created No type checking Unlike variables or functions, the preprocessor does not check data types No semicolon #define PI 3.14;would include the semicolon in the replacement, causing errorsScope A macro defined with #defineis valid from the point of definition to the end of the file (or until#undef)
Summary
The
#definedirective is a powerful preprocessor tool in C that allows programmers to define symbolic constants and function-like macros. It makes programs more readable, portable, and easy to maintain by avoiding the use of hard-coded values throughout the code. - All preprocessor directives begin with the
- 85 marksString Library FunctionsHideAnswer
Discuss any five string library functions. [5]
String library functions are built-in functions used to manipulate strings in C. Their prototypes are declared in the header file <string.h. --- This function returns the length of the string, i.e., the number of characters excluding the...
- 95 marksDynamic Memory AllocationHideAnswer
What is dynamic memory allocation? Discuss the use of malloc() in dynamic memory allocation with example. [1+4]
--- (a) What is Dynamic Memory Allocation? Dynamic memory allocation is the process of allocating memory to a program at the time of execution (runtime) rather than at compile time. In static memory allocation, the size of memory (e.g., ...
- 105 marksIntroductionHideAnswer
What is structure? Create a structure rectangle with data members length and breath. [2+3]
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: - The definition starts with the keyword st...
- 115 marksConcept of FileHideAnswer
Write short note on: a. Benefits of data files b. Graphics functions. [2.5+2.5]
Short Notes
a. Benefits of Data Files (2.5 marks)
A file is a collection of related data placed on the disk. C supports the concept of files through which data can be stored on a disk or secondary storage device, and the stored data can be read whenever required.
The key benefits of using data files are:
1. Permanent Storage of Data
Data stored in files is saved on the disk (secondary storage). Unlike variables stored in RAM, file data is not lost when the program terminates. It can be retrieved at any time.
2. Handling Large Amounts of Data
Files allow programs to process large volumes of data that cannot be held entirely in memory at once. Data can be read or written in parts (blocks, strings, characters, etc.).
3. Data Reusability
Once data is written to a file, it can be read and reused by the same program or different programs multiple times without re-entering the data.
4. Data Sharing Between Programs
Multiple programs can access the same data file, enabling easy sharing and transfer of information between different applications.
5. Easy Data Modification
Files can be opened in various modes such as
"r+"(read + write / update mode) or"a+"(append + read) to modify or add new data without destroying existing data.6. Organized Data Management
Data can be stored in a structured and organized manner. C provides various file modes (
"r","w","a","rb","wb", etc.) and I/O functions (fread(),fwrite(),fprintf(),fscanf(), etc.) to manage data efficiently.7. Buffered I/O for Efficiency
C file handling uses buffers to temporarily hold data during read/write operations. When a file is closed using
fclose(), all buffered data is flushed (written) to the file, ensuring no data is lost and improving I/O performance.
b. Graphics Functions (2.5 marks)
C provides a graphics library (
graphics.h) that allows drawing shapes, lines, and images on the screen using pixel-based coordinates. The origin pixel(0, 0)is located at the top-left corner of the screen.The important graphics functions are:
1.
initgraph(&gd, &gm, path)- Purpose: Initializes the graphics system and puts the screen into graphics mode.
gd= graphics driver,gm= graphics mode,path= path to BGI driver files.- Example:
initgraph(&gd, &gm, "c:\\tc\\bgi");
2.
circle(x, y, radius)- Purpose: Draws a circle with center at
(x, y)and the given radius. - Example:
circle(300, 200, 150);
3.
line(x1, y1, x2, y2)- Purpose: Draws a line from point
(x1, y1)to point(x2, y2)using pixels placed near each other. - Coordinates are measured from the top-left corner of the screen.
4.
getpixel(x, y)- Purpose: Gets the color of the pixel at position
(x, y). - Returns an integer value corresponding to the color of that pixel.
- The pixel is the smallest element on the graphics display screen.
5.
setcolor(color)- Purpose: Sets the current drawing color for subsequent graphics operations.
- Example:
setcolor(WHITE);
6.
closegraph()- Purpose: Closes the graphics mode and restores the screen to text mode, freeing resources used by the graphics system.
Example Program (from notes):
#include<stdio.h> #include<conio.h> #include<graphics.h> void main() { int gd = DETECT, gm; initgraph(&gd, &gm, "c:\\tc\\bgi"); circle(300, 200, 150); setcolor(WHITE); getch(); closegraph(); }Note: In C graphics, images are formed by placing pixels (dots) near each other on the screen. The pixel at position
(0, 0)is always at the top-left corner of the screen. - 125 marksLogical or Boolean operatorHideAnswer
Discuss different logical operations in details. [5]
Logical operators are used to combine two or more conditions (relational expressions) and return a true (1) or false (0) result. They are primarily used in decision-making statements like if, while, and for. --- C provides three logical ...