cp lab programs

I B.Tech I Sem
Regulation: R15
COMPUTER PROGRAMMING
Lab Manual
Prepared by
Faculty Editors: Mr. M. Ranjit Reddy, Assoc. Professor, Dept. of CSE
Mr. M. Mallikarjuna, Asst. Professor, Dept. of CSE
Mr. C. Sudheer Kumar, Asst. Professor, Dept. of CSE
Mr. P. Veera Prakash, Asst. Professor, Dept. of CSE
Mr. G. Chinna Pullaiah, Asst. Professor, Dept. of CSE
Mr. B. Sreedhar, Asst. Professor, Dept. of CSE
Mrs. P. Manasa, Asst. Professor, Dept. of CSE
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY ANANTAPUR
Computer Programming Lab
B.Tech. I - I Sem.
L
4
PART-A (15A05102) COMPUTER PROGRAMMING LAB
C
2
Objectives:


Learn C Programming language
To make the student solve problems, implement algorithms using C language.
List of Experiments/Tasks:
1. Practice DOS and LINUX Commands necessary for design of C Programs.
2. Study of the Editors, Integrated development environments, and Compilers in chosen platform.
3. Write, Edit, Debug, Compile and Execute Sample C programs to understand the programming
environment.
4. Practice programs: Finding the sum of three numbers, exchange of two numbers, maximum of two
numbers, To read and print variable values of all data types of C language, to find the size of all
data types, to understand the priority and associativity of operators using expressions, to use
different library functions of C language.
5. Write a program to find the roots of a Quadratic equation.
6. Write a program to compute the factorial of a given number.
7. Write a program to check whether the number is prime or not.
8. Write a program to find the series of prime numbers in the given range.
9. Write a program to generate Fibonacci numbers in the given range.
10. Write a program to find the maximum of a set of numbers.
11. Write a program to reverse the digits of a number.
12. Write a program to find the sum of the digits of a number.
13. Write a program to find the sum of positive and negative numbers in a given set of numbers.
14. Write a program to check for number palindrome.
15. Write a program to
evaluate the sum
of the following series up to n terms
ex=1+x+x2/2!+x3/3!+x4/4!+--16. Write a program to generate Pascal Triangle.
17. Write a program to read two matrices and print their sum and product in the matrix form.
18. Write a program to read matrix and perform the following operations.
i. Find the sum of Diagonal Elements of a matrix.
ii. Print Transpose of a matrix.
iii. Print sum of even and odd numbers in a given matrix.
19. Write a program to accept a line of characters and print the number of Vowels, Consonants, blank
spaces, digits and special characters.
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 2
Computer Programming Lab
20. Write a program to insert a substring in to a given string and delete few characters from the string.
Don‟t use library functions related to strings.
21. Write a program to perform the operations addition, subtraction, multiplication of complex
numbers.
22. Write a program to split a “file” in to two files, say file1 and file2. Read lines into the “file” from
standard input. File1 should consist of odd numbered lines and file2 should consist of even
numbered lines.
23. Write a program to merge two files.
24. Write a program to implement numerical methods Lagrange’s interpolation, Trapezoidal rule.
25. Write a program to read a set of strings and sort them in alphabetical order.
26. Write a program to read two strings and perform the following operations without using built in
string Library functions and by using your own implementations of functions.
i. String length determination
ii. Compare Two Strings
ii. Concatenate them, if they are not equal
iv. String reversing
27. Write programs using recursion for finding Factorial of a number, GCD, LCM, and solving
Towers of Hanoi problem.
28. Write a program to exchange two numbers using pointers.
29. Write a program to read student records into a file. Record consists of roll no, name and marks of a
student in six subjects and class. Class field is empty initially. Compute the class of a student. The
calculation of the class is as per JNTUA rules. Write the first class, second class, third class and
failed students lists separately to another file.
30. A file consists of information about employee salary with fields employee id, name, Basic, HRA,
DA, IT, other-deductions, Gross and Net salary. Initially only employee id, name, and basic have
valid values. HRA is taken as 10% of the basic, DA is taken as 80% of basic, IT is 20% of the
basic, other deductions is user specified. Compute the Gross and Net salary of the employee and
update the file.
31. Write a program to perform Base (decimal, octal, hexadecimal, etc) conversion.
32. Write a program to find the square root of a number without using built-in library function.
33. Write a program to convert from string to number.
34. Write a program to implement pseudo random generator.
35. Write a program to generate multiplication tables from 11 to 20.
36. Write a program to express a four digit number in words. For example 1546 should be written as
one thousand five hundred and forty six.
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 3
Computer Programming Lab
37. Write a program to generate a telephone bill. The contents of it and the rate calculation etc should
be as per BSNL rules. Student is expected to gather the required information through the BSNL
website.
38. Write a program to find the execution time of a program.
39. Design a file format to store a person's name, address, and other information. Write a program to
read this file and produce a set of mailing labels.
PROGRAMS
4 (a). Write a c program to find the sum of three numbers
Aim:- To write a program find the sum of three numbers
Program Description:- In this program, we accept three numbers and find their sum.
Source Code:/* THE SUM OF THREE NUMBERS
** NAME OF THE PROGRAM: SUM.C
** DATE:
** AUTHOR:
*/
#include<stdio.h> // stdio.h is a header file includes library functions of input/output
#include<conio.h> // conio.h is a header file includes library functions of console input/output
void main()
// program execution starts from main( ) function which is the default function in C
{
int num1,num2,num3,sum;
// defining variables of type integer
sum = 0;
// initializing variable sum
clrscr();
// to clear the previous content on the screen
printf("SUM OF THREE INTEGERS");
printf ("\n=======================\n");
printf("\nEnter three numbers :");
// prompting user to give input
scanf("%d%d%d",&num1,&num2,&num3);
// % is a format specifier which is followed by the type of the value to be read
// and ‘&’ is the address operator which locates where to store the input value
sum = num1+num2+num3;
// performing sum operation
printf("\nSum of %3d,%3d and %3d is = %4d",num1,num2,num3,sum); // displays output
getch(); // it reads a single character directly from the keyboard, without echoing to the screen
}
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 4
Computer Programming Lab
Input
:
Output :
4(b). Write a c program to exchange of two numbers
Aim:- To write program to exchange of two numbers
Program Description:- In this program we exchange two numbers without using the third
variable. The process can be performed by using the third variable also.
Source Code:/* SWAPPING VALUES OF VARIABLES WITHOUT THIRD VARIABLE
** NAME OF THE PROGRAM: SWAPWOTV.C
** DATE:
** AUTHOR:
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2;
// defining variables of type integer
clrscr();
printf("SWAPPING VALUES OF TWO VARIABLES WITHOUT THIRD VARIABLE");
printf ("\n====================================================\n");
printf("\nEnter num1 value: ");
scanf("%d",&num1);
printf("\nEnter num2 value: ");
scanf("%d",&num2);
printf("\nBefore swapping : num1 = %3d and num2 = %3d",num1,num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
// logic to swap two variables
// without using
// third variable
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 5
Computer Programming Lab
printf("\n\nAfter swapping : num1 = %3d and num2 = %3d",num1,num2);
getch();
}
Input :
Output:
4(c). Write a c program to find maximum of two numbers
Aim:- To write a program to find maximum of two numbers
Program Description:In this program, by using the conditional operator we find the maximum of two numbers.
Source Code:/* MAXIMUM OF TWO INTEGERS BY USING TERNARY OPERATOR
** NAME OF THE PROGRAM: MAX.C
** DATE:
** AUTHOR:
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ,max=0; // defining variables of type integer & initializing max to zero
clrscr();
printf(“ MAXIMUM OF TWO NUMBERS");
printf ("\n=======================\n");
printf("\nEnter num1 value: ");
scanf("%d",&num1);
printf("\nEnter num2 value: ");
scanf("%d",&num2);
max = (num1 > num2) ? num1 : num2;
// ?: is a ternary operator
// var = operand1 ? operand2 : operand3;
// if operand1 is true then operand1 value is returned by ?: operator and stored in val
// if operand1 is false then operand2 value is returned by ?: operator and stored in val
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 6
Computer Programming Lab
printf("\nMaximum of %3d and %3d is = %3d",num1,num2,max);
getch();
}
Input :
Output:
4(d). Write a c program to read and print variable values of all data types of C language and
also find their sizes
Aim:- To write a program to read and print variable values of all data types of C language and also
find their sizes.
Program Description:In this program, we accept variables of all data types that are supported by c language and find
their sizes by using sizeof() operator.
Source Code:/* READ AND PRINT VARIABLE VALUES OF DATA TYPES OF C & FIND THEIR SIZES
** NAME OF THE PROGRAM: MAX.C
** DATE:
** AUTHOR:
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
long int li;
unsigned int ui;
float f;
double d;
char c;
clrscr();
printf("MAXIMUM OF TWO NUMBERS");
printf ("\n=======================\n");
printf("\nEnter a integer value
: ");
scanf("%d",&i);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 7
Computer Programming Lab
printf("\nEnter an unsigned value
scanf("%u",&ui);
printf("\nEnter a long integer value
scanf("%ld",&li);
printf("\nEnter a float value
scanf("%f",&f);
printf("\nEnter a double value
scanf("%lf",&d);
: ");
: ");
: ");
: ");
flushall();
// clears all buffers associated with open input streams,
// Any read operation following flushall reads new data
// into the buffers from the input files.
printf("\nEnter a character
: ");
c=getchar(); //getchar() returns a single character from a standard input device - keyboard
printf("\n Given values are:\n===============\n");
printf("\n Integer
= %4d and its size
= %4d",i,sizeof(i));
printf("\n Unsigned Integer = %4u and its size
= %4d",ui,sizeof(ui));
printf("\n Long Integer
= %ld and its size
= %4d",li,sizeof(li));
printf("\n Float
= %6.2f and its size = %4d",f,sizeof(f));
printf("\n Double
= %lf and its size
= %4d",d,sizeof(d));
printf("\n Character
= %c and its size
= %4d",c,sizeof(c));
getch();
}
Input :
Output:
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 8
Computer Programming Lab
4(e). Write a c program to understand the priority and associativity of operators using
expressions
Aim:- To write a program to understand the priority and associativity of operators using expressions
Program Description:In this program, we demonstrate the use of precedence and associativity.
Source Code:/* PRIORITY AND ASSOCIATIVITY OF OPERATORS USING EXPRESSIONS
** NAME OF THE PROGRAM: OPERATOR.C
** DATE:
** AUTHOR:
*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int res = 0;
clrscr();
printf("PRIORITY AND ASSOCIATIVITY OF OPERATORS");
printf ("\n=======================================\n");
res = 2+3*8;
// Since multipliation is having higher priority than addition,
// multiplication is performed first and then addition
printf("\nResult of the expression \' 2+3*8 \'is = %d\n", res);
res = 4*8/2+8;
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 9
Computer Programming Lab
//Both multiplication and division has equal priority and
// hence by using associativity rule, multiplication is performed
//first and then division as the rule is from left to right
printf("\nResult of the expression \'4*8/2+8\' is = %d", res);
getch( );
}
Output:-
4(f). Write a c program to use different library functions of C language.
Aim:- To write a program to use different library functions of C language
Program Description:In this program, we specify the use of various string and mathematical library functions.
Source Code:/* DIFFERENT LIBRARY FUNCTIONS OF C LANGUAGE
** NAME OF THE PROGRAM: LIBFILE.C.C
** DATE:
** AUTHOR:
*/
#include<stdio.h>
#include<conio.h>
#include<math.h> // math.h includes predefined mathematical functions
#include<string.h> //string.h includes predefined string related functions
void main()
{
int num;
float f;
char name[20]; // name is a variable which stores 19 characters + 1 null character
clrscr();
printf("DIFFERENT LIBRARY FUNCTIONS OF C LANGUAGE ");
printf ("\n=========================================\n");
printf("\n Enter a number:");
scanf("%d",&num);
// sqrt( arg ), ceil( arg ), floor( arg ) are few library functions in math.h header file
printf("\n Square root of number
= %6.4f", f=sqrt(num));
printf("\n Ceil value of above result = %f",ceil(f));
printf("\n Floor value of above result= %f",floor(f));
flushall();
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 10
Computer Programming Lab
printf("\n\n Enter a name :");
scanf("%s",name);
// strlen( arg ), strupr( arg ), strlwr( arg ), strrev( arg ) are few library
//functions in string.h header file
printf("\n Length of the name
= %d",strlen(name));
//strlen(str) returns total number of characters in a given string.
printf("\n Given name in uppercase = %s",strupr(name));
//strupr(str) converts the given string in to upper case
printf("\n Given name in lowercase = %s",strlwr(name));
//strlwr(str) converts the given string in to lower case
printf("\n Reverse of the name
= %s",strrev(name));
//strrev(str) reverse the given string.
getch();
}
Input :
Output:
Input :
Output:
Viva Questions
1.
2.
3.
4.
5.
6.
7.
8.
What is an identifier
What are the rules to be followed while declaring the variables
What is a format specifier (or) control string
How to find the size of a data type
What is precedence of operators
What is associativity of operators
What is the difference between user–defined and built-in functions
What are header files.
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 11
Computer Programming Lab
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 12
Computer Programming Lab
5. Write a program to find the roots of a quadratic equation
Aim:- To write a C program to find the roots of a quadratic equation.
Program Description:In this program, based on descriminant which is equal to b2-4ac, we find the roots of the
quadratic equation. If d>=0, the roots are real otherwise imaginary.
Source Code :
/* FINDING THE ROOTS OF A QUADRATIC EQUATION
** NAME OF THE PROGRAM: OPERATOR.C
** DATE:
** AUTHOR:
*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c,det=0;
float root1=0,root2=0,real=0,img=0;
clrscr( );
printf("FINDING THE ROOTS OF A QUADRATIC EQUATION");
printf ("\n=========================================\n");
printf("\n Enter the values of a,b,c in a quadratic equation : ");
scanf("%d%d%d",&a,&b,&c);
if(a==0) // if condition is true block-1 will be executed or false else block will be executed.
{
// stmts in block-1
printf("\n THE EQUATION IS LINEAR\n==================\n"); // stmts in
root1=(float)-c/b;
printf("\n Linear root of the equation is=%f",root1);
}
else
{
// stmts in else block
det = (b*b)-(4*a*c);
if(det ==0) // if condition is true block-1 will be executed
// or false else if block will be executed.
{
// stmts in block-1
printf("\n THE ROOTS ARE REAL AND EQUAL\n==============\n");
root1= (float)(-b/(2*a)); // type casting to float
printf(" Common root is = %6.2f",root1);
}
else if (det>0) // else if ladder if condition is true block-1 will be executed
// or false else block will be executed.
{
// stmts in block-1
printf("\n THE ROOTS ARE REAL AND DISTINCT\n=============\n");
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 13
Computer Programming Lab
root1=(float)(-b+sqrt(d)/(2*a));
root2=(float)(-b-sqrt(d)/(2*a));
printf("\n root1 = %6.2f",root1);
printf("\n root2 = %6.2f",root2);
}
else
{
printf(" THE ROOTS ARE IMAGINARY\n=====================\n");
real=(-b)/(2*a);
img=(sqrt(-det))/(2*a);
printf("\n root1= %.2f + i.2%f\n root2 = %.2f - i%.2f",real,img,real,img);
}
}
}
}
Input :
Output:
Input :
Output:
Input :
Output:
Input :
Output:
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 14
Computer Programming Lab
Viva Questions
1. What are decision making statements
2. What do you mean by type casting
3. What are different types of type casting
4. What are the different forms of if statement
5. What are the disadvantages of nested if-else
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 15
Computer Programming Lab
6.Write a program to compute the factorial of a given number
Aim:- To write a program to find the factorial of a given number
Program Description:In this program, we multiply a variable i whose value is 1 with another variable f which is
initialized with 1. For each iteration we increment the value of a variable i by 1 and then multiply with
same variable f. The process repeats until the i <= n.
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int num ,fact =1,i=1;
clrscr();
printf("\n Enter a number:");
scanf("%d",&n);
while(i<=n)
{
fact = fact*i; // fact*=i;
i++;
}
printf("Factorial of %3d is = %5d",num,fact);
getch();
}
Input
Enter a number: 6
Output
Factorial of 6 is = 720
Viva Questions
1. What are looping statements
2. What is a definite loop. Specify an example
3. What is an indefinite loop. Specify with an example
4. What is the difference between while and do-while
5. What are minimum number of iterations in while and do-while
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 16
Computer Programming Lab
7. Write a program to check whether the number is prime or not.
Aim :- to write a program to check whether the number is prime or not
Program Description:In this program, we divide the given number by a set of values from 1 to given number. If the
number of factors for the given number is two (i.e., it is divisible by 1 and itself),then the given
number is considered as prime number.
Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,k=0;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
i=1;
while(i<=n)
{
if(n%i==0)
k++;
i++;
}
if(k==2)
printf("\n Given number is a prime number");
else
printf("\n Given number is not a prime number");
}
Input:
Enter a number : 6
Output:
Given number is not a prime number
Input:
Enter a number :11
Output:
Given number is a prime number
Viva Questions
1. What is the difference between entry-controlled loop and exit-controlled loop
2. What is the default scope of if – statement
3. What is the difference between initialization and assigning
4. What is the difference between = and ==
5. If(k) . Is this a valid condition. If yes .Specify the reason
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 17
Computer Programming Lab
8. Write a program to find the series of prime numbers in the given range
Aim:- To write a C program to generate all the prime numbers between 1 and n .
Program Description:In this program , we divide a number with 2 to number less than one , if the remainder is 0
for any one of the above divisions , we conclude that it is not a prime number else it is a prime
number. The process repeats for 2 to given n value.
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,k=0;
clrscr();
printf("Enter n value upto where prime numbers to be found: ");
scanf("%d",&n);
if(n==0)
{
printf(" \n Invalid number entered");
}
printf(“ \n Required prime numbers are :”);
i=2;
while(i<=n)
{
k=0;
j=2;
while(j<n)
{
if(i%j==0)
k=1;
j++;
}
if(k==1)
printf(“%4d” , i);
i++;
}
}
Input :Enter n value upto where prime numbers to be found: 10
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 18
Computer Programming Lab
Output:
Required prime numbers are :
2 3 5 7
Viva Questions
1. What do you mean by nesting of structures.
2. Why we should use & in case of scanf() and why we are not using & in case of printf()
3. Which header file to be included to implement clrscr().
4. Why we have to include an header file.
5. In c which is the terminating(or)delimiter operator.
9. Write a program to generate Fibonacci numbers in the given range.
Aim:- to write a C program to generate the Fibonacci numbers in the given range.
Program Description:In this program, we initialize variable f1 to zero and f2 to 1. We print the variable f which is
the sum of f1 and f2. Then we interchange the values such that f2 is stored in f1 and f value is stored in
f2 . The process repeats until n elements are generated.
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,f1=0,f2=1,f;
clrscr();
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 19
Computer Programming Lab
printf(" \n Enter how many fibonacci numbers you want to print : ");
scanf("%d",&n);
printf("\n Fibonacci series is :\n");
scanf("%d\t%d",f1,f2);
for(i=3;i<=n;i++)
{
f=f1+f2;
printf("\t%d",f);
f1=f2;
f2=f;
}
getch();
}
Input:
Enter how many fibonacci numbers you want to print : 8
Output:Fibonacci series is :
0 1 1 2 3 5 8 13
Viva Questions
1. What are backslash Characters
2. List some backslash Characters
3. When to use for and when to use while
4. Can we write a for statement without initialization , condition
decrementation.
5. What are infinite loops
and incrementation /
10. Write a program to find maximum and minimum of set of numbers
Aim:- To write a C program to find both the largest and smallest in a list of integers
Program Description:In this program , we assume first number is both minimum as well as maximum. For
minimum , we compare minimum value with all other elements in the list. If minimum value is greater
than any other value , we make that number as minimum.
For maximum , we compare maximum value with all other elements in the list. If maximum
value is less than any other value , we make that number as maximum
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 20
Computer Programming Lab
int a[20],i,min,max,n;
clrscr();
printf("\n Enter no. of elements:");
scanf("%d",&n);
printf("\n Enter the elements :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
min=max=a[1];
for(i=2;i<=n;i++)
{
if(max<a[i])
max=a[i];
if(min>a[i])
min=a[i];
}
printf("\n Given elements are:\n");
for(i=1;i<=n;i++)
printf("%5d",a[i]);
printf("\n Maximum Value is=%d",max);
printf("\n Minimum Value is=%d",min);
getch();
}
Input
Enter no. of elements:6
Enter the elements : 12 10 8 2 24 15
Output
Given elements are:
12 10 8 2 24 15
Maximum Value is=24
Minimum Value is=2
Viva Questions
1. What is an array
2. Array is static. Explain why
3. What are the advantages and disadvantages of an array.
4. What is a subscript.
5. What is the default range of a subscript.
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 21
Computer Programming Lab
11. Write a program to reverse the digits of a number.
Aim :- To write a program to reverse the digits of a number
Program Description:In this program, for each iteration we divide the number by 10 and the remainder is added to a
variable sum which is multiplied by 10 for every iteration and we reduce the number to quotient. The
process repeats until n>0
Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,s=0;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 22
Computer Programming Lab
while(n>0)
{
r=n%10;
s=(s*10)+r;
n=n/10;
}
printf("\n The reverse of given number is:%d",s);
}
Input:
Enter a number :325
Output:
The reverse of given number is:523
Viva Questions
1. When we storing sum in a variable ,that variable is assigned with the value zero .why
2. What is a remainder operator.
3. Can we apply % operator for float and double values.
4. When we storing product in a variable , that variable is assigned with the value one. Why
5. What is the use of void.
1.
Write a program to find the sum of digits of a number
Aim:- To write a C program to find the sum of digits of a number
Program Description:In this program , for each iteration we divide the number by 10 and the remainder is added to
a variable sum which is initialized to Zero and we reduce the number to quotient. The process repeats
until n>0
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int n ,r ,s=0;
clrscr();
printf("\n Enter the number : ");
scanf("%d",&n);
while(n>0)
{
r=n%10;
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 23
Computer Programming Lab
s=s+r;
n=n/10;
}
printf("\n Sum of the digits is = %4d",s);
getch();
}
Input:
Enter the number : 256
Output:
Sum of the digits is = 13
Viva Questions
1. What are tokens.
2. What is the range of integer data type.
3. What are different data types available in c
4. What are preprocessor directives
5. What is the use of “include” preprocessor directive
13. Write a program to find the sum of positive and negative numbers in a given set of numbers.
Aim:- To write a program to find the sum of positive and negative numbers in a given set of numbers.
Program Description:We identify each element of the array as positive or negative by comparing with zero. Then
we separately store the sum of positive and negative values in two variables which are initialized to
zero.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,sp=0,sn=0,i;
clrscr();
printf("\n Enter size of the array :");
scanf("%d",&n);
printf("\n Enter the values of array :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
{
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 24
Computer Programming Lab
if(a[i]<0) // negative
sn=sn+a[i];
else // positive
sp=sp+a[i];
}
printf("\n In given numbers,sum of positive values :%d",sp);
printf("\n In given numbers,sum of negative values :%d",sn);
}
Input:Enter size of the array:9
Enter the values of array :
8 -5 4 2 -7 -23 65 -32 24
Output:In given numbers, sum of positive values : 103
In given numbers, sum of negative values :-67
Viva Questions
1. int a[20];
After declaring the above array , if we use only ‘a’(without subscript) , what it refers to.
2. What do you mean by static memory allocation.
3. What is the difference between prefix and postfix increment.
4. What is the difference between unary and binary opearators.
5. What are membership operators
14. Write a program to check for number palindrome.
Aim :- To write a program to check for number palindrome
Program Description:In this program, for each iteration we divide the number by 10 and the remainder is added to a
variable sum which is multiplied by 10 for every iteration and we reduce the number to quotient. The
process repeats until n>0. Finally we check the sum and given number, if both are equal we conclude
it as palindrome.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,s=0,k;
clrscr();
printf("\n Enter a number:");
scanf("%d",&n);
k=n;
while(n>0)
{
r=n%10;
s=(s*10)+r;
n=n/10;
}
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 25
Computer Programming Lab
if(k==s)
printf("\n Given number is Palindrome");
else
printf("\n Given number is not a palindrome");
}
Input:
Enter a number:125
Output:
Given number is not a palindrome
Input:
Enter a number:313
Output:
Given number is Palindrome
Viva Questions
1. What is a palindrome number.
2. What is an expression.
3. What do you mean by lvalue and rvalue
4. What are local and global variables.
5. What is the scope of a variable.
15. Write a program to evaluate the sum of the following series up to ‘n’ terms
ex=1+x+x2/2!+x3/3!+x4/4!+-------Aim:- To write a program to evaluate the sum of the given series
Program Description:In this program, we find the sum of n terms where in each term the numerator is multiplied by x to
get the powers of x and denominator is multiplied by k which is initialized by 1 and for every iteration
it is incremented by 1.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
float sum=1.0,s;
int n,i,x,p,m=1;
clrscr();
printf("\n Enter x value :");
scanf("%d",&x);
printf("\n Enter n value :");
scanf("%d",&n);
p=x;
for(i=2;i<=n;i++)
{
s=(float)p/m;
sum=sum+s;
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 26
Computer Programming Lab
m=m*i;
p=x*p;
}
printf("\n Sum of the given series is :%6.4f",sum);
getch();
}
Input:Enter x value :2
Enter n value :3
Output:Sum of the given series is : 5.0000
Viva Questions
1. What is the lifetime of a variable.
2. What are storage classes.
3. Which header file to include in order to use mathematical functions.
4. What is the difference between getc(),getch() and getche()
5. What is difference between keyword and reserved word.
16. Write a program to generate Pascal’s Triangle
Aim:- To generate Pascal’s Triangle
Program Description:In this program , we find binomial co-efficients and print these values in pyramid format
using nesting of for loops.
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,num=1,den=1,m,r,s,t,p,k;
clrscr();
printf("Enter a value:");
scanf("%d",&n);
s=21;
m=1;
r=0;
for(i=1;i<=n+1;i++)
{
if(i!=2)
{
for(k=1;k<=s;k++)
printf(" ");
for(j=1;j<=i;j++)
{
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 27
Computer Programming Lab
for(p=m;p>(m-r);p--)
num=num*p;
for(p=1;p<=r;p++)
den=den*p;
t=num/den;
printf("%5d",t);
r++;
num=1;
den=1;
}
m++;
r=0;
s--;
printf("\n\n"); }
}
}
getch();
}
Input
Enter a value: 5
Viva Questions
1. What are binomial co-efficients
2. What is difference between putc()and
putchar()
3. What is a translator
4. Difference between compiler and
interpreter
5. Why C is called amiddle level language
Output
1
2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 28
Computer Programming Lab
17.Write a program to read two matrices and print their sum and product in the matrix form.
Aim:- To write a program to read matrices and print their sum and product in the matrix form.
Program Description:In this program, To find the Sum of two matrices, we add the corresponding elements.
To find the product, we multiply first row elements of first matrix with first column elements
of second matrix. We obtain the first element in the product matrix by adding all the above products.
Then we multiply first row elements of first matrix with second column elements of second matrix.
We obtain the second element in the product matrix by adding all the above products. Repeat the
above process for remaining elements in matrix.
Source Code :#include<stdio.h>
#include<conio.h>
void input(int a[8][8],int r,int c);
void output(int a[8][8],int r,int c);
void add(int a[8][8],int b[8][8],int s[8][8],int r,int c);
void multiply(int a[8][8],int b[8][8],int s[8][8],int r,int c,int p);
void main()
{
int a[8][8],b[8][8],s[8][8],r1,c1,r2,c2,ch;
clrscr();
printf("\n Enter rows and columns of first matrix:");
scanf("%d%d",&r1,&c1);
printf("\n Enter rows and columns of second matrix:");
scanf("%d%d",&r2,&c2);
printf("\n Enter the elements of first matrix:");
input(a,r1,c1);
printf("\n Enter the elements of second matrix:");
input(b,r2,c2);
printf("\n Elements of first matrix are:");
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 29
Computer Programming Lab
output(a,r1,c1);
printf("\n Elements of second matrix are:");
output(b,r2,c2);
if((r1==r2)&&(c1==c2))
{
add(a,b,s,r1,c1);
printf("\n Sum of the two matrices is:");
output(s,r1,c1);
}
else
{
printf("\n Matrix addition is not possible");
}
if(c1==r2)
{
multiply(a,b,s,r1,c2,c1);
printf("\n Product of the two matrices is:");
output(s,r1,c2);
}
else
{
printf("\n Matrix multiplication is not possible");
}
getch();
}
void input(int a[8][8],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
}
void output(int a[8][8],int r,int c)
{
int i,j;
printf("\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%4d",a[i][j]);
}
printf("\n ");
}
}
void add(int a[8][8],int b[8][8],int s[8][8],int r,int c)
{
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 30
Computer Programming Lab
int i,j;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
s[i][j]=a[i][j]+b[i][j];
}
void multiply(int a[8][8],int b[8][8],int s[8][8],int r,int c,int p)
{
int i,j,k;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
s[i][j]=0;
for(k=0;k<p;k++)
s[i][j]=s[i][j]+(a[i][k]*b[k][j]);
}
}
Input
Enter rows and columns of first matrix:3 3
Enter rows and columns of second matrix:3 3
Enter the elements of first matrix: 5 2 6 9 8 7 1 2 1
Enter the elements of second matrix:6 4 7 8 4 1 3 2 5
Output
Elements of first matrix are:
5 2 6
9 8 7
1 2 1
Elements of second matrix are:
6 4 7
8 4 1
3 2 5
Sum of the two matrices is:
11 6 13
17 12 8
4 4 6
Product of the two matrices is:
64 40 67
139 82 106
25 14 14
Viva Questions
1. What is a function
2. C follows modular programming .Explain
3. What are the advantages of functions
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 31
Computer Programming Lab
4. How to declare and initialize a multi-dimensional array
5. What is the difference row major and column major
18. Write a program to read matrix and perform the following operations.
i. Find the sum of Diagonal Elements of a matrix.
ii. Print Transpose of a matrix.
iii. Print sum of even and odd numbers in a given matrix.
Aim:- To write a program to read matrix and perform operations on it.
Program Description:By interchanging rows and columns we can obtain transpose of a matrix. By adding the sum of
elements where row subscript and column subscript values are equal. We can find the sum of principle
diagonal elements .Similarly we can identify secondary diagonal elements and add to the above sum.
By diving the number by 2 we can identify whether the element is even or odd .By identifying
them we can find the sum of even and odd element values of the matrix.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int a[8][8],s=0,se=0,so=0,n,i,j;
clrscr();
printf("\n Enter the order of the matrix :");
scanf("%d",&n);
printf("\n Enter the elemens of the matrix :");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(a[i][j]%2==0) // even number
se=se+a[i][j];
else
so=so+a[i][j];
if( (i==j) || (i+j)==(n+1) ) //diagonal elements
s=s+a[i][j];
}
printf("\n Sum of all diagonal elements is :%d",s);
printf("\n Sum of even numbers in matrix is :%d",se);
printf("\n Sum of odd numbers in matrix is :%d",so);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 32
Computer Programming Lab
printf("\n Transpose of the given matrix is:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%3d",a[j][i]);
printf("\n");
}
getch();
}
Input:Enter the order of the matrix :3
Enter the elemens of the matrix :
5 2 6
8 1 9
4 3 2
Output:Sum of all diagonal elements is :18
Sum of even numbers in matrix is :22
Sum of odd numbers in matrix is :18
Transpose of the given matrix is:
5 8 4
2 1 3
6 9 2
Viva Questions
1. In a two dimensional array , what the first and second subscripts represents.
2. What is the difference between structure and an array
3. Can we produce the array size at run time. Justify
4. What are different dynamic memory allocation functions.
5. What do you mean by dynamic initialization of a variable.
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 33
Computer Programming Lab
19. Write a program to accept a line of characters and print the count of the number of Vowels,
Consonants, blank spaces, digits and special characters.
Aim:- To write a program to count of the number of Vowels, Consonants, blank spaces, digits and
special characters in a given line of text
Program Description:In this program we consider aline of text and we identify whether each character is a vowel
or consonant or digit or any other special character by comparing the character with the required
character.
Source Code:#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char line[80];
int i,vow=0,con=0,digit=0,spch=0,spaces=0;
clrscr();
printf("\n Enter a line of text :");
scanf("%[^\n]",line);
i=0;
while(line[i]!='\0')
{
line[i]=tolower(line[i]);
if(isalpha(line[i])!=0)
{
if(line[i]=='a'||line[i]=='e'||line[i]=='i'||line[i]=='o'||line[i]=='u')
vow++;
else
con++;
}
else if(isdigit(line[i])!=0)
digit++;
else if(line[i]==' ' || line[i]=='\t')
spaces++;
else
spch++;
i++;
}
printf("\n In the given line of text :\n");
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 34
Computer Programming Lab
printf("\n No. of vowels is=%d",vow);
printf("\n No. of consonants is=%d",con);
printf("\n No. of digits is=%d",digit);
printf("\n No. of spaces is=%d",spaces);
printf("\n No. of special characters is=%d",spch);
getch();
}
Input:Enter a line of text :
This is 21st century #!
Output:In the given line of text :
No. of vowels is=4
No. of consonants is=11
No. of digits is=2
No. of spaces is=4
No. of special characters is=2
Viva Questions
1. What is use of the header file ctype.h
2. What are ASCII characters
3. Why we will not mention & before a string variable name while using scanf()
4. Specify difference between %[^\n] and%s
5. What is a null Character
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 35
Computer Programming Lab
20. Write a program to insert a sub string in to a given string from a given position. Don’t use
library functions related to strings.
Aim:- To insert a sub string in to a given string from a given position.
Program Description:In this program, first we find the sub string length (n) and we shift the entire characters from
insertion position to the end by n positions forward and then we insert the sub string into main string.
Source Code :#include<stdio.h>
#include<conio.h>
#include<string.h>
void insert(char mstr[],char sstr[],int);
void main()
{
char mstr[80],sstr[20];
int p;
printf("\n Enter the main string :");
gets(mstr);
printf("\n Enter sub string to be inserted :");
gets(sstr);
printf("\n Enter the position where substring to be inserted :");
scanf("%d",&p);
insert(mstr,sstr,p);
printf("\n After inserting , the resultant string is :");
puts(mstr);
}
void insert(char mstr[80],char sstr[30],int p)
{
int l1,l2,i,j;
l1=strlen(mstr);
l2=strlen(sstr);
for(i=l1;i>=p;i--)
mstr[i+l2]=mstr[i];
for(i=p,j=0;j<l2;j++,i++)
mstr[i]=sstr[j];
}
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 36
Computer Programming Lab
Input:Enter the main string : This is a text
Enter sub string to be inserted : sample
Enter the position where sub string to be inserted : 9
Ouput:
After inserting , the resultant string is : This is a sample text
Viva Questions
1. Which header file to be included in order to using string functions.
2. What strcmp() returns.
3. How does strcat() works.
4. Specify any 8 string handling functions
5. What is a string constant
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 37
Computer Programming Lab
21. Write a program to perform the operations addition, subtraction, multiplication of complex
numbers.
Aim
To perform various operations on complex numbers
Program Description
In this program , we declare a complex number by using a structure which consists of two fields
namely real, img which represents real and imaginary parts of complex numbers respectively. Here
we accept two complex numbers and perform operations like addition , multiplication etc by using the
common procedure that we use for complex numbers.
Source Code
#include<conio.h>
#include<stdio.h>
struct complex
{
float real;
float img;
};
void output(struct complex);
struct complex add(struct complex,struct complex);
struct complex sub(struct complex,struct complex);
struct complex mul(struct complex,struct complex);
void main()
{
struct complex c1,c2,result;
int choice;
clrscr();
printf("\n Enter first complex number");
printf("\n\n Enter real part :");
scanf("%f",&c1.real);
printf("\n\n Enter imaginary part :");
scanf("%f",&c1.img);
printf("\n Enter second complex number");
printf("\n\n Enter real part :");
scanf("%f",&c2.real);
printf("\n\n Enter imaginary part :");
scanf("%f",&c2.img);
result=add(c1,c2);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 38
Computer Programming Lab
printf("\n Sum of two complex numbers=");
output(result);
result=sub(c1,c2);
printf("\n Difference of two complex numbers=");
output(result);
result=mul(c1,c2);
printf("\n Product of two complex numbers=");
output(result);
getch();
}
void output(struct complex k)
{
if (k.img>=0)
printf("%2.1f+%2.1fi",k.real,k.img );
else
printf("%2.1f-%2.1fi",k.real,(-k.img) );
}
struct complex add(struct complex x,struct complex y)
{
struct complex t;
t.real=x.real+y.real;
t.img=x.img+y.img;
return(t);
}
struct complex sub(struct complex x,struct complex y)
{
struct complex t;
t.real=x.real-y.real;
t.img=x.img-y.img;
return(t);
}
struct complex mul(struct complex x,struct complex y)
{
struct complex t;
t.real=(x.real*y.real)-(x.img*y.img);
t.img=(x.real*y.img)+(x.img*y.real);
return(t);
}
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 39
Computer Programming Lab
Input
Enter first complex number
Enter real part :5.2
Enter imaginary part :3.6
Enter second complex number
Enter real part :4.8
Enter imaginary part :6.2
Output
Sum of two complex numbers=10.0+9.8i
Difference of two complex numbers=0.4-2.6i
Product of two complex numbers=2.6+49.5i
Viva Questions
1. What is a structure
2. What are the different ways to pass a structure as a argument to a function
3. How to access the fields of a structure
4. Can we create a pointer to a structure
5. Is structure is a user-defined or derived data type
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 40
Computer Programming Lab
22. Write a program to split a ‘file’ in to two files, say file1 and file2. Read lines into the ‘file’
from standard input. File1 should consist of odd numbered lines and file2 should consist of even
numbered lines.
Aim:- To split the files into two files
Program Description:In this program we identify whether a line is odd numbered or even numbered by using a
variable k which is initialized to 1. This variable is incremented by 1 when we encounter ‘\n’
character. The odd numbered lines of text is copied to one file and even numbered lines of text are
copied to another file.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2,*fp3;
char ch;
int k=1;
clrscr();
fp1=fopen("c:/myfile.txt","w");
printf("\n Enter the contents of the file (press # at end):\n");
ch=getchar();
while(ch!='#')
{
putc(ch,fp1);
ch=getchar();
}
fclose(fp1);
fp1=fopen("c:/myfile.txt","r");
fp2=fopen("c:/file1.txt","w");
fp3=fopen("c:/file2.txt","w");
ch=' ';
while(!feof(fp1))
{
putc(ch,fp2);
ch=getc(fp1);
while(ch!='\n'&& !feof(fp1)) //odd numbered lines
{
putc(ch,fp2);
ch=getc(fp1);
}
if(ch=='\n')
{
k++;
if(k%2==0)// even numbered lines
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 41
Computer Programming Lab
{
putc(ch,fp3);
ch=getc(fp1);
while(ch!='\n' && !feof(fp1))
{
putc(ch,fp3);
ch=getc(fp1);
}
k++;
}
}
}
fcloseall();
}
Input:Enter the contents of the file (press # at end) :
This is sudheer
I am studying B.Tech first year
I joined in CSE department
My home town is Anantapur
My father is a business man
My Mother is a house wife
My brother is chartered Accountant #
Output:C:\>type myfile.txt
This is sudheer
I am studying B.Tech first year
I joined in CSE department
My home town is Anantapur
My father is a business man
My Mother is a house wife
My brother is chartered Accountant
C:\>type file1.txt
This is sudheer
I joined in CSE department
My father is a business man
My brother is a chartered Accountant
C:\>type file2.txt
I am studying B.Tech first year
My home town is Anantapur
My Mother is a house wife
Viva Questions
1. What is a file
2. What are drawbacks of a standalone applications
3. Why to use a file
4. What are different file opening modes
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 42
Computer Programming Lab
5. What is a binary file
23. Write a program to merge two files.
Aim
To write a c program to merge two files.
Program Description
Here we open the first file in read mode and third fiel in write mode. Now we copy the entire
contents of first file into third file. Now we close the first file and open the second file and copy the
entire contents of second file to third file.
Source Code
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2,*fp3;
char ch;
clrscr();
fp1=fopen("file1.txt","r");
if(fp1==NULL)
{
printf("Given file does n't exists");
exit(0);
}
fp3=fopen("file3.txt","w");
while(!feof(fp1))
{
ch=getc(fp1);
putc(ch,fp3);
}
fclose(fp1);
fp2=fopen("file2.txt","r");
if(fp2==NULL)
{
printf("Given file does n't exists");
exit(0);
}
while(!feof(fp2))
{
ch=getc(fp2);
putc(ch,fp3);
}
fcloseall();
}
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 43
Computer Programming Lab
Output
C:\TC3\BIN>type file1.txt
This is a demo file
My college name is Srinivasa Ramanujan Institute of Technology, Anantapur.
C:\TC3\BIN>type file2.txt
My Name is Sudheer Kumar
I am studying I btech in Srinivasa Ramanujan Institute of Technology
My branch is CSE
C:\TC3\BIN>type file3.txt
This is a demo file
My college name is Srinivasa Ramanujan Institute of Technology, Anantapur.
My Name is Sudheer Kumar
I am studying I btech in Srinivasa Ramanujan Institute of Technology
My branch is CSE
Viva Questions
1. What are the functions used for random accessing of a file.
2. What is the use of feof()
3. Write the syntax of fscanf() and fprintf()
4. What is the use of fread()
5. What is the difference between “w” and “a” modes.
24a. Write a program to implement numerical method - Lagrange’s interpolation
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 44
Computer Programming Lab
Aim:- to implement numerical method - Lagrange’s interpolation
Program Description:Lagrange’s Interpolation Formula:
1. Newton-Gregory forward interpolation is applicable only to equally spaced values of the
argument; it is not applicable for unequal spaced values of argument.
2. Lagrange’s interpolation formula for unequal intervals
f ( x) 
( x  x1 )( x  x2 )......( x  xn )
f ( x0 )
( x0  x1 )( x0  x2 )......( x0  xn )

( x  x0 )( x  x2 )......( x  xn )
f ( x1 )  .........
( x1  x1 )( x1  x2 )......( x1  xn )

( x  x0 )( x  x1 )......( x  xn 1 )
f ( xn )
( xn  x1 )( xn  x2 )......( xn  xn 1 )
Source Code:#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
#define n 5
void main()
{
float y[20],x[20],xinp,u,sum=0,prodd,prodn;
int i,j;
clrscr();
printf("Enter the values of Interpolation Points \n");
for(i=0;i<n;i++)
scanf("%f",&x[i]);
printf("Enter the corresponding values of Y \n");
for(i=0;i<n;i++)
scanf("%f",&y[i]);
printf(" Enter the value of x at which Y(x) is needed \n");
scanf("%f",&xinp);
for(i=0;i<n;i++)
{
prodn=1.0;
prodd=1.0;
for(j=0;j<n;j++)
{
if(i==j)
continue;
prodn=prodn*(xinp-x[j]);
prodd=prodd*(x[i]-x[j]);
}
sum=sum +(prodn/prodd)*y[i];
}
printf(" The value of y is %f\n",sum);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 45
Computer Programming Lab
getch();
}
Input:Enter the values of Interpolation Points
2
5
8
10
12
Enter the corresponding values of Y
4.4
6.2
6.7
7.5
8.7
Enter the value of x at which Y(x) is needed : 7
Output
The value of y is 6.486012
24b. Write a program to implement numerical method- Trapezoidal rule.
Aim:- To implement numerical method- Trapezoidal rule
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 46
Computer Programming Lab
Program Description:Numerical Integration:
Numerical Integration is a process of evaluating a definite integral from a set of tabulated values
of the integrand f(x).
The three methods of numerical integration used are:
1. Trapezoidal Rule.
2. Simpson’s 1/3 rule.
3. Simpson’s 3/8 rule.
Trapezoidal Rule:
According to trapezoidal rule,
x0  nh

x0
h
f ( x)dx  [(sum of first and last ordinates )  2(sum of the remaining ordinates)] Source
2
Source Code:#include<stdio.h>
#include<conio.h>
#include<math.h>
float fun(float x)
{
return(1/(1+(x*x)));
}
void main()
{
float x0,x1,sum,result,h;
int i,n,ch;
clrscr();
printf("\n Enter the lower and upper limits :");
scanf("%f%f",&x0,&x1);
printf("\nEnter the number of intervals :");
scanf("%d",&n);
h=(x1-x0)/n;
sum=fun(x0)+fun(x1);
for(i=1;i<n;i++)
sum=sum+2*fun(x0+i*h);
result=sum*h/2;
printf("\n The Result is = %6.2f",result);
getch();
}
Input:
Enter the lower and upper limits :10 80
Enter the number of intervals :8
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 47
Computer Programming Lab
Output
The Result is = 0.10
Viva Questions
1. Can we call one function inside another function.
2. By default how values does a function returns
3. What is the use of return()
4. What is the use of continue
5. While printing a float value , we used %6.2f .what you mean by that.
25. Write a program to read a set of strings and sort them in alphabetical order.
Aim:- To write a program to read a set of strings and sort them in alphabetical order
Program Description:Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 48
Computer Programming Lab
The sorting of strings is performed in similar to number sorting where we compare the first
number with all the remaining elements to identify the minimum element and placed it in first
position. Similarly we identify all the elements and place them in the corresponding positions.
Source Code:#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[15][20],temp[20];
int i,j,n;
clrscr();
printf("\n Enter number of strings :");
scanf("%d",&n);
printf("\n Enter the strings:\n");
for(i=1;i<=n;i++)
scanf("%s",str[i]);
for(i=1;i<n;i++)
for(j=i+1;j<=n;j++)
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
printf("\n After sorting strings are :\n");
for(i=1;i<=n;i++)
printf("%s\n",str[i]);
getch();
}
Input:Enter number of strings :6
Enter the strings
ramu
krishna
lakshman
balaji
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 49
Computer Programming Lab
deepak
abhiram
Output:After sorting strings are :
abhiram
balaji
deepak
krishna
lakshman
ramu
Viva Questions
1. How to store multiple strings
2. Can we copy one string to another without using strcpy()
3. What is the difference between strdup() and strcpy()
4. Write the structure of a string
5. What is the difference between ‘a’ and “a”
26. Write a program to read two strings and perform the following operations
with out using built-in string Library functions and by using your own implementations of
functions.
i. String length determination
ii .Compare Two Strings
iii. Concatenate them, if they are not equal
iv. String reversing
Aim:- To write a program to read two strings and perform operations on them without using library
functions.
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 50
Computer Programming Lab
Program Description:We find the string length by comparing each character of the string and increment a variable
whose initial value is 0 until we encounter a null character. Then this variable specifies the length of
the string. Once we find the length we can perform reversing by printing the characters from last to
first. Similarly by comparing the corresponding position characters in the given two strings , we can
identify whether the given strings are equal or not.
Source Code:#include<stdio.h>
#include<conio.h>
int stringlength(char *s);
int stringcompare(char *s1,char *s2,int ,int)
void stringconcatenate(char *s1,char *s2,int,int);
void stringreverse(char *s,int);
void main()
{
char str1[20],str2[30];
int n,i,k,l1,l2;
clrscr();
printf("\n Enter the first string:");
scanf("%s",str1);
printf("\n Enter the second string: ");
scanf("%s",str2);
l1=stringlength(str1);
printf("\n Length of first string is=%d",l1);
l2=stringlength(str2);
printf("\n Length of Second string is=%d",l2);
k=stringcompare(str1,str2,l1,l2);
if(k==1)
printf("\n Two strings are equal\n");
else
{
printf("\n Two strings are not equal");
printf("\n After concatenating two strings, resultant string is:");
stringconcatenate(str1,str2,l1,l2);
}
printf("\n Reverse of first string is=");
stringreverse(str1,l1);
printf("\n Reverse of second string is=");
stringreverse(str2,l2);
getch();
}
int stringlength(char *str)
{
int k;
for(k=0;str[k]!='\0';k++);
return(k);
}
int stringcompare(char *s1,char *s2,int l1,int l2)
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 51
Computer Programming Lab
{
int i,t=0;
if(l1==l2)
{
for(i=0;i<l1;i++)
if(s1[i]!=s2[i])
t=1;
if(t==0)
return(1);
else
return(0);
}
else
return(0);
}
void stringconcatenate(char *s1,char *s2,int l1,int l2)
{
int i;
char str[60];
for(i=0;i<l1;i++)
str[i]=s1[i];
str[l1]=' ';
l1++;
for(i=0;i<l2;i++)
str[l1+i]=s2[i];
printf("%s",str);
}
void stringreverse(char *s,int l)
{
int i;
for(i=l-1;i>=0;i--)
printf("%c",s[i]);
}
Input:Enter the first string : krishna
Enter the second string : kishore
Output:Length of first string is=7
Length of Second string is=7
Two strings are not equal
After concatenating two strings, resultant string is :krishna kishore
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 52
Computer Programming Lab
Reverse of first string is=anhsirk
Reverse of second string is=erohsik
Input:Enter the first string:balu
Enter the second string: balu
Output:Length of first string is=4
Length of Second string is=4
Reverse of first string is=ulab
Reverse of second string is=ulab
Viva Questions
1. How to access string by using pointers.
2. What is the use of strrev()
3. What is the difference between upper case and lower case characters
4. C is a case sensitive language. Justify
5. What is the use of strlen()
27(a). Write program using recursion for finding the factorial of a number.
Aim:- To find the factorial of a number using recursion
Program Description:In this program we compare whether n≤0.If the condition is true we return 0 otherwise we
recursively call the same function by reducing the value of n by 1.
Source Code:#include<stdio.h>
#include<conio.h>
int rfact(int n)
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 53
Computer Programming Lab
{
if(n==0 || n==1)
return 1;
else
return(n*rfact(n-1));
}
void main()
{
int n,f;
clrscr();
printf("\n Enter a number:");
scanf("%d",&n);
f= rfact(n);
printf("Factorial of %3d is=%d ",n,f);
getch();
}
Input:Enter a number:5
Output:Factorial of 5 is=120
27(b). Write program using recursion for finding the GCD of two numbers.
Aim:- To find the GCD of two numbers using recursion
Program Description:Let x, y be two values. If x mod y=0 we return y else we consider y value as x and x mod y
as y. By using these new values of x and y we recursively call the same function.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 54
Computer Programming Lab
int a,b,r;
clrscr();
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
if(a>b)
r=rgcd(a,b);
else
r=rgcd(b,a);
printf("GCD of %3d and %3d is=%3d",a,b,r);
getch();
}
int rgcd(int x,int y)
{
if (x%y==0)
return y;
else
return rgcd(y,(x%y));
}
Input:Enter two numbers:8 2
Output:GCD of 8 and 2 is= 2
27(c). Write program using recursion for finding the LCM of two numbers.
Aim:- To find the LCM of two numbers using recursion.
Program Description:We initialize a variable by 1. We divide this variable with the given two numbers. If both of
the remainders are zero we return the variable otherwise we increment the variable by one.
Source Code:#include<stdio.h>
#include<conio.h>
int lcm(int, int);
void main()
{
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 55
Computer Programming Lab
int a, b, result;
clrscr();
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
result = lcm(a, b);
printf("The LCM of %d and %d is %d\n", a, b, result);
getch();
}
int lcm(int a, int b)
{
static int common = 1;
if (common % a == 0 && common % b == 0)
return common;
common++;
lcm(a, b);
return common;
}
Input:Enter two numbers: 8 6
Output:The LCM of 8 and 6 is 24
27(d). Write program using recursion to solve the problem of Towers of Hanoi.
Aim:- To solve the problem of Towers of Hanoi by using recursion
Program Description:Towers of Hanoi:
Problem:
The Towers of Hanoi is a well known children’s game, played with three poles and a number of
different sized disks. Each disk has a hole in the center, allowing it to be placed around any of the
poles. Initially, the disks are placed on the leftmost pole in the order of decreasing as shown below:
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 56
Computer Programming Lab
Left
center
Right
Object of the Game:
The Object of the game is to transfer the disks from the leftmost pole to the right most pole .
Rules of the Game:
 Only one disk is to be transferred at a time.
 Each disk must always be placed around one of the poles but not outside.
 A larger disk should not be placed on top of a smaller disk.
Solution of the Game:
Assume that there are n disks, numbered from smallest to largest. If disks are initially stacked on the
left pole, the problem of moving all n disks to the right pole can be stated in the following recursive
manner.
1. Move the top n-1 disks from the left pole to the center pole.
2. Move the nth disk from left pole to right pole
3. Move the n-1 disks on the center pole to the right pole.
Source Code:#include<stdio.h>
#include<conio.h>
void transfer(int,char,char,char);
void main()
{
int n,ch;
clrscr();
printf("\n Enter no. of disks:");
scanf("%d",&n);
transfer(n,'l','r','t');
getch();
}
void transfer(int n, char from, char to,char temp)
{
if(n>0)
{
transfer(n-1,from,temp,to);
printf("\n Move disk %3d from %3c to %3c",n-1,from,to);
transfer(n-1,temp,to,from);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 57
Computer Programming Lab
}
}
Input:Enter no. of disks:3
Output:Move disk
Move disk
Move disk
Move disk
Move disk
Move disk
Move disk
0 from
1 from
0 from
2 from
0 from
1 from
0 from
l to
l to
r to
l to
t to
t to
l to
r
t
t
r
l
r
r
Viva Questions
1. What is recursion
2. What are the advantage and disadvantages of using recursion
3. What type of problems can be solved by using recursion
4. What is the use of static storage class.
5. What is the scope and lifetime of a static variable
28. Write a program to exchange two numbers using pointers.
Aim:- To exchange two numbers using pointers
Program Description:We use call by reference to swap two numbers using pointers
Source Code:#include<stdio.h>
#include<conio.h>
void exchange(int *,int *);
void main()
{
int a,b;
clrscr();
printf("\n Enter two numbers :");
scanf("%d%d",&a,&b);
printf("\n Before exchanging ,a=%d and b=%d",a,b);
exchange(&a,&b);
printf("\n After exchanging ,a=%d and b=%d",a,b);
getch();
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 58
Computer Programming Lab
}
void exchange(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Input:Enter two numbers :5 9
Output:Before exchanging ,a=5 and b=9
After exchanging ,a=9 and b=5
Viva Questions
1. What are different parameter passing techniques
2. What is the difference between call by value and call by reference
3. What are formal and actual parameters
4. What are the different types of functions
5. What is the default return type of a function
29. Write a program to read student records into a file. Record consists of rollno, name and
marks of a student in six subjects and class. Class field is empty initially. Compute the class of a
student. The calculation of the class is as per JNTUA rules. Write the first class, second class,
third class and failed students lists separately to another file.
Aim:- To read student records into a file and Write the first class, second class, third class and failed
students lists separately to another file as per JNTU rules.
Program Description:In this program we input the rollno , name and six subject marks of each student and
calculate the grade of the student based on JNTU A rules.
Source Code:#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
char rollno[10];
char name[15];
int sub[6];
char grade[15];
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 59
Computer Programming Lab
}s[20];
void main()
{
int n,k,i,j,avg,d[20],f[20],se[20],t[20],fail[20],dc,fc,sc,tc,failc;
FILE *fp;
clrscr();
printf("\n Enter no. of students :");
scanf("%d",&n);
printf("\n Enter students details :");
for(i=1;i<=n;i++)
{
printf("\n Enter %d student details :",i);
flushall();
printf("\n Roll No :");
gets(s[i].rollno);
flushall();
printf("Name=");
gets(s[i].name);
printf("\n Enter six subject Marks:");
for(j=1;j<=6;j++)
scanf("%d",&s[i].sub[j]);
}
dc=fc=sc=tc=failc=0;
for(i=1;i<=n;i++)
{
if(s[i].sub[1]<40 || s[i].sub[2]<40 ||s[i].sub[3]<40
||s[i].sub[4]<40 ||s[i].sub[5]<40 ||s[i].sub[6]<40)
{
failc++;
fail[failc]=i;
strcpy(s[i].grade,"Fail");
}
else
{
avg=(s[i].sub[1]+s[i].sub[2]+s[i].sub[3]+s[i].sub[4]
+s[i].sub[5]+s[i].sub[6])/6;
if(avg>=70)
{
dc++;
d[dc]=i;
strcpy(s[i].grade,"Distinction");
}
else if(avg>=60)
{
fc++;
f[fc]=i;
strcpy(s[i].grade,"First Class");
}
else if(avg>=50)
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 60
Computer Programming Lab
{
sc++;
se[sc]=i;
strcpy(s[i].grade,"Second Class");
}
else
{
tc++;
t[tc]=i;
strcpy(s[i].grade,"Third Class");
}
}
}
fp=fopen("Results.txt","w");
fputs("Details of Distinction students \n",fp);
fputs("Roll No \t Name \t Grade \n",fp);
for(i=1;i<=dc;i++)
{
k=d[i];
fprintf(fp,"%10s%3s%4s\n",s[k].rollno,s[k].name,s[k].grade);
}
fputs("\nDetails of First class students \n",fp);
fputs("Roll No \t Name \t Grade \n\n",fp);
for(i=1;i<=fc;i++)
{
k=f[i];
fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);
}
fputs("\nDetails of Second class students \n",fp);
fputs("Roll No \t Name \t Grade \n",fp);
for(i=1;i<=sc;i++)
{
k=se[i];
fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);
}
fputs("\nDetails of Third class students \n",fp);
fputs("Roll No \t Name \t Grade \n",fp);
for(i=1;i<=tc;i++)
{
k=t[i];
fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);
}
fputs("\nDetails of Failed students \n",fp);
fputs("Roll No \t Name \t Grade \n",fp);
for(i=1;i<=failc;i++)
{
k=fail[i];
fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);
}
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 61
Computer Programming Lab
}
Input:Enter no. of students :5
Enter students details :
Enter 1 student details :
Roll No :108P1A0312
Name=Rakesh
Enter six subject Marks:65 84 73 81 96 77
Enter 2 student details :
Roll No :108P1A0318
Name=Bala Krishna
Enter six subject Marks:42 36 58 64 55 48
Enter 3 student details :
Roll No :108P1A0325
Name=Raghu
Enter six subject Marks:78 84 77 45 55 42
Enter 4 student details :
Roll No :108P1A0342
Name=Krishna
Enter six subject Marks:42 47 43 40 45 51
Enter 5 student details :
Roll No :108P1A0355
Name=Radhika
Enter six subject Marks:55 64 52 51 58 60
Output:C:\TC3\BIN>type results.txt
Details of Distinction students
Roll No
Name
Grade
108P1A0312 Rakesh
Distinction
Details of First class students
Roll No
Name Grade
108P1A0325 Raghu
First Class
Details of Second class students
Roll No
Name
Grade
108P1A0355 Radhika
Second Class
Details of Third class students
Roll No
Name
Grade
108P1A0342 Krishna
Third Class
Details of Failed students
Roll No
Name
Grade
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 62
Computer Programming Lab
108P1A0318 Bala Krishna Fail
Viva Questions
1. What is an array of structures.
2. How to declare an array within the structure
3. How to open a file
4. What is the use of fputs()
5. What is the difference between structure and union.
30. A file consists of information about employee salary with fields employeeid, name, Basic,
HRA, DA, IT, other-deductions, Gross and Net salary. Initially only employeeid, name, and
basic have valid values. HRA is taken as 10% of the basic, DA is taken as 80% of basic, IT is
20% of the basic, other deductions is user specified. Compute the Gross and Net salary of the
employee and update the file.
Aim:To write a program to accept employeeid , name and basic salary .Calculate HRA,DA,IT and
other deductions as per the given conditions and finally to calculate net and gross salary.
Program Description:We accept employee id, name and basic salary from the user and store these details in a file.
When then calculate the allowances of an employee and update the employee file by including the
allowances, net and gross salaries.
Source Code:#include<stdio.h>
#include<conio.h>
#include<string.h>
struct employ
{
int empid;
char name[15];
float basic;
struct allowances
{
float hra;
float da;
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 63
Computer Programming Lab
float ta;
float pf;
float it;
} a;
float net;
float gross;
}emp[20];
int main()
{
int n,i;
FILE *fp;
printf("\n Enter no. of Employees :");
scanf("%d",&n);
printf("\n Enter Employee details :");
for(i=1;i<=n;i++)
{
printf("\n Enter %d employee details :",i);
printf("\n Employee ID :");
scanf("%d",&emp[i].empid);
flush(stdin);
printf("Name :");
gets(emp[i].name);
printf("\n Basic salary :");
scanf("%f",&emp[i].basic);
}
for(i=1;i<=n;i++)
{
emp[i].a.hra= (emp[i].basic * 20) /100;
emp[i].a.da= (emp[i].basic * 80) /100;
emp[i].a.ta= (emp[i].basic * 12) /100;
emp[i].a.pf= (emp[i].basic * 21) /100;
emp[i].a.it= (emp[i].basic * 10) /100;
emp[i].net= emp[i].basic + emp[i].a.hra + emp[i].a.da +emp[i] .a.ta;
emp[i].gross=emp[i].net - emp[i].a.pf-emp[i].a.it;
}
fp=fopen("employeeDetails.txt","w");
fputs("Details of Employee are \n",fp);
fputs("Employee ID \t Name \t Basic \t HRA \t DA \t TA \t PF \t IT \t Net \t Gross\n",fp);
for(i=1;i<=n;i++)
fprintf(fp,"%6d\t%15s\t%6.2f\t%6.2f\t%6.2f\t%6.2f\t%6.2f\t%6.2f%6.2f%6.2f\n",
emp[i].empid , emp[i].name , emp[i].basic ,emp[i].a.hra , emp[i].a.da , emp[i].a.ta , emp[i].a.pf
, emp[i].a.it , emp[i].net , emp[i].gross);
return(0);
}
Output:Details of Employee are
Employee ID
Name Basic
HRA
DA
TA
PF
IT
Net
Gross
1265
Kumar 5200.00 1040.00 4160.00 624.00 1092.00 520.00 11024.00 9412.00
9586
krishna 6300.00 1260.00 5040.00 756.00 1323.00 630.00 13356.00 11403.00
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 64
Computer Programming Lab
Viva Questions
1. What do you mean by structure within the structure
2. How to access inner and outer structure fields when we use structures within the structures.
3. How to create a pointer to a structure
4. How to access pointer fields of a structure by using a structure variable
5. Can we pass a function as a argument to another function. Justify
31. Write a program to perform Base (decimal, octal, hexadecimal, etc) conversion.
Aim:- To perform Base (decimal, octal, hexadecimal, etc) conversion
Program description:
In this program we input a decimal value and we convert that decimal value into binary, octal
and hexa decimal value.
Source Code:
#include<stdio.h>
#include<conio.h>
void dec_bin(int decimal)
{
int r,q,bin[20],i=1,j;
q=decimal;
while(q!=0)
{
bin[i++]=q%2;
q=q/2;
}
for(j=i-1;j>0;j--)
printf("%d",bin[j]);
}
void dec_oct(int decimal)
{
int r,q,oct[10],i=1,j;
q=decimal;
while(q!=0)
{
oct[i++]= q% 8;
q=q/8;
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 65
Computer Programming Lab
}
for(j=i-1;j>0;j--)
printf("%d",oct[j]);
}
void dec_hex(int decimal)
{
int r,q,i=1,j,temp;
char hexa[10];
q=decimal;
while(q!=0)
{
temp = q % 16;
//To convert integer into character
if( temp < 10)
temp =temp + 48;
else
temp = temp + 55;
hexa[i++]= temp;
q=q/16;
}
for(j=i-1;j>0;j--)
printf("%c",hexa[j]);
}
void main()
{
int decimal,octal;
char hexa[20];
long int bin;
clrscr();
printf("\n Enter a decimal value:");
scanf("%d",&decimal);
printf("\n Given decimal value is=%d",decimal);
printf("\n Equivalent binary value:");
dec_bin(decimal);
printf("\n Equivalent Octal value:");
dec_oct(decimal);
printf("\n Equivalent Hexa decimal value:");
dec_hex(decimal);
}
Output
Enter a decimal value:188
Given decimal value is=188
Equivalent binary value:10111100
Equivalent Octal value:274
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 66
Computer Programming Lab
Equivalent Hexa decimal value:BC
Viva Questions
1. If a value is preceded with ‘0X’ , it can be treated as which type of value.
2. If a value is preceded with ‘0’ , it can be treated as which type of values.
3. If a value is preceded with U,F .what do you mean by that
4. When to use %u format specifier
5. What is the difference between signed and unsigned values.
32. Write a program to find the square root of a number without using built-in library function.
Aim:- to find the square root of a number without using built-in library function.
Program Description:The square root of a number can be calculated by using the following procedure
Step1 :- Estimate - First find a number that is as close as square root of a given number by finding
the perfect square roots in which the given number lies between.
Step 2:- Divide – divide the number by one of those square roots
Step 3:- Average – take the average of the result of step 2 and the root
Step 4:- Use the result of step 3 to repeat step2 and step 3 until we have a number htat is accurate
enough.
Ex:- To Find the square root of 10 we use the above procedure
1. Find the two perfect square numbers it lies between
32=9 , 42=16
So square root(10) lies between 3 and 4
2. Divide 10 by 3 , we get 3.33
3. Find average of 3.33 and 3 , we get 3.1667
4. Repeat step 2 i.e., divide 10 by 3.1667 ,we get 3.1579
5. Repeat step 3 i.e., find average of 3.1579 and 3.1667we get 3.1623
6. Try 3.1623 , we get 3.1623 ×3.1623=10.0001
If this is accurate enough we can stop the process otherwise repeat step2 and step3.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
float i,n,temp,avg,square;
clrscr();
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 67
Computer Programming Lab
printf("\n Enter a number :");
scanf("%ld",&n);
if(n>0)
{
for(i=o;i<=n/2;i++)
{
square=i*i;
if(square==n)
{
printf("\n The Square root of %6.0f is =%6.0f”,n,i);
getch();
exit(0);
}
if(square>n)
break;
}
while(1)
{
temp=n/I;
avg=(i+temp)/2;
square=avg*avg;
if(square<=n+0.0001 && square >=n-0.0001)
{
printf("\n The Square root of %6.2f is =%6.4f”,n,avg);
break;
}
i=avg;
}
}
getch();
}
Input :Enter a number :42
Output:Square Root of 42 is=6.4807
Viva Questions
1. What is the use of break statement
2. What is the use of exit()
3. What is unconditional branching statement
4. What are the different types of operators available in c
5. What is the difference between && and &
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 68
Computer Programming Lab
33. Write a program to convert from string to number
Aim:- To convert from string to number
Program Description:In this program we input a string which consists of digits and optionally a minus sign at
beginning for integers. For string containing other characters we can stop conversion as soon as a non
digit character is encountered.
Source Code:#include<stdio.h>
int stringToInt(char[] );
int main()
{
char str[10];
int intValue;
printf("Enter any integer as a string: ");
scanf("%s",str);
intValue = stringToInt(str);
printf("Equivalent integer value: %d",intValue);
return 0;
}
int stringToInt(char str[])
{
int i=0,sum=0;
while(str[i]!='\0')
{
if(str[i]< 48 || str[i] > 57)
{
printf("Unable to convert it into integer.\n");
return 0;
}
else
{
sum = sum*10 + (str[i] - 48);
i++;
}
}
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 69
Computer Programming Lab
return sum;
}
Output:
Input:
Enter any integer as a string: -125
Equivalent integer value: -125
Output:
Enter any integer as a string: 12A3
Unable to convert it into integer.
Equivalent integer value: 0
Viva Questions
1. What is the ASCII value of A and a
2. What is the ASCII value for 0
3. What is the function used to identify whether a character is digit or not.
4. What is a function prototype
5. What is the difference if we declare a function above the main and within the main.
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 70
Computer Programming Lab
34. Write a program to generate pseudo random generator.
Aim:To write a program to generate pseudo random generator
Program Description:We use rand() to create a pseudo random generator
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for (i = 0; i < 10; i++)
{
printf("random_number[%d]= %d\n", i + 1, rand());
}
}
Output:random_number[1]= 346
random_number[2]= 130
random_number[3]= 10982
random_number[4]= 1090
random_number[5]= 11656
random_number[6]= 7117
random_number[7]= 17595
random_number[8]= 6415
random_number[9]= 22948
random_number[10]= 31126
Viva Questions
1. What is the use of rand()
2. What is the difference between round(),ceil() and floor()
3. List any 8 mathematical functions
4. conio.h stands for?
5. What do you mean by console
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 71
Computer Programming Lab
35. Write a program to generate multiplication tables from 11 to 20.
Aim:- to write a program to generate multiplication tables from 11 to 20
Program description:In this program we uses nested for loop to obtain the required result.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,p,m,t;
clrscr();
k=1;
t=11;
for(i=1;i<=10;i++)
{
p=t;
for(j=1;j<=5;j++) // tables from 11 to 15
{
m=p*k;
printf("%3d*%2d=%3d",p,k,m);
p++;
}
printf("\n");
k++;
if(i==10 && t==11) //tables from 16 to 20
{
printf("\n\n");
i=0;
t=16;
k=1;
}
}
getch();
}
Output:11* 1= 11
11* 2= 22
11* 3= 33
11* 4= 44
11* 5= 55
11* 6= 66
12* 1= 12
12* 2= 24
12* 3= 36
12* 4= 48
12* 5= 60
12* 6= 72
13* 1= 13
13* 2= 26
13* 3= 39
13* 4= 52
13* 5= 65
13* 6= 78
14* 1= 14
14* 2= 28
14* 3= 42
14* 4= 56
14* 5= 70
14* 6= 84
15* 1= 15
15* 2= 30
15* 3= 45
15* 4= 60
15* 5= 75
15* 6= 90
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 72
Computer Programming Lab
11* 7= 77
11* 8= 88
11* 9= 99
11*10=110
16* 1= 16
16* 2= 32
16* 3= 48
16* 4= 64
16* 5= 80
16* 6= 96
16* 7=112
16* 8=128
16* 9=144
16*10=160
12* 7= 84
12* 8= 96
12* 9=108
12*10=120
17* 1= 17
17* 2= 34
17* 3= 51
17* 4= 68
17* 5= 85
17* 6=102
17* 7=119
17* 8=136
17* 9=153
17*10=170
13* 7= 91
13* 8=104
13* 9=117
13*10=130
18* 1= 18
18* 2= 36
18* 3= 54
18* 4= 72
18* 5= 90
18* 6=108
18* 7=126
18* 8=144
18* 9=162
18*10=180
14* 7= 98
14* 8=112
14* 9=126
14*10=140
19* 1= 19
19* 2= 38
19* 3= 57
19* 4= 76
19* 5= 95
19* 6=114
19* 7=133
19* 8=152
19* 9=171
19*10=190
15* 7=105
15* 8=120
15* 9=135
15*10=150
20* 1= 20
20* 2= 40
20* 3= 60
20* 4= 80
20* 5=100
20* 6=120
20* 7=140
20* 8=160
20* 9=180
20*10=200
Viva Questions
1. What are bitwise operators
2. What is the use of ?:
3. What is a constant
4. What are the different ways to declare a constant
5. What is enum
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 73
Computer Programming Lab
36. Write a program to express a four digit number in words. For example 1546 should be
written as one thousand five hundred and forty six.
Aim:- To express four digit number in words
Program Description:In this program, we divide the number by 10 and identify the digits in various places and write
the corresponding digit in words by using the switch statement.
Source Code:#include<stdio.h>
#include<conio.h>
void printword(int);
void printtensword(int);
void printteenword(int);
void main()
{
int n,r,i,th,hun,ten,unit;
clrscr();
printf("\n Enter a four digit number:");
scanf("%d",&n);
th=n/1000;
hun=(n%1000)/100;
ten=(n%100)/10;
unit=n%10;
if(n==0)
printf(" Zero ");
if(th>0)
{
printword(th);
printf("thousand");
}
if(hun>0)
{
printword(hun);
printf(" hundred and ");
}
if(ten>1 || unit==0)
printtensword(ten);
if(ten==1)
printteenword(unit);// it depends on unit place
if(unit>0 && ten>1)
printword(unit);
getch();
}
void printword(int ch)
{
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 74
Computer Programming Lab
switch(ch)
{
case 1: printf(" One ");
break;
case 2: printf(" Two ");
break;
case 3: printf(" Three ");
break;
case 4: printf(" Four ");
break;
case 5: printf(" Five ");
break;
case 6: printf(" Six ");
break;
case 7: printf(" Seven ");
break;
case 8: printf(" Eight ");
break;
case 9: printf(" Nine ");
break;
}
}
void printtensword(int ch)
{
switch(ch)
{
case 2: printf(" Twenty ");
break;
case 3: printf(" Thrirty ");
break;
case 4: printf(" Forty ");
break;
case 5: printf(" Fifty ");
break;
case 6: printf(" Sixty ");
break;
case 7: printf(" Seventy ");
break;
case 8: printf(" Eighty ");
break;
case 9: printf(" Ninty ");
break;
}
}
void printteenword(int ch)
{
switch(ch)
{
case 1: printf(" Eleven ");
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 75
Computer Programming Lab
break;
case 2: printf(" Twelve ");
break;
case 3: printf(" Thrirteen ");
break;
case 4: printf(" Forteen ");
break;
case 5: printf(" Fifteen ");
break;
case 6: printf(" Sixteen ");
break;
case 7: printf(" Seventeen ");
break;
case 8: printf(" Eighteen ");
break;
case 9: printf(" Ninteen ");
break;
Viva Questions
1. What is the use of Switch Statement
2. What is the use of default expression
in a switch statement
3. Why to use break in case of switch
4. What are the rules for case labels
5. What is the use of comma operator
}
}
Input:Enter a four digit number:3265
Output:Three thousand Two hundred and Sixty Five
37. Write a program to generate telephone bill as per BSNL rules
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 76
Computer Programming Lab
Subscriber
category
<999
10002999
30000 –
99999
70
0
120
0
200
0
280
0
1.40
1.40
1.40
1.40
140
0
140
0
180
0
180
0
1.40
1.40
1.40
1.40
300
225
300
225
300
225
300
225
1.20
1.20
1.20
1.20
425
400
425
400
425
400
425
400
1.10
1.10
1.10
1.10
975
1000
975
1000
975
1000
975
1000
1.00
1.00
1.00
1.00
1450
1500
1450
1500
1450
1500
1450
1500
0.90
0.90
0.90
0.90
2450
3000
2450
3000
2450
3000
2450
3000
0.80
0.80
0.80
0.80
90
0
90
0
140
0
140
0
1.20
1.20
1.20
1.20
>100000
Plan details and charges
Rural
Basic
Urban
Economy
Special
Special
Plus
Super
Premium
Sulabh
Same for
both
Rural &
Urban
Same for
both
Rural &
Urban
Same for
both
Rural &
Urban
Same for
both
Rural &
Urban
Same for
both
Rural &
Urban
Same for
both
Rural &
Urban
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Note:- The bill amount should include monthly rent , usage charges , service tax(12%) ,education
CESS (2%), Higher Education CESS (1%)
Aim:To write a program to generate the telephone bill as per BSNL rules.
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 77
Computer Programming Lab
Program Description:In this program , we used nested switch statement to calculate the rent , free calls and call charge.
Finally we generate the telephone bill as per the BSNL rules
Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int ctgy,ptgy,ncalls,tcalls,free_calls;
float rent,call_charge,camt,amt,stax,ecess,hcess,total;
char area_type,month[20],cname[20],cadd[40];
clrscr();
printf("\n Subscribers Categories:");
printf("\n 1. 0-999");
printf("\n 2. 1000-2999");
printf("\n 3. 30000-99999");
printf("\n 4. above 100000");
printf("\n Select the category(1-4) :");
scanf("%d",&ctgy);
clrscr();
printf("\n Plan Categories:");
printf("\n 1. Basic");
printf("\n 2. Economy");
printf("\n 3. Special");
printf("\n 4. Special Plus");
printf("\n 5. Super");
printf("\n 6. Premium");
printf("\n 7. Sulab");
printf("\n Select the plan category(1-7) :");
scanf("%d",&ptgy);
flushall();
printf("\n Enter the area type(r/u):");
scanf("%c",&area_type);
switch(ctgy)
{
case 1: switch(ptgy)
{
case 1:if(area_type=='r')
rent=70;
else
rent=140;
free_calls=0;
call_charge=1.40;
break;
case 7:rent=90;
free_calls=0;
call_charge=1.20;
break;
}
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 78
Computer Programming Lab
case 2: switch(ptgy)
{
case 1:if(area_type=='r')
rent=120;
else
rent=140;
free_calls=0;
call_charge=1.40;
break;
case 7:rent=90;
free_calls=0;
call_charge=1.20;
break;
}
case 3: switch(ptgy)
{
case 1:if(area_type=='r')
rent=200;
else
rent=180;
free_calls=0;
call_charge=1.40;
break;
case 7:rent=140;
free_calls=0;
call_charge=1.20;
break;
}
case 4: switch(ptgy)
{
case 1:if(area_type=='r')
rent=280;
else
rent=180;
free_calls=0;
call_charge=1.40;
break;
case 7:rent=140;
free_calls=0;
call_charge=1.20;
break;
}
}
switch(ptgy)
{
case 2: rent=300;
free_calls=225;
call_charge=1.20;
break;
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 79
Computer Programming Lab
case 3: rent=425;
free_calls=400;
call_charge=1.10;
break;
case 4: rent=975;
free_calls=1000;
call_charge=1.00;
break;
case 5: rent=1450;
free_calls=1500;
call_charge=0.90;
break;
case 6: rent=2450;
free_calls=3000;
call_charge=0.80;
break;
}
flushall();
printf("\n Enter the customer name :");
gets(cname);
printf("\n Enter the customer address :");
gets(cadd);
printf("\n Enter billing month:");
scanf("%s",month);
printf("\n Enter number of calls made during the month:");
scanf("%d",&ncalls);
tcalls=ncalls-free_calls;
if(tcalls<0)
tcalls=0;
camt=tcalls*call_charge;
amt=rent+camt;
stax=(amt*12)/100;
ecess=(amt*2)/100;
hcess=(amt*1)/100;
total=rent+camt+stax+ecess+hcess;
clrscr();
printf("\n BHARAT SANCHAR NIGAM LTD.");
printf("\n TELEPHONE BILL");
printf("\n Customer Name:");
puts(cname);
printf("\n Customer Address:");
puts(cadd);
printf("\n Billing Month :");
puts(month);
printf(" \n Summary of Charges \t Amount");
printf("\n Monthly Rent
\t%6.2f",rent);
printf("\n No. of free calls \t%6d",free_calls);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 80
Computer Programming Lab
printf("\n No.of Calls Made \t%6d",ncalls);
printf("\n Usage Charges
\t%6.2f",camt);
printf("\n Service Tax
\t%6.2f",stax);
printf("\n Education CESS
\t%6.2f",ecess);
printf("\n Higher Edu. CESS \t%6.2f",hcess);
printf("\n Total Charges
\t%6.2f",total);
getch();
}
Input
Subscribers Categories:
1. 0-999
2. 1000-2999
3. 30000-99999
4. above 100000
Select the category(1-4) :2
Plan Categories:
1. Basic
2. Economy
3. Special
4. Special Plus
5. Super
6. Premium
7. Sulab
Select the plan category(1-7) :4
Enter the area type(r/u): u
Enter the customer name : C. Sudheer Kumar
Enter the customer address : 21-157, Thilak road , Anantapur
Enter billing month: January-2014
Enter number of calls made during the month: 2258
Output
BHARAT SANCHAR NIGAM LTD.
TELEPHONE BILL
Customer Name: C Sudheer Kumar
Customer Address:21-157, Thilak Raod, Anantapur
Billing Month : January-2014
Summary of Charges
Amount
Monthly Rent
975.00
No. of free calls
1000
No.of Calls Made
2258
Usage Charges
1258.00
Service Tax
267.96
Education CESS
44.66
Higher Edu. CESS
22.33
Total Charges
2567.95
-
Viva Questions
1. C is structured programming language. Justify
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 81
Computer Programming Lab
2. What is the difference between top-down and bottom-up approaches
3. Write the structure a c program
4. What is a macro substitution directive
5. What is the use of #define.
38. Write a program to find the execution time of a program.
Aim:- To find the execution time of a program
Program Description:In this program we find the execution time by starting the clock at beginning of the task and ending
the clock at end of task.
Source Code:Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 82
Computer Programming Lab
#include<stdio.h>
#include<time.h>
void main()
{
int i;
double total_time;
clock_t start, end;
clrscr();
start = clock();//time count starts
srand(time(NULL));
for (i = 0; i < 25000; i++)
{
printf("random_number[%d]= %d\n", i + 1, rand());
}
end = clock();//time count stops
total_time = ((double) (end - start)) / CLK_TCK;//calulate total time
printf("\nTime taken to print 25000 random numbers is: %6.4f seconds", total_time);
return 0;
}
Output:random_number[1]= 26367
random_number[2]= 22547
random_number[3]= 26102
random_number[4]= 8734
random_number[5]= 18502
:
:
:
random_number[24997]= 23216
random_number[24998]= 29173
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 83
Computer Programming Lab
random_number[24999]= 13056
random_number[25000]= 7925
Time taken to print 25000 random numbers is: 17.5275 seconds
Viva Questions
1. What are different functions available in time.h
2. What is an algorithm
3. What are the different categories of algorithms
4. What is a flow chart
5. What are the different steps involved in software development life cycle
39. Design a file format to store a person's name, address, and other information. Write a
program to read this file and produce a set of mailing labels
Aim:To write a c program which accepts person’s name, address ,mobile no., etc and store these details
in a file. Read the contents of the file and print the details in a label format.
Program Description:The program accept the details of a person and store the details in a file. Then the file is opened
in a read mode and print the contents in a label format.
Source Code
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 84
Computer Programming Lab
#include<stdio.h>
#include<string.h>
struct person
{
char name[15];
char dno[15];
char street[15];
char city[15];
long int pincode;
double mobileno;
}s[20];
int main()
{
int n,i,j;
long int pin;
double mob;
char pname[15],d[15],strt[15],c[15];
FILE *fp;
fp=fopen("person.txt","w");
printf("\n Enter no. of Persons :");
scanf("%d",&n);
printf("\n Enter Person details :");
for(i=1;i<=n;i++)
{
printf("\n Enter %d person details :\n",i);
printf("Name :");
scanf("%s",s[i].name);
printf("Door No :");
scanf("%s",s[i].dno);
printf("Street : ");
scanf("%s",s[i].street);
printf("City :");
scanf("%s",s[i].city);
printf("Pincode : ");
scanf("%ld",&s[i].pincode);
printf("Mobile No :");
scanf("%lf",&s[i].mobileno);
fprintf(fp,"%15s%15s%15s%15s%12ld%12.0lf\n",s[i].name,s[i].dno,s[i].street,s[i].city,s[i].pin
code,s[i].mobileno);
}
fclose(fp);
printf("Mailing Labels");
fp=fopen("person.txt","r");
for(i=1;i<=n;i++)
{
printf("\n");
for(j=1;j<=25;j++)
printf("_");
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 85
Computer Programming Lab
printf("\n|");
fscanf(fp,"%s",pname);
printf("%20s|",pname);
printf("\n|");
fscanf(fp,"%s",d);
printf("%20s|",d);
printf("\n|");
fscanf(fp,"%s",strt);
printf("%20s|",strt);
printf("\n|");
fscanf(fp,"%s",c);
printf("%20s|",c);
printf("\n|");
fscanf(fp,"%ld",&pin);
printf("%-20ld|",pin);
printf("\n|");
fscanf(fp,"%lf",&mob);
printf("%-20.0lf|",mob);
printf("\n");
for(j=1;j<=25;j++)
printf("_");
printf("\n");
}
return 1;
}
Output
Enter no. of Persons :2
Enter Person details :
Enter 1 person details :
Name : prakash
Door No :2-34
Street : Nehru-street
City : Anantapur
Pincode : 515001
Mobile No : 7893005535
Enter 2 person details :
Name : Sudheer
Door No :21-157
Street : Tagore-street
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 86
Computer Programming Lab
City : Anantapur
Pincode : 515001
Mobile No : 9505000794
Mailing Labels
_________________________
|
raju|
|
2-34|
|
Nehru-street|
|
Madanapalle|
|517325
|
|9876543210
|
_________________________
_________________________
|
Kiran|
|
34-56|
|
Tagore-street|
|
Madanapalle|
|517325
|
|9638527410
|
_________________________
Viva Questions
1. What are bit fields
2. What is the use of typedef
3. What is the use of variable length parameter list
4. C program execution starts from where
5. main is a keyword or not. Justify
Srinivasa Ramanujan Institute of Technology, Ananthapuramu
Page 87