Reputation: 89
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?
Upvotes: 0
Views: 10770
Reputation: 3600
The main difference between for loop and do-while loop is the fact that:
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
}
Upvotes: 2
Reputation:
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;
Upvotes: 0
Reputation: 789
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.
Upvotes: 0
Reputation: 13620
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;
Upvotes: 4
Reputation: 277
a do while will be exectued at least one time, no mather what the value is i is. Also you should initialise your i.
Upvotes: -1
Reputation: 14053
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.
Upvotes: 1