2nd batch question solve
Question – 1
(a) Importance of Type Casting (4 Marks)
Type casting is converting a variable from one data type to another.
Importance:
• Prevents data loss or incorrect results.
• Allows operations between different data types.
• Improves program accuracy and readability.
Types of Type Casting:
1. Implicit Type Casting (Type Conversion)
o Done automatically by the compiler.
o Smaller data type → larger data type.
o Example:
o int a = 5;
o float b = a; // int → float automatically
o printf("%f", b); // Output: 5.000000
2. Explicit Type Casting (Type Casting by Programmer)
o Done manually by the programmer using (type) keyword.
o Example:
o int a = 10, b = 3;
o float c = (float)a / b; // Explicit cast
o printf("%.2f", c); // Output: 3.33
Improper Type Casting Example:
int a = 5;
char c = a; // May lose data if 'a' is too large
→ Problem: Data overflow, logical error, or inaccurate output.
(b) Difference between Static and Dynamic Memory Allocation
Feature Static Memory Allocation Dynamic Memory Allocation
When allocated At compile time At runtime
Memory size Fixed Flexible
Functions used None malloc(), calloc(), realloc(), free()
Example int arr[10]; int *arr = malloc(n * sizeof(int));
(c) Program for Dynamic Array and Sum (6 Marks)
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, sum = 0;
int *arr;
printf("Enter number of elements: ");
scanf("%d", &n);
arr = (int *)malloc(n * sizeof(int)); // Dynamic allocation
if (arr == NULL) {
printf("Memory not allocated.\n");
return 1;
}
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
printf("Sum = %d\n", sum);
free(arr); // Release memory
return 0;
Question – 2
(a) Standard vs User-defined Header Files (4 Marks)
Type Example Purpose
Standard Header File #include <stdio.h> Predefined system libraries
User-defined Header File #include "math_operations.h" Created by the programmer
(b) Create Two Files
File 1: math_operations.h
int add(int, int);
int subtract(int, int);
int multiply(int, int);
int divide(int, int);
File 2: main.c
#include <stdio.h>
#include "math_operations.h"
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divide(int a, int b) { return a / b; }
int main() {
int x, y;
printf("Enter two integers: ");
scanf("%d %d", &x, &y);
printf("Addition: %d\n", add(x, y));
printf("Subtraction: %d\n", subtract(x, y));
printf("Multiplication: %d\n", multiply(x, y));
printf("Division: %d\n", divide(x, y));
return 0;
(c) Power of a Number using Loop (6 Marks)
#include <stdio.h>
int main() {
int a, b, result = 1;
printf("Enter base and exponent: ");
scanf("%d %d", &a, &b);
for (int i = 1; i <= b; i++) {
result *= a;
printf("%d^%d = %d\n", a, b, result);
return 0;
Question – 3
(a) Purpose of const Keyword (4 Marks)
• Used to define constant values that cannot be changed.
• Improves code safety (prevents accidental changes).
• Improves readability by clearly defining constants.
Example:
const float PI = 3.1416;
(b) Built-in vs User-defined Data Types
Type Example Description
Predefined (Built-in) int, float, char, double Provided by C language
User-defined struct, enum, typedef, union Created by programmer
(c) Importance of break in Switch Case
• Terminates the current case block.
• Prevents “fall-through” into the next case.
Example:
switch(num) {
case 1: printf("One"); break;
case 2: printf("Two"); break;
(d) Leap Year Logic in C (2 Marks)
A year is leap if:
1. Divisible by 4 but not by 100, OR
2. Divisible by 400.
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
printf("Leap Year");
else
printf("Not Leap Year");
Question – 4
(a) Dangling Pointers & Memory Leaks (4 Marks)
Term Meaning Cause Prevention
Dangling Pointer pointing to Freeing memory but not Set pointer = NULL after
Pointer freed memory setting pointer to NULL free()
Memory Memory not Forgetting to free() Always free() dynamically
Leak released after use allocated memory allocated memory
(b) Count Number of Words in a String (4 Marks)
#include <stdio.h>
int main() {
char str[100];
int i, count = 1;
printf("Enter a string: ");
gets(str);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ')
count++;
printf("Number of words = %d\n", count);
return 0;
(c) Frequency Count & Sorting Explanation (6 Marks)
#include <stdio.h>
int main() {
int arr[] = {2, 3, 5, 2, 5, 5};
int count[101] = {0};
int size = sizeof(arr)/sizeof(arr[0]);
for (int i = 0; i < size; i++) {
count[arr[i]]++;
printf("Frequencies:\n");
for (int i = 0; i <= 100; i++) {
if (count[i] > 0)
printf("%d occurs %d times\n", i, count[i]);
// Sorting using count array
printf("Sorted array: ");
for (int i = 0; i <= 100; i++) {
for (int j = 0; j < count[i]; j++) {
printf("%d ", i);
printf("\n");
return 0;
Explanation:
The count array acts as a frequency table, and using it, you can print each number the
number of times it appears — effectively sorting the array (this is called Counting Sort).
Question – 5
(b) Output of the Following Code
Original Code (with corrections for clarity):
#include <stdio.h>
int countDown(int n) {
static int count;
if (n <= 0)
return count;
count++;
return countDown(n - 1);
int main() {
int x = 5;
printf("Total function calls: %d\n", countDown(x));
return 0;
Explanation:
• static int count → declared only once and retains its value between function calls.
• Each recursive call increments count by 1.
• The recursion ends when n <= 0.
• For n = 5, function calls are made with values:
5→4→3→2→1→0
⇒ 5 recursive calls.
Output:
Total function calls: 5
(e) Purpose of Functions in Structured Programming
Functions are reusable blocks of code designed to perform a specific task.
Purpose:
1. Modularity:
Breaks large programs into smaller, manageable sections.
2. Reusability:
Code written once can be used multiple times.
3. Maintainability:
Easier to debug, update, and test.
4. Abstraction:
Hides complex logic behind simple function calls.
Example:
int add(int a, int b) { return a + b; }
→ main() can simply call add(2,3) instead of repeating the logic.
Question – 6
(a) Define Recursion & Fibonacci Function
Recursion:
A function calling itself directly or indirectly until a base condition is met.
Program:
#include <stdio.h>
int fibonacci(int n) {
if (n == 0) return 0;
else if (n == 1) return 1;
else return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n;
printf("Enter position: ");
scanf("%d", &n);
printf("Fibonacci(%d) = %d\n", n, fibonacci(n));
return 0;
How it Works in Memory:
• Each recursive call is stored on the call stack.
• Example for fibonacci(4):
• fib(4)
• → fib(3) + fib(2)
• → fib(2)+fib(1) + fib(1)+fib(0)
• When base conditions are met (n==0 or n==1), recursion stops and results are
returned step by step.
(b) Recursive Depth and Limitations
Concept Explanation
Maximum number of nested function calls before reaching base
Recursion Depth
condition.
Each recursive call consumes memory on the stack; too deep recursion
Limitations
→ stack overflow or crash.
Performance
Repeated function calls → high CPU & memory usage.
Issue
Mitigation Use iteration (loops) or memoization to reduce redundant calls.
Question – 7
(a) File Functions: fopen, fclose, fprintf, fscanf
Function Purpose Example
fopen() Opens a file FILE *fp = fopen("[Link]", "w");
fclose() Closes a file fclose(fp);
fprintf() Writes formatted data to a file fprintf(fp, "Age = %d", age);
fscanf() Reads formatted data from a file fscanf(fp, "%d", &age);
Example Program:
#include <stdio.h>
int main() {
FILE *fp;
int age;
fp = fopen("[Link]", "w");
fprintf(fp, "My age is %d", 20);
fclose(fp);
fp = fopen("[Link]", "r");
fscanf(fp, "My age is %d", &age);
printf("Read from file: %d\n", age);
fclose(fp);
return 0;
}
(b) Output of Given Code Snippet
Let’s rewrite the snippet correctly (there were formatting issues):
#include <stdio.h>
int main() {
int a[5] = {2, 7, 4, 9, 3}, b = 6, i;
int *p = a, *q = p + 1, *r = &b;
*r = *q + 5; // b = 7 + 5 = 12
*p = 10; // a[0] = 10
for (i = 0; i < 5; i++)
printf("%d ", a[i]);
printf("\n%d", b);
return 0;
Step-by-step Execution:
Variable Operation Result
a {2,7,4,9,3} initial
b 6 initial
*r = *q + 5 b = 7 + 5 b = 12
*p = 10 a[0] = 10 a = {10,7,4,9,3}
Output:
10 7 4 9 3
12
(c) Sorting Structure Array by GPA (Descending) and Roll (Ascending)
#include <stdio.h>
struct Result {
float credit, cgpa;
};
struct Student {
int roll;
struct Result res;
};
int main() {
int n, i, j;
printf("Enter number of students: ");
scanf("%d", &n);
struct Student s[n], temp;
for (i = 0; i < n; i++) {
printf("Enter roll and cgpa for student %d: ", i + 1);
scanf("%d %f", &s[i].roll, &s[i].[Link]);
}
// Sort by cgpa (desc), if equal then roll (asc)
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (s[i].[Link] < s[j].[Link] ||
(s[i].[Link] == s[j].[Link] && s[i].roll > s[j].roll)) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
printf("\nSorted Students:\n");
for (i = 0; i < n; i++) {
printf("Roll: %d, CGPA: %.2f\n", s[i].roll, s[i].[Link]);
return 0;
Explanation:
• Sorting priority:
o 1st: Higher CGPA first.
o 2nd (tie): Lower roll number first.
1st batch question solve
Question – 1 (Answer any 7 out of 10)
(a) Necessity of Designing a Header File & Inclusion in C (2 marks)
Necessity:
• Header files store function declarations, macros, and constants that can be
reused in multiple programs.
• Helps in modular programming and code organization.
• Avoids rewriting the same code repeatedly.
Inclusion in Program:
• Standard header file:
• #include <stdio.h>
• User-defined header file:
• #include "myheader.h"
Here " " is used to include a header file from the current directory.
(b) Identify Infinite Loop (2 marks)
Will it be
Loop Reason
Infinite?
A. for(k=1;
Condition k>=1000 is false at start.
k>=1000; k++){}
B. for(k=0;
Condition false at start (0>=1000 false).
k>=1000; k=k*2){}
C. for(k=1024; k>0;
Stops when k becomes 0.
k=k/2){}
Will it be
Loop Reason
Infinite?
D. for(k=1024; Infinite Because k becomes 1 → then k=k/2 = 0 (integer), but still
k>=0; k=k/2){} Loop satisfies k>=0 forever as k remains 0 (no change).
Answer: Loop D executes infinitely because integer division keeps k at 0 indefinitely.
(c) Call by Value vs Call by Reference (2 marks)
Feature Call by Value Call by Reference
Definition Copies actual value into function argument Passes address of variable
Changes inside function do not affect original Changes affect original
Effect
variable variable
Example void fun(int a) void fun(int *a)
Example:
void fun(int a){ a=10; } // Call by value
void fun(int *a){ *a=10; } // Call by reference
(d) Two Variables with Same Name in Same Program (2 marks)
You cannot declare two variables with the same name in the same scope,
but you can declare them in different scopes, such as inside a function or block.
Example:
int x = 10;
void fun() {
int x = 5; // Allowed (different scope)
printf("%d", x);
The inner variable x hides the outer x.
(e) Dereference Operator Causing Segmentation Fault (2 marks)
A segmentation fault occurs when a pointer accesses invalid memory.
Example:
int *p = NULL;
printf("%d", *p); // Segmentation fault
Reason: Dereferencing (*p) a null or uninitialized pointer tries to access restricted
memory, causing a crash.
(f) Why Two-Dimensional Array for Space-Separated Strings (2 marks)
• A string is a 1D array of characters (char str[20]).
• To store multiple strings, we use a 2D array, where:
o Rows = number of strings
o Columns = max characters per string
Example:
char words[5][20]; // 5 strings, each up to 19 chars + '\0'
Each row can store one word (useful for storing sentences).
(g) Prefix vs Subsequence (2 marks)
Prefix: Continuous part starting from the beginning of the string.
Subsequence: Characters taken in order but not necessarily contiguous.
Example for string "PROGRAM":
• Prefix: "PRO", "PROG" (must start from beginning)
• Subsequence: "PGA", "POM" (not necessarily continuous)
Every prefix is a subsequence,
but every subsequence is not necessarily a prefix.
(h) Difference Between While and Do-While Loop (2 marks)
Feature while loop do-while loop
Condition checked Before the loop After the loop
Minimum execution 0 times At least once
Syntax while(condition){...} do{...} while(condition);
Example:
int i=0;
while(i>0){ printf("A"); } // Won’t run
do{ printf("B"); }while(i>0); // Prints once
(i) Difference Between struct and union (based on code) (2 marks)
struct student {
char name[50];
int roll;
float gpa;
};
union student {
char name[50];
int roll;
float gpa;
};
Feature struct union
Allocates memory for all Shares one common memory for all
Memory
members members
Access All members can be used at once Only one member valid at a time
Example struct size = sum of all union size = largest member
(j) Memory Allocation Procedure of an Array (2 marks)
• Arrays store elements in contiguous memory locations.
• Base address = address of the first element.
• Each element can be accessed using indexing.
Example:
int arr[3] = {10, 20, 30};
If base address = 1000 (and each int = 4 bytes):
Element Address
arr[0] 1000
arr[1] 1004
arr[2] 1008
Summary Table for Quick Revision
Sub Topic Key Idea
a Header files Reuse + modularity
b Infinite loop D infinite
c Call type Value vs reference
d Same name vars Different scopes
Sub Topic Key Idea
e Dereference fault Access invalid memory
f 2D array for strings Multiple words
g Prefix vs subsequence Prefix always substring
h while vs do-while Entry vs exit control
i struct vs union Separate vs shared memory
j Array memory Contiguous storage
PART–A
(i) Faster calculation of xⁿ using log₂(n) iterations
This can be done using Exponentiation by Squaring, which reduces time complexity from
O(n) → O(log₂n).
#include <stdio.h>
long long power(int x, int n) {
long long res = 1;
while (n > 0) {
if (n % 2 == 1)
res = res * x; // Multiply if n is odd
x = x * x; // Square the base
n = n / 2; // Divide exponent by 2
return res;
int main() {
int x, n;
printf("Enter base and exponent: ");
scanf("%d %d", &x, &n);
printf("%d^%d = %lld\n", x, n, power(x, n));
return 0;
Concept:
Instead of multiplying x n times, we square the base and halve the exponent each step,
giving O(log₂n) iterations.
(ii) Convert IPv4 Address to 32-bit Binary (No division/modulus allowed)
We can use bitwise operations to print binary representation of each octet.
#include <stdio.h>
void printBinary(int n) {
for (int i = 7; i >= 0; i--) {
int bit = (n >> i) & 1;
printf("%d", bit);
int main() {
int A, B, C, D;
printf("Enter IPv4 address (A B C D): ");
scanf("%d %d %d %d", &A, &B, &C, &D);
printBinary(A); printf(".");
printBinary(B); printf(".");
printBinary(C); printf(".");
printBinary(D); printf("\n");
return 0;
Concept:
The >> operator shifts bits, and & 1 extracts the rightmost bit — no division (/) or modulus
(%) needed.
Example Input:
172 16 0 1
Output:
10101100.00010000.00000000.00000001
(iii) Square Root without sqrt() (approximate, error ≤ 10⁻³)
We can use the Newton–Raphson method (fast convergence).
#include <stdio.h>
float squareRoot(float n) {
float x = n;
float y = 1;
float e = 0.0001; // allowed error
while (x - y > e) {
x = (x + y) / 2;
y = n / x;
return x;
int main() {
float n;
printf("Enter number: ");
scanf("%f", &n);
printf("Square root of %.2f = %.4f\n", n, squareRoot(n));
return 0;
Concept:
Starts with two guesses and iteratively averages them until the difference is minimal.
PART–B
(i) Define function for given graph f(x)
Since the graph details are partly missing, let’s assume a simple piecewise function based
on the provided axis hints.
Example assumption (you can edit as per actual graph):
f(x) = x^2, for 0 < x ≤ 2
f(x) = 5, for 2 < x ≤ 5
C implementation:
#include <stdio.h>
float f(float x) {
if (x > 0 && x <= 2)
return x * x;
else if (x > 2 && x <= 5)
return 5;
else
return 0;
int main() {
float x;
printf("Enter value of x: ");
scanf("%f", &x);
printf("f(%.2f) = %.2f\n", x, f(x));
return 0;
PART–A
(ii) Bitwise Operators in C
Explanation:
Bitwise operators work directly on the binary representation of integers.
For a 32-bit integer, the bits are indexed from 0 (least significant) to 31 (most significant).
How to Set a Particular Bit
To set (turn ON) a bit at position pos:
X = X | (1 << pos);
(1 << pos) shifts 1 to the left by pos bits, creating a mask like 000...0100, then OR (|)
sets that bit to 1.
Example:
Let X = 5 and Y = 6.
Value Binary (8-bit)
X = 5 00000101
Y = 6 00000110
Now let’s demonstrate bitwise operations:
#include <stdio.h>
int main() {
int X = 5, Y = 6;
printf("X = %d (", X);
for (int i = 7; i >= 0; i--) printf("%d", (X >> i) & 1);
printf(")\n");
printf("Y = %d (", Y);
for (int i = 7; i >= 0; i--) printf("%d", (Y >> i) & 1);
printf(")\n\n");
printf("Left shift (X << 3) = %d\n", X << 3); // 8 * X
printf("Right shift (Y >> 2) = %d\n", Y >> 2); // Y / 4
printf("Bitwise OR (X | Y) = %d\n", X | Y);
printf("Bitwise XOR (X ^ Y) = %d\n", X ^ Y);
printf("Bitwise AND (X & Y) = %d\n", X & Y);
return 0;
Output & Explanation
Operation Binary Result
X=5 00000101 5
Y=6 00000110 6
X << 3 00101000 40 (same as 8×X)
Y >> 2 00000001 1 (same as Y÷4)
X|Y 00000111 7
X^Y 00000011 3
X&Y 00000100 4
(1) Recursive Binary Search for First Occurrence
We must find the first index where x = 6 appears in:
arr = {3, 3, 4, 5, 5, 6, 6, 6, 6, 8}
Code:
#include <stdio.h>
int firstOccurrence(int arr[], int low, int high, int x) {
if (low > high)
return -1;
int mid = (low + high) / 2;
if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x)
return mid;
else if (x > arr[mid])
return firstOccurrence(arr, mid + 1, high, x);
else
return firstOccurrence(arr, low, mid - 1, x);
int main() {
int arr[] = {3, 3, 4, 5, 5, 6, 6, 6, 6, 8};
int n = 10, x = 6;
int index = firstOccurrence(arr, 0, n - 1, x);
if (index != -1)
printf("First occurrence of %d is at index %d\n", x, index);
else
printf("Element not found\n");
return 0;
State Diagram (for x = 6)
State low high mid arr[mid] Action
1 0 9 4 5 x > arr[mid] → Search Right
2 5 9 7 6 arr[mid] == x but not first → Search Left
3 5 6 5 6 Found first occurrence (mid=5)
Answer: First occurrence of 6 is at index 5.
(ii) Hex → RGB Conversion
Convert a hex string like "95FF53" or "95ff53" to RGB (149, 255, 83).
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
int hexToDec(char ch) {
if (ch >= '0' && ch <= '9') return ch - '0';
if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
return 0;
int main() {
char hex[7];
printf("Enter hex code (e.g. 95ff53): ");
scanf("%s", hex);
int r = hexToDec(hex[0]) * 16 + hexToDec(hex[1]);
int g = hexToDec(hex[2]) * 16 + hexToDec(hex[3]);
int b = hexToDec(hex[4]) * 16 + hexToDec(hex[5]);
printf("RGB = (%d, %d, %d)\n", r, g, b);
return 0;
Input: 95ff53
Output: RGB = (149, 255, 83)
(iii) Print Digits in Reverse (using recursion)
We print digits of a number without converting to string.
#include <stdio.h>
void Rev(int n) {
printf("%d", n % 10);
if (n / 10 != 0)
Rev(n / 10);
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
Rev(n);
return 0;
Input: 123
Output: 321
Input: 100
Output: 001
(To keep leading zeros, you’d handle the number as a string.)
PART–B
1. Recursive Function recursiveCount
Given incomplete code:
int recursiveCount(int n) {
if (n <= 0)
return 0;
return 1 + recursiveCount(n / 10);
Explanation:
• This function counts the number of digits in n.
• Example:
• recursiveCount(1234)
• = 1 + recursiveCount(123)
• = 1 + 1 + recursiveCount(12)
• = 1 + 1 + 1 + recursiveCount(1)
• =4
Output Example:
#include <stdio.h>
int recursiveCount(int n) {
if (n <= 0)
return 0;
return 1 + recursiveCount(n / 10);
int main() {
int n = 12345;
printf("Number of digits: %d\n", recursiveCount(n));
return 0;
Output:
Number of digits: 5
1. recursiveCount(45678)
Code snippet:
int recursiveCount(int n) {
if(n <= 0)
return 0;
return 1 + recursiveCount(n / 10);
int main() {
int result = recursiveCount(45678);
printf("%d\n", result);
return 0;
}
Step-by-step execution:
• recursiveCount(45678) → 1 + recursiveCount(4567)
• recursiveCount(4567) → 1 + recursiveCount(456)
• recursiveCount(456) → 1 + recursiveCount(45)
• recursiveCount(45) → 1 + recursiveCount(4)
• recursiveCount(4) → 1 + recursiveCount(0)
• recursiveCount(0) → 0
Sum: 1+1+1+1+1 = 5
Output:
Critical input that can fail:
• If n ≤ 0 initially, the function returns 0 (like recursiveCount(-123)), which may be
unexpected for counting digits.
• Another issue: very large integers can cause stack overflow.
2. trickyFunction(n)
Code snippet:
int trickyFunction(int n) {
if(n <= 0)
return 1;
return n + trickyFunction(n-1) - trickyFunction(n-2);
int main() {
int result = trickyFunction(5);
printf("%d\n", result);
return 0;
Step-by-step execution:
Let’s denote f(n) = trickyFunction(n).
Base: f(0) = 1, f(-1) = 1 (by recursion, n ≤ 0)
Now calculate:
• f(1) = 1 + f(0) - f(-1) = 1 + 1 - 1 = 1
• f(2) = 2 + f(1) - f(0) = 2 + 1 - 1 = 2
• f(3) = 3 + f(2) - f(1) = 3 + 2 - 1 = 4
• f(4) = 4 + f(3) - f(2) = 4 + 4 - 2 = 6
• f(5) = 5 + f(4) - f(3) = 5 + 6 - 4 = 7
Output:
PART-A (i) Pascal’s Triangle
Explanation:
• Each number in Pascal’s triangle is the sum of the two numbers directly above it.
• Formula for element at row i, column j:
𝐶(𝑖, 𝑗) = 𝐶(𝑖 − 1, 𝑗 − 1) + 𝐶(𝑖 − 1, 𝑗)
• First and last element of each row = 1.
C Program for Pascal’s Triangle:
#include <stdio.h>
int factorial(int n){
int f = 1;
for(int i = 1; i <= n; i++)
f *= i;
return f;
int combination(int n, int r){
return factorial(n) / (factorial(r) * factorial(n - r));
int main() {
int n;
printf("Enter height of Pascal's triangle: ");
scanf("%d", &n);
for(int i = 0; i < n; i++) {
for(int j = 0; j <= i; j++) {
printf("%d", combination(i, j));
printf("\n");
return 0;
Example Output for n=5:
1
11
121
1331
14641
PART-A (ii) Prime Number Flag Array Analysis
Code snippet analysis:
• flag[n+1] is an array where:
o flag[i] == 0 → possibly prime
o flag[i] > 0 → marked as composite
• The snippet is similar to Sieve of Eratosthenes, but written unclearly.
Simplified Understanding
Assume the intended logic:
int flag[n+1];
for(int i=0; i<=n; i++) flag[i] = 0;
flag[0] = flag[1] = 1; // 0 and 1 are not prime
for(int i=2; i*i <= n; i++) {
if(flag[i] != 0) continue; // skip non-prime
for(int j=i*i; j<=n; j+=i) {
flag[j] = 1; // mark multiples as composite
}
• After running for n = 50:
o flag[i] = 0 → i is prime
o flag[i] = 1 → i is not prime
Flag Array Values (0–50)
i 0 1 2 3 4 5 6 7 8 9 10 11 ... 50
flag 1 1 0 0 1 0 1 0 1 1 1 0 ... 1
• Prime numbers: indices with flag[i] == 0
• 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
Rule:
• Check flag[i]:
o 0 → prime
o 1 → not prime
1. Output of the given code snippet
Code snippet (corrected for readability):
#include <stdio.h>
int main() {
int a[5] = {2, 7, 4, 9, 3}, b = 6;
int *p, *q, *r;
p = a; // pointer to first element of a
q = a;
r = a + 2; // pointer to 3rd element
*(q + 1) = *q + 5; // a[1] = a[0] + 5 → 7 → 2+5 = 7 (already 7)
p = &b; // p points to b = 6
int i;
for (i = 0; i < 5; i++) {
printf("%d ", *q * *p); // multiply current *q by *p (b = 6)
q++;
return 0;
Step-by-step Execution:
• *p = 6 (points to b)
• *q = a[0] = 2 → print 2 * 6 = 12
• q++ → *q = a[1] = 7 → print 7 * 6 = 42
• q++ → *q = a[2] = 4 → print 4 * 6 = 24
• q++ → *q = a[3] = 9 → print 9 * 6 = 54
• q++ → *q = a[4] = 3 → print 3 * 6 = 18
Output:
12 42 24 54 18
PART-B (i) 3x3 Matrix Initialization and Sum
#include <stdio.h>
int main() {
int matrix[3][3];
int sum = 0;
int val = 1;
// Initialize matrix sequentially
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
matrix[i][j] = val++;
sum += matrix[i][j];
// Print matrix (optional)
printf("Matrix:\n");
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
printf("%d ", matrix[i][j]);
printf("\n");
printf("Sum of all elements = %d\n", sum);
return 0;
Explanation:
• Matrix values:
123
456
789
• Sum = 1+2+...+9 = 45
PART-B (ii) Count Occurrences of Target Integer in an Array
#include <stdio.h>
int main() {
int n, target, count = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter elements:\n");
for(int i=0;i<n;i++)
scanf("%d", &arr[i]);
printf("Enter target integer: ");
scanf("%d", &target);
for(int i=0;i<n;i++){
if(arr[i] == target)
count++;
printf("Occurrences of %d = %d\n", target, count);
return 0;
}
PART-A (i) Check if y is Suffix of s
#include <stdio.h>
#include <string.h>
int main() {
char s[100], y[100];
printf("Enter string s: ");
scanf("%s", s);
printf("Enter string y: ");
scanf("%s", y);
int len_s = strlen(s);
int len_y = strlen(y);
if(len_y > len_s){
printf("No, y is not a suffix of s\n");
} else if(strcmp(s + len_s - len_y, y) == 0){
printf("Yes, y is a suffix of s\n");
} else {
printf("No, y is not a suffix of s\n");
return 0;
}
Explanation:
• Suffix means last len_y characters of s must match y.
PART-A (ii) Student & Academic Sorting
Data Types:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int age;
int roll;
float cgpa;
} Academic;
typedef struct {
char name[50];
Academic ac;
} Student;
Sorting Criteria:
1. Descending cgpa
2. Descending age if cgpa same
3. Ascending roll if cgpa & age same
C Program:
int compare(const void *a, const void *b) {
Student *s1 = (Student*)a;
Student *s2 = (Student*)b;
if(s1->[Link] != s2->[Link])
return (s2->[Link] > s1->[Link]) ? 1 : -1; // descending cgpa
if(s1->[Link] != s2->[Link])
return s2->[Link] - s1->[Link]; // descending age
return s1->[Link] - s2->[Link]; // ascending roll
int main() {
Student arr[3] = {
{"Alice", {20, 101, 3.5}},
{"Bob", {22, 102, 3.5}},
{"Charlie", {22, 103, 3.7}}
};
int n = 3;
qsort(arr, n, sizeof(Student), compare);
for(int i=0;i<n;i++)
printf("%s %d %d %.2f\n", arr[i].name, arr[i].[Link], arr[i].[Link], arr[i].[Link]);
return 0;
}
Explanation:
• qsort() is used with a custom comparator function.
• Sorting handles multiple criteria in the specified order.
PART-A: Big Numbers in C
1. Data type for numbers larger than long long
• Standard long long can store up to ~9.2e18. Numbers beyond this are too large.
• In C, there is no built-in big integer type, so we can represent big numbers as
strings and implement arithmetic manually.
2. Function to Sum Two Big Numbers
#include <stdio.h>
#include <string.h>
void addBigNumbers(char num1[], char num2[]) {
int len1 = strlen(num1);
int len2 = strlen(num2);
int maxLen = (len1 > len2 ? len1 : len2) + 1;
int sum[maxLen];
for(int i = 0; i < maxLen; i++) sum[i] = 0;
// Add digits from right to left
int carry = 0;
for(int i = 0; i < maxLen - 1; i++) {
int digit1 = (len1 - 1 - i >= 0) ? num1[len1 - 1 - i] - '0' : 0;
int digit2 = (len2 - 1 - i >= 0) ? num2[len2 - 1 - i] - '0' : 0;
int temp = digit1 + digit2 + carry;
sum[maxLen - 1 - i] = temp % 10;
carry = temp / 10;
sum[0] = carry;
// Print result
int start = (sum[0] == 0) ? 1 : 0;
for(int i = start; i < maxLen; i++)
printf("%d", sum[i]);
printf("\n");
int main() {
char num1[1000], num2[1000];
printf("Enter first big number: ");
scanf("%s", num1);
printf("Enter second big number: ");
scanf("%s", num2);
printf("Sum = ");
addBigNumbers(num1, num2);
return 0;
Explanation:
• Store numbers as strings.
• Add digits from right to left, keeping track of carry.
• Works for arbitrarily large numbers.
PART-B (i) Using Pointers to Access Files
Explanation:
1. In C, FILE * pointer is used to access a file:
FILE *fp;
fp = fopen("[Link]", "r"); // open for reading
2. EOF (End of File):
• Used to detect the end of a file during reading.
• For example: while (fscanf(fp, "%d", &num) != EOF)
Program: Read integers from [Link] and append maximum
#include <stdio.h>
int main() {
FILE *fp;
int num, max;
// Open file in read mode
fp = fopen("[Link]", "r");
if(fp == NULL){
printf("File not found.\n");
return 1;
}
max = -2147483648; // smallest int
while(fscanf(fp, "%d", &num) != EOF) {
if(num > max) max = num;
fclose(fp);
// Open file in append mode
fp = fopen("[Link]", "a");
if(fp == NULL){
printf("Unable to open file.\n");
return 1;
fprintf(fp, "\nMaximum: %d\n", max);
fclose(fp);
printf("Maximum value appended successfully.\n");
return 0;
Explanation:
• Read all integers using fscanf() until EOF.
• Keep track of maximum.
• Re-open file in append mode ("a") to write maximum without deleting existing data.
PART-B (ii) Libraries in C
1. What is a library?
• A library is a collection of pre-written functions that programmers can use to
perform common tasks.
• Example: string.h provides functions for string operations.
2. Example Using string.h Functions
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[50] = "World";
// Compare two strings
if(strcmp(str1, str2) == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");
// Concatenate two strings
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
Explanation:
• strcmp(s1, s2) → returns 0 if strings are equal, negative if s1<s2, positive if s1>s2.
• strcat(s1, s2) → appends s2 to the end of s1.