Introduction to C Programming: Exam Questions & Solutions
Section A
Attempt all questions. (Maximum word limit: 50)
a. Why does a computer understand only binary language?
Computers understand only binary language because they operate using electrical signals, which have two states: on (1) and off (0). These two states correspond to binary digits, making binary the most efficient and reliable way to represent data and instructions electronically.
b. What are system software and application software? Give examples.
- System software: This includes programs that manage the hardware and software resources of the computer, such as operating systems (e.g., Windows, Linux, macOS).
- Application software: These are programs designed for end-users to perform specific tasks, such as word processors (e.g., Microsoft Word, Google Docs), web browsers (e.g., Google Chrome, Mozilla Firefox).
c. Find the subtraction of binary numbers 110101 – 1010 using the 2’s complement method.
- Find the 2’s complement of 1010:
- Invert the digits: 0101
- Add 1: 0101 + 1 = 0110
- Add this to 110101:
- 110101 + 0110 = 100011 (Disregard the carry, which is 1)
- Therefore, the result is 100011.
d. Find the output of the following C code:
#include <stdio.h> int main() { char c = 'A'; printf("\n c = %d", c); return 0; }The output will be:
c = 65because the ASCII value of ‘A’ is 65.e. Subtract (10101011)₂ – (011111)₂.
- First, align and pad the binary numbers:
- 10101011
- 00111111
- Perform binary subtraction:
- 10101011 – 00111111 = 01101100
- Therefore, the result is 01101100.
f. Show the memory representation of a two-dimensional array using an example.
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};Memory representation:
arr[0][0] -> 1 arr[0][1] -> 2 arr[0][2] -> 3 arr[1][0] -> 4 arr[1][1] -> 5 arr[1][2] -> 6g. Differentiate between
gets()andscanf().gets(): Reads a line of text from standard input until a newline character or end-of-file is encountered. Warning: Thegets()function is deprecated and considered unsafe due to potential buffer overflow vulnerabilities. It’s recommended to use safer alternatives likefgets().scanf(): Reads formatted input from standard input. It can read multiple values based on the format specifiers.
h. Define structures in C.
A structure in C is a user-defined data type that allows grouping variables of different types under a single name.
struct Student { char name[50]; int age; float marks; };
Section B
Attempt any two of the following:
a. Convert (111001100.1101)₂ into decimal and convert (11100110.1100011)₂ to octal.
Binary to decimal (111001100.1101)₂:
- Integer part: (1 * 2⁸) + (1 * 2⁷) + (1 * 2⁶) + (0 * 2⁵) + (0 * 2⁴) + (1 * 2³) + (1 * 2²) + (0 * 2¹) + (0 * 2⁰) = 256 + 128 + 64 + 8 + 4 = 460
- Fractional part: (1 * 2⁻¹) + (1 * 2⁻²) + (0 * 2⁻³) + (1 * 2⁻⁴) = 0.5 + 0.25 + 0.0625 = 0.8125
- Decimal value: 460 + 0.8125 = 460.8125
Binary to octal (11100110.1100011)₂:
- Group binary digits in sets of three from the decimal point, adding leading/trailing zeros if needed:
- Integer part: 111 001 100 -> 714
- Fractional part: .110 001 100 -> .614
- Octal value: (714.614)₈
- Group binary digits in sets of three from the decimal point, adding leading/trailing zeros if needed:
b. State the steps of the compilation and execution process of a C program with a diagram.
- Steps:
- Preprocessing: The preprocessor handles directives (e.g.,
#include,#define), expanding macros and including header files. - Compilation: The compiler translates the preprocessed code into assembly language.
- Assembly: The assembler converts the assembly code into machine code, creating an object file.
- Linking: The linker combines object files and libraries into an executable file.
- Execution: The operating system loads the executable into memory and runs it.
- Preprocessing: The preprocessor handles directives (e.g.,
c. Briefly discuss the importance of cache memory.
Cache memory is a small and fast memory that stores frequently accessed data and instructions, speeding up the overall processing time. It acts as a buffer between the CPU and the main memory (RAM), reducing the time the CPU needs to wait for data retrieval. When the CPU needs to access data, it first checks the cache. If the data is found in the cache (a cache hit), it can be accessed much faster than retrieving it from the main memory. If the data is not found in the cache (a cache miss), it is retrieved from the main memory and copied to the cache for faster access in the future.
Section C
Attempt any two of the following:
a. Explain the importance of the
switch–casestatement. In which situations is theswitch–casedesirable? Also, give its limitations.- Importance: The
switchstatement provides a clear and efficient way to handle multiple conditional branches based on the value of a variable or expression. It offers a more structured and readable alternative to using multipleif–else ifstatements, especially when dealing with a large number of possible values. - Desirable Situations:
- When you have a variable or expression that can take on a limited number of discrete values.
- When the code needs to perform different actions based on the specific value of the variable.
- When you want to improve code readability and maintainability compared to using multiple
if–else ifstatements.
- Limitations:
- It only works with integral or enumerated types (e.g.,
int,char,enum). It cannot be used with floating-point types (float,double) or strings. - All cases must be known at compile time. You cannot have cases based on runtime values or variables.
- It does not support range-based cases. Each case must be a specific value.
- It only works with integral or enumerated types (e.g.,
b. Write a C program to calculate the salary of an employee, given their basic pay (user input), HRA = 10% of basic pay, and TA = 5% of basic pay. Define HRA and TA as constants and use them to calculate the salary of the employee.
#include <stdio.h> #define HRA_PERCENTAGE 0.10 #define TA_PERCENTAGE 0.05 int main() { float basic, hra, ta, salary; printf("Enter basic pay: "); scanf("%f", &basic); hra = basic * HRA_PERCENTAGE; ta = basic * TA_PERCENTAGE; salary = basic + hra + ta; printf("Salary: %.2f\n", salary); return 0; }c. Why is nesting of
if–elsestatements necessary? Write a program to find the largest of three numbers using nestedif–elsestatements. (3+4)- Necessity: Nesting
if–elsestatements allows for more complex decision-making processes where multiple conditions must be evaluated in a hierarchical manner. It enables you to create multiple levels of conditions and execute different blocks of code based on the outcome of each condition.
#include <stdio.h> int main() { int a, b, c, largest; printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); if (a >= b) { if (a >= c) { largest = a; } else { largest = c; } } else { if (b >= c) { largest = b; } else { largest = c; } } printf("Largest number: %d\n", largest); return 0; }- Importance: The
Group A
Q1. Answer any six of the following:
What is
#include <stdio.h>?Answer: ii) Inclusion directive
Which of the following is not an operator in C?
Answer: ii)
sizeof()(It’s a compile-time operator)scanf()is a predefined function in which header file?Answer: iii)
stdio.hWhat will be the output of the following C code?
#include <stdio.h> int main() { int y = 10000; int y = 34; printf("Hello World! %d\n", y); return 0; }Answer: Compile-time error (due to redeclaration of the variable
y)Which
forloop has the range of similar indexes of ‘i’ used infor(i = 0; i < n; i++)?Answer: iii)
for(i = n - 1; i >= 0; i--)What will be the output of the following C code?
#include <stdio.h> void main() { int k = 0; for (k) printf("Hello"); }Answer: Compile-time error (due to incorrect use of the
forloop; it requires three expressions separated by semicolons)Where in C does the order of precedence of operators not exist?
Answer: iv) None of the mentioned (Operator precedence always exists in C)
12345 in octal is ______ in decimal.
Answer: 5349
Group B
Q2. Answer any two of the following:
State the differences between a
whileloop and ado-whileloop.whileloop:- The condition is checked before the execution of the loop’s body.
- The loop body may not execute at all if the condition is initially false.
do-whileloop:- The condition is checked after the execution of the loop’s body.
- The loop body will always execute at least once, even if the condition is initially false.
Draw the flowchart of an
if–else ifstatement.+---------------+ | Start | +---------------+ | v +---------------+ | Condition 1 | +---------------+ | +-----+-----+ | | | v v v True False Condition 2 Action 1 | +---------------+ +----->| | v v True False Condition N Action 2 | +---------------+ +----->| | v v True Default Action N Action | | +-----+-----+ | v +---------------+ | End | +---------------+Find the output of the following C code:
#include <stdio.h> int main() { int a = 4; printf("\n%d", 10 + a++); printf("\n%d", 10 + ++a); return 0; }Answer: The output will be:
14 16Explanation:
- In the first
printf()statement,a++uses the post-increment operator. This means the value ofa(which is 4) is used in the expression first, and then it’s incremented to 5. So,10 + a++evaluates to10 + 4 = 14. - In the second
printf()statement,++auses the pre-increment operator. This means the value ofa(which is now 5) is incremented to 6 first, and then the incremented value is used in the expression. So,10 + ++aevaluates to10 + 6 = 16.
- In the first
Mention the rules for naming a variable with an example.
- Variable names in C must begin with a letter (a-z, A-Z) or an underscore (_).
- They can contain letters, digits (0-9), and underscores.
- Keywords (reserved words in C) cannot be used as variable names.
- Variable names are case-sensitive (e.g.,
age,Age, andAGEare considered different variables). - Example:
int age;,float _salary;,char student_name[50];
Group C
Q3. Answer any two of the following:
Write a program to find the largest of three numbers using a ternary operator.
#include <stdio.h> int main() { int a, b, c, largest; printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); printf("Largest number: %d\n", largest); return 0; }What are header files? Why are they important? Can we write a C program without using any header file?
- Header files: Header files in C contain declarations for functions, macros, and data types that are used in the program. They provide the interface to the standard library and other libraries, allowing you to use pre-written code in your programs.
- Importance:
- Code reuse: Header files promote code reuse by providing access to pre-written functions and data types, saving you from having to write everything from scratch.
- Modularity: They help in organizing code into logical units, making it easier to manage and maintain.
- Abstraction: Header files hide the implementation details of functions and data types, allowing you to use them without needing to know how they are implemented.
- Writing without header files: Technically, you can write a C program without using any header files, but it’s highly impractical. You would need to manually declare all the functions and data types that you want to use, which would be time-consuming and error-prone. Additionally, you would lose the benefits of code reuse, modularity, and abstraction provided by header files.
Elaborate on the process of converting a binary number into a decimal with an example.
- Process:
- Start from the rightmost digit (least significant bit) of the binary number.
- Multiply each binary digit (0 or 1) by 2 raised to the power of its position index. The position index starts from 0 for the rightmost digit and increases by 1 for each subsequent digit to the left.
- Sum all the products obtained in step 2 to get the decimal equivalent.
- Example: Convert 1101₂ to decimal:
- (1 * 2³) + (1 * 2²) + (0 * 2¹) + (1 * 2⁰) = 8 + 4 + 0 + 1 = 13
- Therefore, 1101₂ is equal to 13 in decimal.
- Process:
Explain all the data types in terms of their declaration, size, and range.
char:- Declaration:
char variable_name; - Size: 1 byte
- Range: -128 to 127 (signed), 0 to 255 (unsigned)
- Purpose: Stores a single character (letter, digit, symbol).
- Declaration:
int:- Declaration:
int variable_name; - Size: Typically 4 bytes (but can vary depending on the system)
- Range: -2,147,483,648 to 2,147,483,647 (signed)
- Purpose: Stores whole numbers (integers).
- Declaration:
float:- Declaration:
float variable_name; - Size: 4 bytes
- Range: Approximately 3.4E-38 to 3.4E+38 (with approximately 7 digits of precision)
- Purpose: Stores single-precision floating-point numbers (numbers with decimal points).
- Declaration:
double:- Declaration:
double variable_name; - Size: 8 bytes
- Range: Approximately 1.7E-308 to 1.7E+308 (with approximately 15 digits of precision)
- Purpose: Stores double-precision floating-point numbers (numbers with decimal points and higher precision than
float).
- Declaration:
short:- Declaration:
short variable_name; - Size: 2 bytes
- Range: -32,768 to 32,767 (signed)
- Purpose: Stores short integers (smaller range than
int).
- Declaration:
long:- Declaration:
long variable_name; - Size: Typically 4 bytes (but can vary depending on the system)
- Range: -2,147,483,648 to 2,147,483,647 (signed)
- Purpose: Stores long integers (larger range than
inton some systems).
- Declaration:
void:- Declaration:
void - Size: N/A (represents the absence of a value)
- Range: N/A
- Purpose: Used to indicate that a function does not return a value or that a pointer has no specific type.
- Declaration:
Question 4
Attempt any two of the following:
Can we use a “for loop” when the number of iterations is not known in advance? If yes, give a program that illustrates how this can be done.
Answer: Yes, a “for loop” can be used when the number of iterations is not known in advance. This can be achieved by using a breaking condition inside the loop. The loop will continue to iterate until the breaking condition is met.
Example:
#include <stdio.h> int main() { int i = 0; int sum = 0; printf("Enter numbers to add (enter a negative number to stop):\n"); for (;;) { // Equivalent to while(1), an infinite loop int num; scanf("%d", &num); if (num < 0) { break; // Exit the loop when a negative number is entered } sum += num; i++; } printf("Sum of the entered numbers: %d\n", sum); printf("Number of iterations: %d\n", i); return 0; }Draw a flowchart and write a C program to calculate the sum of numbers from 1 to 10 using a
forloop.Flowchart:
+---------------+ | Start | +---------------+ | v +---------------+ | sum = 0 | +---------------+ | v +---------------+ | i = 1 | +---------------+ | v +---------------+ | i <= 10 | +---------------+ | +-----+-----+ | | | v v v True False End loop | v +---------------+ | sum = sum + i | +---------------+ | v +---------------+ | i = i + 1 | +---------------+ | ^ | +-----+ | v +---------------+ | Print sum | +---------------+ | v +---------------+ | End | +---------------+C Program:
#include <stdio.h> int main() { int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } printf("Sum of numbers from 1 to 10: %d\n", sum); return 0; }Write a C program to display the multiplication table of a number.
#include <stdio.h> int main() { int num, i; printf("Enter a number: "); scanf("%d", &num); printf("Multiplication table of %d:\n", num); for (i = 1; i <= 10; i++) { printf("%d x %d = %d\n", num, i, num * i); } return 0; }
Question 5
Attempt any one of the following:
How are structures different from arrays? Give the syntax for declaring a structure. Write a program to read and display the information of five students using an array of structures.
Differences between Structures and Arrays:
- Data types: Structures can hold variables of different data types, while arrays can only hold variables of the same data type.
- Memory allocation: Memory for structure members is allocated contiguously, but not necessarily for array elements (especially for dynamically allocated arrays).
- Purpose: Structures are used to represent a collection of related data items of different data types, while arrays are used to store a collection of data items of the same data type.
Syntax for declaring a structure:
struct structure_name { data_type member1; data_type member2; // ... more members };Program to read and display information of five students using an array of structures:
#include <stdio.h> struct Student { char name[50]; int roll_no; float marks; }; int main() { struct Student students[5]; int i; // Read student information for (i = 0; i < 5; i++) { printf("Enter details for student %d:\n", i + 1); printf("Name: "); scanf("%s", students[i].name); printf("Roll No: "); scanf("%d", &students[i].roll_no); printf("Marks: "); scanf("%f", &students[i].marks); printf("\n"); } // Display student information printf("Student Information:\n"); for (i = 0; i < 5; i++) { printf("Student %d:\n", i + 1); printf("Name: %s\n", students[i].name); printf("Roll No: %d\n", students[i].roll_no); printf("Marks: %.2f\n", students[i].marks); printf("\n"); } return 0; }Write a program to input two m×n matrices and then calculate the product of their corresponding elements and store it in a third m×n matrix.
#include <stdio.h> int main() { int m, n, i, j; printf("Enter the number of rows (m): "); scanf("%d", &m); printf("Enter the number of columns (n): "); scanf("%d", &n); int matrix1[m][n], matrix2[m][n], product[m][n]; // Input for matrix1 printf("Enter elements of the first matrix:\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { scanf("%d", &matrix1[i][j]); } } // Input for matrix2 printf("Enter elements of the second matrix:\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { scanf("%d", &matrix2[i][j]); } } // Calculate the product of corresponding elements for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { product[i][j] = matrix1[i][j] * matrix2[i][j]; } } // Display the product matrix printf("Product of the two matrices:\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%d\t", product[i][j]); } printf("\n"); } return 0; }
