Programming Lab Manual EC213

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Department of ECE, Integral University

Programming Lab (EC213)

List of Experiments

Mode
Planned Actual
S. No. List of Experiments (s) (Lab
teaching teaching
/virtual lab
hours hours
/study)
Write a program in C/C++ to accept a number and print 2 2 eLab on
1
the factorial of a number. i) for n<8 and, ii). for n>8. ILI

Write a program in C/C++ to display Prime Numbers 2 2 eLab on


2
between 0 and 100. ILI

Write a program in C/C++ to display the following 2 2 eLab on


patterns: ILI
3 a. @ b. 1 c. 1 d ****
@@ 12 22 ***
@@@ 123 333 **
@@@@ 1234 4444 *
Write a program in C/C++ to display first 'n' terms of the 2 2 eLab on
4
ILI
fibonacci series
Write a menu driven program in C/C++ to make a simple 2 2 eLab on
5
ILI
calculator using switch case
Write a program in C/C++ to accept 'n' numbers in an 2 2 eLab on
6 array and sort them in ascending order using Bubble Sort ILI
Technique.
Write a program in C/C++ to accept two NxN (Square) 2 2 eLab on
7
ILI
matrices and display their product in a third matrix.
Write a program in C/C++ to accept a name or string and 2 2 eLab on
8
ILI
display its reverse. Also check if it is a palindrome or not.
Write a program in C/C++ using Recursive Techniques to 2 2 eLab on
9 find the minimum number of moves to solve the classical VLAB
puzzle of Towers of Hanoi.
Write a program C/C++ using Functions to find the area 2 2 eLab on
of the figure shown below upto 2 decimal places. VLAB

10

Dr. Piyush Charan, Assistant Professor Page 1


Department of ECE, Integral University
Programming Lab (EC213)

Experiment 1
Object: (a). Write a program in C/C++ to display the factorial of a number if n<8.
(b). Write a program in C/C++ to display the factorial of a number if n>8.

Sample program (a)


#include <stdio.h>
#include <conio.h>
void main()
{
int n, i, fact +1;
clrscr();
printf (“enter a number =”);
scanf (“ %d”, & n);
for (i=n; i>=1; ;i-- )
fact=fact*i;
printf (“the factorial of %d=%d” , fact);
getch();
}
Output:
Enter a number=5
The factorial of 5=120

Algorithm

Step 1: START
Step 2: long int n, i fact // variable declaration of numeric type for numbers and log p.
Step 3: enter the value of n
Step 4: input n
Step 5: [Initialize] i=n, fact =1
Step 6: Repeat steps 6 through 8 until i>=1
Step 7: fact=fact*i
Step 8: i=i-1
Step 9: display fact
Step 10: STOP

Flowchart:

Dr. Piyush Charan, Assistant Professor Page 2


Department of ECE, Integral University
Programming Lab (EC213)

Sample program 1 (b)


#include <stdio.h>
#include <conio.h>
void main()
{
long int n, i, fact +1;
clrsscr();
printf (“enter a number =”);
scanf (“ %ld”, & n);
for (i=n; i>=1; ;i-- )
fact=fact*i;
printf (“the factorial of %ld=%ld” , n fact);
getch ();
}
Output:
Enter a number=8
The factorial of 8=40320

Algorithm

Step 1: START
Step 2: long int n, i fact // variable declaration of numeric by pe for nos. And
Step 3: enter the value of n
Step 4: input n
Step 5: [Initialize] i = n, fact=1
Step 6: Repeat steps 6 through 8 until i>=1
Step 7: fact=fact*i
Step 8: i=i-1
Step 9: display fact
Step 10: STOP

Flowchart:

Dr. Piyush Charan, Assistant Professor Page 3


Department of ECE, Integral University
Programming Lab (EC213)

Experiment 2
Object: Write a program in C/C++ to display all prime numbers between 0 and 100
Sample program
#include <stdio.h>
#include <conio.h>
void main()
{
int i, j, c=0;
clrscr();
printf("the required prime
number between 0 and 100
are=\n");
for (i=1;i<=100;i++)
{
for (j=1;j<=i;j++)
{
if(i%1==0 && i%j==0)
c++;
}
if (c==2)
printf ("%d\t", i);
c=0;
}
getch ();
}

Output:
Required prime number between 0 and 100
2 3 5 7 11 13 17 19 23 29 31 37
41 43 47 53 59 61 67 71 73 79 83 89
97

Algorithm:

Step 1: START
Step 2: int i, j,c,
Step 3: Display “required prime numbers between 0and 100”
Step 4: [Initialize] i = 0, c=0
Step 5: repeat step 5 through step 14 until i<=100
Step 6: [Initialize] j= 1

Dr. Piyush Charan, Assistant Professor Page 4


Department of ECE, Integral University
Programming Lab (EC213)

Step 7: repeat step 7 through step 10 until j<=i


Step 8: if (i % 1= = 0 && i% j = = 0)
Step 9: c= c+1.
Step 10: j = j + 1
Step 11: if (c = = 2)
Step 12: display i
Step 13: [Initialize] c= 0
Step 14: i = i + 1
Step 15: STOP

Dr. Piyush Charan, Assistant Professor Page 5


Department of ECE, Integral University
Programming Lab (EC213)

Experiment 3
Object: Write a program in C/C++ to display the fallowing pattern:
(a) @ (b) 1
@ @ 1 2
@ @ @ 1 2 3
@ @ @ @ 1 2 3 4

Sample program 4(a)


#include <stdio.h>
#include <conio.h>
void main ()
{
int i, j, n;
clrscr();
printf("Enter no of rows n=");
scanf ("%d",&n);
for (i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
getch();
}

Output: Enter no. of rows n= 4


(a) @
@ @
@ @ @
@ @ @ @
Algorithm:

Step 1: START
Step 2: int i, j,n
Step 3: Display “Enter the no. of rows=”
Step 4: Accept n

Dr. Piyush Charan, Assistant Professor Page 6


Department of ECE, Integral University
Programming Lab (EC213)

Step 5: [Initialize] i= 1
Step 6: Repeat steps 6 through 12 until i<=n
Step 7: [Initialize] j= 1
Step 8: Repeat steps 8 through 10 until j<=i
Step 9: Display “ @ ”
Step 10: j = j + 1
Step 11: Display” \ n “
Step 12: i = i + 1
Step 13: STOP

Sample program 4(b)


#include <stdio.h>
#include <conio.h>
void main ()
{
int i, j, n;
clrscr();
printf("Enter no of rows
n=");
scanf ("%d",&n);
for (i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",j);
}
printf("\n");
}
getch();
}

Output: Enter no. of rows n= 4


1
1 2
1 2 3
1 2 3 4

Dr. Piyush Charan, Assistant Professor Page 7


Department of ECE, Integral University
Programming Lab (EC213)

Algorithm:

Step 1: START
Step 2: int i, j,n
Step 3: Display “Enter the no. of rows=”
Step 4: Accept n
Step 5: [Initialize] i= 1
Step 6: Repeat steps 6 through 12 until i<=n
Step 7: [Initialize] j= 1
Step 8: Repeat steps 8 through 10 until j<=i
Step 9: Display j
Step 10: j = j + 1
Step 11: Display “\n”
Step 12: i = i + 1
Step 13: STOP

Dr. Piyush Charan, Assistant Professor Page 8


Department of ECE, Integral University
Programming Lab (EC213)

Experiment 4
Object: Write a program in C/C++ to display first 'n' terms of the fibonacci series
Sample Program
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i , t1=0, t2=1, next_term;
clrscr();
printf("Enter the number of terms
required=");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
printf("\n%d",t1);
next_term=t1+t2;
t1=t2;
t2=next_term;
}
getch();
}

Theory:
Fibonacci series is a series in which each number is the sum of preceding two
numbers. For Example fibonacci series for first 7 terms will be 0,1,1,2,3,5,8.

Dr. Piyush Charan, Assistant Professor Page 9


Department of ECE, Integral University
Programming Lab (EC213)

Algorithm:

Step 1: Start.
Step 2: int n, i, t1, t2, next_term
Step 3: [Initialize] t1=0, t2=1
Step 4: Accept n //The number of terms of fibonacci series required
Step 5: [Initialize] i=1
Step 6: Repeat steps 6 to 12 until i<=n
Step 7: Display new line //Display "\n"
Step 8: Display t1
Step 9: next_term= t1+t2
Step 10: t1=t2
Step 11: t2=next_term
Step 12: i=i+1
Step 13: Stop.

Output:

Flowchart:

Dr. Piyush Charan, Assistant Professor Page 10


Department of ECE, Integral University
Programming Lab (EC213)

Experiment 5
Object: Write a program menu drive program in C/C++ to make a simple calculator using
switch case
Sample program
#include <math.h>
#include <stdio.h>
#include <conio.h>
void main ()
{
int ch;
float a, b, add, mul ,sub, div, exp;
clrsscr();
printf (“enter the value of a=”);
scanf(“%f”, &a);
printf (“enter the value of b=”);
scanf(“%f”, &b);
printf (“\n select your choice from the menu”);
printf (“\1 addition);
printf (“\2 subtraction);
printf (“\3 multiplication);
printf (“\4 division);
printf (“\5 exponentiation);
printf (“\ enter your choice=);
scanf(“%d”, &ch);
swith(ch)
{
case1: add=a+b;
printf(“sum of %f and % f=%f”,a , b, add);
break;
case 2: sub=a-b;
printf(“the difference of %f and % f=%f”,a , b, sub);
break;
case 3: mul=a*b;
printf(“multiplication of %f and % f=%f”,a , b, mul);
break;
case 4: div=a/b;
printf(“division of %f and % f=%f”,a , b, div);
break;
Dr. Piyush Charan, Assistant Professor Page 11
Department of ECE, Integral University
Programming Lab (EC213)

case 5: exp=pow(a,b);
printf(“exponentiation of %f raised to the power of % f=%f”,a , b, exp);
break;
default: printf(“try again: wrong choice”);
break;
}
getch ();
}

Algorithm:

Step 1: START
Step 2: float a, b, add, mul, sub, div, exp int ch
Step 3: Input a
Step 4: Accept a
Step 5: Input b
Step 6: Accept
Step 7: select your choice from menu display given message
Step 8: display
1 Addition
2 Subtraction
3 Multiplication
4 Division
5 Exponentiation
Step 9: Enter choice
Step 10: Pass the choice into switch case
Step 11: In case 1, Addition a & b and print result
Step 12: In case 2, Subtraction a & b and print result
Step 13: In case 3, Multiplication a & b and print result
Step 14: In case 4, Division a & b and print result
Step 15: In case 5, take exponentiation of a & b and print result
Step 16: STOP

Dr. Piyush Charan, Assistant Professor Page 12


Department of ECE, Integral University
Programming Lab (EC213)

Output:
Enter the value of a=3
Enter the value of b=4
Select your choice from the menu
1 Addition
2 Subtraction
3 Multiplication
4 Division
5 Exponentiation
1↩
sum of 4 and 3=7

Dr. Piyush Charan, Assistant Professor Page 13


Department of ECE, Integral University
Programming Lab (EC213)

Experiment No. 6
Object:- Write a program in C/C++ to accept 'n' numbers in an array and sort them in
ascending order using Bubble Sort Technique.

Sample Programs
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50], n, i, j, temp;
clrscr();
printf("Enter the size of array=");
scanf("%d", &n);
printf("Enter the elements in the
array: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
//Sorting Logic
printf("The Sorted Array in
Ascending order is ");
for(i=0;i<=(n-2);i++)
{
for(j=0;j<=(n-2)-i;j++)
{
if (a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
//Printing Sorted Array Logic
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
getch();
}

Dr. Piyush Charan, Assistant Professor Page 14


Department of ECE, Integral University
Programming Lab (EC213)

Theory:
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them if they
are not in the intended order.
This Program sorts the numbers in ascending order using bubble sort. Bubble sort is a
simple sorting algorithm that works by repeatedly stepping through the list to be sorted,
comparing each pair of adjacent items and swapping them if they are in the wrong order. Here
we need to sort a number in ascending order
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.

Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and
swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed.
The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Flowchart:

Dr. Piyush Charan, Assistant Professor Page 15


Department of ECE, Integral University
Programming Lab (EC213)

Experiment No. 7
Object:- Write a program in C to accept two NxN (Square) matrices and display their
product in a third matrix.

Sample Programs

#include <stdio.h>
#include<conio.h>
int main()
{
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;

printf("Enter rows and column for first matrix: ");


scanf("%d %d", &r1, &c1);

printf("Enter rows and column for second matrix: ");


scanf("%d %d",&r2, &c2);

// Column of first matrix should be equal to column of second matrix and


while (c1 != r2)
{
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
}

// Storing elements of first matrix.


printf("\nEnter elements of matrix 1:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}

// Storing elements of second matrix.


printf("\nEnter elements of matrix 2:\n");
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)

Dr. Piyush Charan, Assistant Professor Page 16


Department of ECE, Integral University
Programming Lab (EC213)

{
printf("Enter elements b%d%d: ",i+1, j+1);
scanf("%d",&b[i][j]);
}

// Initializing all elements of result matrix to 0


for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
result[i][j] = 0;
}

// Multiplying matrices a and b and


// storing result in result matrix
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
result[i][j]+=a[i][k]*b[k][j];
}

// Displaying the result


printf("\nOutput Matrix:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
printf("%d ", result[i][j]);
if(j == c2-1)
printf("\n\n");
}
return 0;
}

Algorithm:

Step 1: Start.
Step 2: Enter the row and column of the first (a) matrix.
Step 3: Enter the row and column of the second (b) matrix.
Step 4: Enter the elements of the first (a) matrix.
Step 5: Enter the elements of the second (b) matrix.
Step 6: Print the elements of the first (a) matrix in matrix form.
Step 7: Print the elements of the second (b) matrix in matrix form.

Dr. Piyush Charan, Assistant Professor Page 17


Department of ECE, Integral University
Programming Lab (EC213)

Step 8: Set a loop up to row.


Step 9: Set an inner loop up to the column.
Step 10: Set another inner loop up to the column.
Step 11: Multiply the first (a) and second (b) matrix and store these in the third matrix (c)
Step 12: Print the final matrix.
Step 13: Stop.

Output:

Enter rows and column for first matrix: 3


2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of second.

Enter rows and column for first matrix: 2


3
Enter rows and column for second matrix: 3
2

Enter elements of matrix 1:


Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
Enter elements a22: 0
Enter elements a23: 4

Enter elements of matrix 2:


Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4

Output Matrix:
24 29

6 25

Dr. Piyush Charan, Assistant Professor Page 18


Department of ECE, Integral University
Programming Lab (EC213)

Flowchart:

Dr. Piyush Charan, Assistant Professor Page 19


Department of ECE, Integral University
Programming Lab (EC213)

Experiment 8
Object: Write a program in C/C++ to accept a name or string and display its reverse.
Also check if it is a palindrome or not.

Sample program 8
#include<stdio.h>
#include<conio.h>
void main()
{char a[50],b[50]={'\0'};
int i,j,count=0,flag=1;
clrscr();
printf("Enter a string or name\n");
scanf("%s",& a);
for(i=0;a[i]!='\0';i++)
{
count++;
}
for(i=0,j=count-1;i<count;i++,j--)
{
b[i]=a[j];
}
printf("Reversed Name=%s\n",b);
for(i=0;i<count;i++)
{
if(b[i]!=a[i])
flag=0;
}
if(flag==1)
printf("%s is a palindrome",a);
else
printf("%s is not a palindrome",a);
getch();
}

Theory:
In C programming, a string is simply an array of characters which is always terminated by a null
character. There are many applications and operation of strings in programming of higher level
language. To reverse a string without using the library function is a popular tutorial on string in

Dr. Piyush Charan, Assistant Professor Page 20


Department of ECE, Integral University
Programming Lab (EC213)

C programming. In this tutorial post, we are going to discuss C program to Reverse a String
along with its algorithm, source code, and sample output.
The basic working principle to reverse a string in C programming is to swap the position
of array element i.e. exchange of the position in character array. As the last element in string is a
null character, the first element of array is swapped with the second last element of array. The
exchanged elements are stored and finally printed as console output.

Algorithm:

Step 1: START
Step 2: Declare all the variables ( integer and character type )
Step 3: Enter the string to be reversed
Step 4: Find out the length of string
Step 5: Swap the position of array element using loop
Step 6: Store the swapped position
Step 7: Print the reversed string as console output
Step 8: Stop

Flowchart:

Dr. Piyush Charan, Assistant Professor Page 21


Department of ECE, Integral University
Programming Lab (EC213)

Experiment No. 9

Object :- Write a program in C/C++ using Recursive Techniques to find


the minimum number of moves to solve the classical puzzle of Towers
of Hanoi.
(a). To understand that some problems can be broken down into
smaller similar problems.
(b). To solve such problems using recursive procedures.

Theory :-
• Recursion is a process in which a function calls itself as a
subroutine from the definition of the same function. This allows
the function to be repeated several times, since it calls itself during
its execution. Functions that incorporate recursion are
called recursive functions.
• Recursion is often seen as an efficient method of programming
since it requires the least amount of code to perform the necessary
functions. However, recursion must be incorporated carefully,
since it can lead to an infinite loop if no condition is met that will
terminate the function.
• Sometimes solving a big problem may require us to solve smaller
problems of similar nature. For example, computing the x th number
in the Fibonacci sequence may require us to find the x-1th and the
x-2th numbers in the sequence. If we are able to break the main
problem into smaller instances of the same problem again and
again, so that eventually the smaller problems become trivial, then
we can use the solutions to the trivial problems to progressively
build bigger solutions. Consequently, we can reach the solution of

Dr. Piyush Charan, Assistant Professor Page 22


Department of ECE, Integral University
Programming Lab (EC213)

our main problem. This concept when used in coding is called


recursion.
• For writing a recursive code for a problem, we simply call a
function inside the definition of the same function.
Let us consider the problem of finding the factorial of a number
using recursive techniques:
• Recursion simply means applying a function as a part of the
definition of that same function. Suppose we have to find the
factorial of a number. The mathematical factorial function is
defined as being the product of all the numbers up to and including
the number, and the factorial of 1 is 1. Thinking about this, we see
that another way to express this is that the factorial of N is equal to
N times the factorial of (N-1).
Thus:
1! = 1 2! = 1 × 2 = 1! ×2 3! = 1 × 2 × 3 = 2! × 3 = 6 --- --- N! = 1 ×
2 × 3 × .... (N-2) × (N-1) × N = (N-1)! × N
So we can express this as:

• factorial(n): return n == 0 ? 1 : n * factorial(n-1)

• The important thing to remember when creating a recursive


function is to give an 'end-conditions' or the 'base cases'. We don't
want the function to keep calling itself forever, do we? Somehow,
it should know when to stop. So, we give it a base case. Like here
the base case is for n=1. The key to making this work is that there
must be a terminating condition such that the function branches to
a non-recursive solution at some point.
Hence a feasible recursive solution will have the following two
properties:

Dr. Piyush Charan, Assistant Professor Page 23


Department of ECE, Integral University
Programming Lab (EC213)

 A simple base case (or cases), and


 A set of rules which reduce all other cases toward the base case.

Introduction:-
Tower of Hanoi is a mathematical puzzle where we have three rods
and n disks. The objective of the puzzle is to move the entire stack
to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the
stacks and placing it on top of another stack i.e. a disk can only
be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
Procedure:-
(i). Select the value of N (values must me greater than 1 and less
than or equal to 5).
(ii). Press next to see the execution of the code.
(iii). Relevant line in the code is shown here.
(iv). The output of the code is shown in the right.
Further Reading:-
http://www.tech-faq.com/recursion.html
http://en.wikipedia.org/wiki/Recursion_(computer_science)

Dr. Piyush Charan, Assistant Professor Page 24


Department of ECE, Integral University
Programming Lab (EC213)

Simulation :-
Step 1: Enter the number of disks in Tower 1 as n=3 and click start.

Step 2: Click on next button successively to execute line by line start.

Dr. Piyush Charan, Assistant Professor Page 25


Department of ECE, Integral University
Programming Lab (EC213)

Step 3: Repeat step 2 until all the disks from source tower is moved to
destination folder.

Program :-
C program for Tower of Hanoi using Recursion
#include <stdio.h>
void towers(int, char, char, char);
int main()
{
int num;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi
are :\n");
towers(num, 'A', 'C', 'B');
return 0;
Dr. Piyush Charan, Assistant Professor Page 26
Department of ECE, Integral University
Programming Lab (EC213)

}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg,
topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
Output :-

Result :- The program for “Tower of Hanoi” using recursive techniques


was simulated using online Virtual Lab(vlab) available at the link:
http://cse02-iiith.vlabs.ac.in/exp9/index.html and the resultant C-code
gives the expected output. This program gives the total number of moves
required to transfer ‘n’ number of disks from Tower A to Tower C,
according to the rules of the Puzzle.

Dr. Piyush Charan, Assistant Professor Page 27


Department of ECE, Integral University
Programming Lab (EC213)

Experiment No. 10

Object :- Write a program in C/C++ using Functions to find the area of


the figure shown below upto 2 decimal places.
a) To understand that a big program can be broken up into
independent modules.
b) To learn to define functions and call them with appropriate
parameters.

Dr. Piyush Charan, Assistant Professor Page 28


Department of ECE, Integral University
Programming Lab (EC213)

Theory :-
Function basically is a independent piece of code which takes some
variables as input and returns a result. The function may optionally
update the values of the input variables. Writing a function involves
clearly specifying the characteristics of the funciton in its prototype.
The prototype of a function looks like:

return_type Function_name(datatypes_of_input_variables);

For example, the prototype of a function for computing tax and


returning the total payable amount may look like:

float compute_total(float ,float );

This states that the name of the function is compute_total. It accepts two
float variables as input and returns a float value as output. Next, we
define the function by writing the code corresponding to the
computation of the return value of the function.

float compute_total(float subtotal,float tax_rate)


{ float total;
total=subtotal*(1+(tax_rate/100));
return total;
}

The input variables in this function are named subtotal and tax_rate and
both of them are of float datatype. The value which this function return
will be type casted into float before returning. This function can be
called from the main function as:

Dr. Piyush Charan, Assistant Professor Page 29


Department of ECE, Integral University
Programming Lab (EC213)

total=compute_total(1000,8);

A complete code with functions may look like this:


function_prototypes;
main()
{
function_calls;
}
function definitions;

Procedure :-
1. Click on the square to define a function for calculating the
area of a square.
2. Similarly define functions for the other geometrical figures.
3. The defined functions are shown in the middle window.
4. Now do appropriate function calls in the main program to
compute the area of the figure displayed.
5. Press execute to execute the code and see the output.

Further Reading :-
http://en.wikipedia.org/wiki/Function_(computer_science)
www.cprogramming.com/tutorial/lesson16.html
http://erwnerve.tripod.com/prog/recursion/recintro.htm

Dr. Piyush Charan, Assistant Professor Page 30


Department of ECE, Integral University
Programming Lab (EC213)

Simulation :-

Step 1 :- Open the simulation tab and read the instructions written in the
“initialize window” (on the left of the page).

Step 2 :- Click on the geometrical figures and enter the entries asked in
the “initialize window” (on the left of the page) in order to create a
function for that particular geometrical figure.

Dr. Piyush Charan, Assistant Professor Page 31


Department of ECE, Integral University
Programming Lab (EC213)

Step 3 :- After creation of function for each geometrical figure the


“initialize window” will ask to make appropriate function calls to
compute the area of the figure displayed.

Step 4 :- Pass the arguments into the function so that each function
may return the area of that particular geometrical figure for which that
respective function is created.

Dr. Piyush Charan, Assistant Professor Page 32


Department of ECE, Integral University
Programming Lab (EC213)

Step 5 :- Click on the execute button to execute the code line by line
and observe the value of area returned by each function which is
displayed in the message on the top of the screen.

Step 6 :- Click on “OK” successively to observe the value of area


returned by each of the 7 function calls.

Dr. Piyush Charan, Assistant Professor Page 33


Department of ECE, Integral University
Programming Lab (EC213)

Dr. Piyush Charan, Assistant Professor Page 34


Department of ECE, Integral University
Programming Lab (EC213)

Program :-
C program for finding area of geometrical figure using Functions
#include<stdio.h>
#include<conio.h>

Dr. Piyush Charan, Assistant Professor Page 35


Department of ECE, Integral University
Programming Lab (EC213)

#include<math.h>
float area_sq(float);
float area_rect(float,float); float area_triangle(float); float
area_circle(float); void main()
{
float totalArea;
clrscr();
totalArea=area_sq(4.0)+area_sq(6.0)+area_triangle(4.0)+area_rect(10.0,
4.0)+(area_circle(2.0)/2)+(area_circle(1.25)/2)+area_triangle(7.5);
printf("Total Area : %0.2f\n",totalArea);
getch();
}
//function for square
float area_sq(float a)
{
float area=a*a; return area;
}
//function for rectangle
float area_rect(float a,float b)
{
float area=a*b;

Dr. Piyush Charan, Assistant Professor Page 36


Department of ECE, Integral University
Programming Lab (EC213)

return area;
}
//function for triangle float area_triangle(float a)
{
float area=(sqrt(3)/4.0)*a*a; return area;
}
//function for circle
float area_circle(float a)
{
float area=3.14*a*a; return area;
}
Output :-

Result :- The program for finding area of the displayed figure using
functions was simulated using online Virtual Lab (vlab) available at the
link: http://cse02-iiith.vlabs.ac.in/exp2/index.html and the resultant C-
code gives the expected output.

Dr. Piyush Charan, Assistant Professor Page 37

You might also like