0% found this document useful (0 votes)
20 views

POP Imp Question and Answers From Module 1 -5

The document outlines the curriculum for the Principles of Programming Using C course for the Department of Computer Science and Engineering for the academic year 2024-25. It covers various topics including types of computers, algorithms, flowcharts, C programming structure, formatted input/output, identifiers, output devices, and input devices. Each section includes definitions, examples, and programming exercises to reinforce learning.
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)
20 views

POP Imp Question and Answers From Module 1 -5

The document outlines the curriculum for the Principles of Programming Using C course for the Department of Computer Science and Engineering for the academic year 2024-25. It covers various topics including types of computers, algorithms, flowcharts, C programming structure, formatted input/output, identifiers, output devices, and input devices. Each section includes definitions, examples, and programming exercises to reinforce learning.
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/ 43

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

AY 2024-25
Subject Code: BPOPS103 Subject: Principles of Programming Using C Date: 04/11/2024
Semester: 1 Module: 1 &2 Branch: CSE

Module – 1
Q# CO# BTL Questions Marks

Define computer. Describe the various types of computers based on speed,


memory and cost.

● Computer is an electronic device, which takes input from the user in the
form of data and instructions.
● On receiving the instructions from the user, the computer processes the
data and generates the output and displays it to the user.

Different Types of Computer

Computers can be generally classified by size and power as follows,

1.Supercomputers
● Fastest, most powerful, and most expensive computer
● Used to process large amounts of data and to solve complex scientific
problems
● Can support thousands of users at the same time
● Mainly used for weather forecasting, nuclear energy research, aircraft
design, automotive design, online banking, etc.
● Some examples of supercomputers are CRAY-1, CRAY-2, Control Data
CYBER 205, and ETA A-10
2.Mainframe Computers
● Large-scale computers, but smaller than Supercomputers
● Very expensive
● Need a very large clean room with air conditioning
● Used as servers on the World Wide Web
1. 8M
1 1 ● Some examples are IBM S/390, Control Data CYBER 176
3.Minicomputers
● Smaller, cheaper, and slower than Mainframes
● Can be used as servers in a networked environment
● Widely used in business, education, hospitals, government
● Some examples are AS/400 computers (IBM Corporation), Data General
Corporation, and Prime Computer
4.Microcomputers
Laptop
● Laptops are small microcomputer that can easily fit inside a briefly.
Desktop PCs
● A desktop PC is the most popular model of PCs.
● The system unit of the desktop PC can be placed flat on a desk or table.
Workstation
● Workstation are single-user computer that have the same features of PCs,
but their processing speed matches that of a minicomputer or mainframe
computer.
Network Computer
● Network computer have less processing power, memory, and storage
than a desktop computer.
● These computers are specifically designed to be used as terminals in a
networked environment.
Handheld Computers
● The mid-1990s witnessed a range of small personal computing devices
that are commonly known as handheld computers, or mobile computers.
(Smart phones and Tablet PCs)
Design an algorithm, flowchart and program to compute area and perimeter of
a circle.

● An algorithm provides a blueprint to writing a program to solve a


particular problem.
● It is considered to be an effective procedure for solving a problem in a
finite number of steps.

Algorithm to find area and perimeter of Circle:

Step 1: Start
Step 2: Input the value radius
Step 3: Calculate Area= 3.14 * radius * radius
Step 4: Calculate Perimeter of the Circle Peri = 2 * 3.14 * radius
Step 5: PRINT Area and Peri
Step 6: END

Flowchart
● A flowchart is a graphical representation of an algorithm.

2. 2 2 6M

Program
#include <stdio.h>
int main()
{
int radius;
float area, perimeter;
printf("Enter radius of the Circle:\n");
scanf("%d", & radius);
area = 3.14 * radius * radius;
printf("Area of the Circle = %f \n", area);
perimeter = 2 * 3.14 * radius;
printf("Perimeter of the Circle = %f \n", perimeter);
return 0;
}

Output
Enter radius of the Circle:
3
Area of the Circle =28.26
Perimeter of the Circle =18.84
Explain generations of computers
3. 1 1
First Generation

● These computers were manufactured using thousands of vacuum tubes.


● The Electromagnetic relay was used as primary memory and punch
cards were used to store data and instructions. 8M
Disadvantage

● Generated lot of heat


● Consumed lot of electricity
● Bulky in size, required constant maintenance
● Very expensive

Second Generation

● These computers were manufactured using transistors which were


reliable, cheaper, smaller and cooler than vacuum tubes.
● Magnetic core memory was used as primary memory and magnetic
tapes and disks were used to store data and instructions.
● Programming was done in high level programming language.

Advantage

● Consumed less electricity


● Generated less heat
● Faster cheaper and more reliable

Disadvantage

● Transistors were assembled manually which made commercial


production difficult and expensive

Third Generation

● These computers were manufactured using transistors integrated


chips(IC’s)
● Large Magnetic core memory was used as primary memory and
magnetic tapes and disks were used to store data and instructions.
● Programming was done in high level programming language.

Advantage

● Faster and could perform one million transactions per second


● Smaller, cheaper and more reliable
● Widely used for scientific and business applications

Disadvantage: Difficult to maintain and got heated very quickly.

Fourth Generation
● These computers were manufactured using transistors integrated
chips(IC’s) with LSI’s and later with VLSI.
● Semiconductors memory was used as primary memory and magnetic
tapes and floppy disks were used as portable storage devices.
● Programming was done in high level programming language such as C
and C++.

Advantage

● Smaller, cheaper, faster and more reliable


● Consumer less electricity, generated less heat
● Used as General purpose computers
● Widespread of computers to office and homes

Disadvantage : Not intelligent systems.

Fifth Generation

● Manufactured using transistors integrated chips(IC’s) with ULSI’s(Ultra


Large scale Integration) technology.
● Semiconductors memory was used as primary memory and magnetic
tapes and floppy disks were used as portable storage devices.
● Programming was done in high level programming language such as
Java, Python and C#

Advantage

● Smaller, cheaper, faster, powerful and more reliable


● Consumer less power, generated less heat, high-end features available.

Draw a flowchart and C program which takes as input p,t,r. Compute the
simple interest and display the result.

Flowchart

4. 2 2 6M
Program
#include <stdio.h>
void main()
{
int p,t,r;
float si=0.0;
printf("Enter the values for p,t,r:\n");
scanf("%d%d%d", &p, &t, &r);
si= p*t*r/100.0;
printf("si = %f \n", si);
}

Output
Enter the values for p,t,r:
1200
2
5
si =120.000000
Explain the structure of C program in detail. Write a sample program to
demonstrate the components in the structure of C program

Documentation
Preprocessor Directives
Global Declarations
main( )
{
Local declaration
Statements;
}
Function1( )
{
Local declaration
Statements;
}
......................
......................
FunctionN( )
{
Local declaration
Statements;
}
Documentation
● It includes the statement specified at the beginning of a program, such as
a program's name, date, description, and title.
● It is represented as:
//name of a program
Or

/*
Overview of the code
5. 2 1 8M
*/
Preprocessor Section
● This section contains all the header files used in a program.
● It informs the system to link the header files to the system libraries. It is
given by:
#include<stdio.h>
#include<stdio.h>
● Preprocessor directives are instructions given to the compiler before
actual compilation begins.
● For example, #include is used to include libraries that provide essential
functions like printf() from the standard input-output library (<stdio.h>)
Global Declarations
● Global variables are declared outside any function, usually at the top of
the program.
● These variables can be accessed and modified by any function in the
program.
main() Function
● The main() function is the entry point of every C program.
● It defines where the program starts executing and returns an integer
value (0 means successful execution).

User defined functions


● The user defined functions specified the functions specified as per the
requirements of the user.
● For example, color(), sum(), division(), etc.

Example : To find the sum of two numbers given by the user


/* Sum of two numbers */
#include<stdio.h>
int main()
{
​ int a, b, sum=0;
​ printf("Enter two numbers to be added ");
​ scanf("%d %d", &a, &b);
​ sum = a + b; // calculating sum
​ printf("%d", sum);
​ return 0; // return the integer value in the sum
}
Demonstrate formatted input and output of integer in C with suitable example
(Explain Input Output statements in C)

● Formatted I/O functions are used to take various inputs from the user
and display multiple outputs to the user.
● These types of I/O functions can help to display the output to the user in
different formats using the format specifiers.
● These functions are called formatted I/O functions because we can use
format specifiers in these functions
Format Specifier Description

%d Used for I/O signed integer

%c Used for I/O character value

%f Used for I/O decimal floating-point value


printf()
● printf() function is used in a C program to display any value like float,
integer, character, string, etc on the console screen.
● It is a pre-defined function that is already declared in the stdio.h(header
file).
● Syntax 1: To display any variable value.
printf(“Format Specifier”, var1, var2, …., varn);
● Example: printf("%d", a);
6. 1 2 ● Syntax 2: To display any string or a message 6M
printf(“Enter the text which you want to display”);
● Example: printf("Hello World”);
scanf()
● scanf() function is used in the C program for reading or taking any value
from the keyboard by the user
● This function is declared in stdio.h(header file)
● Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);
● Example: scanf("%d", &a);

Example Program

#include <stdio.h>
void main()
{
int x;
printf(“Please enter any number:\n ”);
scanf(“%d”,&x);
printf(“The entered number is= %d”,x);
}

Output
Please enter any number:
20
The entered number is = 20
Explain the various rules for forming identifiers names. Give examples for valid
and invalid identifiers for the same.

● Identifiers are names given to program elements such as variables, arrays


and functions.
● Identifiers may consist of sequence of letters, numerals, or underscores.

Rules for forming identifier name


● It cannot include any special characters or punctuation marks
(like #, $, ^, ?, .,etc) except the underscore"_".
● There cannot be two successive underscores
● Keywords cannot be used as identifiers
● The names are case sensitive. So, example, “FIRST” is different from
“first” and “First”.
● It must begin with an alphabet or an underscore.
7. 1 1 ● It can be of any reasonable length. Though it should not contain more 8M
than 31 characters.

Mention various output devices and explain hardcopy devices

● Any device that outputs/gives information from a computer is called an


output device.
● Output devices are electromechanical devices which accept digital data
from the computer and converts them into human understandable
language.
● Output devices are classified into 2 types

8.

SOFT COPY DEVICES


● Soft copy output devices are those output devices which produce an
electronic version of an output.
● The output can be viewed only when the computer is on.
● The user can easily edit the soft copy output
● Soft copy cannot be used by people who do not have a computer
Monitors
● The monitor is a soft copy output device used to display video and
graphics information generated by the computer through the video card.
● Monitors have 3 variants:
● Cathode Ray tube(CRT)
● Liquid Crystal Display(LCD)
● Plasma.
Projector
● A projector is a device which takes an image from a video source and
projects it onto a screen or other surface.
● LCD Projector make use of their own light to display the image on the
wall and are based on LCD technology.
Speaker
● Speakers are the output devices that are connected to computers to allow
sound to be output.
● For the working of speakers, sound cards send signals to the speakers
which are converted into audio
● These speakers use internal amplifiers which vibrate at different
frequencies to increase/decrease the volume or amplitude of sound

HARD COPY OUTPUT DEVICES


● Hard copy output devices produces a physical form of output.
● For example, the content of a file printed on a paper is a form of hard
copy output.
Printers
● Printer is a device that outputs text and graphics information obtained
from the computer and prints it on to a paper.
● Printers are available in the market in a variety of size, speed,
sophistication, and cost.
● Printers are divided into two categories which are Impact Printer and
Non-Impact Printer
Plotter
● A plotter is considered to be one of the output devices of the computer
system.
● They are used and utilized extensively for designing and printing
● A plotter takes time to print and is considerably slow compared to
printers.
● These plotters can be connected to computers via USB and Serial Ports.

Explain about different input devices


9.
1 2 6M
Input Devices: An input device is used to feed data and instructions to the
computer.
Keyboard
● A computer keyboard, often known as a laptop keyboard, is a piece of
hardware that allows you to input data into a computer.
● It is often a plug-and-play gadget.
● The alphabets (A-Z), numerals (0-9), symbols, and function keys are all
found on a computer keyboard.
Scanner
● A scanner, like a photocopier, is an input device that is used when paper
data has to be transferred to a computer's hard disc and subsequently
modified.
● The scanner gathers images from the source and transforms them into a
digital version stored on a disc.
Microphone
● A microphone is a type of sound input device used by computers.
● It absorbs sound vibrations and transforms them into audio signals or
records them on media.
● The audio impulses are transformed into digital data, which is then
saved in the computer.
Pointing Device
1.Mouse
● A pointing device that helps users to select items on screen by controlling
the movement of pointer
● Can be used to perform the following operations:
● Point Click
● Drag Scroll
2.Trackball
● A pointing device to control the position of the cursor on the screen
● Usually used in notebook computers, where it is placed on the keyboard
Advantages
● Provides better resolution
● Occupies less space
● Easier to use as compared to a mouse as its use involves less
hand-and-arm movements

Handheld device
1.Joystick
● A joystick is a pointing device for computers that allows you to move the
pointer around the screen.
● Both the bottom and top ends of the stick are connected to a spherical
ball, and the bottom spherical ball slips in a socket.
● Wecan move the joystick in all four directions.

What are the basic datatypes available in C?

● The basic data types are also known as fundamental or primary data
10. 1 2 types. 8M
● Basic data types are used in the C language for storing the available
values in decimal as well as integer forms
● These provide support for both – unsigned and signed literals.
Integer Datatype
● The variables that are of integer type are capable of storing negative,
zero, as well as positive values without the decimals.
● The C language represents the integer data type by the keyword int.
● Size: 4 bytes
● Format Specifier: %d
Syntax of Integer
● int var_name;
● Example: int a;
Character Data Type
● Character data type allows its variable to store only a single character.
● The size of the character is 1 byte.
● It is the most basic data type in C.
● It stores a single character and requires a single byte of memory in
almost all compilers.
● Range: (-128 to 127) or (0 to 255)
● Size: 1 byte
● Format Specifier: %c
Syntax of char
● The char keyword is used to declare the variable of character type:
● char var_name;
● Example : char a = 'z';
printf("Value of a: %c\n", a);
Float Data Type
● In C programming float data type is used to store floating-point values.
● Float in C is used to store decimal and exponential values.
● It is used to store decimal numbers (numbers with floating point values)
with single precision.
● Range: 1.2E-38 to 3.4E+38
● Size: 4 bytes
● Format Specifier: %f
Syntax of float
● The float keyword is used to declare the variable as a floating point:
● float var_name;
● Example: float a;
Double Data Type
● A Double data type in C is used to store decimal numbers (numbers with
floating point values) with double precision.
● It is used to define numeric values which hold numbers with decimal
values in C.
● The double data type is basically a precision sort of data type that is
capable of holding 64 bits of decimal numbers or floating points.
● It can easily accommodate about 16 to 17 digits after or before a decimal
point.
● Range: 1.7E-308 to 1.7E+308
● Size: 8 bytes
● Format Specifier: %lf
Syntax of Double
● The variable can be declared as double precision floating point using the
double keyword:
● double var_name;
● Example : double a;

Course Outcomes:

● CO 1 Elucidate the basic architecture and functionalities of a computer and also recognize the
hardware parts.
● CO 2 Apply programming constructs of C language to solve the real-world problem
● CO 3 Explore user-defined data structures like arrays in implementing solutions to problems like
searching and sorting
● CO 4 Explore user-defined data structures like structures, unions and pointers in implementing
solutions
● CO 5 Design and Develop Solutions to problems using modular programming constructs using
functions
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Important Question and Answers AY 2024-25
Subject Code: BPOPS103 Subject: Principles of Programming Using C Date: 04/11/2024
Semester: 1 Module: 1 &2 Branch: CSE

Module – 2
Marks
Q Mod# CO# BTL Questions
#
Write a note on the following operators. i) Relational ii) Logical iii) Conditional 6M
1. 2 2 2 1)Relational Operator
These operators are used to compare the value of two variables.
Following table shows all the relational operators supported by C language.
Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
== Checks if the values of two operands (A == B) is not true.
are equal or not, if yes then condition
becomes true.
!= Checks if the values of two operands (A != B) is true.
are equal or not, if values are not
equal then condition becomes true.
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right
operand, if yes then condition
becomes true.
< Checks if the value of left operand is (A < B) is true.
less than the value of right operand, if
yes then condition becomes true.
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of
right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is (A <= B) is true.
less than or equal to the value of right
operand, if yes then condition
becomes true.
ii) Logical Operators:
These operators are used to perform logical operations on the given two
variables.
Following table shows all the logical operators supported by C language.
Assume variable A holds 1 and variable B holds 0, then:
Operator Description Example
&& Called Logical AND (A && B) is false.
operator. If both the
operands are nonzero,
then condition becomes
true.
|| Called Logical OR (A || B) is true.
Operator. If any of the
two operands is
non-zero, then condition
becomes true.
! Called Logical NOT !(A && B) is true.
Operator. Use to reverses
the logical state of its
operand. If a condition is
true then Logical NOT
operator will make false.
iii) Conditional Operator
Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e,
executes different statements according to test condition whether it is either true
or false.
Syntax of conditional operators;
conditional_expression?expression1:expression2
If the test condition is true (that is, if its value is non-zero), expression1 is
returned and if false expression2 is returned.
Let us understand this with the help of a few examples:
int x, y ;
scanf ( “%d”, &x ) ;
y = ( x> 5 ? 3 : 4 ) ;
This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in
y.
The equivalent if statement will be,
if ( x > 5 )
y=3;
else
y=4;
2. 2 1 3 Demonstrate the functioning of Bitwise operator in C 6M

Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Bitwise
operators are used in bit level programming. These operators can operate upon
int and char but not on float and double.
Showbits( ) function can be used to display the binary representation of any
integer or character value.
Bit wise operators in C language are; & (bitwise AND), | (bitwise OR), ~
(bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).
The truth tables for &, |, and ^ are as follows
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

List the conditional branching statements in C. Explain any two with example.
3. 2 1 1 Conditional branch statements 6M
 The statements that transfer the control from one place to another place in the
program based on some conditions are called Conditional branch statements.
Simple- if
if-else
Nested-if
if-else-if
switch
If Statement:
✔ The ‘if’ statement is the simplest form of decision control statement.
✔ When a set of statements have to be executed when an expression
(condition) is evaluated to true or skipped when an expression
(condition) is evaluated to false, then if statement is used.
✔ It is used whenever there is only one choice (alternative). Hence it is
also called as “One- way decision or selection statement”.
Syntax of if statement
if(test Expression)
{
Statement 1;
Statement 2;
...

… Statement n;
}
Statement x;
Working Principle
First the test expression is evaluated. If the test expression is true, then the
statements of ‘if’ block (statement 1 to n) are executed. Otherwise these
statements will be skipped and the execution will jump to statement x.
Example
#include<stdio.h>
void main()
{
int age;
printf(“Enter the age:”);
scanf(“%d”,&age);
if(age>=18)
printf(“\nThe person is eligible to vote”);
if(age<18)
printf(“\nThe person is not eligible to vote”);
}

if-else statement
✔ If one set of activities have to be performed when an expression is
evaluated to true and another set of activities have to be performed when
an expression is evaluated to false, then if-else statement is used.
✔ The is-else statement is used when we must choose between two
choices (alternatives). Hence is also called as “Two-way Decision or
Selection Statement”.
Syntax of if-else statement:
if(test Expression)
{
Statement block 1;
}
else
{
Statement block 2;
}
Statement x;
Example
#include<stdio.h>
void main()
{
int age;
printf(“Enter the age:”);
scanf(“%d”,&age);
if(age>=18)
printf(“\nThe person is eligible to vote”);
else
printf(“\nThe person is not eligible to vote”);
}

Illustrate Nested if else in C with suitable example


4 2 2 3 8M
Nested if-else statement
 An if-else statement within if statement or an if-else statement within
else statement is called “nested if or if-else statement”.
 When an action has to be performed based on many decisions involving
various types of expressions and variables, then this statement is used. So it is
called as “Multi-way decision statement”.

Syntax for nested if-else statement


if(testExpression1)
{
if(testExpression2)
{
Statement block 1;
}
else
{
Statement block 2;
}
}
else
{
Statement block 3;
}
Statement x;
Example
Write a C program to find the largest of three numbers.
#include<stdio.h>
void main()
{
int a,b,c;
printf(“Enter the three numbers:”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
printf(“Max=%d”,a);
else
printf(“Max=%d”,c);
}
else
{
if(b>c)
printf(“Max=%d”,b);
else
printf(“Max=%d”,c);
}
}

Write an algorithm, flow chart and C program to check whether the integer is
5. 2 1 3 even or odd. 8M
Program
#include<stdio.h>
void main()
{
int n;
printf(“Enter a number:”);
scanf(“%d”,&n);
if(n%2==0)
printf(“Number is even”);
else
printf(“Number is odd”);
}
Flow Chart

ALGORITHM :
STEP 1: START
STEP 2: Receive data from a user or dynamically assign value
STEP 3: if num percent 2 == 0. Even Integer should be printed.
STEP 4: Else,
STEP 5: Print an Odd Number
STEP 6: END
Write an algorithm, flow chart and C program to check whether the 8M
6. 2 1 3
entered year is leap year or not
Algorithm
Step 1: Start
Step 2: Read the value of the year to be checked from the user
Step 3: Assign the value to a variable, say ‘year’
Step 4: If (year%4 = 0 AND year%100 != 0) OR year%400 = 0, then:
Step 4.1: Display “Leap Year”
Step 5: Else
Step 5.1: Display “Not Leap Year”
Step 6: Stop
Flowchart

Program
#include<stdio.h>
void main()
{
int year;
printf(“Enter any year:”);
scanf(“%d”,&year);
if(((year%4==0)&&(year%100!=0))||(year%400==0))
printf(“%d is a leap year”,year);
else
}
printf(“%d is not a leap year”,year);
}
Write a C program to print whether a given number is palindrome or not 8M
7 2 2 3
#include<stdio.h>
void main()
{
int digit,rev=0,num,n;
printf("Enter the number:\n");
scanf("%d",&num);
n=num;
while(num!=0)
{
digit=num%10;
rev=rev*10+digit;
num=num/10;
}
printf("The reversed number is=%d\n",rev);
if(n==rev)
printf(“ The number is a palindrome”);
else
}
printf(“The number is not a palindrome”);
}

8 2 2 2 Explain switch statement with syntax and example 7M


switch statement
 The ‘switch’ statement is a control statement used to select one alternative
among several alternatives.
 It is a “multi-way decision statement” that tests whether an expression
matches one of the case values and branches accordingly

switch statement syntax


switch(expression)
{
case value-1: Statement block 1;
break;
case value-2: Statement block 2;
break;
…..
…..
case value-n: Statement block n;
break;
default: Statements;
}
Statement x;
Write a C program to display the grade.
#include<stdio.h>
void main()
{
char grade;
printf(“Enter the grade:”);
scanf(“%c”,&grade);
switch(grade)
{
case ‘O’: printf(“Outstanding”);
break;
case ‘A’: printf(“Excellent”);
break;
case ‘B’: printf(“Good”);
break;
case ‘C’: printf(“Fair”);
break;
case ‘F’: printf(“Fail”);
break;
default : printf(“Invalid grade”);
}
}
9 Implement a C program to simulate a simple calculator that performs
2 2 3 6M
arithmetical operations using switch statements.
#include<stdio.h> void main()
{
float a,b,res; char op;
printf("Enter arithmetic expression[operand1 operator operand2]:");
scanf("%f%c%f",&a,&op,&b);
switch(op)
{
case'+': res=a+b;
printf("\nsum=%f",res);
break;
case'-': res=a-b;
printf("\nDifference=%f",res);
break;
case'*': res=a*b; printf("\nProduct=%f",res);
break;
case'/': res=a/b; printf("\nQuotient=%f",res);
break;
default: printf("Invalid operator!");
break;
}
}

10. Define looping. Explain while and do-while with suitable example
2 2 2

A set of statements may have to be repeatedly executed for a specified number


of times or till a condition is satisfied.
 The statements that help us to execute a set of statements repeatedly for
a specified number of times or till a condition is satisfied are called as
Iterative statements or looping constructs or loop control statements.
 These statements are also called as Repetitive or Iterative Statements.

while loop
Loop Statements
for loop
do-while loop
while Loop
 It is a control statement using which the programmer can give
instructions to the computer to execute a set of statements repeatedly as
long as specified condition is satisfied.
 The expression is evaluated to TRUE or FALSE in the beginning of the while
loop. Hence it is called as “Entry-Controlled Loop”.
Syntax of while loop
while(test expression)
{
Statements;
}
Statement x;
Example
Write a C program to print the natural numbers from 1 to 10.
#include<stdio.h>
void main()
{
int i=1;
while(i<=10)
{
printf(“%d\n”,i);
i++;
}
}
do-while Loop
 do- while loop is used when a set of statements have to be repeatedly
executed at least once.
 Since the test expression is evaluated to TRUE or FALSE at the end of
do-while loop, the do- while loop is called as exit-controlled loop.
 The while and for loop test the expression at the top.
 The do-while tests the expression at the bottom after making each passes
through the loop body
Syntax of do-while loop
do
{
Statements;
} while(test expression);
Statement x;
11 List and explain unconditional branching statements with
example(goto,break,continue)
2 2 1
break statement
 In C, break statement is used to terminate the execution of the nearest
enclosing loop in which it appears.
 It is ‘jump’ statement which can be used in switch statement and loops.
 The break statement in switch statement causes the control to come out
of the switch statement and transfers the control to the statement which
follows the switch statement.
switch(ch)
{
case 1: printf(“1st statement”);
break;
case 2: printf(“2nd statement”);
break;
default: printf(“nth statement”);
}
Example
Write a C program to print the numbers (0 to 4) using break.
#include<stdio.h>
void main()
{
int i=0;
while(i<=10)
{
if(i==5)
break;
printf(“%d\n”,i);
i=i+1;
}
}
continue statement
 During execution of a loop, it may be necessary to skip a part of the loop
based on some condition. In such cases, we use continue statement.
 The continue statement is used only in the loops to terminate the current
iteration and continue with the remaining iterations.
Syntax:
1. while(… )

{
if(condition) continue;
……….
}
……….

Write a C program to display the output in the following form 1 3 4 5


#include<stdio.h>
void main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==2)
continue;
printf(“%d”,i);
}
}
Output: 1 3 4 5
goto statement
 The goto statement is a ‘jump’ statement that transfers the control to the
specified statement (Label) in a program unconditionally.
 The specified statement is identified by ‘label’( symbolic name ). Label can
be any valid variable name that is followed by a colon (:)
Syntax
goto label; label:
………… Statements
…………. …………
label: …………
Statements goto label;
Forward Jump Backward Jump
Write a C program to calculate the sum of all numbers entered by the user.
#include<stdio.h>
void main()
{
int n,i,sum=0;
printf(“Enter the number:\n”);
scanf(“%d”,&n);
sum=i=0;
top: sum=sum+n;
i=i+1;
if(i<=n)
goto top;
printf(“Sum of Series=%d”,sum);
}

Course Outcomes:

● CO 1 Elucidate the basic architecture and functionalities of a computer and also recognize the
hardware parts.
● CO 2 Apply programming constructs of C language to solve the real-world problem
● CO 3 Explore user-defined data structures like arrays in implementing solutions to problems like
searching and sorting
● CO 4 Explore user-defined data structures like structures, unions and pointers in implementing
solutions
● CO 5 Design and Develop Solutions to problems using modular programming constructs using
functions
Department of Computer Science and Engineering

Module 3
1. Discuss the implementation of user defined function with suitable example.

Sol A user-defined function is a type of function in C language that is defined by the user
himself to perform some specific task. 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:
a. Function Prototype
b. Function Definition
c. Function Call

#include <stdio.h>

void swap(int a, int b) //Function Definition


{
int temp = a;
a = b;
b = temp;
}

// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap are: %d, %d\n", x,
y);
swap(x, y); //function call
printf("Values of x and y after swap are: %d, %d", x,
y);
return 0;
}

Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 10, 20
2. Explain the syntax of Function Declaration and Function Definition And Function
call with example.
Sol:
a. C Function Prototype/ 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.
Syntax
return_type function_name (type1 arg1, type2 arg2, ... typeN argN);
b. C 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);

// C Program to illustrate the use of user-defined function


#include <stdio.h>

// Function prototype
int sum(int, int);

// Function definition
int sum(int x, int y)
{
int sum;
sum = x + y;
return x + y;
}

// Driver code
int main()
{
int x = 10, y = 11;

// Function call
int result = sum(x, y);
printf("Sum of %d and %d = %d ", x, y, result);

return 0;
}
3. Explain the different parameter passing techniques with example (OR) Differentiate
between call by value and call by reference. Using suitable example
Sol:
We can pass parameters to a function in C using two methods:
A. Call by Value
B. Call by Reference
A. Call by value
In call by value, a copy of the value is passed to the function and changes that are made to the
function are not reflected back to the values. Actual and formal arguments are created in
different memory locations.

Example

// C program to show use of


// call by value
#include <stdio.h>

void swap(int a, int b)


{
int temp = a;
a = b;
b = temp;
}

// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap are: %d, %d\n", x,
y);
swap(x, y);
printf("Values of x and y after swap are: %d, %d", x,
y);
return 0;
}

Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 10, 20
Note: Values aren’t changed in the call by value since they aren’t passed by reference.

B. Call by Reference
In a call by Reference, the address of the argument is passed to the function, and changes that
are made to the function are reflected back to the values. We use the pointers of the required
type to receive the address in the function.
Example

// C program to implement
// Call by Reference
#include <stdio.h>

void swap(int* a, int* b)


{
int temp = *a;
*a = *b;
*b = temp;
}

// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap are: %d, %d\n", x,
y);
swap(&x, &y);
printf("Values of x and y after swap are: %d, %d", x,
y);
return 0;
}

Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 20, 10

4. Describe different types of storage classes in C with example.

Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they
are defined.
The scope of the automatic variables is limited to the block in which they
are defined.

o The automatic variables are initialized to garbage by default.


o The memory assigned to automatic variables gets freed upon exiting from
the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.

Static
o The variables defined as static specifier can hold their value between the
multiple function calls.
o Static local variables are visible only to the function or the block in which
they are defined.
o A same static variable can be declared many times but can be assigned at
only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.
o The keyword used to define static variable is static.

Register
o The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator
for the register variable.
o The access time of the register variables is faster than the automatic
variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the
CPU register. However, it is compiler?s choice whether or not; the variables
can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address
of a variable.
o Static variables can not be stored into the register since we can not use more
than one storage specifier for the same variable.

External
o The external storage class is used to tell the compiler that the variable
defined as extern is declared with an external linkage elsewhere in the
program.
o The variables declared as extern are not allocated any memory. It is only
declaration and intended to specify that the variable is declared elsewhere
in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize
the external variable within any block or method.
o An external variable can be declared many times but can be initialized at
only once.
o If a variable is declared as external then the compiler searches for that
variable to be initialized somewhere in the program which may be extern or
static. If it is not, then the compiler will show an error.

5. Explain the working of recursion with suitable example.


Sol: Recursion in C programming allows a function to call itself to solve an issue.

#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
n = 12;
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}
6. Explain the declaration and initialization of one dimensional and two dimensional
arrays with an example.
Sol: An array is a collection of one or more values of the same data type stored in contiguous
memory locations. The data type can be user-defined or even any other primitive data-type.

One Dimensional Array in C

We can visualize a one-dimensional array in C as a single row to store the


elements. All the elements are stored at contiguous memory locations. Array
Declaration

While declaring a one-dimensional array in C, the data type can be of any type, and also, we
can give any name to the array, just like naming a random variable.
Syntax:
int arr[5]; //arr is the array name of type integer, and 5 is the size of the array

Array Initialization
In static uninitialized arrays, all the elements initially contain garbage values, but we can
explicitly initialize them at their declaration.
Syntax:
<data_type> <arr_name> [arr_size]={value1, value2, value3,…};

Here, parameterized values are constant values separated by a comma.


We can skip the writing size of the array within square brackets if we initialize array elements
explicitly within the list at the time of declaration. In that case, it will pick elements list size
as array size.

Array Accessing
In one-dimensional arrays in C, elements are accessed by specifying the array name and the
index value within the square brackets. Array indexing starts from 0 and ends with size- If
we try to access array elements out of the range, the compiler will not show any error
message; rather, it will return some garbage value.

Syntax:

<arr_name>[index];
//program
#include < stdio.h >

int main() {
//declaring and initializing one-dimensional array in C
int arr[3] = {10, 20, 30};

// After declaration, we can also initialize the array as:


// arr[0] = 10; arr[1] = 20; arr[2] = 30;

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


// accessing elements of array
printf(" Value of arr[%d]: %d\n", i, arr[i]);
}
}

Two dimensional arrays


An array consisting of two subscripts is known as two-dimensional array. These are often
known as array of the array. In two dimensional arrays the array is divided into rows and
columns. These are well suited to handle a table of data. In 2-D array we can declare an array
as:
Declaration:-
Syntax: data_type array_name[row_size][column_size];
Ex:- int arr[3][3];
where first index value shows the number of the rows and second index value shows the
number of the columns in the array.
Initializing two-dimensional arrays:
Like the one-dimensional arrays, two-dimensional arrays may be initialized by following
their declaration with a list of initial values enclosed in braces.
Ex: int a[2][3]={0,0,0,1,1,1};
//program
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
7. Write a C program to implement to Bubble sort technique
#include<stdio.h>
void main()
{
int a[10], n, i, j, temp;
printf("Enter the number of elements\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(j=1; j<n;j++)
{
for(i=0;i<n;i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf("The sorted array is\t");
for(i=0; i<n;i++)
printf(“%d\t”,a[i]);
}
Output
Enter the number of elements 7
Enter the array elements 12 23 10 13 15 1 8
The sorted array is 1 8 10 12 13 15 23
8. Write a C program with algorithm to perform addition of 2-dimensional
Matrix
#include <stdio.h>
int main() {
int m, n, i, j;
printf("Enter the number of rows and columns of the matrices: ");
scanf("%d%d", &m, &n);
int a[m][n], b[m][n], c[m][n];
printf("Enter the elements of matrix A: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of matrix B: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &b[i][j]);
}
}
// add the matrices
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
// print the result
printf("The sum of the two matrices is: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}
Output

Enter the number of rows and columns of the matrices: 2 2


Enter the elements of matrix A:
12
34
Enter the elements of matrix B:
56
78
The sum of the two matrices is:
68
10 12
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Question Bank AY 2024-25
Subject Code: BPOPS103 Subject: Principles of Programming Using C
Semester: 1 Module: 4 Branch: CSE

Module – 4
Mo
Q# CO# BTL Questions Marks
d#
Define String. Explain any 4 string manipulation function with
1. 4 4 2 suitable example. 8M
Answer
A string is a null-terminated character array. This means that after the last
character, a null character („\0‟) is stored to signify the end of the
character array.

● The general form of declaring a string is char str[size];


● For example if we write,
char str[] = “HELLO”;
We are declaring a character array with 5 characters namely, H, E, L, L
and O. Besides, a null character („\0‟) is stored at the end of the string.
So, the internal representation of the string becomes- HELLO‟\0‟. Note
that to store a string of length 5, we need 5 + 1 locations (1 extra for the
null character).
The name of the character array (or the string) is a pointer to the
beginning of the string.
C supports a large number of string handling functions.
• There are numerous functions defined in <string.h> header file.

Strcat Function
Syntax:
char *strcat(char * str1, char *str2);
The strcat function appends the string pointed by str2 to the end of the
string pointed to by str1.
The terminating null character of str1 is overwritten. The process stops
when the terminating null character of str2 is copied.

Strcpy Function
Syntax:
char *strncat(char * str1, char *str2);
This function copies the string pointed to by str2 to str1 including the null
character of str2. It returns the argument str1. Here str1 should be big
enough to store the content of str2.

Strlen Function
Syntax:
Size_t strlen(const char * str);
This function calculates the length of the string str up to but not including
the null character, i.e., the function returns the number of characters in the
string.
Strcmp function
Syntax:
int strcmp(const char * str1, const char *str2);
The strcmp function compares the string pointed to by str1 to the string
pointed to by str2. The function returns zero if the strings are equal.
Otherwise, it returns a value less than zero or greater than zero if str1 is
less than or greater than str2 respectively.
Develop a C program to compare 2 strings without using built-in 6M
2. 4 4 3 function.
Answer
int main()
{
char s[20] = “college”;
char d[20] = “terna”;
int I = 0;
while(s[i] != ‘\0’ || d[i] != ‘\0’)
{
if(d[i] == s[i])
{
cmp = 0;
i++;
}
else
{
cmp = 1;
break;
}}
f(cmp == 0)
printf(“Strings are equal);
else
printf(“Strings are different”);
return 0;
}
Write functions to implement string operations such as find string
3. 4 4 3 6M
length. Use the parameter passing techniques. (Without String
Length Function)
#include <stdio.h>
int len_str(char s[50]);
int comp_str(char s1[50], char s2[50]) ; void concat_str(char s1[50],char
s2[50]);
void main()
{
char s1[50],s2[50],len,c; printf("enter the 1st string\n"); scanf("%s",s1);
printf("enter the 2nd string\n");

scanf("%s",s2); len=len_str(s1);
printf("length of the string1 = %d\n",len); len=len_str(s2);
printf("length of the string2 = %d\n",len); c=comp_str(s1,s2);
if(c==0)
{
printf("strings are equal\n");
}
else
{
printf("strings are not equal\n");
}
concat_str(s1,s2);
}

int len_str(char s[50])


{
int len = 0, i;
for (i = 0; s[i] != '\0'; i++)
{
len++;
}
return len;
}

int comp_str(char s1[50], char s2[50])


{
int len1, len2, i; len1 = len_str(s1); len2 = len_str(s2); if (len1 != len2)
return 1;
for (i = 0; i< len1; i++)
{
if (s1[i] !=s2[i]) return 1;
}
return 0;
}
void concat_str(char s1[50],char s2[50])
{
int i=0,j; j=len_str(s1); while(s2[i]!='\0')
{
s1[j]=s2[i]; j++;
i++;
}
s1[j]='\0';
printf("Concatenation of string1 and string2 %s \n",s1);
}
Explain the difference between gets() and scanf() functions.
5. 4M
4 4 2 Answer
●The string can be read using scanf() by writing
scanf(“%s”, str);
●Although the syntax of scanf() function is well known and easy to use,
the main pitfall with this function is that the function terminates as soon
as it finds a blank space.
For example, if the user enters Hello World, then str will contain only
Hello.
● The string can be read by writing gets(str);
gets() takes the starting address of the string which will hold the input.
The string inputted using gets() is automatically terminated with a null
character.
● The string can also be read by calling the getchar() repeatedly to read a
sequence of single characters (unless a terminating character is entered)
and simultaneously storing it in a character array.
6. 6M
4 4 2 Explain the difference between puts() and printf() functions.
Answer

In C, both puts() and printf() functions are used for printing a string on the
console and are defined in <stdio.h> header file.

puts() Function
The puts() function is used to write a string to the console and it
automatically adds a new line character ‘\n’ at the end.
Syntax
puts("str");
Parameters
• str: It takes a null-terminated string as the argument.
Return Value
• It returns a non-negative value if the output is successful, or
End-of-File if an error occurs.
Printf() Function
The printf() function is also used to print data on the console, but it can
also be used to print the formatted data to the console based on a
specified format string.
Syntax
printf(“format_string”, Arguments);
Parameters
• format_string: It can be a simple string or a string containing
format specifiers.
• Arguments: It is the variable names whose value is to be
printed.
Return Value
• It returns the number of characters successfully written to the
console and a negative value if an error occurs.
Develop a C program to find the largest of three numbers using
7. 4 4 3 6M
pointer.
Answer
#include<stdio.h>
int main()
{
int a,b,c,*pa, *pb, *pc;
printf(“Enter three numbers:\n”);
scanf(“%d%d%d”, &a,&b,&c);
/* Referencing */
pa= &a;
pb= &b;
pc= &c;
if(*pa > *pb && *pa > *pc)
{
printf(“Largest is: %d”, *pa);
}
else if(*pb > *pc && *pb > *pc)
{
printf(“Largest is : %d”, *pb);
}
else
{
printf(“Largest = %d”, *pc);
}
return 0;
}
Define Pointer. Explain pointer variable declaration and initialization
8. 4 4 2 with suitable example. 8M
Answer
Actually pointers are nothing but memory addresses.
● A pointer is a variable that contains the memory location of another
variable.
Another definition of pointer is: “Pointer is a variable which holds the
address of another
variable of same type.”
● The general syntax of declaring pointer variable is
data_type *ptr_name;
Here, data_type is the data type of the value that the pointer will point to.
For example:
int *pnum; char *pch; float *pfnum;
int x= 10;
int *ptr = &x;
The ‘*’ informs the compiler that ptr is a pointer variable and the int
specifies that it will
store the address of an integer variable.
The & operator retrieves the lvalue (address) of x, and copies that to the
contents of the
pointer ptr.
● We can “dereference” a pointer, i.e. refer to the value of the variable to
which it points
by using unary ‘*’ operator as in *ptr. That is, *ptr = 10, since 10 is value
of x.
#include<stdio.h>
int main()
{
int num, *pnum;
pnum = &num;
printf(“\n Enter the number : “);
scanf(“%d”, &num);
printf(“\n The number that was entered is : %d”, *pnum);
return 0;
}
OUTPUT:
Enter the number : 10
The number that was entered is : 10
4 Explain the difference between a null pointer and a void pointer.
9. 4 2 6M
Following table clearly compare Null pointer against void pointer.

Null Pointer Void Pointer

Null pointer is specially reserved Null pointer is specially reserved


value of value of
Null pointer suits well for all data Null pointer suits well for all data
types. Void itself a data type of types. Void itself a data type of
size 1. size 1.
Int, char, float, long, double are int, char, float, long, double are
all data all data
types are supported. Types are supported.

Mention the application of pointer


10. 4 4 2 6M
Answer
Following are the usage of pointers in C:
• For accessing the elements of an array.
Array elements can be accessed through the pointer. You need to
declare and initialize a pointer to an array and using it you can access
each element by incrementing the pointer variable by 1.
The pointer to an array is the address of its 0th element. When the
array pointer is incremented by 1, it points to the next element in
the array.
#include <stdio.h>
int main()
{
int arr[] = {1,2,3,4,5};
int *ptr = arr;
for(int i = 0; i <= 4; i++){
printf("arr[%d]: %d\n", i, *ptr);
ptr++;
}
return 0;
}
• For passing the argument by using references.
When a function is called by reference, the address of the actual
argument variables passed, instead of their values.
The following function receives the reference of two variables
whose values are to be swapped.
/* function definition to swap the values */

int swap(int *x, int *y){


int z;
z = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = z; /* put z into y */

return 0;
}
• For dynamic memory allocation by using malloc() and calloc()
functions .
One of the most important applications of C pointers is to declare
memory for the variables dynamically.
1. The malloc() Function
This function is defined in the "stdlib.h" header file. It allocates a
block memory of the required size and returns a void pointer.
void *malloc (size)
2. The calloc() Function
The C library function "calloc" (stands for contiguous allocation)
allocates the requested memory and returns a pointer to it.
void *calloc(n, size);
Where "n" is the number of elements to be allocated and "size" is
the byte size of each element.
3. The realloc() Function
The realloc() function in C is used to dynamically change the
memory allocation of a previously allocated memory. You can
increase or decrease the size of an allocated memory block by
calling the realloc() function.
void *realloc(*ptr, size);
The first parameter "ptr" is the pointer to a memory block
previously allocated with malloc, calloc or realloc to be
reallocated.
• For returning multiple values.
In C language, the functions can have only one return statement to
return one value at a time. With the help of C pointers, you can
return multiple values from a function by passing arguments as
references.
void funAddSub(int a, int b, int* add, int* sub)
{
*add = a + b;
*sub = a - b;
}
int main() {
int num1 = 10;
int num2 = 3;
// Variables to store results
int res1, res2;
// Calling function to get add and sub
// by passing the address of res1 and res2
funAddSub(num1, num2, &res1, &res2);
// Printing the result
printf("Addition is %d and subtraction is %d", res1, res2);
return 0;
}
Develop a C program to compute the sum, mean and standard
11. 4 4 3 deviation of all element of an array using pointer 8M
Answer
Here's a C program that uses pointers to compute the sum, mean, and
standard deviation of an array of N real numbers:
#include<math.h>
void main()
{
float a[10],*ptr,mean,std,sum=0,sumstd=0;
int n,i;
printf("Enter the no of elements n =");
scanf("%d",&n);
printf(" Enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+ *ptr;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;i<n;i++)
{
sumstd=sumstd+ pow((*ptr-mean),2);
ptr++;
}
std=sqrt(sumstd/n);
printf("Sum=%.3f\t",sum);
printf("Mean=%.3f\t",mean);
printf("Standard Deviation=%.3f\n",std);
}
Course Outcomes:

• CO 1 Elucidate the basic architecture and functionalities of a computer and also recognize the
hardware parts.
• CO 2 Apply programming constructs of C language to solve the real-world problem
• CO 3 Explore user-defined data structures like arrays in implementing solutions to problems like
searching and sorting
• CO 4 Explore user-defined data structures like structures, unions and pointers in implementing
solutions
• CO 5 Design and Develop Solutions to problems using modular programming constructs using
functions
Department of Computer Science and Engineering

Module 5

1. What is Structure? Explain the declaration of a structure with an example


Sol : Structure is basically a user-defined data type that can store related information together.
• The major difference between structure and an array is that, an array contains related information of
the same data type.

Structure declaration:
A structure is declared using the keyword struct followed by a structure name .all the variable of the
structure is declared within the structure.

Syntax:
Struct structure name
{
Data type var-name;
Data type var-name;
……..
};
Example:1
Struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
Now ,structure has become user defined data type each var-name declared within a structure is called
a member of the structure.

Example:2
Struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}stud1,stud2;
In declaration ,we declare two variable stud1 and stud2 of the structure student. So,if you want to
declare more than one variable of the structure, then separate the variable using comma.

2. Develop a C program to read and display the information of all the students
in the class.
Sol:
#include <stdio.h>
// Structure to store student information
struct Student {
int roll_number;
char name[20];
float marks;
};
int main()
{
int n;
// Ask the user for the number of students
printf("Enter the number of students: ");
scanf("%d", &n);
// Array to store student information
struct Student students[n];
// Input student details
for (int i = 0; i < n; i++)
{
printf("\nEnter details for student %d:\n", i + 1);

printf("Roll number: ");


scanf("%d", &students[i].roll_number);
printf("Name: ");
scanf(" %s", students[i].name);
printf("Marks: ");
scanf("%f", &students[i].marks);
}
// Display student details
printf("\nStudent Information:\n");
printf("Roll No\t Name\t Marks\n");
for (int i = 0; i < n; i++)
{
printf("%d %s %f\n", students[i].roll_number, students[i].name, students[i].marks);
}
return 0;
}
3. Differentiate between structure and union.
Sol:
4. Implement structures to read, write and compute average- marks of the students, list the
students scoring above and below the average marks for a class of n students.
Sol:
/* Program to Maintain Student information */
#include<stdio.h>
#include<string.h>
struct student
{
int roll_num, marks;
char name[20];
};
void main()
{
int i, n;
struct student s[10];
int total = 0;
float avg =0.0;
printf("Enter the students n = ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf(" Enter the %d student details\n",i+1);
printf(" Enter the roll number:");
scanf("%d",&s[i].roll_num);
printf(" Enter the student name without spaces:");
scanf("%s",s[i].name);
printf(" Enter the marks:");
scanf("%d",&s[i].marks);
}
printf("\n The student details are \n");
printf(" Roll Num\tName\t\tMarks\n");
for(i=0;i<n;i++)
{
printf("\t%d\t%s\t\t%d\n",s[i].roll_num,s[i].name,s[i].marks);
}
for(i=0;i<n; i++)
{
total = total + s[i].marks;
}
avg = total/n;
printf("Average marks of the class is = %f\n",avg);
printf("\n List of students who have above the average marks\n");
printf(" Roll Num\tName\t\tMarks\n");
for(i=0;i<n;i++)
{
if(s[i].marks >= avg)
{
printf("\t%d\t%s\t\t%d\n",s[i].roll_num,s[i].name,s[i].marks);
}
}
printf("\n List of students who have below the average marks\n");
printf(" Roll Num\tName\t\tMarks\n");
for(i=0;i<n;i++)
{
if(s[i].marks < avg)
{
printf("\t%d\t%s\t\t%d\n",s[i].roll_num,s[i].name,s[i].marks);
}
}
}

5. Explain various modes of operations in which file can be opened for processing.
Sol:
• A file must be first 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 *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.
Below table shows the different modes of file.

6. Write a note on Enumerated data types.


Sol:
Enumerated data types:
• The enumerated data type is a user defined type based on the standard integer type.
• An enumeration consist of a set of named integer constants.
• In an enumerated type each integer value is assigned an identifier.
• To define enumerated data type we use the keyword enum, which is the abbreviation for enumerate.
• Enumerations create new data types to contain values that are not limited to the values that the
fundamental data types may take.
Syntax:
enum enumeration name{identifier1,identifier2,…..identifier 3};
The enum keyword is basically used to declare and initialize a sequence of integer constants.

Example: which creates a new type of variable called COLOURS to store colour constants
enum COLOURS {RED, BLUE, BLACK, GREEN, YELLOW, PURPPLE, WHITE};
COLOUR is the name given to the set of constants. In case you do not assign any value to a constant.
the default value for the first one in the list –RED has the value of 0.The rest of the undefined constants
have a value 1 more than its previous one.
RED=0, BLUE=1,BLACK=2,GREEN=3,YELLOW=4,PURPLE=5,WHITE=6

If you want to explicitly assign values to these integer constants then you should specifically mention
those values as:
enum COLOUR{RED=2,BLUE,BLACK=5,GREEN=7,YELLOW,PURPLE,WHITE=15};
as a result of this statement
RED=2,BLUE=3,BLACK=5,GREEN=7,YELLOW=8,PURPLE=9,WHITE=15.

Example:
#include<stdio.h>
main()
{
enum{RED=2,BLUE,BLACK=5,GREEN=7,YELLOW,PURPLE,WHITE=15};
Printf(“\n RED=%d”,RED);
Printf(“\n BLUE=%d”,BLUE);
Printf(“\n BLACK=%d”,BLACK);
return 0;
}

7. How to dectect end of the file


Sol: Detecting the END-OF_FILE:
When reading or writing data from files,we often do not know exactly how long the file is for
example,while reading the file,we usually start reading from the beginning and proceed towards the
end of the file.
In C there are two ways to detect EOF:
• While reading the file in text mode, character by character the programmer can compare the
character that has been read with the EOF which is a symbolic constant defined in stdio.h with a
value -1 .
while(1)
{
C=fgetc(fp);
if(c==EOF)
break;
printf(“%c”,c);
}
• The other way is to use the standard library function feof ()which is defined in stdio.h. It is used to
distinguish between two cases:
• When a stream operation has reached the end of a file .
• When the EOF error code has returned an error indicator even when the end of the file has
not been reached.
Syntax:
int feof(FILE*fp);

You might also like