Home > database >  How to properly convert from a do-loop to a for-loop?
How to properly convert from a do-loop to a for-loop?

Time:11-05

How would I properly convert this from a do loop to a for loop?

int i = 1;

do {
    if (i % 2 == 0)
        cout << "Hallo\n";
    else
        cout << "Apa Khabar\n";
    i  = 2;
} while (i <= 20);

This is what I have however I am given alot of syntax erros.

for (int i = 1; i % 2 == 0; i <= 20; i  = 2)
    {
        cout << "Hallo\n";

        cout << "Apa Khabar\n";
    }

CodePudding user response:

In regard to your syntax errors in your for-loop code, there are only 3 sections/deliminators, and it looks like you have 4.

Your do-while-loop logic runs until i <= 20, and prints either of 2 strings whether i is even or odd (i%2==0).

In general, when converting a do-while-loop to a for-loop, you can move the while condition into the for-loop's condition statement. In your case, it would look something like this:

for(int i = 1; i <= 20; i  = 2) {    
   if (i % 2 == 0)
      cout << "Hallo\n";
   else
      cout << "Apa Khabar\n";
}

Also note that you are initializing i to 0, and incrementing i each iteration by 2. This means the values of i will be 1, 3, 5, 7, 9... etc. Never being an even number. Because of this, your "Hallo" statement will never execute. Im not sure if this is your desired behavior, but if you want the statements to alternate, instead change your for-loops "step" to 1, like this:

for(int i = 1; i <= 20; i  = 1) {    
   if (i % 2 == 0)
      cout << "Hallo\n";
   else
      cout << "Apa Khabar\n";
}

CodePudding user response:

The first item in a for loop's parentheses is initialization, the second is the test that determines whether the loop body will be executed, and the third is the iteration expression that will be executed after the loop body and before the next test. So, this is what you want...

for( int i = 1; i <= 20; i  = 2 )
{    
   if (i % 2 == 0)
      cout << "Hallo\n";
   else
      cout << "Apa Khabar\n";
}    

CodePudding user response:

Your i % 2 == 0 should be part of the loop's body. Not the loop itself.

A for-loop generally only has three parts

for(initializer; anchor(when to stop); modifier(what changes between iterations))

so what you're looking for is:

for (int i = 1; i <= 20; i  = 2)
{
    if (i % 2 == 0)
    {
        cout << "Hallo\n";
    }
    else
    {
        cout << "Apa Khabar\n";
    }
    
}

CodePudding user response:

The correct answer is:

for ( int i = 1; i<=20; i = 2 )
{
   if (i % 2 == 0)
      cout << "Hallo\n";
   else
      cout << "Apa Khabar\n";
}

There is no need to attempt to merge the if statement into the for statement. The body of the loop should be left intact, except for the line i = 2; which increments the loop counter. This statement should be moved into the third part of the for statement.

  •  Tags:  
  • c
  • Related