BIT102 · TU past paper
C Programming 2080 question paper
The complete TU 2080 exam paper for C Programming (BIT102), all 12 questions with solved model answers written to the mark scheme.
Tap a question to open its answer.
- 110 marksOne-dimensional arraysHideAnswer
What is an array? How an array can be passed as function argument? Write a program to arrange an array having 10 integer numbers in ascending order using function.[10]
--- An array is a collection of elements of the same data type stored in contiguous (adjacent) memory locations, all sharing a common name and accessed individually using an index (subscript). Declaration Syntax: Example: Key Properties:...
- 210 marksSwitch case statementHideAnswer
Explain different control structures in C. Write a program in C to perform different arithmetic operations on two integers and display the result based on choice made by user using switch statement.[10]
Control Structures in C and Switch-Based Arithmetic Calculator
Part 1: Control Structures in C
Control structures determine the flow of execution of a program. C provides three main categories:
1. Sequential Structure
Statements are executed one after another in the order they appear. This is the default flow.
Statement 1 → Statement 2 → Statement 3
2. Selection (Decision) Structures
Used to choose between alternative paths based on a condition.
a)
ifStatementif (condition) { // executes if condition is true }b)
if-elseStatementif (condition) { // executes if true } else { // executes if false }c)
if-else if-else(Ladder)if (condition1) { ... } else if (condition2) { ... } else { ... }d)
switchStatementUsed when a variable is compared against multiple constant values.
switch (expression) { case value1: // statements; break; case value2: // statements; break; default: // statements; }
3. Iteration (Loop) Structures
Used to repeat a block of statements.
a)
forLoopfor (initialization; condition; update) { // body }b)
whileLoopwhile (condition) { // body }c)
do-whileLoopdo { // body } while (condition);Executes the body at least once before checking the condition.
4. Jump Structures
Used to transfer control unconditionally.
Statement Purpose breakExits the nearest loop or switch continueSkips the current iteration gotoJumps to a labeled statement returnExits a function
Part 2: C Program Using Switch for Arithmetic Operations
#include <stdio.h> int main() { int a, b, choice; float result; // Input two integers printf("Enter first integer: "); scanf("%d", &a); printf("Enter second integer: "); scanf("%d", &b); // Display menu printf("\n--- Arithmetic Operations Menu ---\n"); printf("1. Addition\n"); printf("2. Subtraction\n"); printf("3. Multiplication\n"); printf("4. Division\n"); printf("5. Modulus\n"); printf("Enter your choice (1-5): "); scanf("%d", &choice); // Switch statement for operation selection switch (choice) { case 1: result = a + b; printf("Result: %d + %d = %.2f\n", a, b, result); break; case 2: result = a - b; printf("Result: %d - %d = %.2f\n", a, b, result); break; case 3: result = a * b; printf("Result: %d * %d = %.2f\n", a, b, result); break; case 4: if (b == 0) { printf("Error: Division by zero is not allowed.\n"); } else { result = (float)a / b; printf("Result: %d / %d = %.2f\n", a, b, result); } break; case 5: if (b == 0) { printf("Error: Modulus by zero is not allowed.\n"); } else { printf("Result: %d %% %d = %d\n", a, b, a % b); } break; default: printf("Invalid choice! Please enter a number between 1 and 5.\n"); } return 0; }
Sample Output
Enter first integer: 10 Enter second integer: 3 --- Arithmetic Operations Menu --- 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Modulus Enter your choice (1-5): 4 Result: 10 / 3 = 3.33
Key Points About the Switch Statement Used
Feature Description switch(choice)Evaluates the integer variable choicecase n:Matches a specific constant value breakPrevents fall-through to the next case defaultHandles any value not matched by a case Division check Guards against division/modulus by zero - 310 marksDifferences between structure and unionHideAnswer
Differentiate between structure and union? Write a program to read employ id, name, post and salary of employee and display detail of those employee whose post is 'clerk'.[10]
--- Feature Structure Union --------- Keyword struct union Memory Allocation Each member gets its own separate memory All members share the same memory location Total Size Sum of sizes of all members Size of the largest member only Data ...
- 45 marksFactorial using recursionHideAnswer
What is recursion? Write a program to find the factorial of a given integer using recursion. [5]
Recursion and Factorial Program
What is Recursion?
Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. A recursive function solves a problem by breaking it down into smaller subproblems of the same type until it reaches a base case (a condition where the function stops calling itself).
Every recursive function must have:
- Base Case - the condition that terminates the recursion
- Recursive Case - the part where the function calls itself
Factorial Using Recursion
Mathematical Definition
$$n! = \begin{cases} 1 & \text{if } n = 0 \text{ or } n = 1 \ n \times (n-1)! & \text{if } n > 1 \end{cases}$$
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
C Program
#include <stdio.h> // Recursive function to calculate factorial int factorial(int n) { // Base case if (n == 0 || n == 1) { return 1; } // Recursive case else { return n * factorial(n - 1); } } int main() { int num; printf("Enter a positive integer: "); scanf("%d", &num); if (num < 0) { printf("Factorial is not defined for negative numbers.\n"); } else { printf("Factorial of %d = %d\n", num, factorial(num)); } return 0; }
Trace of Execution (for n = 5)
factorial(5) = 5 * factorial(4) = 4 * factorial(3) = 3 * factorial(2) = 2 * factorial(1) = 1 <-- Base case = 2 * 1 = 2 = 3 * 2 = 6 = 4 * 6 = 24 = 5 * 24 = 120Output:
Enter a positive integer: 5 Factorial of 5 = 120
Key Points
Aspect Description Base Case n == 0orn == 1, returns1Recursive Case n * factorial(n-1)Stack Usage Each call is pushed onto the call stack Termination Recursion stops when base case is reached - 55 marksConversion specifiersHideAnswer
What are conversion specifiers? Explain the basic structure of a C program. [5]
--- Conversion specifiers are special format codes used inside printf() and scanf() functions to specify the type and format of data to be printed or read. They always begin with a percent sign (%) followed by a character that indicates ...
- 65 marksNested if elseHideAnswer
Explain nested if else ladder with suitable example. [5]
A nested if-else ladder (also called if-else-if ladder) is a control structure where multiple conditions are checked in sequence. Each else branch contains another if condition, forming a chain (ladder) of conditions. The program checks ...
- 75 marksFor loop structure and syntaxHideAnswer
Explain structure of for loop. Write a program to reverse a number entered by user. [5]
The for loop is an entry-controlled loop used when the number of iterations is known in advance. Syntax: Explanation of each part: Part Description ------------------- Initialization Sets the starting value of the loop variable (executed...
- 85 marksDynamic memory allocationHideAnswer
What is DMA? Write a program to read N numbers and find largest and smallest number using DMA. [5]
Dynamic Memory Allocation (DMA) is the process of allocating memory to a program at runtime (during execution) rather than at compile time. It allows a program to request memory as needed and release it when no longer required. In C, DMA...
- 95 marksFile handling and file operationsHideAnswer
Why data file is needed? Write a program to write N numbers in file 'number.txt' and then read it and display only even numbers. [5]
Data files are needed for the following reasons: 1. Permanent Storage - Data stored in variables is lost when the program ends. Files store data permanently on disk. 2. Large Data Handling - Files allow storing and processing large amoun...
- 105 marksLogical operatorsHideAnswer
List out different operators in C. Explain Logical and relational operator. [5]
The different types of operators in C are: 1. Arithmetic Operators (+, -, , /, %) 2. Relational Operators (<, , <=, =, ==, !=) 3. Logical Operators (&&, , !) 4. Assignment Operators (=, +=, -=, =, /=) 5. Increment/Decrement Operators (++...
- 115 marksSimilarity between arrays and pointersHideAnswer
What is pointer? Explain the similarity between array and pointer in brief. [5]
Pointer and Its Similarity with Array
What is a Pointer?
A pointer is a variable that stores the memory address of another variable rather than storing a direct value. It "points to" the location in memory where data is stored.
Syntax:
data_type *pointer_name;Example:
int a = 10; int *p; p = &a; // p holds the address of variable aHere,
&agives the address ofa, and*p(dereferencing) gives the value stored at that address, i.e.,10.
Similarity Between Array and Pointer
In C, arrays and pointers are closely related. The key similarities are:
1. Array Name as a Pointer
The name of an array acts as a constant pointer to the first element of the array.
int arr[5] = {10, 20, 30, 40, 50}; int *p = arr; // p points to arr[0]Here,
arrand&arr[0]are equivalent.
2. Accessing Elements
Array elements can be accessed using pointer notation, and pointer elements can be accessed using array notation.
Array Notation Pointer Notation Meaning arr[0]*por*(p+0)First element arr[1]*(p+1)Second element arr[i]*(p+i)i-th element printf("%d", arr[2]); // Output: 30 printf("%d", *(p+2)); // Output: 30 (same result)
3. Pointer Arithmetic
Both arrays and pointers support arithmetic operations like increment and decrement to traverse elements.
p++; // moves to the next element (next memory address)
4. Address Relationship
For an array
arr:arr=&arr[0](address of first element)arr + 1=&arr[1](address of second element)arr + i=&arr[i](address of i-th element)
Key Difference (Note)
Although similar, an array name is a constant pointer -- its address cannot be changed, whereas a pointer variable can be reassigned to point to different locations.
p = p + 1; // Valid arr = arr + 1; // ERROR: array name is a constant pointer
In summary, arrays and pointers are interchangeable in many contexts in C, making pointer knowledge essential for efficient array manipulation.
- 125 marksPreprocessor directivesHideAnswer
Write short notes on: a) Macro Write short notes on: b) Opening and closing file [2.5+2.5]
Short Notes
a) Macro
A macro is a preprocessor directive in C that allows a name (identifier) to be associated with a piece of code, a constant, or an expression. The C preprocessor replaces every occurrence of the macro name with its defined text before actual compilation begins.
Types of Macros
1. Object-like Macro (Simple/Symbolic Constant)
#define PI 3.14159 #define MAX 100Every occurrence of
PIin the code is replaced by3.14159.2. Function-like Macro (Macro with Arguments)
#define SQUARE(x) ((x)*(x)) #define MAX(a,b) ((a)>(b) ? (a) : (b))Usage:
SQUARE(5)is replaced by((5)*(5))= 25.Key Points
- Defined using
#definedirective. - Processed by the preprocessor, not the compiler.
- No type checking is performed (unlike functions).
- Parentheses should be used carefully to avoid operator precedence errors.
- Macros can be undefined using
#undef. - They make code more readable, portable, and easy to maintain.
b) Opening and Closing a File
In C, file handling is done using the standard library
<stdio.h>. Before reading from or writing to a file, it must be opened, and after operations are complete, it must be closed.Opening a File
The
fopen()function is used to open a file.Syntax:
FILE *fptr; fptr = fopen("filename", "mode");FILE *is a pointer to a file structure.- If the file cannot be opened,
fopen()returnsNULL.
File Opening Modes
Mode Description "r"Open for reading (file must exist) "w"Open for writing (creates new or truncates existing) "a"Open for appending (creates if not exists) "r+"Open for both reading and writing "w+"Open for reading and writing (truncates) "a+"Open for reading and appending Closing a File
The
fclose()function is used to close an opened file.Syntax:
fclose(fptr);- It flushes any unwritten data to the file.
- Releases the file pointer resource.
- Returns
0on success,EOFon failure.
Example
#include <stdio.h> int main() { FILE *fptr; fptr = fopen("data.txt", "w"); // Open file for writing if (fptr == NULL) { printf("Error opening file!\n"); return 1; } fprintf(fptr, "Hello, File!\n"); // Write to file fclose(fptr); // Close the file return 0; }Note: Always check if
fopen()returnsNULLbefore performing file operations, and always close the file after use to prevent data loss or resource leaks. - Defined using