Final C Manual
Final C Manual
1
Aim : Write a Program to perform basic arithmetic operations.
Theory/Description:
This Program takes two integers a, b as input and performs all the basic arithmetic operations like
addition, subtraction, multiplication, and division on them. In this Program the variable c represents
the result of operation.
Algorithm :
Start
c=a+b
d=a-b
e=a*b
f=(float)a/b
Stop
RCET / Department Of Electrical Engineering / Computer Programming Lab 1
Program :
/*** PROGRAM TO PERFORM BASIC ARITHMETIC OPERATIONS ***/
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b;
float c,d,e,f;
printf(“Enter two values:”);
scanf(“%d%d”,&a,&b);
c=a+b;
d=a-b;
e=a*b;
f=(float)a/b;
printf(“%f%f%f%f”,c,d,e,f);
getch( );
}
Input :
Enter two values:7 4
Output :
11
3
28
1.400000
Description : This Program takes radius of a sphere as input and prints its volume and surface
area. In the Program variable r represents radius, v represents volume of sphere and sa represents
surface area.
Algorithm :
v=(4*PI*r*r*r)/3;
sa=4*PI*r*r;
Stop
Input :
Enter radius of sphere :5
Output :
Volume = 392.750000
Surface area=314.200012
1. Write a Program to read a "float" representing a number of degrees Celsius, and print as a
"float" the equivalent temperature in degrees Fahrenheit. Print your results in a form such as
100.0 degrees Celsius converts to 212.0 degrees Fahrenheit.Given as input an integer number of
seconds, print as output the equivalent time in hours, minutes and seconds. Recommended
output format is something like 7322 seconds is equivalent to 2 hours 2 minutes 2 seconds.
2. Given the values of a,b,c. Write a Program to rotate their values.
b) main( )
{
int a, b;
a = - 3 - - 3;
b = - 3 - - ( - 3 );
printf(“a = %d b = %d, a, b );
}
c) main( )
{
float a = 5, b = 2;
int c;
c = a % b;
printf(“%d”, c );
}
d) main ( )
{
printf(“nn\n\nnn\n”);
printf(“nn/n/nnn/n”);
b. C can be used on :
1) Only MS-DOS operating system
2) Only Linux operating system
3) Only Windows operating system
4) All the above
Description :
This Program takes a number as input and finds whether that number is even or odd. In this Program
the variable n represents the number which is checked for even or odd. To check whether the
number is even or odd the value of n is divided by 2 if the remainder is zero then the number is even
otherwise number is odd.
Algorithm :
Start
Enter a number in n
True Is False
n%2=0
Print number n is
Print number n is odd
even
Stop
Input :
Enter a number:7
Output :
Given number is odd
1. Write a Program which reads two integer values. If the first is less than the second, print the
message up. If the second is less than the first, print the message down If the numbers are equal,
print the message equal If there is an error reading the data, print a message containing the word
Error and perform exit( 0 );
c. main ( )
{
int a = 300, b, c;
if ( a > = 400 )
b = 300;
c = 200;
printf(“\n%d %d”, b, c);
}
d. main ( )
{
int a = 500, b, c;
if ( a > = 400 )
b = 300;
c = 200;
printf(“\n%d%d”, b, c);
}
e. main ( )
{
int x = 3, y = 5;
if ( x = = 3 )
printf(“\n%d”, x);
else ;
printf(“\n%d”, y);
}
f. main ( )
{
int x = 3;
float y = 3.0;
if ( x = = y )
RCET / Department Of Electrical Engineering / Computer Programming Lab 12
printf(“\nx and y are equal”);
else
printf(“\nx and y are not equal”);
}
g. main( )
{
int x = 3, y, z;
y = x = 10;
z = x < 10;
printf(“\nx = %d y = %d z = %d”, x, y, z);
}
b. main ( )
{
int ji = 65;
printf(“\mji >= 65 ? %d : %c”, ji);
}
c. main ( )
{
int x = 10, y = 10;
x = 20 && y ! = 10 ? printf (“True”) : printf (“False”);
}
d. main ( )
{
int n = 9;
( n = = 9 ? printf (“You are correct”); : printf(“You are wrong”););
}
e. main ( )
{
int kk = 65 ll;
ll = ( kk = = 65 : printf (“\n kk == 65”) : printf(“\n kk ! = 65” ) );
}
Description :
This Program takes values of three coefficient of equation as input and calculates its roots.
In this Program variables a, b and c represents coefficients of equation, d represents discriminent r1
and r2 represents roots of equation.
A quadratic equation has two roots which are given by the following formulae :
r1= -b+sqrt(b2 – 4ac)/2a
r2= -b-sqrt(b2 – 4ac)/2a
Here in calculation three cases are possible :
1. If d> 0 then
r1= -b+sqrt(b2 – 4ac)/2a
r2= -b-sqrt(b2 – 4ac)/2a
2. If d=0 then
r1=r2=-b/2a
3. If d<0 the roots are imaginary.
Algorithm :
Step 1: Input the coefficients of the quadratic equation(for eg. a,b,c).
Step 2: Calculate the discriminate (d) using appropriate formula.
Step 3: Check if discriminate is greater than 0.If it is go to step 5.
Step 4: If discriminate is not greater than 0 then check if discriminate is equal to 0.
If it is go to Step5 otherwise go to Step 6.
Step 5: Calculate the roots. Go to Step 7.
Step 6: Print ‘roots are imaginary’ and return.
Step 7: Print the calculated roots and return.
d=((b*b)-(4*a*c))
True False
Is
d>0
True False
d1=sqrt(d) Is
r1=((-b+d1)/(2*a)) d=0
r2=((-b-d1)/(2*a))
Stop
Output :
The Roots of equation are Real And Equal
The Roots are =Root1=Root2= -1.000000
Input :
Enter Three Constants: 2 3 4
Output :
The Roots of equation are Imaginary
1. Write a Program to calculate the division of students according to the following rules:
Description :
This Program takes three integers a, b and c as input and finds the greatest among them.
In this Program values of two variables are first compared with each other and the value greater
among them is then compared with the value of the third variable to find the greatest value.
Algorithm :
Step 1: Input any three numbers( for eg. a,b,c)
Step 2: Check if a is greater than b. if it is goto Step 3 otherwise go to Step 4.
Step 3: Check if a is greater than c. If it is print ‘a is greatest’ and return to operating system
otherwise go to Step 5.
Step 4: Check if b is greater than c. If it is print ‘b is greatest’ and return to operating system.
Step 5: Print ‘c is greatest’.
True false
Is
a>b
True
True false false
Is Is
a>c b>c
a is b is greatest
c is
greatest greatest
stop
Output :
6 is greatest
Assignment
Description :
In this Program variables a, b and c represents three sides of a triangle. Values of a, b and c are
checked to find whether the triangle is an isosceles, scalars or an equilateral triangle.
If the values of a, b and c are equal then the triangle is equilateral.
If the values of two sides are equal then the triangle is isosceles.
Otherwise triangle is scalars.
Algorithm:
Is False
a==b &&
b==c &&
c==a
True
False
Is
Print Triangle is a==b || b==c ||
equilateral c==a
Print Triangle is
True scalene
Print Triangle is
isosceles
Stop
Input :
Enter the three sides of a triangle:2 2 2
Output :
Triangle is equilateral
Input :
Enter the three sides of a triangle:2 3 4
Input :
Enter the three sides of a triangle:2 3 2
Output :
Triangle is isosceles
Assignment
1. Write a Program to input the weight and height of 5 students and calculate the number of
students whose weight is greater than 45 and height is more than 5 feet2 inches.
Description : This Program takes three positive integers a, b and c as input and compares their
values to find greatest among them. Than the square of the greatest value is checked with the sum of
the squares of the other two values and if the square of the greatest value is equal to the sum of the
square of the other two values then they form Pythagorean triplet, and if not they do not form
Pythagorean triplet.
Algorithm :
Step 1: Input any three sides of a triangle ( for eg. a,b,c)
Step 2: Check if a is greater than b and a is greater than c. if it is go to Step 3 else go to Step 4.
Step 3: Check if square of a is equal to sum of square of b and square of c. if it is print ‘Pythagorean
triplet’ and return otherwise go to Step 7.
Step 4: Check if b is greater than a and b is greater than c. if it is go to Step 5 else go to Step 6.
Step 5: Check if square of b is equal to sum of square of a and square of c. if it is print
‘Pythagorean
triplet’ and return otherwise go to Step 7.
Step 6: Check if square of c is equal to sum of square of a and square of b. if it is print
‘Pythagorean
triplet’ and return otherwise go to Step 7.
Step 7: Print ‘ Not a Pythagorean Triplet’
Input :
Enter three positive integers : 3 4 5
Output :
The numbers form Pythagorean triplet
Input :
Enter three positive integers : 2 3 4
Output :
The numbers do not form Pythagorean triplet
1. Input the length of four sides of a polygon and calculate whether the polygon is a rectangle
or square or trapezium.
b. main ( )
{
int ji = 65;
printf(“\mji >= 65 ? %d : %c”, ji);
}
c. main ( )
{
int x = 10, y = 10;
x = 20 && y ! = 10 ? printf (“True”) : printf (“False”);
}
d. main ( )
{
int n = 9;
( n = = 9 ? printf (“You are correct”); : printf(“You are wrong”););
}
e. main ( )
{
int kk = 65 ll;
ll = ( kk = = 65 : printf (“\n kk == 65”) : printf(“\n kk ! = 65” ) );
}
Algorithm:
Output :
Result of addition is :7
Assignment
1. Read an integer value. Assume it is the number of a month of the year; print out the name of that
month
2. Read an integer value. Assume it is the number of a week day; print out the name of that day
Description :
This Program takes a five numbers as input and evaluates their square root. The variable count
keeps the count of numbers read. When the count is less than or equal to 5, goto read; directs the
control to the label read, otherwise the Program stops. Before calculating square root the value of
number is checked and if the number is positive then only its square root is calculated otherwise a
message is displayed that the number is negative.
Algorithm:
count=1
False
Is
count <=5
True
False
Is
x>0
y=sqrt(x)
True
Print value is
Print value of y negative
count=count+1
Stop
Input :
Enter five values :
25 16 -36 9 4
Output :
square root of 25 is : 5.000000
square root of 16 is : 4.000000
value - 3 is negative
square root of 9 is : 3.000000
square root of 2 is : 2.000000
RCET / Department Of Electrical Engineering / Computer Programming Lab 40
Assignment
1. Write a Program for arithmetic operation using goto statement?
Description :
In this Program the variable n represents number whose sum of digits is to be calculated and sum
represents the sum of its digits. To calculate sum number is divided with ten till its value is greater
then zero and the remainder of the division are added to find the required sum.
Algorithm:
Step 1: Initialize sum =0.
Step 2: Input any integer(n).
Step 3: Repeat Steps 4, 5, 6 while n >= 0 .
Step 4: Apply modulus operator on n and store the result in any variable (a).
Step 5: Calculate the sum of sum and a and store it back in sum.
Step 6: Apply the division operator on n and store the result in n.
Step 7: Print the value of variable sum as the sum of digits.
Enter a number in n
False
Is
n>0
True
Stop
Input :
Enter a Number : 1256
Output :
sum of the digits of given number is : 14
Viva-voce quetions
1. What is meant by looping?
2. What is a null statement? Explain typical use of it.
3. How can we create an infinite loop?
4. What would be the output of the following Programs :
a) main ( )
{
int i = 1;
while ( i < = 10)
{
printf(“\n%d”, i);
}
}
b) main ( )
{
int x = 4;
while( x = = 1 )
{
x = x - 1;
printf(“\n%d”, x);
}
}
c) main( )
{
char x;
while(x = 0;x < = 255;x + +)
printf(“\nAscii value % d character %c”, x, x);
}
5. Write a Program to read in 10 numbers and compute the average, maximum and minimum
values.
Description : In this Program the variable x represents the number and the variable n
represents the power by which x is raised to and y represents the required result. The variable
y is initialized to 1 and then multiplied by x, n times using while loop. The loop control
variable count is initialized outside the loop and incremented inside the loop. When the value
of count becomes greater than n, the control exits the loop.
Algorithm :
Step 1 : Read the values of x and n.
Step 2 : Initialize y = 1.0 and count = 1.
Step 3 : Repeat Steps 4, 5 while count < = n.
Step 4 : y = y * x.
Step 5 : Increment count = count + 1.
Step 6 : Print the value of y.
y=1.0
count = 1
y=y*x
count=count+1
False
Is
count<=
n
True
Print the value of
y
Stop
Input :
Enter the values of x and n:2 5
Output :
5 to the power 2 is : 32
Viva-voce quetions
1. What is the difference between while and do-while loop?
2. What do you mean by entry control & exit controlled loop?
3. What would be the output of the following :
int y, x = 0;
do
{
y = x;
}while(x = = 0);
Description :
In this Program variable n represents the number whose factorial is to be found and f represents the
factorial of n. The variable f is initialized to 1 and then multiplied by the loop control variable i, n
times. When the value of i becomes greater than n, the control exits the loop.
Algorithm:
Step 1: Initialize f =1
Step 2: Input the value of number whose factorial is to be found (n).
Step 3: Initialize i =1.
Step 4: Repeat steps 5, 6 while i < =1.
Step 5: Multiply the present value of i with f and store it in f.
Step 6: Increment the current value of i by 1.
Step 7: Print the value of variable f as the factorial of the number.
f=1
i=1
False
Is
i<=n
True
i=i+1
f=f*i
Print value of f,
factorial of n
Stop
Input :
Output :
Factorial of 6 is: 720
Viva-voce quetions
1. Explain the format of for loop.
2. Can we omit any one of the section of for loop?
3. What would be the output of the following :
for(i=0;i<=10;i++);
{
i++;
printf(“%d”,i);
}
Description :
This Program takes number of rows n to be displayed as input and prints the triangle up to that
number of rows. In this Program two loops are there one for rows which is up to n and the other is
for columns which is up to the control variable of the outside loop. A variable c is initialized to zero
outside the loop and incremented and printed inside the loop to display the desired triangle.
Algorithm:
Step 1: Input the number of rows upto which Floyd’s triangle is to be generated(n).
Step 2: Initialize i=1, j=1and c=0.
Step 3: Repeat steps 4, 5, 6, 7 while i < = n.
Step 4: Repeat steps 5,6 while j < = i.
Step 5: Increment the value of c by1.
Step 6: Print the value of c.
Step 7: Print new line.
Input :
Enter value of n : 5
Output :
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Viva-voce quetions
1. What do you mean by nested for loop?
2. What would be the output of the following :
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d”,j);
}
}
Description : In this Program the variable number represents the number whose square root is
to be calculated and the variable count keeps the count of numbers of number. Variable negative
counts the number of negative numbers. In case the series contains any negative number, the process
of evaluation of square root should be bypassed for such numbers because the square root of a
negative number is not defined. The continue statement is used to achieve this. The Program also
prints a message saying that the number is negative and keeps an account of negative numbers. The
final output includes the number of positive values evaluated and the number of negative items
encountered.
Algorithm:
Assignment
1. Write a Program to take as input 100 numbers from the users. If the number is negative it comes
out of the Program.
Viva-voce quetions
1. Explain break and continue statement?
2. The break statement is used to exit from :
a) An if statement
b) A for loop
c) A Program
d) The main() function
3. Which of the following statement is used to take the control to the beginning of the loop?
a) exit
b) break
c) continue
d) None of these
Description :
This Program takes an array as input and displays the sum of its elements as output. This Program
also takes number of elements in the array as input. In this Program variable a[ ] represents the array,
n represents the number of elements in the array and sum represents the sum of the elements in the
array. To calculate sum the variable sum is initialized to zero the added with elements of array inside
a loop. he final value of sum is printed outside the loop.
Algorithm:
Step 1: Input the number of elements of the array(n).
Step 2: Initialize i=0.
Step 3: Repeat Step 4, 5 till i is less than or equal to n .
Step 4: Enter the value of the element of array(a[i]).
Step 5: Increment the value of i by 1.
Step6: Initialize i=0, sum=0.
Step 7: Repeat Steps 8, 9 till i is less than or equal to n .
Step 8: Add the current value of sum to the current value of a[i] and store the result in sum.
Step 9: Increment the value of i by 1.
Step 10: Print the value of the variable sum as the sum of the elements.
Input :
Enter the number of elements in array:5
Enter the elements of array :
1
2
3
4
5
Output :
Sum of the elements of array is :15
2. Read a positive integer value, and compute the following sequence: If the number is even, halve
it; if it's odd, multiply by 3 and add 1. Repeat this process until the value is 1, printing out each
value. Finally print out how many of these operations you performed.
Viva-voce quetions
1. What do you mean by the term array? In which situation do we sue arrays.
2. Identify error , if any, in each of the following statements.
a) int score(100);
b) float values[10,15];
c) float average[ROW],[COLUMN]
d) char name[15];
e) int sum[ ];
Description :
This Program takes two arrays x[ ], y[ ] as input, copies their common elements in third array z[ ]
and displays the elements of third array as output. To find the common elements the elements of
array x and y are compared one by one and before inserting common element in array z a check is
perform to see whether that element is already present in array or not and if not that element is
inserted in array z.
Algorithm:
Input :
Enter The Elements For 1st Array :
1
2
3
4
5
Enter The Elements For 2nd Array :
2
5
6
7
8
Output :
The Common Elements are :
2
5
Viva-voce quetions
Description : This Program takes a one dimensional array as input and arrange them ascending
order using bubble sort technique. In this Program variable a[ ] represents an array, consisting of n
elements.
The sorting ALGORITHM works as follows :
1. Compare the first two elements in array say a[1], and a[2]. If a[2] is smaller than a[1], then
interchange their values.
2. Compare a[2] and a[3]; interchange if a[3] is smaller than a[2].
3. Continue this process till the last two elements are compared and interchanged.
4. Repeat the above steps n-1 times.
In repeated trips through array, the smallest elements ‘bubble up’ to the top. Because of this
bubbling up effect, this ALGORITHM is called bubble sorting.
The bubbling effect is illustrated below for four items :
TRIP-1
80 35 35 35
35 80 65 65
65 80 10
65
10 10 10 80
TRIP-2
35 35 35
65 65 10
10 10 65
80 80 80
10 35
65 65
80 80
During the first trip, three pairs of items are compared and interchanged whenever needed. It should
be noted that the number 80, the largest among the items, has been moved to the bottom at the end of
first trip. This means that the element 80 need not be considered any further. Therefore TRIP-2
requires only two pairs to be compared. This time the number 65 has been moved down the list.
Each trip brings the smallest value 10 up by one level.
The number of steps required in a trip is reduced by one for each trip made. The entire process will
be over when a trip contains only one step. If the list contains n elements, then the number of
comparisons involved would be n(n-1)/2.
Output :
The Sorted Elements :
1
2
3
5
6
7
Viva-voce quetions
1. What would be the output of the following :
a) main( )
{
int num[26], temp;
num[0] = 100;
num[25] = 200;
temp = num[25];
num[25] = num[0];
num[0] = temp;
printf(“\n%d %d”, num[0], num[25]);
}
b) main()
{
int array[26], i;
for(i = 0;i < =25;i ++)
{
array[i] = ’A’ + i;
printf(“\n%d %c”, array[i], array[i]);
}
}
Description :
This Program takes two matrices as input and displays their sum as output. This Program also takes
number of rows and columns in matrices as input. In this Program variables r and c represents the
number of rows and columns respectively. Array variables x and y represents matrices to be added
and z represents the resultant matrix . To obtain the result the elements of matrix x are added with
the corresponding elements of matrix y.
Therefore the sum of two matrices is given by
z[i][j]=x[i][j]+y[i][j]
Where i and j are the indexes for rows and columns.
Algorithm:
Step 1: Input the elements of the first matrix.(x[][])
Step 2: Input the elements of the second matrix.(y[][])
Step 3: Print the elements of the first matrix.
Step 4: Print the elements of the second matrix.
Step 5: Add the elements of the two matrices.
Step 6: Print the sum of the two matrices.(z[][])
Input :
Enter No of Rows & Columns (max : 5,5) :2 3
Enter Elements for 1st Matrix :
123
234
Enter Elements for 2nd Matrix :
234
567
Output :
The Elements In 1st Matrix :
123
234
The Elements In 2nd Matrix :
234
567
Assignment
1. Write a Program to multiply two 3*3 matrices.
Viva-voce quetions
1. What will be the output of the following Program :
main( )
{
static int a[3][3] = {
1, 2, 3,
4, 5, 6,
7, 8, 9
} ;
static int *ptr[3] = { a[0], a[1], a[2] } ;
int **ptr1 = ptr ;
int i ;
printf ( "\n" ) ;
for ( i = 0 ; i <<= 2 ; i++ )
printf ( "%d ", *ptr[i] ) ;
printf ( "\n" ) ;
for ( i = 0 ; i <<= 2 ; i++ )
printf ( "%d ", *a[i] ) ;
printf ( "\n" ) ;
for ( i = 0 ; i <<= 2 ; i++ )
{
printf ( "%d ", **ptr1 ) ;
ptr1++ ;
}
}
2. What do you mean by multidimensional array? Explain the syntax to define it.
3. How can we initialize a multidimensional array? Explain.
Description :
This Program reads a string character by character as input and prints it character by character as
output. In this Program c represents the character read from the keyboard and str represents the
string in which these characters are stored. The function getchar is used to read the string character
by character from the keyboard till the new line character (‘\n’) is encountered and the function
putchar is used to print it character by character on the screen till the null character (‘\0’) is
encountered.
Algorithm:
Input :
Enter a string:this is a character array
Output :
The string is :this is a character array
1. Write a Program to calculate the number of commas and number of tab characters in a string.
Viva-voce quetions
1. What do you mean by string?
2. Describe the limitation of using getchar and scanf functions for reading string.
3. What would be the output of the following :
main( )
{
printf( 5 + ”Fascimile”);
}
a) Error
b) Fascimile
c) mile
d) None of the above
a) 1 1
b) 1 2
c) 2 2
d) 2 1
Description :
This Program takes a list of five names as input and displays the name with the largest number of
characters as output. In this Program variable name represents the array of five
names. To obtain the longest name the length of the names are compared with each other one by one
in a loop that is executed five times, and after the complete execution of loop we get the length and
index of the longest name that is then used to print the longest name.
Algorithm:
Step 1: Input any five names ( name[][]) and store the length of each name(len[]).
Step 2: Initialize l=0.
Step 3: Store the length of longest name in l.
Step 4: Compare l with the lengths of all the elements of the array name.
Step 5: As it matches the name with the corresponding length is printed as the longest name.
Input :
Enter five names:
Dennis Ritchie
B Ram
Peterson
Adam
Sam
Output :
Longest name(s) is : Dennis Ritchie
Description :
In this Program the variable n represents number whose sum of digits is to be calculated and sum
represents the sum of its digits. To calculate sum number is divided with ten till its value is greater
then zero and the remainder of the division are added to find the required sum.
Algorithm:
Input :
Enter any positive number :8228
Output :
Sum of the digits of given number is :20
Viva-voce quetions
1. What do you mean by functions?
2. The main is user defined function. How does it differ from other user-defined functions
Description:
In call by reference addresses of variables are passed to functions as arguments and pointers are
used to access their values in the function. This Program takes two integers a, b as input and displays
them after swapping their values as output. This Program consist of a function swap to which the
addresses of a, b are passed as arguments and it interchanges their values using pointer variables p
and p1. The pointer variables p and p1 contains the addresses of a and b passed to function swap
respectively.
Algorithm:
Step 1: Input any two values (a, b)
Step 2: Call the function swap by passing the addresses of two variables.
Step 3: Inside the function exchange the values of two addresses using a third pointer variable.
Step 4: Print the values of original variables whose addresses were passed.
Output :
Assignment
Viva-voce quetions
Description : This Program takes number of terms as input and prints the Fibonacci series upto
that number of terms. Here variable n represents number of terms and a, b are the first two terms of
the series. This Program makes recursive call to function febo to print the series.
Algorithm:
Step 1: Input the number of terms required in Fibonacci series (n).
Step 2: Initialize the two variables a=1 and b=1.
Step 3: Print the two values.
Step 4: Call the function fibo passing the values of a and b.
Step 5: Inside the function
a. Repeat steps b, c, d and e until the value of count is equal to n-2.
b. Store the sum of values a and b in c.
c. Increment the value of count.
d. Print the value of c.
e. The function should call itself passing the values of b and c as parameters.
f. Return the value of c to the calling function.
Input :
Enter the number of terms:6
Output :
1 1 2 3 5 8
Assignment
1. Write a Program using recursive function to calculate factorial of a number
Viva-voce quetions
1. What do you mean by the term recursion?
2. Why recursion is considered to harmful in some cases?
RCET / Department Of Electrical Engineering / Computer Programming Lab 103
Experiment No. 24
Aim : Write a Program to print first n even numbers using recursive function.
Description : This Program takes the number of terms up to which the even series is to be
displayed as input and displays the series containing only even numbers as output. In this Program
the variable n represents the number of terms and eve is a function that is passed 2* n i.e. the
maximum value in the series as argument. eve is recursive a function that returns the terms of series.
The recursive call is terminated when the value of n becomes 2 and in that case function returns 2
and terminated.
Algorithm :
Step 1 : Read the number of terms (ex n)
Step 2 : Call the function eve with argument 2*n
a. Check the value of n if it is 2 then return 2
b. Print the value of n and call the function again with n-2
Step 3 : Store the returned value in c and print the value of
Input :
Enter number of terms : 6
Output :
Series is :
12
10
8
6
4
2
Assignment
1. Write a Program using recursion to evaluate x-x3/3!+x5/5!....using recursive function.
Viva –Voce Questions
1. Write down the difference between iterative and recursive functions.
2. Is recursive Program is better with respect to time and space than a non recursive Program.
Description :
This Program takes the details of a list of students as input and displays the details of the students
whose marks is greater then 65. In this Program student is a structure that contains following
members:
roll : Its type is integer and this member represents Roll number of a student.
name : name is a character array and it represents Name of a student.
marks : Its type is float and it represents Marks of a student.
st : st represents the array of structure that is used to store details of students.
Algorithm:
Step 1 : Input the roll number , name and marks of 6 students.
Step 2: Check the marks of each student.
Step 3: If marks of any student is greater than or equal to 65 then print student’s rollnumber , name
and marks.
Input :
Enter details of students their roll no, name & marks:
101 C 65
102 XYZ 75
119 DEF 55
103 GHI 70
104 HJY 80
Assignment
1. Define s structure called cricket that will describe the following information
player name
Team name
Batting average
Using cricket declare an array player with 50 elements and write a Program to read the
information about all the 50 players and print a team wise list containing names of players with
their batting average.
2. Point out errors, if any, in the following Program :
main()
{
struct employee
{
char name[25];
int age;
float bs;
};
struct employee e;
strcpy(e.name,”Hacker”);
age = 25;
printf(“\n%s%d”,e.name,age);
}
Viva-voce quetions
1. What is structure?
2 What would be the output of the following Programs :
a) main( )
{
struct gospel
{
int num;
char mess1[50];
char mess2[50];
}m;
m.num = 1;
strcpy(m.mess1, ”If at all that you have is hammer”);
strcpy(m.mess2, ”Everything looks like a nail”);
printf(“\n%u%u%u”, &m.num, m.mess1, m.mess2);
}
b) struct gospel
{
int num;
RCET / Department Of Electrical Engineering / Computer Programming Lab 110
char mess1[50];
char mess2[50];
}m1 = {2, ”If you are driven by success”, ”make sure that it is a quality drive”};
main( )
{
struct gospel m2,m3;
m2 = m1;
m3 = m2;
printf(“\n%d%s%s”, m1.num, m2.mess1, m3.mess2);
}
3. Ten floats are to be stored in memory. What would you prefer, an array or a structure?
4. Given the statement :
maruti.engine.bolts = 25;
which of the following is True?
a) structure bolts is nested within structure engine
b) structure engine is nested within structure maruti
c) structure maruti is nested within structure engine
d) structure maruti is nested within structure bolts
Description :
This Program takes details of employees as input, asks the user to enter the mode of contact and
displays the details according to the mode of contact as output. In this Program contact is a union
and has two members mobileno, email where mobileno represents Mobile number of an employee
and email represents the Email-id.
employee is a structure that has the following members :
name : name is a character array that represents name of employee.
rollno : Represents employee id.
mode_of_contact : It is a variable of type contact and represents Mode of contact.
void main( )
{
struct employee emp;
int mode;
printf(“Enter the employee’s details :\n”);
scanf(“%s%d”,emp.name,&emp.rollno);
printf(“Enter mode of contact :\n”);
printf(“Enter 1 for mobile no.\n2 for email\n”);
scanf(“%d”,&mode);
if(mode==1)
{
printf(“Enter Mobile number:”);
scanf(“%s”,emp.mode_of_contact.mobileno);
printf(“%s\t%d\t
%s\n”,emp.name,emp.rollno,emp.mode_of_contact.mobileno);
}
else
{
printf(“Enter Email-id:”);
RCET / Department Of Electrical Engineering / Computer Programming Lab 114
scanf(“%s”,emp.mode_of_contact.email);
printf(“%s\t%d\t
%s\n”,emp.name,emp.rollno,emp.mode_of_contact.mobileno);
}
getch( );
}
Output :
Enter the employee’s details :
XYZ 101
Enter mode of contact :
Enter 1 for mobile no.\n2 for email
1
Enter Mobile number:9827122222
XYZ 101 9827122222
Assignment
1. Declare a union number having members integer and float. Take input a number that will be either
of type int or float and print it.
Viva-voce quetions
1. What is union?
Description : This Program takes three integers a, b , c as input and displays the largest among
them as output. In this Program a macro max is defined using # define preprocessor directive to
which the values are passed as arguments and it returns the largest value among them. The variable
k represents the larger value among a and b and the variable j represents the final largest value.
Algorithm:
Step 1: Input the values of any three numbers(a,b,c)
Step 2: Calculate maximum of a and b using macro (max) and store it in any variable(k).
Step 3: Calculate maximum of k and c using macro (max) and store it in any variable(j).
Step 4: Print the value of j .
Output :
Enter three values : 4 7 9
Greatest number is : 9
Assignment
1. Write a Program to calculate square of a number using macro.
Viva-voce quetions
1. What do you mean by preprocessor directive?
2. Why macros are considered to be harmful for long Programs?
Description : This Program takes an array as input and displays the array in reverse order as
output. In this Program variable p represents the pointer variable through which the array is read
from the keyboard and displayed in reverse order. To read the array pointer variable is incremented
by 1 after reading each element and to print the array in reverse order the pointer p is decremented
by one and the value pointed by it is printed.
Algorithm:
Step 1: Input the number of elements to be inserted (ex n)
Step 2: Using for-loop input the elements of the array.
Step 3: Print the elements of the array in reverse order using for loop.
Input :
Enter the number of elements in array:5
Enter the elements of array:
1
2
3
4
5
Output :
Array in reverse order :
5
4
3
2
1
Viva-voce quetions
2. What is a pointer?
Description : This Program takes input from the keyboard as input and writes it, character by
character to the file INPUT. The end of the data is indicated by entering an EOF character, which is
control-Z in the reference system. Then the file INPUT is closed. The file INPUT is again opened
fro reading. The Program reads its contents character by character and displays it on the screen.
Reading is terminated when getc encounters the end-of-file mark EOF.
Algorithm:
Step 1: Assign a file pointer to the file INPUT
Step 2: Take input from the keyboard using getchar function till the EOF character is entered.
Step 3: Write characters to the file
Step 4: Close the file
Step 5: Read the characters from the file.
Step 6: Print the characters.
Step 7: Close the file
Input :
Data input
This is the Program to test the file handling
^Z
Output :
Data output
This is the Program to test the file handling
Assignment
Viva-voce quetions
Description : This Program uses three files simultaneously and therefore we need to define
three-file pointers fp,f1,f2. First the file data containing integer values is created. The integer values
are read from keyboard and are written to the file data with the help of putw function. Input from
the keyboard is terminated when we type -1 and the file is closed. The next step is to open all the
three files, data for reading, odd and even for writing. The contents of data file are read, and
written to the files odd and even after appropriate testing.
Algorithm:
Output :
Contents of ODD file:
1
3
5
7
9
Contents of EVEN file:
2
4
6
8
10
Viva-voce quetions
2. Differentiate between the following :
a) getc and getw
b) putc and putw
Description : This Program takes Employee’s details such as employee id, employee name,
basic pay as input, calculates dearness allowance, house rent allowance, income tax & net salary and
stores this details in file named payroll. Then file is again opened in read mode and the displays the
entire contents of file.
In this Program which variable represents which information is given below :
eid – Employee id
ename – Employee name
basic – Basic pay
da – Dearness aloowance
hra – House rent allowance
tax – Income tax
gross – Gross salary
net – Net salary
The values of da, hra, tax, gross and net are calculated as follows :
da=25% of basic
hra=10% of basic
gross=basic+da+hra
tax=30% of gross
net=gross-tax
Algorithm:
Step 1: Input Empid, name and basic pay until EOF character is entered.
Step 2: Calculate HRA, DA, Income Tax and Net salary.
Step 3: Open a new file in write mode and write Empid, name , Basic pay, HRA, DA, Income Tax,
Net salary to the file.
Step 4: Close file.
Step 5: Open file in read mode.
Step 6: Read the contents of the file and print on the screen.
Input :
Enter Employee Id, Name, Basic Pay:
101
Sam
8000
102
Adam
7000
103
Jhon
6000
^Z
Output :
Cotents of file:
__________________________________________________
Employee Id :101
Employee Name :Sam
Basic Pay :8000
Dearness Allowance :2000.000000
RCET / Department Of Electrical Engineering / Computer Programming Lab 135
House Rent Allowance :800.000000
Income Tax :3240.000000
Net Salary :7560.000000
--------------------------------------------------------------------------------
Employee Id :102
Employee Name :Adam
Basic Pay :7000
Dearness Allowance :1750.000000
House Rent Allowance :700.000000
Income Tax :2835.000000
Net Salary :6615.000000
--------------------------------------------------------------------------------
Employee Id :103
Employee Name :Jhon
Basic Pay :6000
Dearness Allowance :1500.000000
House Rent Allowance :600.000000
Income Tax :2430.000000
Net Salary :5670.000000
--------------------------------------------------------------------------------
Assignment
1. Write a Program that will generate a data file containing the list of customers and their
corresponding phone numbers. Use a structure variable to store the number and telephone of
each customer. Create a data file using a sample list.
1. If a file contains the line “I am a boy\r\0” then on reading this line into array str[] using fgets
what would str[] contain:
a) I am a boy\r\n\0
b) I am a boy\r\0
c) I am a boy\n\0
d) I am a boy
2. On opening a file for reading which of the following activities are performed :
a) The disk is searched for existence of the file.
b) The file is brought into the memory
c) A pointer is set up which points to the first character in the file.
d) All the above
Description : This Program takes a list of values using command line argument and the output
of this Program is the sum of these values. List of values will be stored in array argv[]. Since argv
is an array of character pointers so before addition we convert the elements of array argv in integer
using atoi function defined if stdlib.h header file.
Algorithm :
Step 1 : Set sum = 0.
Step 2 : Repeat Step3 and Step 4 while i < argc.
Step 3 : Read values from command line argument and store in argv[i].
Step 4 : Calculate sum=sum + atoi(argv[i]).
Step 5 : Print the value of sum.
Output :
Compile the Program then make executable file of Program by pressing f9 key
Then go to command prompt .
C:\TURBOC>arg 3 4 5 6 7
PROGRAM FOR ADDING A LIST OF VALUES USING COMMAND LINE ARGUMENTS
Sum : 25
5. What do the ‘c’ and ‘v’ in argc and argv stand for?
6. According to ANSI specification which is the correct way of declaring main( ), when it receives
command line argument?
1. main(int argc, char *argv[ ])
2. main(argc, argv)
int argc; char *argv[ ];
3. main( )
{
int argc; char *argv[ ];
}
4. None of the above
4. The maximum length of the command line arguments including the spaces between adjacent
argument is
a. 128 characters
b. 256 characters
c. 67 characters
d. It may very from one operating system to another
Description : It is a menu driven Program which ask the user either to insert, delete, list and
modify the records from a file.
Program :
#include<stdio.h>
main()
{
FILE *fp,*ft;
char another,choice;
struct emp
{
char name[40];
int age;
float bs;
};
struct emp e;
char empname[40];
long int recsize;
fp=fopen("EMP.DAT","rb+");
if ( fp== NULL)
{
fp= fopen("EMP.DAT ","wb+");
if (fp==NULL)
{
puts("Cannot open file");
exit();
recsize= sizeof(e);
while(1)
{
gotoxy(30,10);
printf("1. Add Records");
gotoxy(30,12);
printf("2. List Records");
gotoxy(30,14);
printf("3. Modify Records");
gotoxy(30,16);
printf("4. Delete Records");
gotoxy(30,18);
printf(" 0. Exit");
gotoxy(30,20);
printf("Your choice");
fflush(stdin);
choice=getche();
switch(choice)
{
case'1':
clrscr();
fseek(fp,0,SEEK_END);
another='Y';
while( another=='Y')
{
printf("\n Enter name, age and basic sal");
scanf("%s%d%f",e.name,&e.age,&e.bs);
fwrite(&e,recsize,1,fp);
printf("\n Add another record(Y/N)");
fflush(stdin);
another= getche();
RCET / Department Of Electrical Engineering / Computer Programming Lab 145
}
break;
case'2':
clrscr();
rewind(fp);
while( fread(&e,recsize,1,fp)==1)
printf("\n%s%d%f",e.name,e.age,e.bs);
break;
case'3':
clrscr();
another='Y';
while(another=='Y')
{
printf("\n Enter name of employee to modify");
scanf("%s",empname);
rewind(fp);
while(fread(&e,recsize,1,fp)==1)
{
if (strcmp(e.name,empname)==0)
{
printf("\n Enter new name , age & bs");
scanf("%s%d%f",e.name,&e.age,&e.bs);
fseek(fp,recsize,SEEK_CUR);
fwrite(&e,recsize,1,fp);
break;
}
}
printf("\nModify another record(Y/N)");
fflush(stdin);
another=getche();
}
break;
RCET / Department Of Electrical Engineering / Computer Programming Lab 146
case'4':
clrscr();
another='Y';
while( another=='Y')
{
printf("\n Enter name of employeeto delete");
scanf("%s", empname);
ft=fopen("TEMP.DAT","wb");
rewind(fp);
while(fread(&e,recsize,1,fp)==1)
{
if (strcmp(e.name,empname)!=0)
fwrite(&e,recsize,1,ft);
}
fclose(fp);
fclose(ft);
remove("TEMP.DAT");
rename("TEMP.DAT","EMP.DAT");
fp=fopen("EMP.DAT","rb+");
printf("Delete another record(Y/N)");
fflush(stdin);
another=getche();
}
break;
case'0':
fclose(fp);
exit();
}
}
}
1. Add Records
2. List Records
3. Modify Records
4. Delete Records
0. Exit
Your choice 1
Output
1. Add Records
2. List Records
3. Modify Records
4. Delete Records
0. Exit
Your choice
Assignment
5. Write a Program that prepares the Roll list of students. The names of students are supplied from
data file and they are written on a new file by allotting the roll numbers sequentially to the
students.
Viva-Voce Questions
6. Explain the functioning of fseek and ftell.
7. Explain rewind function.
Description :
Algorithm :
Step01. Start of Program
Step02. Input Lower limit a
Step03. Input Upper limit b
Step04. Input no. of subintervals n
Step05. h=(b-a)/n
Step06. sum=0
Step07. sum=fun(a)+4*fun(a+h)+fun(b)
Step08. for i=3;i<n;i+=2
Step09. sum+=2*fun(a+(i-1)*h)+4*fun(a+i*h)
Step10. End of loop i
Step11. Result=sum*h/3
Step12. Print output result
Step13. End of Program
Step14. Start of section fun
Step15. Temp=1/(1+(x*x))
Step16. Return temp
Step17. End of section fun
Define fn y(x)
h=(xn-x0)/n
s=y0+yn+4y1
s+=4*yi+2*yi+1
P=s*(h/3)
STOP
Output
Enter the range -
Lower Limit a - 0
Upper Limit b - 6
Enter no of subintervals – 6
Value of the internal is 1.3662
Press Enter to Exit
Description :
One member of the family of Runge–Kutta methods is so commonly used that it is often referred to
as "RK4" or simply as "the Runge–Kutta method".
Then, the RK4 method for this problem is given by the following equations:
Thus, the next value (yn+1) is determined by the present value (yn) plus the product of the size of the
interval (h) and an estimated slope. The slope is a weighted average of slopes:
In averaging the four slopes, greater weight is given to the slopes at the midpoint:
The RK4 method is a fourth-order method, meaning that the error per step is on the order of h5,
while the total accumulated error has order h4.
Algorithm :
1. Function F(x)=(x-y)/(x+y)
2. Input x0,y0,h,xn
3. n=(xn-x0)/h
4. x=x0
5. y=y0
6 For i=0,n
7. k1 = h*F(x,y)
8. k2 = h*F(x+h/2,y+k1/2)
9. k3 = h*F(x+h/2,y+k2/2)
10. k4 = h*F(x+h,y+k3)
11. k = (k1+(k2+k3)2+k4)/6
12. Print x, y
13. x = x+h
14. y = y+k
15. Next i
16. Stop
F(x,y)=(x-y)/(x+y)
Input x0,y0,h,xn
n = (xn-x0)/h
x = x0
y = y0
For i = 0,n
k1 = h*F(x,y)
k2 = h*F(x+h/2, y+k1/2)
k3 = h*F(x+h/2,y+k2/2)
k4 = h*F(x+h, y+k3)
k=(k1+2(k2+k3)+k4)/6
Print x, y
x=x+h
y=y+k
STOP
Program:
/***Program of runge kutta method***/
#include<stdio.h>
#define F(x,y) (x-y)/(x+y)
main()
{
int i,n;
float x0,y0,h,xn,k1,k2,k3,k4,x,y,k;
printf("\nENTER THE VALUES:x0,y0,h,xn:\n");
scanf("%f%f%f%f",&x0,&y0,&h,&xn);
n=(xn-x0)/h;
x=x0;
y=y0;
Output :
X=0.000000 y=1.000000
X=0.020000 y=0.980000
X=0.040000 y=0.960816
X=0.060000 y=0.942446
X=0.080000 y=0.924885
X=0.100000 y=0.908128
Description :
The Euler forward scheme may be very easy to implement but it can't give accurate
solutions. A very small step size is required for any meaningful result. In this scheme, since, the
starting point of each sub-interval is used to find the slope of the solution curve, the solution would
be correct only if the function is linear. So an improvement over this is to take the arithmetic average
of the slopes at xi and xi+1(that is, at the end points of each sub-interval). The scheme so obtained is
called modified Euler's method. It works first by approximating a value to yi+1 and then improving it
by making use of average slope.
If Euler's method is used to find the first approximation of yi+1 then
Algorithm :
1. function f(x,y)=(x-y)/(x+y)
2. input x0,y0,h,xn
3. n=((xn-x0)/h)+1
4. for i=1,n
5. y=y0+h*f(x0,y0)
6. x=x+h
7. print x0,y0
8. if x = xn then
x0 = x
y0 = y
else
9. Next i
10. Stop
F(x,y)=(x-y)/(x+y)
Input x0,y0,h,xn
For i = 1,n
y = y0+h*F(x0,y0)
x = x+h
Print x0,y0
If No
x < xn
Yes
x0 = x
y0 = y
STOP
# include<stdio.h>
# define F(x,y) (x-y) / (x+y)
main ()
{
int i,n;
float x0,y0,h,xn,x,y;
printf(“\n Enter the values: x0,y0,h,xn: \n”);
scanf(“%f%f%f%f”,&x0,&y0,&h,&xn);
n=(xn-x0)/h+1;
for(i=1;i<=n;i++)
{
y=y0+h*F(x0,y0);
x=x0+h;
printf(“\n X=%f Y=%f”,x0,y0);
if(x<xn)
{
x0=x;
y0=y;
}
}
return;
}
Output :
Enter the values: x0,y0,h,xn:
0 1 0.02 0.1
X=0.000000 Y=1.000000
X=0.020000 Y=0.980000
X=0.040000 Y=0.960800
X=0.060000 Y=0.942399
X=0.080000 Y=0.924793
X=0.100000 Y=0.907978
The Newton-Raphson Method is a powerful method of finding the roots of the function f(x), that is
the values of x for which f(x) = 0. Suppose that xold is an estimate of the root. Then a better estimate
is xnew which is defined by:
xnew = xold-f(xold)/g(xold)
This procedure is iterated until convergence is achieved, defined by |xnew – xold| < acc, where acc is
user defined accuracy.
Algorithm :
a. Print convergent
b. Print x1, f(x1), i
c. End of Program
Step 10. x0 = x1
h = f (x0 ) / d f (x0)
x1 = x0 – h
print itr, x1
# include <stdio.h>
# include <conio.h>
# include <math.h>
# include <process.h>
# include <string.h>
//.....defining formulae
void NEW_RAP();
//…..Function Declaration
void NEW_RAP()
{
// Internal Declaration Field
long float x1,x0;
long float f0,f1;
long float df0;
int i=1;
int itr;
float EPS;
float error;
}
// Finding an Approximate ROOT of Given Equation, Having –ve value
x0 = x1-0.01;
f0 = f(x0);
printf(“Enter the number of iterations : “);
scanf(“%d”,&itr);
if(fabs(f0)>f1)
{
Printf(“\n\t The root is near to %.4f\n”,x1);
}
if(f1>fabs(f(x0)))
{
Printf(“\n\t The root is near to %.4f\n”,x0);
}
X0 = (x0+x1)/2;
For(;i<=itr;i++)
{
F0=f(x0);
Df0=df(x0);
X1=x0 – (f0/df00;
Printf(“\n\t\t The %d Approximant ion to the root is : %f,I,x1”);
Error=fabs(x1-x0);
If(error<EPS)
{
Break;
}
X0=x1;
If(error>EPS)
{
Printf(“\n\n\t NOTE:-”);
Printf(“The Number Of Iteration are not sufficient ”);
}
Printf(“\n\n\n\t\t\t----------------------------------------------”);
Printf(“\n\t\t\t The Root Is %.4f ”,x1);;
Printf(“\n\t\t\t----------------------------------------------”);
}
Assignment
1. Write a Program to implement simpson’s 3/8 rule.
Viva-Voce Questions
1. Explain Newton Raphson Method.
2. Explain Euler’s equation.
3. What is Runge Kutta Method.
Description: This Program takes required input for calculating the area of a circle, triangle,
square, and rectangle.
Algorithm
Step 1 : input the length and width of a rectangle, triangle or square (ex a,b)
Step 2 : input the radius of a circle ( ex. r)
Step 3 : calculate the area of triangle using formula area = 0.5 * a * b
Step 4 : calculate the area of square using formula area = a * a
Step 5 : calculate the area of rectangle using formula area = a * b
Step 6 : calculate the area of circle using formula area = 0.5 * a * b
Step 7 : print all the results.
Step 8 : exit.
at = 0.5 * a * b
as = a * a
ar = a * b
ac = 3.14*r * r
Stop
Input :
Enter sides-4.5 , 5
Enter radius- 3.2
Output :
Area of triangle=11.250000
Area of rectangle=22.500000
Area of square=20.25000
Area of circle=32.153603
Algorithm
Start
Stop
Input :
Enter age - 21
Enter Name of the student - shubham
Output :
Name of the student is shubham and age is 21
Aim-. Write a Program to find the average of three marks of students & calculate the
percentage.
Description-This program takes the marks of the student as input and stored the marks in an
array and calculate the average of marks.
Algorithm
Start
Calculate percentage
Stop
for(i=0;i<3;i++)
{
printf("\n enter marks of %d subject out of 100",+1);
scanf("%f", &m[i]);
sum=sum+m[i];
}
p =(sum/300)*100;
av=sum/3;
printf("\n average marks=%f percent=%f",av,p);
getch();
}
Input :
enter marks of 1 subject out of 100-75
enter marks of 2 subject out of 100-79
enter marks of 3 subject out of 100-71
Output :
average marks =75 percent =75
Description- this program takes one string as input and check weather it is palindrome or not.
Algorithm :
Step 5 : Exit.
Is
beg<=back)
&& flag=1
Is str[beg] == str[back]
Flag = 1
Flag = 0
Print “Palindrome”
Print “Not
Palindrome”
Stop
Stop
Input :
enter the string madam
Output :
yes it is palindrome
RCET / Department Of Electrical Engineering / Computer Programming Lab 173
Experiment No. 42
Description:
In this Program variable n represents the number whose factorial is to be found and f represents the
factorial of n. The variable f is initialized to 1 and then multiplied by the loop control variable i, n
times. When the value of i becomes greater than n, the control exits the loop.
Algorithm:
Step1: Read n
Step2: Print 1. for Factorial, 2. for Prime and Not prime, 3. for Odd and Even
Step3: If the user inputs 1
a. Initialize f = 1, i =1
b. Repeat steps c, d while i<=n
c. Multiply the present value of i with f and store it in f.
d. Increment the current value of i by 1.
e. Print f
Step4: If the user inputs 2
a. Initialize f = 0, i=1
b. Repeat steps while i<=n
c. Divide n by i
d. If the remainder is zero, increment value of f by 1.
e. Increment the value of i by 1.
f. If the value of f = 2, print “Number is prime” otherwise goto step h.
g. Print “Number is not prime”.
Step5: If the user inputs 3
a. Divide n by i.
b. If the remainder is zero, print “Number is Even” otherwise goto step c.
c. Print “Number is Odd”.
f=0, i=1
i=1
False
Is
i<=n
True
i=i+1
f=f*i
Print value of f,
factorial of n
Stop
f=0, i =2
For(i=2,i<=n/2;i++)
Is n%i
==0
f = 1 , break
END FOR
Is f == Print number is
1 Prime
Stop
Enter a number in n
True Is False
n%2=0
Print number n is
Print number n is odd
even
Stop
Input :
Enter a Number:
5
********* MENU *********
1. Find Factorial
2. Check prime or not
3. Check even or odd
Output:
Factorial of 5 = 120
Aim: Write a program to calculate the area & perimeter of the rectangle and the area &
circumference of the circle. The length and breadth of a rectangle and radius of a circle are input
through keyboard.
Description:
This program takes length and breadth of a rectangle, radius of circle as input. Calculates the area of
rectangle and circle. Perimeter of rectangle and circumference of circle.
Algorithm:
Start
Read l, b, r
Rec_area = l * b
peri_area = l * b
cir_area = l * b
cir_cum = l * b
Print rec_area,
rec_peri,
cir_area,
cir_cum
Stop
RCET / Department Of Electrical Engineering / Computer Programming Lab 180
Program:
#include<stdio.h>
#include<conio.h>
#define PI 3.14
void main()
{
float l, b, r;
float rec_area, cir_area, rec_peri, cir_cum;
printf(“Enter Length and Breadth of the Rectangle:\n”);
scanf(“%d%d”, &l, &b);
rec_area = l * b;
rec_peri = 2 * (l + b);
printf (“Enter Radius of Circle:\n”);
scanf(“%d”, &r);
cir_area = PI * r * r;
cir_cum = 2 * PI * r;
printf (“Area of Rectangle = %f”, rec_area);
printf (“Perimeter of Rectangle = %f”, rec_peri);
printf (“Area of Circle = %f”, cir_area);
printf (“Circumference of Circle = %f”, cir_cum);
getch ();
}
Input:
Output:
Area of Rectangle = 120
Perimeter of Rectangle = 46
Area of Circle = 113.04
Circumference of Circle =37.68
Aim: Write a program to determine whether the character entered through a keyboard is a capital
letter, a small case letter, a digit or a special symbol.
Description:
This program takes a character as an input using getchar() function. The functions isupper, islower,
isdigit function is used to check the entered character whether it is in uppercase, lowercase, a digit
respectively. These functions are used in the “if” statement and returns a non-zero value if the
condition is true else zero. The header file required for these functions is “ctype.h>
Algorithm:
Step1: Read ch
Step 2: Check if ch is in uppercase, print “Character is in Uppercase”, otherwise go to step3.
Step 3: Check if ch is in lowercase, print “Character is in Lowercase”, and otherwise go to step4.
Step4: Check if ch is a digit, print “Charcter is a Digit”, otherwise go to step5.
Step5: Print “Character is a Special symbol”.
Flowchart:
Start
Read ch
Is ch
in
uppe
r
Print “Character is in case
Uppercase”
Is ch
in
lowe
r
Print “Character is in case
Lowercase”
Stop
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char ch;
printf(“Enter a character to check whether it is in uppercase, lowercase, a digit or a special
symbol\n”);
getchar(ch);
if(isupper(ch))
printf(“Character is in Uppercase\n”);
else if(islower(ch))
printf(“Character is in Lowercase\n”);
else if(isdigit(ch))
printf(“Character is a Digit\n”);
else
printf(“Character is a Special Symbol\n”);
getch();
}
Input:
Enter a character to check whether it is in uppercase, lowercase, a digit or a special symbol:
B
Output:
Character is in Uppercase
Input:
Enter a character to check whether it is in uppercase, lowercase, a digit or a special symbol
v
Output:
Character is in Lowercase
Input:
Enter a character to check whether it is in uppercase, lowercase, a digit or a special symbol
5
Output:
Character is a Digit
Aim: Write a program to add first seven terms of the following series using looping statements
series is
Description:
In this program ‘i’ and ‘j’ are the loop variables. Variable ‘f’ is initialized to 1 and is used to store
the factorial of ‘i’ after calculation. ‘sum’ is the variable initialized to zero and finally after 7 times
executing the loop sum of the series is stored in ‘sum’.
Algorithm :
f=1,sum=1,i=1,j=1
For(i=1,i<=n;i++)
For(j=1,j<=i;i++)
F=f*i
END FOR
s = s + 1/f
END FOR
Stop
Input:
Enter the value of n 7
Output:
Sum of Series = 2.721