CSC 101 Lecture Notes Week 2
Let's Start Programming
1 ////
2 //
3 // This program computes simple statistics for five real numbers entered from
4 // the terminal. The statistics computed are the sum of the numbers, the
5 // arithmetic mean, and the standard deviation.
6 //
7 // Author: Gene Fisher (gfisher@calpoly.edu)
8 // Created: 30mar99
9 // Last Modified: 1apr99
10 //
11 ////
12
13 #include <iostream.h>
14 #include <math.h>
15
16 const int NUM_DATA_POINTS = 5; // Fixed number of data points
17
18 int main () {
19
20 float i1, i2, i3, i4, i5; // Input variables
21 float sum; // Computed sum
22 float mean; // Computed mean
23 float std_dev; // Computed standard deviation
24
25 //
26 // Prompt the user for the input.
27 //
28 cout << "Enter five real numbers, separated by spaces: ";
29
30 //
31 // Input the numbers.
32 //
33 cin >> i1 >> i2 >> i3 >> i4 >> i5;
34
35 //
36 // Compute the sum.
37 //
38 sum = i1 + i2 + i3 + i4 + i5;
39
40 //
41 // Compute the mean.
42 //
43 mean = sum / NUM_DATA_POINTS;
44
45 //
46 // Compute the standard deviation.
47 //
48 std_dev = sqrt((pow(i1 - mean, 2) +
49 pow(i2 - mean, 2) +
50 pow(i3 - mean, 2) +
51 pow(i4 - mean, 2) +
52 pow(i5 - mean, 2)) / (NUM_DATA_POINTS - 1));
53
54 //
55 // Output the results.
56 //
57 cout << endl
58 << "Sum = " << sum << ", "
59 << "Mean = " << mean << ", "
60 << "Standard deviation = " << std_dev << ", "
61 << endl << endl;
62 }
means "store the value 1 in the memory location named x".x = 1
x = 1is simply a statement of fact; it means "the value denoted by the variable x is equal to 1".
x = x + 1
//
// Prompt for and input the first number.
//
cout << "Enter the first of five numbers: ";
cin >> i1;
//
// Intialize the sum to the first number.
//
sum = i1;
//
// Output the sum so far (which is just the value of the first number).
//
cout << "Running sum so far = " << sum << endl;
//
// Prompt for and input the second number.
//
cout << "Enter the second of five numbers: ";
cin >> i2;
//
// Update the sum by adding in the second number.
//
sum = sum + i2;
//
// Output the sum so far, which is now the total of the first two numbers.
//
cout << "Running sum so far = " << sum << endl;
//
// Prompt for, input, and add in the remaining three numbers. Print the
// running sum after each number is added in.
//
cout << "Enter the third of five numbers: ";
cin >> i3;
sum = sum + i3;
cout << "Running sum so far = " << sum << endl;
cout << "Enter the fourth of five numbers: ";
cin >> i4;
sum = sum + i4;
cout << "Running sum so far = " << sum << endl;
cout << "Enter the fifth of five numbers: ";
cin >> i5;
sum = sum + i5;
cout << "Total of all five numbers = " << sum << endl;