简体   繁体   中英

Converting for loop to do while loop in C++

I need to convert this for loop to a do while:

for (int i = 0; i <= input; i = i + 2)
{
    cout << name << " is number " << input << endl;
    total = total + i;
}
cout << endl;
cout << total << endl;

This is what I have so far:

do
{
    cout << name << " is number " << input << endl;
    i += 2;
    total += i;
} while (i <= input);
cout << endl;
cout << total << endl;

It doesn't give the same total value as the for loop. What am I doing wrong?

You have to add i to the total before incrementing it by 2

So the do..while loop should be like this:

do
{
    cout << name << " is number " << input << endl;
    total += i;
    i += 2;
} while (i <= input);
cout << endl;
cout << total << endl;

The main difference between for loop and do-while loop is the fact that:

  • For loop executes 0 or more times
  • But the do-while loop executes 1 or more times

Example:

int input = 100;

//Will never execute as i is bigger than 5
for (int i = input; i<5; ++i)
    cout << i;

//Will execute only one time as i < 5 is checked only
//after first execution
int i = input;
do
{
    cout << i;
} while(i < 5);

The way to correctly do you task is:

int i = 0;
//if used to prevent first execution
if (i <= input)
{
    do
    {
        cout << name << " is number " << input << endl;
        total = total + i;
        i = i + 2;
    } while(i <= input);
}

But for is better to rewrite for loop like

for(BEFORE_STATEMENT; FINISH_STATEMENT; ITERATE_STATEMENT)
{
    LOOP_CODE
}

as while loop, which will work the same

BEFORE_STATEMENT
while(FINISH_STATEMENT)
{
    LOOP_CODE
    ITERATE_STATEMENT
}

You just need to change

i += 2;
total += i;

to

total += i;
i += 2;

In your for loop:

total = total + i;  

i is equal to 0 at the first iteration. The way you were doing it in the do - while loop, i was set to 2 before the total addition.

If you haven't done so in a previous portion of the code, you need to initialize i in the do...while.

Also, in the do...while, change the order to have total incremented before i is incremented.

Your code is incorrect. Corect is

do
{
    cout << name << " is number " << input << endl;
    total += i;//swap these lines
    i += 2;//
} while (i <= input);
cout << endl;
cout << total << endl;

a do while will be exectued at least one time, no mather what the value is i is. Also you should initialise your i.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM