0% found this document useful (0 votes)
18 views41 pages

PPS - Winter 2022 Paper Solution

This document is an examination paper for the Programming for Problem Solving course at Gujarat Technological University, covering various topics in C programming. It includes questions on computer system components, flowchart symbols, data types in C, control structures, and programming tasks such as checking character types and calculating factorials. The exam consists of multiple-choice questions and programming exercises, with a total of 70 marks available.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views41 pages

PPS - Winter 2022 Paper Solution

This document is an examination paper for the Programming for Problem Solving course at Gujarat Technological University, covering various topics in C programming. It includes questions on computer system components, flowchart symbols, data types in C, control structures, and programming tasks such as checking character types and calculating factorials. The exam consists of multiple-choice questions and programming exercises, with a total of 70 marks available.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Seat No.

: ________
jagrutawaaz.com Enrolment No.___________

GUJARAT TECHNOLOGICAL UNIVERSITY


BE - SEMESTER–I & II(NEW) EXAMINATION – WINTER 2022
Subject Code:3110003 Date:07-03-2023
Subject Name:Programming for Problem Solving
Time:10:30 AM TO 01:00 PM Total Marks:70
Instructions:
1. Attempt all questions.
2. Make suitable assumptions wherever necessary.
3. Figures to the right indicate full marks.
4. Simple and non-programmable scientific calculators are allowed.
Marks
Q.1 (a) List out and briefly explain basic building blocks of Computer system. 03
(b) Describe various symbols used for preparing flow chart. 04
(c) List and explain different data types available in C. 07

Q.2 (a) Demonstrate the working of bitwise shift and sizeof operator with an 03
example.
(b) Differentiate while and do..while loop. 04
(c) Write a C program to check whether the entered character is alphabet, 07

z
digit, space or any special character.
OR aa
(c) Write a C program to print following pattern: 07
1
Aw
22
333
4444
ut

Q.3 (a) Find out error(s), if any in the following code and correct it: 03
int main() {
gr

if(10%2==0){
break;
Ja

}
}
(b) Examine following code and give output of it. 04
void main(){
int a=0;
while (a<10) {
a++;
if (a%3==1) {
continue;
}
printf (" %d", a);
}}
(c) Write a C program to find factorial of a given number. 07
OR
Q.3 (a) Find out error(s), if any in the following code and correct it: 03
int main() {
printf(“%f %d”, 7.0%5.0, 5 || -2);
}
(b) Examine following code and give output of it. 04
void main(){
int i=1;
Youtube: Jagrut Awaaz
1
jagrutawaaz.com for (i=10; i>=1 ; --i) {
printf (“ %d”, i);
i--;
}
}
(c) Write a C program to make sum of digits of a given number. (if input is 07
145, output should be 10)

Q.4 (a) Difference between call by value and call by reference. 03


(b) Explain the concept of recursion with an example. 04
(c) Write a C program to make sum of array elements. 07
OR
Q.4 (a) Briefly explain storage class auto and extern. 03
(b) Explain switch statement with an example. 04
(c) Write a C program to sort an array in ascending order. 07

Q.5 (a) Give the significance of getc(), getw(), fscanf(). 03


(b) Compare structure and union. 04
(c) Describe categories of User defined function. 07
OR
Q.5 (a) List down and briefly explain methods for dynamic memory allocation. 03
(b) Write a C program to copy content of one file to other with the help of file 04

z
handling functions.
aa
(c) Explain any four string handling functions with an example. 07
Aw
ut
gr
Ja

Youtube: Jagrut Awaaz


2
PPS
jagrutawaaz.com WINTER-2022

Q.1 (a) List out and briefly explain basic building blocks of Computer
system.
Ans.
➢ Central Processing Unit (CPU): Often referred to as the brain of
the computer, the CPU performs arithmetic and logical operations,
controls the flow of data, and executes instructions from
programs.
➢ Memory: This is where data and instructions are stored
temporarily or permanently. It includes:
RAM (Random Access Memory): Volatile memory that provides
space for the CPU to read and write data quickly. It is cleared

z
when the computer is turned off.
aa
ROM (Read-Only Memory): Non-volatile memory that stores
Aw
critical system instructions and firmware.
➢ Storage: Used for long-term data storage. It includes:
ut

Hard Drive (HDD) / Solid-State Drive (SSD): Devices used to store


operating systems, applications, and files.
gr

➢ Motherboard: The main circuit board that connects all the


Ja

components of the computer. It provides pathways for data to


travel between the CPU, memory, storage, and peripheral devices.
➢ Input Devices: Devices used to enter data into the computer.
Examples include keyboards, mice, and scanners.
➢ Output Devices: Devices that display or output information from
the computer. Examples include monitors, printers, and speakers.
➢ Power Supply Unit (PSU): Converts electrical power from an
outlet into a usable form for the computer’s components.
➢ Bus: A communication system that transfers data between
components within the computer. It can be parallel or serial and
includes data, address, and control buses.

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

(b) Describe various symbols used for preparing flow chart.


Ans.
Flowcharts use various symbols to represent different types of
actions or steps in a process.
1. Oval (Start/End): Represents the start or end of a flowchart. It
is used to denote the beginning and conclusion of a process.
2. Rectangle (Process): Indicates a process or operation where an
action is performed, such as a calculation or a data
manipulation step.
3. Diamond (Decision): Represents a decision point where the

z
process flow branches based on a condition (e.g., yes/no or
true/false). aa
4. Parallelogram (Input/Output): Used to show input to or output
Aw

from a process, such as user data entry or display of results.


5. Arrow (Flow Line): Indicates the direction of the flow of control
ut

from one step to the next.


gr

6. Circle (Connector): Used to connect different parts of a


flowchart, especially when the flowchart is split across multiple
Ja

pages or sections.
7. Document (Document): Represents a document or report that
is part of the process.
8. Predefined Process (Subroutine): Indicates a predefined
process or a set of operations that is defined elsewhere. It
represents a complex process that is not detailed in the current
flowchart.

(c) List and explain different data types available in C.


Ans.

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

➢ Integer Types:
• int: Represents integer values. The size of int is typically 4 bytes
(32 bits), but this can vary depending on the system.
• short: Represents smaller integer values. It usually takes 2 bytes
(16 bits).
• long: Represents larger integer values. It is typically 4 bytes (32
bits) or 8 bytes (64 bits), depending on the system.
• long long: Represents even larger integer values. It is usually 8
bytes (64 bits).
Each of these types can be signed or unsigned:

z
• signed: Can represent both positive and negative values.

aa
unsigned: Can only represent non-negative values (zero and
Aw
positive numbers).
➢ Character Type:
ut

• char: Represents single characters. It usually takes 1 byte (8


bits). Characters are typically stored using ASCII or Unicode
gr

encoding.
Ja

➢ Floating-Point Types:
• float: Represents single-precision floating-point numbers. It
typically uses 4 bytes (32 bits) and has about 7 decimal digits of
precision.
• double: Represents double-precision floating-point numbers. It
usually takes 8 bytes (64 bits) and has about 15 decimal digits
of precision.
• long double: Represents extended-precision floating-point
numbers. The size and precision can vary but it is generally
larger than double (e.g., 12 or 16 bytes).

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

➢ Void Type:
• void: Represents the absence of data. It is used in function
declarations to indicate that the function does not return a
value or as a pointer type to represent a generic pointer (e.g.,
void *).
➢ Derived Data Types:
• array: A collection of elements of the same type stored in
contiguous memory locations.
• pointer: A variable that stores the memory address of another
variable.

z
• structure: A user-defined data type that groups related
aa
variables of different types under a single name.
• union: A user-defined data type that allows storing different
Aw

data types in the same memory location, but only one member
at a time.
ut

➢ Enumerated Type:
gr

• enum: A user-defined data type that consists of a set of named


integer constants. It is used to define variables that can only
Ja

hold a set of predefined values.

Q.2 (a) Demonstrate the working of bitwise shift and sizeof


operator with an example.
Ans.
➢ Bitwise Shift Operators
Bitwise shift operators shift the bits of a number to the left or
right. In C, we have two bitwise shift operators:
1. Left Shift (<<): Shifts bits to the left, effectively multiplying the
number by 2^n, where n is the number of positions shifted.

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

2. Right Shift (>>): Shifts bits to the right, effectively dividing the
number by 2^n, where n is the number of positions shifted.
➢ Example:
#include <stdio.h>

int main() {
unsigned int num = 8; // Binary: 0000 1000

// Left shift by 2 positions


unsigned int leftShift = num << 2; // Binary:
0010 0000 (32 in decimal)

z
aa
printf("Left Shift: %d << 2 = %d\n", num,
leftShift);
Aw

// Right shift by 2 positions


unsigned int rightShift = num >> 2; // Binary:
ut

0000 0010 (2 in decimal)


gr

printf("Right Shift: %d >> 2 = %d\n", num,


rightShift);
Ja

return 0;
}

➢ sizeof Operator
The sizeof operator is used to determine the size of a data type
or variable in bytes.
➢ Example:
#include <stdio.h>

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

int main() {
int intVar = 0;
float floatVar = 0.0;
char charVar = 'a';

printf("Size of int: %zu bytes\n",


sizeof(intVar));
printf("Size of float: %zu bytes\n",
sizeof(floatVar));
printf("Size of char: %zu bytes\n",

z
sizeof(charVar));
aa
printf("Size of int: %zu bytes\n",
sizeof(int)); // Directly with data type
Aw
printf("Size of float: %zu bytes\n",
sizeof(float)); // Directly with data type
ut

return 0;
gr

}
Ja

(b) Differentiate while and do..while loop.


Ans.
SR.NO while loop do-while loop

1. While the loop is an entry The do-while loop is an exit


control loop because control loop because in this,
firstly, the condition is first of all, the body of the loop
checked, then the loop's is executed then the condition
body is executed. is checked true or false.

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

2. The statement of while The statement of the do-while


loop may not be executed loop must be executed at least
at all. once.
3. The while loop As long as the condition is
terminates when the true, the compiler keeps
condition becomes false. executing the loop in the do-
while loop.
4. In a while loop, the test In a do-while loop, the variable
condition variable must of test condition Initialized in
be initialized first to check the loop also.
the test condition in the

z
loop.
5. In a while loop, at the
aa
In this, at the end of the
end of the condition, condition, there is a
Aw

there is no semicolon. semicolon.


Syntax: Syntax:
ut

while (condition) while (condition);


gr
Ja

(c) Write a C program to check whether the entered character is


alphabet, digit, space or any special character.
Ans.
#include <stdio.h>
#include <ctype.h> // For isalpha, isdigit, and
isspace functions

int main() {
char ch;

// Prompt the user to enter a character

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

printf("Enter a character: ");


scanf("%c", &ch);

// Check if the character is an alphabet


if (isalpha(ch)) {
printf("The character '%c' is an
alphabet.\n", ch);
}
// Check if the character is a digit
else if (isdigit(ch)) {
printf("The character '%c' is a

z
digit.\n", ch);
}
aa
Aw
// Check if the character is a space
else if (isspace(ch)) {
printf("The character '%c' is a
ut

space.\n", ch);
gr

}
Ja

// If none of the above, it is a special


character
else {
printf("The character '%c' is a special
character.\n", ch);
}

return 0;
}

OR
(c) Write a C program to print following pattern:

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

1
22
333
4444
Ans.
#include <stdio.h>

int main() {
int i, j;

z
aa
// Loop to control the number of rows
for (i = 1; i <= 4; i++) {
Aw
// Loop to print each number in the row
for (j = 1; j <= i; j++) {
ut

printf("%d ", i);


gr

}
// Move to the next line after printing
Ja

all numbers in the current row


printf("\n");
}

return 0;
}

Q.3 (a) Find out error(s), if any in the following code and correct it:
int main() {
if(10%2==0){
break;

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

}
}

Ans.
The code provided has an issue because break is used
incorrectly outside of a loop or switch statement. The break
statement is intended to be used within loops (for, while, do-while)
or switch statements to exit from them. In the given code, break is
used in the if statement, which is not allowed.
➢ Corrected code:
#include <stdio.h>

z
int main() {
if (10 % 2 == 0) {
aa
Aw
// Use of `break` is not appropriate
here, so we will use a different statement
printf("10 is divisible by 2\n");
ut

}
gr

return 0;
Ja

(b) Examine following code and give output of it.


#include <stdio.h>

void main() {
int a = 0;
while (a < 10) {
a++;
if (a % 3 == 1) {
continue;

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

}
printf(" %d", a);
}
}

Ans.
➢ Code Analysis:
1. Initialization: a is initialized to 0.
2. Loop: The while loop continues as long as a is less than 10.
3. Increment: Inside the loop, a is incremented by 1 with a++.
4. Condition Check: The if statement checks if a % 3 == 1. If true,

z
aa
continue is executed, which skips the rest of the loop body and
goes to the next iteration.
Aw
5. Printing: If a % 3 != 1, the printf function is executed to print the
value of a.
ut

➢ Output:
gr

The continue statement causes the loop to skip printing when a %


3 == 1. For values of a where a % 3 is not 1, the value is printed.
Ja

(c) Write a C program to find factorial of a given number.


Ans.
#include <stdio.h>

// Function prototype
int factorial(int n);

int main() {
int num;

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

// Input from the user


printf("Enter a number: ");
scanf("%d", &num);

// Check for negative input


if (num < 0) {
printf("Factorial is not defined for negative
numbers.\n");
} else {
// Calculate factorial using the recursive

z
function
aa
printf("Factorial of %d is %d\n", num,
factorial(num));
Aw

}
ut

return 0;
gr

}
Ja

// Recursive function to find factorial


int factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n == 0 || n == 1) {
return 1;
} else {
// Recursive case: n * factorial of (n-1)
return n * factorial(n - 1);
}
}

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

OR
Q.3 (a) Find out error(s), if any in the following code and correct it:
int main() {
printf(“%f %d”, 7.0%5.0, 5 || -2);
}
Ans.
➢ Invalid Use of % Operator with Floating-Point Numbers:
• The % operator is only applicable to integer types. In the code,
7.0 % 5.0 attempts to use % with floating-point numbers, which
is not allowed.

z
aa
➢ Incorrect Use of || Operator in printf:
• The || operator is a logical OR operator, which returns 1 for
Aw

true and 0 for false. The expression 5 || -2 will always be 1


because any non-zero value in a logical context is treated as
true.
ut

➢ Corrected Code:
gr

#include <stdio.h>
Ja

int main() {
// Corrected version of the code
// Print only valid expressions
printf("%d %d\n", 5 % 2, 5 || -2);
return 0;
}

(b) Examine following code and give output of it.


#include <stdio.h>

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

void main() {
int i = 1;
for (i = 10; i >= 1; --i) {
printf(" %d", i);
i--;
}
}

Ans.
➢ Code Analysis:

z
1. Initialization:
o
aa
int i = 1; initializes i to 1, but this value is immediately
Aw
overridden by the for loop initialization.
2. For Loop:
ut

o Initialization: i is set to 10.


gr

o Condition: The loop continues while i >= 1.


Ja

o Update: --i decrements i by 1 at the end of each iteration,


but i-- inside the loop also decrements i by 1.
3. Loop Execution:
o In each iteration, printf(" %d", i); prints the current value
of i.
o After printing, i-- is executed, which decrements i by 1.
➢ Execution Steps:
1. First Iteration:
o i starts at 10.
o Print 10.

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

o Decrement i by 1 in the printf statement, so i becomes 9.


o Decrement i by 1 again in the loop body, so i becomes 8.
2. Second Iteration:
o i is 8.
o Print 8.
o Decrement i by 1, so i becomes 7.
o Decrement i by 1 again, so i becomes 6.
3. Third Iteration:
o i is 6.

z
o Print 6. aa
o Decrement i by 1, so i becomes 5.
Aw

o Decrement i by 1 again, so i becomes 4.


4. Fourth Iteration:
ut

o i is 4.
gr

o Print 4.
Ja

o Decrement i by 1, so i becomes 3.
o Decrement i by 1 again, so i becomes 2.
5. Fifth Iteration:
o i is 2.
o Print 2.
o Decrement i by 1, so i becomes 1.
o Decrement i by 1 again, so i becomes 0.
6. End of Loop:

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

o The loop condition i >= 1 fails because i is now 0, so the


loop ends.
➢ Output:
The output of the code is:
10 8 6 4 2

(c) Write a C program to make sum of digits of a given number. (if


input is 145, output should be 10)
Ans.
#include <stdio.h>

z
int main() {
aa
Aw
int number, sum = 0, digit;

// Prompt the user to enter a number


ut

printf("Enter a number: ");


gr

scanf("%d", &number);
Ja

// Store the original number for later use


int temp = number;

// Handle negative numbers by taking their


absolute value
if (number < 0) {
number = -number;
}

// Loop to calculate the sum of digits

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

while (number > 0) {


// Extract the last digit of the number
digit = number % 10;
// Add the digit to the sum
sum += digit;
// Remove the last digit from the number
number /= 10;
}

// Output the result


printf("Sum of digits of %d is %d\n", temp,

z
sum); aa
Aw
return 0;
}
ut
gr

Q.4 (a) Difference between call by value and call by reference.


Ans.
Ja

Call By Value Call By Reference


While calling a function, we pass While calling a function, instead of
the values of variables to it. Such passing the values of variables, we
functions are known as “Call By pass the address of variables(location
Values”. of variables) to the function known as
“Call By References.

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

In this method, the value of each In this method, the address of actual
variable in the calling function is variables in the calling function is
copied into corresponding copied into the dummy variables of
dummy variables of the called the called function.
function.

With this method, the changes With this method, using addresses
made to the dummy variables in we would have access to the actual
the called function have no variables and hence we would be
effect on the values of actual able to manipulate them.
variables in the calling function.

z
the values of actual variables
aa
In call-by-values, we cannot alter In call by reference, we can alter the
values of variables through function
Aw
through function calls. calls.
ut
gr

(b) Explain the concept of recursion with an example.


Ja

Ans.
Recursion is a programming concept where a function calls
itself to solve a problem. The recursive approach divides a problem
into smaller sub-problems of the same type, solving each sub-
problem in turn. This process continues until a base case is reached,
which stops the recursion.
Base Case:
• The condition under which the recursion stops. It prevents
infinite recursion and allows the function to terminate.
Recursive Case:

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

• The part of the function where the function calls itself to


handle smaller instances of the problem.
Example:
#include <stdio.h>

// Recursive function to calculate factorial


int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;

z
}
aa
// Recursive case: factorial of n is n times
factorial of (n-1)
Aw
else {
return n * factorial(n - 1);
ut

}
gr

}
Ja

int main() {
int num;

// Prompt the user to enter a number


printf("Enter a non-negative integer: ");
scanf("%d", &num);

// Check if the number is non-negative


if (num < 0) {

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

printf("Factorial is not defined for


negative numbers.\n");
} else {
// Calculate and print the factorial
printf("Factorial of %d is %d\n", num,
factorial(num));
}

return 0;
}

(c) Write a C program to make sum of array elements.

z
Ans. aa
#include <stdio.h>
Aw

int main() {
ut

int n, i;
int sum = 0;
gr
Ja

// Prompt the user to enter the number of


elements
printf("Enter the number of elements in the
array: ");
scanf("%d", &n);

// Declare an array of size 'n'


int arr[n];

// Prompt the user to enter the elements of


the array

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

printf("Enter %d elements:\n", n);


for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Calculate the sum of the array elements


for (i = 0; i < n; i++) {
sum += arr[i];
}

// Print the result

z
aa
printf("Sum of the array elements is %d\n",
sum);
Aw

return 0;
ut

}
gr

OR
Ja

Q.4 (a) Briefly explain storage class auto and extern.


Ans.
➢ auto Storage Class:
1. Scope:
o The auto storage class is the default for local variables in
C. It limits the scope of the variable to the block (usually a
function) in which it is defined.
2. Lifetime:

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

o The lifetime of an auto variable is limited to the execution


of the block in which it is defined. Once the block is
exited, the variable is destroyed and its memory is
reclaimed.
3. Initialization:
o An auto variable is not automatically initialized; it holds an
indeterminate value until it is explicitly initialized.
4. Usage:
o In practice, auto is rarely used explicitly since it is the
default storage class for local variables. You typically do
not need to specify auto explicitly unless for clarity or

z
educational purposes. aa
➢ extern Storage Class:
Aw

1. Scope:
o The extern storage class extends the visibility of a variable
ut

or function to other files or translation units. It allows you


gr

to declare a variable or function that is defined in another


file.
Ja

2. Lifetime:
o An extern variable has a global lifetime, meaning it exists
for the duration of the program. However, it must be
defined in one source file.
3. Initialization:
o The extern declaration does not initialize the variable. It is
only a declaration that tells the compiler that the variable
is defined elsewhere.
4. Usage:

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

o Use extern to declare a variable or function in one file that


is defined in another. This is useful for sharing global
variables or functions between different files.

(b) Explain switch statement with an example.


Ans.
The switch statement in C is a control flow statement that
allows you to select one of many code blocks to be executed based
on the value of an expression. It's often used when you need to
choose between multiple possible execution paths based on the
value of a single variable.

z
➢ Syntax of switch Statement: aa
switch (expression) {
Aw

case constant1:
// Code to execute if expression ==
ut

constant1
break;
gr

case constant2:
Ja

// Code to execute if expression ==


constant2
break;
// More cases can be added
default:
// Code to execute if none of the cases
match
}

➢ Example:
#include <stdio.h>

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

int main() {
int day;

// Prompt the user to enter a day number


printf("Enter a number (1-7) to get the
corresponding day of the week: ");
scanf("%d", &day);

// Switch statement to determine the day of


the week

z
switch (day) {
case 1:
aa
Aw
printf("Monday\n");
break;
case 2:
ut

printf("Tuesday\n");
gr

break;
Ja

case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid input. Please enter a
number between 1 and 7.\n");
break;
}

z
return 0; aa
}
Aw

(c) Write a C program to sort an array in ascending order.


ut

Ans.
gr

#include <stdio.h>
Ja

// Function to perform Bubble Sort


void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
// Swap if the element found is
greater than the next element
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

arr[j+1] = temp;
}
}
}
}

// Function to print the array


void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);

z
} aa
printf("\n");
Aw

}
ut

int main() {
gr

int n, i;
Ja

// Prompt the user to enter the number of


elements
printf("Enter the number of elements in the
array: ");
scanf("%d", &n);

// Declare an array of size 'n'


int arr[n];

// Prompt the user to enter the elements of


the array

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

printf("Enter %d elements:\n", n);


for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Sort the array


bubbleSort(arr, n);

// Print the sorted array


printf("Sorted array in ascending order:\n");
printArray(arr, n);

z
aa
return 0;
Aw

Q.5 (a) Give the significance of getc(), getw(), fscanf().


ut

Ans.
gr

➢ getc()
Ja

Significance:
• Function: int getc(FILE *stream);
• Purpose: Reads the next character from the specified file
stream.
• Return Value: Returns the next character as an unsigned char
cast to an int or EOF if end-of-file is reached or an error
occurs.
• Usage: Useful for reading single characters from a file or input
stream one at a time.
➢ getw()

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

Significance:
• Function: int getw(FILE *stream);
• Purpose: Reads an integer from the specified file stream.
• Return Value: Returns the integer read from the file or EOF if
end-of-file is reached or an error occurs.
• Usage: Useful for reading integer values from a file. Note that
getw() is less commonly used today due to its dependence
on machine architecture and lack of portability.
➢ fscanf()
Significance:

z
• aa
Function: int fscanf(FILE *stream, const char *format, ...);
• Purpose: Reads formatted input from the specified file
Aw
stream. It can be used to read various data types, including
integers, floats, and strings, according to the specified format
string.
ut

• Return Value: Returns the number of items successfully read


gr

and assigned, or EOF if an error occurs or end-of-file is


Ja

reached.
• Usage: Useful for reading and parsing formatted input from a
file or input stream, similar to scanf() but for file streams.

(b) Compare structure and union.


Ans.
Parameter Structure Union

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

Keyword A user can deploy the A user can deploy the


keyword struct to keyword union to define a
define a Structure. Union.
Internal The implementation of In the case of a Union, the
Implementation Structure in C occurs memory allocation occurs
internally- because it for only one member with
contains separate the largest size among all
memory locations the input variables. It
allotted to every input shares the same location
member. among all these
members/objects.

z
Accessing A user can access A user can access only one
Members aa
individual members at
a given time.
member at a given time.
Aw

Syntax The Syntax of declaring The Syntax of declaring a


a Structure in C is: Union in C is:
ut

struct [structure name] union [union name]


gr

{ {
Ja

type element_1; type element_1;


type element_2; type element_2;
. .
. .
} variable_1, } variable_1, variable_2, …;
variable_2, …;

(c) Describe categories of User defined function.


Ans.

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

1. Functions with No Arguments and No Return Value


Definition:
• These functions neither accept any parameters nor return a
value. They perform operations based on internal logic and
often are used for tasks that don't need to communicate results
back to the caller.
Example:
#include <stdio.h>

void printHello() {

z
printf("Hello, World!\n");
}
aa
Aw

int main() {
printHello(); // Function call
ut

return 0;
gr

}
Ja

2. Functions with No Arguments but a Return Value


Definition:
• These functions do not take any parameters but return a value.
They are used to compute a result or obtain a value that is used
elsewhere in the program.
Example:
#include <stdio.h>

int getRandomNumber() {
return 42; // Return a fixed number

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

int main() {
int num = getRandomNumber();
printf("The random number is %d\n", num);
return 0;
}

3. Functions with Arguments but No Return Value


Definition:
• These functions accept parameters but do not return a value.

z
They are often used to perform operations or modify global
aa
variables or passed-by-reference arguments.
Aw
Example:
#include <stdio.h>
ut

void printSum(int a, int b) {


gr

printf("Sum: %d\n", a + b);


Ja

int main() {
printSum(5, 7); // Function call
return 0;
}

4. Functions with Arguments and a Return Value


Definition:

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

• These functions take parameters and return a value. They are


commonly used to perform calculations or operations that
require inputs and produce results.
Example:
#include <stdio.h>

int add(int a, int b) {


return a + b; // Return the sum of two
numbers
}

z
int main() { aa
int result = add(3, 4);
Aw
printf("Result: %d\n", result);
return 0;
ut

}
gr

OR
Q.5 (a) List down and briefly explain methods for dynamic memory
Ja

allocation.
Ans.
Dynamic memory allocation allows you to allocate memory at
runtime using specific library functions. This is useful when the
amount of memory needed cannot be determined at compile time.
1. malloc() (Memory Allocation)
• Function: void* malloc(size_t size);
• Purpose: Allocates a block of memory of size bytes and returns
a pointer to the beginning of the block.

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

• Usage: The memory allocated by malloc is uninitialized,


meaning it contains indeterminate values.
• Example:
int *arr = (int*) malloc(10 * sizeof(int)); //
Allocate memory for an array of 10 integers
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Use the allocated memory
free(arr); // Free the allocated memory

z
2. calloc() (Contiguous Allocation)
aa
Aw
• Function: void* calloc(size_t num, size_t size);
• Purpose: Allocates memory for an array of num elements, each
ut

of size bytes. The allocated memory is initialized to zero.


gr

• Usage: Useful when you need to initialize the allocated memory


to zero.
Ja

• Example:
int *arr = (int*) calloc(10, sizeof(int)); //
Allocate and zero-initialize memory for an array
of 10 integers
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Use the allocated memory
free(arr); // Free the allocated memory

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

3. realloc() (Reallocation)
• Function: void* realloc(void* ptr, size_t size);
• Purpose: Resizes a previously allocated memory block to a new
size. If the new size is larger, the new memory is uninitialized. If
the new size is smaller, the excess memory is freed.
• Usage: Useful when you need to change the size of a previously
allocated memory block.
• Example:
int *arr = (int*) malloc(10 * sizeof(int)); //
Allocate initial memory
if (arr == NULL) {

z
aa
printf("Memory allocation failed\n");
return 1;
Aw

}
arr = (int*) realloc(arr, 20 * sizeof(int)); //
ut

Resize the memory block to hold 20 integers


if (arr == NULL) {
gr

printf("Memory reallocation failed\n");


Ja

return 1;
}
// Use the reallocated memory
free(arr); // Free the allocated memory

4. free() (Deallocate Memory)


• Function: void free(void* ptr);
• Purpose: Deallocates previously allocated memory. The pointer
ptr must point to a memory block allocated by malloc, calloc, or
realloc.

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

• Usage: It is important to free dynamically allocated memory


when it is no longer needed to avoid memory leaks.
• Example:
int *arr = (int*) malloc(10 * sizeof(int)); //
Allocate memory
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Use the allocated memory
free(arr); // Deallocate the memory

z
aa
(b) Write a C program to copy content of one file to other with the
Aw
help of file handling functions.
Ans.
ut

#include <stdio.h>
gr

int main() {
Ja

FILE *sourceFile, *destinationFile;


char sourceFileName[100],
destinationFileName[100];
char ch;

// Prompt user for file names


printf("Enter the name of the source file: ");
scanf("%s", sourceFileName);

printf("Enter the name of the destination file:


");

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

scanf("%s", destinationFileName);

// Open the source file in read mode


sourceFile = fopen(sourceFileName, "r");
if (sourceFile == NULL) {
printf("Error opening source file.\n");
return 1;
}

// Open the destination file in write mode


destinationFile = fopen(destinationFileName,

z
"w"); aa
if (destinationFile == NULL) {
Aw
printf("Error opening destination file.\n");
fclose(sourceFile); // Close source file
before exiting
ut

return 1;
gr

}
Ja

// Copy content from source file to destination


file
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destinationFile);
}

printf("File content copied successfully.\n");

// Close both files


fclose(sourceFile);

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

fclose(destinationFile);

return 0;
}

(c) Explain any four string handling functions with an example.


Ans.
1. strlen
• Description: Returns the length of the string, excluding the null
terminator.

z
• Syntax: size_t strlen(const char *str);
aa
• Example:
Aw
#include <stdio.h>
#include <string.h>
ut
gr

int main() {
const char *str = "Hello, World!";
Ja

size_t length = strlen(str);


printf("Length of the string: %zu\n", length);
return 0;
}

2. strcpy
• Description: Copies the source string to the destination string.
• Syntax: char *strcpy(char *dest, const char
*src);
• Example:

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

#include <stdio.h>
#include <string.h>

int main() {
char src[] = "Hello, World!";
char dest[50];
strcpy(dest, src);
printf("Copied string: %s\n", dest);
return 0;
}

z
3. strncpy

aa
Description: Copies up to n characters from the source string to
the destination string.
Aw

• Syntax: char *strncpy(char *dest, const char


*src, size_t n);
ut

• Example:
gr

#include <stdio.h>
Ja

#include <string.h>

int main() {
char src[] = "Hello, World!";
char dest[50];
strncpy(dest, src, 5);
dest[5] = '\0'; // Null-terminate the
destination
printf("Copied string: %s\n", dest);
return 0;
}

JAGRUT AWAAZ Youtube: Jagrut Awaaz


PPS
jagrutawaaz.com WINTER-2022

4. strcat
• Description: Appends the source string to the end of the
destination string.
• Syntax: char *strcat(char *dest, const char *src);
• Example:
#include <stdio.h>
#include <string.h>

int main() {
char dest[50] = "Hello";

z
char src[] = ", World!";
strcat(dest, src);
aa
Aw
printf("Concatenated string: %s\n", dest);
return 0;
}
ut
gr
Ja

JAGRUT AWAAZ Youtube: Jagrut Awaaz

You might also like