[Solved] What is the difference between these for loops? [closed]


This is the line I’m having a problem with

    for(int i = a; i &lt= b; i++) { /* body of the loop */ }

See e.g. https://en.cppreference.com/w/cpp/language/for, it translates into something like:

Executes int i = a; once, then executes the body of the loop and i++ repeatedly, until the value of condition i <= b becomes false. The test takes place before each iteration.

So, basically, it defines an integer variable i, initializes it with the value of a and while its value is less than or equal to b it executes the body of the loop and increments i.

Now consider the text of the assignment:

You will be given two positive integers, a and b (a <= b), separated by a newline.
[…] For each integer n in the interval [a,b] :

That’s the first logic difference between your implementation and the accepted one. Consider this lines:

// The use of an array instead of two different variables is not a problem, but...
int n[2];
cin >> n[0] >> n[1];

// The loop is executed only twice, only for the two ends values, not the values in between
for (int i = 0; i <= 1; i++) { 
//          ^^^     ^^^ 
    if (n[i] == 1)
        cout << "one" << endl;
    else if (n[i] == 2)
    // ...
}

The correct way to loop “for each integer in the interval [a,b]”, given your array of two values, would be

for (int i = n[0]; i <= n[1]; i++) { 
//          ^^^^^^     ^^^^^^ 
    if (i == 1)
    // ^^^     
        cout << "one" << endl;
    else if (i == 2)
    //      ^^^
    // ...
}

The second one is that you have two loops, so each one is executed for each value, printing two strings, while you should have one loop and print one line for each value:

for (int i = n[0]; i <= n[1]; i++) { 
//          ^^^^^^     ^^^^^^ 
    if (i == 1)
        cout << "one" << endl;
    else if (i == 2)

// ...

    else if (i == 9)
//      ^^^^
        cout << "nine" << endl;
    else if (i % 2)
//  ^^^^^^^^        
        cout << "odd" <<endl;
    else
        cout << "even" <<endl;  
}

4

solved What is the difference between these for loops? [closed]