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

PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL (3)

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)
47 views

PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL (3)

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/ 68

PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

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.

/* Program demonstrating operators in C */


#include<stdio.h>
int main( )
{
int a,b,c;
printf(“Enter two values:”);
scanf(“%d %d”, &a, &b);

printf("a+b=%d\n", a+b);
printf("a-b=%d\n", a-b);
printf("a*b=%d\n", a*b);
printf("a/b=%d\n", a/b);
printf("a%%b=%d\n", a%b);

printf("++a=%d\n",++a);
printf("--b=%d\n",--b);
printf("a++=%d\n",a++);
printf("b--=%d\n",b--);

printf("a+=5 value is: %d\n",a+=5);


printf("a-=2 value is: %d\n",a-=2);
printf("a*=3 value is: %d\n",a*=3);
printf("b/=2 value is: %d\n",b/=2);
printf("b%%=4 value is: %d\n",b%=4);

printf("a>b=%d\n",a>b);
printf("a<b=%d\n",a<b);
printf("a>=b=%d\n",a>=b);
printf("a<=b=%d\n",a<=b);
printf("a!=b=%d\n",a!=b);

printf("(a>b)&&(b<a)=%d\n",(a>b)&&(b<a));
printf("(a<b)||(b<a)=%d\n",(a<b)||(b<a));
printf("!(a!=b)=%d\n",!(a!=b));
printf("!(a==b)=%d\n",!(a==b));

printf("a&b=%d\n",a&b);
printf("a|b=%d\n",a|b);
printf("a^b=%d\n",a^b);
PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

printf("a>>2=%d\n",a>>2);
printf("b<<3=%d\n",b<<3);

}
OUTPUT:
Enter two values:9 4
a+b=13
a-b=5
a*b=36
a/b=2
a%b=1
++a=10
--b=3
a++=10
b--=3
a+=5 value is: 16
a-=2 value is: 14
a*=3 value is: 42
b/=2 value is: 1
b%=4 value is:1

a>b=1
a<b=0
a>=b=1
a<=b=0
a!=b=1

(a>b)&&(b<a)=1
(a<b)||(b<a)=1
!(a!=b)=0
!(a==b)=1

a&b=0
a|b=43
a^b=43
a>>2=10
b<<3=8
2. Write a simple program that converts one given data type to another using
auto conversion and casting. Take the values from standardinput.

/* Program demonstrating type conversion */

#include<stdio.h>
int main( )
{
int x, sum;
char y;
float z;
printf("Enter a character:");
scanf("%c",&y);

printf(“Enter a number:”);
scanf(“%d”, &x);

x = x + y; //y implicitly converted to int. ASCII value of 'a'=97


z = x + 1.5; //x implicitly converted to float//
printf("x=%d, z=%f\n", x, z);

sum = (int)z + 1; //explicit conversion from float to int//


printf("sum=%d\n",sum);
return 0;
}

OUTPUT:

Enter a character: b
Enter a number: 10

x=108, z=109.500000
sum=110

3. Write a program to find the max and min from the three numbers.

/* Program to find max and min from three numbers */

#include<stdio.h>
int main( )
{
int a,b,c;
printf("Enter 3 numbers");
scanf("%d %d %d", &a, &b, &c);

if(a>b && a>c)


printf("Maximum number = %d", a);
else if(b>a && b>c)
printf("Maximum number = %d", b);
else
printf("Maximum number = %d", c);

if(a<b && a<c)


printf("Minimum number = %d", a);
else if(b<a && b<c)
printf("Minimum number = %d", b);
else
printf("Minimum number = %d”, c);
return 0;
}

OUTPUT:

Enter 3 numbers
11
22
33
Maximum number = 33
Minimum number = 11

4. Write the program for the simple and compound interest.

/* Program demonstrating simple and compound intrest */

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

}
COMPILATION & EXECUTION:
$gcc interest.c -lm
$./a.out

OUTPUT:

Enter the value of Principal p = 1000


Enter Rate of Interest r = 2
Enter Time Period in years n = 3
Simple Interest SI=60.000000
Compound Interest CI=61.207939
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.

/* Program to find Class awarded for a given percentage of marks */

#include<stdio.h>
int main( )
{
float marks;
printf("Enter percentage of marks:\n");
scanf("%f", &marks);

if(marks<40)
printf("Failed\n");
else if( marks >= 40 && marks < 60 )
printf("Second class\n");
else if( marks >= 60 && marks < 70 )
printf("First class\n");
else
printf("Distinction\n");

OUTPUT:

Enter percentage of marks:


40
Second class

Enter percentage of marks:


39
Failed

Enter percentage of marks:


65
First class

Enter percentage of marks:


77
Distinction
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

/* Program to print multiplication table up to given number of rows */

#include <stdio.h>
int main( )
{
int n, rows, i;
printf("Enter which multiplication table to print?\n ");
scanf("%d", &n);
printf(“Enter number of rows in the multiplication table\n “);
scanf(“%d”, &rows);
for(i =1; i <= rows; ++i)
printf("%d * %d = %d \n", n, i, n*i);

return 0;
}

OUTPUT:

Enter which multiplication table to print?


7
Enter number of rows in the multiplication table
5

7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35

7. Write a program that shows the binary equivalent of a given positive


number between 0 to 255.

/* Program demonstrating binary equivalent of a given positive number */

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

int main( )

int n, r, i=1,bin=0;

printf("Enter a positive number between 0 to 255\n") ;

scanf("%d", &n) ;

if(n < 0 && n > 255)

printf("Invalid input. Please enter between 0 to 255 only\n");

exit(1);

printf("\nThe binary equivalent of %d is : ",n);

while (n!=0) {

r = n % 2;

n /= 2;

bin += r * i;

i *= 10;

printf("%d”,bin);

return 0;

OUTPUT:

Enter a positive number between 0 to 255


7
The binary equivalent of 7 is : 111
Enter a positive number between 0 to 255
562
Invalid input. Please enter between 0 to 255 only
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)).

/* program to calculate the time taken by the ball dropped from the
topof the building */
#include<stdio.h>
#include<math.h>
int main( )
{

int s, i=1;
double t, a=9.8;
for(i = 1; i <= 10; i++)

t = sqrt( 2*s / a);


printf(“Time taken by the ball to reach %d floor = %f\n”, i, t);
s += 3;
}
return 0;

}
OUTPUT:
Time taken by the ball to reach 1 floor = 0.782461
Time taken by the ball to reach 2 floor = 1.106567
Time taken by the ball to reach 3 floor = 1.355262
Time taken by the ball to reach 4 floor = 1.564922
Time taken by the ball to reach 5 floor = 1.749636
Time taken by the ball to reach 6 floor = 1.916630
Time taken by the ball to reach 7 floor = 2.070197
Time taken by the ball to reach 8 floor = 2.213133
Time taken by the ball to reach 9 floor = 2.347382
Time taken by the ball to reach 10 floor = 2.474358
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).

/* Program demonstrating switch statement */


#include <stdio.h>
int main( )
{
int a, b, c;
char ch;
printf("Enter an operator (+, -, *, /, %) \n");
scanf("%c", &ch);
printf("Enter the values of a and b\n");
scanf("%d %d", &a, &b);
switch(ch)
{
case '+' : c = a + b;
printf("Sum = %d", c);
break;

case '-' : c = a - b;
printf("Difference = %d", c);
break;

case '*' : c = a * b;
printf("Product = %d", c);
break;

case '/' : c = a / b;
printf("Quotient = %d", c);
break;

case '%' : c = a % b;
printf("Remainder = %d", c);
break;

default : printf("Invalid operator");


break;
}
return 0;
}
OUTPUT:
Enter an operator (+, -, *, /, %)
*
Enter the values of a and b
15 5
Product = 75
Enter an operator (+, -, *, /, %):$
Invalid operator
10. Write a program that finds if a given number is a prime number.

/* Program to test whether the given number is prime or not*/

#include <stdio.h>
int main( )
{
int n, i, count = 0;
printf("Enter a number\n ");
scanf("%d", &n);
for(i = 1; i <= n; i++)
if (n % i = = 0)
count++;

if(count = = 2)
printf(“The given number %d is a prime number”, n);
else
printf(“The given number %d is not a prime number”, n);
return 0;
}

OUTPUT:
Enter a number

24

The given number 24 is not a prime number

Enter a number

59

The given number 59 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.

/* Program to find sum of individual digits of a positive integer and


testing whether it is a palindrome or not*/

#include<stdio.h>
int main ( )
{
int temp,n,rem=0,sum=0,rev=0;
printf("Enter a positive integer\n");
scanf("%d",&n);

temp=n;

while(n>0)
{
rem=n%10;
sum=sum+rem;
rev=(rev*10)+rem;
n=n/10;
}

printf ("Sum of individual digits of given number = %d\n", sum);

if(temp==rev)
printf("Given number is a palindrome\n");
else
printf("Given number is not a palindrome\n");

OUTPUT:

Enter a positive integer:


767
Sum of individual digits of given number = 20
Given number is palindrome

Enter a positive integer


249
Sum of individual digits of given number = 15
Given number is not 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.

/* Program to calculate first n terms of Fibonacci series */


#include<stdio.h>
int main( )
{
int f1=0,f2=1,terms, i,f3=0;

printf("Enter number of terms in the fibonacci series: \n ");


scanf("%d",&terms);
printf("Fibonacci series is\n");

printf("%d %d",f1,f2);
for(i=3; i<=terms; i++)
{
f3 = f1+ f2;
printf(" %d", f3);
f1=f2;
f2=f3;
}
return 0;
}

OUTPUT:
Enter number of terms in the fibonacci series:
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.

/* Program to calculate prime numbers between 1 and n */

#include<stdio.h>
int main( )
{
int n, i, j, count;

printf("Enter n value:\n");
scanf("%d", &n);
printf("The prime numbers between 1 to %d are\n",n);

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


{
count = 0;
for(j = 1; j <= i; j++)
if(i % j == 0)
count++;

if(count == 2)
printf("%d\t", i);

}
return 0;
}

OUTPUT:

Enter n value:
10
The prime numbers between 1 to 10 are
2 3 5 7

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

/* Program to find the roots of a Quadratic equation */

#include<stdio.h>
#include<math.h>
int main( )
{
int a, b, c, d;
double root1=0.0, root2=0.0;

printf("Enter the values of a, b, c\n");


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

d = (b * b) - (4 * a * c);
if(d > 0)
{
printf("Roots are real and distinct \n");
root1 = (-b + sqrt(d)) / (2.0 * a);
root2 = (-b - sqrt(d) )/ (2.0 * a);
printf("Root1 = %lf \n”, root1);
printf(“Root2 = %lf\n", root2);
}
else if (d == 0)
{
printf("Roots are real and equal\n");
root1 = root2 = -b / (2.0 * a);

printf("Root1 = %lf\n", root1);


printf("Root2 = %lf\n", root2);
}
else
printf("Roots are imaginary");

return 0;
}

OUTPUT:

Enter the values of a, b, c


2 -1 -3
Roots are real and distinct
Root1 = -1.00000
Root2 = 1.50000

Enter the values of a, b, c


123
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 + .............

/* Program to calculate the sum of the series */


#include<stdio.h>
#include<math.h>
int main( )
{
float x, term=0, sum=1.0;
int i,n,denr;

printf("Enter number of terms\n");


scanf("%d", &n);

printf("Enter x value\n ");


scanf("%f", &x);

for(I =1; I < n; i++)


{
denr = 2*i;
term = pow(-1,i)*pow(x,i)/denr;
sum = sum + term;
}

printf("Sum of the series = %f\n", sum);

return 0;
}

OUTPUT:

Enter number of terms


4
Enter x value
2
Sum of the series = -0.333333

Enter number of terms


5
Enter x value
3
Sum of the series = 7.375000
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.

/* Program to calculate the sum of the geometric progression */

#include <stdio.h>
#include <math.h>
int main( )
{
int n, x, i;

float sum = 0.0;

printf("Enter n value (power of the last term)\n");

scanf("%d", &n);

printf("Enter x value\n");

scanf("%d", &x);

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

sum=sum + pow(x, i);

printf("Sum of the geometric progression = %f”, sum);

return 0;

OUTPUT:

Enter n value (power of the last term)


3
Enter x value
5
Sum of the geometric progression = 156.000000

Enter n value (power of the last term)


5
Enter x value
2
Sum of the geometric progression = 63.000000
17. Write a C program to find the minimum, maximum and average in
an array of integers.

/* Program to find the minimum, maximum and average of an array */


#include <stdio.h>
#define MAX_SIZE 50 // Maximum array size
int main()
{
int a[MAX_SIZE], i, max, min, n, sum;
float avg;
/* Input number elements of the array */
printf("Enter how many elements in the array? ");
scanf("%d", &n);
/* Input array elements */
printf("Enter %d elements\n ", n);
for(i = 0; i < n; i++)
scanf("%d", &a[i]);

/* Assume first element as maximum and also as minimum */


max = min = sum = a[0];
for(i = 1; i < n; i++)
{
if(a[i] > max)
max = a[i];
if(a[i] < min)
min = a[i];
sum = sum + a[i];
}
avg = sum/2.0;
printf("Maximum value = %d\n", max);
printf("Minimum value = %d\n", min);
printf("Average value = %f\n", avg);
return 0;
}

OUTPUT:
Enter how many elements in the array? 5
Enter 5 elements
25784
Maximum value = 8
Minimum value = 2
Average value = 13.000000
18. Write a functions to compute mean, variance, Standard Deviation
of n elements in single dimension array.
#include<stdio.h>
#include<math.h>
double std_dev(int a[ ], int n);
double variance(int a[ ], int n);
float mean(int [ ], int n);
int main( )
{
double s;
int a[50], n, i;
printf("enter how many elements:");
scanf("%d", &n);
printf("enter %d elements: ", n);
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
s=std_dev(a,n);
printf("\nstandard deviation=%f\n",s);
return 0;
}
double std_dev(int a[ ], int n)
{
double sd,v;
v=variance(a,n);
sd=sqrt(v);
return(sd);
}
double variance(int a[ ], int n)
{
int i;
float m,sum=0.0,v;
m=mean(a,n);
for(i=0;i<n;i++)
sum=sum+(m-a[i])*(m-a[i]);
v=sum/n;
printf("variance=%f\n",v);
return(v);
}
float mean(int a[ ], int n)
{
float sum=0.0,m;
int i;
for(i=0;i<n;i++)
sum=sum+a[i];
m=sum/n;
printf("\nmean=%f\n",m);
return(m);
}
OUTPUT: enter how many elements: 3
enter 3 elements: 2 6 9
mean=5.666667
variance=8.222222
standard deviation=2.867442
19. Write a C program that uses functions to perform Addition of Two
Matrices.
#include<stdio.h>
void input(int x[5][5],int m,int n);
void add(int x[5][5],int y[5][5],int z[5][5],int m,int n);
void display(int x[5][5],int m,int n);
int main( )
{
int a[5][5], b[5][5], c[5][5], m, n;
printf("enter how many rows and columns\n");
scanf("%d %d", &m, &n);

printf("enter %d elements of first matrix\n", m*n);


input(a,m,n);

printf("enter %d elements of second matrix\n", m*n);


input(b,m,n);

add(a,b,c,m,n);

printf("\nmatrix A is\n");
display(a,m,n);

printf("\nmatrix B is\n");
display(b,m,n);

printf("\nresultant matrix C is\n");


display(c,m,n);

return 0;
}
void input(int x[5][5], int m, int n)
{
int i, j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&x[i][j]);
}
void add(int x[5][5], int y[5][5], int z[5][5], int m, int n)
{
int i, j;
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
z[i][j] = x[i][j] + y[i][j];
}
void display(int x[5][5], int m, int n)
{
int i, j;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
printf("%4d", x[i][j]);
printf("\n");
}
}

OUTPUT:
enter how many rows and columns
2 2
enter 4 elements of first matrix
1 111
enter 4 elements of second matrix
2 222

matrix A is
1 1
1 1

matrix B is
2 2
2 2

resultant matrix C is
3 3
3 3

20. Write a C program that uses functions to perform Multiplication of


Two Matrices.
#include<stdio.h>
#include<stdlib.h>
void input(int x[5][5], int rows, int cols);
void multiply(int x[5][5], int y[5][5], int z[5][5], int r1, int c1, int r2, int c2);
void display(int x[5][5], int rows, int cols);

int main()
{
int a[5][5], b[5][5], c[5][5] = {0}, r1, c1, r2, c2;
printf("enter first matrix rows and columns\n");
scanf("%d %d", &r1, &c1);
input(a, r1, c1);

printf("enter second matrix rows and columns\n");


scanf("%d %d", &r2, &c2);
input(b, r2, c2);

multiply(a, b, c, r1, c1, r2, c2);

printf("\nmatrix A is\n");
display(a, r1, c1);

printf("\nmatrix B is\n");
display(b, r2, c2);

printf("\nproduct matrix C is\n");


display(c, r1, c2);

return 0;
}
void input(int x[5][5], int rows, int cols)
{
int i, j;
printf("enter %d elements:", rows*cols);
for(i = 0; i < rows; i++)
for(j = 0; j < cols; j++)
scanf("%d", &x[i][j]);
}
void multiply(int x[5][5], int y[5][5], int z[5][5], int r1, int c1, int r2, int c2)
{
int i, j, k;
if(c1 != r2)
{
printf("matrix multiplication is not possible\n");
exit(1);
}
for(i=0;i<r1;i++)
for(j=0;j<c2;j++)
for(k=0;k<r2;k++)
z[i][j] += x[i][k]*y[k][j];
}

void display(int x[5][5], int rows, int cols)


{
int i, j;
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
printf("%4d", x[i][j]);

printf("\n");
}
}

OUTPUT1:
enter first matrix rows and columns
23
enter 6 elements
111111
enter second matrix rows and columns
32
enter 6 elements
222222

matrix A is
1 1 1
1 1 1

matrix B is
2 2
2 2
2 2
product matrix C is
6 6
6 6

OUTPUT2:

enter first matrix rows and columns


23
enter 6 elements
111111
enter second matrix rows and columns
22
enter 4 elements
2222
matrix multiplication is not possible
21. Transpose of a matrix with memory dynamically allocated for the
new matrix as row and column counts may not be same.
#include<stdio.h>
#include<stdlib.h>
void main( )
{
int **a, **b;
int rows, cols;
int i, j;
printf("enter rows and columns of matrix\n");
scanf("%d %d", &rows, &cols);

/* allocate memory for matrix A */


a = (int **) malloc(sizeof(int *)*rows);
for( i = 0; i < rows; i++)
a[i] = (int *) malloc(sizeof(int*)*cols);

// input matrix A
printf("enter matrix of order %d by %d\n", rows, cols);
for(i = 0; i < rows; i++)
for(j = 0; j < cols; j++)
scanf("%d", &a[i][j]);

/* allocate memory for matrix B */


b = (int **) malloc(sizeof(int *)*cols);
for( i = 0; i < cols; i++)
b[i] = (int *) malloc(sizeof(int*)*rows);

//transpose the matrix


for(i = 0; i < rows; i++)
for(j = 0; j < cols; j++)
b[j][i] = a[i][j];
//output matrix B
printf("\n The Transpose matrix is\n");
for(i = 0; i < cols; i++)
{
for(j = 0; j < rows; j++)
printf("%4d", b[i][j]);
printf("\n");
}
/*free memory of matrix A*/
for(i=0;i<rows;i++)
free(a[i]);
free(a);
/*free memory of matrix B*/
for(i = 0; i < cols; i++)
free(b[i]);
free(b);
} // end of main

OUTPUT:
enter rows and columns for matrix
23
enter matrix of order 2 by 3
123
456

The Transpose matrix is


1 4
2 5
3 6
22. Write C programs that use both recursive and non-recursive
functions to find the factorial of a given integer.
#include <stdio.h>
int main( )
{
int n;
long f1, f2;

printf("Enter a number\n");
scanf("%d", &n);

f1 = recfactorial(n);
printf("The factorial of %d using recursion is %ld \n", n, f1);

f2 = nonrecfactorial(n);
printf("The factorial of %d using non-recursion is %ld ", n, f2);

return 0;
}

int recfactorial(int x)
{
if(x == 0 || x==1)
return(1);
return( x * recfactorial(x - 1));
}

int nonrecfactorial(int x)
{
int i;
long f = 1;
for(i = 1;i <= x; i++)
{
f = f * i;
}
return(f);
}

OUTPUT:
Enter a number
5
The factorial of 5 using recursion is 120
The factorial of 5 using non-recursion is 120

23. To find the GCD (greatest common divisor) of two given


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

c = recgcd(a, b);
printf("The gcd of %d and %d using recursion is %d\n", a,b, c);

d = nonrecgcd(a, b);
printf("The gcd of two numbers using non-recursion is %d", d);

return 0;
}

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
8 20
The gcd of 8 and 20 using recursion is 4
The gcd of 8 and 20 using non-recursion is 4
24. Write a C program to find x^n.

/* program to calculate x^n (x to the power of n) */


#include <stdio.h>
#include <math.h>
int main( )
{
int x, n;
int result;
printf("Enter the base, x\n ");
scanf("%d", &x);
printf("Enter the power, n ");
scanf("%d", &n);

result =pow((double)x, n);


printf("%d to the power of %d is: %d", x, n, result);
return 0;
}

OUTPUT:
Enter the base, x
2
Enter the power, n
3
2 to the power of 3 is: 8
25. Write a program for reading elements using pointer into array and
display the values using array.

#include<stdio.h>
int main( )
{
int a[50],*p, i, n;
p = a;
printf("Enter the size of array\n");
scanf("%d", &n);

printf("Enter %d elements of array\n", n);


for(i = 0; i < n; ++i)
scanf("%d", p+i);

printf(“The elements of array are\n”);


for(i = 0;i < n; ++i)
printf("%4d", *(p+i));

return 0;
}

OUTPUT:
Enter the size of array
5
Enter 5 elements of array
2 34 56

The elements of array are


2 3 4 5 6
26. Write a program for display values reverse order from array
usingpointer.

#include<stdio.h>
#define MAX 30
int main( )
{
int n, i, a[MAX];
int *ptr;
ptr = &a[0];
printf("\nEnter the size of array \n ");
scanf("%d", &n);

printf("\nEnter %d integers into array\n",n);


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

printf("\nElements of array in reverse order are");


for (i = n - 1; i >= 0; i--)
{
printf("%d ",*ptr);
ptr--;
}

return 0;

OUTPUT:
Enter the size of array
5
Enter 5 integers into array
11 22 33 44 55

Elements of array in reverse order are


55 44 33 22 11
27. Write a program through pointer variable to sum of n elements
from array.

#include <stdio.h>
#include <malloc.h>
int main( )
{
int i, n, sum = 0;
int a[20], *p;
printf("Enter the size of array \n");
scanf("%d", &n);

printf("Enter %d elements\n", n);


for (i = 0; i < n; i++)
scanf("%d", a + i);
p=a;
/* Compute the sum of all elements in the given array */
for (i = 0; i < n; i++)
{
sum = sum + *p;
p++;
}
printf("Sum of all elements in array = %d\n", sum);

return 0;
}

OUTPUT:
Enter the size of array
5
Enter 5 elements
1 2 3 4 5
Sum of all elements in array = 15
28. Write a C program to display the contents of a file to standard
output device.

#include<stdio.h>
int main( )
{
FILE *fp1;
char c;
fp1 = fopen("abc.txt", "w");

printf("enter the text\n");


while((c = getchar()) != EOF)
putc(c, fp1);

fclose(fp1);

fp1 = fopen("abc.txt","r");

printf("\nThe data from file is \n");


while((c = getc(fp1))!=EOF)
putchar(c);
printf("\n");

fclose(fp1);

return 0;
}

OUTPUT:
enter the text
hello
welcome
^d
The data from file is
hello
welcome
29. Write a C program which copies one file to another, replacing all
lowercase characters with their uppercase equivalents.

#include<stdio.h>
int main( )
{
FILE *fp1, *fp2;
char *fn1, *fn2, ch;

fp1=fopen("abc.txt","r");
fp2=fopen("file.txt","w");

if(fp1 == NULL||fp2 == NULL)


{
printf("\n unable to open file");
exit(1);
}

while((ch = fgetc(fp1)) != EOF)


{
if(ch >= 'a' && ch <= 'z')
ch=ch-32;
fputc(ch, fp2);
}
printf("\n File successfully copied");
fclose(fp1);
fclose(fp2);

return 0;
}

0UTPUT:
File successfully copied
$cat file.txt
PPS LAB
PROGRAMMING
30. 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.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[])
{
FILE *fp1;
char ch;
int count=0;

if((fp1=fopen(argv[1], "r")) == NULL)


{
printf("Error in opening file\n");
exit(1);
}

while((ch = fgetc(fp1)) != EOF)


if(ch==argv[2][0])
count++;

printf("The character being written was %c and it occurred %d times",


argv[2], count);
fclose(fp1);
}

OUTPUT:

$ ./a.out abc.txt e
The character being written was e and it occurred 3 times

31. 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.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp1;
int i,pos,k;
fp1 = fopen(argv[1], "wb");
for(i=2;i<=11;i++)
putw((atoi(argv[i])),fp1);

printf("Enter an index between 1 to 10:");


scanf("%d", &pos);

printf("Enter new value:");


scanf("%d", &k);

rewind(fp1);
fseek(fp1,pos,SEEK_SET);
putw(k,fp1);

fclose(fp1);

fp1 = fopen(argv[1], "rb");


while((k=getw(fp1)) != EOF)
printf("%4d",k);

fclose(fp1);
return 0;
}

OUTPUT:
$ ./a.out num.txt 1 2 3 4 5 6 7 8 9 10
Enter an index between 1 to 10: 4
Enter new value:8
1 2 3 8 5 6 7 8 9 10
32. 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).
#include<stdio.h>
int main(int argc, char *argv[])
{
FILE *fp1, *fp2, *fp3;
int i, ch;
fp1 = fopen(argv[1], "r");
fp2 = fopen(argv[2], "r");
fp3 = fopen(argv[3], "a");
while((ch = getc(fp1)) != EOF)
putc(ch, fp3);
fclose(fp1);

while((ch = getc(fp2)) != EOF)


putc(ch, fp3);
fclose(fp2);
fclose(fp3);
printf("The contents of merged file\n");
fp3 = fopen(argv[3], "r");
while((ch = getc(fp3)) != EOF)
printf("%c",ch);

fclose(fp3);
}

OUTPUT:
$ ./a.out abc.txt abc.txt third.txt
The contents of merged file
hello
welcome
hello
welcome

33. Write a C program to convert a Roman numeral ranging from I to L


to its decimal equivalent.
#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;
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];
}
}
printf("decimal equivalent is %d", k);
}

OUTPUT:
Enter the roman number
XIV
decimal equivalent is 14
34. Write a C program that converts a number ranging from 1 to 50 to
Roman equivalent.
/* C Program to Convert Numbers to Roman Numerals */
#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;
int 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))
{
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);
}
}
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: 500
Roman number is be: D
35. Write a C program that uses functions to insert a sub-string into a
given main string from a given position.
#include<stdio.h>
#include<string.h>
int main( )
{
char str1[20], str2[20];
int l1, l2, n, i;
puts("Enter the main string \n");
gets(str1);

l1 = strlen(str1);

puts("Enter the sub string \n");


gets(str2);

l2 = strlen(str2);

printf("Enter the position where the sub string is to be inserted\n");


scanf("%d", &n);

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);
return 0;
}
OUTPUT:
Enter the main string
pps
Enter the sub string
lab
Enter the position where the sub string is to be inserted
3
After inserting, the string is: ppslab
36. Write a C program that uses functions to delete n Characters from a
given position in a given string.

#include<stdio.h>
#include<string.h>
int main( )
{
char str[20];
int i, n, l, pos;
puts("Enter the string\n");
gets(str);

printf("Enter the position from 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);
for(i = pos + n; i < l; i++)
str[i - n] = str[i];

str[i - n] = '\0';

printf("The string after deletion is: %s", str);

return 0;
}

OUTPUT:
Enter the string
programerror

Enter the position from where the characters are to be deleted


7
Enter the number of characters to be deleted
5
The string after deletion is: program
37. 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.)

#include <stdio.h>
#include <string.h>
int main( )
{
char str[20];
int i, l, f = 0;

printf("Enter any string\n");


gets(str);

l = strlen(str);
for(i = 0; i <= l - 1; i++)
{
if(str[i] == str[l - 1 - i])
f = f + 1;
}

if(f == l)
printf("The string is palindrome");
else
printf("The string is not a palindrome");

return 0;
}

OUTPUT:
Enter any string
madam
The string is palindrome

Enter any string


mahesh
The string is not a palindrome
38. Write a C program that displays the position of a character ch in
the string S or – 1 if S doesn‘t contain ch.

#include<stdio.h>
#include<string.h>
int main( )
{
char s[30], t[20];
char *found;

puts("Enter the first string\n ");


gets(s);

puts("Enter the string to be searched\n ");


gets(t);

found = strstr(s, t);

if(found)
printf("Second String is found in the First String at %d position.\n",
found - s);
else
printf("-1");

return 0;
}

OUTPUT:

Enter the first string:


Rajkumar

Enter the string to be searched:


kumar
Second String is found in the First String at 3 position.
39. Write a C program to count the lines, words and characters in a
given text.

#include <stdio.h>
int main( )
{
char ch;
unsigned long linecount, wordcount, charcount;
int u;
linecount=0;
wordcount=0;
charcount=0;

puts(“Enter any string\n”);


while((ch=getc(stdin))!=EOF)
{
if (ch !='\n') {++charcount;}
if (ch==' ' || ch=='\n') {++wordcount;}
if (ch=='\n') {++linecount;}
}

if(charcount>0)
{
++wordcount;
++linecount;
}

printf("\nNumber of characters=%lu\n”, charcount);


printf(“Number of words=%lu\n”, wordcount);
printf(“Number of lines=%lu\n", linecount );

return 0;
}
OUTPUT:
Enter any string
hai everyone
this is pps lab ^d

Number of characters=27
Number of words=6
Number of lines=2
40. Write a menu driven C program that allows a user to enter 5
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.

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

int option;
int smallest(int u, int w, int x, int y, int z);
int largest(int u, int w, int x, int y, int z);
int sum(int u, int w, int x, int y, int z);
int avg(int u, int w, int x, int y, int z);
int main(void)
{

int one, two, three, four, five;


printf ("\t***********************");
printf("\n\t MENU ");
printf("\n\t***********************");
printf("\n\t* 1. SMALLEST *");
printf("\n\t* 2. LARGEST *");
printf("\n\t* 3. SUM *");
printf("\n\t* 4. AVERAGE *");
printf("\n\t)**********************");
printf("\n Please type your choice: ");
scanf ("%d", &option);

printf("\n Please enter 5 integers:");


scanf ("%d %d %d %d %d", &one, &two, &three, &four, &five);
switch(option)
{
case 1: smallest(one, two, three, four, five);
break;

case 2: largest(one, two, three, four, five);


break;

case 3: sum(one, two, three, four, five);


break;

case 4: avg(one, two, three, four, five);


}
return 0;
}
int smallest(int u, int w, int x, int y, int z)
{
if (one<two && one<three && one<four && one<five)
printf("smallest num is=%d", one);
else if (two<one && two<three && two<four && two<five)
printf("smallest num is=%d", two);
else if (three<one && three<two && three<four && three<five)
printf("smallest num is=%d", three);
else if (four<one && four<two && four<three && four<five)
printf("smallest num is=%d", four);
else
printf("smallest num is=%d", five);
}

int largest(int u, int w, int x, int y, int z)


{
if (one>two && one>three && one>four && one>five)
printf("largest num is=%d", one);
else if (two>one && two>three && two>four && two>five)
printf("largest num is=%d", two);
else if (three>one && three>two && three>four && three>five)
printf("largest num is=%d", three);
else if (four>one && four>two && four>three && four>five)
printf("largest num is=%d", four);
else
printf("largest number=%d", five);
}

int sum(int u, int w, int x, int y, int z)


{
int a = one + two + three + four + five;
printf("sum of numbers=%d", a);
return(0);
}

int avg(int u, int w, int x, int y, int z)


{
int b = (one + two + three + four + five)/5;
printf("avg of numbers=%d", b);
return(0);
}

OUTPUT:
***********************
MENU
***********************
* 1. SMALLEST *
* 2. LARGEST *
* 3. SUM *
* 4. AVERAGE *
**********************
Please type your choice
2
Please enter 5 integers
23 45 67 89 08
largest number =89

41. Write a C program to construct a pyramid of numbers as


follows:
/* program to print the following format */
1
12
123
#include<stdio.h>
int main()
{
int i, j, n;
printf(“Enter how many rows?\n”);
scanf(“%d”, &n);
for(i = 1;i <= n; i++)
{
for(j = 1;j <= i; j++)
printf("%4d", j);

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

OUTPUT:
Enter how many rows?
3

1
12
123

42. Write a C program to construct a pyramid of numbers as


follows:
*
**
* * * #include<stdio.h>
int main( )
{
int i, j, n;
printf(“Enter how many rows?\n”);
scanf(“%d”, &n);

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


{
for(j=1;j <= i; j++)
printf(" * ");
printf("\n");
}

return 0;
}

OUTPUT:
Enter how many rows?
3

*
**
***

43. Write a C program to construct a pyramid of numbers as


follows:

1
23
456

#include<stdio.h>
int main( )
{
int i, j, h, n, c=1;
printf(“Enter how many rows?\n”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
for(j=0;j<=i;j++)
{
printf("%4d",c);
c++;
}
printf("\n");
}

return 0;
}

OUTPUT:
Enter how many rows?
3

1
23
456

44. Write a C program to construct a pyramid of numbers as


follows:

1
22
333
4444

#include<stdio.h>
int main( )
{
int i, j, n;
printf(“Enter how many rows?\n”);
scanf(“%d”, &n);

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


{
for(j=1; j<=i; j++)
printf("%4d",i);

printf("\n");
}

return 0;
}

OUTPUT:
Enter how many rows?
3

1
2 2
3 3 3
4 4 4 4

45. Write a C program to construct a pyramid of numbers as


follows:

*
**
***
**
*

#include<stdio.h>
int main( )
{
int i,j,n,columns;
columns=1;
printf("Enter the number of columns\n");
scanf("%d", &n);
for(i=1;i < n*2; i++)
{
for(j=1; j <= columns; j++)
printf(" * ");

if(i < n)
columns++;
else
columns--;

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

OUTPUT:
Enter the number of columns
3
*
**
***
**
*
Sorting and Searching:

46. 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.

#include<stdio.h>
int main( )
{
int i, a[20], n, key, flag = 0;
printf("Enter the size of an array \n");
scanf("%d", &n);

printf("Enter the array elements\n");


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

printf("Enter the key element\n");


scanf("%d", &key);

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


{
if(a[i] == key)
{
flag = 1;
break;
}
}

if(flag == 1)
printf("The key element is found at location %d", i + 1);
else
printf("The key element is not found in the array");
}
OUTPUT:
Enter the size of an array
5
Enter the array elements
1 3 6 2 4
Enter the key element
6
The key element is found at location 3
47. 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.

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

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


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");
return 0;
}
OUTPUT:
Enter the size of array:
6
Enter the array elements in ascending order
11 22 33 44 55 66
Enter the key element
33
The key element is found at location 3
48. Write a C program that implements the Bubble sort method to sort
a given list of integers in ascending order.

#include<stdio.h>
int 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("%4d", a[i]);
}

Output:
Enter the size of the array
5
Enter the array elements
1 8 3 6 2
The sorted array is
1 2 3 6 8
49. Write a C program that sorts the given array of integers using
selection sort in descending order.

#include<stdio.h>
int main( )
{
int n, a[20], max, 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++)


{
max = i;
for(j = i + 1; j < n; j++)
{
if(a[j] > a[max])
max = j;
}
temp = a[i];
a[i] = a[max];
a[max] = temp;
}

printf("The sorted array is\n");


for(i=0; i < n; i++)
printf("%4d", a[i]);
}
OUTPUT:
Enter the size of the array
4
Enter the array elements
1 8 3 9
The sorted array is
1 3 8 9
50. Write a C program that sorts the given array of integers using
insertion sort in ascending order.

#include<stdio.h>
int main( )
{
int i, j, count, temp, number[25];
printf("How many numbers u are going to enter?: ");
scanf("%d",&count);

printf("Enter %d elements: ", count);


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

// Implementation of insertion sort algorithm


for(i=1;i<count; i++)
{
temp=number[i];
j=i-1;
while((temp<number[j])&&(j>=0))
{
number[j+1]=number[j];
j=j-1;
}
number[j+1]=temp;
}

printf("The sorted array is\n ");


for(i = 0;i < count; i++)
printf("%4d ", number[i]);

return 0;
}

OUTPUT:
How many numbers u are going to enter?: 4
Enter 4 elements:
2 6 8 1
The sorted array is
1 2 6 8
51. Write a C program that sorts a given array of names.
/* Program demonstrating sorting array of names */

#include <stdio.h>
#include <string.h>
int main()
{
int i, j, num;
char name[20][10], t_name[15][10], temp[20];
printf("Please enter how many number of names to be sorted\n");
scanf("%d", &num);

printf("Please enter %d names one by one\n", num);


for(i=0; i< num ; i++)
{
scanf("%s",name[i]);
strcpy (t_name[i], name[i]);
}

printf("Names before sorting in alphabetical order\n");


for(i=0; i< num ; i++)
printf("%s\n",t_name[i]);

for(i=0; i < num-1 ; i++)


for(j=i+1; j< num; j++)
if(strcmp(name[i],name[j]) > 0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}

printf("Names after sorting in alphabetical order\n");


for(i=0; i< num ; i++)
printf("%s\n", name[i]);

}
OUTPUT:
Please enter how many number of names to be sorted
5
Please enter 5 names one by one
Raj kiran sravan vijay murali
Names before sorting in alphabetical order
Raj
kiran
sravan
vijay
murali

Names after sorting in alphabetical order


kiran
murali
Raj
sravan
vijay

You might also like