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

PPS LAB PROGRAMS

Uploaded by

chaitubudati
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

PPS LAB PROGRAMS

Uploaded by

chaitubudati
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 75

1.

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.

Arithmetic Operators
#include <stdio.h>
int main()
{
int a,b,c;
printf(“enter a and b values”);
scanf(“%d %d”,&a,&b);
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c); c=a
%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output:
enter a and b values 9 4
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1

Increment and decrement operators


#include <stdio.h>
int main(){
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("a++ = %d \n", a++);
printf("++a = %d \n", ++a);
printf(“b++ = %d \n", b++);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
Output
a++=10
++a = 12
b++=100
--b = 101
++c = 11.500000
++d = 99.500000

Assignment Operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a;
printf("c = %d \n", c);
c += a; // c = c+a
printf("c = %d \n", c);
c -= a; // c = c-a
printf("c = %d \n", c);
c *= a; // c = c*a
printf("c = %d \n", c);
c /= a; // c = c/a
printf("c = %d \n", c);
c %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}

Output
c=5
c = 10
c=5
c = 25
c=5
c=0

Relational Operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d = %d \n", a, b, a == b); // true
printf("%d == %d = %d \n", a, c, a == c); //
false printf("%d > %d = %d \n", a, b, a > b);
//false
printf("%d > %d = %d \n", a, c, a > c); //false
printf("%d < %d = %d \n", a, b, a < b); //false
printf("%d < %d = %d \n", a, c, a < c); //true
printf("%d != %d = %d \n", a, b, a != b); //false
printf("%d != %d = %d \n", a, c, a != c); //true
printf("%d >= %d = %d \n", a, b, a >= b); //true
printf("%d >= %d = %d \n", a, c, a >= c); //false
printf("%d <= %d = %d \n", a, b, a <= b); //true
printf("%d <= %d = %d \n", a, c, a <= c); //true
return 0;
}
Output
5 == 5 = 1
5 == 10 = 0
5>5=0
5 > 10 = 0
5<5=0
5 < 10 = 1
5 != 5 = 0
5 != 10 = 1
5 >= 5 = 1
5 >= 10 = 0
5 <= 5 = 1
5 <= 10 = 1

Logical Operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;// 1 (true) 0(false)
result = (a == b) && (c > b);
printf("(a == b) && (c > b) equals to %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) equals to %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) equals to %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) equals to %d \n", result);
result = !(a != b);
printf("!(a == b) equals to %d \n", result);
result = !(a == b);
printf("!(a == b) equals to %d \n", result);
return 0;
}
Output
(a == b) && (c > b) equals to 1
(a == b) && (c < b) equals to 0
(a == b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0

Bitwise operator
#include <stdio.h>
int main(){
int a = 12, b = 25, num=212, i;
printf("AND = %d", a&b);
printf("OR = %d", a|b);
printf("XOR = %d", a^b);
printf("complement = %d\n",~35);
printf("complement = %d\n",~-12);
for (i=0; i<=2; ++i)
printf("Right shift by %d: %d\n", i, num>>i);
printf("\n");
for (i=0; i<=2; ++i)
printf("Left shift by %d: %d\n", i, num<<i);
return 0;
}
Output
AND = 8
OR = 29
XOR = 21
complement = -36
complement = 11
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53

Left Shift by 0: 212


Left Shift by 1: 424
Left Shift by 2: 848

sizeof Operator
#include <stdio.h>
int main()
{
int a, e[10];
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
printf("Size of integer type array having 10 elements = %lu bytes\n", sizeof(e));
return 0;
}
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8
bytes Size of char = 1
byte
Size of integer type array having 10 elements = 40 bytes

Conditional Operator/Ternary Operator


#include <stdio.h>

int main(){

int year;
printf("Enter a year to check if it is a leap year or not \n");
scanf("%d", &year);

(year%4==0 && year%100!=0) ? printf("Leap Year") :


(year%400 ==0 ) ? printf("Leap Year") : printf("not a leap year");
getch();

}
Output
Enter a year to check if it is a leap year or not
2014
not a leap year

Enter a year to check if it is a leap year or not


2004
Leap Year
b. Write a simple program that converts one given data type to another using auto conversion and
casting. Take the values from standard input.

Using auto conversion


#include<stdio.h>
int main(){
int x; // integer x
char y; // character c
printf(“enter x and y
values”); scanf(“%d
%c”,&x,&y);
// y implicitly converted to int.
// let y value is ‘a’,ASCII value of 'a' is
97 x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
}

Output:

enter x and y values 10 a

x = 107, z = 108.000000

Using type Casting

#include<stdio.h>
int main()
{
double x;
printf(“enter x value:”);
scanf(“%lf”,&x);
// Explicit conversion from double to int
int sum = (int)x + 1;
printf("sum = %d", sum);
return 0;
}

Output:
enter x value: 1.2
sum = 2
2. Simple numeric problems

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

#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("\nMaximum number is a = %d",a);

else if(b>a && b>c)

printf("\nMaximum number is b = %d",b);

else

printf("\nMaximum number is c = %d",c);

if(a<b && a<c)

printf("\nMinimum number is a = %d",a);

else if(b<a && b<c)

printf("\nMinimum number is b = %d",b);

else

printf("\nMinimum number is c = %d",c);

Output

Enter 3 numbers 1

Maximum number is c =3

Minimum number is a =1
b. Write the program for the simple, compound interest.

#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 the value of Rate r = ");

scanf("%f",&r);

printf("Enter the value of Period in year n = ");

scanf("%d",&n);

SI = ((p*r*n)/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;

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


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.

#include <stdio.h>

int main(void)

int num;

printf("Enter your percentage ");

scanf("%d",&num);

printf("\n You entered %d", num); // printing outputs

if(num >= 70){

printf("\n You got Distinction"); // printing outputs

else if ( num >=60 && num<=70){ // Note the space between else & if

printf("\n You got First Class");

else if ( num >=40 &&num<=60)

{ printf(" \nYou got Second class ");

else if ( num < 40){

printf(" \n You Failed in this exam");

return 0;

Output

Enter your percentage 65

You got First Class


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:

5x1=5

5 x 2 = 10

5 x 3 = 15

#include <stdio.h>

int main(){

int n, i, row;

printf("Enter an integer: ");

scanf("%d",&n);

printf("Enter no of rows:

"); scanf("%d",&row);

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

printf("%d * %d = %d \n", n, i, n*i);

return 0;

Output

Enter an integer: 9

Enter no of rows:5

9*1=9

9 * 2 = 18

9 * 3 = 27

9 * 4 = 36

9 * 5 = 45
e. Write a program that shows the binary equivalent of a given positive number between 0 to 255.

#include<stdio.h>

int main()

int n,i; //given by user 24

int bn[50];

printf("enter the number to convert into binary equivalet");

scanf("%d",&n);

for(i=0;n>0;i++) //

bn[i]=n%2;

n=n/2;

printf("binary number

is"); for(i=i-1;i>=0;i--)

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

Output

enter n 12

1100
3. 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 = 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)).

#include<stdio.h>

#include<math.h>

main()

int s=30,u=0,r,t;

float a=9.8;

r=2*s/a;

t=sqrt(r);

printf(“time taken is%d”,t);

Output

time taken is 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)

#include <stdio.h>

void main()

int a, b, c;

char ch;

printf("Enter your operator(+, -, /, *, %)\n");

scanf("%c", &ch);

printf("Enter the values of a and b"); scanf("%d

%d", &a, &b);


switch(ch)

case '+': c = a + b;

printf("addition of two numbers is %d", c);

break;

case '-': c = a - b;

printf("substraction of two numbers is %d", c);

break;

case '*': c = a * b;

printf("multiplication of two numbers is %d", c);

break;

case '/': c = a / b;

printf("remainder of two numbers is %d", c);

break;

case '%': c = a % b;

printf("quotient of two numbers is %d", c);

break;

default: printf("Invalid operator");

break;

Output:

Enter your operator(+, -, /, *, %)

Enter the values of a and b 1 2

addition of two numbers is 3


c. Write a program that finds if a given number is a prime number.

#include <stdio.h>

int main()

int n, i, flag = 0;

printf("Enter a positive integer: ");

scanf("%d",&n);

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

// condition for nonprime number

if(n%i==0)

flag++;

if (flag==2)

printf("%d is a prime number.",n);

else

printf("%d is not a prime number.",n);

return 0;

Output:

Enter a positive integer: 3

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

#include<stdio.h>

#include<math.h>

void main ()

int number = 0, digit = 0, sumOfDigits = 0,original_number,reverse_integer;

printf("Enter any number");

scanf("%d", &number);

original_number=number;

while (number != 0)

digit = number % 10;

reverse_integer=reverse_integer*10 + digit;

number = number / 10;

if (original_number == reverse_integer)

printf("%d is a palindrome.", original_number);

else

printf("%d is not a palindrome.", original_number);

printf ("\nSum of individual digits of a given number is %d", sumOfDigits);

Output:

Enter any number 123

123 is not a 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.

#include <stdio.h>

int main()

int i, n, t1 = 0, t2 = 1, nextTerm;

printf("Enter the number of terms: ");

scanf("%d", &n);

printf("Fibonacci Series: ");

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

printf("%d, ", t1);

nextTerm = t1 + t2;

t1 = t2;

t2 = nextTerm;

return 0;

Output:

Enter the number of terms: 10

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,


f. Write a C program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user.

#include<stdio.h>

void main()

int n, i, j, count;

printf("Enter any number\n");

scanf("%d", &n);

printf("The prime numbers between 1 to %d\n",n);

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

count = 0;

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

if(i % j == 0)

count++;

if(count == 2)

printf("%d\t", i);

} }

Output:

The prime numbers between 1 to 21

2 3 5 7 11 13 17 19

The prime numbers between 1 to 10

2 3 5 7
g. Write a C program to find the roots of a Quadratic equation.

#include<stdio.h>

#include<math.h>

int main(){

float a,b,c;

float d,root1,root2;

printf("Enter a, b and c of quadratic equation: ");

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

d = b * b - 4 * a * c;

if(d < 0){

printf("Roots are complex number.\n");

printf("Roots of quadratic equation are: ");

printf("%.3f%+.3fi",-b/(2*a),sqrt(-d)/(2*a));

printf(", %.3f%+.3fi",-b/(2*a),-sqrt(-d)/(2*a));

return 0;

else if(d==0){

printf("Both roots are equal.\n");

root1 = -b /(2* a);

printf("Root of quadratic equation is: %.3f ",root1);

return 0;

else{

printf("Roots are real numbers.\n");

root1 = ( -b + sqrt(d)) / (2* a);

root2 = ( -b - sqrt(d)) / (2* a);


printf("Roots of quadratic equation are: %.3f , %.3f",root1,root2);

return 0;

Output:

Enter a, b and c of quadratic equation: 2 4 1

Roots are real numbers.

Roots of quadratic equation are: -0.293, -1.707


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

main()

float x,s=0,i;

printf(“enter fractional value”);

scanf(“%f”,&x); for(i=1;i<=3;i+

+)

s+=pow(-x,i)/(2*i);

s=1-s; printf(“result=

%f”,s);

Output:

enter fractional value 2

result=-0.3
i. 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 n, x, i, sum = 0;

printf("Enter the limit");

scanf("%d", &n);

printf("Enter the value of x");

scanf("%d", &x);

if(x < 0 || n < 0)

printf("illegal value");

else

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

sum=sum + pow(x, i);

printf("sum=%d", sum);

Output:

Enter the limit 2

Enter the value of x 2

sum=7
4. Arrays and Pointers and Functions:

a. Write a C program to find the minimum, maximum and average in an array of integers.

#include <stdio.h>

#define MAX_SIZE 100 // Maximum array size

int main()

int arr[MAX_SIZE];

int i, max, min, size,avg=0,sum=0;

/* 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=0; 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+=arr[i];

avg=sum/size;

/* Print maximum and minimum element */ printf("\

nMaximum element = %d\n", max);

printf("Minimum element = %d\n", min);

printf("Average = %d", avg);

return 0;

Output

Enter size of the array:

Enter elements in the array:

21349

Maximum element = 9

Minimum element = 1
Average = 3
b. Write a functions to compute mean, variance, Standard Deviation, sorting of n elements in single
dimension array.

#include <stdio.h>

#include <math.h>

int cal(float [10],int);

#define MAXSIZE 10

void main()

float x[MAXSIZE];

int i, n;

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

scanf("%d", &n);

printf("Enter %d real numbers \n", n);

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

scanf("%f", &x[i]);

cal(x,n);

int cal(float x[10],int n)

int i, sum=0, sum1 = 0;

float average, variance, std_deviation;

/* Compute the sum of all elements */

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

sum = sum + x[i];


}

average = sum / (float)n;

/* Compute variance and standard deviation */

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

sum1 = sum1 + pow((x[i] - average), 2);

variance = sum1 / (float)n;

std_deviation = sqrt(variance);

printf("Average of all elements = %.2f\n", average);

printf("variance of all elements = %.2f\n",

variance); printf("Standard deviation = %.2f\n",

std_deviation);

Output:

Enter the value of N

Enter 4 real numbers

1234

Average of all elements = 2.50

variance of all elements = 1.25

Standard deviation = 1.12


c. Write a C program that uses functions to perform the following:

i. Addition of Two Matrices

#include <stdio.h>

void matrixAddition(int a[10][10], int b[10][10], int sum[10][10]);

int rows, columns;

int main()

int a[10][10], b[10][10], sum[10][10], i, j;

/* get the number of rows and columns from user */

printf("Enter the no of rows and columns:");

scanf("%d%d", &rows, &columns);

/* input first matrix */

printf("Enter the input for first matrix:\n");

for (i = 0; i < rows; i++) {

for (j = 0; j < columns; j++)

{ scanf("%d", &a[i][j]);

/* input second matrix */

printf("Enter the input for second matrix:\n");

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

{
for (j = 0; j < columns; j++)

{ scanf("%d", &b[i][j]);

/* matrix addtion */

matrixAddition(a, b, sum);

/* print the results */

printf("\nResult of Matrix Addition:\n");

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

for (j = 0; j < columns; j++)

printf("%d", sum[i][j]);

printf("\t");

printf("\n");

return 0;

/* adds two matrices and stores the output in third matrix */

void matrixAddition(int a[10][10], int b[10][10], int sum[10][10])

int i, j;
for (i = 0; i < rows; i++)

for (j = 0; j < columns; j++)

sum[i][j] = a[i][j] + b[i][j];

return;

}Output:

Enter the number of rows and columns of matrix 2 2

Enter the elements of first matrix

11

11

Enter the elements of second matrix

11

11

Sum of entered matrices:-

22

22
ii. Multiplication of Two Matrices

#include<stdio.h>

int mulmatrix(int [10][10],int [10][10],int,int,int,int);

int main()

int m, n, p, q, c, d, k,first[10][10], second[10][10];

printf("Enter number of rows and columns of first matrix");

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

printf("Enter elements of first matrix\n");

for (c = 0; c < m; c++)

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

scanf("%d", &first[c][d]);

printf("Enter number of rows and columns of second matrix");

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

if (n != p)

printf("The matrices can't be multiplied with each other.\n");

else{

printf("Enter elements of second matrix\n");

for (c = 0; c < p; c++){

for (d = 0; d < q; d++)

scanf("%d", &second[c][d]);

mulmatrix(first,second,m,n,p,q);
}

int mulmatrix(int first[10][10],int second[10][10],int m,int n,int p,int q)

int c,d,k,sum=0,multiply[10][10];

for (c = 0; c < m; c++) {

for (d = 0; d < q; d++)

{ for (k = 0; k < p; k++)

sum = sum + first[c][k]*second[k][d];

multiply[c][d] = sum;

sum = 0;

printf("Product of the matrices:\n");

for (c = 0; c < m; c++) {

for (d = 0; d < q; d++) printf("%d\

t", multiply[c][d]); printf("\n");

Output:

Enter the number of rows and columns of first matrix 2 2

Enter the elements of first matrix

11

11

Enter the number of rows and columns of first matrix 2 2


Enter the elements of second matrix

11

11

Product of the matrices:

22

22

iii. Transpose of a matrix with memory dynamically allocated for the new matrix as row and
column counts may not be same.

#include <stdio.h>

int main()

int a[10][10], transpose[10][10], r, c, i, j;

printf("Enter rows and columns of matrix: ");

scanf("%d %d", &r, &c);

// Storing elements of the matrix printf("\

nEnter elements of matrix:\n"); for(i=0; i<r;

++i)

for(j=0; j<c; ++j)

printf("Enter element a%d%d: ",i, j);

scanf("%d", &a[i][j]);

// Displaying the matrix a[][] */

printf("\nEntered Matrix: \n");

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

for(j=0; j<c; ++j)

{
printf("%d ", a[i][j]);

if (j == c-1) printf("\n\

n");

// Finding the transpose of matrix a

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

for(j=0; j<c; ++j)

transpose[j][i] = a[i][j];

// Displaying the transpose of matrix a

printf("\nTranspose of Matrix:\n");

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

for(j=0; j<r; ++j)

printf("%d ",transpose[i][j]);

if(j==r-1)

printf("\n\n");

return 0;

Enter rows and columns of matrix: 2

Enter elements of matrix:

Enter element a00: 1

Enter element a01: 2


Enter element a10: 3

Enter element a11: 4

Entered Matrix:

12

34

Transpose of Matrix:

13

24

d. Write C programs that use both recursive and non-recursive functions.

i. To find the factorial of a given integer.

#include <stdio.h>

int recfactorial(int

x);

int nonrecfactorial(int x);

void main()

int n, a, b;

printf("Enter any number\n");

scanf("%d", &n);

a = recfactorial(n);

printf("The factorial of a given number using recursion is %d \n", a);

b = nonrecfactorial(n);

printf("The factorial of a given number using nonrecursion is %d ", b);

int recfactorial(int x)

{ int f;

if(x == 0){
return(1);

else{

f = x * recfactorial(x - 1);

return(f);

int nonrecfactorial(int x)

{ int i, f = 1;

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

f = f * i;

return(f);

Output

Enter any number


4
The factorial of a given number using recursion is 24
The factorial of a given number using nonrecursion is
24

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

#include <stdio.h>

int recgcd(int x, int y);

int nonrecgcd(int x, int y);

void main()

int a, b, c, d;
printf("Enter two numbers a and b");

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

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);

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 and b 11 2


The gcd of two numbers using recursion is 1
The gcd of two numbers using nonrecursion is 1

iii. To find x^n

#include <stdio.h>

int main()

int base, exponent;

int result = 1;

printf("Enter a base number: ");

scanf("%d", &base);

printf("Enter an exponent: ");

scanf("%d", &exponent);

result=nonrec(base,exponent);

printf("Answer = %lld\n",

result);

result = recpower(base, exponent);

printf("recursion Answer = %lld", result);

int recpower(int base, int a)

{ if (a != 0)

return (base * recpower(base, a - 1));

else

return 1;

int nonrec(int b,int exponent)

{
int result=1;

for (exponent; exponent>0; exponent--)

result = result * b;

Output

Enter a base number: 5

Enter an exponent: 5

Answer = 3125

recursion Answer = 3125

e. Write a program for reading elements using pointer into array and display the values using
array.

#include <stdio.h>

int main(){

int arr[10]; //declare integer array

int *pa; //declare an integer

pointer int i;

pa=&arr[0]; //assign base address of

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

for(i=0;i< 10; i++){

scanf("%d",pa+i); //reading through pointer

printf("\nEntered array elements are:\n");

for(i=0;i<10;i++){

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

}
return 0;

Output:

Enter array elements:

1234551233

Entered array elements are:

1234551233

f. Write a program for display values reverse order from array using pointer.

#include<stdio.h>
#define MAX 30
void main() {
int size, i, arr[MAX];
int *ptr;
ptr = &arr[0];
printf("\nEnter the size of array : ");
scanf("%d", &size);
printf("\nEnter %d integers into array: ", size);
for (i = 0; i < size; i++) {
scanf("%d", ptr); ptr+
+;
}
ptr = &arr[size - 1];

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

for (i = size - 1; i >= 0; i--) {


printf("\nElement%d is: %d ", i, *ptr);
ptr--;
}
}
Output:
Enter the size of array : 3

Enter 3 integers into array: 1

Elements of array in reverse order are :


Element2 is: 3

Element1 is: 2

Element0 is: 1

g. Write a program through pointer variable to sum of n elements from array.

#include<stdio.h>

#include<conio.h>

void main() {

int

numArray[10];

int i, sum = 0;

int *ptr;

printf("\nEnter 10 elements :

"); for (i = 0; i < 10; i++)

scanf("%d", &numArray[i]);

ptr = numArray; /* a=&a[0] */

for (i = 0; i < 10; i++) {

sum = sum +

*ptr; ptr++;

printf("The sum of array elements : %d", sum);

Output:

Enter 10 elements : 11 12 13 14 15 16 17 18 19 20

The sum of array elements is 155


5. Files

a. Write a C program to display the contents of a file to standard output device.

#include <stdio.h>

#include <stdlib.h>

int main()

FILE *fptr;

char filename[100], c;

printf("Enter the filename to open:");

scanf("%s", filename);

fptr = fopen(filename, "r"); // Open file

if (fptr == NULL){

printf("Cannot open file \n");

exit(0);

c = fgetc(fptr); // Read contents from

file while (c != EOF){

printf ("%c", c);

c = fgetc(fptr);

fclose(fptr);

return 0;
}

Output:

Enter the filename to open: a.txt

/*Contents of a.txt*/

b. Write a C program which copies one file to another, replacing all lowercase characters with their
uppercase equivalents.

#include<stdio.h>

#include<stdlib.h>

int main()

FILE *fp1, *fp2;

char ch;

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

if (fp1 == NULL)

puts("File does not exist..");

exit(1);

fp2 = fopen("target.txt", "w");

if (fp2 == NULL)

puts("File does not exist..");

fclose(fp1);

exit(1);

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

{
ch = toupper(ch);

fputc(ch,fp2);

printf("\nFile successfully copied..");

return 0;

Output

File successfully copied..


Content in source.txt file.

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.

#include <stdio.h>

#include <stdlib.h>

int main()

{
int count=0;

char c;

FILE *fp1;

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

if (fp1 == NULL)

puts("Could not open files");

exit(0);

printf("enter a search character");

scanf("%c",&c);

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

count++;

printf("%d",count);

fclose(fp1);

return 0;

e. 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).

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

int main()
{
// Open two files to be merged
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");
// Open file to store the result
FILE *fp3 = fopen("file3.txt", "w");
char c;

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


{
puts("Could not open files");
exit(0);
}

// Copy contents of first file to file3.txt


while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);

// Copy contents of second file to file3.txt


while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);

printf("Merged file1.txt and file2.txt into file3.txt");

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

Output:

Merged file1.txt and file2.txt into file3.txt


6. Strings

a. 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], len, i, k;

printf("Enter the roman number\n");

scanf("%s", &rom);

len =strlen(rom);

for(i = 0; i < len; 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': a[i] = 500;

break;

case 'M': a[i] = 1000;

break;

default : printf("Invalid choice");

break;

k = a[len - 1];

for(i = len - 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


XVII

decimal equivalent is 17

b. Write a C program that converts a number ranging from 1 to 50 to Roman equivalent

#include <stdio.h>

int main () {

int num;

printf("Enter your input:");

scanf("%d", &num);

printf("Roman Number: ");

while (num > 0) {

if (num >= 1000) {

/* M - 1000 */

printf("M");

num = num - 1000;

} else if (num >= 500) {

/*

* D is 500. CM is 900

* CM = M - C = 1000 - 100 => 900

*/

if (num >= 900) {

printf("CM");

num = num -

900;

} else {

printf("D");

num = num - 500;

}
} else if (num >= 100) {

/* C is 100. CD is 400

* CD = D - C = 500 - 100 => 400

*/

if (num >= 400) {

printf("CD");

num = num - 400;

} else {

printf("C");

num = num - 100;

} else if (num >= 50) {

/* L is 50. XC is 90

* XC = C - X = 100 - 10 => 90

*/

if (num >= 90) {

printf("XC");

num = num - 90;

} else {

printf("L");

num = num - 50;

} else if (num >= 9) {

/* XL is 40. IX is 9. X is 10

* XL = L - X = 50 - 10 = 40

* IX = X - I = 10 - 1 = 9
*/

if (num >= 40) {

printf("XL");

num = num - 40;

} else if (num == 9)

{ printf("IX");

num = num - 9;

} else {

printf("X");

num = num - 10;

} else if (num >= 4) {

/* V is 5 and IV is 4

* IV = V - I = 5 - 1 => 4

*/

if (num >= 5) {

printf("V");

num = num - 5;

} else {

printf("IV");

num = num - 4;

} else {

printf("I");

num = num - 1;

}
}

printf("\n");

Output

Enter your input:22

Roman Number: XXII

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

#include<stdio.h>

#include<string.h>

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);

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

After inserting the string is sachtendulkarin

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

#include<stdio.h>

#include<string.h>

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);

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

sachin

Enter the position where characters are to be deleted

Enter the number of characters to be deleted

The string is sain

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

#include <stdio.h>

#include <string.h>

void 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");

Output:

Enter any string

madam

The string is a palindrome

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.

#include<stdio.h>

#include<string.h>

void main()

char s[30], t[20];


char *found;

puts("Enter the first string: ");

gets(s);

puts("Enter the string to be searched: ");

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");

Output:

1.Enter the first string:

hyderabad

Enter the string to be searched:

de

second string is found in the first string at 2 position


h. Write a C program to count the lines, words and characters in a given text.

#include <stdio.h>

#include <string.h>

void main()

char str[100];

int i = 0, l = 0, f = 1;

puts("Enter any string\n");

gets(str);

for(i = 0; str[i] !='\0'; i++)

l = l + 1;

printf("The number of characters in the string are %d\n", l);

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

if(str[i] == ' ')

f = f + 1;

printf("The number of words in the string are %d", f);

Output:
Enter any string

abc def ghi jkl mno pqr stu vwx yz

The number of characters in the string are 34

The number of words in the string are 9


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

#include <stdio.h>

#include <stdlib.h>

int option;

int small(int n,int a[]);

int large(int n,int a[]);

int sum(int n,int a[]);

int avg(int n,int a[]);

int menu();

int a[20],n,i,small1=0,sum1=0,large1=0,avg1=0;

int main(void)

printf("enter no of elements");

scanf("%d",&n);

printf("enter elements");

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

scanf("%d",&a[i]);

menu();

printf("\n Please type your choice: ");

scanf("%d",&option);

switch(option)

{
case 1: small(n,a);

break;

case 2: large(n,a);

break;

case 3: sum(n,a);

break;

case 4: avg(n,a);

break;

default:

printf("invalid");

return 0;

int menu()

printf ("\n***********************");

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**********************");

int small(int n,int a[])

{
small1=a[0];

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

if(small1>a[i])

small1=a[i];

printf("%d",small1);

int large(int n,int a[])

large1=a[0];

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

if(large1<a[i])

large1=a[i];

printf("%d",large1);

int sum(int n,int a[])

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

{
sum1=sum1+a[i];

printf("%d",sum1);

int avg(int n,int a[])

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

sum1=sum1+a[i];

avg1=sum1/n; printf("\n

%d",avg1);

Output

enter no of elements

enter elements 2 3 4 5 6 4

***********************

* MENU *

* *

* 1. SMALLEST *

* 2. LARGEST *

* 3. SUM *

* 4. AVERAGE *

**********************

Please type your choice:4


4

b. Write a C program to construct a pyramid of numbers as follows:

a) 1

12

123

#include <stdio.h>

int main()

int i, j;

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

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

printf("%d ",j);

printf("\n");

return 0;

Output

12

123

b) *

**
***

#include <stdio.h>

int main()

int i, j;

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

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

printf("*");

printf("\n");

return 0;

Output

**

***

c) Floyd's Triangle

23

456

#include <stdio.h>

int main()

{
int i, j, number= 1;

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

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

printf("%d ", number);

++number;

printf("\n");

return 0;

Output

23

456

d)

22

333

4444

#include <stdio.h>

int main()

int i, j,num=1;

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


{

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

printf("%d", num);

++num;

printf("\n");

return 0;

Output

22

333

4444

e)

**

***

**

#include<stdio.h>

int main()

int i, j, N, columns;

printf("Enter number of columns:");


scanf("%d",&N);

columns=1; printf("\

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 number of columns:

**

***

****

***

**
*

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

#include<stdio.h>

void 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");

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

scanf("%d", &a[i]);

printf("Enter the key elements");

scanf("%d", &key);

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");

Output

Enter the size of an array 5

Enter the array elements

23456

Enter the key elements

The key elements is found at location 3

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.

#include<stdio.h>

void main()

int a[20], i, n, key, low, high, mid;

printf("enter n value");

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");

Output

enter n

value 5

Enter the array elements in ascending order

23456

Enter the key element

4
The key element is found at location 3

c. Write a C program that implements the Bubble sort method to sort a given list of integers in
ascending order.

#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]);

Output

Enter the size of the array 5

Enter the array elements

23756

The sorted array is

d. Write a C program that sorts the given array of integers using selection sort in descending order

#include<stdio.h>

void main()

int n, a[20], min, 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++)

min = i;

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

if(a[j] > a[min])

min = j;

temp = a[i];

a[i] = a[min];

a[min] = temp;

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

for(i = 0; i < n; i++) printf("%d\

n", a[i]);

Output

Enter the size of the array 5

Enter the array elements

23756

The sorted array is

2
e. Write a C program that sorts the given array of integers using insertion sort in ascending order

#include <stdio.h>

int main()

int n, array[1000], i, j, t;

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

scanf("%d", &n);

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

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

scanf("%d", &array[i]);

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

j = i;

while ( j > 0)

if(array[j-1] > array[j])

{ t = array[j];

array[j] = array[j-1];

array[j-1] = t;

j--;

printf("Sorted list in ascending order:\n");

for (i = 0; i <= n - 1; i++) {


printf("%d\n", array[i]);

return 0;

Output

Enter number of elements 5

Enter 5 integers

2 3 7 10 6

Sorted list in ascending order:

10

f. Write a C program that sorts a given array of names

#include<stdio.h>

#include<string.h>

int main(){

int i,j,count;

char str[10][10],temp[10];

printf("No of strings to be

entered:"); scanf("%d",&count);

printf("Enter the Strings one by one: ");

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

scanf("%s",&str[i]);

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

{ if(strcmp(str[i],str[j])>0)

strcpy(temp,str[i]);

strcpy(str[i],str[j]);

strcpy(str[j],temp);

printf("Order of Sorted Strings are:\n");

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

puts(str[i]);

return 0;

Output

How many strings u are going to enter?: 5

Enter Strings one by one:

Sri

Devi

College

Engineering

Technology

Order of Sorted Strings:

College

Devi

Engineering

Sri
Technology

You might also like