Principles of Programming using C(BPOPS103/203) SEM-1
VTU Question & Solution (February 2025)
Prof. Lynsha Pratheeba HP, Prof. Reshma, Prof. Kavyashree Prof. Rajeshwari R
Department of CSE
MODULE-1
Q1 a. List and explain any 5 characteristics of a computer. [10 Marks]
1. Speed
Executing mathematical calculation, a computer works faster and more accurately
than human. Computers have the ability to process so many millions (1,000,000) of
instructions per second. Computer operations are performed in micro and nano
seconds. A computer is a time saving device. It performs several calculations and
tasks in few seconds that we take hours to solve. The speed of a computer is measure
in terms of GigaHertz and MegaHertz.
2. Diligence
A human cannot work for several hours without resting, yet a computer never tires. A
computer can conduct millions of calculations per second with complete precision
without stopping. A computer can consistently and accurately do millions of jobs or
calculations. There is no weariness or lack of concentration. Its memory ability also
places it ahead of humans.
3. Reliability
A computer is reliable. The output results never differ unless the input varies. the
output totally depends on the input. when an input is the same the output will also be
the same. A computer produces consistent results for similar sets of data, if we
provide the same set of input at any time we will get the same result.
4. Automation
The world is quickly moving toward AI (Artificial Intelligence)-based technology. A
computer may conduct tasks automatically after instructions are programmed. By
executing jobs automatically, this computer feature replaces thousands of workers.
Automation in computing is often achieved by the use of a program, a script, or batch
processing.
5. Versatility
Versatility refers to a capacity of computer. Computer perform different types of tasks
with the same accuracy and efficiency. A computer can perform multiple tasks at the
same time this is known as versatility. For example, while listening to music, we may
develop our project using PowerPoint and Wordpad, or we can design a website.
6. Memory
A computer can store millions of records. these records may be accessed with
complete precision. Computer memory storage capacity is measured in Bytes,
Kilobytes(KB), Megabytes(MB), Gigabytes(GB), and Terabytes(TB). A computer has
built-in memory known as primary memory.
Q.1.b) Draw the block diagram of a computer, explain all of its blocks such as
input, output storage and CPU. [10 Marks]
Input
All the data received by the computer goes through the input unit. The input unit
comprises different devices like a mouse, keyboard, scanner, etc. In other words, each
of these devices acts as a mediator between the users and the computer.
The data that is to be processed is put through the input unit. The computer accepts the
raw data in binary form. It then processes the data and produces the desired output.
The 3 major functions of the input unit are-
Take the data to be processed by the user.
Convert the given data into machine-readable form.
And then, transmit the converted data into the main memory of the computer.
The sole purpose is to connect the user and the computer. In addition, this
creates easy communication between them.
CPU (Central Processing Unit)
Central Processing Unit or the CPU, is the brain of the computer. It works the same
way a human brain works. As the brain controls all human activities, similarly the
CPU controls all the tasks. The CPU conducts all the arithmetical and logical
operations in the computer.
CPU comprises of two units, namely – ALU (Arithmetic Logic Unit) and CU (Control
Unit). Both of these units work in sync. The CPU processes the data as a whole.
ALU – Arithmetic Logic Unit
The Arithmetic Logic Unit is made of two terms, arithmetic and logic. There
are two primary functions that this unit performs.
1. Data is inserted through the input unit into the primary memory.
Performs the basic arithmetical operations on it, like addition,
subtraction, multiplication, and division. It performs all sorts of
calculations required on the data. Then, it sends back data to the
storage.
2. The unit is also responsible for performing logical operations like
AND, OR, Equal to, less than, etc. In addition to this, it conducts
merging, sorting, and selection of the given data.
CU – Control Unit
The control unit as the name suggests is the controller of all the activities/tasks
and operations. All this is performed inside the computer.
The memory unit sends a set of instructions to the control unit. Then the
control unit in turn converts those instructions. After that these instructions are
converted to control signals.
These control signals help in prioritizing and scheduling activities. Thus, the
control unit coordinates the tasks inside the computer in sync with the input
and output units.
Memory Unit
All the data that has to be processed or has been processed is stored in the memory
unit. The memory unit acts as a hub of all the data. It transmits it to the required part
of the computer whenever necessary.
The memory unit works in sync with the CPU. This helps in faster accessing and
processing of the data. Thus, making tasks easier and quicker.
There are two types of computer memory-
Primary Memory
This type of memory cannot store a vast amount of data. Therefore, it is only
used to store recent data. The data stored in this is temporary. It can get erased
once the power is switched off. Therefore, is also called temporary memory or
main memory.
RAM stands for Random Access Memory. It is an example of primary
memory. This memory is directly accessible by the CPU. It is used for reading
and writing purposes. For data to be processed, it has to be first transferred to
the RAM and then to the CPU.
Secondary Memory
As explained above, the primary memory stores temporary data. Thus it
cannot be accessed in the future. For permanent storage purposes, secondary
memory is used. It is also called permanent memory or auxiliary memory. The
hard disk is an example of secondary memory. Even in a power failure data
does not get erased easily.
Output
There is nothing to be amazed by what the output unit is used for. All the information
sent to the computer once processed is received by the user through the output unit.
Devices like printers, monitors, projectors, etc. all come under the output unit.
The output unit displays the data either in the form of a soft copy or a hard copy. The
printer is for the hard copy. The monitor is for the display. The output unit accepts the
data in binary form from the computer. It then converts it into a readable form for the
user.
Q.2.a) Explain the following Paradigms.
i) Procedural programming
ii) Object Oriented programming [10 Marks]
i) Procedural Programming Paradigm
Procedural programming is the traditional approach to C programming and follows a
step-by-step method of solving problems by dividing them into functions or
procedures.
Features of Procedural Programming are below:
Structured Programming: Code is written in a structured manner using
functions, loops, and conditionals.
Top-down Approach: The program is divided into small functions that
perform specific tasks.
Global and Local Variables: Data is stored in variables, and functions operate
on them.
Reusability: Functions can be reused within the program to avoid repetition.
Memory Management: Uses stack memory allocation for function calls.
Example Program:
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int main() {
int num1 = 5, num2 = 10;
int sum = add(num1, num2);
printf("Sum: %d\n", sum);
return 0;
}
Advantages of Procedural Programming
Simple and easy to understand.
Efficient use of memory and CPU.
Suitable for small-scale applications.
Disadvantages of Procedural Programming
Difficult to manage for large programs.
Lack of data security (global variables can be modified from anywhere).
Less reusable compared to object-oriented programming.
Object-Oriented Programming:
C is not an object-oriented programming language by design, but OOP principles can
be implemented using structures, function pointers, and encapsulation techniques.
Key Features of Object-Oriented Programming in C
Encapsulation: Grouping related variables and functions inside a structure.
Abstraction: Hiding implementation details using functions.
Polymorphism: Using function pointers for different behaviours.
Inheritance (Limited in C): Achieved using structures within structures.
Example:
#include <stdio.h>
#include <string.h>
struct Car {
char brand[20];
int modelYear;
void (*display)(struct Car);
};
void showCarDetails(struct Car c)
{
printf("Brand: %s, Model Year: %d\n", c.brand, c.modelYear);
}
int main() {
struct Car car1;
strcpy(car1.brand, "Toyota");
car1.modelYear = 2022;
car1.display = showCarDetails;
car1.display(car1);
return 0;
}
Advantages of OOP in C
Improves modularity and code organization.
Enhances code reusability.
Provides better data security and abstraction.
Disadvantages of OOP in C
C does not fully support OOP like C++ or Java.
Implementing OOP features requires extra effort.
No direct support for classes and inheritance.
Q.2.b) Explain the structure of a C program with an example. [10 Marks]
Documentation Section:
This section is used to write Problem, file name, developer, date etc in comment lines
within /*....*/ or separate line comments may start with // . Compiler ignores
this section. Documentation enhances the readability of a program.
Link section :
To include header and library files whose in-built functions are to be used. Linker also
required these files to build a program executable. Files are included with directive #
Include Definition section: To define macros and symbolic constants by
preprocessor directive #define.
Global section:
To declare global variables – to be accessed by all functions main() is the user defined
function which is recognized by the compiler first. So, all C program must have user
defined function main() { ............. }. It should have declaration part first then
executable part.
Sub program section:
There may be other user defined functions to perform specific task when called.
/* Example: a program to find area of a circle – area.c - Documentation Section*/
#include <stdio.h> /* - Link/Header Section */
#define PI 3.14 /* definition/global section*/
int main() /* main function section */
{
float r, area; /* declaration part */
printf(“Enter radius of the circle : “); /* Execution part*/
scanf(“%f”, &r);
area=PI*r*r; /* using symbolic constant PI */
printf(“Area of circle = %0.3f square unit\n”, area);
return (0);
}
MODULE-2
Q.3.a) Explain Arithmetic and Relational Operators of C with example. [10 Marks]
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition,
subtraction, multiplication, and division.
List of Arithmetic Operators in C
Operator Symbol Example Description
Addition + a+b Adds two values
Subtraction - a-b Subtracts one value from another
Multiplication * a*b Multiplies two values
Division / a/b Divides one value by another
Modulus % a%b Returns remainder of division
Example:
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("Addition: %d + %d = %d\n", a, b, a + b);
printf("Subtraction: %d - %d = %d\n", a, b, a - b);
printf("Multiplication: %d * %d = %d\n", a, b, a * b);
printf("Division: %d / %d = %d\n", a, b, a / b);
printf("Modulus: %d %% %d = %d\n", a, b, a % b);
return 0;
}
Output:
Addition: 10 + 3 = 13
Subtraction: 10 - 3 = 7
Multiplication: 10 * 3 = 30
Division: 10 / 3 = 3
Modulus: 10 % 3 = 1
2. Relational Operators
Relational operators are used to compare two values and return a Boolean result (1
for true, 0 for false).
List of Relational Operators in C
Operator Symbol Example Description
Equal to == a == b Returns true if both values are equal
Not equal to != a != b Returns true if values are not equal
Greater than > a>b Returns true if left operand is greater
Less than < a<b Returns true if left operand is smaller
Greater than or equal to >= a >= b Returns true if left operand is greater or equal
Less than or equal to <= a <= b Returns true if left operand is smaller or equal
Example:
#include <stdio.h>
int main() {
int x = 5, y = 10;
printf("x == y: %d\n", x == y);
printf("x != y: %d\n", x != y);
printf("x > y: %d\n", x > y);
printf("x < y: %d\n", x < y);
printf("x >= y: %d\n", x >= y);
printf("x <= y: %d\n", x <= y);
return 0;
}
Output:
x == y: 0
x != y: 1
x > y: 0
x < y: 1
x >= y: 0
x <= y: 1
Q.3.b) Develop a complete C program to find real roots of a quadratic equation
by accepting the coefficients. [10 Marks]
Program:
#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,desc;
float r1,r2;
float realpart,imgpart;
printf("Enter the coefficients - a, b and c :");
scanf("%f%f%f",&a,&b,&c);
if(a==0) // if equation is Linear
{
printf("Coefficient of 'a' cannot be zero....\n");
printf("Its a linear equation\n");
return 1;
}
Desc = (b * b) - (4.0 * a * c);
if(desc==0)
{
printf("The roots are real and equal\n");
r1 = r2 = (-b) / (2.0*a);
printf("The two roots are r1=r2=%f\n",r1);
}
else if(desc>0)
{
printf("The roots are real and distinct\n");
r1 = (-b+sqrt(desc)) / (2.0*a);
r2 = (-b-sqrt(desc)) / (2.0*a);
printf("The roots are r1=%f and r2=%f\n",r1,r2);
}
else // discriminant is less than zero, roots are imaginary
{
printf("The roots are imaginary\n");
realpart = (-b) / (2.0*a);
imgpart = sqrt(-desc) / (2.0*a);
printf("The roorts are \n");
printf("r1 = %f + i %f \n",realpart,imgpart);
printf("r2 = %f - i %f \n",realpart,imgpart);
}
return 0;
}
Output:
Enter the coefficients of a, b and c :1 1 1
The roots are imaginary
The roorts are
r1=-0.500000 + i 0.866025
r2=-0.500000 - i 0.866025
2.
Enter the coefficients of a, b and c :1 2 1
The roots are real and equal
The two roots are r1=r2=-1.000000
3.
Enter the coefficients of a, b and c :1 6 5
The roots are real and distinct
The roots are r1=-1.000000 and r2=-5.000000
4.
Enter the coefficients of a, b and c :0 5 3
Coefficient of a cannot be zero....
Please try again....
Q.4.a) Explain the logical and assignment operators of C with example.
1. Logical Operators in C
Logical operators are used to perform logical operations, mainly in
conditional statements (e.g., if, while). They return 1 (true) or 0 (false) based on the
result.
List of Logical Operators in C
Operator Symbol Example Description
Returns true if both
Logical AND && (a > 5) && (b < 10)
conditions are true
Logical OR ` `
Reverses the truth value (true
Logical NOT ! !(a > 5)
to false and vice versa)
Example:
#include <stdio.h>
int main() {
int a = 8, b = 5;
printf("Logical AND (a > 5 && b < 10): %d\n", (a > 5 && b < 10)); // Both condn true → 1
printf("Logical OR (a < 5 || b < 10): %d\n", (a < 5 || b < 10)); // One condition true → 1
printf("Logical NOT !(a > 5): %d\n", !(a > 5)); // True becomes False → 0
return 0;
}
Output:
Logical AND (a > 5 && b < 10): 1
Logical OR (a < 5 || b < 10): 1
Logical NOT !(a > 5): 0
2. Assignment Operators in C
Assignment operators are used to assign values to variables. Some operators
also modify the value while assigning.
List of Assignment Operators in C
Operator Symbol Example Equivalent To
Simple Assignment = a = 10; Assigns 10 to a
Add and Assign += a += 5; a = a + 5;
Subtract and Assign -= a -= 5; a = a - 5;
Multiply and Assign *= a *= 5; a = a * 5;
Divide and Assign /= a /= 5; a = a / 5;
Modulus and Assign %= a %= 5; a = a % 5;
Example:
#include <stdio.h>
int main() {
int a = 10;
printf("Initial value of a: %d\n", a);
a += 5; // a = a + 5
printf("After a += 5: %d\n", a);
a -= 3; // a = a - 3
printf("After a -= 3: %d\n", a);
a *= 2; // a = a * 2
printf("After a *= 2: %d\n", a);
a /= 4; // a = a / 4
printf("After a /= 4: %d\n", a);
a %= 3; // a = a % 3
printf("After a %%= 3: %d\n", a);
return 0;
}
Output:
Initial value of a: 10
After a += 5: 15
After a -= 3: 12
After a *= 2: 24
After a /= 4: 6
After a %= 3: 0
Q.4.b) Write a C Program to find the factorial of a given integer n. Explain the
computation process. [10 Marks]
Program:
#include <stdio.h>
long factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d = %llu\n", n, factorial(n));
}
return 0;
}
Output:
Enter a positive integer: 5
Factorial of 5 = 120
Computation Process (Using Recursion)
1. The factorial() function is called with input nnn.
2. If nnn is 0 or 1, it returns 1 (base case).
3. Otherwise, the function calls itself with n−1n - 1n−1, multiplying nnn with the
factorial of n−1n - 1n−1.
4. This continues until the base case is reached.
5. The results are combined, and the final factorial is displayed.
MODULE-3
Q.5.a) Write a C program to find the sum and average of n integers. [10 Marks]
Program
#include <stdio.h>
int main() {
int n, i;
float sum = 0, average;
printf("Enter the number of integers: ");
scanf("%d", &n);
if (n <= 0) {
printf("Please enter a positive number of integers.\n");
return 1; // Exit the program with an error code
}
int numbers[n]; // Array to store the numbers
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &numbers[i]); // Read each number
sum += numbers[i]; // Add to sum
}
average = sum / n;
printf("Sum = %.2f\n", sum);
printf("Average = %.2f\n", average);
return 0;
}
Output:
Enter the number of integers: 5
Enter 5 integers:
10 20 30 40 50
Sum = 150.00
Average = 30.00
Enter the number of integers: -3
Please enter a positive number of integers.
Q.5.b) Explain the concept of function declaration and function definition with
an example. [10 Marks]
A user-defined function is a type of function in C language that is defined by the
user himself to perform some specific tasks. It provides code reusability and
modularity to our program. User-defined functions are different from built-in
functions as their working is specified by the user and no header file is required for
their usage.
The user-defined function in C can be divided into three parts:
1. Function Declaration
2. Function Definition
3. Function Call
Function Declaration
A function prototype is also known as a function declaration which specifies the
function’s name, function parameters, and return type. The function prototype
does not contain the body of the function. It is basically used to inform the compiler
about the existence of the user-defined function which can be used in the later part of
the program.
return_type function_name (type1 arg1, type2 arg2, ... typeN argN);
Function Definition
Once the function has been called, the function definition contains the actual
statements that will be executed. All the statements of the function definition are
enclosed within { } braces.
Syntax
return_type function_name (type1 arg1, type2 arg2 .... typeN argN) {
// actual statements to be executed
// return value if any
}
C Function Call
In order to transfer control to a user-defined function, we need to call it. Functions are
called using their names followed by round brackets. Their arguments are passed
inside the brackets.
Syntax
function_name(arg1, arg2, ... argN);
Example program:
#include <stdio.h>
int sum(int, int);
int sum(int x, int y)
{
int sum;
sum = x + y;
return x + y;
}
int main()
{
int x = 10, y = 11;
int result = sum(x, y);
printf("Sum of %d and %d = %d ", x, y, result);
return 0;
}
Output
Sum of 10 and 11 = 21
Q.6.a) Write a C program to add two mxn matrices. [10 Marks]
Program:
#include <stdio.h>
#define ROWS 3
#define COLS 3
void readMatrix(int matrix[ROWS][COLS], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}
void printMatrix(int matrix[ROWS][COLS], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
void addMatrices(int mat1[ROWS][COLS], int mat2[ROWS][COLS], int
result[ROWS][COLS], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
int main() {
int mat1[ROWS][COLS], mat2[ROWS][COLS], result[ROWS][COLS];
printf("Enter elements for the first matrix:\n");
readMatrix(mat1, ROWS, COLS);
printf("Enter elements for the second matrix:\n");
readMatrix(mat2, ROWS, COLS);
addMatrices(mat1, mat2, result, ROWS, COLS);
printf("The resulting matrix after addition is:\n");
printMatrix(result, ROWS, COLS);
return 0;
}
Example Output:
Enter elements for the first matrix:
Enter element [1][1]: 1
Enter element [1][2]: 2
Enter element [1][3]: 3
Enter element [2][1]: 4
Enter element [2][2]: 5
Enter element [2][3]: 6
Enter element [3][1]: 7
Enter element [3][2]: 8
Enter element [3][3]: 9
Enter elements for the second matrix:
Enter element [1][1]: 9
Enter element [1][2]: 8
Enter element [1][3]: 7
Enter element [2][1]: 6
Enter element [2][2]: 5
Enter element [2][3]: 4
Enter element [3][1]: 3
Enter element [3][2]: 2
Enter element [3][3]: 1
The resulting matrix after addition is:
10 10 10
10 10 10
10 10 10
Q.6.b) Explain the following with an example:
i) Passing the entire array.
ii) Passing the individual elements of an ID array. [10 Marks]
i) Passing the entire array:
When an array is passed to a function, only its base address (reference) is
passed, not the entire array.
Example:
#include <stdio.h>
void displayArray(int arr[], int size) {
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int numbers[] = {10, 20, 30, 40, 50}; // Define an array
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate size of the array
displayArray(numbers, size);
return 0;
Output:
Array elements: 10 20 30 40 50
ii) Passing the individual elements of an ID array.
Program
#include <stdio.h>
void square(int num) {
num = num * num; // Modifies the local copy
printf("Squared value: %d\n", num);
}
int main() {
int arr[] = {2, 4, 6, 8}; // Define an array
printf("Original value: %d\n", arr[1]);
square(arr[1]); // Pass the second element (4)
printf("After function call, original value: %d\n", arr[1]);
return 0;
}
Output:
Original value: 4
Squared value: 16
After function call, original value: 4
MODULE - 4
Q.7.a) Write a C program to find the length of a given string without using
inbuilt function. [10 Marks]
Program:
#include <stdio.h>
int main() {
char str[100]; // Declare a string with a maximum size of 100
int length = 0; // Variable to store the length
printf("Enter a string: ");
scanf("%[^\n]", str); // Reads the entire line including spaces
while (str[length] != '\0') {
length++; // Increase length count for each character
}
printf("Length of the string: %d\n", length);
return 0;
}
Output:
Enter a string: Hello World
Length of the string: 11
Explanation:
1. Input Handling:
o The user enters a string.
o scanf("%[^\n]", str); ensures we read the full line including spaces
until a newline (\n) is encountered.
2. Finding the Length:
o A while loop runs through the string character by character.
o It increments length until it finds the null terminator (\0).
o The final value of length gives the total number of characters in the
string.
3. Displaying the Result:
o The length is printed to the console.
Q.7.b) What is a pointer? Show the use of two pointer operators & and *.
[10 Marks]
A pointer in C is a variable that stores the memory address of another variable.
Pointers are used for efficient memory access, dynamic memory allocation, and
passing values by reference.
The ampersand (&) operator gives the memory address of a variable.
The asterisk (*) operator is used to access the value at a memory address
(dereferencing).
Syntax:
data_type *pointer_name;
Program:
#include<stdio.h>
#include<math.h>
int main()
{
int i,n;
float a[10],mean,sd,sum,var;
float *p; // p is a pointer to float value
//p=&a[];
printf("\n Enter Number of elements :");
scanf("%d",&n);
printf("\n Enter the elements :");
p=a; // pointer p points to first element of a
for(i=0;i<n;i++)
{
scanf("%f",p);
p++; // pointer p points to the next element of the array
}
p=a; // Initialize p to the first element of the array
printf("\n input Elements are:\n");
for(i=0;i<n;i++)
{
printf("%f",*p);
p++; // Pointer p is made to point to the next element
}
p=a; // Initialize p to the first element of the array
sum=sd=mean=var=0;
// Find the sum of the array elements
for(i=0;i<n;i++)
{
sum=sum+(*p);
p++;
}
// Find the mean
mean=sum/n;
// Find variance
p=a;
for(i=0;i<n;i++)
{
var=var+pow((*p-mean),2);
p++;
}
var=var/n;
// Find Standard Deviation
sd=sqrt(var);
// Print Sum, mean and Standard Deviation
printf("\n\n mean=%f\nsum=%f\nsd=%f\nvar=%f\n",mean,sum,sd,var);
return 0;
}
Output:
Enter Number of elements: 5
Enter the elements : 1 2 3 4 5
Input Elements are:
1.0000002.0000003.0000004.0000005.000000
Mean=3.000000
Sum=15.000000
Standard Deviation=1.414214
Variance=2.000000
Q.8.a) Write a C program to compare two given string S1 and S2 Without using
inbuilt function. [10 Marks]
Program:
#include <stdio.h>
int main()
char str1[50], str2[50];
int i,result=0;
printf("\nEnter two strings for string compare :");
scanf("%s",str1);
scanf("%s",str2);
for(i=0;str1[i] != '\0' || str2[i] != '\0';i++)
if (str1[i] != str2[i])
result = str1[i]-str2[i];
break;
if(result < 0)
printf("String %s is less than string %s\n",str1,str2);
}
else if (result == 0)
printf("String %s is same as string %s\n",str1,str2);
else
printf("String %s is greater than string %s\n", str1,str2);
return 0;
Output:
Enter two strings for string compare: Dog Cat
String Dog is greater than string Cat
Enter two strings for string compare: cat dog
String cat is less than string dog
Enter two strings for string compare: cat cat
String cat is same as string cat
Q.8.b) How do you declare and initialize pointers in C? Show with example.
[10 Marks]
A pointer is a variable that holds the address of another variable.
Syntax:
data_type *pointer_name = &variable;
data_type: The type of data the pointer will point to (e.g., int, float, etc.).
*pointer_name: The pointer variable that will store the address of a variable
of type data_type.
&variable: The address of the variable of the same type to which the pointer
will point.
Example:
•int *ip; /* pointer to an integer */
•double *dp;/* pointer to a double */
•float *fp;/* pointer to a float */
•char *ch /* pointer to a character *
Example Program:
#include<stdio.h>
void main()
int x = 99;
int *ptr; // Declare a pointer
ptr = &x; // Assign the value to pointer
printf("Value of ptr = %d\n", *ptr);
printf("Address of ptr =%p\n", ptr);
Output:
Value of ptr = 99
Address of ptr =0x7ffdba4e00e4
MODULE - 5
Q.9.a) What is recursion? Give one example. [10 Marks]
A recursive function is a function that calls itself to solve a smaller version of
its task until a final call is made which does not require a call to itself.
#include <stdio.h>
Program:
#include <stdio.h>
long long factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 0)
printf("Factorial is not defined for negative numbers.\n");
else
printf("Factorial of %d is %lld\n", num, factorial(num));
return 0;
Output:
Enter a number: 5
Factorial of 5 is 120
Q.9.b) Differentiate between arrays and Structures in C. [10 Marks]
Q.10.a) Explain the process of opening and closing a file. [10 Marks]
Opening a File
A file must first be opened before data can be read from it or written to it. In order to
open a file and associate it with a stream, the fopen() function is used. The prototype
of fopen() can be given as
FILE *fopen(const char *file_name, const char 26 mode);
Using the above prototype, the file whose pathname is the string pointed to by
file_name is opened in the mode specified using the mode. If successful, fopen()
returns a pointer-to- structure and if it fails, it returns NULL.
Look at the code given below which opens a file using the fopen().
FILE *fp;
Fp = fopen("Student.DAT", "r");
if (fp==NULL)
printf("\n The file could not be opened");
exit (1);
Closing a File Using fclose()
To close an open file, the fclose() function is used which disconnects a file pointer
from a file. After the fclose() has disconnected the file pointer from the file, the
pointer can be used to access a different file or the same file but in a different mode.
The fclose() function not only closes the file, but also flushes all the buffers that are
maintained for that file. If you do not close a file after using it, the system closes it
automatically, when the program exits. However, since there is a limit on the number
of files which can be opened simultaneously; the programmer must close a file when
it has been used. The prototype of the fclose()function can be given as
int fclose (FILE *fp);
Program:
#include<stdio.h>
int main()
{
char src_fname[20], tar_fname[20], ch;
printf("Enter input file name and target file name :");
scanf("%s%s", src_fname, tar_fname);
FILE *fp1,*fp2;
fp1 = fopen(src_fname, "r");
if (fp1 == NULL)
printf("Unable to open file - %s in Read mode\n",src_fname);
return 1;
fp2 = fopen(tar_fname, "w");
if (fp2 == NULL)
printf("Unable to open file - %s in write mode\n", tar_fname);
return 2;
while ((ch = fgetc(fp1)) != EOF)
fputc(ch, fp2);
printf("File copied successfully\n");
fclose(fp1);
fclose(fp2);
Output:
Enter input file name and target file name : src.c tar.c
File copied successfully.
Q.10.b) Differentiate between structures and union. [10 Marks]
Ans: