Possible title: How to Print All Elements of a Vector Using a For Loop in C++

  • Context: C/C++ 
  • Thread starter Thread starter ineedhelpnow
  • Start date Start date
  • Tags Tags
    Vectors
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 5K views
ineedhelpnow
Messages
649
Reaction score
0
Write a for loop to print all NUM_VALS elements of vector 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.Sample program:
Code:
#include <iostream>
#include <vector>
using namespace std;

int main() {
   const int NUM_VALS = 4;             
   vector<int> hourlyTemp(NUM_VALS); 
   int i = 0;                         

   hourlyTemp.at(0) = 90;
   hourlyTemp.at(1) = 92;
   hourlyTemp.at(2) = 94;
   hourlyTemp.at(3) = 95;

   <STUDENT CODE>
   cout << endl;

   return 0;
}

Below, do not type an entire program. Only type the portion indicated by the above instructions (and if a sample program is shown above, only type the <STUDENT CODE> portion.)

answer is
Code:
   for(int i=0; i<NUM_VALS; i++)
   {
   if(i==0)
   cout << hourlyTemp[i] ;
   else cout <<", " << hourlyTemp[i];
   }

but is there any other way to write the if else statement?
 
on Phys.org
Hi Pippy! (Smile)

There's lots of ways.
For instance:
Code:
for(int i=0; i<NUM_VALS; i++)
{
   if(i>0) {
      cout << ", ";
   }
   cout << hourlyTemp[i] ;
}

Or:
Code:
for(int i=0; i<NUM_VALS; i++)
{
   cout << hourlyTemp[i] ;
   if (i < NUM_VALS - 1) {
      cout << ", ";
   }
}
(Wasntme)
 
I like Serena said:
Hi Pippy! (Smile)

There's lots of ways.
For instance:
Code:
for(int i=0; i<NUM_VALS; i++)
{
   if(i>0) {
      cout << ", ";
   }
   cout << hourlyTemp[i] ;
}

Or:
Code:
for(int i=0; i<NUM_VALS; i++)
{
   cout << hourlyTemp[i] ;
   if (i < NUM_VALS - 1) {
      cout << ", ";
   }
}
(Wasntme)

Hey ILS. :o
yeah i like the last way the best i think. its saying print all the numbers from the list and as long as its less than the last one also print the comma and space (Thinking) i always forget that NUM_VALS-1 means the item before the last.