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.
Related
I'm learning and tinkering with the C programming language. Unfortunately, While learning and playing with the do-while loop, I'm confused. I wrote and ran a program to increment a variable from 1 to 100 with condition i<=100; the code ran successful, but when I changed the condition of the do-while loop to i==100, the output confuses me because only 1 is printed on the console. Please help.
The code below gives the expected output.
#include<stdio.h>
int main(){
int i=1;
do{
printf("\n%d\n",i);
++i;
} while(i<=100);
}
The code below gives output 1.
#include<stdio.h>
int main(){
int i=1;
do{
printf("\n%d\n",i);
++i;
} while(i==100);
}
Thank you.
The second one loops if i == 100. It is not the truth (as i == 1) on the first iteration and loop exits.
The do-while loop always executes once and then checks whether the condition holds true. If the condition is true, the loop executes again and then checks the condition.
In your case, the mandatory first pass prints the value of i and then increments it. Next, the condition is checked while(i==100). At this point, i is 2 and the condition fails resulting in the loop being terminated.
First code
#include<stdio.h>
int main()
{
while(printf("Hello"))
return 0;
}
Produces only Hello as a output
Second code
#include<stdio.h>
int main()
{
while(printf("Hello"));
return 0;
}
Second code prints Hello for infinite times.
Third code
#include<stdio.h>
int main()
{
while(printf("Hello"))
{}
return 0;
}
Third code also prints Hello for infinite times.
Compiler used - GCC 9.0.1
why this is happening?
while takes a statement after the closing ).
6.8.6 Iteration statements
iteration-statement:
while ( expression ) statement
....
In
while(printf("Hello"))
return 0;
that statement (which is basically while's argument) is return 0; (6.8.6)
In
while(printf("Hello"));
the statement is ; (an empty (null)/expression statement (6.8.3)).
In
while(printf("Hello")){}
it's an empty compound statement ({}, 6.8.2), which is semantically equivalent to ;.
Your code snippets are examples of misleading whitespace—where the whitespace makes humans understand things differently from a compiler.
Less misleading renderings would be:
while(printf("Hello"))
return 0;
,
while(printf("Hello"))
; //or perhaps a {} instead of the null statement
and
while(printf("Hello"))
{}
printf returns number of characters printed (which is 5). Any non zero number evaluates to true. So the loop is an infinite loop.
The rest depends on what happens withing the loop. In the second and third cases, the loops are empty (contain no statements) so they keep executing
In the first case, return 0 is executed within the loop. Return breaks the control flow out of the loop causing the loop (and in this case the program) to stop executing
In your first code snippet, the return 0; statement is part of the while loop's 'body'; in fact, it is the entirety of that body! So, on the first run through that loop, the program exits (because that what return 0; does when executed in main) and the loop is, thus, abruptly terminated.
In the second and third snippets, you have an empty body for the loop, but that does not prevent it from running, as the printf("Hello") function call will return the number of characters that were output - which will be non-zero, and thus interpreted as "true".
In the first one the body of the while is the return 0 so it will return after the first iteration. Meanwhile with the other two version is the same, having an empty body so they infinitely going on doing nothing but the condition is keep evaluating which will print "hello".
while(printf("Hello"))
return 0;
is same as
while(printf("Hello"))
{
return 0;
}
First Code:
printf("Hello") returns the number of characters.
When printf("Hello") is used inside while loop it will print Hello and return 5.
Since it is greater than 0 while loop consider this as true and execute the statement below the while, which is return 0.
The return 0 makes the main function to return 0 and stop the exeution.
The code
while(printf("Hello"))
return 0;
is same as
while(printf("Hello"))
{
return 0;
}
Second Code:
Since you used ; after while() ,it will not execute the statement after ;.
So the statement return 0 is not executed and while checks the condition infinite times printing infinite Hello.
Third code:
While will execute the statements only within the { }.
Since its empty every time after searching for statement it will go back and check the condition.
Since the condition is always true it will not reach the return 0 and it will print Hello infinite times.
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
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.
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.