Function Homework

 

 

1.  Show what is printed by the following program.

 

#include <iostream.h>

int mix(int a, int& b);

 

void main()

{

int k = 4, p = 4, ans;

ans = mix(k,p);

    cout<<"k = "<< k <<" p = " << p << " ans = " <<ans<<endl;

   

  k = 3  

  ans = mix(p,k);

  cout<<"k = " << k <<" p = " << p << " ans = " <<ans<<endl;

    

}

 

int mix(int a, int& b)

{

     int j, sum = 0;

     b = 3;

    

     for (j = 1; j <= a; j++)

          sum += j * b;

 

     cout<< endl <<"in mix: a = "<< a <<" b = "

            << b << " sum = " << sum << endl;

     return sum;

}

 

 

2. Answer each of the following questions based on the following C++ program. Show how the variables change value.

 

#include <iostream.h>

 

void fun(int& , int );

float num = 3.2;

 

void

main()

{

    int p, q, r;

 

    p = 5;

    q = 10;

    r = 15;

    cout << "In main: num is " << num << endl;

    cout << "In main: p  = " << p << " q = " << q 

             << " r = " << r << endl;

    fun(r,p);

    cout << "In main: p  = " << p << " q = " << q 

             << " r = " << r << endl;

    cout << "In main: num is " << num << endl;

}

 

void

fun(int& m, int n)

{

    int o;

    ++n;

    o = n + m;

    ++m;

    cout << "In fun: num is " << num << endl;

    cout << "In fun: m = " << m << " n = " << n

                 << " o = " << o << endl;

    num = 22.4;

    cout << "In fun: num is " << num << endl;

}

 

a) The variable that is global to both main and fun is _________.

 

b) The variable local to fun is ______________________________.

 

c) The reference parameter in fun is?_____________________________

 

d) What is printed by the above program?

 

 


3. Show exactly what is printed by the following program.

 

#include <iostream.h>

void sub (int m, int n);

 

void main( )

{

int p, q, r;

 

     p = 5;

     q = 10;

     r = 15;

     cout <<  "\nIn main: p  =  " << p << 

" q =  " << q  << " r =  " << r;

     sub(r, p);

     cout <<  "\nIn main: p  =  " << p     

<<  " q =  " << q  << " r =  " << r;

     sub(q, r);

     cout <<  "\nIn main: p  =  " << p <<  "

q =  " << q  << " r =  " << r;

}

 

void sub (int m, int n)

{

int o;

    

     n++;

     o =  m + 2;

     m++;

     cout <<  "\nIn sub: m  =  " << m << 

" n =  " << n  << " o =  " << o;

}