vendredi 22 septembre 2017

Print new line ONLY at the end of a vector - "if" statement outside of a "for" loop

code:

#include <iostream>
#include <vector>

int main () {

std::cout << "Please, enter the number of iterations: ";    //Inputs

int iterations;
std::cin >> iterations;

std::cout << "Which term would you like to know: ";

int term;
std::cin >> term;   //End inputs

std::vector<int> series;     //definition of vector "series"

for (int n = 1;  n <= iterations; n++) {    //creation of "series"

    int next = (2 * n - 3);
    series.push_back(next);

}

std::cout << "The value of term "   //prints the n term
          << term
          << " is: "
          << series[term-1]         //term-1 "adjust" the indexing
          << std::endl;

std::cout << "The entire serie up to "
          << iterations
          << " terms is: ";

for (int i = 0;  i < series.size(); i++) {      //prints (elements of vector) "series"

    std::cout << series[i] << ' ';

    if (i == series.size()-1) {     //new line only at the end the series

        std::cout << std::endl; 
    }

}

return 0;

}

I got 9/10 with this comment: "if condition inside loop will only be satisfied once, but checked every time. Move outside of loop". I really don't how could I place the if statement out of the loop. The scope of that for-if statement is to add a new line only at the end of the vector "series". I can't think about anything else but for sure I'm experienced enough and there is another more elegant solution. I'm asking here because I have to submit another assignment and I don't want to submit it with the same error.

PS: the other comment was: light over-commenting. Did I really commented to much?

Aucun commentaire:

Enregistrer un commentaire