CSI Pract7 8
CSI Pract7 8
C++ Programming
Practical No. 7
Aim
: To study the function calling methods.
Problem statement
Write a program in c++ to exchange the variables
using the call by reference method of calling
functions.
Enter the program and verify the execution of the
same on the computer.
C++ Program to exchange the contents of two variables using call by value
#include<iostream.h>
void main( )
{
int a,b;
void swap(int , int );
cout<<”Enter two values “;
cin>>a>>b;
cout<<”The Original values are “<<a<<”\t”<<b<<endl;
swap(a,b);
cout<<”The Exchanged values are “<<a<<”\t”<<b<<endl;
}
void swap( int x, int y)
{
int t;
t=x;
x = y;
y = t;
}
Sinhgad_JR_CS_DEPT_TG_C++_ 4
C++ Program to exchange the contents of two variables using call by
reference.
#include<iostream.h>
void swap(int * , int *);
void main( )
{
int a,b;
•In Call by value, a copy of the variable is passed whereas in Call by reference, a
variable itself is passed.
•In Call by value, actual and formal arguments will be created in different
memory locations whereas in Call by reference, actual and formal arguments
will be created in the same memory location.
•Call by value is the default method in programming languages like C++, PHP,
Visual Basic NET, and C# whereas Call by reference is supported only Java
language.
Problem statement
Write a program in c++ to calculate the factorial
of a number using the recursive function.
Enter the program and verify the execution of the
same on the computer.
// Factorial of n = 1*2*3*...*n
#include <iostream.h>
int factorial(int);
void main()
{ int n, result;
cout << "Enter a non-negative number: "; Output
cin >> n; Enter a non-negative number: 4
Factorial of 4 = 24
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
}
int factorial(int n)
{
if (n > 1) Logic of the program
{ return n * factorial(n - 1); }
else
{
return 1;
}
}
Recursive Function