60-140

Introduction to Algorithms and Programming I

Dr. Christie Ezeife

Lab. Exercises  #3 (Lab Date:  Week 5 of Classes)

Objectives are to:

1.                                          Practise on solving problems using top-down design approach by writing algorithms and programs with functions as taught in chapter 4 of text book.

2.                                         Feel comfortable with such concepts as: function prototypes, function call, function definition, call-by-value parameters, call-by-reference parameters, formal and actual parameters, local and global variables, structure and flowcharts, cohesion and coupling, variable scoping rules. 

Continue to prepare for Quiz #1 if not yet written

Que. 1.    Given the following program, show the values of the variables a, b, c, x, y, z in the main function after each function call to FindSum. Also, show the values of a, b, c in FindSum immediately after executing each function call to FindSum.

#include <stdio.h

/*   function prototype declaration for FindSum   */

void FindSum(int, int, int *);

int main(void)
{

int a=2, b=5, c=1, x=3, y=4, z=7; 

/*   body of main   */

  FindSum (a, b, &c);    /* a first call to FindSum   */ 
  printf(“first call in main %d  %d  %d  %d  %d  %d \n”, a, b, c, x, y, z); 

  FindSum (x, y, &z);    /* a second call to FindSum   */
 printf(“second call in main %d  %d  %d  %d  %d  %d \n”, a, b, c, x, y, z); 

  return  0;

}

 

/*   definition of FindSum   */

void FindSum (int a, int b, int *c)
{

  a += (b * 2);
  b += (b * 2);
*c += (b * 2);

  printf(“in FindSum: %d  %d  %d \n”, a, b, *c); 

}

Hints on how to solve

 i.                     First trace the above program with hand and write the values of the variables a, b, c, x, y, z in the main function after each function call to FindSum.

Also, record the values of variables a, b, c in FindSum immediately after executing each function call to FindSum.

In main

    a

    b

   c

   x

    y

  z

After 1st call to FindSum

 

 

 

 

 

 

After 2nd call to FindSum

 

 

 

 

 

 

 

In FindSum

a

b

*c

After 1st call to FindSum

 

 

 

After 2nd call to FindSum

 

 

 

 

ii.                   Then, type in the program, compile and run to compare the results of your trace with that of your run.
If the two results do not match, talk to your lab instructor or GA for help 

Que. 2.       a) Question is: What is meant by the scope of a variable?
b) Give the variable scoping rules
c) Why is the use of parameters preferred over the use of global variables?

Que. 3.    Do question 1 of Section 4.6.