+ 2
C language, increment Number doWhile
Hello world, I did a simple prog that just increase number on row, I'm wondering why it also printf number 11 even if I want stop at number 10, where is bug? thank u for attention, have nice day https://code.sololearn.com/cTLK6XMn45SN/?ref=app
6 odpowiedzi
+ 11
this is because do while loop is a exit control loop where first the instructions are execute then the condition is checked in your program it print value till 10 then after 10 at 11 condition is false but as the property of do while loop Loop body will be executed first, and then condition is checked so it will print 11 too
Exit Controlled Loop is used when checking of test condition is mandatory after executing the loop body.
+ 10
#include <stdio.h>
int main() {
int x; int y;
for(x=1, y=10; x<=y; x++)
{
printf ("%d\n",x);
}
return 0;
}
you can do like this too
+ 9
#include <iostream>
using namespace std;
int main ()
{
int i= 1;
while( i <=10 )
{
cout << "value of i: " << i << endl;
i++;
}
return 0;
}
and by while loop you can do like this
+ 1
thank u, so I have to do a statement saying to stop printf after 10 was printed?
+ 1
The first 10 prints are done inside the for loop.
Because you declared the x and y variables outside of the loop they keep theire values.
Last loop: x=10, but it will do another increment after the loop
So after the for loop x=11
A do-while loop always runs the first time and then checks the conditions if it should run more times.
=> printf -> x=11
after the printout there is another x++
So actually x =12 at the end of the program
@Gawen Steasy
Your answer is right, but the main problem in his code are not the do while loop alone
0
Because you always execute the contents of a do loop at least once, so x was 11 before you even started the loop.
https://code.sololearn.com/cAwnUSo6kVTF/#c