0% found this document useful (0 votes)
64 views89 pages

PCD Manual

This document contains details about the Computer Programming Lab course offered at Global Academy of Technology during the 2017-2018 academic year. The document includes information about the course code, prerequisites, objectives, outcomes, syllabus, evaluation criteria and list of experiments to be performed. Some key experiments include developing programs to find roots of quadratic equations, check for palindromes, compute factorials and polynomials, sort arrays, and perform matrix operations. Students will implement the programs in C/C++ and evaluate their output.
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)
64 views89 pages

PCD Manual

This document contains details about the Computer Programming Lab course offered at Global Academy of Technology during the 2017-2018 academic year. The document includes information about the course code, prerequisites, objectives, outcomes, syllabus, evaluation criteria and list of experiments to be performed. Some key experiments include developing programs to find roots of quadratic equations, check for palindromes, compute factorials and polynomials, sort arrays, and perform matrix operations. Students will implement the programs in C/C++ and evaluate their output.
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/ 89

GLOBAL ACADEMY OF TECHNOLOGY

Rajarajeshwari Nagar, Bengaluru – 560 098.

DEPARTMENT
of
COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

Academic Year : 2017 - 2018(ODD SEMESTER)


Programme (UG/PG) : UG
Year / Semester : I Yr / I Sem
Course Code : 15CPL16/26
Course Title : COMPUTER PROGRAMMING LAB

Current Version / Date : V1.3 / 01.08.2017

Prepared By
Department of CSE, GAT
GLOBAL ACADEMY OF TECHNOLOGY

VISION
Become a premier institution imparting quality education in engineering and
management to meet the changing needs of society.

MISSION
M1. Create environment conducive for continuous learning through quality
teaching and learning processes supported by modern infrastructure.

M2. Promote Research and Innovation through collaboration with industries.

M3. Inculcate ethical values and environmental consciousness through


holistic education programs.
GLOBAL ACADEMY OF TECHNOLOGY
PROGRAM OUTCOMES (POs)
Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. 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.
4. 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.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. 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.
7. 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.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. 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.
11. 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.
12. 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.
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING

VISION
To achieve academic excellence and strengthen the skills to meet emerging
challenges of computer science and engineering.

MISSION
M1. To impart strong theoretical foundations in the field of Computer
Science and Engineering accompanied with extensive practical training.
M2. To inculcate research and innovation spirit among students through
interaction with industry and projects that address societal issues.
M3. Instill professional ethics and social values amongst students with
concern for environment.

PSO
PSO1: Design, Implement and test system software and application software
to meet the desired needs.
PSO2: Develop solutions in the area of communication networks, data base
Systems and computing systems.
Global Academy of Technology

Course Details
Course Name: Computer Programming Lab.
Course Code: 15CPL16/26.
Course prerequisite: Basic Mathematics knowledge and Logical thinking.

Course objectives
Upon completion of this course, students are expected to:

1. Understand various parts of a computer and write algorithms and flow chart to solve
problems.
2. Familiarize with Turbo C/Dev C++ Editor and write, compile and execute programs
using C Programming concepts.
3. Analyze and implement programs using derived, user data types and functions.
4. Write programs for creating files and perform operations on files.

Course outcomes
Upon successful completion of this course, students should be able to:

Subject code: 15CPL16/26 Subject Name: Computer Programming Lab


No. of
Cos COURSE OUTCOME KL
sessions
CO1 Identify hardware components of computer U 2
CO2 Execute C programs on control structures. AP 2
CO3 Execute C programs using 1-dimensional and 2-dimensional arrays. AP 3
CO4 Execute C programs on string handling functions. AP 2
CO5 Write C programs using user-defined functions and file handling
AP 3
functions.
CO6 Execute C programs on pointers and structures AP 2
Global Academy of Technology

COMPUTER PROGRAMMING LAB


Subject Code: 15CPL16/26 IA Marks: 20
No. of Practical Hrs. / Week: 03 Exam Hours: 03
Total No. of Practical Hrs: 42 Exam Marks: 80

PART A
Demonstration of Personal Computer and its Accessories:

Demonstration and Explanation on Disassembly and Assembly of a Personal Computer by the


faculty-in-charge. Students have to prepare a write-up on the same and include it in the Lab
record and evaluated.

Laboratory Session-1: Write-up on Functional block diagram of Computer, CPU, Buses,


Mother Board, Chip sets, Operating System & types of OS, Basics of Networking &
Topology and NIC.

Laboratory Session-2: Write-up on RAM, SDRAM, FLASH memory, Hard disks, Optical
media, CDROM/R/RW, DVDs, Flash drives, Keyboard, Mouse, Printers and Plotters.
Introduction to flowchart, algorithm and pseudo code.

Note: These TWO Laboratory sessions are used to fill the gap between theory classes and
practical sessions. Both sessions are to be evaluated as lab experiments.

PART B
Laboratory Experiments:
Implement the programs with WINDOWS / LINUX platform using appropriate
C compiler.
1. Design and develop a flowchart or an algorithm that takes three coefficients (a, b, and c)
of a Quadratic equation (ax2+bx+c=0) as input and compute all possible roots. Implement a C
program for the developed flowchart/algorithm and execute the same to output the possible
roots for a given set of coefficients with appropriate messages.

2. Design and develop an algorithm to find the reverse of an integer number NUM and
check whether it is PALINDROME or NOT. Implement a C program for the developed
algorithm that takes an integer number as input and output the reverse of the same with
suitable messages. Ex: Num: 2014, Reverse: 4102, Not a Palindrome

3. a. Design and develop a flowchart to find the square root of a given number N.
Implement a C program for the same and execute for all possible inputs with appropriate
messages. Note: Don’t use library function sqrt(n).
Global Academy of Technology

b. Design and develop a C program to read a year as an input and find whether it is leap year
or not. Also consider end of the centuries.

4. Design & develop an algorithm to evaluate polynomial f(x) = a4x4 + a3x3 + a2x2 + a1x +a0,
for a given value of x and its coefficients using Horner’s method. Implement a C program for
the same and execute the program with different set of values of coefficients and x.

5. Draw the flowchart and Write a C Program to compute Sin(x) using Taylor series
approximation given by Sin(x) = x - (x3/3!) + (x5/5!) - (x7/7!) + …….
Compare your result with the built- in Library function. Print both the results with appropriate
messages.

6. Develop an algorithm, implement and execute a C program that reads N integer numbers
and arrange them in ascending order using Bubble Sort.

7. Develop, implement and execute a C program that reads two matrices A (m x n ) and B
(p x q ) and Compute product of matrices A and B. Read matrix A and matrix B in row major
order and in column major order respectively. Print both the input matrices and resultant
matrix with suitable headings and output should be in matrix format only. Program must
check the compatibility of orders of the matrices for multiplication. Report appropriate
message in case of incompatibility.

8. Develop, implement and execute a C program to search a Name in a list of names using
Binary searching Technique.

9. Write and execute a C program that


i. Implements string copy operation STRCOPY(str1,str2) that copies a string str1 to another
string str2 without using library function.
ii. Read a sentence and print frequency of vowels and total count of consonants.

10. a. Design and develop a C function RightShift(x ,n) that takes two integers x and n as
input and returns value of the integer x rotated to the right by n positions. Assume the integers
are unsigned. Write a C program that invokes this function with different values for x and n
and tabulate the results with suitable headings.

b. Design and develop a C function isprime(num) that accepts an integer argument and returns
1 if the argument is prime, a 0 otherwise. Write a C program that invokes this function to
generate prime numbers between the given ranges.
Global Academy of Technology

11. Draw the flowchart and write a recursive C function to find the factorial of a number, n!,
defined by fact(n)=1, if n=0. Otherwise fact(n)=n*fact(n-1). Using this function, write a C
n
program to compute the binomial coefficient Cr. Tabulate the results for different values of
n and r with suitable messages.

12. Given two university information files “studentname.txt” and “usn.txt” that contains
students Name and USN respectively. Write a C program to create a new file called
“output.txt” and copy the content of files “studentname.txt” and “usn.txt” into output file in
the sequence shown below. Display the contents of output file “output.txt” on to the screen.

Student Name USN


Name 1 USN1
Name 2 USN2
…… …..

13. Write a C program to maintain a record of n student details using an array of structures
with four fields (Roll number, Name, Marks, and Grade). Assume appropriate data type for
each field. Print the marks of the student, given the student name as input.
14. Write a C program using pointers to compute the sum, mean and standard deviation of all
elements stored in an array of n real numbers.
Global Academy of Technology

VTU Lab Evaluation Process


Week wise valuation of each program
Sl.No Activity Marks (2015 Scheme)

1 Observation Book 4

2 Record / Manual 8

TOTAL 12

Internal Assessment Evaluation (End of Semester)


Sl.No Activity Marks (2015 Scheme )

1 Write-Up 12

2 Conduction 56

3 Viva Voce 12
TOTAL 80

FINAL INTERNAL ASSESSMENT CALCULATION


Sl.No Activity Marks (2015 Scheme )
1 Average of Weekly Entries 12
Internal Assessment
2 8
Reduced To
TOTAL 20
Global Academy of Technology

Steps to log in to the Dev C++ Editor:


 Switch on the system
 Enter user id: student, password: student
 Double click ‘Shortcut to Dev C++’ on desktop
 Otherwise open ‘Windows Explorer’ by right clicking on ‘Start’ button
Select ’C:\Program Files (x86)\Dev-Cpp’ (check in your system where the IDE resides)
Double click on ‘devcpp’

Dev C++ Commands:


 Ctrl S: To save the program
 Ctrl O: To open a source file (.c file) using dialogue box.
 F9: To compile the program.
 F10: To run the program.
 Alt F4: To come out of the editor or to exit.
 Ctrl F9: To check for syntax error.
 F5: Debug option (Expand debug tab, use add watch tab to know how to trace the
program)
Global Academy of Technology

TABLE OF CONTENTS

Program No. Program Title Page No.


1 To find roots of a Quadratic Equation. 1
2 To check whether a number is Palindrome or Not. 6
3a To find square root of a given number. 10
3b To check whether it is a leap year or not. 14
4 To evaluate polynomial using Horner’s method. 17
5 To compute Sin(x) using Taylor Series. 21
6 To sort numbers using Bubble Sort. 27
7 To multiply two matrices. 32
8 To search for a name using Binary Search. 38
9 To implement String Copy and count number of vowels and 43
Consonants.
10 a To right rotate a number. 49
10 b To generate a range of prime numbers. 53
11 To compute Binomial Co-efficient. 57
12 To merge two files. 60
13 To implement an array of structures. 65
14 To compute sum, mean and standard deviation. 71
Global Academy of Technology

1. Design and develop a flowchart or an algorithm that takes three coefficients (a, b, and c) of a
Quadratic equation (ax2+bx+c=0) as input and compute all possible roots. Implement a C
program for the developed flowchart/algorithm and execute the same to output the possible
roots for a given set of coefficients with appropriate messages.

Theory:
A quadratic equation is a polynomial equation of the second degree. The general form is ax2 +
bx + c=0, where a, b, and c are constants, with a ≠ 0. (If a = 0, the equation becomes a Linear
Equation.)
Solving for ‘x’ then gives

Algorithm :
step 1: read a, b, c

step 2: if (a == 0)
write “invalid data”
exit
end if
disc = b*b-4*a*c
deno = 2*a

step 3: if (disc>0)
write “roots are real and distinct”
root1=(-b+√disc)/deno
root2=(-b-√disc)/deno
write “root1,root2”

else if (disc = = 0)
write “roots are real and equal”
root1=root2=-b/deno
write “root1,root2”

else
write “roots are complex”
root1 = -b/deno
root2 = √|disc|/deno
write “root1+iroot2”
write “root1-iroot2”

step 4: stop.

Dept of CSE 1 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart :

Start

Read a,b,c

F T
Is a == 0?
disc ← (b * b) – 4 * a * c
deno ← 2 * a

F
Is disc>0?
Print Invalid
data
T

Print “roots are real Stop


and distinct” A

root1← ( - b + √disc)/ deno


root2← (- b - √disc)/ deno F
Is
disc==0?

T
Print “Roots are complex”
Print “roots are real
& equal”

ip ←√fabs (disc) / deno


root1←root2← - b/deno rp ← - b/ deno

root1← rp + i ip
root2← rp – i ip

Print root1, root2

Dept of CSE 2 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 1:

#include<stdio.h>
#include<math.h>
#include<process.h>

void main( )
{
float a,b,c,disc,deno,rootl,root2,ip,rp;

printf (" Enter three values of co-efficients \n" );


scanf ("%f%f%f", &a,&b,&c);

if (a == 0)
{
printf("\n invalid data");
getch();
exit(0);
}

disc =(b*b) - (4*a*c); // discriminant


deno = 2*a;

if (disc>0) // real distinct or unequal roots


{
printf ( "\nRoots are real and distinct: " ) ;
rootl = (-b + sqrt(disc)) /deno;
root2 = (-b - sqrt(disc)) /deno;
printf("\n\t Rootl = %f and Root2 = %f", rootl, root2);
}
else if(disc== 0) // real equal roots
{
printf ( " \nRoots are real and equal: " ) ;
printf("\n\t Rootl = Root2 = %f",-b/deno);
}
else // real and imaginary roots
{
printf("\nRoots are complex:\n");
ip=sqrt(fabs(disc))/(deno);
rp=-b/deno;
printf("\n\t Rootl = %f + i%f \n\n\t Root2 = %f - i%f", rp,ip,rp,ip);
}
getch();
}

Dept of CSE 3 CPLab Manual_15CPL16/26


Global Academy of Technology

SAMPLE INPUT / OUTPUT:

Run 1:
Enter values of co-efficient
2
4
2
Roots are real and equal:
Rootl=Root2 =-1.000000

Run 2:
Enter values of co-efficient
2
8
1
Roots are real and distinct:
Rootl = -0.129171 and Root2 = -3.870829

Run 3:
Enter values of co-efficient
4
5
6
Roots are complex:
Rootl = -0.625000 + i1.053269
Root2 = -0.625000 -i1.053269

Run 4:
Enter values of co-efficient
0
5
6
Invalid data

Dept of CSE 4 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 5 CPLab Manual_15CPL16/26


Global Academy of Technology

2. Design and develop an algorithm to find the reverse of an integer number NUM and check
whether it is PALINDROME or NOT. Implement a C program for the developed algorithm
that takes an integer number as input and output the reverse of the same with suitable
messages. Ex: Num: 2014, Reverse: 4102, Not a Palindrome.

Theory:
A palindrome number or numeral palindrome is a 'symmetrical' number like 16461, which
remains the same when its digits are reversed. The term palindromic is derived from palindrome,
which refers to a word like rotor that remains unchanged under reversal of its letters. The
palindromic numbers (in decimal) are:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161,
171, 181, 191, …

Algorithm:

Step 1: read num

Step 2: temp=num

Step 3: while (temp!=0)


digit=temp%10
rev=rev*10+digit
temp= temp/10
end while

Step 4: write “reverse number.”

Step 5: if(num==rev)
write “ num is a Palindrome”
else
write “ num is not a Palindrome”
end if

Step 6 : stop.

Dept of CSE 6 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart:

Dept of CSE 7 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 2:

#include<stdio.h>
#include<process.h>

void main ( )
{
int num , temp , digit , rev;

rev = 0;

printf ("\n Enter any number \n");


scanf ("%d", &num);

temp=num; //copy of num to a temp variable

while (temp!=0) /* to determine reverse of a number*/


{
digit=temp%10;
rev=rev*10+digit;
temp=temp/10;
}

printf("\n Reversed number is = %d\n",rev);

if (num= = rev)
printf ("\n %d is a palindrome",num);
else
printf ("\n %d is not a palindrome",num);
getch();
}

SAMPLE INPUT / OUTPUT:

Run 1:
Enter any number 2332
Reversed number is = 2332
2332 is a palindrome

Run 2:
Enter any number 4324
Reversed number is=4234
4324 is not a plindrome

Dept of CSE 8 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 9 CPLab Manual_15CPL16/26


Global Academy of Technology

3a: Design and develop a flowchart to find the square root of a given number N. Implement
a C program for the same and execute for all possible inputs with appropriate messages.
Note: Don’t use library function sqrt (n).

Algorithm:

Dept of CSE 10 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart:
Start

j=0.0001

Read num1

num← fabs(num1)

F i←0
i←i + j i<num

T
F
is (i*i)>num?

T
i←i-j,Tbreak

is num1>=0 ?
F
T
Print num1, i Print num1, i“i”

Stop

Dept of CSE 11 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 3a:

#include<stdio.h>
#include<conio.h>

void main()
{
float i,j;
float num,num1;
j=0.0001; // accuracy

printf("Enter any Number : ");


scanf("%f",&num1); // input to find square root

num=fabs(num1);

for(i=0;i<num;i=i+j) // sequential iteration


{

if((i*i)>num) /* check if (i*i) value is greater to num value then it is a


square root value*/
{
i=i-j; /* in for loop i is incremented, hence its subtracted as result is
achieved.*/
break;
}
}

if (num1>=0)
printf("Square Root of %f is %f",num1,i);

else
printf("Square Root of %f is (%f)i",num1,i);
getch();

SAMPLE INPUT / OUTPUT :


Run 1:
Enter any number: 2
Square root of 2.000000 is 1.41

Run 2:
Enter any number: -4
Square root of 4.000000 is 2.00 i

Dept of CSE 12 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 13 CPLab Manual_15CPL16/26


Global Academy of Technology

3b. Design and develop a C program to read a year as an input and find whether it is leap year
or not. Also consider end of the centuries.

Definition of leap year:

Rule 1: A year is called leap year if it is divisible by 400.


For example: 1600, 2000 etc leap year while 1500, 1700 are not leap year.

Rule 2: If year is not divisible by 400 as well as 100 but it is divisible by 4 then that year are also
leap year.
For example: 2004, 2008, 1012 are leap year.

Flowchart:
Start

Read year

Is
(year%400 == 0) || (((year%400!=0)
&&( year%100 != 0)) || (year%4 ==0))

F
T

T a leap year
print print not a leap
year
year

Stop

Dept of CSE 14 CPLab Manual_15CPL16/26


Global Academy of Technology

Algorithm:

Program 3b:

#include<stdio.h>

void main()
{
int year;

printf("Enter a year to check if it is a leap year\n");


scanf("%d", &year);

if ( ( year%400 == 0) ||(((year%400!=0) &&( year%100 != 0)) || (year%4 == 0 )))


printf("%d is a leap year.\n", year);
else
printf("%d is not a leap year.\n", year);

getch();

SAMPLE INPUT / OUTPUT:

Run 1: Run 2:
Enter a year to check if it is a leap year Enter a year to check if it is a leap year
2010 2008
2010 is not a leap year. 2008 is a leap year.

Dept of CSE 15 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 16 CPLab Manual_15CPL16/26


Global Academy of Technology

4. Design, develop and execute a program in C to evaluate the given polynomial, f(x) =
a4x4+a3x3+a2x2+a1x+a0, for a given value of x and coefficients using Horner’s
method.Implement a C program for the same and execute the program with different set of
values of coefficients and x.

Theory:
A univariate polynomial function has the following form:

For example if k = 4 the order of the polynomial is 4 and the function has the following form:

Horner's method is commonly used to find the roots of a polynomial function. However it can
also be used to evaluate the polynomial function for a given value of x.

The main goal of the Horner scheme is to reduce the number of multiplications needed by
isolating the variable (in this case x).

A concrete example:

The main advantage here is that when using Horner's method it is not necessary to use a power
function to evaluate the variable x.

Algorithm:

Dept of CSE 17 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart:

Start

Read n , x

F i←0
i+1 i<=n

T
Read a[i]

result ← a[n]

F i← n-1
i-1 i>=0

T
result ←result*x+a[i]

Print result

Stop

Dept of CSE 18 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 4:

#include<stdio.h>

void main()
{
int n,i;
float a[30],x,result;

printf("Enter maximum Degree of polynomial \n"); // read the polynomial


scanf("%d",&n);

printf("Enter Co-efficients of the polynomial\n");


for(i=0;i<=n;i++)
scanf("%f",&a[i]);

printf("Enter the value for x\n");


scanf("%f",&x);

result=a[n];

for(i=n-1;i>=0;i--) // to calculate and print the polynomial using Horner’s rule


result=result*x+a[i];
printf("Evaluated result=%f\n",result);

getch();
}

SAMPLE INPUT / OUTPUT:


RUN 1:
Enter maximum Degree of polynomial
5
Enter Co-efficients of the polynomial
654321
Enter the value of x….
1
Evaluated result =21.000000

RUN 2:
Enter maximum Degree of polynomial
4
Enter Co-efficients of the polynomial
54321
Enter the value of x….
1
Evaluated result =15.000000

Dept of CSE 19 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 20 CPLab Manual_15CPL16/26


Global Academy of Technology

5. Draw the flowchart and Write a C Program to compute Sin(x) using Taylor series
approximation given by
Sin(x) = x - (x3/3!) + (x5/5!) - (x7/7!) + …….

Algorithm:

Step 1: Read x in degrees


Step 2: Convert x to radians
x=x*3.14/180
Step 3: for ( i = 1 to 100)
term = (-term*x*x)/((2*i)*(2*i+1))
sum = sum + term
Step 4: Print sum as sin(x) using Taylor Series
Step 5: stop

Flowchart:

Dept of CSE 21 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 5:

#include<stdio.h>
#include<conio.h>

void main()
{
float x, sum,term,;
int n,i;

printf("Enter the value x in degrees:");


scanf("%f", &x);

x=x*3.14/180; /* convert to radians */


sum=term=x; /* first term and initial sum*/

for(i=1;i<100;i++)
{
term=(-term*x*x)/((2*i)*(2*i+1)); /* next term*/
sum=sum+term;
}

printf("The sine value is %f", sum);


getch();
}

SAMPLE INPUT / OUTPUT:


Run 1:
Enter the value x in degrees:
45
The sine value is 0.706825

Run 2:
Enter the value x in degrees:
90
The sine value is 1.000000

Dept of CSE 22 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 23 CPLab Manual_15CPL16/26


Global Academy of Technology

Compare your result with the built- in Library function. Print both the results with
appropriate messages.

Algorithm:
Step 1: Read x in degrees
Step 2: Convert x to radians
x=x*3.14/180
Step 3: for ( i = 1 to 100)
term = (term*x*x)/((2*i)*(2*i+1))
sum = sum + term
Step 4: Print sum as sin(x) using Taylor Series
Step 5: Print The sine value from built in function is sin(x)
Step 6: Stop

Flowchart:
Start

Read x in degrees

x←x*3.14/180
sum← term←x

F
i←1
i←i + 1 i<100

term← (-term*x*x)/((2*i)*(2*i+1))
sum←sum + term

Print sum as sin(x)

sum←sin(x)

Print built-in sine value


n sin(x)

Stop

Dept of CSE 24 CPLab Manual_15CPL16/26


Global Academy of Technology

Program:

#include<stdio.h>
#include<math.h>

void main()
{
float x, sum,term;
int n,i;

printf("Enter the value x in degrees:");


scanf("%f", &x);

x=x*3.14/180; /* convert to radians */


sum=term=x;

for(i=1;i<100;i++)
{
term=(-term*x*x)/((2*i)*(2*i+1));
sum=sum+term;
}

printf("The sine value is %f \n", sum);


sum = sin(x); /* built – in library function */

printf("The sine value from built-in function is %f \n",sum);


getch();
}

SAMPLE INPUT / OUTPUT:

Run 1:
Enter the value x in degrees:
45
The sine value is 0.706825
The sine value from built-in function is 0.706825

Run 2:
Enter the value x in degrees:
90
The sine value is 1.000000
The sine value from built-in function is 1.000000

Dept of CSE 25 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 26 CPLab Manual_15CPL16/26


Global Academy of Technology

6. Develop an algorithm, implement and execute a C program that reads N integer numbers
and arrange them in ascending order using Bubble Sort.

Theory:
Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be
sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order.
The pass through the list is repeated until no swaps are needed, which indicates that the list is
sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list.
Because it only uses comparisons to operate on elements, it is a comparison sort.

Algorithm :

Dept of CSE 27 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart:

Start

Read n

Read n elements

F
i←0
i←i + 1 i<n
T

Read a[i]

Print sorted
Print n
array
elements

i←0
i←i + 1 i<n i ←0 i<n
F
i ←i+1
T i ←i+1
Print a[i] Print a[i]

F j←1
j←j+ 1 j<n

T
Stop
F
i←0
i←i+ 1 i < n-j

T
F is
a[i]>a[i+1] ?

T
temp ←a[i]
a[i] ←a[i+1]
A a[i+1] ←temp

Dept of CSE 28 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 6:

#include<stdio.h>
#include<conio.h>

void main()
{
int n,i,j,temp,a[10],k;
printf("Enter the number of elements\n");
scanf("%d",&n);

printf("Enter the elements to sort\n"); /* read the array to be sorted */


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

printf("Given array:\n"); /* printing the array accepted as input */


for(i=0;i<n;i++)
printf("%d\n",a[i]);

/* Function to sort the elements */


for(j=1;j<n;j++) /* n-1 passes */
{
for(i=0;i<n-j;i++) /* comparisons */
{
if(a[i]>a[i+1])
{
temp=a[i]; /* exchange of elements if a[i] is greater than a[i+1]*/
a[i]=a[i+1];
a[i+1]=temp;
}
}
}

printf("Sorted array:\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}

Dept of CSE 29 CPLab Manual_15CPL16/26


Global Academy of Technology

SAMPLE INPUT / OUTPUT:

Run 1:
Enter the number of elements
3
Enter the elements to sort
26
51
8

Given array:
26
51
8

Sorted array:
8
26
51

Run 2:
Enter the number of elements
5
Enter the elements to sort
88
36
5
99
2

Given array:
88
36
5
99
2

Sorted array:
2
5
36
88
99

Dept of CSE 30 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 31 CPLab Manual_15CPL16/26


Global Academy of Technology

7. Develop, implement and execute a C program that reads two matrices A (m x n ) and B (p x
q ) and Compute product of matrices A and B. Read matrix A and matrix B in row major
order and in column major order respectively. Print both the input matrices and resultant
matrix with suitable headings and output should be in matrix format only. Program must
check the compatibility of orders of the matrices for multiplication. Report appropriate
message in case of incompatibility.

Algorithm:

Step 1: Read m,n


Read p,q

Step 2: if (n!=p)
print “Aborting!!!!!! Multiplication Of The Above Matrices Not Possible.”
goto step 7
else
print “multiplication possible”

Step 3: for(i=0 to m)
for(j=0 to n)
Read a[i][j]
end for
end for
for (j=0 to q)
for (i=0 to p)
Read b[j][i]
end for
end for

Step 4: for (i=0 to m)


for(j=0 to q)
c[i][j]=0
end for
end for

Step 5: for(k=0 to n)
c[i][j] =c[i][j]+a[i][k]*b[k][j]
end for

Step 6: print ”multiplication of a[i][j] & b[i][j] is”


for (i=0 to m)
for (j=0 to q)
print (c[i][j])
end for
end for
Step 7: Stop

Dept of CSE 32 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart:

Dept of CSE 33 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 7:

#include<stdio.h>
#include<conio.h>

void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;

printf("Enter The Rows And Columns Of The First Matrix:");


scanf("%d %d",&m,&n);

printf("\nEnter The Rows And Columns Of The Second Matrix:");


scanf("%d %d",&p,&q);

if(n!=p)
{
printf("Aborting!!!!!!\nMultiplication of the Above Matrices Not Possible.");
getch();
exit(0);
}
else
printf("Multiplication Is Possible\n");

printf("\nEnter Elements Of The First Matrix:\n");


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

printf("\nEnter Elements Of The Second Matrix:\n");


for(j=0;j<q;j++)
{
for(i=0;i<p;i++)
scanf("%d", &b[j][i]);
}

printf("The First Matrix Is:\n");

for(i=0;i<m;i++)
{
for(j=0;j<n;j++) //print the first matrix
{
printf(" %d\t ",a[i][j]);
}

Dept of CSE 34 CPLab Manual_15CPL16/26


Global Academy of Technology

printf("\n");
}
printf("The Second Matrix Is:\n");

for(i=0;i<p;i++)
{
for(j=0;j<q;j++) //print the second matrix
{
printf(" %d\t ",b[i][j]);
}
printf("\n");
}

for(i=0;i<m;i++) /* for each row in result matrix C*/


{
for(j=0;j<q;j++) /* for each column in result matrix C*/
{
c[i][j] = 0;
for(k=0;k<n;k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}

printf("\nmultiplication Of The Above Two Matrices Are:\n\n");

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf(" %d\t ",c[i][j]);
}
printf("\n");
}

getch();
}

Dept of CSE 35 CPLab Manual_15CPL16/26


Global Academy of Technology

SAMPLE INPUT / OUTPUT:

Run 1:
Enter The Rows And Columns Of The First Matrix: 2 2

Enter The Rows And Columns Of The Second Matrix: 2 2

Multiplication Is Possible

Enter Elements Of The First Matrix:


1 1
1 1

Enter Elements Of The Second Matrix:


1
2
3
4

The First Matrix Is:


1 1
1 1

The Second Matrix Is:


1 3
2 4

Multiplication Of The Above Two Matrices Are:


3 7
3 7

Run 2:
Enter The Rows And Columns Of The First Matrix: 2 2

Enter The Rows And Columns Of The Second Matrix: 3 2

Aborting!!!!!!
Multiplication of the Above Matrices Not Possible.

Dept of CSE 36 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 37 CPLab Manual_15CPL16/26


Global Academy of Technology

8. Develop, implement and execute a C program to search a Name in a list of names using
Binary searching Technique.

Theory:
In computer science, a binary search is an algorithm for locating the position of an item in a
sorted array. The idea is simple: compare the target to the middle item in the list. If the target
is the same as the middle item, you've found the target. If it's before the middle item, repeat
this procedure on the items before the middle. If it's after the middle item, repeat on the items
after the middle
Algorithm:
1. get the middle element;
2. if the middle element equals to the searched value, the algorithm stops;
3. otherwise, two cases are possible:
case1: searched value is less, than the middle element. In this case, go to the step 1 for the part
of the array, before middle element.
case 2: searched value is greater, than the middle element. In this case, go to the step 1 for the
part of the array, after middle element.

Algorithm:

step 1: read n

step 2: for (i=0 to n in steps of 1) do


read a[i]
end for

step 3: read key

step 4: low = 0,high = n-1


mid = (low+high)/2

step 5: while(key != a[mid] and low <= high)


if(key > a[mid])
low = mid + 1
if(key<a[mid])
high=mid-1;
mid=(low+high)/2;
end while

step 6: if (key == a[mid]


write “search is successful, key found”
else
print “search is unsuccessful, key not found”
end if else

step 7: stop

Dept of CSE 38 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart:

Dept of CSE 39 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 8:

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,low,high,mid;
char a[20][20], key[20];

printf("Enter the number of names:\n");


scanf("%d",&n);

printf("Enter the names in lexicographic (alphabetical) order as in dictionary:\n");


for(i=0;i<n;i++)
scanf("%s",&a[i]);

printf("Enter the key name to be searched:\n");


scanf("%s",&key);

low=0; /* initial position of array */


high=n-1; /* end point or last position of array */
mid=(low+high)/2; /* finding the midpoint of the array */

while((strcmp(key,a[mid])!= 0)&&low<=high)
{
if(strcmp(key,a[mid]) > 0)
low=mid+1;
if(strcmp(key,a[mid]) < 0)
high=mid-1;
mid=(low+high)/2;
}

if(strcmp(key,a[mid]) == 0) /* comparing the string to check if they are same */


printf("Search is successful. Key name is found\n");
else
printf("Search is not successful. Key name is not found\n");

getch();
}

Dept of CSE 40 CPLab Manual_15CPL16/26


Global Academy of Technology

SAMPLE INPUT / OUTPUT:

Run 1:
Enter the number of names:
5

Enter the names in lexicographic (alphabetical) order as in dictionary:


arjun
bindu
chaitra
darshan
deepa

Enter the key name to be searched:


deepa

Search is successful. Key name is found.

Run 2:
Enter the number of names:
4

Enter the names in lexicographic (alphabetical) order as in dictionary:


dick
john
ruth
sam

Enter the key name to be searched:


rose

Search is not successful. Key name is not found

Dept of CSE 41 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 42 CPLab Manual_15CPL16/26


Global Academy of Technology

9. Write and execute a C program that,


i. Implements string copy operation STRCOPY (str1, str2) that copies a string str1 to another
string str2 without using library function.
ii. Read a sentence and print frequency of vowels and total count of consonants.

9 i:

Algorithm:

Step 1: Read string str1


Step 2: Print string str1
Step 3:strcopy(str1,str2)
for i=0 to str1[i]!=’\0’
str2[i]=str1[i]
i++
str2[i]=’\0’
Step 4: print str2
Step 5: Stop

Flowchart:
strcopy(str1,str2)
Start

read str1 F i← 0 str1[i]


!= '\0'

i ← i+1
strcopy(str1,str2)
T

str2[i] ←str1[i]
i←i+1
Print str2

str2[i] ←’\0’
Stop

return

Dept of CSE 43 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 9 i:

#include<stdio.h>

void strcopy(char[],char[]);

int main()
{
char str1[100],str2[100];
printf("Enter any string: ");
gets(str1);
strcopy(str1,str2);
printf("After copying: %s",str2);
return 0;
}

void strcopy(char str1[],char str2[])


{
int i;
for(i = 0; str1[i] != '\0'; ++i)
str2[i] = str1[i];
str2[i] = '\0';
}

SAMPLE INPUT / OUTPUT:

Enter any string: global


After copying: global

OUTPUT:

Dept of CSE 44 CPLab Manual_15CPL16/26


Global Academy of Technology

9 ii:

Algorithm:

Step1: Read a line of string


Step2: for i=0 to end of line
Step3: check isalpha buit-in function and convert to lowercase using tolower() function.
Step4: check the condition for all the vowels(a,e,i,o,u) using if statement
Step5: Increment the count of vowels & consonants.
Step 3: print count of vowels.
Step 4: print count of consonants
Step 5: stop

Dept of CSE 45 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart
Start

Read string

F i ←0 i<strlen(s)

i← i+1

T
B

is F
isalpha(s[i])?

T
ch=tolower(s[i])

is
ch == ‘a’ || ch == ‘e’ ||
ch ==’i’ ||
F ch ==’o’|| ch ==’u’? T
T
Consonants++ vowels++
else

print count of
vowels and
consonants

Stop

Dept of CSE 46 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 9ii:

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

void main()
{
char s[150], ch;
int i,vowels=0, consonants=0;

printf("Enter a string:\n");
gets(s);

for(i=0;i < strlen(s);i++) /* to check the string with vowels and consonants */
{
if( isalpha(s[i]))
{
ch=tolower(s[i]);
if(ch == ‘a’ || ch == ‘e’ || ch ==’i’ || ch ==’o’|| ch ==’u’)
vowels++;
else
consonants++;
}
}

printf(" No of vowels in the given string is %d\n”, vowels);


printf(" No of consonants in the given string is %d\n”, consonants);

getch();

SAMPLE INPUT / OUTPUT:

Run 1:
Enter a string:
Global academy of technology
No of vowels in the given string is: 9
No of consonants in the given string is: 16

Run 2:
Enter a string:
C programming lab
No of vowels in the given string is: 4
No of consonants in the given string is: 11

Dept of CSE 47 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 48 CPLab Manual_15CPL16/26


Global Academy of Technology

10. a. Design and develop a C function RightShift(x ,n) that takes two integers x and n as input
and returns value of the integer x rotated to the right by n positions. Assume the integers are
unsigned. Write a C program that invokes this function with different values for x and n and
tabulate the results with suitable headings.

Algorithm:

Step 1: Read value of x

Step 2: Read no. of bits ‘n’ to be rotated

Step 3: result = rightrot(x,n)


goto step 5

Step 4: Print “the rotated value”


goto step 6

Step 5: Read i

for(i=1 to n)
if(x%2==0)
x=x>>1;
else
x=x>>1;
x+=32768;
end if
return x to step 4

Step 6: Stop

Dept of CSE 49 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart:

Dept of CSE 50 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 10 a:

#include<stdio.h>
#include<conio.h>

unsigned int rightrot(unsigned int x, int n); // function declaration

void main()
{
unsigned int x,res;
int n;

printf("Enter the value of x\n");


scanf("%u", &x);

printf("Enter the no. of bits to be rotated\n");


scanf("%d", &n);

res = rightrot(x,n); //function call

printf("\nThe Rotated Value is = %u\n", res);


getch();
}

unsigned int rightrot(unsigned int x, int n) // function definition


{
int i;
for(i=1;i<=n;i++) // performs n rotation
{
if(x%2==0) // for even number last bit will be zero
x=x>>1;
else
{ // for odd number last bit will be one
x=x>>1;
x+=32768;
}
}
return x;
}

Dept of CSE 51 CPLab Manual_15CPL16/26


Global Academy of Technology

SAMPLE INPUT / OUTPUT:

Run 1
Enter the value of x
4
Enter the no. of bits to be rotated
2
The Rotated Value is = 1

Run 2
Enter the value of x
15
Enter the no. of bits to be rotated
1
The Rotated Value is = 32775

OUTPUT:

Dept of CSE 52 CPLab Manual_15CPL16/26


Global Academy of Technology

10 b. Design and develop a C function isprime(num) that accepts an integer argument and
returns 1 if the argument is prime, a 0 otherwise. Write a C program that invokes this function
to generate prime numbers between the given range.

Algorithm:

Dept of CSE 53 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart :

isprime(i)
Start

T
is Return 0
Read n1,n2
n=1||n=0?

F
F
i ←n1 i<=n2
i←2 F
i←i+1 i<=n/2

i←i+1
T

T
is F
isprime(i)? F is T Return 0
n%i==0?

print i Return 1

Stop

Dept of CSE 54 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 10 b:

#include<stdio.h>
#include<conio.h>

int isprime(int); // function declaration

void main()
{
int i,n1,n2;

printf("Enter the range");


scanf("%d%d",&n1,&n2);

for(i=n1;i<=n2;i++)
{
if(isprime(i)) // function call
printf("%d\t",i);
}
getch();
}

int isprime(int n) //function definition


{
int i;
if(n==1 || n==0)
return 0;

for(i=2;i<=n/2;i++) /* calculation of prime numbers from the range of numbers */


{
if(n%i==0)
return 0;
}
return 1;
} // end of function

SAMPLE INPUT / OUTPUT:

Run 1:
Enter the range 1 10
2357

Run 2:
Enter the range 0 15
2 3 5 7 11 13

Dept of CSE 55 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 56 CPLab Manual_15CPL16/26


Global Academy of Technology

11. Draw the flowchart and write a recursive C function to find the factorial of a number, n!,
defined by fact(n)=1, if n=0. Otherwise fact (n) =n*fact (n-1). Using this function, write a C
program to compute the binomial coefficient nCr. Tabulate the results for different values of n
and r with suitable messages.

Algorithm:

Step 1: Read n and r


Step 2: ncr =fact(n)/(fact(n-r)*fact(r))
Step 3: fact(n) : if (n==0 or n==1) return 1 else return(n*fact(n-1));
Step 4: Print Binomial Coefficient nCr
Step 5: stop

Flowchart:

Dept of CSE 57 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 11:

#include<stdio.h>
#include<conio.h>

long int fact(long int); // function declaration

void main()
{
long int n,r,ncr;

printf("\n Enter n and r values:");


scanf("%ld%ld",&n,&r);

ncr=fact(n)/(fact(n-r)*fact(r)); //function call

printf("\n Binomial co-efficient : %ld",ncr);

getch();

long int fact(long int x) //function definition, recursive nature


{
if(x==0)
return 1;
else
return(x*fact(x-1));
} // end of function factorial

SAMPLE INPUT / OUTPUT:


Run 1:
Enter n and r values: 5 2
Binomial co-efficient: 10

Run 2:
Enter n and r values: 12 4
Binomial co-efficient: 495

Dept of CSE 58 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 59 CPLab Manual_15CPL16/26


Global Academy of Technology

12. Given two university information files “studentname.txt” and “usn.txt” that contains
students Name and USN respectively. Write a C program to create a new file called
“output.txt” and copy the content of files “studentname.txt” and “usn.txt” into output file in
the sequence shown below. Display the contents of output file “output.txt” on to the screen.
Student Name USN
Name 1 USN1
Name 2 USN2

Algorithm:

Step 1: Input student names and usn into studentname.txt and usn.txt respectively.

Step 2: Open files.

Step 3: If any error in opening files. Report error and exit.

Step 4: While (read a character from file 1and continue till not end of file and read a character
from file 2and continue till not end of file)

Step5: Copy the character into a new file output.txt.

Step 6: Open output.txt in read mode to output the characters on console.

Step 7: While (read characters from output.txt file till not end of file) and display it on the
console

Step 8: Close all files.

Dept of CSE 60 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart:
Start

Enter name in studentname.txt


Enter USN in usn.txt

Open studentname.txt in read mode


Open usn.txt in read mode

Is T
fp1==NULL Print file
|| not found
fp2==NULL?

F
Open output.txt in write mode

Is
(fscanf(fp1,"%s",
name)!=EOF) F
&&
(fscanf(fp2,"%s",
usn)!=EOF)? fclose output.txt

Open output.txt in read mode

T
fprint name and usn in output.txt
Is
fscanf(fp3,"%s%s",
name,usn)!=EOF?
F

Print name & usn on


console

Stop
Close all files

Dept of CSE 61 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 12:

#include<stdio.h>
#include<stdlib.h>

int main()
{
FILE *fp1,*fp2,*fp3;
char name[20],usn[20];

fp1=fopen("studentname.txt","r"); /*Open studentname.txt in read mode*/


fp2=fopen("usn.txt","r"); /* Open usn.txt in read mode*/

if(fp1==NULL|| fp2==NULL) /* error in opening files*/


{
printf("File not found\n");
exit(0);
}

fp3=fopen("output.txt","w"); /*Open output.txt in write mode*/

while(fscanf(fp1,"%s",name)!=EOF && fscanf(fp2,"%s",usn)!=EOF)


{
fprintf(fp3,"%s\t%s\n",name,usn);
}

fclose(fp3);

fp3=fopen("output.txt","r");

printf(“Files are merged into third file successfully\n”);


printf("NAME\t\t\tUSN\n");

while(fscanf(fp3,"%s%s",name,usn)!=EOF)
{
printf("%s\t\t\t%s\n",name,usn); /*output characters to console*/
}

fclose(fp1);
fclose(fp2);
fclose(fp3);
}

Dept of CSE 62 CPLab Manual_15CPL16/26


Global Academy of Technology

SAMPLE INPUT / OUTPUT:

Create two files with required content:


1. studentname.txt sample content:Student Name
Aarthi
Archana
2. usn.txt sample content: USN
1GA10CS001
1GA10CS002

RUN 1:
Files are merged into third file successfully
NAME USN
Aarthi 1GA10CS001
Archana 1GA10CS002

Check output.txt file will be created with contents:


Aarthi 1GA10CS001
Archana 1GA10CS002

RUN 2:
File not found.

Dept of CSE 63 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 64 CPLab Manual_15CPL16/26


Global Academy of Technology

13. Write a C program to maintain a record of “n” student details using an array of structures
with four fields (Roll number, Name, Marks, and Grade). Each field is of an appropriate data
type. Print the marks of the student given student name as input.

Algorithm:

Step 1: Input the number of students and read student data in terms of roll number, student name,
marks and grade respectively.

Step 2: Display information of students.

Step 3: Input the name of the student to be searched

Step 4: If the name exists then print the student is in list and also marks .

Step5: Else display student is not in list.

Step 6: Stop.

Dept of CSE 65 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart:

Dept of CSE 66 CPLab Manual_15CPL16/26


Global Academy of Technology

Program 13:

#include <stdio.h>

struct student
{ // structure definition
char name[50];
int roll;
int marks;
char grade[2];
}; // end of structure definition

int main()
{
struct student s[100]; // s is an array of structure
char searchname[50];
int i, n;

printf("Enter the number of students:\n");


scanf("%d", &n);

printf("Enter information of students:\n");


for(i=0;i<n;++i)
{
printf("\nFor %d Student\n",i+1);
printf("\nEnter roll number \n");
scanf("%d",&s[i].roll);
printf("Enter name: ");
scanf("%s",&s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("Enter grade: ");
scanf("%s",&s[i].grade);

printf("\n");
}

printf("Displaying information of students:\n\n");


for(i=0;i<n;++i)
{
printf("\nFor %d Student\n",i+1);
printf("Roll number: %d\n", s[i].roll);
printf("Name: %s\n", s[i].name);
printf("Marks: %d\n", s[i].marks);
printf("Grade: %s\n", s[i].grade);
printf("\n");
}

Dept of CSE 67 CPLab Manual_15CPL16/26


Global Academy of Technology

printf("Enter the Search Name of the Student :");


scanf("%s",&searchname);

for(i=0;i<n;++i)
{ /* string comparison, check against all student names until found */
if (strcmp( s[i].name, searchname ) == 0)
{
printf("%s is in the List and her marks is %d\n",s[i].name,s[i].marks);
getch();
return 0;
}
}

printf("%s Student is not in the List\n", searchname);


getch();
return 0;
}

SAMPLE INPUT / OUTPUT:

Run1:
Enter the number of students:
1
Enter information of students:

For 1 Student

Enter roll number


12
Enter name: nita
Enter marks: 97
Enter grade: A

Displaying information of students:

For 1 Student
Roll number: 12
Name: nita
Marks: 97
Grade: A

Enter the Search Name of the Student :nita


nita is in the List and her marks is 97

Dept of CSE 68 CPLab Manual_15CPL16/26


Global Academy of Technology

Run2:
Enter the number of students:
2
Enter information of students:

For 1 Student

Enter roll number


1234
Enter name: kusum
Enter marks: 56
Enter grade: C

For 2 Student

Enter roll number


1235
Enter name: Lata
Enter marks: 90
Enter grade: A

Displaying information of students:

For 1 Student
Roll number: 1234
Name: kusum
Marks: 56
Grade: C

For 2 Student
Roll number: 1235
Name: Lata
Marks: 90
Grade: A

Enter the Search Name of the Student :Leena


Leena Student is not in the List

Dept of CSE 69 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 70 CPLab Manual_15CPL16/26


Global Academy of Technology

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

Algorithm:

Dept of CSE 71 CPLab Manual_15CPL16/26


Global Academy of Technology

Flowchart:
start

Read size of array

a ← (int *) malloc(n * sizeof(int))


i←0

Read list of elements in


the array

F i←0
i<n
i←i+1
T

read a+i

F i←0
i<n
i←i+1

sum ← sum + *(a + i)

mean ← (float)sum / (float)n

F
i←0 i<n
i←i+1
T
var ← (*(a + i)) - (int)mean
num ← num + var*var
A

Dept of CSE 72 CPLab Manual_15CPL16/26


Global Academy of Technology

variance ← (float)num / (float)n


std_dev ← sqrt(variance)

Print Sum, Mean and Standard


Deviation

Stop

Program 14:

#include <stdio.h>
#include <malloc.h>
#include<math.h>

void main()
{
int i, n, sum = 0, num = 0, var;
float mean, std_dev, variance;
int *a;

printf("Enter the size of array A \n");


scanf("%d", &n);

a = (int *) malloc(n * sizeof(int)); //dynamic memory allocation for the array

printf("Enter Elements of Array \n");


for (i = 0; i< n; i++)
{
scanf("%d", a + i); //read individual element into array
}

/* Compute the sum of all elements in the given array */

for (i = 0; i< n; i++)


{
sum = sum + *(a + i);
}

Dept of CSE 73 CPLab Manual_15CPL16/26


Global Academy of Technology

mean = (float)sum / (float)n;

/* Compute the standard deviation of the given array */


for (i = 0; i< n; i++)
{
var = (*(a + i)) - (int)mean;
num = num + var*var;
}

variance = (float)num / (float)n;


std_dev = sqrt(variance); //use standard built-in method to find square root

printf("\nSum is %d \t",sum);
printf("\nMean is %f \t",mean);
printf("\nStandard Deviation is %f \n",std_dev);

free(a); //de-allocate memory of the array

getch();

return;
}

SAMPLE INPUT / OUTPUT:

Run 1:
Enter the size of array A
5
Enter Elements of Array
1 2 30 5 4
Sum is 42
Mean is 8.400000
Standard Deviation is 10.899542

Run 2:
Enter the size of array A
4
Enter Elements of Array
12 14 16 18
Sum is 60
Mean is 15.00000
Standard Deviation is 2.236068

Dept of CSE 74 CPLab Manual_15CPL16/26


Global Academy of Technology

OUTPUT:

Dept of CSE 75 CPLab Manual_15CPL16/26


Global Academy of Technology

Possible set of Viva Questions

1) What is a flowchart?
2) What is an Algorithm?
3) What is recursion?
4) What are advantages of flow charts?
5) What are different symbols in flowcharts?
6) What is a connector symbol?
7) Is the following assignment correct? A==10;
8) char a=”r”; Is the declaration correct?
9) What is the maximum length of variable?
10) Can a C keyword used as a variable name?
11) What does an expression contains?
12) How is an expression evaluated?
13) What does the modulus performs?
14) Name different logical operators.
15) What is syntax of conditional operator?
16) Is the scanf statement correct? scanf(“%s”,&a);
17) What is a variable?
18) How a variable is declared?
19) What is a constant?
20) List some valid logical expression.
21) What is the difference between post and pre increment/decrement?
a) when they are stand alone
b) when they are embed in an expression
22) What is a keyword?
23) What are Literals?
24) What are two categories of C constants?
25) What is the range of integer constant?
26) What is the output of printf("%d") ?
27) Is there a similarity between for and while?
28) Difference between if-else if ladder and switch
29) What is ternary operator? Write the syntax
30) Difference between while and do-while
31) In what scenario we have to apply for loop?
32) Does break exits from the two loops?
33) How does continue work?
34) What is string? Difference between string and char
35) Difference between array and linked-lists?
36) Difference between linked-lists and trees?

Dept of CSE 76 CPLab Manual_15CPL16/26


Global Academy of Technology

37) What do you mean by abstract data-type?


38) Name some dynamic memory allocation methods
39) What is the use of free()?
40) What is a pointer?
41) What is NULL pointer?
42) What is the use of return statement?
43) Explain the function signature.
44) How does a stack work?
45) Difference between stack and queue?
46) What is dangling pointer in c?
47) What will be output of following c program?
void main()
{
int *ptr;
printf("%u\n",ptr);
printf("%d",*ptr);
}
48) Write a c program without using any semicolon which output will : Hello word.
49) Swap two variables without using third variable.
50) Swap two variables using built in function.

Dept of CSE 77 CPLab Manual_15CPL16/26

You might also like