MAKAUT Solved Paper · UPID : 002008

Programming for Problem Solving

B.Tech Even Semester Examination 2022–2023 · Paper Code: ESCS201 · Full Marks: 70

Group-A: Very Short Answer Type Questions Answer Any 10 · [ 1 x 10 = 10 Marks ]

1. (I) What is the use of continue in loop? [ 1 Mark ]

Answer: The continue statement is used inside loop structures (for, while, do-while) to prematurely skip the remaining statements inside the loop body for the current iteration and jump directly to the loop's continuation or condition evaluation for the next cycle.

1. (II) What is the string function used to reverse a string? [ 1 Mark ]

Answer: In legacy non-standard C libraries (like Borland Turbo C), the function strrev() is used to reverse a string in-place.
Note: Because strrev() is not part of the standard ANSI/ISO C library, standard C programs implement string reversal manually using two pointers swapping characters from the start and end of the string.

1. (III) What is the time complexity of Bubble sort? [ 1 Mark ]

Answer:
Worst and Average Case: \(O(n^2)\) (quadratic time).
Best Case: \(O(n)\) (linear time, when an optimized boolean swap flag is used on an already sorted input array).

1. (IV) What are preprocessor? [ 1 Mark ]

Answer: The C Preprocessor is a system program that processes the C source code text before the compiler begins syntax analysis. It executes preprocessor directives starting with `#` (such as #include for header file inclusion, #define for macro constants, and #ifdef for conditional compilation) and produces an expanded source code translation unit.

1. (V) Recursion uses which data structure? [ 1 Mark ]

Answer: Stack (specifically, the Runtime Call Stack).

Explanation: Every time a recursive function calls itself, a new stack frame (activation record) containing local variables, parameters, and return memory addresses is pushed onto the call stack. When the base case is reached and functions return, their frames are popped sequentially in LIFO (Last-In, First-Out) order.

1. (VI) What header file is used for string operation? [ 1 Mark ]

Answer: <string.h>.

Explanation: This standard library header declares essential string manipulation and memory handling functions such as strlen(), strcpy(), strcat(), strcmp(), memcpy(), and memset().

1. (VII) What is nested if-else? [ 1 Mark ]

Answer: A nested if-else statement refers to placing an entire if or if-else conditional block inside the body of another outer if or else block. It is used to test multi-level, hierarchical, or dependent logical decisions.

1. (VIII) & (XII) What is the use of goto statement in C? [ 1 Mark ]

Answer: The goto statement performs an unconditional jump from its current execution line to a user-defined label inside the same function scope (e.g., goto error_handler; ... error_handler:).

While generally discouraged in structured programming due to creating tangled "spaghetti code", its legitimate use case in C is clean error handling and jumping out of deeply nested multi-level loops where a simple break cannot reach.

1. (IX) What is linear searching in an array? [ 1 Mark ]

Answer: Linear Search (sequential search) is the simplest searching algorithm where we examine each array element sequentially from the beginning (index 0) to the end until a match for the target search key is found or the list is exhausted. Its worst-case time complexity is \(O(n)\).

1. (X) What is Macro? [ 1 Mark ]

Answer: A Macro is a fragment of code or a symbolic constant that has been assigned a name using the #define preprocessor directive. When the preprocessor runs, it performs inline text replacement—substituting every occurrence of the macro name in the code with its defined replacement text before compilation.

1. (XI) What is the value of the following if a=2 ?
printf("%d",--a);
[ 1 Mark ]

Console Output 1

Explanation: The operator --a is the pre-decrement operator. It decrements the value of variable a by 1 before the expression is evaluated or passed to printf. Thus, if \(a = 2\), `--a` changes \(a\) to 1 and immediately prints 1.

Group-B: Short Answer Type Questions Answer Any 3 · [ 5 x 3 = 15 Marks ]

2. What is structure? What is array of structures? Show with an example. [ 5 Marks ]

Structure Definition: A structure (struct) is a user-defined composite data type in C that groups together related variables of different data types under a single unified name. Each variable inside a structure is called a member.

Array of Structures: An array of structures is an array where each individual element is a structure variable of the same type. It is widely used to store tabular records, such as databases of students, employees, or books.

#include <stdio.h> // Defining a structure for a Book record struct Book { int id; char title[50]; float price; }; int main() { // Declaring and initializing an Array of 3 Book Structures struct Book library[3] = { {101, "Let Us C", 350.50}, {102, "Programming in ANSI C", 420.00}, {103, "Data Structures Using C", 550.75} }; printf("=== Library Book Catalog (Array of Structures) ===\n"); for (int i = 0; i < 3; i++) { printf("Book %d: ID=%d | Title: %-25s | Price: ₹%.2f\n", i + 1, library[i].id, library[i].title, library[i].price); } return 0; }
Sample Execution === Library Book Catalog (Array of Structures) === Book 1: ID=101 | Title: Let Us C | Price: ₹350.50 Book 2: ID=102 | Title: Programming in ANSI C | Price: ₹420.00 Book 3: ID=103 | Title: Data Structures Using C | Price: ₹550.75

3. Write a program to find roots of a quadratic equation. [ 5 Marks ]

Mathematical Formula: For a quadratic equation \(ax^2 + bx + c = 0\), the discriminant is \(D = b^2 - 4ac\).
• If \(D > 0\): Two real and distinct roots: \(r_1, r_2 = \frac{-b \pm \sqrt{D}}{2a}\).
• If \(D = 0\): Two real and equal roots: \(r_1 = r_2 = \frac{-b}{2a}\).
• If \(D < 0\): Complex conjugate roots: \(\text{Real Part} = \frac{-b}{2a}, \text{Imaginary Part} = \frac{\sqrt{-D}}{2a}\).

#include <stdio.h> #include <math.h> int main() { double a, b, c, discriminant, root1, root2, realPart, imagPart; printf("Enter coefficients a, b and c: "); if (scanf("%lf %lf %lf", &a, &b, &c) != 3 || a == 0) { printf("Error: Coefficient 'a' cannot be zero in a quadratic equation!\n"); return 1; } discriminant = b * b - 4 * a * c; printf("\n=== Quadratic Equation Roots Analysis ===\n"); printf("Equation : %.2fx^2 + %.2fx + %.2f = 0\n", a, b, c); if (discriminant > 0) { root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); printf("Nature : Two Real and Distinct Roots\n"); printf("Root 1 = %.4f\n", root1); printf("Root 2 = %.4f\n", root2); } else if (discriminant == 0) { root1 = root2 = -b / (2 * a); printf("Nature : Two Real and Equal Roots\n"); printf("Root 1 = Root 2 = %.4f\n", root1); } else { realPart = -b / (2 * a); imagPart = sqrt(-discriminant) / (2 * a); printf("Nature : Complex / Imaginary Conjugate Roots\n"); printf("Root 1 = %.4f + %.4fi\n", realPart, imagPart); printf("Root 2 = %.4f - %.4fi\n", realPart, imagPart); } return 0; }
Sample Output Cases Case 1 (Real Distinct): Enter coefficients a, b and c: 1 -5 6 Nature : Two Real and Distinct Roots Root 1 = 3.0000 | Root 2 = 2.0000 Case 2 (Complex Roots): Enter coefficients a, b and c: 1 2 5 Nature : Complex / Imaginary Conjugate Roots Root 1 = -1.0000 + 2.0000i | Root 2 = -1.0000 - 2.0000i

4. Draw flowchart to evaluate factorial of a numbers. [ 5 Marks ]

Below is the standard diagrammatic flowchart representation for calculating factorial \(N!\):

[ START ]
|
v
[ Input integer N ]
|
v
/ Is N < 0 ? \ ----( YES )----> [ Print "Error: Negative Input" ] --> [ STOP ]
\ /
| ( NO )
v
[ Initialize FACT = 1, I = 1 ]
|
+-------------+
| |
v |
/ Is I <= N ? \ | (NO: Loop Exits)
\ / --+----------------------------------+
| ( YES ) |
v v
[ FACT = FACT * I ] [ Print FACT ]
| |
v v
[ I = I + 1 ] [ STOP ]
|
+-----( Jump back to loop condition )

5. What is conditional operator? [ 5 Marks ]

Answer: The conditional operator (also known as the ternary operator) is the only operator in C that takes three operands. Its symbols are a question mark and a colon: ? :.

Syntax: condition ? expression_if_true : expression_if_false;
How it works: The compiler evaluates condition. If it evaluates to true (non-zero), the entire ternary expression yields the value of expression_if_true. If false (zero), it yields the value of expression_if_false. It serves as a compact, inline shorthand for simple if-else statements.

// Finding maximum of two numbers using ternary conditional operator int a = 45, b = 78; int max = (a > b) ? a : b; // Evaluates to b (78) printf("Maximum value is %d\n", max);

6. What will be output of the code below?
#include <stdio.h>
int main() {
  int a[5] = {1, 2, 3, 4, 5};
  int i;
  for (i = 0; i < 5; i++)
    if ((char)a[i] == '5')
      printf("%d\n", a[i]);
    else
      printf("FAIL\n");
}
[ 5 Marks ]

Console Output FAIL FAIL FAIL FAIL FAIL

Detailed Logic Breakdown:
1. Notice the condition in the if statement: if ((char)a[i] == '5').
2. The integer array contains numbers: 1, 2, 3, 4, 5. When element a[4] (which is the integer 5) is cast to a character via (char)a[i], it results in the character with ASCII decimal code 5 (an unprintable control code).
3. However, on the right side of the comparison, the character literal '5' (in single quotes) represents the ASCII digit '5', whose numeric decimal code is exactly 53!
4. Since integer 5 never equals ASCII code 53, the condition is false for all 5 array iterations! Thus, the else branch executes 5 times, printing FAIL on 5 lines.

Group-C: Long Answer Type Questions Answer Any 3 · [ 15 x 3 = 45 Marks ]

7. (a) What is the difference between Array and Structure? Show with example.
(b) What are the differences between Structure and Union? Show with example.
(c) Write a program using structure to take 10 students name, roll, marks and print the records with average marks.
[ 4 + 3 + 8 = 15 Marks ]

(a) Difference Between Array and Structure [4 Marks]:

Feature Array Structure (struct)
Data Types Homogeneous collection: all elements must have the exact same data type (e.g., all ints). Heterogeneous collection: members can be of completely different data types (int, float, char, array).
Element Access Elements are accessed via integer indices (subscripts) like arr[0]. Members are accessed using dot operator (.) or arrow operator (->) like s.name.

(b) Difference Between Structure and Union [3 Marks]:

In a structure, memory is allocated independently for all members simultaneously, making total size equal to the sum of members. In a union, all members share the exact same starting memory address, making total size equal to the largest single member. Thus, only one union member can be active at any given time.


(c) Program Using Structure for 10 Students with Average Marks [8 Marks]:

#include <stdio.h> #define N 10 struct Student { int roll; char name[50]; float marks; }; int main() { struct Student st[N]; float total_marks = 0.0, average; printf("=== Enter details for %d Students ===\n", N); for (int i = 0; i < N; i++) { printf("\nStudent %d:\n", i + 1); printf("Enter Roll Number : "); scanf("%d", &st[i].roll); printf("Enter First Name : "); scanf("%49s", st[i].name); printf("Enter Marks (0-100): "); scanf("%f", &st[i].marks); total_marks += st[i].marks; } average = total_marks / N; printf("\n=======================================================\n"); printf(" STUDENT ACADEMIC RECORDS \n"); printf("=======================================================\n"); printf("Roll No Name Marks \n"); printf("-------------------------------------------------------\n"); for (int i = 0; i < N; i++) { printf("%-10d %-29s %-8.2f\n", st[i].roll, st[i].name, st[i].marks); } printf("-------------------------------------------------------\n"); printf("Total Class Marks : %.2f / %d\n", total_marks, N * 100); printf("Class Average Marks : %.2f\n", average); printf("=======================================================\n"); return 0; }

8. (a) Write a program to check a number is even or odd.
(b) Write a program to check a number is prime or not.
(c) Add all even numbers from an array.
[ 5 + 5 + 5 = 15 Marks ]

(a), (b), (c) Integrated C Program Solving All Three Parts:

#include <stdio.h> #include <math.h> // Function for Part (a): Check Even or Odd void checkEvenOdd(int num) { if (num % 2 == 0) printf("%d is an EVEN number.\n", num); else printf("%d is an ODD number.\n", num); } // Function for Part (b): Check Prime or Not int isPrime(int num) { if (num <= 1) return 0; if (num == 2) return 1; if (num % 2 == 0) return 0; for (int i = 3; i <= sqrt(num); i += 2) { if (num % i == 0) return 0; } return 1; } // Function for Part (c): Sum of Even Numbers in Array int sumEvenInArray(const int arr[], int size) { int sum = 0; for (int i = 0; i < size; i++) { if (arr[i] % 2 == 0) { sum += arr[i]; } } return sum; } int main() { int val, n; // Part (a) Demo printf("--- Part (a): Even/Odd Test ---\nEnter an integer: "); scanf("%d", &val); checkEvenOdd(val); // Part (b) Demo printf("\n--- Part (b): Prime Test ---\nEnter an integer: "); scanf("%d", &val); if (isPrime(val)) printf("%d is a PRIME number.\n", val); else printf("%d is NOT a prime number.\n", val); // Part (c) Demo printf("\n--- Part (c): Sum of Even Array Elements ---\nEnter array size: "); scanf("%d", &n); int arr[n]; printf("Enter %d integers: ", n); for (int i = 0; i < n; i++) scanf("%d", &arr[i]); printf("Sum of all even numbers in array = %d\n", sumEvenInArray(arr, n)); return 0; }

9. (a) What is an Operating system?
(b) What are the functions of operation system?
(c) What is booting?
(d) What are the differences between compiler and Interpreter?
[ 4 + 4 + 3 + 4 = 15 Marks ]

(a) Operating System Definition [4 Marks]: An Operating System (OS) is system software that manages computer hardware and software resources and acts as an intermediary interface between computer users and physical CPU/memory hardware. Examples: Windows, Linux, macOS, Android.

(b) Functions of an OS [4 Marks]:
1. Process & Processor Management: Scheduling CPU time among concurrent running processes (multitasking).
2. Memory Management: Allocating and deallocating RAM memory space to programs dynamically.
3. File & Storage Management: Organizing data into hierarchical directories and files on disk drives.
4. I/O Device Management: Communicating with peripherals via hardware device drivers.

(c) What is Booting? [3 Marks]: Booting is the initial startup sequence executed by a computer when powered on. The BIOS/UEFI firmware runs Power-On Self-Tests (POST), locates the Master Boot Record (MBR), and loads the Operating System kernel from disk storage into active RAM memory.

(d) Compiler vs Interpreter [4 Marks]: A compiler translates the entire source code into a standalone machine code executable file in one pre-run batch, executing faster. An interpreter translates and executes source code line-by-line during runtime without creating a standalone binary file.

10. (a) Write a program to print diagonal matrix from 5 x 5 matrix.
(b) Write a program to concatenate two strings without using strcat() function in C.
(c) Write a program to sort n elements from an array.
[ 5 + 5 + 5 = 15 Marks ]

(a) Print Diagonal Elements of 5 x 5 Matrix [5 Marks]:

#include <stdio.h> int main() { int mat[5][5] = { {10, 2, 3, 4, 50}, {6, 20, 8, 90, 10}, {11, 12, 30, 14, 15}, {16, 70, 18, 40, 20}, {80, 22, 23, 24, 50} }; printf("Main Diagonal (i == j): "); for (int i = 0; i < 5; i++) printf("%d ", mat[i][i]); printf("\nSecondary Diagonal (i + j == 4): "); for (int i = 0; i < 5; i++) printf("%d ", mat[i][4 - i]); printf("\n"); return 0; }

(b) Concatenate Two Strings Without strcat() [5 Marks]:

#include <stdio.h> int main() { char str1[100] = "Hello, "; char str2[] = "MAKAUT Students!"; int i = 0, j = 0; while (str1[i] != '\0') i++; // Find end of first string while (str2[j] != '\0') { str1[i] = str2[j]; // Append character by character i++; j++; } str1[i] = '\0'; // Null-terminate concatenated string printf("Concatenated String: %s\n", str1); return 0; }

(c) Sort n Elements from an Array using Bubble Sort [5 Marks]:

#include <stdio.h> int main() { int n = 6, arr[] = {64, 34, 25, 12, 22, 11}; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } printf("Sorted Array: "); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); return 0; }

11. (a) Convert Binary to Decimal of \((1101.01)_2\).
(b) What is 2's Complement? Show by example.
(c) Using 2's Complement do \(10101_2 - 00111_2\).
(d) Convert Decimal to Octal \((5673)_{10}\).
[ 4 + 4 + 4 + 3 = 15 Marks ]

(a) Convert Binary to Decimal \((1101.01)_2\) [4 Marks]:
• Integer part: \(1 \times 2^3 + 1 \times 2^2 + 0 \times 2^1 + 1 \times 2^0 = 8 + 4 + 0 + 1 = 13\).
• Fractional part: \(0 \times 2^{-1} + 1 \times 2^{-2} = 0 + 0.25 = 0.25\).
• Total Decimal Value: \((13.25)_{10}\).

(b) What is 2's Complement? [4 Marks]:
The 2's complement of a binary number is obtained by first inverting all its bits (1's complement) and then adding 1 to the least significant bit (LSB). It is the universal standard representation for signed negative integers in computers because it allows arithmetic subtraction to be performed using addition circuitry without having two representations for zero.
Example: To find 2's complement of \(00111_2\) (+7):
1's complement (invert bits): `11000`
Add 1 to LSB: `11000 + 1` = 11001 (-7 in 5-bit 2's complement).

(c) Subtraction Using 2's Complement: \(10101_2 - 00111_2\) [4 Marks]:
We perform: \(10101_2 + (\text{2's complement of } 00111_2)\).
From (b), 2's complement of `00111` is `11001`.
Now add:
    `10101` (21 in decimal)
+   `11001` (-7 in decimal)
---
= `101110`
Since this is 5-bit arithmetic, we discard the final carry out (the 6th bit `1`).
Result: \(01110_2\) (which is exactly \(21 - 7 = 14_{10}\)!).

(d) Convert Decimal to Octal \((5673)_{10}\) [3 Marks]:
Divide repeatedly by 8 and record remainders from bottom to top:
• \(5673 \div 8 = 709\), remainder 1
• \(709 \div 8 = 88\), remainder 5
• \(88 \div 8 = 11\), remainder 0
• \(11 \div 8 = 1\), remainder 3
• \(1 \div 8 = 0\), remainder 1
Reading remainders from bottom to top: \((13051)_8\).