0% found this document useful (0 votes)
52 views72 pages

22pop13 Laboratory Manual

The document contains information about a laboratory manual for the Principles of Programming Laboratory course, including the program outcomes, vision and mission statements of the institution and department, program educational objectives, program specific outcomes, course learning objectives, and course outcomes. It also includes an index of programs to be covered in the course with the corresponding course outcome, program outcomes, and level of cognitive process based on Bloom's taxonomy.

Uploaded by

pooja pp
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)
52 views72 pages

22pop13 Laboratory Manual

The document contains information about a laboratory manual for the Principles of Programming Laboratory course, including the program outcomes, vision and mission statements of the institution and department, program educational objectives, program specific outcomes, course learning objectives, and course outcomes. It also includes an index of programs to be covered in the course with the corresponding course outcome, program outcomes, and level of cognitive process based on Bloom's taxonomy.

Uploaded by

pooja pp
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/ 72

Department of Computer Science and Engineering

Jnanaprabha, Virgo Nagar Post, Bengaluru-560049

Academic Year: 2022-23

LABORATORY MANUAL
SEMESTER : I & II

SUBJECT : PRINCIPELS OF PROGRAMMING LABORATORY

SUBCODE : 22POP13/23

NAME :

USN :

SECTION:

Page | 1
PROGRAM OUTCOMES

PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.

PO2: Problem analysis: Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

PO3: Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO4: Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with
an understanding of the limitations.

PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.

PO7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9: Individual and Team Work: Function effectively as an individual and as a member or leader
in diverse teams, and in multi – disciplinary settings.

PO10: Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the
Engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO12: Life-long learning: Recognize the need for and have the preparation and ability to engage
in independent and life -long learning in the broadest context of technological change.
Page | 2
Department of Computer Science and Engineering

INSTITUTE VISION AND MISSION

VISION

The East Point College of Engineering and Technology aspires to be a globally acclaimed
institution, recognized for excellence in engineering education, applied research and
nurturing students for holistic development.

MISSION

M1: To create engineering graduates through quality education and to nurture


innovation, creativity and excellence in teaching, learning and research

M2: To serve the technical, scientific, economic and societal developmental needs of our
communities

M3: To induce integrity, teamwork, critical thinking, personality development and ethics
in students and to lay the foundation for lifelong learning

Page | 3
Department of Computer Science and Engineering

DEPARTMENT VISION AND MISSION

VISION
The department aspires to be a Centre of excellence in Computer Science & Engineering to
develop competent professionals through holistic development.

MISSION

M1: To create successful Computer Science Engineering graduates through effective


pedagogies, the latest tools and technologies, and excellence in teaching and learning.

M2: To augment experiential learning skills to serve technical, scientific, economic, and social
developmental needs.

M3: To instil integrity, critical thinking, personality development, and ethics in students for a
successful career in Industries, Research, and Entrepreneurship.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


PEO 1: To produce graduates who can perform technical roles to contribute effectively in
software industries and R&D Centre

PEO 2: To produce graduates having the ability to adapt and contribute in key domains of
computer science and engineering to develop competent solutions.

PEO 3: To produce graduates who can provide socially and ethically responsible solutions
while adapting to new trends in the domain to carve a successful career in the industry

Page | 4
PROGRAM SPECIFIC OUTCOMES (PSOs)
PSO1: To conceptualize, model, design, simulate, analyse, develop, test, and validate
computing systems and solve technical problems arising in the field of computer science &
engineering.
PSO2: To specialize in the sub-areas of computer science & engineering systems such as
cloud computing, Robotic Process Automation, cyber security, big data analytics, user interface
design, and IOT to meet industry requirements.
PSO3: To build innovative solutions to meet the demands of the industry using appropriate
tools and techniques.

COURSE LEARNING OBJECTIVES


CLO 1: Elucidate the basic architecture and functionalities of a Computer

CLO 2: Apply programming constructs of C language to solve the real-world problems

CLO 3: Explore user-defined data structures like arrays, structures and pointers in
implementing solutions to problems

CLO 4. Design and Develop Solutions to problems using structured programming


constructs such as functions and procedures

COURSE OUTCOMES
At the end of the course the student will be able to:

CO1: Elucidate the basic architecture and functionalities of a computer and also recognize

the hardware parts

CO2: Apply programming constructs of C language to solve the real world problem

CO3: Explore user-defined data structures like arrays in implementing solutions to

problems like searching and sorting

CO4: Explore user-defined data structures like structures, unions and pointers in

implementing solutions

CO5: Design and Develop Solutions to problems using modular programming constructs using
functions

Page | 5
Note: SEE marks for the practical course is 50 Marks.

Page | 6
Page | 7
Index
Sl. Page
Program List CO PO RBT
No. No
PART A
PO1,
PO2,
1 Simulation of a Simple Calculator PO3,
CO2 L3 7
PO5,
PO12
PO1,
Compute the roots of a quadratic equation by accepting the PO2,
2 coefficients. Print appropriate messages. CO2 PO3, L3 11
PO5,
PO12

An electricity board charges the following rates for the use


of electricity: for the first 200 units 80 paise per unit:
for the next 100 units 90 paise per unit: beyond 300 units PO1,
PO2,
Rs 1 per unit. All users are charged a minimum of Rs.
3 CO2 PO3, L3 15
100 as meter charge. If the total amount is more than Rs PO5,
400, then an additional surcharge of 15% of total amount PO12

is charged. Write a program to read the name of the user,


number of units consumed and print out the charges.

Write a C Program to display the following by reading the


number of rows as input,
1 PO1,
PO2,
121
4 CO2 PO3, L3 19
12321 PO5,
1234321 PO12

---------------------------
nth row
PO1,
PO2,
5 Implement Binary Search on Integers. CO3 PO3, L3 21
PO5,
PO12

PO1,
PO2,
Implement Matrix multiplication and validate the rules of
6 multiplication. CO3 PO3, L3 25
PO5,
PO12
Compute sin(x)/cos(x) using Taylor series approximation. PO1,
Compare your result with the built-in library function. PO2,
7 CO3 L2 30
PO5,
Print both the results with appropriate inferences. PO12
PO1,
Sort the given set of N numbers using Bubble sort. PO2,
8 CO3
L2 34
PO5,
PO12
PO1,
Write functions to implement string operations such as
PO2,
9 compare, concatenate, and find string length. Use the CO4 L2 37
parameter passing techniques. PO5,
PO12
Implement structures to read, write and compute
PO1,
average- marks of the students, list the students scoring
PO2,
10 above CO4 L2 45
PO5,
and below the average marks for a class of N students. PO12

PO1,
Develop a program using pointers to compute the sum,
PO2,
11 mean and standard deviation of all elements stored in CO4 PO5, L2 52
an array of N real numbers. PO1
2
PO1,
Write a C program to copy a text file to another, read both PO2,
12 CO5 L2 56
the input file name and target file name. PO5,
PO12
Course Articulation Matrix
COs POs
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 3 2 3 1 - - - - 1 - - 1
CO2 3 2 3 1 - - - - 1 - - 1
CO3 3 2 3 1 1 - - - 1 - - 1
CO4 3 2 3 1 1 - - - 1 - - 1
CO5 3 2 3 1 - - - - 1 - - 1
3 - High Correlation 2 - Medium Correlation 1 – Low Correlation
Principles of Programming Laboratory 22POP13/23

INTRODUCTION

Familiarization with computer hardware and programming environment, concept of


naming the program files, storing, compilation, execution and debugging. Taking any simple
C- code. Computer is an advanced electronic device that takes raw data as an input from the
user and processes it under the control of a set of instructions (called program), produces a
result (output), and saves it for future use.

DEPT.CSE.EPCET 1
Principles of Programming Laboratory 22POP13/23

Input Unit
This unit contains devices with the help of which we enter data into the computer. This
unit creates a link between the user and the computer. The input devices translate the
informationinto a form understandable by the computer.

CPU (Central Processing Unit)


CPU is considered as the brain of the computer. CPU performs all types of data
processingoperations. It stores data, intermediate results, and instructions (program). It
controls the operation of all parts of the computer.
CPU itself has the following three components −

 ALU (Arithmetic Logic Unit)


 Memory Unit

DEPT.CSE.EPCET 2
Principles of Programming Laboratory 22POP13/23

 Control Unit
 Memory or Storage Unit

This unit can store instructions, data, and intermediate results. This unit supplies information
to other units of the computer when needed. It is also known as internal storage unit or the
main memory or the primary storage or Random Access Memory (RAM).
Its size affects speed, power, and capability. Primary memory and secondary memory are
twotypes of memories in
the computer. Functions of the
memoryunit are −
o It stores all the data and the instructions required for processing.
o It stores intermediate results of processing.
o It stores the final results of processing before these results are released to an
outputdevice.
o All inputs and outputs are transmitted through the main memory.

Control Unit
This unit controls the operations of all parts of the computer but does not carry out
anyactual data processing operations.
Functions of this unit are −
o It is responsible for controlling the transfer of data and instructions among other
units ofa computer.
o It manages and coordinates all the units of the computer.
o It obtains the instructions from the memory, interprets them, and directs the
operation ofthe computer.
o It communicates with Input/Output devices for transfer of data or results from storage.
o It does not process or store data.

ALU (Arithmetic Logic Unit)


This unit consists of two subsections namely,
- Arithmetic Section
- Logic Section
 Arithmetic Section
Function of arithmetic section is to perform arithmetic operations like addition,
subtraction, multiplication, and division. All complex operations are done by making
repetitive use of the above operations.

 Logic Section
Function of logic section is to perform logic operations such as comparing, selecting,
matching, and merging of data.

DEPT.CSE.EPCET 3
Principles of Programming Laboratory 22POP13/23

Output Unit
The output unit consists of devices with the help of which we get the information from the
computer. This unit is a link between the computer and the users. Output devices translate the
computer's output into a form understandable by the users.
Following are some of the important input devices which are used
ina computer −
Keybo
ard
Mouse
Joy
Stick
Light
pen
Track
Ball
Scann
er
Graphic
Tablet
Microphon
e
Magnetic Ink Card
Reader(MICR)Optical
Character Reader(OCR) Bar
Code Reader
Optical Mark Reader(OMR)
Following are some of the important output devices used in a
computerMonitors
Graphic
Plotter
Printer
Programming Environment
If we want to set up environment for C programming language, we need the
followingtwo software tools available on computer, (a) Text Editor and (b) The C
Compiler.
An integrated development environment (IDE) is a software application that
providescomprehensive facilities to computer programmers for software
development. An IDE normally consists of a source code editor, build automation
tools, and a debugger. Most modern IDEs have intelligent code completion. Some
IDEs, such as NetBeans and Eclipse, contain a compiler, interpreter, or both;
Naming the program files : A filename is a name used to uniquely identify a computer file
stored in a file system. The filename can consist of letters, digits and special characters. The
files that we create with editor are called the source files and they contain the program source
codes. The source files for C programs are typically named with the extension ".c".
Syntax: filename.ext ic, Eg: hello.c

DEPT.CSE.EPCET 4
Principles of Programming Laboratory 22POP13/23

The Translation is done after examine each instruction for correctness. When there are no
errors, the translated program is stored on another file with the name filename.o. This program
is the object code. Eg- hello.o.
Execution is the process of loading the executable object code into computer memory
andexecute the instructions.
$ ./a.out

Debugging is a systematic process of spotting and fixing the number of bugs, or defects,
in apiece of software so that the software is behaving as expected.
Let us look at a simple code that would print the words "Hello World" −
#include<stdio
.h>int main() {
/* my first program
in C */
printf("Hello,
World! \n"); return
0;
}
Let us take a look at the various parts of the above program −
The first line of the program #include <stdio.h> is a preprocessor command, which tells
a Ccompiler to include stdio.h file before going to actual compilation.
The next line int main() is the main function where the program execution begins.

The next line /*...*/ will be ignored by the compiler and it has been put to add additional
commentsin the program. So such lines are called comments in the program.
The next line printf(...) is another function available in C which causes the message "Hello,
World!"to be displayed on the screen.

The next line return 0; terminates the main() function and returns the value 0.
Compile and Execute C Program :Let us see how to save the source code in a file, and how to
compileand run it.
Open a text editor and add the above-mentioned
code.Save the file as hello.c
Open a command prompt and go to the directory where you have saved the
file.Type gcc hello.c and press enter to compile your code
If there are no errors in your code, the command prompt will take you to the next line
andwould generate a.out executable file.
Now, type a.out to execute your program.
You will see the output "Hello World" printed on the screen.

$ gcc hello.c
$ ./a.out
Hello, World!

DEPT.CSE.EPCET 5
Principles of Programming Laboratory 22POP13/23

DEPT.CSE.EPCET 6
Principles of Programming Laboratory 22POP13/23

1. Simulation of Simple Calculator.


(Develop a program to solve simple computational problems using arithmetic expressions and
useof eachoperator leading to simulation of a commercial calculator. (No built-in math
function))

Algorithm:
Step1: [Initialize]
start
Step2: [Input a simple arithmetic expression]
Read a,op,c
Step3: [Check for arithmetic operators using switch case with operator op]
switch(op)
case '+': res=a+b; goto
step 4 case '-' : res=a-b;
goto step 4 case '*':
res=a*b; goto step 4case
'/':
if(b
!=0)
res=a/b
;
else

printf("division by zero is not


possible");goto step 5
end if
goto step 4
case '%': res=a%b; goto step
4 default: printf("illegal
operator");
goto step 5
Step4:[Print the result res] Print
a,op,b,resStep 5: [Finished] Stop

DEPT.CSE.EPCET 7
Principles of Programming Laboratory 22POP13/23

Flowchart:

DEPT.CSE.EPCET 8
Principles of Programming Laboratory 22POP13/23

Program:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a, b, res; char op;
printf("Enter a simple arithmetic expression:\n");
scanf("%d%c%d",&a,&op,&b);
switch(op)
{
case '+':res=a+b;
break;
case '-':res=a-b;
break;
case '*':res=a*b;
break;
case '/':if(b!=0)
res=a/b;
else
{
printf("division by zero is not possible\n");
exit(0);
}
break;
case '%':res=a%b
; break;
default:printf("Illigal operator\n");

DEPT.CSE.EPCET 9
Principles of Programming Laboratory 22POP13/23

exit(0);
}
printf("\nResult=%d”,res);

return 0;

TEST CASE:

Test Cases: Test No Input Parameters Expected Output Obtained Output


1 5+3 5+3=8 5+3=8
2 5-3 5-3=2 5-3=2
3 5*3 5*3=15 5*3=15
4 5/3 5/3=1 5/3=1
5 5%3 5%3=2 5%3=2
6 5/0 division by zero is not division by zero is not
possible possible
7 5_3 illegal operator illegal operator

DEPT.CSE.EPCET 10
Principles of Programming Laboratory 22POP13/23

2. Compute the roots of a quadratic equation by accepting the coefficients. Print


appropriate messages

Algorithm:
Step1: [Initialize]
start
Step2: [Input the coefficients of quadratic equation]
Read a,b,c.
Step3: [Check for valid coefficients]
If (a==0)
Then invalid coefficients. Go to step 6
Step4:[Compute discriminate value as d]
d=b*b-4*a*c
Step5: [Check for d value to compute roots]

5.1:if (d>0)
then
print real and distinct
rootsroot1=(-
b+√d)/(2*a) root2=(-b-
√d)/(2*a)
print
root1,root
2 goto
step 6
5.2 :if (d==0) then
print real and equal roots root1 = root2= -
b/(2*a)print root1,root2
go to step 6
Step 5.3:if (d<0) then
print real and imaginary real=-b/(2*a)
imag=(√fabs(d))/(2*a) print root1 as real+iimag
printroot2 as real-I imag
goto step 6
Step 6: [Finished] Stop

DEPT.CSE.EPCET 11
Principles of Programming Laboratory 22POP13/23

Flowchart:

DEPT.CSE.EPCET 12
Principles of Programming Laboratory 22POP13/23

Program:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
float a, b, c, d,root1,root2,real,imag;
printf("enter the coefficients a, b, c:\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0||b==0||c==0)
{
printf("Invalid coefficients\n");
exit(0);
}
d=b*b-4*a*c;
if(d>0)
{
root1=(-b+sqrt(d))/(2.0*a);
root2=(-b-sqrt(d))/(2.0*a);
printf("the roots are real and distinct...\n");
printf("root1=%.2f\n”,root1);
printf(“root2=%.2f\n",root2);
}
else if(d==0)
{
root1=root2=-b/(2.0*a);
printf("the roots are real and equal..\n");
printf("root1=%.2f\n”,root1);
printf(“root2=%.2f\n",root2);
}

else
{
real= -b/(2.0*a);
imag=sqrt(fabs(d))/(2.0*a);
printf("the roots are complex and
imaginary..\n");
printf("root1=%.2f+i%.2f\n",real,imag);
printf(“root2=%.2f-i%.2f\n",real,imag);
}

return 0;
}

DEPT.CSE.EPCET 13
Principles of Programming Laboratory 22POP13/23

TEST CASE:

Test Cases: Test No Input Parameters Expected Output Obtained Output


1 a=0, b=0, c=1 Invalid Coefficients Invalid Coefficients
2 a=1, b=6, c=9 Roots are real and Roots are real and
equal equal
root1=-3, root2=-3 root1=-3, root2=-3
3 a=1, b=-5, c=3 Roots are real and Roots are real and
distinct distinct
root1=4.30, root1=4.30,
root2=0.69 root2=0.69
4 a=1, b=4, c=7 Roots are complex and Roots are complex and
imaginary imaginary
root1= -2+i1.73, root1= -2+i1.73,
root2= -2- i1.73 root2= -2- i1.73

DEPT.CSE.EPCET 14
Principles of Programming Laboratory 22POP13/23

3. An electricity board charges the following rates for the use of electricity: for the
first 200 units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units
Rs 1 per unit. All users are charged a minimumof Rs. 100 as meter charge. If the total
amount is more than Rs 400, then an additional surcharge of 15% of total amount is
charged. Write a program to read the name of the user, number of units consumed and
print out the charges.

Algorithm
Step 1: [Initialize]
Start
Step 2:[Read the name of the user and number of units of electricity consumed]
Read name,units
Step 3: [Use else if ladder, to satisfy the given condition: for the first 200 units 80 paise per
unit:for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per unit. All users
are charged a minimum of Rs.100 as meter charge]
if(units<=200)
rupees=100+units*0.80;
else if(units<=300 && units>200)
rupees=100+200*0.80+(units-
200)*0.90;else
rupees=100+200*0.80+100*0.90+(units-
300)*1.00;end if
Step 4:[Use simple if to satisfy, the total amount is more than Rs 400, then an additional
surchargeof 15% of total amount is charged]
if(rupees>400)
rupees=rupees+0.15*rup
ees;end if
Step 5:[Print the name of user and amount to be paid]
Print name, rupees
Step 6:[Finished]
Stop

DEPT.CSE.EPCET 15
Principles of Programming Laboratory 22POP13/23

Flowchart:

DEPT.CSE.EPCET 16
Principles of Programming Laboratory 22POP13/23

Program
#include<stdio.h>
int main()
{
char name[20]; int units;
float rupees=0;
printf("\n enter the name of the user :");
gets(name);
printf("\n enter number of units consumed :");
scanf("%d",&units);
if(units<=200)
rupees=100+units*0.80;
else if(units<=300 && units>200)
rupees=100+200*0.80+(units-200)*0.90;
else
rupees=100+200*0.80+100*0.90+(units-300)*1.00;
if(rupees>400)
rupees=rupees+0.15*rupees;
printf("%s has to pay rupees %.2f",name,rupees);
return 0;
}

DEPT.CSE.EPCET 17
Principles of Programming Laboratory 22POP13/23

Test Cases:

Test No Input Parameters Expected Output Obtained Output


enter the name of the user Sonia has to pay rupees Sonia has to pay rupees
1. :Sonia 260 260
enter number of units consumed
: 200
2 enter the name of the user Sonia has to pay rupees Sonia has to pay rupees
:Sonia 350 350
enter number of units consumed
: 300
3 enter the name of the user Sonia has to pay rupees Sonia has to pay rupees
:Sonia 517.5 517.5
enter number of units consumed
: 400

DEPT.CSE.EPCET 18
Principles of Programming Laboratory 22POP13/23

4. Write a C program to display the following by reading the number of rows as input
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
-----------------------------------------------------------------------------------------
nth row

#include <stdio.h>
void main()
{
int i,j,n;
printf("Input number of rows : ");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
/* print blank spaces */
for(j=1;j<=n-i;j++)
printf(" ");
/* Display number in ascending order upto middle*/
for(j=1;j<=i;j++)
printf("%d",j);

/* Display number in reverse order after middle */


for(j=i-1;j>=1;j--)

DEPT.CSE.EPCET 19
Principles of Programming Laboratory 22POP13/23

printf("%d",j);

printf("\n");
}
}

DEPT.CSE.EPCET 20
Principles of Programming Laboratory 22POP13/23

5. Implement Binary search on Integer/names

Algorithm
Step 1: [Initialize]
Start
Step 2:[Read number of numbers and the numbers’ and n numbers in ascending order
in anarray]
Read n, a[]
Step 3: [Read the number to be searched as key]
Read key
Step 4:[Set low and
high]
low=
0
high
=n-1
Step 5:[Iterate using while loop until low<=high and !found]
while(low<=high &&
!found)mid=(low+high)/2
if(a[mid]==key)
found=1
else
if(a[mid]<key)
low=mid+1
else
high=m
id-1end
if
end while
Step 6:[Finished]
Stop

DEPT.CSE.EPCET 21
Principles of Programming Laboratory 22POP13/23

Flowchart:

DEPT.CSE.EPCET 22
Principles of Programming Laboratory 22POP13/23

Program:
#include<stdio.h>
#include<string.h>
int main()
{
int a[10],key;
int n,i,low,high,mid,found=0;
printf("enter the number of numbers to read\n");
scanf("%d",&n);
printf("enter the numbers in ascending order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the number to search\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high && !found)
{
mid=(low+high)/2;
if(a[mid]==key) found=1;
else if(a[mid]<key) low=mid+1;
else high=mid-1;
}
if(found==1)
printf("\n number found at position:%d",mid+1);
else
printf("\n number not found");
return 0;

DEPT.CSE.EPCET 23
Principles of Programming Laboratory 22POP13/23

}
Test Cases:

Test Input Parameters Expected Output Obtained Output


No
1 enter the number of numbers to read 5 number found at number found at
enter the numbers in ascending order position 5 position 5
10 20 30 40 50
enter the number to search 50
2 enter the number of numbers to read 5 number not found number not found
enter the numbers in ascending order
10 20 30 40 50
enter the number to search 5

DEPT.CSE.EPCET 24
Principles of Programming Laboratory 22POP13/23

6. Implement Matrix multiplication and validate the rules of matrix multiplication.

Algorithm
Step 1: [Initialize]
start
Step 2:[Read the order and the matrices (2D array) from the
user]Read order of matrices a[ ] [ ] and b[ ][ ] i.e m*n and
p*q Read a[][] and b[][] arrays.
Step 3: [check for possibility of multiplication]
if n!=p
Print Matrix multiplication not
possible.goto step 6
else
goto
Step 4
end if
Step 4:[Multiply the two matrices a*b(nested for is used)]
for(i=0;i<m;i
++)
for(j=0;j<q;j+
+) c[i][j]=0;
for(k=0;k<n;k
++)
c[i][j]=c[i][j]+a[i][k]*b[k][j]
;end for
en
d
for
end
for
Step 5:[Display the resultant C Matrix]
Print the input matrices a[ ][ ],b[ ][ ] and resultant matrix c[ ][ ]
Step 6:[Finished]
Stop

DEPT.CSE.EPCET 25
Principles of Programming Laboratory 22POP13/23

Flowchart:

DEPT.CSE.EPCET 26
Principles of Programming Laboratory 22POP13/23

Program
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[10][10],b[10][10],c[10][10], m,n,p,q,i,j,k;
printf("Enter the order of the matrix A and order of the matrix B\n");
scanf("%d%d%d%d",&m,&n,&p,&q);
if(n!=p)
{
printf("\n multiplication not possible");
exit(0);
}
else
{
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<p;i++)
{
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
}

DEPT.CSE.EPCET 27
Principles of Programming Laboratory 22POP13/23

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{ c[i][j]=0;
for(k=0;k<n;k++) c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf("\n Product of A and B matrices : MATRIX C\n");
for(i=0;i<m;i++)
{
printf("\n"); for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
}
}
return 0;
}

DEPT.CSE.EPCET 28
Principles of Programming Laboratory 22POP13/23

Test cases:
Test Input Parameters Expected Output Obtained Output
No
1 Enter the order of the matrix A 2 2 MATRIX A MATRIX A
Enter the order of the matrix B 2 2 12 12
Enter the elements of matrix A... 34 34
1234 MATRIX B MATRIX B
Enter the elements of matrix B... 56 56
5678 78 78
Product of A and B Product of A and B
matrices : MATRIX C matrices : MATRIX C
19 22 19 22
43 50 43 50
2 Enter the order of the matrix A 2 3 multiplication not multiplication not
Enter the order of the matrix B 2 2 possible possible
Enter the elements of matrix A...
123456
Enter the elements of matrix B...
5678

DEPT.CSE.EPCET 29
Principles of Programming Laboratory 22POP13/23

7. Compute sin(x)/cos(x) using Taylor series approximation.


Compare your result with the built-in library function. Print both
the results with appropriate inferences.

Algorithm
Step 1: [Initialize]
Start
Step 2: [Set PI=3.142]
PI=3.142
Step 3: [Reading
degree]
read degree
Step 4:[Calculate x to convert degree to
radians]
x=degree*(PI/180)
Step 5:[Set the intial values of
nume,deno,i]
num
e=x;
deno
=1;
i=2;
Step 6:[Iterate using do while loop till term>=0.000001]
do
term=nume/den
o; nume=-
nume*x*x;
deno=deno*i*(i
+1);
sum=sum+term
; i=i+2;
while(fabs(term)>=0.000001);
Step 7: [Display the result]
Print degree and sum.
Also, print using built in function sin(x).
Step 8: [Finished]
Stop

FlowChart:

DEPT.CSE.EPCET 30
Principles of Programming Laboratory 22POP13/23

DEPT.CSE.EPCET 31
Principles of Programming Laboratory 22POP13/23

Program
#include<stdio.h>
#include<math.h>
#define PI 3.142
int main()
{
int i,degree;
float x,sum=0,term,nume,deno;
printf("enter the value of degree");
scanf("%d",&degree);
x=degree * (PI/180);
nume=x;
deno=1;
i=2;
do
{
term=nume/deno;
nume=-nume*x*x; deno=deno*i*(i+1);
sum=sum+term;
i=i+2;
}
while(fabs(term)>=0.00001);
printf("\nThe sine of %d is %.2f",degree,sum);
printf("\nThe sine function of %d is %.2f using library function",degree,sin(x));
return 0;
}

DEPT.CSE.EPCET 32
Principles of Programming Laboratory 22POP13/23

Test cases:

Test No Input Parameters Expected Output Obtained Output

1 Degree=0 The sine of 0 is 0 The sine of 0 is 0


The sine function 0 is 0 using The sine function 0 is 0
library function using library function
2 Degree=60 The sine of 60 is 0.866093 The sine of 60 is 0.866093
The sine function 60 is The sine function 60 is
0.866093 using library 0.866093 using library
function function
3 Degree=-10 The sine of -10 is -0.173670 The sine of -10 is -
The sine of -10 is -0.173670 0.173670
using library function The sine of -10 is -
0.173670 using library
function

DEPT.CSE.EPCET 33
Principles of Programming Laboratory 22POP13/23

8. Sort the given set of N numbers using Bubble sort.


Algorithm
Step 1: [Initialize]
start
Step 2: [Input number of elements]
read n
Step 3: [Input unsorted elements in an
array]Read elements in array a[]
for(i=0;i<n;i++)
read
a[i]
end
for
Step 4: [output unsorted elements in
array]Print elements in array a[]
for(i=0;i<n;i++)
print
a[i]
end
for
Step 5:[Iterate array a[] in two loops. Outer loop gives number of passes. Inner loop does n-I
comparisions and swap task. In each pass, compare each pair of adjacent items. If former
element is greater than latter one, swap them.]
for(i=0;i<n-
1;i++)
for(j=0;j<n-1-
i;j++)
if(a[j]>a[j+1])
temp=a[
j]
a[j]=a[j+
1]
a[j+1]=t
emp
e
nd if
end for
end for
Step 6: [Display sorted elements in
array]Print elements in array
a[] for(i=0;i<n;i++)
print
a[i]
end
for
Step 7: [Finished]
Stop

Program

DEPT.CSE.EPCET 34
Principles of Programming Laboratory 22POP13/23

#include<stdio.h>
int main()
{
int n,i,j,a[10],temp;
printf("\n enter the number of elements");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
printf("\nThe sorted elements are\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
return 0;
}

DEPT.CSE.EPCET 35
Principles of Programming Laboratory 22POP13/23

Test cases:

Test No Input Parameters Expected Output Obtained Output


1 Enter the number of Original elements are Original elements are
elements 5 23 4 6 12 40 23 4 6 12 40
Enter the array elements The sorted elements are The sorted elements are
23 4 6 12 40 4 6 12 23 40 4 6 12 23 40
2 Enter the no.of elements 4 Original elements are Original elements are
Enter the array elements -3 -9 12 6 -3 -9 12 6
-3 -9 12 6 The sorted elements are The sorted elements are
-9 -3 6 12 -9 -3 6 12

DEPT.CSE.EPCET 36
Principles of Programming Laboratory 22POP13/23

9. Write functions to implement string operations such as compare, concatenate,


string length. Convince the parameter passing techniques.

Algorithm
Step 1: [Initialize]
start
Step 2: [Input two source strings]
read source1,source2
Step 3: [Caculate length1 of source1 by calling the user defined function,strlength(); Repeat the
same for length2 of source2 ]
length1=strlength(sourc
e1);
length2=strlength(sourc
e2);
Step 4: [Ouput length1,length2]
Print length1,length2
Step 5: [Compare the two strings by calling the user defined function,strcompare()]
k=strcompare(source1,source2);
Step 6: [check k, to find the whether the strings are same or not]
if(k==0)
print Both strings are
sameelse
print strings are
differentend if
Step 7: [Concatenate two strings by calling the user defined function,strconcat() and the
concatenated string is stored in source1]
strconcat(source1,sourc
e2);print source1
Step 8: [Finished]
Stop

Algorithm (user defined function -


strlength())Step 1: [Initialize]
Start
Step 2: [set i=0]
i=0
Step 3: [receive the source string as str, read character by character, count one by one until we
reach NULL character]
while(str[i]!='\0'
)i++
end while
Step 4: [return i to the calling function]
return i
Algorithm (user defined function -
strcompare())Step 1: [Initialize]
Start
Step 2: [set i=0]

DEPT.CSE.EPCET 37
Principles of Programming Laboratory 22POP13/23

i=0
Step 3: [Receive both the source strings as str1 and str2, read character by character until they
match, if the matched character is a NULL then go out of while loop, when any
unmatchedcharacter then go out of loop]
while(str1[i]==str
2[j])
if(str1[i]=='\0')
br
ea
k;
en
d
if
i+
+;
j+
+;
end while
Step 4: [calculate k]
k=str1[i]-str2[j];
Step 5: [return i to the calling function]
return k

Algorithm (user defined function -


strconcat())Step 1: [Initialize]
Start
Step 2: [set i=0]
i=0
Step 3: [Receive both the source strings as str1 and str2, calculate length of str1 using
strlength()as l]
l=strlength(str1)
Step 4: [read str2 character by character and store it from the end of str1]
while(str2[i]!='
\0')
str1[l+i]=str2[i
] i++
end while
Step 5: [return to the calling function]
Return

DEPT.CSE.EPCET 38
Principles of Programming Laboratory 22POP13/23

Flowchart

DEPT.CSE.EPCET 39
Principles of Programming Laboratory 22POP13/23

DEPT.CSE.EPCET 40
Principles of Programming Laboratory 22POP13/23

DEPT.CSE.EPCET 41
Principles of Programming Laboratory 22POP13/23

Program :
#include<stdio.h>
int strlength(char str1[50]);
void strconcat(char str1[50],char str2[50]);
int strcompare(char str1[50],char str2[50]);
int strlength(char str1[50])
{
int i=0;
while(str[i]!='\0')
i++;
return i;
}
void strconcat(char str1[50],char str2[50])
{
int i=0,l; l=strlength(str1);
while(str2[i]!='\0')
{
str1[l+i]=str2[i]; i++;
}
str1[l+i]='\0';
}
int strcompare(char str1[50],char str2[50])
{
int i=0,k; while(str1[i]==str2[i])
{
if(str1[i]=='\0') break;
i++;
}

DEPT.CSE.EPCET 42
Principles of Programming Laboratory 22POP13/23

k=str1[i]-str2[i];
return k;
}
int main()
{
char source1[50],source2[50];
int length1,length2,k;
printf("\n Enter the source string 1:");
gets(source1);
printf("\n Enter the source string 2:");
gets(source2);
length1=strlength(source1);
length2=strlength(source2);
printf("\n string length of string 1 is %d",length1);
printf("\n string length of string 1 is %d",length2);
k=strcompare(source1,source2);
if(k==0)
printf("\n Both string are same");
else
printf("\n Both string are different");
strconcat(source1,source2);
printf("\n concatenated string is ");
puts(source1);
return 0;
}

DEPT.CSE.EPCET 43
Principles of Programming Laboratory 22POP13/23

Test Cases:

Test Input Parameters Expected Output Obtained Output


No
1 Enter the source string1 :good string length of string 1 is 4 string length of string 1
Enter the source string2: string length of string 2 is 4 is 4
good Both strings are same string length of string 2
concatenated string is is 4
goodgood Both string are same
concatenated string is
goodgood
2 Enter the source string1 : string length of string 1 is string length of string 1
East 4 is
4
3 Enter the source string 2: string length of string 2 is 5 string length of string 2
Point strings are different is 5
concatenated string is strings are different
EastPoint concatenated string is
EastPoint

DEPT.CSE.EPCET 44
Principles of Programming Laboratory 22POP13/23

10. Implement structures to read, write, and compute average- marks and the
students scoring above and below theaverage marks for a class of N students.
Algorithm
Step 1: [Initialize]
Start
Step 2:[Create a structure student]
Create a structure called student with fields rollno,name,marks,grade with suitable datatypes.
struct student
{
int rollno;char name[20]; float marks;
};
Step 3:[Set found=0, sum=0]
found=0
Step 4:[Read the number of student details]
Read n
Step 5: [Read n student details. Iterate using a for loop for inputting rollno, name, marks of each student]
for(i=0;i<n;i++)
printf(“\nenter the %d student
details”,i+1);printf(“\n enter roll
number:”); scanf(“%d”,&s[i].rollno);
printf(“\n enter student
name:”);
scanf(“%s”,s[i].name);
printf(“\n enter the
marks:”);
scanf(“%d”,&s[i].marks);
end for
Step 6:[Display the n student details]
Print the rollno, name, marks of all students by iterating using a for loop.
Step 7:[Calculate sum of the marks of all students]
for(i=0;i<n;i++)
sum=sum+s[i].m
arksend for
Step 8:[calculate average]
average=sum/n;
Step 9:[Display the names of students scoring above average]
for(i=0;i<n;i++)
if(s[i].marks>=aver
age)
printf("%s\t",s[i].na
me)end if
end for
Step 10:[Display the names of students scoring below average]
for(i=0;i<n;i++)
if(s[i].marks<average)
printf("%s\t",s[i].name
)end if
end for

DEPT.CSE.EPCET 45
Principles of Programming Laboratory 22POP13/23

Step 11:[Display no students scored below average, if found==0]


if(found==0)
printf("\n no
students scored
below average")end
if
Step 12:Stop

DEPT.CSE.EPCET 46
Principles of Programming Laboratory 22POP13/23

Flowchart:

DEPT.CSE.EPCET 47
Principles of Programming Laboratory 22POP13/23

DEPT.CSE.EPCET 48
Principles of Programming Laboratory 22POP13/23

Program
#include<stdio.h>
#include<string.h>
struct student
{
int rollno;
char name[20];
float marks;
};
int main()
{
int i,n,found=0;
struct student s[10];
float sum=0,average;
printf("\nEnter the number of student details");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nenter the %d student details",i+1);
printf("\n enter roll number:");
scanf("%d",&s[i].rollno);
printf("\n enter student name");
scanf("%s",s[i].name);
printf("\n enter the marks:");
scanf("%f",&s[i].marks);
}
printf("\nStudent details are\n");

DEPT.CSE.EPCET 49
Principles of Programming Laboratory 22POP13/23

printf("\nRollno\t\tName\t\tMarks\n");
for(i=0;i<n;i++)
printf("%d\t\t%s\t\t%f\n",s[i].rollno,s[i].name,s[i].marks);
for(i=0;i<n;i++)
sum=sum+s[i].marks;
average=sum/n;
printf("\nAVERAGE=%,2f",average);
printf("\n students scoring above average\n");
for(i=0;i<n;i++)
{
if(s[i].marks>=average)
{
printf("%s\t",s[i].name);
}
}
printf("\n students scoring below average\n");
for(i=0;i<n;i++)
{
if(s[i].marks<average)
{
printf("%s\t",s[i].name);
found=1;
}
}
if(found==0)
printf("\n no students scored below average");
return 0;

DEPT.CSE.EPCET 50
Principles of Programming Laboratory 22POP13/23

Test Input Parameters Expected Output Obtained Output


cases
Test No
1 Enter the number ofstudent details 4 Student details are Student details are Rollno Name
enter the 1 student details Rollno Name Marks Marks100 austin 56.000
enter roll number: 100enter student 100 austin 56.000 200 banu 67.000
name:austin 200 banu 67.000 300 charan 90.000
enter the marks: 56enter the 2 300 charan 90.000 400 dina 69.000 Average=70.500000
student details 400 dina 69.000 Students scoring aboveaverage
enter roll number: 200enter student Average=70.500000 charan Students scoring below
name:banu Students scoring above average
enter the marks: 67enter the 3 average charan austin banu dina
student details Students scoring below
enter roll number: 300enter student average
name:charan austin banu dina
enter the marks: 90 enter roll number:
400
enter student name:dinaenter the marks:
69

2 Enter the number ofstudent details 4 Student details are Student details are Rollno Name
enter the 1 student details Rollno Name Marks Marks100 austin 100.000
enter roll number: 100enter student 100 austin 100.000 200 banu 100.000
name:austin 200 banu 100.000 300 charan 100.000
enter the marks: 100enter the 2 300 charan 100.000 400 dina 100.000
student details 400 dina 100.000 Average=100.000000 Students
enter roll number: 200enter student Average=100.000000 scoring above
name:banu Students scoring above
average

DEPT.CSE.EPCET 51
Principles of Programming Laboratory 22POP13/23

11.Develop a program using pointers to compute the sum, mean and standard deviation
of all elements stored in an array of n real numbers.

Algorithm
Step 1: [Initialize]
Start
Step 2:[Read the no of elements and array elements]
Rea
dn
Rea
d a[]
Step 3: [Set starting address of array to a pointer variable]
ptr=a
Step 4:[Iterate using a for loop to find sum using pointers]
for(i=0;i<n;i
++)
sum=sum+*
ptr ptr++
end for
Step 5:[Calculate mean]
mean=sum/n
Step 6: [Set starting address of array to a pointer variable]
ptr=a
Step 7:[Iterate using a for loop to find sumstd using pointers]
for(i=0;i<n;i++ )
sumstd=sumstd+pow((*ptr-
mean),2)ptr++
end for
Step 8:[Calculate standard deviation]
std=sqrt(sumstd/n)
Step 9:[Display the result]
Print sum,mean,std
Step 10:[Finished]
Stop

DEPT.CSE.EPCET 52
Principles of Programming Laboratory 22POP13/23

Flowchart:

DEPT.CSE.EPCET 53
Principles of Programming Laboratory 22POP13/23

Program
#include<stdio.h>
#include<math.h>
int main()
{
float a[10],*ptr,mean,std,sum=0,sumstd=0;
intn,i;
printf(“\n Enter the number of elements”);
scanf(“%d”,&n);
printf(„\n Enter the array elements”);
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=%.2f\n”,sum);
printf(“Mean=%.2f\n”,mean);
printf(“Standard Deviation=%f\n”,std);

return 0;

DEPT.CSE.EPCET 54
Principles of Programming Laboratory 22POP13/23

Test cases:

Test No Input Parameters Expected Output Obtained Output


1 Enter the number of Sum= 28 Sum= 28
elements 5 Mean= 5.6 Mean= 5.6
Enter the array Standard Deviation= Standard Deviation=
elements 1 5 9 6 7 2.09 2.09
2 Enter the number of Sum= 10.68 Sum= 10.68
elements 4 Mean= 2.67 Mean= 2.67
Enter the array Standard Deviation= Standard Deviation=
elements 2.3 1.1 4.5 0.863 0.863
2.78

DEPT.CSE.EPCET 55
Principles of Programming Laboratory 22POP13/23

12. Write a C program to copy a text file to another, read both the input file name and
target file name.

Program for Copying the Content:

#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
char ch;// source_file[20], target_file[20];
FILE *source, *target;
char source_file[]="x1.txt";
char target_file[]="x2.txt";
source = fopen(source_file, "r");
if (source == NULL) {
printf("Press any key to exit...
");
exit(EXIT_FAILURE);
}
target = fopen(target_file, "w");
if (target == NULL) {
fclose(source);
printf("Press any key to exit...
");
exit(EXIT_FAILURE);
}
while ((ch = fgetc(source)) != EOF)
fputc(ch, target);
printf("File copied successfully.

DEPT.CSE.EPCET 56
Principles of Programming Laboratory 22POP13/23

");
fclose(source);
fclose(target);
return 0;
}
Program for Reading the content from File

#include <stdio.h>
int main ()
{
FILE *fp;
char temp[100];
/* open file for reading */
fp = fopen('example.txt' , 'r');
/*fgets() function reads a line of text having maximum length of 100 and the contents are
stored in character array 'temp'*/
if( fgets (temp, 100, fp)!=EOF )
{
/* write contents to standard output */
puts(temp);
}
fclose(fp);
return(0);
}

DEPT.CSE.EPCET 57
Principles of Programming Laboratory 22POP13/23

VIVA QUESTIONS

1. Who developed C language?


C language was developed by Dennis Ritchie in 1970 at Bell Laboratories.

2. Which type of language is C?


C is a high – level language and general purpose structured programminglanguage.

3. What is a compiler?
Compile is a software program that transfer program developed in high level language
intoexecutable object code.

4. What are reserved words with a programming language?


The words that are part of the slandered C language library are called reserved words. Those
reserved words have special meaning and it is not possible to use them for any activity other
than its intended functionality.

5. What is a program?
A computer program is a collection of the instructions necessary to solve a specific problem.

6. What is an algorithm?
The approach or method that is used to solve the problem is known as algorithm.

7. What is structure of C program?


A C program contains Documentation section, Link section, Definition section, Global
declaration section, Main function and other user defined functions

DEPT.CSE.EPCET 58
Principles of Programming Laboratory 22POP13/23

8. What is a C token and types of C tokens?


The smallest individual units are known as C tokens. C has six types of tokens
Keywords,Constants, Identifiers, Strings, Operators and Special symbols.

9. What is a Keyword?
Keywords are buildingblocks for program statements and have fixed meanings and these
meanings cannot be changed.

10. How many Keywords (reserve words) are in C?


There are 32 Keywords in C language.

11. What is an Identifier?


Identifiers are user-defined names given to variables, functions and arrays.
13. . What are the Back Slash character constants or Escape sequence characters available
in C?

Back Slash character constant are \t, \n, \0

14. What is a variable?


Variables are user-defined names given to memorylocations and are used to store values.
Avariable may have different values at different times during program execution

15. What are the Data Types present in C?


Primary or Fundamental Data types (int, float, char), Derived Data types(arrays, pointers)and
User- Defined data types(structures, unions, enum)

16. How to declare a variable?


The syntax for declaring variable is data type variable_name-1, variable_name-2, ... variable
name-n;

DEPT.CSE.EPCET 59
Principles of Programming Laboratory 22POP13/23

17. What is meant by initialization and how we initialize a variable?


While declaring a variable assigning value is known as initialization. Variable can be initialized
by using assignment operator (=).

18. What are integer variable, floating-point variable and character variable?
A variable which stores integer constants are called integer variable. A variable which stores
real values are called floating-point variable. A variable which stores character constants are
called character variables.

19. How many types of operator or there in C?


C consist Arithmetic Operators (+, -, *, /,%), Relational Operators (<, <=, >, >=, !=), Logical
Operators (&&, ||,
!), Assignment Operators (=, +=, -=, *=, /=), Increment and Decrement Operators (++, --),
Conditional Operator(?:), Bitwise Operators(<<, >>, ~, &, |, ^) and Special Operators (. , ->,
&, *, sizeof)

20. What does static variable mean?


Static variables are the variables which retain their values between the function calls. They are
initialized only once their scope is within the function in which they are defined.

21. What is a pointer?


Pointers are variables which stores the address of another variable. That variable may be a
scalar (including another pointer), or an aggregate (array or structure). The pointed-to object
may be part of a larger object, such as a field of a structure or an element in an array
22. What are the uses of a pointer?
Pointer is used in the following cases
i) It is used to access array elements
ii) It is used for dynamic memory allocation.
iii) It is used in Call by reference
iv) It is used in data structures like trees, graph, linked list etc.
23. What is a structure?

DEPT.CSE.EPCET 60
Principles of Programming Laboratory 22POP13/23

Structure constitutes a super data type which represents several different data types in a single
unit. A structure can be initialized if it is static or global.

24. What is a union?


Union is a collection of heterogeneous data type but it uses efficient memory utilization
technique by allocating enough memory to hold the largest member. Here a single area of
memory contains values of different types at different time. A union can never be initialized.

25. What are the differences between structures and union?


A structure variable contains each of the named members, and its size is large enough to hold
all the members. Structure elements are of same size.
A union contains one of the named members at a given time and is large enough to hold the
largest member. Union element can be of different sizes.

26. What are the differences between structures and arrays?


Structure is a collection of heterogeneous data type but array is a collection of homogeneous
data types.
Array
1-It is a collection of data items of same data type. 2-It has declaration only
3-.There is no keyword.
4- array name represent the address of the starting element.

Structure
1-It is a collection of data items of different data type.
2- It has declaration and definition
3-keyword struct is used
4-Structure name is known as tag it is the short hand notation of the declaration.

DEPT.CSE.EPCET 61
Principles of Programming Laboratory 22POP13/23

27. Where is the auto variables stored?


Auto variables can be stored anywhere, so long as recursion works. Practically, they„re stored
on the stack. It is not necessary that always a stack exist. You could theoretically allocate
function invocation records from the heap.

28. What is the use of typedef?


The typedef help in easier modification when the programs are ported to another machine. A
descriptive new name given to the existing data type may be easier to understand the code.

29. Out of fgets() and gets() which function is safe to use and why?
fgets() is safer than gets(), because we can specify a maximum input length. Neither one is
completely safe, because the compiler can„t prove that programmer won„t overflow the buffer
he pass to fgets ().

DEPT.CSE.EPCET 62

You might also like