Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

c programming lab manual final(new) (1)

The document is a lab manual for B.Tech. I Semester students focusing on Computer Programming using C. It contains a comprehensive list of programming exercises, including tasks related to data types, operators, control structures, arrays, functions, and file handling. Each section includes algorithms, source code, and expected outputs for various C programming tasks.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

c programming lab manual final(new) (1)

The document is a lab manual for B.Tech. I Semester students focusing on Computer Programming using C. It contains a comprehensive list of programming exercises, including tasks related to data types, operators, control structures, arrays, functions, and file handling. Each section includes algorithms, source code, and expected outputs for various C programming tasks.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 96

I B.Tech. – I Sem.

Computer Programming using C Lab

Table of Contents
Sl. No. Contents Page No

1. Write A C PROGRAM TO PRINT SIZE OF ALL DATA TYPES?.........................1


2. Write A C PROGRAM TO PRINT range OF ALL DATA TYPES?.........................2
3. write a c program to determine working operators of c operators?............................3
4. write a c program to illustrate the math.h functions?..................................................5
5. write a c program to find if number is even or odd using if-else condition?..............6
6. write a c program to find greatest number using nested-if condition?........................7
7. write a c program to find greatest number using if-else ladder condition?................8
8. write a c program to read roll number,6 subject marks.Find out total ,average of
marks and grade points?..............................................................................................9
9. write a c program to print name of given numbers using switch statements?..........10
10. write a c program to print your name using while loop?..........................................11
11. write a c program to print your name using for loop?..............................................12
12. write a c program to print your name using do-while loop?.....................................13
13. write a c program to print numbers using while loop using break?..........................14
14. write a c program to print numbers using for loop using continue?.........................15
15. write a c program which is menu trivial program to compute area of various
geometrical shapes?..................................................................................................16
16. write a c program to calculate factorial of a given number?.....................................17
17. write a c program to display n terms of even natural numbers and their sum?.........18
18. write a c program to display n terms in harmonic series and their sum ?1+1/2+1/3+
…+1/n.......................................................................................................................19
19. write a c program to check whether the given number is an Armstrong or not?......20
20. write a c program to compare two strings without using string library functions?...21
21. WRITE A C PROGRAM TO ILLUSTRATE ALL STRING HANDLING
FUNCTION?.............................................................................................................22
22. write a c program to print individual character string in reverse order?...................23
23. write a c program to print all unique numbers in an array?......................................24
24. write a c program to separate odd and even integers in separate arrays?.................25
25. write a c program to sort array in descending order?................................................26
26. write a c program to find transpose of a matrix?......................................................27
27. write a c program to print the matrix multiplication of two square matrices?..........28
28. write a c program to find addition of square matrices?.............................................30
I B.Tech. – I Sem. Computer Programming using C Lab

29. write a c program to check whether given number is prime number or not using
function?....................................................................................................................32
30. write a c program to get largest number of an array using function?.......................33
31. write a c program to add the two numbers using call by value?...............................34
32. write a c program to swap two elements using call by reference?............................35
33. write a c program to find the factorial of given number is recursive function?........36
34. write a c program to store user information using dynamic memory allocation?.....37
35. write a c program to demonstrate how to handle the pointers in program and also
usage of & and * operator ?.....................................................................................38
36. write a c program to find the largest element using dynamic memory allocation?. .39
37. write a c program to find sum of two numbers using dynamic memory location?...40
38. write a c program to display contents of file?...........................................................41
39. write a c program to copy one file to another?..........................................................42
40. write a c program to append one file to another file?...............................................43
41. write a c program using e-num?................................................................................44
42. write a c program to write to a binary file using fwrite?...........................................45
43. write a c program using typedef with structures/unions?..........................................46
44. Write a c program to implement the Bisection method for finding the real root of a
nonlinear equation.....................................................................................................47
45. Write a c program to implement the Newton-Raphson method for finding real roots
of a nonlinear equation..............................................................................................50
46. Write a c program to implement the LaGrange interpolation formula.....................53
47. Write a c program for approximating the definite integral of a continues function
using Simpson's 1/3 rule...........................................................................................56
I B.Tech. – I Sem. Computer Programming using C Lab

1.Write A C PROGRAM TO PRINT SIZE OF ALL DATA TYPES?

Algorithm:

1. Define variables for each data type:

Declare variables of various data types for which you want to find the sizes. You can use
sizeof operator to find the size of each data type

2 Use printf to print the size of each data type:

Use printf statements to print the size of each data type along with a message.

3. Compile and run the program:

Save the program in a .c file (e.g., sizeof_datatypes.c) and compile it using a C compiler. Then,
run the executable to see the sizes of different data types.

4.Exit the program.

Source code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main(void)
{
printf("\n * Size of Integer Data Types***");
printf("\n size of integer is: %d", sizeof(int));
printf("\n size of signed int is : %d", sizeof(signed int));
printf("\n size of unsigned int Is: %d", sizeof(unsigned int));
printf("\n** size of short Integer Data Types**");
printf("\n size of short int is: %d", sizeof(short int));
printf("\n size of signed short int is: %d", sizeof(signed short int));
printf("\n size of unsigned short int is: %d", sizeof(unsigned short int));
printf("\n size of character Data Types *");
printf("\n size of char is: %d", sizeof(char));
printf("\n size of signed char is: %d", sizeof(char));
printf("\n size of unsigned char is: %d", sizeof(unsigned char));
printf("\n\n* Size of Long Integer Data Types *");
printf("\n size of long int is: %d", sizeof(long int));
printf("\n size of signed long int is:%d",sizeof(signed long int));
printf("\n size of unsigned long int is :%d", sizeof(unsigned long int));
printf("\n size of long long int is: %d", sizeof(long long int));
printf("\n size of unsigned long long int is: %d", sizeof(unsigned long long int));
printf("\n size of Float Data Types");
printf("In size of float is: %d", sizeof(float));
printf("\n sige of double is : %d", sizeof(double));
printf ("\n size of long double is: %d",sizeof(long double));
getch();
return 0;
}

1|Page
I B.Tech. – I Sem. Computer Programming using C Lab

Output:
* Size of Integer Data Types***
size of integer is: 4
size of signed int is : 4
size of unsigned int Is: 4
** size of short Integer Data Types**
size of short int is: 2
size of signed short int is: 2
size of unsigned short int is: 2
size of character Data Types *
size of char is: 1
size of signed char is: 1
size of unsigned char is: 1
* Size of Long Integer Data Types *
size of long int is: 4
size of signed long int is:4
size of unsigned long int is :4
size of long long int is: 8
size of unsigned long long int is: 8
size of Float Data TypesIn size of float is: 4
sige of double is : 8
size of long double is: 16

2|Page
I B.Tech. – I Sem. Computer Programming using C Lab

2.Write A C PROGRAM TO PRINT range OF ALL DATA TYPES?

Algorithm:

1. Define variables to store the range information.


2. Print the range of each data type using the predefined macros from <limits.h> and
<float.h>.
3. Compile and run the program to see the range information for various data types.

* Note that the specific range values may vary depending on your system and
compiler.

4.Exit the program.

Source code:-
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
printf("The Range of character Data Types");
printf("\n range of CHAR bit %d", (CHAR_BIT));
printf("\n range of CHAR Maximum is : %d", (CHAR_MAX));
printf("\n range of CHAR minimum is: %d", (CHAR_MIN));
printf("\n range of Integer Data Types");
printf("\n range of INT maximum is:%d", (INT_MAX));
printf("\n range of INT minimum is: %d", (INT_MIN));
printf("\n range of unsigned INT maximum is: %d", (INT_MAX));
printf("\n range of Long Integer Data Type");
printf("\n range of signed CHAR maximum is: %d", (CHAR_MAX));
printf("\n range of signed CHAR minimum is: %d", (CHAR_MIN));
printf("\n range of unsigned CHAR maximum is: %d", (CHAR_MAX));
printf("\n range of Short Integer Data Types");
printf("\n range of short INT maximumis: %hd", (SHRT_MAX));
printf("\n range of short INT minimum is: %hd", (SHRT_MIN));
printf("\n range of unsigned short INT maximum is %d", (SHRT_MAX));
printf("\n range of long INT maximum range is: %ld", (LONG_MAX));
printf("\n range of Long INT minimum range is %ld",(LONG_MIN));
printf("\n range of unsigned long INT maximum range is % lu", (LONG_MAX));
getch();
}
Output:
The Range of character Data Types
range of CHAR bit 8
range of CHAR Maximum is : 127
range of CHAR minimum is: -128
range of Integer Data Types
range of INT maximum is:2147483647

3|Page
I B.Tech. – I Sem. Computer Programming using C Lab

range of INT minimum is: -2147483648


range of unsigned INT maximum is: 2147483647
range of Long Integer Data Type
range of signed CHAR maximum is: 127
range of signed CHAR minimum is: -128
range of unsigned CHAR maximum is: 127
range of Short Integer Data Types
range of short INT maximumis: 32767
range of short INT minimum is: -32768
range of unsigned short INT maximum is 32767
range of long INT maximum range is: 2147483647
range of Long INT minimum range is -2147483648
range of unsigned long INT maximum range is 2147483647

4|Page
I B.Tech. – I Sem. Computer Programming using C Lab

3.write a c program to determine working operators of c


operators?
Algorithm:

1. Define the main function:


Define the main() function, which is the entry point of the C program.
2. .Declare and initialize variables:
Declare and initialize variables to hold values for the operators' operations.
3. Perform logical operations:
Perform logical operations using logical operators (e.g., &&, ||, !) and display the results.
4. Perform arithmetic operations:
Perform arithmetic operations using arithmetic operators (e.g., +, -, *, /, %) and display
the results.
5. Perform shift operations:
Perform shift operations using shift operators (e.g., <<, >>) and display the results.
6. Perform relational operations:
Perform relational operations using relational operators (e.g., ==, !=, <, >, <=, >=) and
display the results.
7. Perform increment and decrement operations:
Perform increment and decrement operations using increment and decrement operators
(e.g., ++, --) and display the results.
8. Display the results:
Display the results of each operation to demonstrate the behavior of the respective
operators.
9.Exit the program.

Source code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

void main()
{
int a,b;
printf("enter the numbers: \n");
scanf("%d%d",&a,&b);
printf("Arithmatic operators");

5|Page
I B.Tech. – I Sem. Computer Programming using C Lab

printf("sum of numbers a and b is %d",(a+b));


printf("difference of numbers a-b is %d\n",(a-b));
printf("product of numbers a and b %d\n",(a*b));
printf("division of numbers a and b is %d\n",(a/b));
printf("modulus of numbers a/b %d\n",(a%b));
printf("Relational operators");
printf("less than operator %d\n",(a<b));
printf("Greater than operator %d\n",(a>b));
printf(" Equal to operator %d\n",(a==b));
printf("Not equal to operator %d\n",(a!=b));
printf("Increment operators");
printf("pre increment ++a %d\n",(++a));
printf("post increment b++ %d\n", (b++));
printf("Decrement operators");
printf("pre decrement --a %d\n",(--a));
printf("post decrement b-- %d\n",(b--));
printf("logical operators");
printf("AND operator %d\n",(a&b));
printf("OR Operator %d\n",(a|b));
printf("NOT operator %d\n",(!(a>b)));
printf("BIT WISE operator");
printf("AND OPERATOR %d\n",(a&&b));
printf("OR OPERATOR %d\n",(a||b));
printf("left shift operator %d\n",a<<2);
printf("Right shift operator %d\n",b>>3);
printf("exclusive OR operates %d\n",(a^b));
printf("Ternary operator");
printf(" the value of %d\n",(a<b?a:b));
getch();
}
Out put:
enter the numbers:
10 8
Arithmatic operatorssum of numbers a and b is 18difference of numbers a-b is 2
product of numbers a and b 80
division of numbers a and b is 1

6|Page
I B.Tech. – I Sem. Computer Programming using C Lab

modulus of numbers a/b 2


Relational operatorsless than operator 0
Greater than operator 1
Equal to operator 0
Not equal to operator 1
Increment operatorspre increment ++a 11
post increment b++ 8
Decrement operatorspre decrement --a 10
post decrement b-- 9
logical operatorsAND operator 8
OR Operator 10
NOT operator 0
BIT WISE operatorAND OPERATOR 1
OR OPERATOR 1
left shift operator 40
Right shift operator 1
exclusive OR operates 2
Ternary operator the value of 8

7|Page
I B.Tech. – I Sem. Computer Programming using C Lab

4.write a c program to illustrate the math.h functions?

Algorithm:

1. Declare the main function: Define the main function, which is the entry point of
your. Program.
2. Use math.h functions: Inside the main function, you can use various math.h
functions. Here are some examples: *Square
Root (sqrt): Calculate the square root of a number.
*Exponentiation (pow): Calculate the power of a number.
*Trigonometric Functions (sin, cos, tan): Calculate trigonometric values.
*Logarithmic Functions (log, log10): Calculate logarithms.
3. Compile and run the program: Save your C program with a .c extension (e.g.,
math_functions.c).
4. Execute the program: Run the compiled program.
5. Exit the program.

Source code:
#include<stdio.h>
#include<math.h>
void main()
{
double x=4.5,y=5,Pi=M_PI;
printf("Square root value of filter is %lf\n", x,sqrt(x));
printf("exponential value is %lf\n",x,(exp(x)));
printf("natural log of %lf is %lf\n", x,log(x));
printf("log 10 value of %lf is %lf\n",x,log10(x));
printf("absolute value is off %lf\n",x,fabs(x));
printf("ceil value of %lf is %lf\n",x,ceil(x));
printf("floor value of %lf is %lf\n",x,(floor(x)));
printf("power value is %lf\n",(pow(x,y)));
printf("Modular value of %lf is %lf/n",(fmod(x,y)));
printf("sine of X value is %lf\n",sin(x));
printf("Cosine of x value is %lf\n",cos(x));
printf("tan of x value is %lf\n",tan(x));
printf("hyperbolic sine of x is %lf\n",sinh(x));
printf("hyperbolic cosine of x is %lf\n",cosh(x));
printf("hyperbolic tan of x is %lf\n",tanh(x));
printf("arc sine of X is %lf\n",asin(sin(x)));
printf("arc cosine of x is %lf\n",acos(cos(x)));
printf("arc tan of x is %lf\n",atan(tan(x)));
printf("sine of pi %lf\n",sin(M_PI));
printf("cosine of pi is %lf\n",cos(M_PI));
printf(" tan of pi is %lf\n",tan(M_PI));
getch();
}

8|Page
I B.Tech. – I Sem. Computer Programming using C Lab

Output:-
Square root value of filter is 4.500000
exponential value is 4.500000
natural log of 4.500000 is 1.504077
log 10 value of 4.500000 is 0.653213
absolute value is off 4.500000
ceil value of 4.500000 is 5.000000
floor value of 4.500000 is 4.000000
power value is 1845.281250
Modular value of 4.500000 is 0.000000/nsine of X value is -0.977530
Cosine of x value is -0.210796
tan of x value is 4.637332
hyperbolic sine of x is 45.003011
hyperbolic cosine of x is 45.014120
hyperbolic tan of x is 0.999753
arc sine of X is -1.358407
arc cosine of x is 1.783185
arc tan of x is 1.358407
sine of pi 0.000000
cosine of pi is -1.000000
tan of pi is -0.000000

9|Page
I B.Tech. – I Sem. Computer Programming using C Lab

5.write a c program to find if number is even or odd using if-else


condition?

Algorithm:

1. Declare Variables: Declare a variable to store the input number.


2. Input: Prompt the user to enter a number and read the input.
3. Check Even or Odd: Use an if-else statement to check if the number is even or
odd.
* The % operator is used to calculate the remainder when num is divided by 2.
* The % If the remainder is 0, the number is even. Otherwise, it's odd.

4. Output: Display the result.

5. End of Program: Return 0 to indicate successful program execution.

Source code:-
#include<stdio.h>
void main()
{
int n;
printf("enter a number:");
scanf("%d",&n);
if(n%2 ==0)
{
printf("number is even");
}
else
{
printf("number is odd");
}
getch();
}
Output:
enter a number:8
number is even

10 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

6.write a c program to find greatest number using nested-if


condition?

Algorithm:

1. Define the main function, which is the entry point of the program.
2. In this program, we declare three integer variables num1, num2, and
num3 to store the input numbers. We use the scanf function to read
three numbers from the user.
3. The nested if statements are used to compare the numbers. We first
compare num1 and num2, and then based on the result of this
comparison, we compare the greater of the two with num3 to determine
the greatest number.

* If num1 is greater than or equal to num2, it compares num1 with


num3.
* If num1 is greater than or equal to num3, it means that num1 is the
greatest number.
* If num1 is not greater than or equal to num3, it means that num3 is
the greatest number.
* If num1 is not greater than or equal to num2, it compares num2
with num3.
* If num2 is greater than or equal to num3, it means that num2 is the
greatest number.
* If num2 is not greater than or equal to num3, it means that num3 is
the greatest number.

4. Finally, we use printf to display the greatest number to the user.


5. Compile the program and run it. Enter three numbers when prompted,
and the program will display the greatest among them.

6.Exit the program.

Source code:-
#include<stdio.h>
void main()
{
int a, b, c;
printf("enter the numbers: \n");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)

11 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

printf("a");
else
printf("c");
}
else
{
if(b>c)
printf("b");
else
printf("c");
}

getch();
}Output:-
enter the numbers:
3 7 10
c

12 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

7.write a c program to find greatest number using if-else ladder


condition?

Algorithm:

1. Declare variables to store the numbers and the greatest number.


 You can use variables like num1, num2, num3, and max to store the
input numbers and the greatest number.
2. Input the numbers from the user:
 Use scanf or any other input method to get the values of num1,
num2, and num3 from the user
3. Compare the numbers using the if-else ladder:
 Use a series of if-else if statements to compare the numbers
and find the greatest one. The ladder structure ensures that each
condition is checked in order until a true condition is found.
 if num1 is greater than or equal to both num2 and num3, and if it is, it
assigns num1 to greatest. If not, it checks if num2 is greater, and if not,
it assigns num3 to greatest.
4. Display the greatest number:
 Use printf to display the value of the greatest number.
6. Complete the Program: Complete the program with a return 0;
statement to indicate successful execution.

7.Exit the program.

Source Code:
#include<stdio.h>
void main()
{
int a,b,c;
printf("enter the numbers: \n");
scanf("%d%d%d",&a,&b,&c);
if((a>b) && (a>c))
printf("a");
else if(b>c)
printf("b");
else
printf("C");
getch();
}

13 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

Output:-
enter the numbers:
378
C

14 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

8.write a c program to read roll number,6 subject marks.Find out


total ,average of marks and grade points?

Algorithm:

1. Define the main function, which is the entry point of the program.
2. Define constants for the number of subjects and grade points.
3. Declare variables to store the roll number, subject marks, total, average, and grade
points.
4. Display a message to prompt the user to enter the roll number.
5. Read the roll number from the user.
6. Display a message to prompt the user to enter the marks for each subject.
7. Use a loop to read the marks for each subject and calculate the total marks.
8. Calculate the average marks.
9. Determine the grade points based on the average marks.
10. Display the roll number, total marks, average marks, and grade points.
11. Exit the program.

Source code:-
#include<stdio.h>
int main()
{
int a,b,c,d,e,f,rollno, tot, Avg, grades;
char name[8];
printf("Enter the student name:");
scanf("%s",&name);
printf("enter the roll number\n");
scanf("%d",&rollno);
printf("enter six subject marks \n");
scanf("%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f);
tot = a+b+c+d+e+f;
Avg = tot/6;
printf("average is %d",Avg);
if ((Avg>90)&&(Avg<=100))
printf(" the grade point is 10");
else if((Avg>80)&&(Avg<=90))
printf(" the grade point is 9");
else if((Avg>70)&&(Avg<=80))
printf("the grade point is 8");
else if ((Avg>60)&&(Avg<=70))
printf("the grade point is 7");
else if((Avg>50)&&(Avg<=60))
printf("the grade point is 6");
15 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

else if ((Avg>40) && (Avg<=50))


printf("the grade point is 5");
else
printf ("failed and grade points is 0");
return 0;
}

Output:
Enter the student name:sai
enter the roll number
42
enter six subject marks
90 80 95 75 80
80
average is 83 the grade point is 9

16 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

9.write a c program to print name of given numbers using switch


statements?

Algorithm:

1. Define the Main Function.


2. Take input from the user.
3. use a switch statement to print the name of the number based
on the input.
4. Handle Invalid Input: It's a good practice to handle cases
where the user enters a number outside the expected range. In
this example, we use the default case to print an error
message.
5. Compile and Run: Save the program with a .c
extension ,compile it using a C compiler, and run the executable.
6. This program will take a number as input and print its name
using a switch statement.
7. Exit the program.

Source code:-

#include<stdio.h>
int main()
{
int n;
printf("enter a number:");
scanf("%d",&n);
switch(n)
{
case 1:printf("value of n is one");
break;
case 2:printf("value of n is two");
break;
case 3:printf("value of n is three");
break;
case 4:printf("value of n is four");
break;
case 5:printf("value of n is five");
break;
case 6:printf("value of n is six");
break;
case 7:printf("value of n is seven");
break;
case 8:printf("value of n is eight ");
break;
case 9:printf("value of n is nine");
break;

17 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

case 10:printf("value of n is ten");


break;
default: printf("value of n is others");
}
return 0;
}
Output:

enter a number:8
value of n is eight

18 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

10.write a c program to print your name using while loop?

Algorithm:

1. Declare the main function


2. Declare a character array to store your name: You'll need a character
array (string) to store your name.
3. Initialize a variable for loop control: You should initialize a variable to
control the while loop.
4. Use a while loop to print each character of your name: Use a while loop
to iterate through the characters in your name string and print them one by
one.
5. Print a newline character: To ensure that your name is printed on a new
line
6. End the main function: Finally, end the main function with a return
statement.
7. Exit the program.

Source code:-
#include<stdio.h>
void main()
{
int i=1,n;
printf("enter the numer:");
scanf("%d",&n);
char name[10];
printf("enter the name:");
scanf("%s",&name);

while(i<=n)
{
printf("name is:%s\n",name);
i++;
}

getch();
}

19 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

Output:-
enter the numer:5
enter the name:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW

20 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

11.write a c program to print your name using for loop?

Algorithm:

1. Declare main Function: Declare the main function, which is the entry
point of the program.
2. Use a for Loop: Use a for loop to print each character of your name one by
one.
3. declare an array of characters.
4. The for loop iterates from i = 0 to i < n where n is a number.
5. Increment i++.
6. Compile and Run: Save the program with a .c extension , compile it
using a C compiler, and run the executable.
7. Exit the program..

Source code:-
#include<stdio.h>
void main()
{
int i ,n;
printf("enter the number:");
scanf("%d",&n);
char name[8];
printf("enter the name:");
scanf("%s",&name);
for(i=1;i<=n;i++)
{
printf("name is :%s\n",name);
}
getch();
}
Output:
enter the number:5
enter the name:GVPCEW
name is :GVPCEW
name is :GVPCEW
name is :GVPCEW
name is :GVPCEW
name is :GVPCEW

21 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

22 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

12.write a c program to print your name using do-while loop?

Algorithm:

1. Define the main function.


2. Declare variables: Declare any variables you will need.
3. Write the do-while loop: Use a do-while loop to print your name. The loop will
run at least once.
4. use printf to print your name.
5. Compile and run.
6. Exit the program.

Source code:-
#include<stdio.h>
void main()
{
int i=1,n;
printf("enter the number:");
scanf("%d",&n);
char name[8];
printf("enter the name:");
scanf("%s",&name);
do
{
printf("name is:%s\n",name);
i++;
}while(i<=n);
getch();
}

23 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

Output:
enter the number:10
enter the name:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW
name is:GVPCEW

24 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

13.write a c program to print numbers using while loop using


break?

Algorithm:

1.Define the main function.

2. Declare the variables.

3. use while loop.

4. The while (1) creates an infinite loop, and we will use the break statement to exit the
loop when necessary.

5. Inside the loop, print the value of num

6.Add a conditional statement to check whether you should break out of the loop.

7.Exit the program.

Source code:-
#include<stdio.h>
void main()
{
int i=1;
while(i<=10)
{
if(i==6)
break;
printf("%d\n",i);
i++;
}
getch();
}
Output:
1
2
3
4
5

25 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

14.write a c program to print numbers using for loop using


continue?

Algorithm:

1.Define the main function.


2.Declare any required variables.
3.Prompt the user to enter the desired range of numbers and store the input in the range
variable.
4.Use a for loop to iterate from 1 to the specified range (i should start from 1 and go up to
range).
5.use the continue statement to skip the current iteration and proceed to the next iteration.
6.Exit the program.

Source code:-
#include<stdio.h>
void main()
{
int i=1;
for(i=1;i<=10;i++)
{
if(i==5)
continue;
printf("%d\n",i);
}
getch();
}

26 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

Output:
1
2
3
4
6
7
8
9
10

27 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

15.write a c program which is menu trivial program to compute


area of various geometrical shapes?

Algorithm:

1.Define the main function.

2. Declare global constants and variables for menu options and user input.

3. Define functions to calculate the area of each shape.

4. Implement the main menu function to display options to the user.

5.Use switch statement to calculate area of required shape.

6.Exit the program.

Source code:-
#include <stdio.h>
void main()
{
int ch, ba, h, l, b, a, x, t, rec, squ, dr, r, cir;
float pi = 3.14;
printf("the menu of various geometrical shapes: \n");
printf("1. area of triangle\n");
printf(" 2. area of rectangle\n");
printf(" 3. area of square\n");
printf("4. area of circle\n");
printf("\n enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("enter values of ba and h:");
scanf("%d%d",&ba,&h);
t=0.5*ba*h;
printf("area of triangle is %d\n",t);
break;
case 2:printf("enter values of I and b: ");
scanf("%d%d",&l,&h);
rec = l*b;
printf ("area of rectangle is %d\n", rec);
break;
case 3:printf("enter value of a:");
scanf("%d",&a);
squ=a*a;
printf("area of squase is %d\n", squ);

28 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

break;
case 4:printf("enter value of r:");
scanf("%d",&r);
cir=pi*r*r;
printf("area of circle is %d\n", cir);
default:printf("invalid shape");
}
getch();
}
Output:
the menu of various geometrical shapes:
1. area of triangle
2. area of rectangle
3. area of square
4. area of circle
enter your choice:1
enter values of ba and h:4 6
area of triangle is 12

29 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

16.write a c program to calculate factorial of a given number?

Algorithm:

1.Define the main function.

2. Declare Variables: Declare variables to store the input number and the result
(factorial).

3. Use printf to prompt the user to enter the number and scanf to read the input.

4. Initialize the factorial variable to 1.

5. Use a loop (for or while) to calculate the factorial of the input number. Multiply
factorial by the current value of num in each iteration and decrement num until it reaches
1.

6.Print the result and exit the program.

Source code:-
#include<stdio.h>
int main()
{
int i,sum=1,n;
printf("Enter a number: ");
scanf("%d",&n);
for(i=2;i<=n;i++)
{
sum=sum*i;
}
printf("Factorial of %d is: %d",n,sum);
return 0;
}
Output:
Enter a number: 5
Factorial of 5 is: 120

30 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

17.write a c program to display n terms of even natural numbers


and their sum?

Algorithm:

1.Define the main function.

2. Declare variables to store user input, calculate the sum, and control the loop.
3.Prompt the user to enter the value of 'n.'
4.Read the value of 'n' from the user.
5.Initialize a variable to keep track of the current even number and set it to 2 (the first
even natural number).
6.Initialize a variable to keep track of the sum and set it to 0.
7.Use a loop to generate and display the even natural numbers and update the sum until 'n'
terms are displayed.
8.Display each even number as it is generated.
9.Update the sum by adding the current even number to it.
10.Increment the current even number by 2 to move to the next even natural number.
11.Repeat steps 8-10 'n' times.
12.Display the sum of the 'n' even natural numbers.
13.End the program.

Source code:-
#include<stdio.h>
void main()
{
int i,n,sum=0;
printf("Input number of terms : ");
scanf("%d",&n);
printf("\n The even numbers are :");
for(i=1;i<=n;i++)
{
printf("%d ",2*i);
sum+=2*i;
}
printf("\nThe Sum of even Natural Number upto %d terms : %d\n",n,sum);
}

31 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

Output:

Input number of terms:5


The even numbers are :2 4 6 8 10
The Sum of even Natural Number upto 5 terms:30

32 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

18.write a c program to display n terms in harmonic series and


their sum ?1+1/2+1/3+…+1/n

Algorithm:

1.Define the main function.

2. Declare variables:
 Declare variables to store the number of terms (n), the harmonic sum (sum), and a
counter for the loop (i).
3.Prompt the user for the number of terms (n):
 Display a message asking the user to input the number of terms (n).
4.Read the input for the number of terms (n):
 Use scanf to read the input for the number of terms (n).
5.Initialize the sum of the harmonic series (sum):
 Initialize the sum variable to 0.
6.Iterate from 1 to n:
 Use a loop to iterate from 1 to n.
7.Calculate the harmonic term (1/i):
 Calculate the harmonic term for the current iteration (1/i).
8.Add the harmonic term to the sum:
 Add the harmonic term to the sum variable.
9.Display the harmonic term for the current iteration:
 Display the harmonic term for the current iteration.
10.Display the current value of the sum:
 Display the current value of the sum.
11.Display the total sum of the harmonic series:
 Display the total sum of the harmonic series.
12.End the program

Source code:-
#include<stdio.h>
void main()
{
int i,n;
float s=0.0;
printf("Input the number of terms : ");
scanf("%d",&n);
printf("\n\n");
for(i=1;i<=n;i++)
{
if(i<n)
{

33 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

printf("1/%d + ",i);
s+=1/(float)i;
}
if(i==n)
{
printf("1/%d ",i);
s+=1/(float)i;
}
}
printf("\n Sum of Series upto %d terms : %f\n",n,s);
}
Output:
Input the number of terms : 5

1/1 + 1/2 + 1/3 + 1/4 + 1/5

Sum of Series upto 5 terms : 2.283334

34 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

19.write a c program to check whether the given number is an


Armstrong or not?

Algorithm:

1..Declare the main function.


2.We take an integer input from the user.
3.We calculate the number of digits in the input number by repeatedly dividing it by 10.

4.We store the original input number in originalNum so that we can compare the result
later.

5.We then calculate the sum of each digit raised to the power of n, where n is the number
of digits.

6.Finally, we compare the result with the original number to determine whether it's an
Armstrong number or not.

7.Exit the program.

Source code:-

#include <stdio.h>
void main()
{
int n,r,sum=0,temp;
printf("Input a number: ");
scanf("%d",&n);
for(temp=n;n!=0;n=n/10)
{
r=n % 10;
sum=sum+(r*r*r);
}
if(sum==temp)
printf("%d is an Armstrong number.\n",temp);
else
printf("%d is not an Armstrong number.\n",temp);
}

35 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

Output:
Input a number: 153
153 is an Armstrong number.

36 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

20.write a c program to compare two strings without using string


library functions?

Algorithm:

1. Prompt for Input:


 Ask the user to input two strings to be compared.
2. Read Input Strings:
 Read and store the input strings.
3. Initialize Variables:
 Initialize two index variables (e.g., i and j) to 0 to iterate through the characters of
the input strings.
4. Iterate Through Characters:
 Start a loop to iterate through each character of both strings.
 Compare the characters at the current indices i and j.
5. Comparison Logic:
 If the characters are equal, increment both indices i and j.
 If the characters are not equal, break the loop and set a flag indicating inequality.
6. Check Comparison Result:
 After the loop, check the flag to determine if the strings are equal or not.
7. Display Result:
 Display the comparison result based on the flag.

Source code:-
#include <stdio.h>
void main()
{
char str1[20],str2[20];
int i;
printf("enter two strings: \n");
gets(str1);
gets(str2);
i=0;
while(str1[i]=str2[i] && str1[i]!=0)
i++;
if (str1[i]>str2[i])
printf("str1>str2");
else if (str1[i] <str2[i])
printf ("str1 < str2");
else
printf ("str1 = str2");

37 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

getch();
}
Output:-
enter two strings:

GVPCEW

GVPCEW

str1 = str2

38 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

21)WRITE A C PROGRAM TO ILLUSTRATE ALL STRING HANDLING FUNCTION?

Algorithm:

1. Declare a character array (string) to store the input string and initialize it.

2. Display a menu to the user with options for different string handling functions, such as:

a. Length of the string

b. Copying a string

c. Concatenating two strings

d. Comparing two strings

e. Searching for a substring

f. Reversing a string

3. Read the user's choice.

4. Based on the user's choice, perform the corresponding string handling function using
standard C library functions like strlen, strcpy, strcat, strcmp, strstr, and a custom function
for reversing the string.

5. Display the result of the chosen operation.

6. Ask the user if they want to perform another operation or exit the program.

7. Repeat steps 3-6 until the user chooses to exit.

8. End the program.

Source code:
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main()
{
char x[10],y[10],z[10];
printf("enter the strings: \n");
scanf("%s%s",&x,&y);
printf("string length is %d\n",strlen(x));
printf("string comparing %d\n",strcmp(x,y));
printf("copy string is %s\n",strcpy (z,x));

39 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

printf("string cat is %s\n",strcat (x,y));


printf("string reverse is %s\n",strrev(y));
printf("string is %s\n",strstr(x,y));
getch();
}
Output: -
enter the String: ab cd
String length is +2
string comparing -1.
Copy string is ab
String cat is abcd
String reverse is dc.
string is abcd

40 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

22)write a c program to print individual character string in reverse


order?

Algorithm:

1.Declare a character array (string) to store the input string.

2.Read the input string from the user and store it in the character array.

3.Calculate the length of the string using the strlen function. Let's call this length x.

4.Create a loop that iterates from x - 1 down to 0 (inclusive).

5.Inside the loop, print the character at the current index of the string.

6.Repeat this process for each character in reverse order.

7.End the program.

Source code:
#include<stdio.h>
#include<string.h>
void main()
{
char x[10];
int i;
printf("enter the string :\n");
scanf("%s",&x);
printf("string is %s",strrev(x));
for (i=0;i<=6;i++)
{
printf("%5c",x[i]);
}
}
Output:
Enter the string:
Gvpcew
String is w c e p v g

41 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

23)write a c program to print all unique numbers in an array?

Algorithm:

1.Declare an integer array to store the numbers.

2.Initialize variables to keep track of the array size and a flag to identify unique numbers.

3.Read the size of the array from the user.

4.Read the elements of the array from the user and store them in the array.

5.Create a nested loop to compare each element with the rest of the elements in the array.

6.For each element, set the unique flag to true initially.

7.Compare the current element with all other elements in the array.

8.If a match is found (excluding the element itself), set the unique flag to false.

9.After comparing the current element with all others, if the unique flag is still true, print
the element as a unique number.

10.Repeat steps 6-9 for all elements in the array.

11.Finish the program.

Source code:
#include <stdio.h>
#include <string.h>
void main()
{
int arr[100],n,i,j,ctr=0,k;
printf("enter size of assay: ");
scanf ("%d",&n);
printf("Input elements in array is:\n");
for(i=0;i<n;i++)
{
printf ("elements %d:",i);
scanf("%d",&arr[i]);
}
printf("In the unique elements in array are:\n");
for(i=0;i<n;i++)
{
ctr=0;
k=n;
for(j=0;j<k+1;j++)
{
if(i!=j)
{
42 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

if(arr[i]==arr[j])
{
ctr++;
}
}
}
if(ctr==0)
{
printf("%d\t",arr[i]);
}
}
}
Output:
enter size of assay: 5
Input elements in array is:
elements 0:1
elements 1:5
elements 2:9
elements 3:3
elements 4:3
In the unique elements in array are:
1 5 9

43 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

24)write a c program to separate odd and even integers in separate


arrays?
Algorithm:

1.Declare an integer array to store the numbers.

2.Initialize variables to keep track of the array size and a flag to identify unique numbers.

3.Read the size of the array from the user.

4.Read the elements of the array from the user and store them in the array.

5.Create a nested loop to compare each element with the rest of the elements in the array.

6.For each element, set the unique flag to true initially.

7.Compare the current element with all other elements in the array.

8.If a match is found (excluding the element itself), set the unique flag to false.

9.After comparing the current element with all others, if the unique flag is still true, print
the element as a unique number.

10.Repeat steps 6-9 for all elements in the array.

11.Finish the program.

Source code:
#include <stdio.h>
#include <conio.h>
void main()
{
int a[20],o[10],e[10],i,j=0,k=0,n;
printf(" enter the number : \n");
scanf("%d",&n) ;
for(i=0;i<=n;i++)
{
printf(" a[%d]", i);
scanf("%d",&a[i]);
}
for(i=0; i<=n;i++)
{
if(a[i]%2==0)
{
e[j] = a[i];
j++;
}
else
{

44 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

o[k] = a[i];
k++;
}
}
printf("even and odd are:");
for(i=0;i<=j;i++)
{
printf("%5d\n",e[i]);
}
for(i=0;i<=k;i++)
{
printf("%5d",o[i]);
}
getch();
}
Output:
enter the number: 5
a[0]=1
a[i]=2
a[2]=3
a[3]=3
a[4]=4
a[5]=5
even and odd are:
246
135

45 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

25)write a c program to sort array in descending order?

Algorithm:

1.Start with an unsorted array.

2.Initialize a variable n to store the number of elements in the array.

3.Loop through the array using a nested loop:

a. The outer loop runs from i = 0 to n-1.

b. The inner loop runs from j = 0 to n-i-1.

3.Inside the inner loop, compare array[j] and array[j+1].

a. If array[j] is less than array[j+1], swap them.

4.You can use a temporary variable to perform the swap.

5.After completing each pass of the inner loop, the largest element in the unsorted portion
will "bubble up" to the end of the array.

6.Repeat steps 3-5 for a total of n-1 passes through the array.

7.The array will now be sorted in descending order

Source code:
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],i,n,temp,j;
printf("enter the number:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("a[%d]=",i );
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}
46 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

}
printf("\n");
}
for(i=0;i<n;i++)
{
printf("%4d",a[i]);
}
getch();
}
Output:
enter the number:
5
a[0]=8
a[1]=0
a[2]=3
a[3]=7
a[4]=2
0 2 3 7 8

47 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

26)write a c program to find transpose of a matrix?

Algorithm:

1.Start with a given matrix, which is typically represented as a two-dimensional array.

2.Initialize variables for the number of rows (say rows) and the number of columns (say
columns) in the matrix.

3.Create a new matrix to store the transpose. This new matrix will have dimensions
columns x rows because the rows of the original matrix become columns in the transpose,
and vice versa.

4.Use nested loops to iterate through the elements of the original matrix.

a. The outer loop iterates over rows, from i = 0 to i < rows.

b. The inner loop iterates over columns, from j = 0 to j < columns.

5.Assign the value of matrix[i][j] to transpose[j][i]. In other words, swap the row and
column indices when copying values to the transpose matrix.

6.After completing the loops, the transpose matrix will contain the transpose of the
original matrix.

Source code:
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10][10],b[10][10],r,c,i,j;
printf("enter the rows and columns of matrix: \n");
scanf("%d%d",&r,&c);
printf("enter the matrix:\n");
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
printf("a[%d][%d]=",i,j);
scanf("%d%d",&a[i][j]);
}
}
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
b[j][i] = a[i][j] ;
}
}
48 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

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


{
for(j=0; j<r; j++)
{
printf("%d",b[i][j]);
}
}
getch();
}
Output:
enter size of rows and columns:2 3
enter the matrix:
a[0][0]=1
a[0][1]=2
a[0][2]=3
a[1][0]=4
a[1][1]=5
a[1][2]=6
14
25
36

49 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

27)write a c program to print the matrix multiplication of two


square matrices?

Algorithm:

1.Define a constant for the size of the matrices (assuming square matrices)

2.Declare the matrices you want to multiply, along with the result matrix

3.Initialize or populate matrixA and matrixB with values

4.Use nested loops to perform the matrix multiplication and store the result in the result
matrix

5.Use another set of nested loops to print the resulting matrix (result)

6.Wrap everything in the main function

7.end the program.

Source code:
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,r1,c1,c2,r2;
printf("enter the rows and Columns:");
scanf("%d%d%d%d",&r1,&r2,&c1,&c2 );
for(i=0; i<r1; i++)
{
for(j=0;j<c1;j++)
{
printf("a[%d][%d]",i,j);
scanf("%d",&a[i][j]);
}
}
for (i=0;i<r2; i++)
{
for(j=0; j<c2; j++)
{

50 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

printf("b[%d][%d]",i,j);
scanf("%d",&b[i][j]);
}
}
if(c1==r2)
{
for(i=0;i<r1; i++)
{
for(j=0; j<c2; j++)
{
c[i][j]=0;
for(k=0; k<r1; k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%5d",c[i][j]);
}
printf("\n");
}
}
else
{
printf("not possible\n");
}
getch();
}
Output:
Enter the rows and columns:2 2
2 2
a[0][0]=1

51 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

a[0][1]=2
a[1][0]=3
a[1][1]=4
b[0][0]=4
b[0][1]=3
b[1][0]=2
b[1][1]=1
8 6
20 13

52 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

28)write a c program to find addition of square matrices?

Algorithm:

1.Declare and initialize variables:

2.Define constants for the size of the matrices (e.g., N for the number of rows and
columns).

3.Declare two 2D arrays to store the matrices, e.g., matrixA[N][N] and matrixB[N][N].

4.Declare another 2D array to store the result, e.g., result[N][N].

5.Use nested loops to input values for matrixA and matrixB from the user or through
some other means. Use two loops to iterate through rows and columns.

6.Use nested loops to iterate through each element of the matrices (rows and columns).

7.For each element (i, j) in the result matrix, calculate result[i][j] = matrixA[i][j] +
matrixB[i][j].

8.End the program.

Source code:
#include <stdio.h>
#include <Conio.h>
void main()
{
int a[5][5],b[5][5],x[5][5],i,j,r,c;
printf("enter rows and columns: \n");
scanf("%d%d",&r,&c);
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
printf("a[%d][%d]",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0; i<r; i++)
{
for(j=0;j<c;j++)
53 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

{
printf("b[%d][%d]",i,j);
scanf("%d",&b[i][j]);
}
}
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
x[i][j]=a[i][j]+b[i][j];
}
}
for(i=0; i<c; i++)
{
for(j=0;j<r;j++)
{
printf("%5d",x[i][j]);
}
printf("\n");
}
getch();
}
Output:
enter rows and columns:
3 3
a[0][0] = 2
a[0][1] = 3
a[0][3]=4
a[1][0] = 5
a[1][1] = 6
a [1][2] = 7
a[2][0]=3
a[2][1]=6
a[2][2] = 8
b[0][0] =9
b[0][1] = 7

54 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

b[0][2] = 5
b[1][0] = 2
b[1] [1] = 0
b[1][2] = 8
b[2][0] = 4
b[2][1] = 5
b[2][2] = 8
11 10 9
7 6 15
7 11 16

55 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

29)write a c program to check whether given number is prime


number or not using function?

Algorithm:

1.Declare a function prototype for your prime-checking function.

2.Inside the main function, declare a variable to store the user input (the number to be
checked for primality).

3.Prompt the user to enter the number and read the input.

4.Call the prime-checking function with the user's input as an argument.

5.Inside the prime-checking function:

a. Check if the input number is less than or equal to 1. If it is, return false (not prime).

b. Iterate from 2 to the square root of the input number.

c. For each iteration, check if the input number is divisible by the current iteration value.
If it is, return false (not prime).

d. If no divisors are found, return true (prime).

6.Back in the main function, based on the return value of the prime-checking function,
display whether the number is prime or not

7.End the program.

Source code:
#include <stdio.h>
#include <conio.h>
int prime (int n)
{
int i;
for(i=2; i<= n/2; i++)
{
if(n%i==0)
{
return 0;
}
return 1;
}
}
int prime(int);
void main()
56 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

{
int num, ret;
printf("enter the number "\n");
scanf("%d", &num);
ret=prime(num);
if (ret ==0)
{
printf("Not prime\n");
}
else
{
printf(“prime\n”);
}
getch();
}
Output:
Enter the number: 3
Prime number

57 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

30)write a c program to get largest number of an array using


function?

Algorithm:

1.Declare Function Prototype:

2.Declare a function prototype for the function that will find the largest number.

3.Define the Main Function:

a. Define the main function where you'll declare the array and perform input and output
operations.

4.Declare and Initialize the Array:

a. Declare an integer array and initialize it with the desired values.

5.Call the Function:

a. Call the findLargest function, passing the array and its size as arguments. Assign the
result to a variable to store the largest number.

6.Write the findLargest Function:

a. Define the findLargest function below the main function. This function should accept
an integer array and its size as parameters. Inside this function, use a loop to iterate
through the array elements and keep track of the largest number found so far.

7.Return the Largest Number:

8.After finding the largest number inside the findLargest function, return it to the main
function

9.End the program.

Source code:
#include <stdio.h>
#include <conio.h>
int findlargest(int b[], int n )
{
int i,l=b[0];
for(i=0; i<n; i++)
{
if(l>b[i])
{
l=b[i];
}
}
58 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

return l;
}
int main()
{
int j,b[10],n,largest;
printf("enter the size of array: \n");
scanf("%d",&n);
for(j=0;j<n; j++)
{
printf("enter the element:\n");
scanf("%d",&b[j]);
}
largest= findlargest(b,n);
printf("The largest number is %d", largest);
return 0;
}
Output:
Enter the size of array:
3
Enter the elements:
2
8
6
Largest element is 8

59 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

31)write a c program to add the two numbers using call by value?

Algorithm:

1.Declare a function prototype for the addition function. This is necessary because you're
using a function before defining it.

2.Declare two variables.

3.add the two variables using and return the result to main function.

4.Define the main function.

5.Define the add function. This function takes two integer parameters and returns the sum
of the two numbers.

6.End the program.

Source code:
#include <stdio.h>
#include <conio.h>
int add(int n1, int n2)
{
return n1+n2;
}
int add(int,int);
void main()
{
int a,b,res;
printf("enter the number :\n");
scanf("%d%d",&a,&b);
res=add(a,b);
printf("%d",res);
getch();
}
Output:
Enter the number:6 5
Sum of the numbers is:11

60 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

32)write a c program to swap two elements using call by reference?

Algorithm:

1.Declare a Function

2.Declare a function that will perform the swap operation. The function should take two
integer pointers as parameters to allow call by reference.

3.Define the Swap Function:

4.Inside the function:

5.Declare a temporary variable to store one of the elements.

6.Use pointers to swap the values of the two elements.

7.In the Main Function:

8.Declare two integer variables to store the elements you want to swap.

9.Prompt the user to input these elements and read them into the variables.

10.Call the Swap Function: Call the swap function, passing the addresses of the two
variables as arguments.

11.Print the Swapped Elements: In the main function, after the swap function is called,
print the values of the two variables to verify that they have been swapped.

12.End the program.

Source code:
#include <stdio.h>
#include <conio.h>
int swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int n1,n2, result;

61 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

printf("enter the numbers: \n");


scanf("%d%d",&n1,&n2);
printf(" before swapping is %d %d\n", n1,n2);
result =swap(&n1,&n2);
printf("after swapping is %d %d\n",n1,n2);
getch();
}
Output:
Enter the numbers: 6 7
Before swapping:6 7
After swapping:7 6

62 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

33)write a c program to find the factorial of given number is


recursive function?

Algorithm:

1.Define the recursive function to calculate the factorial. The function should take an
integer as its argument and return an integer.

2.In the function, check for the base case:

3.If the input number is 0, return 1. (0! = 1)

4.If the input number is not 0, calculate the factorial recursively by calling the function
with the argument reduced by 1 and multiply it by the current number.

5.In the main() function:

a. Declare a variable to store the input number.

6.Prompt the user to enter a number and store it in the variable.

7.Call the recursive factorial function with the input number as an argument and store the
result in another variable.

8.Print the result to the console.

9.End the program.

Source code:

#include <stdio.h>
#include <conio.h>
int fact(int n)
{
if(n==1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
63 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

void main()
{
int n=5,retvalue;
retvalue=fact(n);
printf("factorial is %d\n",retvalue);
getch();
}
Output:
Factorial is 120

64 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

34)write a c program to store user information using dynamic


memory allocation?

Algorithm:

1.Define a structure to hold user information

2.Declare variables and a pointer for dynamic memory allocation

3.Prompt the user for the number of users and allocate memory accordingly

4.Loop to input user information

5.Display the stored user information

6.Release the dynamically allocated memory

7.End the program.

Source code:
#include <stdio.h>
#include <stdlib.h >
struct user
{
int roll;
char name[30];
int rank;
};
int main()
{
struct user *ptr;
int n,i;
printf("enter the number:\n");
scanf("%d",&n);
ptr=(struct user*)malloc(n*sizeof(struct user));
for (i=0;i<n;i++)
{
printf("enter the roll,name,rank:\n");
scanf("%s%d%d",(ptr+i)->name,&(ptr+i)->roll,&(ptr+i)->rank);
}
for(i=0;i<n;i++)
{
printf("name is %s\n roll number is %d\n rank is %d\n",(ptr+i)->name,
(ptr+i)->roll, (ptr+i)->rank);
}
return 0;
}
Output:
enter the number:2
Enter name,roll, rank:
sai
65 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

2
60
enter name, you, rank:
Ram
3
70
name is sai
roll number is 2
rank is 60
name is ram 2
roll number is 3
Rank is 70

66 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

35)write a c program to demonstrate how to handle the pointers in


program and also usage of & and * operator ?

Algorithm:

1.Define Variables: Start by defining the variables you'll be using in your program.
Include a variable of a specific data type (e.g., int) and a pointer variable of the same
type.

2.Initialize Variables: Assign values to your variables. This will help demonstrate how
pointers work.

3.Declare a Pointer: Declare a pointer variable using the same data type as the variable it
will point to.

4.Assign the Address: Use the & operator to assign the memory address of the variable to
the pointer.

5.Access the Value through Pointer: Use the * operator to access the value stored at the
memory location pointed to by the pointer.

6.Modify Value through Pointer: Change the value using the pointer.

7.Print Results: Print out the values of both the original variable and the variable accessed
through the pointer to demonstrate that they've changed.

8.End Program.

Source code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *ptr,a=10;
int **p2;
ptr=&a;
p2=&ptr;
printf("value of &a is %x\n", &a);
printf( "value of Ptr is %x\n", ptr);
printf(" value of &ptr is %x\n", &ptr);
printf(" Value of *ptr is %d\n", *ptr);
printf(" Value of *P2 is %d\n", *p2);

67 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

printf("value of p2 is %x\n", p2);


printf("value of &P2 is %x\n", &p2);
printf("value of **p2 is %d\n", **p2);
getch();
}
output-
value of &a is 62fe14
value of Ptr is 62fe14
value of &ptr is 62fe18
Value of *ptr is 10
Value of *P2 is 6487572
value of p2 is 62fe18
value of *p2 is 62fe08
Value of **pa is 10

68 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

36)write a c program to find the largest element using dynamic


memory allocation?

Algorithm:

1.Declare the variables and pointer

2.Allocate memory dynamically for an array to store elements.

3.Read the elements into the dynamically allocated array.

4.Traverse the array to find the largest element.

5.Print the largest element.

6.End the program.

Source code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i;
double *data;
printf("Enter the total number of elements: ");
scanf("%d", &n);
// Allocating memory for n elements
data = (double *)calloc(n,sizeof(double));
if(data == NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}
// Storing numbers entered by the user.
for(i = 0; i < n; ++i)
{
printf("Enter number%d: ", i + 1);
scanf("%lf", data + i);
}

69 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

// Finding the largest number


for (i = 1; i < n; ++i)
{
if (*data < *(data + i))
{
*data = *(data + i);
}
}
printf("Largest number = %.2lf", *data);
free(data);
return 0;
}
Output:
Enter the total number of elements: 5
Enter number1: 2
Enter number2: 1
Enter number3: 45
Enter number4: 60
Enter number5: 82
Largest number = 82.00

70 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

37)write a c program to find sum of two numbers using dynamic


memory location?

Algorithm:

1.Declare variables to store the two numbers and the sum:

2.Allocate memory for num1, num2, and sum using the malloc function

3.Check if memory allocation was successful. If not, exit the program

4.Prompt the user to enter the two numbers:

5.Calculate the sum of the two numbers

6.end the program.

Source code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,*ptr,sum = 0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum+=*(ptr + i);
}
printf("Sum = %d",sum);
free(ptr);
return 0;
}
71 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

Output:
Enter number of elements: 3
Enter elements: 8 10 2
Sum = 20

72 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

38)write a c program to display contents of file?

Algorithm:

1.Declare variables to hold file pointers and other necessary variables.

2.Ask the user to enter the name of the file they want to display.

3.Open the specified file in read mode. Check if the file exists and can be opened
successfully.

4.Use a loop to read and display the contents of the file character by character until the
end of the file is reached.

5.Close the file when done to free up system resources.

6.End the program.

Source code:
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char c;
char fname[30];
printf("enter the file name:");
scanf("%s",fname);
fptr=fopen(fname,"r");
if(fptr==NULL)
{
printf("no such file");
}
printf("\n contents of the file are:\n");
while((c=fgetc(fptr))!=EOF)
{
printf("%c",c);
}
fclose(fptr);
}

73 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

Output:
enter the file name:file.txt
contents of the file are: #include <stdio.h>
int main()
{
printf(“hello world\n”);
}

74 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

39)write a c program to copy one file to another?

Algorithm:

1.Declare File Pointers: Declare two file pointers to represent the source and destination
files.

2.Open Source File: Use fopen() to open the source file in read mode ("rb" for binary files
or "r" for text files)

3.Open Destination File: Use fopen() to open the destination file in write mode ("wb" for
binary files or "w" for text files)

4.Copy Data: Use a loop to read data from the source file and write it to the destination
file until the end of the source file is reached. You can use fread() to read data and
fwrite() to write data.

5.Close Files: After copying is complete, close both the source and destination files using
fclose()

6.End the program.

Source code:
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp1,*fp2;
char c;
char fname1[30],fname2[30];
printf("enter the source file:");
scanf("%s",fname1);
fp1=fopen(fname1,"r");
if(fp1==NULL)
{
printf("no such file");
exit(0);
}
printf("enter destination file:");
scanf("%s",fname2);
fp2=fopen(fname2,"w");
if(fp2==NULL)
{
printf("unable to create file");
exit(0);
}
while((c=fgetc(fp1))!=EOF)
{
fputc(c,fp2);
75 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

fclose(fp1);
fclose(fp2);
}
fp2=fopen(fname2,"r");
while((c=fgetc(fp2))!=EOF)
{
printf("%c",c);
}
getch();
}
Output:
enter the source file:file.txt
enter destination file:sample.txt
#include <stdio.h>
int main()
{
printf(“hello world\n”);
}

76 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

40)write a c program to append one file to another file?

Algorithm:

1.Declare two FILE pointers, one for the source file (the file to be appended) and one for
the destination file (the file where data will be appended).

2.Use fopen to open the source file in read mode ("r").

3.Use fopen to open the destination file in append mode ("a").

4.Use a loop to read data from the source file using functions like fread or fgets. Write the
read data into the destination file using functions like fwrite or fputs.

5.After the copying process is complete, close both the source and destination files using
fclose.

6.Properly close all files and free any allocated resources.

7.End the program.

Source code:
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp1,*fp2;
char c;
char fname1[30],fname2[30];
printf("enter the source file:");
scanf("%s",fname1);
fp1=fopen(fname1,"r");
if(fp1==NULL)
{
printf("no such file");
exit(0);
}
printf("enter destination file:");
scanf("%s",fname2);
fp2=fopen(fname2,"a");
if(fp2==NULL)
{
printf("unable to create file");
exit(0);
}
while((c=fgetc(fp1))!=EOF)
{
fputc(c,fp2);
fclose(fp1);

77 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

fclose(fp2);
}
fp2=fopen(fname2,"r");
while((c=fgetc(fp2))!=EOF)
{
printf("%c",c);
}
getch();
}
Output:
enter the source file:file.txt
enter destination file:sample.txt
#include <stdio.h>
int main()
{
printf(“hello world\n”);
}
#include <stdio.h>
int main()
{
printf(“hello world\n”); }

78 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

41)write a c program using e-num?

Algorithm:

1.Define your enum at the top of your program

2.Declare variables of the enum type

3.Assign values to the enum variables

4.You can use the enum variables in your program logic.

5.End the program.

Source code:
#include<stdio.h>
#include<conio.h>
void main()
{
enum week{mon,tue,wed,thu,fri,sat,sun};
enum weekday;
day=thu;
printf(“Thursday number is “%d”,day );
getch();
}
Output :
Number is 3

79 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

42)write a c program to write to a binary file using fwrite?

Algorithm:

1.Declare any variables you'll need, such as file pointers and data to be written.

2.Open the binary file in write mode.

3.Verify that the file was opened successfully.

4.Use fwrite to write data to the file.

5.Close the file when you're done writing.

6.End the program.

Source code:
#include<stdio.h>
#include<conio.h>
struct threeNum
{
int n1,n2,n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if((fptr=fopen("c","wb"))==NULL)
{
printf("error!opening file");
}
for(n=1;n<5;++n)
{
num.n1=n;
num.n2=5*n;
num.n3=5*n+1;
fwrite(&num,sizeof(struct threeNum),1,fptr);
}
fclose(fptr);
if((fptr=fopen("c:","rb"))==NULL)
{
printf("error ! opening file");
}
for(n=1;n<5;++n)
{
fread(&num,sizeof(struct threeNum),1,fptr);
printf("n1:%d\tn2:%d\tn3:%d\n",num.n1,num.n2,num.n3);
}

80 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

return 0;
}
Output:
n1:4 n2:20 n3:21
n1:4 n2:20 n3:21
n1:4 n2:20 n3:21
n1:4 n2:20 n3:21

81 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

43)write a c program using typedef with structures/unions?

Algorithm:

1.Begin by defining your structure or union using the struct or union keyword.

2.Use the typedef keyword to create an alias for your structure or union.

3.Declare variables of the newly created type.

4.Initialize the structure or union variables with values.

5.print the data required.

5.End the program.

Source code:
#include<stdio.h>
#include<string.h>
typedef union students
{
char name[20];
char branch[20];
int ID _ no;
}students;
int main()
{
student st ;
strcpy (st.name, “GVPCEW”);
printf ( “NAME is %s” , st.name);
strcpy ( st . branch, “CSE”);
printf (“branch is %s”, st.branch );
st.ID _ no=100;
printf (“ID_no:%d\n”,st.ID_no);
return 0;
}

82 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

Output:
Name is GVPCEW
branch is CSE
ID _ no is 100

83 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

44) Write a c program to implement the Bisection method for


finding the real root of a nonlinear equation

Bisection Method is one of the simplest, reliable, easy to implement and convergence
guaranteed method for finding real root of non-linear equations. It is also known as
Binary Search or Half Interval or Bolzano Method.
Bisection method is bracketing method and starts with two initial guesses say x0 and x1
such that x0 and x1 brackets the root i.e. f(x0)f(x1)< 0
Bisection method is based on the fact that if f(x) is real and continuous function, and for
two initial guesses x0 and x1 brackets the root such that: f(x0)f(x1) < 0 then there exists
atleast one root between x0 and x1.
Root is obtained in Bisection method by successive halving the interval i.e. If x0 and x1
are two guesses then we compute new approximated root as:
x2 = (x0 + x1)/2
Now we have following three different cases:
1. If f(x2)=0 then the root is x2.
2. If f(x0)f(x2)< 0 then root lies between x0 and x2.
3. If f(x0)f(x2)> 0 then root lies between x1 and x2.
And then process is repeated until we find the root within desired accuracy.
Bisection Method Algorithm (Step Wise)
1. start
2. Define function f(x)
3. Choose initial guesses x0 and x1 such that f(x0)f(x1) < 0
4. Choose pre-specified tolerable error e.
5. Calculate new approximated root as x2 = (x0 + x1)/2
6. Calculate f(x0)f(x2)
a. if f(x0)f(x2) < 0 then x0 = x0 and x1 = x2
b. if f(x0)f(x2) > 0 then x0 = x2 and x1 = x1
c. if f(x0)f(x2) = 0 then goto (8)
7. if |f(x2)| > e then goto (5) otherwise goto (8)
8. Display x2 as root.
9. Stop

C Source code: Bisection Method


/* Header Files */
#include<stdio.h>
#include<conio.h>
#include<math.h>
84 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

/*
Defining equation to be solved. Change this equation to solve another problem. */
#define f(x) cos(x) - x * exp(x)
void main()
{
float x0, x1, x2, f0, f1, f2, e;
int step = 1;
clrscr();
/* Inputs */
up:
printf("\nEnter two initial guesses:\n");
scanf("%f%f", &x0, &x1);
printf("Enter tolerable error:\n");
scanf("%f", &e);
/* Calculating Functional Value */
f0 = f(x0);
f1 = f(x1);
/* Checking whether given guesses brackets the root or not. */
if( f0 * f1 > 0.0)
{
printf("Incorrect Initial Guesses.\n");
goto up;
}
/* Implementing Bisection Method */
printf("\nStep\t\tx0\t\tx1\t\tx2\t\tf(x2)\n");
do
{
x2 = (x0 + x1)/2;
f2 = f(x2);

printf("%d\t\t%f\t%f\t%f\t%f\n",step, x0, x1, x2, f2);

if( f0 * f2 < 0)
{
x1 = x2;
f1 = f2;

85 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

}
else
{
x0 = x2;
f0 = f2;
}
step = step + 1;
}while(fabs(f2)>e);
printf("\nRoot is: %f", x2);
getch();
}
Output
Enter two initial guesses:
0
1
Enter tolerable error:
0.0001
Step x0 x1 x2 f(x2)
1 0.000000 1.000000 0.500000 0.053222
2 0.500000 1.000000 0.750000 -0.856061
3 0.500000 0.750000 0.625000 -0.356691
4 0.500000 0.625000 0.562500 -0.141294
5 0.500000 0.562500 0.531250 -0.041512
6 0.500000 0.531250 0.515625 0.006475
7 0.515625 0.531250 0.523438 -0.017362
8 0.515625 0.523438 0.519531 -0.005404
9 0.515625 0.519531 0.517578 0.000545
10 0.517578 0.519531 0.518555 -0.002427
11 0.517578 0.518555 0.518066 -0.000940
12 0.517578 0.518066 0.517822 -0.000197
13 0.517578 0.517822 0.517700 0.000174
14 0.517700 0.517822 0.517761 -0.000012
Root is: 0.517761

86 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

45) Write a c program to implement the Newton-Raphson method


for finding real roots of a nonlinear equation

Newton Raphson
Newton Raphson Method is an open method and starts with one initial guess for finding
real root of non-linear equations.
In Newton Raphson method if x0 is initial guess then next approximated root x1 is
obtained by following formula:
x1 = x0 - f(x0) / g(x0)
And an algorithm for Newton Raphson method involves repetition of above process i.e.
we use x1 to find x2 and so on until we find the root within desired accuracy.

Algorithm for Newton Raphson Method


An algorithm for Newton Raphson method requires following steps in order to solve any
non-linear equation with the help of computational tools:
1. Start
2. Define function as f(x)
3. Define first derivative of f(x) as g(x)
4. Input initial guess (x0), tolerable error (e)
and maximum iteration (N)
5. Initialize iteration counter i = 1
6. If g(x0) = 0 then print "Mathematical Error"
and goto (12) otherwise goto (7)
7. Calcualte x1 = x0 - f(x0) / g(x0)
8. Increment iteration counter i = i + 1
9. If i >= N then print "Not Convergent"
and goto (12) otherwise goto (10)
10. If |f(x1)| > e then set x0 = x1
and goto (6) otherwise goto (11)
11. Print root as x1
12. Stop

87 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

Program for Newton Raphson (NR) Method


This program implements Newton Raphson method for finding real root of nonlinear
equation in C programming language.
In this C program, x0 is initial guess value, e is tolerable error and f(x) is non-linear
function whose root is being obtained using Newton method.
C Source code: Newton Raphson Method
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>

/* Defining equation to be solved. Change this equation to solve another problem. */


#define f(x) 3*x - cos(x) -1

/* Defining derivative of g(x).


As you change f(x), change this function also. */
#define g(x) 3 + sin(x)

void main()
{
float x0, x1, f0, f1, g0, e;
int step = 1, N;
clrscr();
/* Inputs */
printf("\nEnter initial guess:\n");
scanf("%f", &x0);
printf("Enter tolerable error:\n");
scanf("%f", &e);
printf("Enter maximum iteration:\n");
scanf("%d", &N);
/* Implementing Newton Raphson Method */
printf("\nStep\t\tx0\t\tf(x0)\t\tx1\t\tf(x1)\n");
do
{
g0 = g(x0);
f0 = f(x0);
if(g0 == 0.0)
{
printf("Mathematical Error.");
exit(0);
}

x1 = x0 - f0/g0;

printf("%d\t\t%f\t%f\t%f\t%f\n",step,x0,f0,x1,f1);
x0 = x1;

step = step+1;

88 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

if(step > N)
{
printf("Not Convergent.");
exit(0);
}

f1 = f(x1);

}while(fabs(f1)>e);

printf("\nRoot is: %f", x1);


getch();
}
Output:
Enter initial guess:
1
Enter tolerable error:
0.00001
Enter maximum iteration:
10

Step x0 f(x0) x1 f(x1)


1 1.000000 1.459698 0.620016 0.000000
2 0.620016 0.046179 0.607121 0.046179
3 0.607121 0.000068 0.607102 0.000068

Root is: 0.607102

89 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

46) Write a c program to implement the LaGrange interpolation


formula.

Lagrange Method
In many real world applications of science and engineering, it is required to find the value
of dependent variable corresponding to some value of independent variable by analyzing
data which are obtained from some observation. For example, suppose we have following
sets of data tabulated for x (independent variable) and y (dependent variable) :
----------------------------------------
| x: | x0 | x1 | x2 | x3 | ... | xn |
-----------------------------------
| y: | y0 | y1 | y2 | y3 | ... | yn |
----------------------------------------
Then the method of finding the value of y = f(x) corresponding to any value of x=xi
within x0 and xn is called interpolation. Thus interpolation is the process of finding the
value of function for any intermediate value of the independent variable. If we need to
estimate the value of function f(x) outside the tabular values then the process is called
extrapolation. However, in general, extrapolation is also included in interpolation.
There are different methods for interpolation for example: Newtons Forward
Interpolation, Netwtons Backward Interpolation, Newtons General Interpolation with
divided difference, Lagrange Interpolation etc. In this article we are going to develop an
algorithm for Lagrange Interpolation.
Formula: Lagrange Interpolation Method
If y = f(x) takes the value of y0 , y1 , y2 , y3 , ... , yn corresponding to x0 , x1 , x2 , x3 , ...
, xn then
y = f(x) = (x - x1)(x - x2)...(x - xn) * y0/(x0 - x1)(x0 - x2)...(x0 - xn)

(x - x0)(x - x2)...(x - xn) * y1/(x1 - x0)(x1 - x2)...(x1 - xn)

+ .... +

(x - x1)(x - x2)...(x - xn-1) * yn/(xn - x0)(xn - x1)...(xn - xn-1)

is known as Lagrange Interpolation Formula for unequal intervals and is very simple to
implement on computer.
Algorithm: Lagrange Interpolation Method
1. Start

2. Read number of data (n)

3. Read data Xi and Yi for i=1 ton n

90 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

4. Read value of independent variables say xp


whose corresponding value of dependent say yp is to be determined.

5. Initialize: yp = 0

6. For i = 1 to n
Set p = 1
For j =1 to n
If i ≠ j then
Calculate p = p * (xp - Xj)/(Xi - Xj)
End If
Next j
Calculate yp = yp + p * Yi
Next i

6. Display value of yp as interpolated value.

7. Stop

C Source code: Lagrange Interpolation

#include<stdio.h>
#include<conio.h>

void main()
{
float x[100], y[100], xp, yp=0, p;
int i,j,n;
clrscr();
/* Input Section */
printf("Enter number of data: ");
scanf("%d", &n);
printf("Enter data:\n");
for(i=1;i<=n;i++)
{
printf("x[%d] = ", i);
scanf("%f", &x[i]);
printf("y[%d] = ", i);
scanf("%f", &y[i]);
}
printf("Enter interpolation point: ");

91 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

scanf("%f", &xp);
/* Implementing Lagrange Interpolation */
for(i=1;i<=n;i++)
{
p=1;
for(j=1;j<=n;j++)
{
if(i!=j)
{
p = p* (xp - x[j])/(x[i] - x[j]);
}
}
yp = yp + p * y[i];
}
printf("Interpolated value at %.3f is %.3f.", xp, yp);
getch();
}
C Program Output: Lagrange Interpolation
Enter number of data: 5 ↲
Enter data:
x[1] = 5 ↲
y[1] = 150 ↲
x[2] = 7 ↲
y[2] = 392 ↲
x[3] = 11 ↲
y[3] = 1452 ↲
x[4] = 13 ↲
y[4] = 2366 ↲
x[5] = 17 ↲
y[5] = 5202 ↲
Enter interpolation point: 9 ↲
Interpolated value at 9.000 is 810.000.

Note: ↲ indicates ENTER is pressed.

92 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

47) Write a c program for approximating the definite integral of a


continues function using Simpson's 1/3 rule.

Simpson's 3/8 Rule


Algorithm
1. Start
2. Define function f(x)
3. Read lower limit of integration, upper limit of
integration and number of sub interval
4. Calcultae: step size = (upper limit - lower limit)/number of sub interval
5. Set: integration value = f(lower limit) + f(upper limit)
6. Set: i = 1
7. If i > number of sub interval then goto
8. Calculate: k = lower limit + i * h
9. If i mod 3 =0 then
Integration value = Integration Value + 2* f(k)
Otherwise
Integration Value = Integration Value + 3 * f(k)
End If
10. Increment i by 1 i.e. i = i+1 and go to step 7
11. Calculate: Integration value = Integration value * step size*3/8
12. Display Integration value as required answer
13. Stop

Simpson 1/3 Rule C Program


#include<stdio.h>
#include<conio.h>
#include<math.h>
/* Define function here */
#define f(x) 1/(1+x*x)
int main()
{
float lower, upper, integration=0.0, stepSize, k;
int i, subInterval;
clrscr();
/* Input */
93 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab

printf("Enter lower limit of integration: ");


scanf("%f", &lower);
printf("Enter upper limit of integration: ");
scanf("%f", &upper);
printf("Enter number of sub intervals: ");
scanf("%d", &subInterval);

/* Calculation */
/* Finding step size */
stepSize = (upper - lower)/subInterval;

/* Finding Integration Value */


integration = f(lower) + f(upper);
for(i=1; i<= subInterval-1; i++)
{
k = lower + i*stepSize;
if(i%2==0)
{
integration = integration + 2 * f(k);
}
else
{
integration = integration + 4 * f(k);
}
}
integration = integration * stepSize/3;
printf("\nRequired value of integration is: %.3f", integration);
getch();
return 0;
}
Simpson's 1/3 Rule C Program Output
Enter lower limit of integration: 0
Enter upper limit of integration: 1
Enter number of sub intervals: 6
Required value of integration is: 0.785

94 | P a g e

You might also like