BIT102 ยท TU past paper
C Programming 2078 question paper
The complete TU 2078 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.
- Q1.10 marksOperator precedence and associativityHideAnswer
What is an expression and operator? Discuss operator associativity in C.Write a program to find factorial of a given integer using recursion.[5+5]
Expression, Operator, Operator Associativity in C + Factorial Using Recursion
(a) Expression and Operator
Expression
An expression in C is a valid combination of operands (variables, constants) and operators that evaluates to a single value.
Examples:
Expression Type a + b * cArithmetic expression x > yRelational expression a = 10Assignment expression a && bLogical expression
Operator
An operator is a special symbol that instructs the compiler to perform a specific mathematical, logical, or relational operation on one or more operands.
Types of Operators in C:
Type Operators Example Arithmetic +,-,*,/,%a + bRelational <,>,<=,>=,==,!=a > bLogical &&,||,!a && bAssignment =,+=,-=,*=a = 5Unary ++,--,-a++Bitwise &,|,^,~a & bConditional ? :a>b ? a : b
Operator Associativity
Associativity defines the direction of evaluation when two or more operators of the same precedence appear in a single expression. It resolves ambiguity in such expressions.
There are two types:
- Left to Right (L to R): Evaluation proceeds from left side to right side
- Right to Left (R to L): Evaluation proceeds from right side to left side
Associativity Table:
Operator Type Operators Associativity Unary ++,--,!,-(unary)Right to Left Arithmetic (high) *,/,%Left to Right Arithmetic (low) +,-Left to Right Relational <,>,<=,>=Left to Right Equality ==,!=Left to Right Logical AND &&Left to Right Logical OR ||Left to Right Assignment =,+=,-=,*=Right to Left Example 1 (Left to Right):
10 - 4 - 2 = (10 - 4) - 2 // Left to Right = 6 - 2 = 4Example 2 (Right to Left):
a = b = c = 5; // Evaluated as: a = (b = (c = 5)) // c = 5 first, then b = 5, then a = 5Conclusion: Associativity ensures that expressions with operators of equal precedence are evaluated in a well-defined, unambiguous order.
(b) Program to Find Factorial Using Recursion
Concept of Recursion
Recursion is a programming technique where a function calls itself repeatedly to solve a smaller sub-problem, until a base condition is reached that stops further calls.
Factorial Definition:
factorial(n) = n ร factorial(n-1), for n > 1 factorial(0) = 1 (base case) factorial(1) = 1 (base case)
C Program
#include <stdio.h> // Recursive function to calculate factorial int factorial(int n) { if (n == 0 || n == 1) // Base condition return 1; else return n * factorial(n - 1); // Recursive call } int main() { int num; printf("Enter a positive integer: "); scanf("%d", &num); if (num < 0) printf("Factorial is not defined for negative numbers."); else printf("Factorial of %d = %d\n", num, factorial(num)); return 0; }
Sample Output
Enter a positive integer: 5 Factorial of 5 = 120
Trace of Recursive Calls 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 = 120Final Result: 5! = 120
Key Point: Every recursive function must have a base case to prevent infinite recursion and stack overflow.
- Q2.10 marksRules for naming valid identifiersHideAnswer
What is an Identifier and Keyword? Explain the rules for naming valid Identifiers in C with example.Write a program to convert a given string to lowercase without using any library functions.[5+5]
Identifiers and Keywords in C
Identifiers
An identifier is a name given to various program elements such as variables, functions, arrays, structures, and user-defined types. Identifiers are used to uniquely identify a program element within its scope.
Example:
int age; // 'age' is an identifier float salary; // 'salary' is an identifier void display(); // 'display' is an identifier
Keywords
A keyword is a reserved word that has a predefined meaning in the C language. Keywords cannot be used as identifiers. C has 32 keywords.
Examples of Keywords:
intfloatcharifelsewhileforreturnvoidstructswitchbreak
Rules for Naming Valid Identifiers in C
-
Letters, digits, and underscore only: An identifier can only contain alphabets (A-Z, a-z), digits (0-9), and underscore ( _ ).
-
Must begin with a letter or underscore: An identifier cannot start with a digit.
-
No spaces allowed: Spaces are not permitted inside an identifier.
-
Keywords not allowed: Reserved keywords cannot be used as identifiers.
-
Case sensitive:
Ageandageare treated as different identifiers. -
No special characters: Characters like
@,#,$,!, etc. are not allowed. -
Length: Typically, the first 31 characters are significant (as per ANSI C standard).
Examples:
Identifier Valid/Invalid Reason ageValid Starts with letter _salaryValid Starts with underscore total_marksValid Letters and underscore var1Valid Letter followed by digit 1varInvalid Starts with digit my varInvalid Contains space intInvalid Reserved keyword my@nameInvalid Special character @
Program to Convert a String to Lowercase Without Library Functions
#include <stdio.h> int main() { char str[100]; int i; printf("Enter a string: "); gets(str); /* read the string */ /* Convert each character to lowercase */ for (i = 0; str[i] != '\0'; i++) { /* Check if character is uppercase (A=65, Z=90 in ASCII) */ if (str[i] >= 'A' && str[i] <= 'Z') { /* Add 32 to convert uppercase to lowercase */ str[i] = str[i] + 32; } } printf("Lowercase string: %s\n", str); return 0; }Sample Output:
Enter a string: Hello WORLD Lowercase string: hello worldLogic Explanation:
- In ASCII, uppercase letters range from 65 ('A') to 90 ('Z').
- Lowercase letters range from 97 ('a') to 122 ('z').
- The difference between any uppercase letter and its lowercase equivalent is 32.
- So, adding 32 to an uppercase character converts it to lowercase.
- For example:
'A'(65) + 32 = 97 ='a' - Characters that are already lowercase or non-alphabetic are left unchanged.
-
- Q3.10 marksBasic data types and their rangesHideAnswer
What different data types available in C along with their respective range?Write a program to check whether a given integer is palindrome or not.[5+5]
Data Types in C with Their Ranges
(a) Data Types in C
A data type defines the type of data a variable can hold, the amount of memory allocated, and the operations that can be performed on it.
Primary (Fundamental) Data Types in C
Data Type Size Range char1 byte -128 to 127 unsigned char1 byte 0 to 255 int2 or 4 bytes -32,768 to 32,767 (2 bytes) / -2,147,483,648 to 2,147,483,647 (4 bytes) unsigned int2 or 4 bytes 0 to 65,535 (2 bytes) / 0 to 4,294,967,295 (4 bytes) short int2 bytes -32,768 to 32,767 long int4 bytes -2,147,483,648 to 2,147,483,647 unsigned long int4 bytes 0 to 4,294,967,295 float4 bytes 3.4E-38 to 3.4E+38 (6 decimal digits precision) double8 bytes 1.7E-308 to 1.7E+308 (15 decimal digits precision) long double10 bytes 3.4E-4932 to 1.1E+4932 void0 bytes No value Classification of Data Types
Data Types in C โโโ Primary (Basic) โ โโโ int โ โโโ char โ โโโ float โ โโโ double โ โโโ void โโโ Derived โ โโโ Array โ โโโ Pointer โ โโโ Function โโโ User Defined โโโ struct โโโ union โโโ enum
(b) Program to Check Palindrome Integer
Concept
A number is called a palindrome if it reads the same forwards and backwards.
- Example: 121, 1331, 12321 are palindromes
- Example: 123, 456 are NOT palindromes
Algorithm
- Read the integer
n - Store original number in
original - Reverse the digits of
nto getreversed - If
original == reversed, it is a palindrome - Otherwise, it is not a palindrome
C Program
#include <stdio.h> int main() { int n, original, reversed = 0, remainder; printf("Enter an integer: "); scanf("%d", &n); original = n; /* Handle negative numbers - negative numbers are not palindromes */ if (n < 0) { printf("%d is NOT a palindrome.\n", n); return 0; } /* Reverse the digits of the number */ while (n != 0) { remainder = n % 10; /* Extract last digit */ reversed = reversed * 10 + remainder; /* Build reversed number */ n = n / 10; /* Remove last digit */ } /* Check if original and reversed are equal */ if (original == reversed) { printf("%d is a PALINDROME.\n", original); } else { printf("%d is NOT a PALINDROME.\n", original); } return 0; }Dry Run / Trace (for n = 121)
Iteration n remainder (n%10) reversed Start 121 - 0 1st 12 1 0*10+1 = 1 2nd 1 2 1*10+2 = 12 3rd 0 1 12*10+1 = 121 original = 121,reversed = 121- Since
121 == 121, it is a PALINDROME
Sample Output
Enter an integer: 121 121 is a PALINDROME. Enter an integer: 123 123 is NOT a PALINDROME. - Q4.5 marksBreak and continue statementsHideAnswer
How break statement is different from continue statement. Explain with examples? [5]
- Q5.5 marksBasic structure of C programHideAnswer
What is the basic structure of a C program? Explain each part. [5]
Basic Structure of a C Program
Basic Structure of a C Program
A C program is organized into several distinct sections. Below is the general template:
/* Documentation Section */ // Program description, author, date /* Link Section (Header Files) */ #include <stdio.h> #include <conio.h> /* Definition Section (Macros/Constants) */ #define PI 3.14159 /* Global Declaration Section */ int globalVar; /* Main Function */ int main() { /* Local Declaration */ int a, b; /* Executable Statements */ printf("Hello, World!\n"); return 0; } /* User-Defined Functions */ void myFunction() { // function body }
Explanation of Each Part
1. Documentation Section
- Contains comments about the program such as program name, author, date, and purpose.
- Written using
/* ... */(multi-line) or//(single-line). - Ignored by the compiler; meant for human readability.
2. Link Section (Header Files)
- Contains preprocessor directives that include standard library header files.
- Syntax:
#include <filename.h> - Example:
#include <stdio.h>includes standard input/output functions likeprintf()andscanf(). - These are processed before compilation.
3. Definition Section
- Used to define symbolic constants or macros using
#define. - Example:
#define PI 3.14159 - The preprocessor replaces every occurrence of
PIwith3.14159before compilation.
4. Global Declaration Section
- Variables declared here are global variables, accessible throughout the entire program.
- Declared outside all functions.
- They retain their value for the entire lifetime of the program.
5. Main Function
main()- Every C program must have exactly one
main()function -- it is the entry point of execution. - Contains two parts:
- Local Declaration: Variables declared inside
main(), accessible only within it. - Executable Statements: The actual logic -- assignments, function calls, loops, etc.
- Local Declaration: Variables declared inside
- Returns an integer value to the operating system (
return 0indicates successful execution).
6. User-Defined Functions
- Functions written by the programmer to perform specific tasks.
- Defined after (or before)
main(). - Promotes modularity and code reusability.
Summary Table
Section Purpose Documentation Comments and program description Link Section Includes header/library files Definition Section Defines constants and macros Global Declaration Declares global variables main()FunctionEntry point; contains program logic User-Defined Functions Custom functions for specific tasks - Q6.5 marksMulti-dimensional arraysHideAnswer
What do you mean by multi-dimensional array? Write a program to display the sum of two mxn matrices. [5]
Multi-Dimensional Array
Definition
A multi-dimensional array is an array that has more than one dimension (index). It can be thought of as an array of arrays. The most common form is the two-dimensional (2D) array, which represents data in rows and columns (like a matrix).
General syntax in C:
data_type array_name[size1][size2]...[sizeN];For a 2D array (matrix):
int matrix[m][n]; // m rows and n columnsElements are accessed using two indices:
matrix[i][j]whereiis the row index andjis the column index.
Program to Display the Sum of Two M x N Matrices
#include <stdio.h> int main() { int m, n, i, j; int A[10][10], B[10][10], C[10][10]; // Input dimensions printf("Enter number of rows (m): "); scanf("%d", &m); printf("Enter number of columns (n): "); scanf("%d", &n); // Input elements of matrix A printf("\nEnter elements of Matrix A (%dx%d):\n", m, n); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("A[%d][%d]: ", i, j); scanf("%d", &A[i][j]); } } // Input elements of matrix B printf("\nEnter elements of Matrix B (%dx%d):\n", m, n); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("B[%d][%d]: ", i, j); scanf("%d", &B[i][j]); } } // Calculate sum: C = A + B for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { C[i][j] = A[i][j] + B[i][j]; } } // Display the result matrix C printf("\nSum Matrix C = A + B:\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%d\t", C[i][j]); } printf("\n"); } return 0; }
Sample Output
Enter number of rows (m): 2 Enter number of columns (n): 2 Enter elements of Matrix A (2x2): A[0][0]: 1 A[0][1]: 2 A[1][0]: 3 A[1][1]: 4 Enter elements of Matrix B (2x2): B[0][0]: 5 B[0][1]: 6 B[1][0]: 7 B[1][1]: 8 Sum Matrix C = A + B: 6 8 10 12
Key Points
Concept Detail Declaration int A[10][10]declares a 2D arrayAccess A[i][j]accesses element at rowi, columnjNested loops Outer loop for rows, inner loop for columns Addition rule C[i][j] = A[i][j] + B[i][j]for each element - Q7.5 marksFile creation and copyingHideAnswer
Write a program to create a file "duplicate" that contains the exact copy of file "original". [5]
- Q8.5 marksFormatted input outputHideAnswer
Explain any four input/output functions used in C language with suitable example [5]
- Q9.5 marksPattern generation using arraysHideAnswer
Write a program to generate the following pattern of integers.
1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1[5]
Pattern Generation Program
Pattern Analysis
Looking at the pattern carefully:
1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1Each row
iprints numbers from 1 to i, then back from i-1 to 1.
C Program
#include <stdio.h> int main() { int n, i, j; printf("Enter the number of rows: "); scanf("%d", &n); for (i = 1; i <= n; i++) { /* Print increasing part: 1 to i */ for (j = 1; j <= i; j++) { printf("%d ", j); } /* Print decreasing part: i-1 down to 1 */ for (j = i - 1; j >= 1; j--) { printf("%d ", j); } printf("\n"); } return 0; }
Output (for n = 5)
1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1
Step-by-Step Explanation
Row (i) Increasing Part Decreasing Part Full Row 1 1 (none) 1 2 1 2 1 1 2 1 3 1 2 3 2 1 1 2 3 2 1 4 1 2 3 4 3 2 1 1 2 3 4 3 2 1 5 1 2 3 4 5 4 3 2 1 1 2 3 4 5 4 3 2 1 Logic Summary:
- Outer loop controls the row number
ifrom1ton - First inner loop prints
jfrom1toi(ascending) - Second inner loop prints
jfromi-1to1(descending) - Total numbers in row
i=2i - 1
- Outer loop controls the row number
- Q10.5 marksFinding smallest element using pointersHideAnswer
Write a program to find smallest element of an array using a pointer. [5]
- Q11.5 marksStoring and displaying structure dataHideAnswer
Write a program to store and display basic information (Roll, name, address, email. and phone) of students of using a structure. [5]
Program to Store and Display Student Information Using Structure
Concept
A structure in C is a user-defined data type that groups related variables of different data types under a single name.
C Program
#include <stdio.h> #include <string.h> // Define the structure struct Student { int roll; char name[50]; char address[100]; char email[50]; char phone[15]; }; int main() { int i, n; printf("Enter number of students: "); scanf("%d", &n); // Declare an array of structures struct Student s[n]; // Input student information for (i = 0; i < n; i++) { printf("\n--- Enter details for Student %d ---\n", i + 1); printf("Roll Number : "); scanf("%d", &s[i].roll); printf("Name : "); getchar(); // clear input buffer fgets(s[i].name, sizeof(s[i].name), stdin); s[i].name[strcspn(s[i].name, "\n")] = '\0'; // remove newline printf("Address : "); fgets(s[i].address, sizeof(s[i].address), stdin); s[i].address[strcspn(s[i].address, "\n")] = '\0'; printf("Email : "); fgets(s[i].email, sizeof(s[i].email), stdin); s[i].email[strcspn(s[i].email, "\n")] = '\0'; printf("Phone : "); fgets(s[i].phone, sizeof(s[i].phone), stdin); s[i].phone[strcspn(s[i].phone, "\n")] = '\0'; } // Display student information printf("\n========== Student Information ==========\n"); for (i = 0; i < n; i++) { printf("\nStudent %d:\n", i + 1); printf(" Roll Number : %d\n", s[i].roll); printf(" Name : %s\n", s[i].name); printf(" Address : %s\n", s[i].address); printf(" Email : %s\n", s[i].email); printf(" Phone : %s\n", s[i].phone); } return 0; }
Sample Output
Enter number of students: 2 --- Enter details for Student 1 --- Roll Number : 101 Name : Ram Sharma Address : Kathmandu Email : [email protected] Phone : 9841000001 --- Enter details for Student 2 --- Roll Number : 102 Name : Sita Thapa Address : Pokhara Email : [email protected] Phone : 9841000002 ========== Student Information ========== Student 1: Roll Number : 101 Name : Ram Sharma Address : Kathmandu Email : [email protected] Phone : 9841000001 Student 2: Roll Number : 102 Name : Sita Thapa Address : Pokhara Email : [email protected] Phone : 9841000002
Key Points
Feature Detail struct StudentUser-defined structure with 5 members struct Student s[n]Array of structures to store multiple students s[i].rollDot operator used to access structure members fgets()Used to read strings with spaces - Q12.5 marksComments and escape sequencesHideAnswer
Write Short Notes on: a) Escape Sequence Write Short Notes on: b) Null Pointer [2.5+2.5]