0% found this document useful (0 votes)
55 views58 pages

PPS Lab Manual for C Programming

Uploaded by

laxminayanan546
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)
55 views58 pages

PPS Lab Manual for C Programming

Uploaded by

laxminayanan546
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/ 58

KOMMURI PRATAP REDDY INSTITUTE OF TECHNOLOGY

(COLLEGE OF ENGINEERING)

PROGRAMMING FOR PROBLEM SOLVING LAB MANNUAL

LAB MANUAL

B.TECH(I YEAR–II SEM)


R18 REGULATION
(Common for CSE, CSE(AI&ML),CSE(DS),IT, EEE)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

(ARTIFICAL INTELLIGENCE &MACHINE LEARNING)

PPS LAB MANUAL


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

PROGRAMMING FOR PROBLEM SOLVING LAB

[Note:The programs may be executed using any available Open Source/ Freely available IDE
Some of the Tools available are:
CodeLite: https://codelite.org/
Code::Blocks: http://www.codeblocks.org/
DevCpp : http://www.bloodshed.net/devcpp.html
Eclipse: http://www.eclipse.org
This list is not exhaustive and is NOT in any order of preference]

Course Objectives: The students will learn the following:


To work with an IDE to create, edit, compile, run and debug programs
To analyze the various steps in program development.
To develop programs to solve basic problems by understanding basic concepts in C
like operators, control statements etc.
To develop modular, reusable and readable C Programs using the concepts like
functions, arrays etc.
To Write programs using the Dynamic Memory Allocation concept.
To create, read from and write to text and binary files

Course Outcomes: The candidate is expected to be able to:


formulate the algorithms for simple problems
translate given algorithms to a working and correct program
correct syntax errors as reported by the compilers
identify and correct logical errors encountered during execution
represent and manipulate data with arrays, strings and structures
use pointers of different types
create, read and write to and from simple text and binary files
modularize the code with functions so that they can be reused

SYLLABUS:

Practice sessions:
a. Write a simple program that prints the results of all the operators available in C (including
pre/ post increment , bitwise and/or/not , etc.). Read required operand values from standard
input.
b. Write a simple program that converts one given data type to another using auto conversion
and casting. Take the values form standard input.
Simple numeric problems:
a. Write a program for fiend the max and min from the three numbers.
b. Write the program for the simple, compound interest.
c. Write program that declares Class awarded for a given percentage of marks, where mark
<40%= Failed, 40% to <60% = Second class, 60% to <70%=First class, >=70% =
Distinction. Read percentage from standard input.
d. Write a program that prints a multiplication table for a given number and the number of
rows in the table. For example, for a number 5 and rows = 3, the output should be:

PPS LAB MANUAL


e. 5 x 1 = 5
f. 5 x 2 = 10
g. 5 x 3 = 15
h. Write a program that shows the binary equivalent of a given positive number between 0 to
255.
Expression Evaluation:
a. A building has 10 floors with a floor height of 3 meters each. A ball is dropped from the top of
the building. Find the time taken by the ball to reach each floor. (Use the formula s = t+(1/2)at^2
where u and a are the initial velocity in m/sec (= 0) and acceleration in m/sec^2 (= 9.8 m/s^2)). b.
Write a C program, which takes two integer operands and one operator from the user, performs
the operation and then prints the result. (Consider the operators +,-,*, /, % and use Switch
Statement)
c. Write a program that finds if a given number is a prime number
d. Write a C program to find the sum of individual digits of a positive integer and test given number
is palindrome.
e. A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0 and
1. Subsequent terms are found by adding the preceding two terms in the sequence. Write a C
program to generate the first n terms of the sequence.
f. Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied
by the user.
g. Write a C program to find the roots of a Quadratic equation.
h. Write a C program to calculate the following, where x is a fractional value.
i. 1-x/2 +x^2/4-x^3/6
j. Write a C program to read in two numbers, x and n, and then compute the sum of this
geometric progression: 1+x+x^2+x^3+………….+x^n. For example: if n is 3 and x is
5, then the program computes 1+5+25+125.
Arrays and Pointers and Functions:
a. Write a C program to find the minimum, maximum and average in an array of integers.
b. Write a functions to compute mean, variance, Standard Deviation, sorting of n elements in
single dimension array.
c. Write a C program that uses functions to perform the following:
d. Addition of Two Matrices
e. ii. Multiplication of Two Matrices
f. iii. Transpose of a matrix with memory dynamically allocated for the new matrix as
row and column counts may not be same.
g. Write C programs that use both recursive and non-recursive functions
h. To find the factorial of a given integer.
i. ii. To find the GCD (greatest common divisor) of two given integers.
j. iii. To find x^n
k. Write a program for reading elements using pointer into array and display the values using
array.
l. Write a program for display values reverse order from array using pointer.
m. Write a program through pointer variable to sum of n elements from array.

Files:
a. Write a C program to display the contents of a file to standard output device.
b. Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents.

PPS LAB MANUAL


c. Write a C program to count the number of times a character occurs in a text file. The
file name and the character are supplied as command line arguments.
d. Write a C program that does the following: It should first create a binary file and store 10
integers, where the file name and 10 values are given in the command line. (hint: convert the
strings using atoi function) Now the program asks for an index and a value from the user and the
value at that index should be changed to the new value in the file. (hint: use fseek function) The
program should then read all 10 values and print them back.
e. Write a C program to merge two files into a third file (i.e., the contents of the firs t file
followed by those of the second are put in the third file).
Strings:
a. Write a C program to convert a Roman numeral ranging from I to L to its decimal
equivalent. b. Write a C program that converts a number ranging from 1 to 50 to Roman
equivalent c. Write a C program that uses functions to perform the following operations:
d. To insert a sub-string in to a given main string from a given position.
e. ii. To delete n Characters from a given position in a given string.
f. Write a C program to determine if the given string is a palindrome or not (Spelled same in both
directions with or without a meaning like madam, civic, noon, abcba, etc.)
g. Write a C program that displays the position of a character ch in the string S or – 1 if S doesn‘t
contain ch.
h. Write a C program to count the lines, words and characters in a given text.
Miscellaneous:
a. Write a menu driven C program that allows a user to enter n numbers and then choose between
finding the smallest, largest, sum, or average. The menu and all the choices are to be functions.
Use a switch statement to determine what action to take. Display an error message if an invalid
choice is entered.
b. Write a C program to construct a pyramid of numbers as follows:
1
12
123
*
**
***
1
23
456
1
22
333
4444
*
**
***

PPS LAB MANUAL


**
*
Sorting and Searching:
a. Write a C program that uses non recursive function to search for a Key value in a given list of
integers using linear search method.
b. Write a C program that uses non recursive function to search for a Key value in a given sorted
list of integers using binary search method.
c. Write a C program that implements the Bubble sort method to sort a given list of integers
in ascending order.
d. Write a C program that sorts the given array of integers using selection sort in descending
order
e. Write a C program that sorts the given array of integers using insertion sort in ascending order
f. Write a C program that sorts a given array of names

Suggested Reference Books for solving the problems:


i. Byron Gottfried, Schaum’s Outline of Programming with C, McGraw-Hill
ii. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage
Learning, (3rd Edition)
iii. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice
iv. Hall of India
v. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
vi. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
vii. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition

PPS LAB MANUAL


INDEX

Sno Name of the Experiment Page no

1 Write a simple program that prints the results of all the operators available in C
(including pre/ post increment, bitwise and/or/not, etc.). Read required operand
values from standard input. 9
2 Write a simple program that converts one given data type to another using auto
conversion and casting. Take the values form standard input 10
3 Write a program for find the max and min from the three numbers. 11
4 Write the program for the simple, compound interest 12
5 Write program that declares Class awarded for a given percentage of marks, where
mark <40%= Failed, 40% to <60% = Second class, 60% to <70%=First class, >=
70% = Distinction. Read percentage from standard input. 12
6 Write a program that prints a multiplication table for a given number and the
number of rows in the table. 13
7 Write a program that shows the binary equivalent of a given positive number
between 0 to 255 14
8 A building has 10 floors with a floor height of 3 meters each. A ball is dropped
from the top of the building. Find the time taken by the ball to reach each floor. 14
9 Write a C program, which takes two integer operands and one operator from the
user, performs the operation and then prints the result. 15
10 Write a program that finds if a given number is a prime number 16
11 Write a C program to find the sum of individual digits of a positive integer and test
given number is palindrome 17
12 Write a C program to generate the first n terms of the Fibonacci sequence. 18
13 Write a C program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user 18
14 Write a C program to find the roots of a Quadratic equation 19
15 Write a C program to calculate the following, where x is a fractional value. 1-x/2
+x^2/4-x^3/6 19
16 Write a C program to read in two numbers, x and n, and then compute the sum of
this geometric progression: 1+x+x^2+x^3+………….+x^n. 20
17 Write a C program to find the minimum, maximum and average in an array of
integers. 20
18 Write a functions to compute mean, variance, Standard Deviation, sorting of n
elements in single dimension array. 22
19 Write a C program that uses functions to perform the following:
i) Addition of Two Matrices
ii) Multiplication of Two Matrices
iii)Transpose of a matrix 24
Write C programs that use both recursive and non-recursive functions
20 i. To find the factorial of a given integer.
ii. To find the GCD (greatest common divisor) of two given integers.
iii. To find x^n 28

PPS LAB MANUAL


21 Write a program for reading elements using pointer into array and display the
values using array 31
22 Write a program for display values reverse order from array using pointer 31
23 Write a program through pointer variable to sum of n elements from array. 32
24 Write a C program to display the contents of a file to standard output device. 33
25 Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents 33
26 Write a C program to count the number of times a character occurs in a text file.
The file name and the character are supplied as command line arguments. 34
27 Write a C program that does the following:
It should first create a binary file and store 10 integers, where the file name and 10
values are given in the command line. (hint: convert the strings using atoi
function) Now the program asks for an index and a value from the user and the
value at that index should be changed to the new value in the file. (hint: use fseek
function) The program should then read all 10 values and print them back 34
28 Write a C program to merge two files into a third file 37
29 Write a C program to convert a Roman numeral ranging from I to L to its decimal
equivalent 37
30 Write a C program that converts a number ranging from 1 to 50 to Roman
equivalent 39
31 Write a C program that uses functions to perform the following operations:
i) To insert a sub-string in to a given main string from a given position.
ii) To delete n Characters from a given position in a given string. 42
32 Write a C program to determine if the given string is a palindrome or not (Spelled
same in both directions with or without a meaning like madam, civic, noon, abcba,
etc.) 44
33 Write a C program that displays the position of a character ch in the string S or – 1
if S doesn‘t contain ch 44
34 Write a C program to count the lines, words and characters in a given text. 45
35 Write a menu driven C program that allows a user to enter n numbers and then
choose between finding the smallest, largest, sum, or average. The menu and all
the choices are to be functions. Use a switch statement to determine what action to
take. Display an error message if an invalid choice is entered. 46
36 Write a C program to construct a pyramid of numbers as follows
1 * 1 1 *
12 ** 23 22 **
123 *** 456 333 ***
4444 **
* 48
37 Write a C program that uses non recursive function to search for a Key value in a
given list of integers using linear search method 51
38 Write a C program that uses non recursive function to search for a Key value in
given sorted list of integers using binary search method. 52
39 Write a C program that implements the Bubble sort method to sort a given list of
integers in ascending order 53
40 Write a C program that sorts the given array of integers using selection sort in 54

PPS LAB MANUAL


descending order
41 Write a C program that sorts the given array of integers using insertion sort in
ascending order 55
42 Write a C program that sorts a given array of names 56

PPS LAB MANUAL


Practice sessions:

1) Write a simple program that prints the results of all the operators available in C
(including pre/ post increment, bitwise and/or/not, etc.). Read required operand
values from standard input.

Source Code: i) Arithmetic Operators (+,-,*,/,%)


#include<stdio.h>
void main()
{
int a,b;
printf(“Enter a,b values”);
scanf(“%d%d”,&a,&b);
printf(“\nSum is %d”,a+b);
printf(“\n Subtraction is %d”,a-b);
printf(“\nMultiplication is %d”,a*b);
printf(“\nDivision is %d”,a/b);
printf(“\nMod is %d”,a%b);
}

Output:
Enter a,b values 5 3
Sum is 8
Subtraction is 2
Multiplication is 15
Division is 1
Mod is 2

i) Relational Operators, Logical Operators


#include<stdio.h>
void main()
{
int per,a,b;
printf(“\nEnter Percentage”);
scanf(“%d”, &per);
printf(“\n Enter a, b values”);
scanf(“%d%d”,&a,&b);
if(per>=60&&per<70)
printf(“\n First class”);
else
printf(“\nNot First Class”);
if(a==b)
printf(“\na nad b are equal”);
else
printf(“\na and b are not equal”);
}

PPS LAB MANUAL


Output:
Enter Percentage 65
Enter a, b values 6 7
First class
a and b are not equal
ii) Increment and Decrement Operators (++,--) , Bitwise operators (and, or, not)
#include<stdio.h>
void main()
{
int x,y,a,b;
printf(“\n enter x,y values”);
scanf(“%d%d”,&x,&y);
printf(“\n enter a,b values of either 0 or
1”); scanf(“%d%d”,&a,&b);
printf(“\n Post increment is: %d”,x++);
printf(“\n Pre increment is: %d”,++y);
if(a&b)
printf(“\ntrue”);
else
printf(“\nfalse”);
}
Output:
enter x,y values 5 8
enter a,b values of either 0 or 1
11
Post increment is: 5
Pre increment is: 9
true

2) Write a simple program that converts one given data type to another using auto
conversion and casting. Take the values form standard input

Source Code:
#include<stdio.h>
void main()
{
char c;
int a;
float b;
printf("Enter a character");
scanf("%c",&c);
printf("Enter an integer value");
scanf("%d",&a);
printf("Enter a float value");

PPS LAB MANUAL


scanf("%f",&b);
printf("\nimplicit conversion is");
printf("c=%d\n",c);
b=a;
printf("a value is assigned to b as %f\n",b);
printf("Explicit Casting of float b to integer is");
printf("%d\n",(int)b);
getch();
}

Output:
Enter a characterB
Enter an integer value3
Enter a float value5

implicit conversion isc=66


a value is assigned to b as 3.000000
Explicit Casting of float b to integer is3

Simple numeric problems:


3) Write a program for find the max and min from the three numbers.
Source Code:

#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter 3 numbers");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
printf("Maximum number is a = %d",a);
else if(b>c)
printf("Maximum number is b = %d",b);
else
printf("Maximum number is c = %d",c);
if(a<b && a<c)
printf("Minimum number is a = %d",a);
else if(b<c)
printf("Minimum number is b = %d",b);
else
printf("Minimum number is c = %d",c);
getch();
}

PPS LAB MANUAL


Output
Enter 3 numbers 45 1 3
Maximum number is a = 45 Minimum number is b = 1

4) Write the program for the simple, compound


interest. Source code:
#include<stdio.h>
#include<math.h>
int main()
{
float p,q,r,SI,CI;
int n;
printf(“\n Enter the value of Principal p= “);
scanf(“%f”,&p);
printf(“\n Enter the value of rate r=“);
scanf(“%f”,&r);
printf(“\n Enter the value of Period in years n=“);
scanf(“%d”,&n);
SI=((n*p*r)/100);
Printf(“\n Simple Interest SI=%f“,SI);;
q=1+(r/100);
CI=p*pow(q,n)-p;
printf(“\n Compound Interest CI=%f”,
CI); return 0;
}

Output:
Enter the value of Principal p=1000
Enter the value of rate r=12
Enter the value of period in year n=2
Simple interest SI=240.000000
Compound Interest CI= 254.400009

5) Write program that declares Class awarded for a given percentage of marks, where
mark <40%= Failed, 40% to <60% = Second class, 60% to <70%=First class, >=
70% = Distinction. Read percentage from standard input.
Source code:
#include<stdio.h
> void main()
{
int per;
printf("Enter
percentage:");
scanf("%d",&per);
if(per<40)

PPS LAB MANUAL


printf("FAIL");
else if(per>=40&&per<60)
printf("Second CLass");
else if(per>=60&&per<70)
printf("First CLass");
else if(per>=70)
printf("Distinction");
getch();
}

Output:
Enter percentage:63
First CLass

6) Write a program that prints a multiplication table for a given number and the
number of rows in the table. For example, for a number 5 and rows = 3, the output
should be:
5x1=5
5 x 2 = 10
5 x 3 = 15
Source code:
#include<stdio.h
> void main()
{
int n,x,i;
printf("Enter table number
x:"); scanf("%d",&x);
printf("Enter number of rows
n:"); scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d*%d=%d\n",x,i,x*i);
getch();
}

Output:
Enter table number x:5
Enter number of rows n:6
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30

PPS LAB MANUAL


7) Write a program that shows the binary equivalent of a given positive number
between 0 to 255

#include <stdio.h>
int binary_conversion(int);
int main()
{
int num, bin;
printf("Enter a decimal number: ");
scanf("%d", &num);
bin = binary_conversion(num);
printf("The binary equivalent of %d is %d\n", num, bin);
getch();
}
int binary_conversion(int num)
{
if (num == 0)
{
return 0;
}
else
{
return (num % 2) + 10 * binary_conversion(num / 2);
}
}

Output:
Enter a decimal number:15
The binary equivalent of 15 is 1111

PPS LAB MANUAL


Expression Evaluation:

8) A building has 10 floors with a floor height of 3 meters each. A ball is dropped from
the top of the building. Find the time taken by the ball to reach each floor. (Use the
formula s = ut+(1/2)at^2 where u and a are the initial velocity in m/sec (=
0) and acceleration in m/sec^2 (= 9.8 m/s^2)).
Source code:
#include<stdio.h>
#include<math.h>
int time(float t);
int s=3;
float
a=9.8;
main()
{
float t;
t=sqrt((2*s)/a);
printf("time to reach for every floor
%f\n",t); time(t);
getch();

int time(float t)
{
float t1;
s=s+3;
if(s<=30)
{
t1=sqrt((2*s)/a);
printf("time to reach for every floor %f\n",t1-t);
time(t1);
}
}
Output
time to reach for every floor 0.782461
time to reach for every floor 0.324106
time to reach for every floor 0.248695
time to reach for every floor 0.209660
time to reach for every floor 0.184714
time to reach for every floor 0.166994
time to reach for every floor 0.153567
time to reach for every floor 0.142937
time to reach for every floor 0.134249
time to reach for every floor 0.126976

PPS LAB MANUAL


9) Write a C program, which takes two integer operands and one operator from the
user, performs the operation and then prints the result.
(Consider the operators +,-,*, /, % and use Switch Statement)
Source Code:
#include<stdio.h>
void main()
{
int a,b,c;
char ch;
printf("MENU\n 1.Addition + \n 2.Subtraction -\n 3.Multiplication * \n 4.Division / \n 5.Modulo
% \n");
printf("Enter the operator from the given menu list");
scanf("%c",&ch);
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='%')
{
printf("\nEnter a, b Values ");
scanf("%d%d",&a,&b);
}
switch(ch)
{
case '+': c=a+b;
printf("\nSum is %d",c);
break;
case '-':c=a-b;
printf("\nDifference is %d",c);
break;
case '*':c=a*b;
printf("\n Product is %d",c);
break;
case '/':c=a/b;
printf("\n Division is %d",c);
break;
case '%':c=a%b;
printf("\n Modulo is %d",c);
break;
default: printf("Invalid Choice");
}
getch();
}
Output:
MENU
1.Addition +
2.Subtraction -
3.Multiplication *
4.Division /
5.Modulo
Enter the operator from the given menu list*
Enter a, b Values 5 6
Product is 30

PPS LAB MANUAL


10) Write a program that finds if a given number is a prime number
Source Code:
#include<stdio.h
> void main()
{
int j,n,f=0;
printf("Enter number
n"); scanf("%d",&n);
for(j=1;j<=n;j++)
if(n%j==0)
f++;
if(f==2)
printf("%d is a prime number",n);
else
printf("%d is not a prime number",n);
getch();
}

Output:
Enter number n 37
37 is a prime number

11) Write a C program to find the sum of individual digits of a positive integer and
test given number is palindrome
Source Code:
#include
<stdio.h> void
main()
{
int num, temp, k, reverse = 0,s=0;

printf("Enter an integer \n");


scanf("%d", &num);
/* original number is stored at temp */
temp = num;
while (num > 0)
{
k = num % 10;
s=s+k;
reverse = reverse * 10 + k;
num = num/10;
}
printf("Given number is = %d\n", temp);
printf("Its reverse is = %d\n", reverse);
printf("\n Sum of individual digits is %d\n",s);
if (temp == reverse)
printf("Number is a palindrome \n");
else
printf("Number is not a palindrome \n");
PPS LAB MANUAL
getch();
}

Output:
Enter an integer 424
Given number is = 424
Its reverse is = 424
Sum of individual digits is 10
Number is a palindrome
12) A Fibonacci sequence is defined as follows: the first and second terms in the
sequence are 0 and 1. Subsequent terms are found by adding the preceding two
terms in the sequence. Write a C program to generate the first n terms of the
sequence.
Source Code:
#include<stdio.h>
void main()
{
int n1=0,n2=1,n,i,f;
printf("enter fibonacci sries length n: ");
scanf("%d",&n);
printf("\n Fibonacci Series is: ");
printf("%d %d",n1,n2);
for(i=1;i<=(n-2);i++)
{
f=n1+n2;
printf(" %d",f);
n1=n2;
n2=f;
}
getch();
}
Output:
enter fibonacci sries length n: 6
Fibonacci Series is:0 1 1 2 3 5

13) Write a C program to generate all the prime numbers between 1 and n, where n
is a value supplied by the user.
Source Code:
#include<stdio.h>
void main()
{
int i,j,f,n;
printf("Enter the number n: ");
scanf("%d",&n);
printf("Prime Numbers from 1 to %d are: ",n);
for(i=1;i<=n;i++)
{
f=0;
for(j=1;j<=i;j++)
if(i%j==0)
f++;
if(f==2)

PPS LAB MANUAL


printf(" %d",i);
}
getch();
}

Output: Enter the number n: 9

Prime Numbers from 1 to 9 are: 2 3 5 7

14) Write a C program to find the roots of a Quadratic equation


Source Code:
#include<stdio.h>
#include<math.h>
void main()
{
int a,b,c,d; float r1,r2;
printf("Enter a,b,c values");
scanf("%d%d%d",&a,&b,&c)
; d=b*b-4*a*c;
if(d>0)
{
r1=(-b+sqrt(d))/(2*a); r2=(-b-
sqrt(d))/(2*a); printf("Roots are:
%f , %f",r1,r2);
}
else if(d==0)
{
r1=r2=-b/(2*a);
printf("Roots are Equal: %f , %f",r1,r2);
}
else
printf("Roots are Imaginary");
getch();
}
Output:
Enter a,b,c values4 2
6 Roots are Imaginary

15) Write a C program to calculate the following, where x is a fractional value.


1-x/2 +x^2/4-x^3/6
Source Code: /* Write a C program to calculate the following, where x is a fractional
value. 1-x/2 +x^2/4-x^3/6 */
#include<stdio.h>
#include<math.h>
void main()
{
int i,x,n;
float sum=1;
printf("Enter x,n values:");
PPS LAB MANUAL
scanf("%d%d",&x,&n);

PPS LAB MANUAL


for(i=1;i<=n;i++)
{
sum=sum+((pow(-1,i)*(pow(x,i)))/(2*i));
}
printf("%f",sum);
}

Output:
Enter x,n values:2 3
-0.333333

16) Write a C program to read in two numbers, x and n, and then compute the sum
of this geometric progression: 1+x+x^2+x^3+………….+x^n. For example: if n is
3
and x is 5, then the program computes 1+5+25+125.
Source Code:
/*Write a C program to read in two numbers, x and n, and then compute the sum of this
geometric progression:1+x+x^2+x^3+….+x^n. For example: if n is 3 and x is 5, then the
program computes 1+5+25+125. */
#include<stdio.h>
#include<math.h>
void main()
{
int i,x,n;
int sum=0;
printf("Enter x,n values:");
scanf("%d%d",&x,&n);
for(i=0;i<=n;i++)
{
sum=sum+pow(x,i);
}
printf("%d",sum);
}

Output:
Enter x,n values:6 2
43
Arrays and Pointers and Functions:

17) Write a C program to find the minimum, maximum and average in an array of
integers.
Source Code:
#include <stdio.h>
void main()
{
int arr[100];
int i, max, min, size,sum;

PPS LAB MANUAL


float avg;

/* Input size of the array */


printf("Enter size of the array: ");
scanf("%d", &size);

/* Input array elements */


printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/* Assume first element as maximum and minimum */
max = arr[0];
min = arr[0];

/* Find maximum and minimum in all array elements. */


for(i=1; i<size; i++)
{
/* If current element is greater than max */
if(arr[i] > max)
{
max = arr[i];
}
/* If current element is smaller than min */
if(arr[i] < min)
{
min = arr[i];
}
}
sum = avg = 0;

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


{
sum = sum + arr[i];
}

avg = (float)sum / size;

printf("Maximum element = %d\n", max);


printf("Minimum element = %d", min);
printf("\n Average of array values is %f", avg);
}
Output:
Enter size of the array: 6
Enter elements in the array: 58

PPS LAB MANUAL


41
25
14
78
51
Maximum element = 78
Minimum element = 14
Average of array values is 44.500000

18) Write a functions to compute mean, variance, Standard Deviation, sorting of


n elements in single dimension array.
Source Code:
#include<stdio.h>
#include<math.h>
float mean(int arr[],int size);
float variance(int arr[],int size);
float dev(int arr[],int size);
void sort(int arr[],int size);
void main()
{
int arr[100];
int i, size,sum;
float avg;

/* Input size of the array */


printf("Enter size of the array: ");
scanf("%d", &size);

/* Input array elements */


printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
printf(" Mean is %f\n",mean(arr,size)); printf("
variance is %f\n",variance(arr,size)); printf("
Standard Deviation is %f\n",dev(arr,size));
sort(arr,size);
}
float mean(int arr[],int size)
{
int sum,i;
float avg;
sum = avg = 0;

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

{
sum = sum + arr[i];
}

PPS LAB MANUAL


avg = (float)sum / size;
return avg;
}
float variance(int arr[],int size)
{
float var,me=mean(arr,size);
int sum=0,i;
for (i = 0; i < size; i++)
{
sum = sum + pow((arr[i] -me ), 2);
}
var = sum / (float)size;
return var;
}
float dev(int arr[],int size)
{
float stddev, var=variance(arr,size);
stddev = sqrt(var);
return stddev;
}
void sort(int arr[],int size)
{
int temp,i,j;
for (i = 0; i < size; ++i)
{

for (j = i + 1; j < size; ++j)


{

if (arr[i] > arr[j])


{
temp= arr[i];
arr[i] = arr[j];
arr[j] = temp;

}
printf("The numbers arranged in sorting order are:
\n"); for (i = 0; i < size; ++i)

printf("%d ", arr[i]);


}
Output:
Enter size of the array: 5
Enter elements in the array: 36
25
14
85
47
PPS LAB MANUAL
Mean is 41.400002
variance is 595.599976
Standard Deviation is 24.404917
The numbers arranged in sorting order are:
14 25 36 47 85

19) Write a C program that uses functions to perform the following:


i) Addition of Two Matrices
ii) Multiplication of Two Matrices
iii) Transpose of a matrix with memory dynamically allocated for the new
matrix as row and column counts may not be same

I) Addition of Two
Matrices Source Code
#include<stdio.h>
int mtxadd(int a[5][5],int b[5][5],int m,int
n); int i,j;
void main()
{
int a[5][5],b[5][5],p,q,m,n;
printf("Enter 1st Matrix order");
scanf("%d%d",&m,&n);
printf("Enter 2nd Matrix order");
scanf("%d%d",&p,&q);
if(m==p&&n==q)
{
printf("Enter 1st Matrix Elements: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter 2nd Matrix Elements: ");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
printf(“Matrix Addition is:\n”);
mtxadd(a,b,m,n);
}

24

PPS LAB MANUAL


else
printf("Matrix Addition is not possible due to order of
matrices"); getch();
}
int mtxadd(int a[5][5],int b[5][5],int m,int n)
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]+b[i][j]);
printf("\n");
}
return 0;
}
Output:
Enter 1st Matrix order 3 3
Enter 2nd Matrix order 3 3
Enter 1st Matrix Elements:
123
456
789

Enter 2nd Matrix Elements:


321
654
987
Matrix Addition is:
4 4 4
10 10 10
16 16 16

II) Source Code: //Matrix Multiplication


#include<stdio.h>
int mtxmul(int a[5][5],int b[5][5],int m,int n,int q);
int i,j;
void main()
{
int a[5][5],b[5][5],p,q,m,n;
printf("Enter 1st Matrix order");
scanf("%d%d",&m,&n);
printf("Enter 2nd Matrix order");
scanf("%d%d",&p,&q);
if(n==p)
{
printf("Enter 1st Matrix Elements: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter 2nd Matrix Elements: ");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
PPS LAB MANUAL
scanf("%d",&b[i][j]);
mtxmul(a,b,m,n,q);
}
else
printf("Matrix Multiplication is not possible");
getch();
}
int mtxmul(int a[5][5],int b[5][5],int m,int n,int q)
{
int k,c[5][5];
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]+=a[i][k]*b[k][j];
}
}
printf("Matrix Multiplication is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
return 0;
}

Output:
Enter 1st Matrix order2 4
Enter 2nd Matrix order4 3
Enter 1st Matrix Elements:
1357
2468

Enter 2nd Matrix Elements:


189
2 7 10
3 6 11
4 5 12

Matrix Multiplication is:


50 94 178
60 120 220

III) Source code://Transpose


#include <stdio.h>
int trans(int matrix[10][10],int m,int n);
int c, d;
PPS LAB MANUAL
int main()
{
int m, n,mat[10][10];
printf("Enter the number of rows and columns of
matrix\n"); scanf("%d%d", &m, &n);
printf("Enter elements of the matrix\n");
for (c = 0; c < m; c++)
for(d = 0; d < n; d++)
scanf("%d",
&mat[c][d]);
trans(mat,m,n);
return 0;
}
int trans(int matrix[10][10],int m,int n)
{
int
transpose[10][10]; for (c =
0; c < m; c++)
for( d = 0 ; d < n ; d++ )
transpose[d][c] =
matrix[c][d];

printf("Transpose of the matrix:\n");


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

Output:
Enter the number of rows and columns of matrix 3 2
Enter elements of the matrix

45
67
89
Transpose of the matrix:
4 6 8
5 7 9

20) Write C programs that use both recursive and non-recursive functions
i) To find the factorial of a given integer.
PPS LAB MANUAL
ii. To find the GCD (greatest common divisor) of two given integers.
iii. To find x^n
Source Code:
i)/*C program recursive and non-recursive functions to find the factorial of a
given integer.*/

#include<stdio.h>
void main()
{
int n, a, b;
printf("Enter any number\n");
scanf("%d", &n);
a = recfact(n);
printf("The factorial of a given number using recursion is %d \n",
a); b = nonrecfact(n);
printf("The factorial of a given number using nonrecursionis %d ", b);
getch();
}
int recfact(int x)
{
int f;
if(x == 0)
{
return(1);
}
else
{
f = x * recfact(x - 1);
return(f);
}
}
int nonrecfact(int x)
{
int i, f = 1;
for(i = 1;i <= x; i++)
{

f = f * i;
}
return(f);
}
Output: Enter any number 5
The factorial of a given number using recursion is 120
The factorial of a given number using nonrecursionis 120

ii) Source Code /* GCD using rec and


nonrec*/ #include <stdio.h>
void main()
{
int a, b, c, d;
printf("Enter two numbers a, b\n");
scanf("%d%d", &a, &b);

PPS LAB MANUAL


c = recgcd(a, b);
printf("The gcd of two numbers using recursion is %d\n",
c); d = nonrecgcd(a, b);
printf("The gcd of two numbers using nonrecursion is %d",
d); getch();
}
int recgcd(int x, int y)
{
if(y == 0)
{
return(x);
}
else
{
return(recgcd(y, x % y));
}
}
int nonrecgcd(int x, int y)
{
int z;
while(x % y != 0)
{
z = x % y;
x = y;
y = z;
}
return(y);
}
Output: Enter two numbers a, b 6 5
The gcd of two numbers using recursion is 1
The gcd of two numbers using nonrecursion is 1

iv) X^n
Source code:
#include <stdio.h>
int power(int n1, int n2);
int nonrec(int b,int p);
int main()
{
int base, q, p, r;

printf("Enter base number: ");


scanf("%d",&base);

printf("Enter power number(positive integer): ");


scanf("%d",&p);
q=nonrec(base,p);
r = power(base, p);
printf("\nNon Recursive %d^%d = %d", base, p, r);
printf("\nRecursive %d^%d = %d", base, p, r);
getch();
PPS LAB MANUAL
return 0;

}
int nonrec(int b,int p)
{
int i,m=1;
if(p!=0)
{
for(i=1;i<=p;i++)
m=m*b;
return m;
}
else
return 1;
}
int power(int base, int p)
{
if (p != 0)
return (base*power(base, p-1));
else
return 1;
}

Output
Enter base number: 5
Enter power number(positive integer): 3
Non Recursive 5^3 = 125
Recursive 5^3 = 125

21) Write a program for reading elements using pointer into array and display the
values using array
Source Code:
#include
<stdio.h> void
main()
{
int arr[5], i;
printf("Enter elements: ");

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


scanf("%d", arr + i);

printf("You entered: \n");


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

}
Output:
Enter elements: 6
12
44
421
PPS LAB MANUAL
25
You entered:
6
12
44
421
25

22) Write a program for display values reverse order from array using pointer
Source Code:
#include
<stdio.h> void
main()
{
int arr[5], i;
printf("Enter elements:
"); for(i = 0; i < 5; ++i)
scanf("%d", &arr[i]);
printf("You entered:
\n"); for(i = 4; i>=0; --i)
printf("%d\n", *(arr+i));

}
Output:
Enter elements: 5
26
12
15
23
You entered:
23
15
12
26
5

23) Write a program through pointer variable to sum of n elements from


array. Source Code:
#include
<stdio.h> void
main()
{
int arr[5], i,sum=0;
printf("Enter elements: ");
for(i = 0; i < 5; ++i)
scanf("%d", &arr[i]);
printf("You entered:
\n"); for(i = 0; i < 5; ++i)
sum=sum+ *(arr+i);
printf("%d\n", sum);

PPS LAB MANUAL


}

Output:
Enter elements: 45
12
22
33
14
You entered:
126

FILES:

24) Write a C program to display the contents of a file to standard output


device. Source Code:
#include<stdio.h
> void main()
{
FILE *fp; char ch;
fp=fopen("ex.c","r")
; if(fp==NULL)
printf("File doesnot exists");
else
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}
Output:
void
main()
{
printf(“hi”);
}

25) Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents
Source Code:
#include<stdio.h
> void main()
{
FILE *fp1,*fp2; char ch;
fp1=fopen("fact.c","r");
fp2=fopen("fac.c","w");

PPS LAB MANUAL


while((ch=getc(fp1))!=EOF
)
{
if(ch>=97&&ch<=122)
ch=ch-32;
printf("%c",ch);
putc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
}

Output:
VOID MAIN()

{
INT A;
}

26) Write a C program to count the number of times a character occurs in a text
file. The file name and the character are supplied as command line arguments.
Source Code
#include<stdio.h>
void main(int argc,char *argv[])
{

FILE *fp;
char ch, c=*argv[1];
int i=0;
fp=fopen(argv[2],"r");
while((ch=getc(fp))!=EOF)
{
if(ch==c)
i++;
printf("%c",ch);
}
printf("\n %c repeats %d times",c,i);
}

Output: x repeats 5 times

27) Write a C program that does the following:


It should first create a binary file and store 10 integers, where the file name and 10
values are given in the command line. (hint: convert the strings using atoi function)
Now the program asks for an index and a value from the user and the value at that
index should be changed to the new value in the file. (hint: use fseek function) The
program should then read all 10 values and print them back
Source code 1:
PPS LAB MANUAL
#include <stdio.h>
#include<stdlib.h>
struct twonum
{
int n1;
};

void main(int argc,char *argv[])


{
int i,j,k,n,f=0;

struct twonum num;


FILE *fp;
fp= fopen(argv[1],"wb");
if (fp == NULL)
{
printf("Error in opening file");
}
else
for(i = 2; i <argc; ++i)
{
num.n1=atoi(argv[i]);
fwrite(&num, sizeof(num), 1, fp);
}
fclose(fp);
fp=fopen(argv[1],"rb+");
printf("Enter index for changing value: ");
scanf("%d",&k);
printf("\nEnter value for change");
scanf("%d",&n);
fseek(fp,sizeof(num)*(k-1),SEEK_SET);
fread(&num,sizeof(num),1,fp);
num.n1=n;
fseek(fp,sizeof(num)*(k-1),SEEK_SET);
fwrite(&num, sizeof(num), 1, fp);
fclose(fp);
fp=fopen(argv[1],"rb");
for(i = 2; i <argc; ++i)
{
fread(&num, sizeof(num), 1, fp);
printf("%d\t",num.n1);
}
fclose(fp);
getch();
}

PPS LAB MANUAL


Source Code 2:
#include <stdio.h>
#include<stdlib.h>
struct twonum
{

int n1;
};
void main(int argc,char *argv[])
{
int i,j,k,n,f=0;
struct twonum num;
FILE *fp;
fp= fopen(argv[1],"wb");
if (fp == NULL)
{
printf("Error in opening file");
}
else
for(i = 2; i <argc; ++i)
{
num.n1=atoi(argv[i]);
fwrite(&num, sizeof(num), 1, fp);
}
rewind(fp);
printf("Enter index for changing the value: ");
scanf("%d",&k);
printf("\nEnter new value for change: ");
scanf("%d",&n);
fseek(fp,sizeof(num)*(k-1),SEEK_SET);
num.n1=n;
fwrite(&num, sizeof(num), 1, fp);
fclose(fp);
fp=fopen(argv[1],"rb");
printf(“\nUpdated binary file content is:”);
for(i = 2; i <argc; ++i)
{
fread(&num, sizeof(num), 1, fp);
printf("%d\t",num.n1);
}
fclose(fp);
getch();
}

Input: (in Command prompt) data4.dat 2 3 4 5 6 7 8 9 10 11


Output:
Enter index for changing the value: 7
Enter new value for change: 90
Updated binary file content is:
PPS LAB MANUAL
2 3 4 5 6 7 90 9 10 11

36

PPS LAB MANUAL


28) Write a C program to merge two files into a third file (i.e., the contents of the first
file followed by those of the second are put in the third file).
Source Code:
#include<stdio.h
> void main()
{
FILE *fp1,*fp2,*fp3; char
ch; fp1=fopen("fac.c","r");
fp2=fopen("disp.c","r");
fp3=fopen("ex.c","w");
while((ch=getc(fp1))!=EOF
)
{
putc(ch,fp3);
}
while((ch=getc(fp2))!=EOF)
{
putc(ch,fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
}

Output:
#include<stdio.h>
void main()
{
int a;
}
#include<stdio.h>
void main()
{
float c;
}

PPS LAB MANUAL


STRINGS:

29) Write a C program to convert a Roman numeral ranging from I to L to its


decimal equivalent.
Source Code:
#include <stdio.h>
#include
<string.h>
#include <stdlib.h>
void main()
{
char rom[30];
int a[30], l, i, k, dec;
printf("Enter the roman number\n");
scanf("%s", &rom);
l =strlen(rom);
for(i = 0; i < l;
i++)
{
switch (rom[i])
{
case 'I': a[i] = 1;
break;
case 'V': a[i] = 5;
break;
case 'X': a[i] = 10;
break;
case 'L': a[i] = 50;
break;
case 'C': a[i] = 100;
break;
case 'D': dec = dec + 500;
break;
case 'M': a[i] = 1000;
break;
default : printf("Invalid choice");
break;
}
}
k = a[l - 1];
for(i = l - 1; i > 0; i--)
{
if(a[i] > a[i - 1])
{
k = k - a[i - 1];
}
if(a[i] <= a[i - 1])
{
k = k + a[i - 1];
}

PPS LAB MANUAL


}
printf("decimal equivalent is %d", k);
}

Output:
Enter the roman number XIV
Decimal equivalent is 14

30) Write a C program that converts a number ranging from 1 to 50 to Roman


equivalent
Source Code:
#include <stdio.h>
void predigit(char num1, char num2);
void postdigit(char c, int n);

char romanval[1000];
int i = 0;
int main()
{
int j;
long number;

printf("Enter the number: ");


scanf("%d", &number);
if (number <= 0)
{
printf("Invalid number");
return 0;
}
while (number != 0)
{
if (number >= 1000)
{
postdigit('M', number / 1000);
number = number - (number / 1000) * 1000;
}
else if (number >= 500)
{
if (number < (500 + 4 * 100))
{
postdigit('D', number / 500);
number = number - (number / 500) * 500;
}
else
{
predigit('C','M');
number = number - (1000-100);
}
}
else if (number >= 100)
{
if (number < (100 + 3 * 100))
PPS LAB MANUAL
39

{
postdigit('C', number / 100);
number = number - (number / 100) * 100;
}
else
{
predigit('L', 'D');
number = number - (500 - 100);
}
}
else if (number >= 50 )
{
if (number < (50 + 4 * 10))
{
postdigit('L', number / 50);
number = number - (number / 50) * 50;
}
else
{
predigit('X','C');
number = number - (100-10);
}
}
else if (number >= 10)
{
if (number < (10 + 3 * 10))
{
postdigit('X', number / 10);
number = number - (number / 10) * 10;
}
else
{
predigit('X','L');
number = number - (50 - 10);
}
}
else if (number >= 5)
{
if (number < (5 + 4 * 1))
{
postdigit('V', number / 5);
number = number - (number / 5) * 5;
}
else
{
predigit('I', 'X');

number = number - (10 - 1);


}
PPS LAB MANUAL
}
else if (number >= 1)
{
if (number < 4)
{
postdigit('I', number / 1);
number = number - (number / 1) * 1;
}
else
{
predigit('I', 'V');
number = number - (5 - 1);
}
}
}
printf("Roman number is: ");
for(j = 0; j < i; j++)
printf("%c", romanval[j]);
return 0;
}

void predigit(char num1, char num2)


{
romanval[i++] = num1;
romanval[i++] = num2;
}

void postdigit(char c, int n)


{
int j;
for (j = 0; j < n; j++)
romanval[i++] = c;
}
Output:
Enter the number:51
Roman number is: LI

PPS LAB MANUAL


31) Write a C program that uses functions to perform the following operations:
i) To insert a sub-string in to a given main string from a given position.

ii) To delete n Characters from a given position in a given string.

Source code:
/*To insert a sub-string in to a given main string from a given position. */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void insert(char str1[],char str2[],int l1,int l2,int n);
void main()
{
char str1[20], str2[20];
int l1, l2, n, i;
puts("Enter the string 1\n");
gets(str1);
l1 = strlen(str1);
puts("Enter the string 2\n");
gets(str2);
l2 = strlen(str2);
printf("Enter the position where the string is to be inserted\n");
scanf("%d", &n);
insert(str1,str2,l1,l2,n);
getch();
}
void insert(char str1[],char str2[],int l1,int l2,int n)
{
int i;
for(i = n; i < l1; i++)
{
str1[i + l2] = str1[i];
}
for(i = 0; i < l2; i++)
{
str1[n + i] = str2[i];
}
str2[l2 + 1] = '\0';
printf("After inserting the string is %s", str1);
}

Output:
Enter the string 1
sachin
Enter the string 2
tendulkar
Enter the position where the string is to be inserted 4
After inserting the string is sachtendulkarin
PPS LAB MANUAL
Source code:
/*To delete n Characters from a given position in a given string.*/

#include<stdio.h>
#include<string.h>
void delete(char str[],int n,int l,int pos);
void main()
{
char str[20];
int i, n, l, pos;
puts("Enter the string\n");
gets(str);
printf("Enter the position where the characters are to be deleted\n");
scanf("%d", &pos);
printf("Enter the number of characters to be deleted\n");
scanf("%d", &n);
l = strlen(str);
delete(str,n,l,pos);
}
void delete(char str[],int n,int l,int pos)
{
int i;
for(i = pos + n; i < l; i++)
{
str[i - n] = str[i];
}
str[i - n] = '\0';
printf("The string is %s", str);
}

Output
Enter the string
saradi
Enter the position where characters are to be deleted 2
Enter the number of characters to be deleted 2
The string is sadi

43

PPS LAB MANUAL


32) Write a C program to determine if the given string is a palindrome or not (Spelled same
in both directions with or without a meaning like madam, civic, noon, abcba, etc.)
Source code
#include<stdio.h>
#include<string.h
> void main()
{
char s1[20],s2[20];
printf("enter String s1:
"); gets(s1);
strcpy(s2,s1); strrev(s2);
if(strcmp(s1,s2)==0)

printf("%s is in Palindrome\n",s1);
else
printf("%s is not in Palindrome\n",s1);
}

Output:
enter String s1: DAD
DAD is in Palindrome

33) Write a C program that displays the position of a character ch in the string S or –
1 if S doesn‘t contain ch
Source Code:
#include<stdio.h>
#include<string.h>
main()
{
char s[10],t[10];
char *found;
printf("Enter a String:");
gets(s);
printf("Enter t String:");
gets(t);
found=strstr(s,t);
if(found)
printf("String is found at : %d position",found-s);
else
printf("-1");
getch();
}

Output:
Enter a String:country

44

Enter t String:try
String is found at : 4 position
PPS LAB MANUAL
34) Write a C program to count the lines, words and characters in a given
text. Source Code:
#include<stdio.h
> void main()
{
char line[80],ch;
int i,j,end=0,c=0,w=0,l=0;
printf("enter a line of text, press enter at the end\n");
while(end==0)
{
j=0;
while((ch=getchar())!='\n')
line[j++]=ch;
line[j]='\0';
if(line[0]=='\0')
break;
else
{
w++;
for(i=0;line[i]!='\0';i++)
{
if(line[i]==' '||line[i]=='\t')
w++;
else
c++;
}
l=l+1;
}
}
printf("\n");
printf("number of lines=%d\n",l);
printf("number of words=%d\n",w);
printf("number of characters=%d\n",c);
}

Output:
enter a line of text, press enter at the end

hi hello
where are you
i am going to college

PPS LAB MANUAL


number of lines=3
number of words=10
number of characters=35

Miscellaneous:

35) Write a menu driven C program that allows a user to enter n numbers and then
choose between finding the smallest, largest, sum, or average. The menu and all the
choices are to be functions. Use a switch statement to determine what action to
take. Display an error message if an invalid choice is entered.
Source Code:
#include<stdio.h
>
int small(int a[], int n);
int large(int a[], int n);
int sum(int a[], int n);
int avg(int a[], int n);
void main()
{
int i,ch,n,a[20]; printf("Enter n
value:"); scanf("%d",&n);
printf("Enter array
Elements"); for(i=0;i<n;i++)

scanf("%d",&a[i]);
printf("\n MENU \n1.Finding Smallest Element\n 2.Finding Largest Element\n");
printf("\n3. Finding Sum of all Elements\n 4.Finding Average of all Elements\n");
printf("Enter Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: small(a,n);
break;
case 2: large(a,n);
break;
case 3: sum(a,n);
break;
case 4: avg(a,n);
break;
default:printf("Invalid choice");
}

getch();
}
int small(int a[], int n)
{
int i,s;
s=a[0];

PPS LAB MANUAL


for(i=0;i<n;i++)
if(a[i]<s)
s=a[i];
printf("Smallest number is %d\n",s);
return 0;
}
int large(int a[], int n)
{
int i,s;
s=a[0];
for(i=0;i<n;i++)
if(a[i]>s)
s=a[i];
printf("Largest number is %d\n",s);
return 0;
}
int sum(int a[], int n)
{
int i,s=0;
for(i=0;i<n;i++)
s=s+a[i];
printf("Sum is %d\n",s);
return 0;
}
int avg(int a[], int n)
{
int i,s=0;
float d;
for(i=0;i<n;i++)
s=s+a[i];
d=s/n;
printf("Average is %f\n",d);
return 0;
}
Output:
Enter n value:4
Enter array Elements2
3
4
1
MENU
1.Finding Smallest Element
2.Finding Largest Element

3. Finding Sum of all Elements


4.Finding Average of all Elements
Enter Choice:2
Largest number is 4

PPS LAB MANUAL


36) Write a C program to construct a pyramid of numbers as follows
1 * 1 1 *
12 ** 23 22 **
123 *** 456 333 ***
4444 **
*

i) Source Code:
#include
<stdio.h> int
main()
{
int i, j, rows;
printf("Enter number of rows:
"); scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}
Output:
Enter number of rows:
51
12
123
1234
12345

ii) Source Code:


#include <stdio.h>
int main()
{

int i, j, rows;

printf("Enter number of rows: ");


scanf("%d",&rows);

for(i=1; i<=rows; ++i)


{
for(j=1; j<=i; ++j)

PPS LAB MANUAL


{
printf("* ");
}
printf("\n");
}
return 0;
}

Output:
Enter number of rows: 4
*
**
***
****

iii) Source Code: ( Floyd’s Triangle)


#include <stdio.h>
int main()
{
int rows, i, j, number= 1;

printf("Enter number of rows: ");


scanf("%d",&rows);

for(i=1; i <= rows; i++)


{
for(j=1; j <= i; ++j)
{
printf("%d ", number);
++number;
}
printf("\n");
}
return 0;
}

Output:
Enter number of rows: 4
1
23
456
7 8 9 10

iv) Source Code:


#include
<stdio.h> int
main()
{
int i,j,n;
printf("Enter number of rows:
"); scanf("%d",&n);
for(i=1;i<=n;i++)
PPS LAB MANUAL
{
for(j=1;j<=i;j++)
{
printf("%d",i);
}
printf("\n");
}
return 0;
}
Output:
Enter number of rows: 8
1
22
333
4444
55555
666666
7777777
88888888

v) Source Code:
#include<stdio.h>
void main()
{
int n, c, k;
printf("Enter number of rows\n");
scanf("%d",&n);
for ( c = 1 ; c <= n ; c++)
{
for ( k = 1 ; k <= c ; k++ )
printf("*");
printf("\n");
}
for ( c = n - 2 ; c >= 0 ; c-- )

{
for ( k = c ; k >= 0 ; k-- )
printf("*");
printf("\n");
}
getch();
}

Output:
Enter number of rows 3
*
**
***
**
*
PPS LAB MANUAL
Sorting and Searching:

37) Write a C program that uses non recursive function to search for a Key value in a
given list of integers using linear search method
Source Code:
#include<stdio.h
>
void search(int a[],int key,int n);
void main()
{
int i, a[20], n, key;
printf("Enter the size of an array
\n"); scanf("%d", &n);
printf("Enter the array elements");
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter the key
elements"); scanf("%d", &key);
search(a,key,n);
}
void search(int a[],int key,int n)
{
int flag = 0,i;
for(i = 0; i < n; i++)
if(a[i] == key)
{
flag = 1;
break;
}
if(flag == 1)
printf("The key elements is found at location %d", i + 1);
else
printf("The key element is not found in the array");

Input & Output:


Enter the size of an array 6
Enter the array elements 50 10 5 200 20 1
Enter the key element 1
The key Element is found at location 6

PPS LAB MANUAL


38) Write a C program that uses non recursive function to search for a Key value in a
given sorted list of integers using binary search method.
Source Code:
#include<stdio.h>
void main()
{
int a[20], i, n, key, low, high, mid;
printf("Enter array size:");
scanf("%d",&n);
printf(“Enter the array elements in ascending order”);
for(i = 0; i < n; i++)
{
scanf(“%d”, &a[i]);
}
printf(“Enter the key element\n”);
scanf(“%d”, &key);
low = 0;
high = n - 1;
while(high >= low)
{
mid = (low + high) / 2;
if(key == a[mid])
break;
else
{
if(key > a[mid])
low = mid + 1;
else
high = mid - 1;
}
}
if(key == a[mid])

printf(“The key element is found at location %d”, mid +


1); else
printf(“the key element is not found”);
getch();
}

Output:
Enter array size:6
Enter the array elements in ascending order23
25
29
54
65
74
Enter the key element
PPS LAB MANUAL
65
The key element is found at location 5

39) Write a C program that implements the Bubble sort method to sort a given list
of integers in ascending order
Source Code:
#include<stdio.h>
void main()
{
int n, a[20], temp, i, j;
printf("Enter the size of the array\n");
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; j++)
{
if(a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("The sorted array is\n");
for(i = 0; i < n; i++)
printf("%d\n", a[i]);
getch();

}
Output:
Enter the size of the array
6
Enter the array elements
23
14
25
68
2
45
The sorted array is
2
14
23
25
45
68

PPS LAB MANUAL


40) Write a C program that sorts the given array of integers using selection sort in
descending order
Source code:

#include<stdio.h>
void main()
{
int a[20],n, s, i, j, temp;
printf("enter number of elements:");
scanf("%d",&n);
printf("\n Enter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
s=i;
for(j=i+1;j<n;j++)
{
if(a[j]>a[s])
s=j;
}
temp=a[s];
a[s]=a[i];
a[i]=temp;
}
printf(“\n Array elements after selection sort:”);
for(i=0;i<n;i++)

printf("%d ",a[i]);
getch();
}

Output:
enter number of elements:5
Enter 5 elements: 45 32 89 12 8
Array elements after selection sort:
89 45 32 12 8

41) Write a C program that sorts the given array of integers using insertion sort in
ascending order
Source Code:
#include<stdio.h>
int main()
{

PPS LAB MANUAL


int a[100],n,temp,i,j;
printf("Enter number of terms: ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<n;i++)
{
temp = a[i];
j=i-1;
while(temp<a[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to temp>data[j] in above line.*/
{
a[j+1] = a[j];
--j;
}
a[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",a[i]);
getch();
return 0;
}
Output:
Enter number of terms: 5
Enter elements: 32
14
25
65
35
In ascending order: 14 25 32 35 65

42) Write a C program that sorts a given array of names


Source Code:
#include<stdio.h>
#include<string.h>
void main()
{
char a[10][10], t[10];
int i,j,n;
printf("Enter Number of Strings:");
scanf("%d",&n);
printf("Enter %d Strings:",n);
for(i=0;i<n;i++)
scanf("%s",a[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(strcmp(a[i],a[j])>0)

PPS LAB MANUAL


{
strcpy(t,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],t);
}
}
printf("Strings after sorting\n");
for(i=0;i<n;i++)
printf("%s\n",a[i]);
getch();
}

Output:
Enter Number of Strings:5
Enter 5 Strings:modi
india
kranthi
akash
nithin
Strings after sorting
akash
India
kranthi
modi
nithin

PPS LAB MANUAL


PPS LAB MANUAL

You might also like