Need help printing out elements in an array

Here is the problem I've been given to work with.

Write a for loop to print all NUM_VALS elements of array hourlyTemp. Separate elements with a comma and space. Ex: If hourlyTemp = {90, 92, 94, 95}, print:
90, 92, 94, 95
Note that the last element is not followed by a comma, space, or newline.

**I'm having trouble printing out that last element without a comma. How do I go about doing this? I'm not looking for an answer. But a hint would help. Also I'm very new at this. So nothing too advanced. Thanks for any help.

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

int main() {
   const int NUM_VALS = 4;
   int hourlyTemp[NUM_VALS];
   int i = 0;

   hourlyTemp[0] = 90;
   hourlyTemp[1] = 92;
   hourlyTemp[2] = 94;
   hourlyTemp[3] = 95;

     for(i=0; i<4; i++)
     {
        cout<<hourlyTemp[i]<<", ";
}
  
   
   cout << endl;

   return 0;
}
Last edited on
closed account (48T7M4Gy)
Output the looped answer as a string and display all of that string except the last character or two as appropriate.


Or, use a while loop with the last line, without the ',' immediately outside the loop.

Or, use an if statement inside the for loop.
Last edited on
1
2
3
4
print the first number
then loop till end
    print ,
    print the number

Last edited on
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
#include <iostream>
using namespace std;

int main() {
   const int NUM_VALS = 4;
   int hourlyTemp[NUM_VALS];
   int i = 0;

   hourlyTemp[0] = 90;
   hourlyTemp[1] = 92;
   hourlyTemp[2] = 94;
   hourlyTemp[3] = 95;

     for(i=0; i<4; i++)
     {
        cout<<hourlyTemp[i];

        if (i != 3)
        {
            std::cout << ", ";
        }
     }
  
   
   cout << endl;

   return 0;
}
Last edited on
Topic archived. No new replies allowed.