0% found this document useful (0 votes)
23 views40 pages

Pps - Summer 2024

This document outlines the examination details for the Programming for Problem Solving course at Gujarat Technological University for Summer 2024. It includes instructions for the exam, a series of questions covering topics such as computer anatomy, algorithms, flowcharts, C programming structure, and user-defined functions. The document also provides specific programming tasks and theoretical questions to assess students' understanding of programming concepts.
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)
23 views40 pages

Pps - Summer 2024

This document outlines the examination details for the Programming for Problem Solving course at Gujarat Technological University for Summer 2024. It includes instructions for the exam, a series of questions covering topics such as computer anatomy, algorithms, flowcharts, C programming structure, and user-defined functions. The document also provides specific programming tasks and theoretical questions to assess students' understanding of programming concepts.
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/ 40

Enrolment No.

/Seat No_______________

GUJARAT TECHNOLOGICAL UNIVERSITY


BE - SEMESTER–I & II (NEW) EXAMINATION – SUMMER 2024
Subject Code:3110003 Date:12-07-2024
Subject Name:Programming for Problem Solving
Time:02:30 PM TO 05: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) Draw neat Block Diagram illustrating the Anatomy of a Computer System. 03

Z
(b) Illustrate an Algorithm to check whether the given year is leap year or not. 04

AA
(c) Define Flow chart, List the rules for designing a Flow chart and Rephrase the 07
merits and demerits of flow chart.

Q.2 (a) List the rules to assign a name to an Identifier (Variable) 03


AW
(b) Illustrate the basic structure of a C Programs and highlight usual sections of 04
main function.
(c) Construct a C program which receives number of days as input and converts 07
them in to Year, Months and Days,
OR
(c) Construct a C program to swap the values of two integers with use of only 07
T

two variables.
U

Q.3 (a) Contrast the Entry Control loop and Exit Control loop. 03
(b) Construct a C program to find the largest number amongst three integers 04
R

entered.
(c) Construct a C program to check if entered integer is a prime number or note. 07
OR
G

Q.3 (a) Debug the following codes and show the output for this: 03
For ( i=0 ; i<=50 ; i++ );
{
JA

printf( “\n %d” , i )


}

*consider header files and declaration of variable is done.


(b) Explain nested if-else statement with suitable example. 04
(c) Construct a C program to print following pattern 07
1
23
456
7 8 9 10
11 12 13 14 15…..

Click :Youtube Channel | Free Material | Download App


Q.4 (a) List the types of Array. 03
(b) Summarize the methods for initialization of One-Dimensional array. 04
(c) Construct a C program to multiply 3X3 matrix. 07
OR
Q.4 (a) List the application of gets getchar and puts functions. 03
(b) Summarize the method for Declaration, initialization and Printing on screen 04
of a String.
(c) Define a Structures which contains details of a Cricketer: 07
• Name of Player:
• Team name:
• Total run scored:
• Batting average:

Z
Q.5 (a) Write True / False against following statements: 03

AA
1) Pointer is a variable which holds address of location where value of
other variable is stored.
2) Pointer holds the address in form of float or integer.
3) The address of a variable can be stored in two or more pointers.
(b) List the categories of User Defined Functions and Discuss any one of these. 04
AW
(c) Construct a C program which used a user define function that receives an 07
integer and returns square and cube of it and prints in main function.
OR
Q.5 (a) What are the arithmetic operators that are permitted on pointers? 03
(b) Show the use of Malloc, Calloc, Free and Realloc in context of Dynamic 04
memory allocation.
T

(c) List and discuss file handling functions used in C. 07

*************
U
R
G
JA

Click :Youtube Channel | Free Material | Download App


SUMMER-2024

PPS-SUMMER-2024

Q.1 (a) Draw neat Block Diagram illustrating the Anatomy of a


Computer System.
Ans.

Z
AA
AW
T
U

Input Devices:
R

• These devices are used to provide data and control signals to the computer.
• Examples: Keyboard, Mouse, Scanner, etc.
G

Central Processing Unit (CPU):


JA

• The CPU is the brain of the computer, responsible for executing instructions.
• Control Unit (CU): It directs the operation of the processor and coordinates the
execution of instructions by controlling the flow of data between the CPU and other
components.
• Arithmetic and Logic Unit (ALU): Performs arithmetic operations (addition,
subtraction, etc.) and logical operations (comparisons, decision-making).
• Registers: Small, fast storage locations inside the CPU used to store intermediate
data and instructions.

JAGRUT AWAAZ 1

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
Memory Unit:
• Stores data and instructions before and after processing.
• Primary Memory (RAM): Temporarily holds data that is currently being used or
processed. It is volatile and loses data when the power is off.
• Secondary Memory: Provides long-term storage. Examples include Hard Drives,
SSDs, etc.
Output Devices:
• Devices that convert the processed data from the computer into a human-readable

Z
format.
• Examples: Monitor, Printer, Speakers, etc.

AA
(b) Illustrate an Algorithm to check whether the given year is leap
year or not.
AW
Ans.
T
U
R
G
JA

JAGRUT AWAAZ 2

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
(c) Define Flow chart, List the rules for designing a Flow chart and
Rephrase the merits and demerits of flow chart.
Ans.
A flowchart is a graphical representation of a process or algorithm that uses symbols to
show the steps in a sequence. It is used to illustrate the flow of control in a system, making
it easier to understand and analyze the process, algorithm, or workflow.
Rules for Designing a Flowchart:
1. Start and End Points: A flowchart must have a clear start and end, typically

Z
represented by oval symbols labeled "Start" and "End."
2. Flow Direction: The flow of the chart should be from top to bottom or left to

AA
right.
3. Use Standard Symbols: Only use standard flowchart symbols for specific
purposes:
o Oval: Start/End
AW
o Rectangle: Process or action step
o Diamond: Decision point
o Parallelogram: Input/Output
T

o Arrows: Indicate the flow direction.


U

4. Single Entry and Exit: Each flowchart symbol should have only one entry and one
exit, except decision symbols which can have two exits.
R

5. Clarity and Simplicity: Keep the flowchart simple and easy to understand. Avoid
complex and overlapping lines.
G

6. Consistent Level of Detail: Maintain a consistent level of detail. Each step should
be simple and represent a meaningful action.
JA

7. Use Connector Symbols: For complex flowcharts, use connector symbols (circle)
to indicate jumps within the flowchart.
8. Label Decisions and Arrows: Label decision branches (Yes/No, True/False) and
arrow directions when necessary for clarity.
Merits of Flowcharts:
1. Clarity of Process: Flowcharts visually represent a process, making it easier to
understand and follow.

JAGRUT AWAAZ 3

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
2. Effective Communication: They help convey the structure and flow of a process
to team members and stakeholders.
3. Problem Solving: Flowcharts aid in identifying problem areas or inefficiencies in a
process.
4. Documentation Tool: They serve as documentation for processes and algorithms,
useful for future reference.
5. Efficient Debugging: In programming, flowcharts make it easier to trace errors and
bugs in the logic.
6. Improved Analysis: Flowcharts simplify the analysis of complex systems by

Z
breaking them into simpler steps.

AA
Demerits of Flowcharts:
1. Time-Consuming: Designing a detailed flowchart for complex processes can be
time-consuming. AW
2. Complexity in Large Systems: For large and complicated systems, flowcharts can
become overly complex and hard to follow.
3. Not Suitable for All Types of Problems: Flowcharts may not be suitable for
highly detailed or algorithmic problems where pseudocode or other forms of
documentation are more efficient.
T

4. Difficult Modifications: Updating or modifying a flowchart requires significant


effort, especially for large processes.
U

5. Limited Representation: Flowcharts may not capture detailed logic and can
oversimplify certain aspects of processes.
R
G

Q.2 (a) List the rules to assign a name to an Identifier (Variable).


Ans.
JA

Here is the list of rules and regulations to follow when defining identifiers in C:
1. The identifier cannot begin with a digit/ numeric digit.
2. The initial letter/ first element of an identifier should always either be an underscore
or an alphabet.
3. The letters that follow the first could be a character, a number, or an underscore in
the identifier.

JAGRUT AWAAZ 4

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
4. However, note that no special symbol can be used.
5. The alphabetical characters can be written in either uppercase letters or lowercase
letters.
6. This is because identifiers are case-sensitive and can distinguish between uppercase
and lowercase letters.
7. Commas and blank spaces are not permitted when naming an identifier.
8. The length of an identifier in C is limited to 31 characters.
9. The use of keywords in C as an identifier is strictly prohibited. That is, you cannot

Z
use an in-built keyword as an identifier as well.
10. And lastly, identifiers must be short yet descriptive and also simple to understand

AA
(b) Illustrate the basic structure of a C Programs and highlight usual
sections of main function.
AW
Ans.
#include <stdio.h> // Preprocessor directive

// Global variable declarations (optional)


T
U

int main() {
// Local variable declarations
R
G

// Main function body (Logic/Statements)


printf("Hello, World!\n");
JA

// Return statement
return 0;
}
Usual Sections of the main Function:

JAGRUT AWAAZ 5

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
The main function is the entry point of a C program. It typically contains the following
sections:
1. Preprocessor Directives:
o Syntax: #include <header_file>
o These lines are used to include header files containing standard library functions (like
#include <stdio.h> for input/output functions).
o Example: #include <stdio.h> allows the use of functions like printf() and scanf().
2. Global Declarations (Optional):

Z
o Variables and functions declared here are accessible throughout the program,
including the main function and other functions.

AA
o Example: int global_var = 10;
3. Function Definition (main): AW
o This is the starting point of execution. The basic syntax of the main function is:
int main() {
// Code
}
T

o The main function must return an integer (typically 0 for successful execution).
4. Local Variable Declarations:
U

o Local variables are declared within the main function and are only accessible within
R

this function.
o Example:
G

int a = 5;
5. Statements and Expressions (Logic):
JA

o This is the core part of the program where the logic, computations, and statements
are executed.
o Example:
printf("Sum is: %d\n", a + b);
6. Return Statement:

JAGRUT AWAAZ 6

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
o The main function must end with a return statement to return an integer value to the
operating system.
o Example:
return 0;

(c) Construct a C program which receives number of days as input


and converts them in to Year, Months and Days.
Ans.

Z
#include <stdio.h>

AA
int main() {
int ndays, y, m, d; // Declare variables for number of
days, years, months, and days
AW
// Prompt user for input number of days and store in
'ndays'
printf("Input no. of days: ");
scanf("%d", &ndays);
T
U

// Calculate years, months, and remaining days


R

y = (int) ndays/365;
ndays = ndays-(365*y);
G

m = (int)ndays/30;
d = (int)ndays-(m*30);
JA

// Print the result


printf(" %d Year(s) \n %d Month(s) \n %d Day(s)", y, m,
d);

return 0;

JAGRUT AWAAZ 7

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
}

OR
(c) Construct a C program to swap the values of two integers with
use of only two variables.
Ans.
// C Program to Swap Two Numbers using a

Z
// Temporary Variable
#include <stdio.h>

AA
int main() {
int a = 5, b = 10, temp;
AW
// Swapping values of a and b
temp = a;
a = b;
T

b = temp;
U
R

printf("a = %d, b = %d\n", a, b);


return 0;
G

}
JA

Q.3 (a) Contrast the Entry Control loop and Exit Control loop
Ans.
Entry Controlled Loop Entry Controlled Loop
Condition is evaluated before body of loop Condition is evaluated after body of loop is
is executed. executed.

JAGRUT AWAAZ 8

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
Loop body may not execute if condition is Loop body executes at least once before
false initially. condition evaluation.
while (condition) { // Loop body } do { // Loop body } while (condition);
Used when the loop may not need to Used when the loop body must execute at
execute at all if the condition is initially least once before evaluating the condition.
false.

(b) Construct a C program to find the largest number amongst three


integers entered.

Z
Ans.

AA
#include <stdio.h> // Include standard input-output
library AW
int main() {
int num1, num2, num3; // Declare three integer
variables
int largest; // Variable to hold the largest
T

number
U

// Input: Prompt user to enter three integers


R

printf("Enter three integers: ");


scanf("%d %d %d", &num1, &num2, &num3);
G
JA

// Logic to find the largest number


if (num1 >= num2 && num1 >= num3) {
largest = num1;
}
else if (num2 >= num1 && num2 >= num3) {
largest = num2;
}
JAGRUT AWAAZ 9

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
else {
largest = num3;
}

// Output the largest number


printf("The largest number is: %d\n", largest);

return 0; // Return 0 to indicate successful

Z
execution

AA
}

(c) Construct a C program to check if entered integer is a prime


number or note
AW
Ans.
// C Program to check for prime number using
// Simple Trial Division
T

#include <stdbool.h>
U

#include <stdio.h>
R

int main() {
G

int n = 29;
JA

int cnt = 0;

// If number is less than/equal to 1,


// it is not prime
if (n <= 1)
printf("%d is NOT prime\n", n);

JAGRUT AWAAZ 10

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
else {

// Check for divisors from 1 to n


for (int i = 1; i <= n; i++) {

// Check how many number is divisible


// by n
if (n % i == 0)

Z
cnt++;

AA
}

// If n is divisible by more than 2 numbers


AW
// then it is not prime
if (cnt > 2)
printf("%d is NOT prime\n", n);
T

// else it is prime
U

else
printf("%d is prime", n);
R

}
G

return 0;
JA

OR
Q.3 (a) Debug the following codes and show the output for this: For (
i=0 ; i<=50 ; i++ ); { printf( “\n %d” , i ) }
*consider header files and declaration of variable is done.
JAGRUT AWAAZ 11

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
Ans.
Errors in the Code:
1. For should be lowercase for: C is case-sensitive, so the keyword For is incorrect.
It should be for.
2. Unnecessary semicolon after for loop: The semicolon at the end of the for loop
creates an empty loop, meaning the body of the loop will not execute as expected.
3. Incorrect quotation marks: The quotation marks used in printf() are wrong (they
are curly quotes “ and ”). C uses straight double quotes " for strings.

Z
4. Missing semicolon after printf: The printf() statement is missing a semicolon (;) at
the end.

AA
Explanation of Fixes:
• Changed For to for: The correct C syntax for loops.
• Removed semicolon after for loop: The loop should have no semicolon after the
AW
parentheses, so the following block {} can be executed.
• Fixed the quotes in printf(): Replaced the curly quotes with straight quotes.
• Added missing semicolon after printf(): Every C statement needs to end with a
semicolon.
T

(b) Explain nested if-else statement with suitable example.


U

Ans.
A nested if-else statement is an if-else statement that is placed inside another if-else
R

statement. This is useful when you need to make multiple decisions based on different
conditions.
G

Syntax of Nested if-else:


if (condition1) {
JA

// Executes when condition1 is true


if (condition2) {
// Executes when both condition1 and condition2 are true
} else {
// Executes when condition1 is true, but condition2 is false
}
JAGRUT AWAAZ 12

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
} else {
// Executes when condition1 is false
}
Example of Nested if-else in C:
#include <stdio.h>

int main() {
int num;

Z
AA
// Input a number from the user
printf("Enter an integer: ");
scanf("%d", &num);
AW
// Outer if-else statement
if (num >= 0) {
// If the number is positive or zero, check
T

further
U

if (num % 2 == 0) {
printf("The number %d is even and
R

positive.\n", num);
} else {
G

printf("The number %d is odd and positive.\n",


num);
JA

}
} else {
// If the number is negative
printf("The number %d is negative.\n", num);
}

JAGRUT AWAAZ 13

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
return 0;
}
Explanation of Nested if-else Flow:
• If the number is non-negative (num >= 0), the program then checks whether the
number is even or odd using the condition num % 2 == 0.
• If the number is negative, it simply prints that it is negative without further checks.
Advantages of Nested if-else:
• Helps in handling complex decision-making scenarios where multiple conditions must

Z
be checked.

AA
• Improves readability when logically related conditions are grouped together.

(c) Construct a C program to print following pattern


AW
1
23
456
7 8 9 10
T

11 12 13 14 15…..
U

Ans.
R

#include <stdio.h>
G

int main() {
JA

int i, j, num = 1; // Declare variables

// Outer loop to control the number of rows


for (i = 1; i <= 5; i++) {
// Inner loop to control the numbers in each row
for (j = 1; j <= i; j++) {
// Print the current number and increment it
JAGRUT AWAAZ 14

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
printf("%d ", num);
num++; // Increment the number
}
// Move to the next line after printing each row
printf("\n");
}

return 0;

Z
}

AA
Q.4 (a) List the types of Array. AW
Ans.
Arrays in C are classified into different types based on the number of dimensions. Here
are the most common types of arrays:
1. One-Dimensional Array (1D Array):
A one-dimensional array stores a list of elements in a single row or a linear
T

o
form.
U

o Example:
int arr[5] = {10, 20, 30, 40, 50};
R

o It can be accessed using a single index, like arr[0], arr[1], etc.


2. Two-Dimensional Array (2D Array):
G

o A two-dimensional array is like a matrix or table of elements arranged in rows


JA

and columns.
o Example:
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
JAGRUT AWAAZ 15

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
o Elements are accessed using two indices, like arr[1][2] (second row, third
column).

3. Multidimensional Array (3D Array and beyond):

o A multidimensional array extends the concept of a 2D array to multiple


dimensions.
o Example of a 3D Array:
int arr[2][3][4] = {
{

Z
{1, 2, 3, 4},

AA
{5, 6, 7, 8},
{9, 10, 11, 12}
},
AW
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
T

}
U

};
R

• Elements are accessed using three indices, like arr[1][2][3] (second block, third row,
G

fourth column).
(b) Summarize the methods for initialization of One-Dimensional
JA

array.
Ans.
In C, a one-dimensional array can be initialized in several ways. Here are the common
methods for initializing a one-dimensional array:

1. Initialization at the Time of Declaration:

JAGRUT AWAAZ 16

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
• You can initialize an array when it is declared by specifying the values in curly braces
{}.
• Syntax:
data_type array_name[array_size] = {value1, value2, value3, ...};
• Example:
int arr[5] = {10, 20, 30, 40, 50};

2. Partial Initialization:

Z
• If you provide fewer values than the size of the array, the remaining elements are
initialized to 0.

AA
• Syntax:
data_type array_name[array_size] = {value1, value2};
AW
• Example:
int arr[5] = {10, 20}; // The remaining elements will be 0

3. Array Size Omitted:


• You can omit the array size during initialization. The compiler will automatically
T

determine the size based on the number of values provided.


Syntax:
U

data_type array_name[] = {value1, value2, value3, ...};


R

• Example:
G

int arr[] = {10, 20, 30, 40, 50}; // Size is automatically set to 5
JA

4. Initialization Using Loops:


• You can initialize an array using loops, especially when the array size is large or when
values follow a specific pattern.
• Syntax:
for (int i = 0; i < array_size; i++) {
array_name[i] = some_value_or_expression;
}
JAGRUT AWAAZ 17

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
• Example:
int arr[5];
for (int i = 0; i < 5; i++) {
arr[i] = i * 10; // Initializes arr[0] = 0, arr[1] = 10, ..., arr[4] = 40
}

(c) Construct a C program to multiply 3X3 matrix.

Z
Ans.
#include <stdio.h>

AA
#define SIZE 3 // Define the size of the matrix
AW
void multiplyMatrices(int firstMatrix[SIZE][SIZE], int
secondMatrix[SIZE][SIZE], int result[SIZE][SIZE]) {
// Initialize the result matrix to 0
for (int i = 0; i < SIZE; i++) {
T

for (int j = 0; j < SIZE; j++) {


U

result[i][j] = 0;
R

}
}
G

// Multiply the matrices


JA

for (int i = 0; i < SIZE; i++) {


for (int j = 0; j < SIZE; j++) {
for (int k = 0; k < SIZE; k++) {
result[i][j] += firstMatrix[i][k] *
secondMatrix[k][j];
}

JAGRUT AWAAZ 18

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
}
}
}

void printMatrix(int matrix[SIZE][SIZE]) {


for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("%d ", matrix[i][j]);

Z
}

AA
printf("\n");
}
}
AW
int main() {
int firstMatrix[SIZE][SIZE], secondMatrix[SIZE][SIZE],
result[SIZE][SIZE];
T
U

// Input for the first matrix


printf("Enter elements of the first 3x3 matrix:\n");
R

for (int i = 0; i < SIZE; i++) {


G

for (int j = 0; j < SIZE; j++) {


scanf("%d", &firstMatrix[i][j]);
JA

}
}

// Input for the second matrix


printf("Enter elements of the second 3x3 matrix:\n");
for (int i = 0; i < SIZE; i++) {

JAGRUT AWAAZ 19

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
for (int j = 0; j < SIZE; j++) {
scanf("%d", &secondMatrix[i][j]);
}
}

// Multiply the matrices


multiplyMatrices(firstMatrix, secondMatrix, result);

Z
// Display the result

AA
printf("Result of matrix multiplication:\n");
printMatrix(result); AW
return 0;
}

OR
T

Q.4 (a) List the application of gets getchar and puts functions.
U

Ans.
R

1. gets Function:
• Purpose: Reads a string from standard input (stdin) until a newline character or EOF
G

is encountered.
Syntax:
JA

char *gets(char *str);


Applications:
• Reading Strings: Used to read a line of text into a character array.
• User Input: Suitable for getting user input that may contain spaces (e.g.,
names, sentences).
2. getchar Function:

JAGRUT AWAAZ 20

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
• Purpose: Reads a single character from standard input.
• Syntax:
int getchar(void);
Applications:
• Character Input: Useful for reading characters one at a time, often in cases
where the program needs to process input immediately.
• Control Characters: Can be used to read special control characters (like
newline or EOF).

Z
• Input Validation: Often employed in loops to validate or filter character
input.

AA
3. puts Function:
• Purpose: Writes a string to standard output (stdout) followed by a newline
character.
AW
• Syntax:
int puts(const char *str);
Applications:
• Displaying Strings: Commonly used for displaying messages, prompts, or any
T

string data to the console.


U

• Simple Output: Ideal for printing simple strings without the need for format
specifiers.
R

(b) Summarize the method for Declaration, initialization and Printing


G

on screen of a String.
JA

Ans.
1. Declaration of a String
To declare a string in C, you typically use a character array or a pointer to a character.
Here are two common methods:
a. Using a Character Array:
char str[100]; // Declares a string with a maximum size of 99 characters (plus
a null terminator)

JAGRUT AWAAZ 21

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
b. Using a Pointer:
char *str; // Declares a pointer to a character
2. Initialization of a String
You can initialize a string at the time of declaration or assign a value later. Here are the
methods for both:
a. Initialization at Declaration:
char str1[] = "Hello, World!"; // The size is automatically determined
b. Using strcpy Function (from <string.h>):

Z
You can also assign a string value after declaration using the strcpy function

AA
char str2[100];
strcpy(str2, "Hello, World!"); // Copy the string to the character array
3. Printing a String on the Screen
AW
To print a string on the screen, you can use the printf or puts function.
a. Using printf:
printf("%s\n", str1); // Prints the string using format specifier %s
b. Using puts:
puts(str1); // Prints the string followed by a newline character
T
U

(c) Define a Structures which contains details of a Cricketer:


• Name of Player:
R

• Team name:
G

• Total run scored:


• Batting average:
JA

Ans.
#include <stdio.h>

// Define a structure named 'Cricketer'


struct Cricketer {
char name[50]; // Name of the player (string)
JAGRUT AWAAZ 22

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
char team[50]; // Team name (string)
int total_runs; // Total runs scored (integer)
float batting_average; // Batting average (float)
};

int main() {
// Create an instance of the Cricketer structure
struct Cricketer player;

Z
AA
// Input details for the cricketer
printf("Enter the name of the player: ");
fgets(player.name, sizeof(player.name), stdin); //
AW
Reading name (with spaces)

printf("Enter the team name: ");


fgets(player.team, sizeof(player.team), stdin); //
T

Reading team name (with spaces)


U

printf("Enter total runs scored: ");


R

scanf("%d", &player.total_runs); // Reading total runs


scored
G

printf("Enter batting average: ");


JA

scanf("%f", &player.batting_average); // Reading batting


average

// Displaying the details of the cricketer


printf("\nCricketer Details:\n");
printf("Name of Player: %s", player.name);

JAGRUT AWAAZ 23

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
printf("Team Name: %s", player.team);
printf("Total Runs Scored: %d\n", player.total_runs);
printf("Batting Average: %.2f\n", player.batting_average);

return 0;
}

Q.5 (a) Write True / False against following statements:

Z
1) Pointer is a variable which holds address of location where value of

AA
other variable is stored.
Ans. True
Explanation: A pointer is a variable that stores the memory address of another
variable.
AW
2) Pointer holds the address in form of float or integer.
Ans. False
Explanation: A pointer holds an address in a specific format (typically a memory
address), and its type is defined based on the type of variable it points to (e.g., int*, float*,
T

char*). The address itself is generally represented as an integer type (usually an unsigned
long integer), but pointers themselves are not classified as float or integer types.
U

3) The address of a variable can be stored in two or more pointers.


R

Ans. True
Explanation: Multiple pointers can hold the address of the same variable, allowing them
G

to point to the same memory location.


JA

(b) List the categories of User Defined Functions and Discuss any one
of these.
Ans.
Categories of User-Defined Functions
1. Based on Return Type:
o Functions with Return Type: Functions that return a value (e.g., int, float,
char).
JAGRUT AWAAZ 24

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
o Functions without Return Type: Functions that do not return a value
(declared with the void return type).
2. Based on Number of Parameters:
o Functions with Parameters: Functions that take one or more arguments.
o Functions without Parameters: Functions that do not take any arguments.
3. Based on Functionality:
o Standard Functions: Functions that are predefined in libraries (like printf,
scanf).

Z
o Custom Functions: Functions defined by the user to perform specific tasks.

AA
Discussion on Functions with Return Type
Functions with Return Type are the most common category of user-defined functions.
AW
These functions perform a specific task and return a value back to the caller. The return
type of the function defines the data type of the value that the function will return.
Structure of a Function with Return Type
The structure of a function with a return type typically includes:
• Return Type: The data type of the value being returned.
T

• Function Name: A unique identifier for the function.


U

• Parameters (if any): Input values the function takes.


R

• Function Body: The block of code that defines what the function does.
Example of a Function with Return Type
G

Here's a simple example that illustrates how to define and use a function that calculates the
square of an integer:
JA

#include <stdio.h>

// Function to calculate the square of an integer


int square(int num) {
return num * num; // Return the square of the number
}

JAGRUT AWAAZ 25

Click :Youtube Channel | Free Material | Download App


SUMMER-2024

int main() {
int number, result;

// Input a number from the user


printf("Enter an integer: ");
scanf("%d", &number);

Z
// Call the square function and store the result

AA
result = square(number);

// Display the result


AW
printf("The square of %d is %d\n", number, result);

return 0;
}
T
U

(c) Construct a C program which used a user define function that


receives an integer and returns square and cube of it and prints in
R

main function.
G

Ans.
#include <stdio.h>
JA

// Function to calculate square and cube of a number


void calculateSquareAndCube(int num, int *square, int *cube) {
*square = num * num; // Calculate square
*cube = num * num * num; // Calculate cube
}

JAGRUT AWAAZ 26

Click :Youtube Channel | Free Material | Download App


SUMMER-2024

int main() {
int number, square, cube;

// Input an integer from the user


printf("Enter an integer: ");
scanf("%d", &number);

Z
// Call the function to calculate square and cube

AA
calculateSquareAndCube(number, &square, &cube);

// Print the results


AW
printf("The square of %d is %d\n", number, square);
printf("The cube of %d is %d\n", number, cube);

return 0;
T

}
U

OR
R

Q.5 (a) What are the arithmetic operators that are permitted on
G

pointers?
Ans.
JA

In C, pointers can be manipulated using certain arithmetic operators. However, it's


important to note that pointer arithmetic is primarily meaningful for array manipulation and
accessing elements in a contiguous memory block. Here are the arithmetic operators that
can be used with pointers:
Arithmetic Operators Permitted on Pointers
1. Addition (+):

JAGRUT AWAAZ 27

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
o You can add an integer value to a pointer. This operation moves the pointer
forward by that number of elements, based on the size of the data type the
pointer points to.
o Example:
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Points to the first element of the array
ptr = ptr + 2; // Now ptr points to the third element (30)
2. Subtraction (-):

Z
• You can subtract an integer value from a pointer, which moves the pointer
backward by that number of elements.

AA
• You can also subtract one pointer from another if they point to elements of
the same array, which results in the difference in terms of the number of
elements between the two pointers.
AW
• Example:
ptr = arr + 3; // Now ptr points to the fourth element (40)
ptr = ptr - 1; // Now ptr points to the third element (30)
3. Increment (++):
T

• The increment operator moves the pointer to the next element in the array.
U

• Example:
int *ptr = arr; // ptr points to 10
R

ptr++; // Now ptr points to 20


G

4. Decrement (--):
• The decrement operator moves the pointer to the previous element in the
JA

array.
• Example:
ptr--; // Now ptr points back to 10

(b) Show the use of Malloc, Calloc, Free and Realloc in context of
Dynamic memory allocation.
Ans.
JAGRUT AWAAZ 28

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
Dynamic memory allocation in C is a way to allocate memory at runtime. The standard
library provides several functions for dynamic memory management, including malloc,
calloc, free, and realloc.
1. malloc
The malloc function allocates a specified number of bytes of memory and returns a pointer
to the first byte of that memory. The memory allocated using malloc is uninitialized,
meaning it contains garbage values.
Syntax:
void* malloc(size_t size);

Z
Example:

AA
#include <stdio.h>
#include <stdlib.h>
AW
int main() {
int *arr;
int n = 5;
T

// Allocate memory for an array of 5 integers


U

arr = (int*)malloc(n * sizeof(int));


R

if (arr == NULL) {
G

printf("Memory allocation failed!\n");


return 1;
JA

// Initialize and print the array


for (int i = 0; i < n; i++) {
arr[i] = i + 1; // Assign values 1 to 5
printf("%d ", arr[i]);

JAGRUT AWAAZ 29

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
}

// Free the allocated memory


free(arr);

return 0;
}
2. calloc

Z
The calloc function allocates memory for an array of specified elements and initializes

AA
all bits to zero. It is useful when you want to ensure that the allocated memory starts with
a known value.
Syntax:
void* calloc(size_t num, size_t size);
AW
Example:
#include <stdio.h>
#include <stdlib.h>
T

int main() {
U

int *arr;
R

int n = 5;
G

// Allocate memory for an array of 5 integers and


initialize to zero
JA

arr = (int*)calloc(n, sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

JAGRUT AWAAZ 30

Click :Youtube Channel | Free Material | Download App


SUMMER-2024

// Print the array (all elements will be 0)


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

// Free the allocated memory


free(arr);

Z
AA
return 0;
}
3. free
AW
The free function is used to deallocate memory that was previously allocated using
malloc, calloc, or realloc. This prevents memory leaks by releasing the memory back to the
system.
Syntax:
T

void free(void* ptr);


Example
U

// (Continuation from previous examples)


R

// free(arr); // This line was already included in both examples.


G

4. realloc
JA

The realloc function is used to change the size of previously allocated memory. It can
increase or decrease the size of the memory block. If the new size is larger, the additional
memory is uninitialized. If it is smaller, the excess memory is freed.
Syntax:
void* realloc(void* ptr, size_t new_size);
Example:
#include <stdio.h>

JAGRUT AWAAZ 31

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
#include <stdlib.h>

int main() {
int *arr;
int n = 5;

// Allocate memory for an array of 5 integers


arr = (int*)malloc(n * sizeof(int));

Z
AA
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
AW
}

// Initialize the array


for (int i = 0; i < n; i++) {
T

arr[i] = i + 1; // Assign values 1 to 5


U

}
R

// Resize the array to hold 10 integers


G

n = 10;
arr = (int*)realloc(arr, n * sizeof(int));
JA

if (arr == NULL) {
printf("Memory reallocation failed!\n");
return 1;
}

JAGRUT AWAAZ 32

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
// Initialize the new elements
for (int i = 5; i < n; i++) {
arr[i] = i + 1; // Assign values 6 to 10
}

// Print the array


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

Z
}

AA
// Free the allocated memory
free(arr);
AW
return 0;
}
T

(c) List and discuss file handling functions used in C.


U

Ans.
File handling in C is crucial for reading from and writing to files, enabling persistent data
R

storage. C provides several standard library functions for file operations, which are defined
in the stdio.h header file.
G

1. fopen
JA

Purpose: Opens a file and returns a file pointer.


Syntax:
FILE* fopen(const char* filename, const char* mode);
Parameters:
• filename: The name of the file to be opened.
• mode: A string that specifies the file access mode (e.g., "r", "w", "a", etc.).

JAGRUT AWAAZ 33

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
Modes:
• "r": Open for reading (file must exist).
• "w": Open for writing (creates a new file or truncates existing).
• "a": Open for appending (writes data at the end of the file).
• "r+": Open for reading and writing (file must exist).
• "w+": Open for reading and writing (creates a new file or truncates existing).
• "a+": Open for reading and appending.

Z
Example:
FILE *file = fopen("example.txt", "r");

AA
if (file == NULL) {
perror("Error opening file");
}
AW
2. fclose
Purpose: Closes an opened file.
Syntax:
T

int fclose(FILE* stream);


U

Parameters:
stream: A pointer to the file to be closed.
R

Example:
G

if (fclose(file) != 0) {
perror("Error closing file");
JA

3. fprintf
Purpose: Writes formatted data to a file.
Syntax:
int fprintf(FILE* stream, const char* format, ...);

JAGRUT AWAAZ 34

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
Parameters:
• stream: Pointer to the file where data will be written.
• format: A format string similar to printf.
Example:
fprintf(file, "Hello, World! Number: %d\n", 42);

4. fscanf
Purpose: Reads formatted input from a file.

Z
Syntax:

AA
int fscanf(FILE* stream, const char* format, ...);
Parameters:
• stream: Pointer to the file from which data will be read.
AW
• format: A format string similar to scanf.
Example:
int number;
fscanf(file, "%d", &number);
T
U

5. fgets
Purpose: Reads a string from a file.
R

Syntax:
G

char* fgets(char* str, int n, FILE* stream);


Parameters:
JA

• str: Pointer to the buffer where the read string will be stored.
• n: The maximum number of characters to read (including the null terminator).
• stream: Pointer to the file from which to read.
Example:
char buffer[100];
fgets(buffer, sizeof(buffer), file);

JAGRUT AWAAZ 35

Click :Youtube Channel | Free Material | Download App


SUMMER-2024
6. fputs
Purpose: Writes a string to a file.
Syntax:
int fputs(const char* str, FILE* stream);
Parameters:
• str: The string to write.
• stream: Pointer to the file where the string will be written.

Z
Example:
fputs("This is a line.\n", file);

AA
7. fseek
Purpose: Moves the file pointer to a specified location in the file.
Syntax:
AW
int fseek(FILE* stream, long offset, int whence);
Parameters:
• stream: Pointer to the file.
T

• offset: The number of bytes to move the pointer.


• whence: The reference point for the offset (e.g., SEEK_SET, SEEK_CUR,
U

SEEK_END).
Example:
R

fseek(file, 0, SEEK_END); // Move to the end of the file


G

8. ftell
Purpose: Returns the current position of the file pointer.
JA

Syntax:
long ftell(FILE* stream);
Parameters:
• stream: Pointer to the file.
Example:
long pos = ftell(file);

JAGRUT AWAAZ 36

Click :Youtube Channel | Free Material | Download App


SUMMER-2024

Z
AA
AW
T
U
R
G
JA

JAGRUT AWAAZ 37

Click :Youtube Channel | Free Material | Download App

You might also like