Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 64

Laboratory Manual

of

Programming for problem solving

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

JNTUH COLLEGE OF ENGINEERING SULTANPUR

Sultanpur,Sangareddy District, Pulkal, Telangana 502293

Web: www.jntuhces.ac.in

(2020-21)
CS106ES/CS206ES: PROGRAMMING FOR PROBLEM SOLVING LAB B.Tech. I Year I Sem. L T
P C 0 0 3 1.5

[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

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 to find the max and min from the three numbers.
b. Write the program for the simple, compound interest.
c. Write the 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:
5x1=5
5 x 2 = 10
5 x 3 = 15
e. 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 = 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)).
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. ( 1-x/2 +x^2/4-x^3/6 )
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.

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:
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.
d. Write C programs that use both recursive and non-recursive functions
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.
e. Write a program for reading elements using pointer into array and display the values using array.
f. Write a program for display values reverse order from array using pointer.
g. 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.
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:
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.
d. 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.)
e. Write a C program that displays the position of a character ch in the string S or – 1 if S doesn‘t contain ch.
f. 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 * 1 1 *
12 ** 23 22 **
123 *** 456 333 ***
4444 **
*

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, McGraw Hill, 4th Edition
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.

Program:

#include<stdio.h>
int main()
{
int a = 9,b = 4, c,result;
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);
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
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);
printf("Size of int=%lu bytes\n",sizeof(a));

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

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

result = (a&b);
printf("bitwise and between a and b is %d",result);

return 0;
}
Output:-
systemno30:~/C_Lab$ gcc 1_Operators.c
systemno30:~/C_Lab$ ./a.out
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b = 1
++a = 10
--b = 3
c = 10
c = 20
c = 10
c = 100
c = 10
c=0
Size of int=4 bytes
10 == 3 = 0
10 == 0 = 0
10 > 3 = 1
10 > 0 = 1
10 < 3 = 0
10 < 0 = 0
10 != 3 = 1
10 != 0 = 1
10 >= 3 = 1
10 >= 0 = 1
10 <= 3 = 0
10 <= 0 = 0
(a == b) && (c > b) equals to 0
(a == b) && (c < b) equals to 0
(a == b) || (c < b) equals to 1
(a != b) || (c < b) equals to 1
!(a == b) equals to 0
!(a == b) equals to 1
bitwise and between a and b is 2
Program:
#include<stdio.h>

void main( )

int a,b;

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

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

printf("The Arithmetic Operators results is: %d %d %d %d\n", a+b,a-b,a*b,a/b);

printf("The Relational Operators result is : %d %d %d %d\n", a>b,a<b,a>=b,a<=b);

printf("The Logical Operators result is : %d %d %d %d\n", a&&b,a||b,a==b,!(a==b));

printf("The Increment Operator result is : %d %d %d %d\n",a++,++a,b++,++b);

printf("The Decrement Operator result is : %d %d %d %d\n",a--,--a,b--,--b);

printf("The Bitwise AND Operator result is : %d\n",a&b);

printf("The Bitwise OR Operator result is : %d\n",a|b);

printf("The Bitwise NOT Operator result is : %d\n",a^b);

Output:

systemno30:~/C_Lab$ gcc 1_a_OperatorsInC.c

systemno30:~/C_Lab$ ./a.out

enter the values of a and b2 4

The Arithmetic Operators results is: 6 -2 8 0

The Relational Operators result is : 0 1 0 1

The Logical Operators result is :1101

The Increment Operator result is : 3 3 5 5

The Decrement Operator result is : 3 3 5 5

The Bitwise AND Operator result is : 0

The Bitwise OR Operator result is : 6

The Bitwise NOT Operator result is : 6


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

Program:
#include<stdio.h>
void main()
{
int i;
char y;
float z;

printf("Enter an integer and character value:\n");


scanf("%d %c",&i,&y);
i+=y;
printf("After auto conversion i value is %d\n",i);

printf("Enter a float value:\n");


scanf("%f",&z);
i+=(int)z;
printf("Value of i after type casting %d\n",i);
}

Output:-

systemno30:~/C_Lab$ gcc 1_b_CastingConversation.c


systemno30:~/C_Lab$ ./a.out
Enter an integer and character value:
25
g
After auto conversion i value is 128
Enter a float value:
25.2
Value of i after type casting 153
2. Simple numeric problems:

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

Program:
#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter a, b, c:\n");
scanf("%d%d%d",&a,&b,&c);
//finding maximum of three numbers
if(a>b && a>c)
printf("\n a is Maximum");
else if(b>c && b>a)
printf("\n b is Maximum ");
else
printf("\n c is Maximum ");
//finding minimum of three numbers
if(a<b && a<c)
printf("\na is Minimum");
else if(b<c && b<a)
printf("\nb is Minimum");
else
printf("\nc is Minimum");

Output:

systemno30:~/C_Lab$ gcc 2_a_MinMax.c


systemno30:~/C_Lab$ ./a.out
Enter a, b, c:
5 1 9
c is Maximum
b is Minimum
b. Write the program to find SI and CI

Program:
#include<stdio.h>
void main()
{
int p;
float t,r,SI,CI;
printf("Enter p, t, r:\n");
scanf("%d%f%f",&p,&t,&r);
SI=(p*t*r)/100;
CI=(p*(pow((1+r/100),t)))-p;
printf("SI = %f \n CI = %f\n",SI,CI);

Output:

systemno30:~/C_Lab$ gcc 2_b_SimpleCompound.c -lm


systemno30:~/C_Lab$ ./a.out
Enter p, t, r:
5 7 9
SI = 3.150000
CI = 4.140198
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.

Program:
#include<stdio.h>
void main()
{
int n,per;
printf("Enter Marks:\n");
scanf("%d",&n);
per = n*100/1000; //percentage calculation
if(per>=70)
printf("grade is distinction\n ");
else if( per>=60 && per<70)
printf("First class");
else if(per>=40 && per<60)
printf("Second class");
else
printf("Fail");
}

Output:

systemno30:~/C_Lab$ gcc 2_c_Grades.c


systemno30:~/C_Lab$ ./a.out
Enter marks(below 1000): 567
Second 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

Program:
#include<stdio.h>
void main()
{
int i,n;
printf("Enter a number: ");
scanf("%d",&n);
for(i=1;i<=3;i++)
{
printf("%d * %d = %d\n",n,i,n*i);
}

Output:-

systemno30:~/C_Lab$ gcc 2_d_MultiplicationTable.c


systemno30:~/C_Lab$ ./a.out
Enter a number: 5
5*1=5
5 * 2 = 10
5 * 3 = 15
e. Write a program that shows the binary equivalent of a given positive number between 0 to 255.

Program:
#include<stdio.h>
void main()
{
int n,bin=0,r,i=1;
printf("Enter a number between o to 255:\n");
scanf("%d",&n);
while(n!=0)
{
r=n%2;
n=n/2;
bin+=r*i;
i*=10;

}
printf("Binary number is %d\n",bin);
}

Output:

systemno30:~/C_Lab$ gcc 2_e_BinaryEquivalent.c


systemno30:~/C_Lab$ ./a.out
Enter a number between 0 to 255:
5
Binary number is 101
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)).

Program:
#include<stdio.h>
int main()
{
int s,u,t,a,i;
printf("\nEnter accelaration (a): ");
scanf("%d",&a);
printf("\nEnter velocity (u): ");
scanf("%d",&u);
printf("\nEnter time (t): ");
scanf("%d",&t);
//for(i=9;i>=0;i--)
{
s = u*t + (1/2)*a*t*t;
printf("\nTime taken to reach i floor = %d\n",s);
}
}

Output:

systemno30:~/C_Lab$ gcc 3_a_DistanceCal.c


systemno30:~/C_Lab$ ./a.out
Enter accelaraion (a):
Enter velocity (u):
Enter time (t):
Time taken to reach 9 floor =
Time taken to reach 8 floor =
Time taken to reach 7 floor =
Time taken to reach 6 floor =
Time taken to reach 5 floor =
Time taken to reach 4 floor =
Time taken to reach 3 floor =
Time taken to reach 2 floor =
Time taken to reach 1 floor =
Time taken to reach 0 floor =
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)

Program:

#include<stdio.h>
void main()
{
int a,b,c;
char x;
printf("Enter two numbers a and b: ");
scanf("%d%d",&a,&b);
printf("Enter an operator: ");
scanf("%c",&x);
switch(x)
{
case '+':
c=a+b;
printf("Sum = %d\n",c);
break;
case '-':
c=a-b;
printf("Difference = %d\n",c);
break;
case '*':
c=a*b;
printf("Product = %d\n",c);
break;
case '/':
c=a/b;
printf("Quotient = %d\n",c);
break;
case '%':
c=a%b;
printf("Remainder = %d\n",c);
break;
default:
printf("Invalid choice\n");

}
}
Output:
systemno30:~/C_Lab$ gcc 3_b_OperatorsUsingSwitch.c
systemno30:~/C_Lab$ ./a.out
Enter two numbers a and b: 5 6
Enter an operator: +
Sum = 11
systemno30:~/C_Lab$ ./a.out
Enter two numbers a and b: 5 2
Enter an operator: -
Difference = 3
systemno30:~/C_Lab$ ./a.out
Enter two numbers a and b: 5 2
Enter an operator: *
Product = 3
systemno30:~/C_Lab$ ./a.out
Enter two numbers a and b: 5 2
Enter an operator: /
Quotient = 2
systemno30:~/C_Lab$ ./a.out
Enter two numbers a and b: 5 2
Enter an operator: %
Reminder = 1
c. Write a program that finds if a given number is a prime number

Program:
#include<stdio.h>
void main()
{
int n,i,count=0;
printf("Enter a number:\n");
scanf("%d",&n);
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
count++;
break;
}
}
if(c==0)
{
printf("%d is a prime number\n",n);
}
else
{
printf("%d is not a prime number\n",n);
}
}

Output:

systemno30:~/C_Lab$ gcc 3_c_PrimeNumber.c


systemno30:~/C_Lab$ ./a.out
Enter a number:
5
5 is a prime number
systemno30:~/C_Lab$ ./a.out
Enter a number:
6
6 is not 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.

Using For Loop:

Program:
#include<stdio.h>
void main()
{
int n,r,t,s=0,reverse=0;//n=123
printf("Enter a number:\n");
scanf("%d",&n);
t=n;//t=123
for(;n!=0;n/=10)//123,12,1
{
r=n%10;//last digit = 3,2,1
s=s+r;//s=0+3=3,3+2=5,5+1=6
reverse=reverse*10+r;//0*10+3=3,3*10+2=32,32*10+1=321
}
printf("Sum of individual digits of %d is %d\n",t,s);
printf("Reverse of %d is %d\n",t,reverse);
if(t==reverse)
printf("%d is a Palindrome\n",t);
else
printf("%d is not a Palindrome\n",t);
}

Output:

systemno30:~/C_Lab$ gcc 3_d_Palindrome.c


systemno30:~/C_Lab$ ./a.out
Enter a number:
151
Sum of individual digits of 151 is 7
Reverse of 151 is 151
151 is a Palindrome

systemno30:~/C_Lab$ ./a.out
Enter a number:
152
Sum of individual digits of 152 is 8
Reverse of 152 is 251
152 is not a Palindrome
Using WhileLoop:

Program:

#include<stdio.h>
void main()
{
int n,r,temp,sum=0,reverse=0;//n=123
printf("Enter a number:\n");
scanf("%d",&n);
temp=n;//t=123
while(n>0)//123,12,1
{
r=n%10; //last digit = 3,2,1
sum=sum+r; //s=0+3=3,3+2=5,5+1=6
reverse=reverse*10+r; //0*10+3=3,3*10+2=32,32*10+1=321
n = n/10; //12,1
}
printf("Sum of individual digits of %d is %d\n",temp,sum);
printf("Reverse of %d is %d\n",temp,reverse);
if(temp==reverse)
printf("%d is a Palindrome\n",temp);
else
printf("%d is not a Palindrome\n",temp);
}

Output:
systemno30:~/C_Lab$ gcc 3_d_SumAndPalindrome_WhileLoop.c
systemno30:~/C_Lab$ ./a.out
Enter a number:
123
Sum of individual digits of 123 is 6
Reverse of 123 is 321
123 is not a Palindrome

systemno30:~/C_Lab$ ./a.out
Enter a number:
151
Sum of individual digits of 151 is 7
Reverse of 151 is 151
151 is 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.

Using WhileLoop:

Program:
#include<stdio.h>
void main()
{
int a=0,b=1,c,n,i=0;
printf("Enter a number:\n");
scanf("%d",&n);
printf("%d\t%d ",a,b);
while(i<n-2)
{
c=a+b;
a=b;
b=c;
printf("\t%d",c);
i++;
}
}

Output:

systemno30:~/C_Lab$ gcc 3_e_FibonacciSequence.c


systemno30:~/C_Lab$ ./a.out
Enter a number:
5
0 1 1 2 3

Using For Loop:

Program:
#include<stdio.h>
void main()
{
int a=0,b=1,c,n,i;
printf("Enter a number:\n");
scanf("%d",&n);
printf("%d\t%d ",a,b);
for(i=0;i<n-2;i++)
{
c=a+b;
a=b;
b=c;
printf("\t%d",c);
}
printf("\n");
}

Output:

systemno30:~/C_Lab$ gcc 3_e_FibonacciSequence_ForLoop.c


systemno30:~/C_Lab$ ./a.out
Enter a number:
5
0 1 1 2 3
f. Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied
by the user.

Program:

#include<stdio.h>
void main()
{
int i,j,n,count;
printf("Enter a number:\n");
scanf("%d",&n);
printf("Prime numbers between 1 and %d is : \n",n);
for(j=1;j<=n;j++)
{
count=0;
for(i=2;i<=j/2;i++)
{
if(j%i==0)
{
count++;
break;
}
}
if(count==0)
{
printf("%d \t",j);
}

}
}

Output:

systemno30:~/C_Lab$ gcc 3_f_PrimeNumbers_1toN.c


systemno30:~/C_Lab$ ./a.out
Enter a number:
10
Prime numbers between 1 and 10 is :
1 2 3 5 7
g. Write a C program to find the roots of a Quadratic equation.

Program:
#include<stdio.h>
#include<math.h>
int main()
{
double a, b, c, determinant, root1,root2, realPart, imaginaryPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf%lf%lf",&a, &b, &c);
determinant = b*b-4*a*c;
// condition for real and different roots
if (determinant > 0)
{
// sqrt() function returns square root
root1 = (-b+sqrt(determinant))/(2*a);
root2 = (-b-sqrt(determinant))/(2*a);
printf("root1 = %.3lf and root2 = %.2lf\n",root1 , root2);
printf("Roots are real and unequal\n");
}
//condition for real and equal roots
else if (determinant == 0)
{
root1 = root2 = -b/(2*a);
printf("root1 = root2 = %.2lf\n", root1);
printf("Roots are real and equal\n");
}
// if roots are not real
else
{
realPart = -b/(2*a);
imaginaryPart = sqrt(-determinant)/(2*a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi\n", realPart, imaginaryPart, realPart,
imaginaryPart);
printf("Imaginary Roots\n");
}
return 0;
}

Output:

systemno30:~/C_Lab$ gcc 3_g_RootsOfQuadraticEquation.c -lm


systemno30:~/C_Lab$ ./a.out
Enter coefficients a, b and c: 1 2 5
root1 = -1.00+2.00i and root2 = -1.00-2.00i
Imaginary Roots

systemno30:~/C_Lab$ ./a.out
Enter coefficients a, b and c: 1 4 2
root1 = -0.586 and root2 = -3.41
Roots are real and unequal
h. Write a C program to calculate the following, where x is a fractional value.
1-x/2 +x^2/4-x^3/6

Program:
#include<stdio.h>
#include<math.h>
void main()
{
float y,x;
printf("Enter a fractional value:\n");
scanf("%f",&x);
y=1-(x/2)+((pow(x,2))/4)-((pow(x,3))/6);
printf("1-x/2+x^2/4+x^3/6 = %f",y);
}

Output:

systemno30:~/C_Lab$ gcc 3_h_EquationCalOfX.c -lm


systemno30:~/C_Lab$ ./a.out
Enter a fractional value:
5
1-x/2+x^2/4+x^3/6 = -16.083334
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.

Program:

#include<stdio.h>
#include<math.h>
void main()
{
float y=1.0,x,n;
printf("Enter two numbers:\n");
scanf("%f%f",&x,&n);
for(int i=1;i<=n;i++)
{
y+=pow(x,i);
}
printf(" value is %f",y);
}

Output:

systemno30:~/C_Lab$ gcc 3_i_GeometricExpressionCal.c -lm


systemno30:~/C_Lab$ ./a.out
Enter two numbers:
5
3
value is 156.000000
4. Arrays and Pointers and Functions:
a. Write a C program to find the minimum, maximum and average in an array of integers.

Program:

#include<stdio.h>
void main()
{
int a[20],avg,i,n,s=0,min,max;
printf("Enter number of elements u want to give as input:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Entered array elements are: ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);

s+=a[i]; // sum of array elements


}
avg=s/n; // average of array elements
printf("\navg is: %d",avg);
min=max=a[0]; //intializing min and max as 0
for(i=1;i<n;i++)
{
if(a[i]<min) //true
{ //if an array element value is lessthan value in min
min=a[i]; // array element is assigned to min
}
else if(a[i]>max)//true
{ //if an array element value is greaterthan value in max
max=a[i]; // array element is assigned to min
}
}
printf("\nmin and max are %d and %d\n",min,max);
}

Output:

systemno30:~/C_Lab$ gcc 4_a_MinMaxAvg_OfArray.c


systemno30:~/C_Lab$ ./a.out
Enter number of elements u want to give as input:
5
Enter 5 elements:
5
1
6
4
8
Entered array elements are: 5 1 6 4 8
avg is: 4
min and max are 1 and 8
b. Write a functions to compute mean, variance, Standard Deviation, sorting of n elements in single
dimension array.

Program:

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

int meanfun(int *,int);


void sdfun(int *,int,int);
void sort(int *, int);

void main()
{
int a[20],mean,i,j,n,temp,s=0,sd,var;
printf("Enter number of elements u want to give as input:\n");
scanf("%d",&n);
printf("Enter %d values: \n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
mean=meanfun(a,n);
printf("Mean value = %d\n",mean);
sdfun(a,n,mean);
sort(a,n);
printf("Sorted array values are: ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n");
}

int meanfun(int *a,int n)


{
int i,s=0,mean;
printf("Enteredvalues are: \n");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
s+=a[i];

}
printf("\n");
mean=s/n;
return mean;
}

void sdfun(int *a,int n,int mean)


{
int i,j,x=0,var,sd;
for(i=0;i<n;i++)
{
x+=(a[i]-mean)*(a[i]-mean);

}
var=x/n;
sd=sqrt(var);
printf("Variance=%d\nStandard Deviation=%d\n",var,sd);
}
void sort(int *a,int n)
{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}

Output:

systemno30:~/C_Lab$ gcc 4_b_MVSD.c -lm


systemno30:~/C_Lab$ ./a.out
Enter number of elements u want to give as input:
5
Enter 5 values:
1
6
4
8
6
Entered values are : 1 6 4 8 6
Mean value = 5
Variance=5
Standard Deviation=2
Sorted array values are:1 4 6 6 8
c. Write a C program that uses functions to perform the following:
1) Addition of Two Matrices
2) Multiplication of Two Matrices
3) Transpose of a Martrix

Program:

#include<stdio.h>
void add(int a[10][10], int b[10][10], int d[10][10],int r, int c);
void mul(int a[][10], int b[][10], int m[][10],int r1, int c1, int c2 );
void tran(int a[][10],int r, int c);
void main()
{
int a[10][10],b[10][10],d[10][10],m[10][10],r1,c1,r2,c2,i,j;
printf("Enter number of rows and columns of a Matrix:\n");
scanf("%d%d",&r1,&c1);
printf("Enter number of rows and columns of bMatrix:\n");
scanf("%d%d",&r2,&c2);
printf("Enter %d values for matrix a :\n",r1*c1);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter %d values for matrix b :\n",r2*c2);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
if(r1==r2 && c1==c2)
{
add(a,b,d,r1,c1);
}
if(c1==r2)
{
mul(a,b,m,r1,c1,c2);
}
tran(a,r1,c1);
}
void add(int a[10][10], int b[10][10], int d[10][10],int r, int c)
//void add(int *a[10], int *b[10], int *d[10],int r, int c)
{
int i,j;
printf("Addition of two matrix is\n");
for(i=0;i<r;i++)
{

for(j=0;j<c;j++)
{
d[i][j]=a[i][j]+b[i][j];
printf("%d\t",d[i][j]);
}
printf("\n");
}
}
void mul(int a[][10], int b[][10], int m[][10],int r1, int c1, int c2 )
{
int i,j,k;
printf("Resultant matrix after multiplication\n");
for(i=0;i<r1;i++)
{

for(j=0;j<c2;j++)
{
m[i][j]=0;
for(k=0;k<c1;k++)
{
m[i][j]+=a[i][k]*b[k][j];

}
printf("%d\t",m[i][j]);
}
printf("\n");
}

}
void tran(int a[][10],int r, int c)
{
printf("Transpose of matrix is\n");
for(int i=0;i<c;i++)
{
for(int j=0;j<r;j++)
{
printf("%d\t",a[j][i]);
}
printf("\n");
}

Output:

systemno30:~/C_Lab$ gcc 4_c_AddMulTransOfMatrices.c


systemno30:~/C_Lab$ ./a.out
Enter number of rows and columns of a Matrix:
2 2
Enter number of rows and columns of b Matrix:
2 2
Enter 4 values for matrix a :
1 6
4 3
Enter 4 values for matrix b :
8 3
4 9
Addition of Two Matrices :
9 9
8 12
Resultant matrix after multiplication
32 57
44 39
Transpose of a matrix is
1 4
6 3
i. Addition of Two Matrices

WithOut Functions:

Program:

#include<stdio.h>
void main()
{
int a[10][10],b[10][10],d[10][10],r1,c1,r2,c2,i,j;
printf("Enter number of rows and columns of a Matrix:\n");
scanf("%d%d",&r1,&c1);
printf("Enter number of rows and columns of bMatrix:\n");
scanf("%d%d",&r2,&c2);
printf("Enter %d values for matrix a :\n",r1*c1);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter %d values for matrix b :\n",r2*c2);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
if(r1==r2 && c1==c2)
{
printf("Addition of two matrices :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
d[i][j]=a[i][j]+b[i][j];
printf("%d\t",d[i][j]);
}
printf("\n");
}
}
}
Output:

systemno30:~/C_Lab$ gcc 4_c_1_AdditionOfMatrices.c


systemno30:~/C_Lab$ ./a.out
Enter number of rows and columns of a Matrix:
2 2
Enter number of rows and columns of b Matrix:
2 2
Enter 4 values for matrix a :
2 4
3 6
Enter 4 values for matrix b :
1 9
2 4
Addition of two matrices :
3 13
5 10
With Functions:
Program:
#include<stdio.h>
void add(int a[10][10], int b[10][10], int d[10][10],int r, int c);
void main()
{
int a[10][10],b[10][10],d[10][10],r1,c1,r2,c2,i,j;
printf("Enter number of rows and columns of a Matrix:\n");
scanf("%d%d",&r1,&c1);
printf("Enter number of rows and columns of bMatrix:\n");
scanf("%d%d",&r2,&c2);
printf("Enter %d values for matrix a :\n",r1*c1);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter %d values for matrix b :\n",r2*c2);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
if(r1==r2 && c1==c2)
{
add(a,b,d,r1,c1);
}
}
void add(int a[10][10], int b[10][10], int d[10][10],int r, int c)
//void add(int *a[10], int *b[10], int *d[10],int r, int c)
{
int i,j;
printf("Addition of two matrix is\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
d[i][j]=a[i][j]+b[i][j];
printf("%d\t",d[i][j]);
}printf("\n");
}
}
Output:
systemno30:~/C_Lab$ gcc 4_c_1_AdditionOfMatricesWF.c
systemno30:~/C_Lab$ ./a.out
Enter number of rows and columns of a Matrix:
2 2
Enter number of rows and columns of b Matrix:
2 2
Enter 4 values for matrix a :
4 6
4 3
Enter 4 values for matrix b :
1 6
4 3
Addition of two matrix is
5 12
8 6
ii. Multiplication of Two Matrices

WithOut Functions:

Program:
#include<stdio.h>
void main()
{
int r,c,i,j,k,a[50][50],b[50][50],m[50][50];
printf("Enter number of rows and columns of array a and b\n");
scanf("%d%d",&r,&c);
printf("Enter elements of matrix a\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter elements of matrix b\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("Elements of resultant matrix c:\n");
for(i=0;i<r;i++)
{

for(j=0;j<c;j++)
{
m[i][j]=0;
for(k=0;k<c;k++)
{
m[i][j]+=a[i][k]*b[k][j];

}
printf("%d\t",m[i][j]);
}
printf("\n");
}
}

Output:

systemno30:~/C_Lab$ gcc 4_c_2_MultiplicationOfTwoMatrices.c


systemno30:~/C_Lab$ ./a.out
Enter number of rows and columns of array a and b
2 2
Enter elements of matrix a
6 5
1 3
Enter elements of matrix b
8 3
1 6
Elements of resultant matrix c:
53 48
11 21
With Functions:
Program:
#include<stdio.h>
void mul(int a[][10], int b[][10], int m[][10],int r1, int c1, int c2 );
void main()
{
int a[10][10],b[10][10],m[10][10],r1,c1,r2,c2,i,j;
printf("Enter number of rows and columns of a Matrix:\n");
scanf("%d%d",&r1,&c1);
printf("Enter number of rows and columns of bMatrix:\n");
scanf("%d%d",&r2,&c2);
printf("Enter %d values for matrix a :\n",r1*c1);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter %d values for matrix b :\n",r2*c2);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
if(c1==r2)
mul(a,b,m,r1,c1,c2);
}
void mul(int a[][10], int b[][10], int m[][10],int r1, int c1, int c2 )
{
int i,j,k;
printf("Resultant matrix after multiplication\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
m[i][j]=0;
for(k=0;k<c1;k++)
{
m[i][j]+=a[i][k]*b[k][j];

}
printf("%d\t",m[i][j]);
} printf("\n");
}
}
Output:
systemno30:~/C_Lab$ gcc 4_c_2_MultiplicationOfTwoMatrices.c
systemno30:~/C_Lab$ ./a.out
Enter number of rows and columns of a Matrix:
2 2
Enter number of rows and columns of b Matrix:
2 2
Enter 4 values for matrix a :
1 5
3 2
Enter 4 values for matrix b :
4 3
2 9
Resultant matrix after multiplication
14 48
16 27
iii. Transpose of a matrix with memory dynamically allocated for the new matrix as row and column
counts may not be same.

Program:

#include<stdio.h>
void tran(int a[][10],int r, int c);
void main()
{
int a[10][10],r,c,i,j;
printf("Enter number of rows and columns of a Matrix:\n");
scanf("%d%d",&r,&c);
printf("Enter %d values for matrix a :\n",r*c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
tran(a,r,c);
}

void tran(int a[][10],int r, int c)


{
printf("Transpose of matrix is\n");
for(int i=0;i<c;i++)
{
for(int j=0;j<r;j++)
{
printf("%d\t",a[j][i]);
}
printf("\n");
}
}

Output:

systemno30:~/C_Lab$ gcc 4_c_3_TransposeOfMatrix.c


systemno30:~/C_Lab$ ./a.out
Enter number of rows and columns of a Matrix:
2 2
Enter 4 values for matrix a :
5 6
1 8
Transpose of a matrix is
5 1
6 8
d. Write C programs that use both recursive and non-recursive functions

1) To find the factorial of a given integer.


Non-Recursive:
Program:
#include<stdio.h>
int f(int);
void main()
{
int n,fact;
printf("Enter a number:\n");
scanf("%d",&n);
fact=f(n);
printf("Factorial of %d is %d\n",n,fact);
}
int f(int n)
{
int i,fact=1;
for(i=1;i<=n;i++)
fact*=i;
return fact;
}
Output:
systemno30:~/C_Lab$ gcc 4_d_factorial_NonRecursive.c
systemno30:~/C_Lab$ ./a.out
Enter a number:
5
Factorial of 5 is 120

Recursive:
Program:
#include<stdio.h>
int f(int);
void main()
{
int n,fact;
printf("Enter a number:\n");
scanf("%d",&n);
fact=f(n);
printf("Factorial of %d is %d\n",n,fact);
}
int f(int n)
{
if(n==1)
return 1;
else
return (n*f(n-1));
}

Output:
systemno30:~/C_Lab$ gcc 4_d_factorial_Recursive.c
systemno30:~/C_Lab$ ./a.out
Enter a number:
5
Factorial of 5 is 120
2) To find the GCD (greatest common divisor) of two given integers.

Program:

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

unsigned int GcdRecursive(unsigned m, unsigned n);


unsigned int GcdNonRecursive(unsigned p,unsigned q);

int main(void)
{
int a,b,I,Gcd;

printf("Enter the two numbers whose GCD is to be found: ");


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

printf("GCD of %d and %d Using Recursive Function is %d\n", a,b,GcdRecursive(a,b));


printf("GCD of %d and %d Using Non-Recursive Function is %d\n", a,b,GcdNonRecursive(a,b));

/* Recursive Function*/
unsigned int GcdRecursive(unsigned m, unsigned n)
{
if(n>m)
return GcdRecursive(n,m);
if(n==0)
return m;
else
return GcdRecursive(n,m%n);
}

/* Non-Recursive Function*/
unsigned intGcdNonRecursive(unsigned p,unsigned q)
{
unsigned remainder;
remainder = p-(p/q*q);

if(remainder==0)
return q;
else
GcdRecursive(q,remainder);
}

Output:

systemno30:~/C_Lab$ gcc 4_d_2_GCD.c


systemno30:~/C_Lab$ ./a.out
Enter the two numbers whose GCD is to be found: 6 5
GCD of 6 and 5 Using Recursive Function is 1
GCD of 6 and 5 Using Non-Recursive Function is 1
3) To find x^n
Non-Recursive:
Program:
#include<stdio.h>
int p(int,int);
void main()
{
int power,n,x,fact;
printf("Enter a number x and power n:\n");
scanf("%d%d",&x,&n);
power=p(x,n);
printf("%d to the power of %d is %d\n",x,n,power);
}
int p(int x,int n)
{
inti,pow=1;
for(i=1;i<=n;i++)
pow*=x;
return pow;
}

Output:
systemno30:~/C_Lab$ gcc 4_d_3_x^n_NonRecursive.c
systemno30:~/C_Lab$ ./a.out
Enter a number x and power n:
5 2
5 to the power of 2 is 25

Recursive:
Program:
#include<stdio.h>
int p(int,int);
void main()
{
int power,n,x,fact;
printf("Enter a number x and power n:\n");
scanf("%d%d",&x,&n);
power=p(x,n);
printf("%d to the power of %d is %d\n",x,n,power);
}
int p(int x,int n)
{
if(n==1)
return x;
else
return x*p(x,n-1);
}
Output:
systemno30:~/C_Lab$ gcc 4_d_3_x^n_Recursive.c
systemno30@:~/C_Lab$ ./a.out
Enter a number x and power n:
5 2
5 to the power of 2 is 25

systemno30:~/C_Lab$ ./a.out
Enter a number x and power n:
2 6
2 to the power of 6 is 64
e. Write a program for reading elements using pointer into array and display the values using
array.

Program:

#include<stdio.h>
int main()
{
int a[10],i,n;
int *p = a; //assigining Array index to pointer variable
printf("Enter No of elements you want: ");
scanf("%d",&n);
printf("Enter %d elements: \n",n);
for(i = 0; i < n; i++)
{
scanf("%d", p); // reading elements using pointer variable
p++; // incrementing pointer accessing value
}
printf("Entered elements are : ");
for(i = 0; i < n; i++)
{
printf("%d\t", a[i]); // displaying the elements using array
}
return 0;
}

Output:

systemno30:~/C_Lab$ gcc 4_e_ReadandDisplay_ArrayEle_UsingPointers.c


systemno30:~/C_Lab$ ./a.out
Enter No of elements you want: 5
Enter 5 elements: 1 2 3 4 5
Entered elements are : 1 2 3 4 5
f. Write a program for display values reverse order from array using pointer.

Program:

#include<stdio.h>
int main()
{
int a[10],i,n;
printf("Enter No of elements you want: ");
scanf("%d",&n);
printf("Enter %d elements: \n",n);
for(i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}
printf("Entered elements are : ");
for(i = 0; i < n; i++)
{
printf("%d\t", a[i]); // displaying the elements using array
}
printf("\nDisplay values in reverse order using Pointers : \n");
int *p = &a[n-1]; // assigning the nth value in a array to pointer
for(i = 0; i < n; i++)
{
printf("%d\t", *p); // displaying the elements in reverse order using pointers
p--; //decrementing the pointer value to access array index
}
return 0;
}

Output:

systemno30:~/C_Lab$gcc4_f_ReverseOrder_usingPointers.c
systemno30:~/C_Lab$ ./a.out
Enter No of elements you want: 5
Enter 5 elements:
1
2
3
4
5
Entered elements are : 1 2 3 4 5
Display values in reverse order using Pointers :
5 4 3 2 1
g. Write a program through pointer variable to sum of n elements from array.

Program:

#include<stdio.h>
int main()
{
int a[10],i,n,sum=0;
int *p = a; //assigining Array index to pointer variable
printf("Enter No of elements you want: ");
scanf("%d",&n);
printf("Enter %d elements: \n",n);
for(i = 0; i < n; i++)
{
scanf("%d",&a[i]); // reading values into array a[]
}
for(i = 0; i < n; i++)
{
sum = sum + *p; //adding the values using pointers
p++; // incrementing pointer accessing value
}
printf("Sum of array elements using Pointers : %d \n",sum);
return 0;
}

Output:

systemno30:~/C_Lab$ gcc 4_g_SumOfArray_UsingPointers.c


systemno30:~/C_Lab$ ./a.out
Enter No of elements you want: 5
Enter 5 elements:
1 2 3 4 5
Sum of array elements using Pointers : 15
5. Files:

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

Program:

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Unable to open file a.txt");
}
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
}

Output:

systemno30:~/C_Lab$ gcc 5_a_FileDisplay.c


systemno30:~/C_Lab$ ./a.out
Hello,
Welcome to Computer Programming lab.
b. Write a C program which copies one file to another, replacing all lowercase characters with
their uppercase equivalents.

Program:

#include<stdio.h>
void main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("a.txt","r");
fp2=fopen("b.txt","w");
if(fp1==NULL)
{
printf("Unable to open file a.txt");
}
if(fp2==NULL)
{
printf("Unable to open file a.txt");
}

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

Output:

systemno30:~/C_Lab$ gcc 5_b_CopyFile_From_LowercaseToUppercase.c


systemno30:~/C_Lab$ ./a.out
HELLO,
WELCOME TO COMPUTER PROGRAMMING LAB.
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.

Program:
#include<stdio.h>
void main()
{
FILE *fp;
cha rch,x;
int c=0;

fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Unable to open file a.txt\n");
}
printf("Enter a character:\n");
scanf("%c",&x);

while((ch=fgetc(fp))!=EOF)
{
if(ch==x)
++c;

}
printf("%d times character %c occurs in the respective file\n",c,x);

Output:
systemno30:~/C_Lab$ gcc 5_c_CharacterCountinaFile.c
systemno30:~/C_Lab$ ./a.out
Enter a character:
t
2 times character t occurs in the respective file

systemno30:~/C_Lab$ ./a.out
Enter a character:
e
4 times character e occurs in the respective file
d. 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).

Program:
#include<stdio.h>
void main()
{
FILE *fp1,*fp2,*fp3;
char ch;
fp1=fopen("a.txt","r");
fp2=fopen("b.txt","r");
fp3=fopen("c.txt","a");
if(fp1==NULL)
{
printf("Unable to open file a.txt");
}
if(fp2==NULL)
{
printf("Unable to open file a.txt");
}

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

fputc(ch,fp3);
printf("%c",ch);
}
while((ch=fgetc(fp2))!=EOF)
{

fputc(ch,fp3);
printf("%c",ch);
}

Output:
systemno30:~/C_Lab$ gcc 5_d_MergingTwoFiles_Into_ThirdFile.c
systemno30:~/C_Lab$ ./a.out
Hello,
Welcome to Computer Programming lab.
HELLO,
WELCOME TO COMPUTER PROGRAMMING LAB.
6. Strings
a. Write a C program to convert a Roman numeral ranging from I to L to its decimal equivalent.

Program:
#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); //IV
l =strlen(rom); // length (l) = 2
for(i = 0; i < l; i++)
{
switch (rom[i]) // rom[i] = rom[0] = I
{
case'I': a[i] = 1; //a[0] = 1
break;
case'V': a[i] = 5; //a[1] = 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");
}
}
k = a[l -1]; // a[2-1] = a[1] = 5 (step 20)
for(i = l -1; i > 0; i--) // i= (len)2 - 1 = 1 = True
{
if(a[i] > a[i -1]) // a[1] > a[0] = 5 > 1 = True
{
k = k -a[i -1]; // k = 5 - a[1-1] = 5-a[0] = 5 - 1 = 4
}
if(a[i] <= a[i -1])
{
k = k + a[i -1];
}
}
printf("decimal equivalent is %d\n", k);
}

Output:
systemno30:~/C_Lab$ gcc 6_a_RomanNumeral_to_DecimalEquivalent.c
systemno30:~/C_Lab$ ./a.out
Enter the roman number
VI
decimal equivalent is 6

systemno30:~/C_Lab$ ./a.out
Enter the roman number
MDC
decimal equivalent is 1100
b. Write a C program that converts a number ranging from 1 to 50 to Roman equivalent

Program:

#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("%ld", &number);
if (number <= 0)
{
printf("Invalid number");
return0;
}
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\n", romanval[j]);
return0;
}

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:

systemno30:~/C_Lab$ gcc 6_b_DecimalNumber_to_RomanEquivalent.c


systemno30:~/C_Lab$ ./a.out
Enter the number: 14
Roman number is: XIV

systemno30:~/C_Lab$ ./a.out
Enter the number: 55
Roman number is: LV

systemno30:~/C_Lab$ ./a.out
Enter the number: 1580
Roman number is: MDLXXX
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.

Program:
#include<stdio.h>
#include<string.h>
void main()
{
char s[20],ss[10],b[10];
int i,j,n,p,l,len;
printf("Enter a string :\n");
scanf("%s",s);
printf("Enter substring to be inserted:\n");
scanf("%s",ss);
printf("Enter the position where the substring has to be inserted:\n");
scanf("%d",&p);
len=strlen(s);
l=strlen(ss);
for(i=p,j=0;s[i]!='\0';i++,j++)
{
b[j]=s[i];
}

for(i=p,j=0; ss[j] !='\0'; i++,j++)


{
s[i] = ss[j];
}
for(i=p+l,j=0; b[j] != '\0'; i++,j++)
{
s[i] = b[j];
}
//printf("%s\n",s);
for(i=0;i<len+l;i++)
printf("%c",s[i]);
}

Output:

systemno30:~/C_Lab$ gcc 6_c_1_InsertSubString_Into_MainString.c


systemno30:~/C_Lab$ ./a.out
Enter a string :
seema
Enter substring to be inserted:
sony
Enter the position where the substring has to be inserted:
2
sesonyema
ii) To delete n Characters from a given position in a given string.

Program:

#include<stdio.h>
void main()
{
int n,i,p,num;
char s[10];
printf("Enter a position: ");
scanf("%d",&p);
printf("Enter number of characters(elements) to be deleted: ");
scanf("%d",&num);
printf("Enter string : ");
scanf("%s",s);
printf("String is :%s\n",s);
for(i=p;s[i]!='\0';i++)
{
s[i]=s[i+num];
}

printf("Elements after deleting elements from position p are: ");


printf("%s\n",s);

Output:

systemno30:~/C_Lab$ gcc 6_c_2_DeleteNChar_From_GivenString.c


systemno30:~/C_Lab$ ./a.out
Enter a position: 2
Enter number of characters(elements) to be deleted: 3
Enter string : KimNamjoon
String is : KimNamjoon
Elements after deleting elements from position p are: Kimjoon
d. 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.)

Method – 1:

Program:
#include<stdio.h>
#include<string.h>
void main()
{
char s[10];
int i,j,len,n=0;
printf("Enter a string: ");
scanf("%s",s);
len=strlen(s);
printf("String length is: %d\n",len);
for(i=0,j=(len-1);i<=(len/2);i++,j--)
{
if(s[i]==s[j])
n++;
}
printf("n is %d \n",n);
if(n==((len/2)+1))
printf("%s is a Palindrome\n",s);
else
printf("%s is not a Palindrome\n",s);
}

Output:

systemno30:~/C_Lab$ gcc 6_d_StringPalindrome.c


systemno30:~/C_Lab$ ./a.out
Enter a string: jimin
String length is: 5
n is 2
jimin is not a Palindrome

systemno30:~/C_Lab$ ./a.out
Enter a string: madam
String length is: 5
n is 3
madam is a Palindrome
Method – 2:

Program:
#include<stdio.h>
#include<string.h>
void main()
{
char s[10],rev[10];
int i,j,len,n;
printf("Enter a string: ");
scanf("%s",s);
len=strlen(s);
printf("String length is: %d\n",len);
for(i = len -1, j=0; i>=0; i--, j++)
{
rev[j]==s[i])
}
n = strcmp(rev,s);
if(n==0)
{
printf("%s is a Palindrome\n",s);
}
else
{
printf("%s is not a Palindrome\n",s);
}
}

Output:

systemno30:~/C_Lab$ gcc 6_d_StringPalindrome.c


systemno30:~/C_Lab$ ./a.out
Enter a string: jimin
String length is: 5
jimin is not a Palindrome

systemno30:~/C_Lab$ ./a.out
Enter a string: madam
String length is: 5
madam is a Palindrome
e. Write a C program that displays the position of a character ch in the string S or – 1 if S doesn‘t
contain ch.

Program:

#include<stdio.h>
#include<string.h>
void main()
{
char s[10],ch;
int i,c=0;
printf("Enter a string: ");
scanf("%s",s);
printf("Enter a character: ");
scanf("%c",&ch);
printf("String is: %s\n",s);
printf("Character is: %c\n",ch);
for(i=0; s[i]!='\0'; i++)
{
if(s[i]==ch)
{
printf("Position of %c in %s is %d\n",ch,s,i+1);
c=1;
break;
}
}
if(c==0)
{
printf(" -1 \n%s Doesnt contain char %c \n",s,ch);
}
}

Output:
systemno30:~/C_Lab$ gcc 6_e_CharPosition_InStrings.c
systemno30:~/C_Lab$ ./a.out
Enter a string: kimNamjoon
Enter a character: m
String is: kimNamjoon
Character is: m
Position of m in kimNamjoon is 3

systemno30:~/C_Lab$ ./a.out
Enter a string: KimSeokJin
Enter a character: p
String is: KimSeokJin
Character is: p
-1
KimSeokJin Doesnt contain char p
f. Write a C program to count the lines, words and characters in a given text.

Program:

#include<stdio.h>
#include<string.h>
void main()
{
char s[50];
int i,w=1,ch,l=1;
printf("Enter the String:\n");
gets(s);
ch = strlen(s);
printf("Number of characters in a given string: %d\n",ch);
for(i=0; s[i] != '\0'; i++)
{
if(s[i] == '')
{
w++;
}

}
printf("Number of Words in a given string: %d\n",w);
printf("Number of Lines in a given string: %d\n",l);
}

Output:
systemno30:~/C_Lab$ gcc 6_f_Words_Lines_Char_Count.c
systemno30:~/C_Lab$ ./a.out
Enter the String:
This is Programming for Problem Solving Lab
Number of characters in a given string: 43
Number of Words in a given string: 7
Number of Lines in a given string: 1
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.

Program:

#include<stdio.h>
#include<stdlib.h>
int smallest(int a[20],int n);
int largest(int a[20],int n);
int sum(int a[20],int n);
int average(int a[20],int n);
int main()
{
int a[20],i,n,choice;
printf("Enter number of elements you want: \n ");
scanf("%d",&n);
printf("Enter %d values \n",n);
for(i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}
while(1)
{
printf("\nChoose an option to find \n");
printf("1.Smallest\n2.Largest\n3.Sum\n4.Average\n5.Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);

switch(choice)
{
case1: smallest(a,n);
break;
case2: largest(a,n);
break;
case3: sum(a,n);
break;
case4: average(a,n);
break;
case5: exit(0);
default: printf("Invalid Choice\n");
}
}
}
int smallest(int a[20],int n)
{
int i, sm = a[0];
for(i = 0; i < n; i++)
{
if(a[i] < sm)
{
sm = a[i];
}
}
printf("Smallest Number in an array is: %d \n", sm);
}
int largest(int a[20],int n)
{
int i, l = a[0];
for(i = 0; i < n; i++)
{
if(a[i] > l)
{
l = a[i];
}
}
printf("Largest Number in an array is: %d \n", l);
}
int sum(int a[20],int n)
{
int i,sum=0;
for(i = 0; i < n; i++)
{
sum = sum + a[i];
}
printf("Sum of values in an array is: %d \n", sum);
}
int average(int a[20],int n)
{
int i,sum=0,avg;
for(i = 0; i < n; i++)
{
sum = sum + a[i];
}
avg = sum/n;
printf("Average value in an array is: %d \n", avg);
}

Output:
systemno30:~/C_Lab$ gcc 7_a_MenuDriven.c
systemno30:~/C_Lab$ ./a.out
Enter number of elements you want:
5
Enter 5 values
1 2 3 4 5

Choose an option to find


1.Smallest
2.Largest
3.Sum
4.Average
5.Exit
Enter your choice: 1
Smallest Number in an array is: 1

Choose an option to find


1.Smallest
2.Largest
3.Sum
4.Average
5.Exit
Enter your choice: 2
Largest Number in an array is: 5

Choose an option to find


1.Smallest
2.Largest
3.Sum
4.Average
5.Exit
Enter your choice: 3
Sum of values in an array is: 15

Choose an option to find


1.Smallest
2.Largest
3.Sum
4.Average
5.Exit
Enter your choice: 4
Average value in an array is: 3

Choose an option to find


1.Smallest
2.Largest
3.Sum
4.Average
5.Exit
Enter your choice: 7
Invalid Choice

Choose an option to find


1.Smallest
2.Largest
3.Sum
4.Average
5.Exit
Enter your choice: 5
b. Write a C program to construct a pyramid of numbers as follows:
1 * 1 1 *
12 ** 23 22 **
123 *** 456 333 ***
4444 **
*

Program:
#include<stdio.h>
void main()
{
int i,j,n;
printf("\n1.Number Pattern\n");
for(i=1;i<=3;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",j);
}
printf("\n");
}
printf("\n2.Star Pattern\n");
for(i=1;i<=3;i++)
{
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
printf("\n3.Number Pattern\n");
n=1;
for(i=1;i<=3;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",n);
n++;
}
printf("\n");
}

printf("\n4.Number Pattern\n");
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",i);
}
printf("\n");
}
printf("\n5.Star Pattern\n");
for(i=1;i<=5;i++)
{
if(i <=3)
{
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
else
{
for(j=i;j<=5;j++)
{
printf("* ");
}
printf("\n");
}
}
}

Output:
systemno30:~/C_Lab$ gcc 7_b_PyramidOf_NumbersAndPatterns.c
systemno30:~/C_Lab$ ./a.out
1.Number Pattern
1
12
123

2.Star Pattern
*
**
***

3.Number Pattern
1
23
456

4.Number Pattern
1
22
333
4444

5.Star Pattern
*
**
***
**
*
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.

Program:
#include<stdio.h>
void linearsearch(inta[30],int key, int n);
int main()
{
int i,j,n,key,a[30];
printf("How many number of elements u want: ");
scanf("%d",&n);
printf("Enter %d elements \n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched: ");
scanf("%d",&s);
linearsearch(a,s,n);

}
void linearsearch(inta[30],int key, int n);
{
int i,c=0;
for(i=0;i<n;i++)
{
if(key == a[i])
{
printf("Element found at position %d",i+1);
c=1;
break;
}
}
if(c==0)
printf("Element not found\n");
}

Output:
systemno30:~/C_Lab$ gcc 8_a_LinearSearch.c
systemno30:~/C_Lab$ ./a.out
How many number of elements u want: 5
Enter 5 elements
53496
Enter the element to be searched:4
Element found at position 3

systemno30:~/C_Lab$ ./a.out
How many number of elements u want: 5
Enter 5 elements
53496
Enter the element to be searched:7
Element not found
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.

Program:
#include<stdio.h>
int sorting(int [],int);
int binaryearchs(int [],int key,int n);
void main()
{
intn,i,p,key,a[30];
printf("How many number of elements u want: ");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter searching element:\n");
scanf("%d",&key);
sorting(a,n);
printf("Array elements after Sorting:\n");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n");
p=binarysearch(a,key,n);
if(p>0)
printf("Element found at position %d\n",p);
else
printf("Element not found\n");
}
int sorting(int a[],int n)
{
int i,j,temp;
for(i=0;i<n;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;
}
}
}
}
int binarysearch(int b[],int key,int n)
{
int low,high,mid;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key == b[mid])
{
return mid+1;
}
else if(key < b[mid])
{
high=mid-1;
}
else
{
low=mid+1;
}
}
return -1;
}

Output:
systemno30:~/C_Lab$ gcc 8_b_BinarySearch.c
systemno30:~/C_Lab$ ./a.out
How many number of elements u want: 5
Enter 5 elements:
26843
Enter searching element:
8
Array elements after Sorting:
2 3 4 6 8
Element found at position 5

systemno30:~/C_Lab$ ./a.out
How many number of elements u want: 5
Enter 5 elements:
26843
Enter searching element:
5
Array elements after Sorting:
2 3 4 6 8
Element not found
c. Write a C program that implements the Bubble sort method to sort a given list of integers in
ascending order.

Program:
#include<stdio.h>
void bubblesort(int [],int);
int main()
{
int n,a[30],i;
printf("Enter how many elements u want to sort:");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
bubblesort(a,n);
printf("Sorted list of given elements is\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
}
void bubblesort(inta[],int n)
{
int i,j,temp;
for(i=0;i<n;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;
}
}
}
}

Output:

systemno30:~/C_Lab$ gcc 8_c_BubbleSort.c


systemno30:~/C_Lab$ ./a.out
Enter how many elements u want to sort:5
Enter 5 elements
4 9 2 6 3
Sorted list of given elements is
2 3 4 6 9

systemno30:~/C_Lab$ ./a.out
Enter how many elements u want to sort:5
Enter 5 elements
5 3 8 1 4
Sorted list of given elements is
1 3 4 5 8
d. Write a C program that sorts the given array of integers using selection sort in descending
order

Program:
#include<stdio.h>
voidselectionsort(int [],int);
int main()
{
int n,a[30],i;
printf("Enter how many elements u want to sort:");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
selectionsort(a,n);
printf("Sorted list of given elements is\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
}
voidselectionsort(int a[],int n)
{
int min,i,j,t;
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min])
{
min=j;
}
}
if(min!=i)
{
t=a[min];
a[min]=a[i];
a[i]=t;
}
}
}

Output:
systemno30:~/C_Lab$ gcc 8_d_SelectionSort.c
systemno30:~/C_Lab$ ./a.out
Enter how many elements u want to sort:5
Enter 5 elements:
2 6 3 9 7
Sorted list of given elements is
2 3 6 7 9
e. Write a C program that sorts the given array of integers using insertion sort in ascending order

Program:
#include<stdio.h>
void insertionsort(int [],int);
int main()
{
int n,a[30],i;
printf("Enter how many elements u want to sort:");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
insertionsort(a,n);
printf("Sorted list of given elements is\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
}
void insertionsort(int a[],int n)
{
int x,i,j;
for(i=1;i<n;i++)
{
x=a[i];
for(j=i-1; j>=0 && a[j]>x; j--)
{
a[j+1]=a[j];

}
a[j+1]=x;
}
}

Output:

systemno30:~/C_Lab$ gcc 8_e_InsertionSort.c


systemno30:~/C_Lab$ ./a.out
Enter how many elements u want to sort:5
Enter 5 elements:
5 9 2 4 6
Sorted list of given elements is
2 4 5 6 9

You might also like