c programming lab manual final(new) (1)
c programming lab manual final(new) (1)
Table of Contents
Sl. No. Contents Page No
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
Algorithm:
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
Use printf statements to print the size of each data type along with a message.
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.
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
Algorithm:
* Note that the specific range values may vary depending on your system and
compiler.
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
4|Page
I B.Tech. – I Sem. Computer Programming using C Lab
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
6|Page
I B.Tech. – I Sem. Computer Programming using C Lab
7|Page
I B.Tech. – I Sem. Computer Programming using C Lab
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
Algorithm:
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
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.
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
Algorithm:
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
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
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
Algorithm:
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
enter a number:8
value of n is eight
18 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
Algorithm:
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
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
Algorithm:
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
Algorithm:
4. The while (1) creates an infinite loop, and we will use the break statement to exit the
loop when necessary.
6.Add a conditional statement to check whether you should break out of the loop.
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
Algorithm:
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
Algorithm:
2. Declare global constants and variables for menu options and user input.
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
Algorithm:
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.
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.
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
Algorithm:
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:
32 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
Algorithm:
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
34 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
Algorithm:
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.
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
Algorithm:
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
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:
b. Copying a string
f. Reversing a string
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.
6. Ask the user if they want to perform another operation or exit 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
40 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
Algorithm:
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.
5.Inside the loop, print the character at the current index of the string.
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
Algorithm:
2.Initialize variables to keep track of the array size and a flag to identify unique numbers.
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.
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.
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
2.Initialize variables to keep track of the array size and a flag to identify unique numbers.
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.
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.
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
Algorithm:
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.
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
Algorithm:
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.
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
49 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
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
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)
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
Algorithm:
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].
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].
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
Algorithm:
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.
a. Check if the input number is less than or equal to 1. If it is, return false (not prime).
c. For each iteration, check if the input number is divisible by the current iteration value.
If it is, return false (not 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
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
Algorithm:
2.Declare a function prototype for the function that will find the largest number.
a. Define the main function where you'll declare the array and perform input and output
operations.
a. Call the findLargest function, passing the array and its size as arguments. Assign the
result to a variable to store the largest number.
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.
8.After finding the largest number inside the findLargest function, return it to the main
function
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
Algorithm:
1.Declare a function prototype for the addition function. This is necessary because you're
using a function before defining it.
3.add the two variables using and return the result to main function.
5.Define the add function. This function takes two integer parameters and returns the sum
of the two numbers.
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
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.
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.
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
62 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
Algorithm:
1.Define the recursive function to calculate the factorial. The function should take an
integer as its argument and return an integer.
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.
7.Call the recursive factorial function with the input number as an argument and store the
result in another variable.
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
Algorithm:
3.Prompt the user for the number of users and allocate memory accordingly
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
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
68 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
Algorithm:
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
70 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
Algorithm:
2.Allocate memory for num1, num2, and sum using the malloc function
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
Algorithm:
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.
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
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()
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
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).
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.
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
Algorithm:
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
Algorithm:
1.Declare any variables you'll need, such as file pointers and data to be written.
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
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.
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
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
/*
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);
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
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.
87 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
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);
89 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
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)
+ .... +
is known as Lagrange Interpolation Formula for unequal intervals and is very simple to
implement on computer.
Algorithm: Lagrange Interpolation Method
1. Start
90 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
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
7. Stop
#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.
92 | P a g e
I B.Tech. – I Sem. Computer Programming using C Lab
/* Calculation */
/* Finding step size */
stepSize = (upper - lower)/subInterval;
94 | P a g e