Lab 24dec 56C

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

FUNCTIONS - ARGUMENTS PASSING BY REFERENCE/VALUE

MODIFYING GLOBAL/LOCAL VARIABLES

Every variable has an address. Sometimes we need to pass address of variable. Address can be
accessed by ‘&’ called ampersand sign. Reference provide alias for variable. When we provide
argument by value, the called function creates a new variable of same type as the argument and
copies the argument’s value into it. Passing arguments by value is useful when function does not
need to modify original variable in the calling program. When reference is passed, the actual
address of variable is passed as arguments to function. Function can access the actual variables
in the calling program.

Example:
ref.cpp
// demonstrates passing by reference
#include <iostream>
int main()
{
void intfrac(float, float&, float&); //declaration
float number, intpart, fracpart; //float variables
do {
cout << “\nEnter a real number: “; //number from user
cin >> number;
intfrac(number, intpart, fracpart); //find int and frac
cout << “Integer part is “ << intpart //print them
<< “, fraction part is “ << fracpart << endl;
} while( number != 0.0 ); //exit loop on 0.0
return 0;
}
//--------------------------------------------------------------
// intfrac()
// finds integer and fractional parts of real number
void intfrac(float n, float& intp, float& fracp)
{
long temp = static_cast<long>(n); //convert to long,
intp = static_cast<float>(temp); //back to float
fracp = n - intp; //subtract integer part
}
Output
Enter a real number: 99.44
Integer part is 99, fractional part is 0.44
Exercise Questions:

1. Write a program having just one function. It should take value from user in length;
function can convert the length in centimeters, meters, inches and feet. Program should
display all the values.

2. Write a program that will illustrate the use of a function for computing the square of a
number. There must be three other functions aside from main ( ). The first function must be
responsible for inputting the data the second for computation of squares and the third, for
displaying the result.

Sample Run:

Input N: 3

The square of 1 is 1

The square of 2 is 4

The square of 3 is 9

3. Using Call By Reference define function swap(), which exchanges the values of the two
integer variables pointed to by its arguments.

Sample Run:

Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :200

After swap, value of b :100

4. Comment on the output of the following C++ code?


1. #include <iostream>
2. using namespace std;
3. void Sum(int a, int b, int & c)
4. {
5. a = b + c;
6. b = a + c;
7. c = a + b;
8. }
9. int main()
10. {
11. int x = 2, y =3;
12. Sum(x, y, y);
13. cout << x << " " << y;
14. return 0;
15. }

You might also like