Challenge 18

Description

The purpose of this challenge is to pass pointers as function parameters. This challenge illustrates the use of the dereferencing operator as well as the relationship between pointers and arrays.

History

In the 1700s, Johann Carl Friedrich Gauss was a young boy in grade school. For disrupting his class, his teacher gave him a mathematical task to keep him occupied for a while. Gauss solved the problem almost instantly.

His task was to sum up all integer numbers from 1 and 100. He wrote the numbers 1 to 100 and lined it up with the numbers going in reverse from 100 to 1. He broke the task down as follows:

1 + 100 = 101
2 + 99  = 101
3 + 98  = 101

99 + 2  = 101
100 + 1 = 101
101 * 100 = 10100

Noting that this method was actually double the result, he simply divided the number by 2 to arrive at 5050.

Requirements

  1. Create two integer arrays, int forward[100], int backward[100]
  2. Write a function void fill(int * array, int start, int end). Use this function to fill each of your arrays so that each subsequent element contains values 1 more or less than the previous element.
  3. Write a function int sum(int * array). This function calculates the sum of all the elements in array the “normal” way, by iterating through all elements and accumulating the total. As you iterate through the array, you must use array addresses with offsets instead of array subscripts to modify or read the array elements.
  4. Write a function int gauss_sum(int * fw, int *bw). This function calculates the total by adding corresponding elements of fw and bw – remember to divide your final total by 2. As you iterate through the array, you must use array addresses with offsets instead of array subscripts to modify or read the array elements.
  5. Finally, display the values for both total and gauss_total to the console proving that Gauss was right

Sample main()

int main()
{
  int forward[100], backward[100];
  int total, gauss_total;
  
  // fill arrays
  fill(forward, 1, 100);  // fills forward array with 1 through 100
  fill(backward, 100, 1); // fills backward array with 100 through 1

  total = sum(forward);   // you can also call as 
                          // total = sum(backward)
                          // result should be the same

  gauss_total = gauss_sum(forward, backward);  

  cout << "Gauss was ";
  cout << (total == gauss_total ? "right" : "wrong") << endl;
  return 0;
}

LEGEND
PROGRAM OUTPUT
USER INPUT
FROM INPUT

CATALOG ID: CPP-CHAL0018

Print Requirements