Difference between "while" loop and "do while" loop - c

What is the difference between while loop and do while loop. I used to think both are completely same.Then I came across following piece of code:
do {
printf("Word length... ");
scanf("%d", &wdlen);
} while(wdlen<2);
This code works perfectly. It prints word length and tascans the input. But when I changed it to
while(wdlen<2){
printf("Word length... ");
scanf("%d", &wdlen);
}
It gives a blank screen. It do not work. So there is some functional difference between both loops. Can anybody explain it?
Is there any other difference in these two?

The do while loop executes the content of the loop once before checking the condition of the while.
Whereas a while loop will check the condition first before executing the content.
In this case you are waiting for user input with scanf(), which will never execute in the while loop as wdlen is not initialized and may just contain a garbage value which may be greater than 2.

While : your condition is at the begin of the loop block, and makes possible to never enter the loop.
Do While : your condition is at the end of the loop block, and makes obligatory to enter the loop at least one time.

do {
printf("Word length... ");
scanf("%d", &wdlen);
} while(wdlen<2);
A do-while loop guarantees the execution of the loop at least once because it checks the loop condition AFTER the loop iteration. Therefore it'll print the string and call scanf, thus updating the wdlen variable.
while(wdlen<2){
printf("Word length... ");
scanf("%d", &wdlen);
}
As for the while loop, it evaluates the loop condition BEFORE the loop body is executed. wdlen probably starts off as more than 2 in your code that's why you never reach the loop body.

do while in an exit control loop.
while is an entry control loop.

While:
entry control loop
condition is checked before loop execution
never execute loop if condition is false
there is no semicolon at the end of while statement
Do-while:
exit control loop
condition is checked at the end of loop
executes false condition at least once since condition is checked later
there is semicolon at the end of while statement.

The difference is in when the condition gets evaluated. In a do..while loop, the condition is not evaluated until the end of each loop. That means that a do..while loop will always run at least once. In a while loop, the condition is evaluated at the start.
Here I assume that wdlen is evaluating to false (i.e., it's bigger than 1) at the beginning of the while loop, so the while loop never runs. In the do..while loop, it isn't checked until the end of the first loop, so you get the result you expect.

Do while loop will be executed atleast once.......but while loop will check the condition first and then it may or may not get executed depending on the condition.
In your example wdlen may assume any garbage value which is > 2 so while loop will never get executed.
whereas do while loop will be ececuted and will tell u to enter the value and check that value in terminating condition

while(wdlen<2){
...
}
If wdlen (assuming it's a stack variable) is not initialized or assigned a value before the while loop is entered, it will contain whatever was in that space in memory before (i.e. garbage). So if the garbage value is < 2, the loop executes, otherwise it doesn't.
do{
...
}while(wdlen<2)
will execute once and then checks on condition to run loop again, and this time it might succeed if by chance wdlen which is uninitialized is found to be less than 2.

Probably wdlen starts with a value >=2, so in the second case the loop condition is initially false and the loop is never entered.
In the second case the loop body is executed before the wdlen<2 condition is checked for the first time, so the printf/scanf is executed at least once.

while test the condition before executing statements within the while loop.
do while test the condition after having executed statement within the loop.
source: let us C

while test the condition before executing statements in the while loop.
do while test the condition after having executed statement inside the loop.

In WHILE first check the condition and then execute the program
In DO-WHILE loop first execute the program at least one time then check the condition

The difference between do while (exit check) and while (entry check) is that while entering in do while it will not check but in while it will first check
The example is as such:
Program 1:
int a=10;
do{
System.out.println(a);
}
while(a<10);
//here the a is not less than 10 then also it will execute once as it will execute do while exiting it checks that a is not less than 10 so it will exit the loop
Program 2:
int b=0;
while(b<10)
{
System.out.println(b);
}
//here nothing will be printed as the value of b is not less than 10 and it will not let enter the loop and will exit
output Program 1:
10
output Program 2:
[nothing is printed]
note:
output of the program 1 and program 2 will be same if we assign a=0 and b=0 and also put a++; and b++; in the respective body of the program.

While Loop:
while(test-condition)
{
statements;
increment/decrement;
}
Lower Execution Time and Speed
Entry Conditioned Loop
No fixed number of iterations
Do While Loop:
do
{
statements;
increment/decrement;
}while(test-condition);
Higher Execution Time and Speed
Exit Conditioned Loop
Minimum one number of iteration
Find out more on this topic here: Difference Between While and Do While Loop
This is valid for C programming, Java programming and other languages as well because the concepts remain the same, only the syntax changes.
Also, another small but a differentiating factor to note is that the do while loop consists of a semicolon at the end of the while condition.

The difference between a while constructs from Step 1 versus a do while is that any expressions within the do {} will be running at least once regardless of the condition within the while() clause.
println("\nStep 2: How to use do while loop in Scala")
var numberOfDonutsBaked = 0
do {
numberOfDonutsBaked += 1
println(s"Number of donuts baked = $numberOfDonutsBaked")
} while (numberOfDonutsBaked < 5)
Here is detail explaination: Explanation
Visit: coderforevers

The most important difference between while and do-while loop is that in do-while, the block of code is executed at least once, even though the condition given is false.
To put it in a different way :
While- your condition is at the begin of the loop block, and makes possible to never enter the loop.
In While loop, the condition is first tested and then the block of code is executed if the test result is true.

Related

Why does the print statement not get executed at all?

This is the program:
#include<stdio.h>
int main()
{
int i=(-5);
while(i<=5){
if (i>=0){
break;
}
else{
i++;
continue;
}
printf("hello\n");
}
return 0;
}
My question is, why does 'hello' not get printed at all?
Because you have used continue incorrectly. It basically stops the line that is after it and goes to the condition checking part of the while loop. That's why it doesn't print hello.
From standard $6.8.6.2
A continue statement causes a jump to the loop-continuation portion of
the smallest enclosing iteration statement; that is, to the end of the
loop body.
You have a single if else statement. Everything that happens inside that loop will happen inside the if or the else. In your particular case, it will execute the else statement until 'i' is 0(the continue makes it so that it goes back to the loop condition, but in your case the continue is completely unnecessary because it's the last statement in the else), then it will execute the if and break out of the loop
Stepping though the loop, we have
1st pass i == -5, if condition false, else branch taken, i incremented to -4, continue to start of while loop
2nd to 4th pases same for i == -4 to i == -2
5th pass i == -1, if condition false, else branch taken, i incremented to 0, continue to start of while loop
6th pass i == 0, if condition true, break from while loop, return 0 from main
Neither of the if branches cause the flow to pass through the printf line.
The reason why printf() statement will never execute is because you had break statement in if and continue statement in else. Both statement are useful to break or skip the flow of execution of program.
Click here to learn when to use those statements.
Now, here i is initialized with -5. So until i reaches the value 0, else() part of the code will be executed. Else has continue statement, that will skip all the following statements and start next iteration. So, printf() statement will be skipped every time.
Once i will be incremented up to 0,if() part of code will be executed. If() has break statement that will break the loop and execution of the program will be over by main() returning 0 as there are no more statements following loop other than return 0.
Hope it'll be helpful.

I want to know the output of code

for(print("a");print("b");print("c"))
{
printf("d");
}
This question was asked in an interview , my answer was "abdcabdcabdc....." .
I want to know the proper output an explanation.Please help me out.
First of all the print in the for loop would be printf.
The output of this code will be
abdcbdcbdcbdc... infinite times.
(a will be printed only once as we initialize the counter in loop only once)
EXPLANATION
As it's a for loop so the execution will be in the following order.
Initialization
Conditon Check
Body Execution
Increment counter
Here in the condition there is a printf statement which always return the number of characters it prints. Here, printf("d") returns 1 as it is printing only 1 character.
And in C, 1 is treated as TRUE and 0 is treated as FALSE.
So, here the condition is always TRUE, so it runs for infinite times.

Unexpected Infinite for loop

I am beginner in C and I was experimenting with for loop and I came across a infinite loop which should not be a infinite loop, can anyone help me understand why it is a infinite loop
void main()
{
int i;
for(i=1,printf("Initialization");i++ <=5,printf("\nCondition");printf("%d",i))
printf("\nInside the loop :");
}
while this is not a infinite loop
void main()
{
int i;
for(i=1,printf("Intialization");printf("\nCondition"),i++<= 5;printf("%d",i))
printf("\nInside the loop\n");
}
The reason is that your loop conditions (between two semicolons) look like this:
i++ <=5, printf("\nCondition") // First loop
printf("\nCondition"), i++<= 5 // Second loop
Both conditions are comma expressions, meaning that only the last part matters in terms of generating the value (both parts are good for their side effects, though).
In the first case, the overall condition result is what printf("\nCondition") returns. It always returns non-zero*, interpreted as "true", so the loop is infinite.
In the second case, the overall result is what i++<=5 returns, which starts off as "true", and becomes "false" after five iterations. That is when the second loop terminates.
* Specifically, printf returns the number of characters printed, so in your case that would be 10. This is not essential to understanding why the loop is infinite, though.
you have 2 conditions remember that printf returns number of characters printed and that is always non zero hence results in infinite loop
Simple comma operator realizes all side effects in operands, discards result of it's first operand, and then evaluates it's second one. So, in first snippet, althought i++ will be realized, condition <= result will be discarted, so effective condition in for will be result of printf("\nCondition"), that's 10=true. In second snippet first operand result printf(...) = 10 will be discard, and will be used as pure condition just i<=5.
Here some doc :
https://en.wikipedia.org/wiki/Comma_operator,
https://uvesway.wordpress.com/2012/11/02/c-loops-for-and-the-comma-operator/
If we write more than one condition in for loop condition portion compiler will check all conditions but it will consider the right most condition to check whether the condition is TRUE/FALSE.
In your first program you write two conditions one is i++<5,printf("\ncondition").
printf always return number of printable characters in that function.so every time printf returning 9 in your program for that only condition never become false.
But in your second program you write i++<5 is right most condition for that when ever i value becomes 5 condition becomes false so control will come out side of the loop.
If you want to check whether printf returning number of printable characters then try this.
enter code here
unsigned int a=printf("HAI");
in this case printf will return 3 to the integer variable a

difference between two different while loops with and without termination?

Whats difference in the working of
while(i++<100)
and
while(i++<100);
Is this correct that in 1st case, i increases until its value reach to 99 but in 2nd case,; is an error that's why nothing is going to happen?
No:
while(i++<100); is a loop with a empty command (does nothing until i is 100), (there is no compilation error).
And while(i++<100) {commands} is a same loop but does someting.
The first one is not terminated by a ; - it will execute the the follows it until i reaches the limit.
The second one is terminated by a ; - which means that there's an implicit empty block there. In other words, it's equivalent to having while(i++<100) {}. I.e. - do nothing until i reaches the limit.
There is no syntax error, just second while loop keep on incrementing till it meats the condition,
while(i++<100);
Remember ; is statement terminator. Scope of while works with either on statement terminator, or scope delimiters {}.
while (i++ < 100) - Will execute block after this statement till condition is valid i.e. i < 100.
while (i++ < 100); - Will execute it self till i < 100.
in 2nd case,";" is an error
NO. Just think of this while() as a part of do...while loop. It's perfectly valid.
However, even in normal while() loop scenario, both the statements are valid, but their behavior is different.
while (i++ < 100)
it causes the next instruction or block following while() to be executed untill the condition goes to FALSE (i goes to 99).
while(i++<100);
essentially does nothing, execpt increasing the value of i till 99.

Can an empty for-loop be "correct"?

I have a doubt about the for loop of the following code in C:
main()
{
int i=1;
for(;;)
{
printf("%d",i++);
if(i>10)
break;
}
}
I saw this code in a question paper. I thought that the for loop won't work because it has no condition in it. But the answer says that the code has no error. Is it true ? If true, how ?
The regular for loop has three parts:
Initialization
Condition
Increment
Usually they are written like this:
for (initialization; condition; increment) { statements }
But all three parts are optional. In your case, all parts are indeed missing from the for loop, but are present elsewhere:
The initialization is int i=1
The condition is if (i>10) break
The increment is i++
The above code can be equivalently written as:
for (int i=1; i <= 10; i++) {
printf("%d", i);
}
So all the parts necessary for a for loop are present, except they are not inside the actual for construct. The loop would work, it's just not a very readable way to write it.
The for (;;) loop is an infinite loop, though in this case the body of the loop takes actions that ensure that it does not run forever. Each component of the control is optional. A missing condition is equivalent to 1 or true.
The loop would be more clearly written as:
for (int i = 1; i < 11; i++)
printf("%d", i);
We can still debate whether the output is sensible:
12345678910
could be produced more easily with:
puts("12345678910");
and you get a newline at the end. But these are meta-issues. As written, the loop 'works'. It is syntactically correct. It also terminates.
You are not specifying any parameters or conditions in your for loop, therefore, it would be an endless loop. Since there is a break condition based on another external variable, it would not be infinite.
This should be re-written as:
for (int i = 1; i <= 10; i++)
printf("%d",i++);
It's an infinite loop. When there is not a condition in for and we use ;; the statements in the body of for will be executed infinitely. However because there is a break statement inside it's body, if the variable i will be greater than 10, the execution will be stopped.
As it is stated in MSDN:
The statement for(;;) is the customary way to produce an infinite loop which can only be exited with a break, goto, or return statement.
For further documentation, please look here.
Even if a for loop is not having any condition in it, the needed conditions are specified inside the for loop.
The printf statement has i++ which keeps on increasing the value of i and next we have if statement which will check if value of i is less than 10. Once i is greater than 10 it will break the loop.

Resources