converting while loop to a for loop

Hey guys, so just doing some practice questions and came across this one in particular where i feel like i may be missing something. Any advice here?(note: the code isn't meant to do anything significant, just testing my ability to convert to a different loop).

while loop:

1
2
3
4
5
6
7
  int i = m;
  while (i <= u){
    u++;
    cin >> i;
    i = 2*i;
  }


For loop:

1
2
3
4
5
6
7
int main(){
 int i = m;
   for(int i=0; i <=u; u++){
     cin >>i;
     i = 2*i;
   }
}
Last edited on
1
2
3
4
   for(int i = m; i <= u; ++u) {
     cin >> i;
     i = 2*i;
   }
Last edited on
Thank you, I had a feeling something was off. Could you please just quickly explain why i'd need to include that i = m as part of my initialization for the for loop even if m is never used? Is it simply just a shortcut?
The value of m is used to initialize i. The loop runs if and only if i is less than or equal to u, so if m is greater than u, the loop body never executes.

Your attempt declares two different variables named i; the one visible inside the loop is always initialized to 0.

The following conversion is technically more accurate (the scope of i is not limited to the loop, as in the original code.)
1
2
3
4
5
int i = m; 
for( ; i <= u; ++u) {
  cin >> i;
  i = 2*i;
}
Last edited on
Thank you very much for the explanation!
Topic archived. No new replies allowed.