Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Functions and Passing Variables by Reference

Example 1

Example 2

Example 3

Example 1

#include "stdafx.h"

#include<iostream>

using namespace std;

void demonstrate(int & a);

 

int main()

{

            int remember = 0;

            for (int i = 1; i<5;i++)

            {

                        demonstrate(remember);

            }

            cout<<"The value of remember is now "<<remember<<endl;

            return 0;

}

void demonstrate(int & a)

{

            a = a++;

}

Example 2

What is the output?    answer

#include "stdafx.h"

#include <iostream>

using namespace std;

 

int functionOne(int a);

void functionTwo(int &b);

void functionThree(int c);

 

int main()

{

      int a = 7;

      int b = 8;

      int c = 9;

    functionOne(a);

      cout<<"The value of a is now: " <<a<<endl;

      functionTwo(b);

      cout<<"The value of b is now: "<<b<<endl;

      cout<<"The value of c is now: "<<c<<endl;

      return 0;

}

int functionOne(int a)

{

  a = 10*a;

  return a;

}

void functionTwo(int &b)

{

   b = 10*b;

   functionThree(b);

}

void functionThree(int c)

{

   c = 10*c;

}

 

Example 3      answer

#include "stdafx.h"

#include <iostream>

using namespace std;

void demonstrate(int &number);

 

int main ()

{

      int age = 17;

      cout<<"The value of age is: "<<age<<endl;

      cout<<"The address where the variable age is stored is: "<<&age<<endl;

      demonstrate(age);

      cout<<"Value of age is now: "<<age<<endl;

      return 0;

}

void demonstrate(int &number)

{

    number = 4*number; 

}