Reputation:
Why the loop goes on to infinity , I have put limits via n<6 , one more thing , the code prints 111111... . The output that I expect is 12345.
#include <stdio.h>
//Compiler version gcc 6.3.0
int main()
{
int n=1;
do{
while(n<6)
printf("%d",n);
n++;
}
while(n<6);
return 0;
}
Upvotes: 0
Views: 77
Reputation: 55
The right code should be:
#include <stdio.h>
//Compiler version gcc 6.3.0
int main()
{
int n=1;
do{
printf("%d",n);
n++;
}
while(n<6);
return 0;
}
In addition, I find no reason to use a do-while statement. A simple while would make the work:
int n=1
while(num<6)
{
printf("%d",n);
num++;
}
Also, for a known length of inputs, it is more right to use a for loop.
Upvotes: 0
Reputation: 74615
Why this is an infinite loop?
Because this:
do{
while(n<6)
printf("%d",n);
n++;
}
...
Is actually this:
do{
while(n<6) {
printf("%d",n);
}
n++;
}
...
The code will never escape the "single statement while loop" just under the do
. I would suggest that deleting it so that you only have one line that says while(n<6)
, just above the return
, will make your program function as you expect
Upvotes: 6
Reputation: 67584
Becuase in this loop only one statement is executed.
while(n<6)
printf("%d",n);
It is same as:
while(n<6)
{
printf("%d",n);
}
You enter this loop when n == 1
which meets the loop condition condition
Upvotes: 0