Iterating through arrays part 2

The problem wants me to print each number that is greater than 21.
This is what I have.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
  
#include <iostream>
using namespace std;

int main() {
   const int NUM_ELEMENTS = 8; // Number of elements
   int userVals[NUM_ELEMENTS]; // User numbers
   int i = 0;                  // Loop index
   int sumVal = 0;             // For computing sum
   
   // Prompt user to populate array
   cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;

   for (i = 0; i <= NUM_ELEMENTS; ++i) {
      cout << "Value: " << endl;
      cin >> userVals[i];
   }
   
   // Determine sum
   sumVal = 0;
   
   for (i = 0; i < NUM_ELEMENTS; ++i) {
      sumVal = sumVal + userVals[i];
   }
   
   cout << "Sum: " << sumVal << endl;
    
// Print the numbers greater than 21 and what I added
cout << endl<< "Numbers greater than 21: " << endl;

for (i = 0; i < NUM_ELEMENTS; ++i){
    if (userVals[i] > 21){
        cout << endl;
    }
}
    
   return 0;
}
Change this - for (i = 0; i <= NUM_ELEMENTS; i++)

To this - for (i = 0; i < NUM_ELEMENTS; i++)

The reason they are not being printed out, is because you are telling the program to only print out a new line...

1
2
3
if (userVals[i] > 21){
        cout << endl;
    }


see? If the value is above 21, print endl. You want it to print out that specific value

1
2
3
4
if (userVals[i] > 21)
{
	cout << userVals[i] << endl;
}
Last edited on
Topic archived. No new replies allowed.