Arrays Project

Write a program to: 1) Read N(set max to 500) numbers from the keyboard (provide a method to end the input).

2) Ask the user of the program if the program should:

a) calculate the average of the numbers entered.
or
b) calculate the sum of the numbers entered.

3) Produce the result as the user instructed on the screen with appropriate messages. (Hint: repetitions, arrays, functions must be used....here's what I have so far...my question is what do I type to make all the integers add to each other? I guess what I'm trying to say is how can I possibly write code that knows exactly how many integers were entered and what to do with them?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int main() {
	int n[501];
  
 cout << "Please enter your numbers";
 cin >> n;

 cout <<"Would you like to calculate the average or the sum of these numbers?" << endl;
 cout << "To calculate the sum of these numbers type sum or for average type average" << endl;
 cin >> answer;

 if (answer==sum){
   
     }

 if (answer==average){

     }


  
    system("PAUSE");
	return 0;
}
1
2
cout << "Please enter your numbers";
 cin >> n;


This will not work. You need a loop to fill the array. Assuming only positive integers are allowed (if non positive are allowed then I will show you a different method).
1
2
3
4
5
6
7
8
9
10
11
12
13
int x = 0, n[500] = {0}; //Set all array elements to be zero. 
while(n != -1 && x < 501) //While the user has not quit and less than 500 numbers are entered. 
{
    cout << "Please enter your number. Type -1 to finish\n"; 
    cin >> n[x]; //Fill element x with the number just entered.  
    if(n == -1)//If the user wants to quit. 
    {
         n[x] = 0; //Get rid of the -1.
         --x;  //The last number entered does not count, because it was just -1 (to exit)
         break; //Exit this loop. 
    }
    ++x; //Next time we will fill the next element of the array.
}


Now, at the end of this piece of code, x will be equal to the number of numbers entered and the array will be filled with whatever numbers the user entered.

1
2
3
4
5
6
7
8
9
cin >> answer;

 if (answer==sum){
   
     }

 if (answer==average){

     }


Here you have not declared answer. It looks like you want to #include <string> and make answer a string. This is also not how to compare strings. Here is the correct way.
1
2
3
4
5
6
7
8
9
10
11
#include <string> 
using std::string;  //Better than using namespace std; is to use only the things you are using. 
using std::cout; 

string answer; 
while(answer != "sum" || answer != "average") //Strings need double quotation marks. 
{
    cin >> answer; //Get answer from user. 
}
if(answer == "sum") //Double quotes again. 
cout << "sum is: "; 
Last edited on
Topic archived. No new replies allowed.