Output of a simple for loop? - c

I'm VERY new to c programming. The output of the following program is
One Two Two One but I don't know why. Can anyone explain this to me?
#include <stdio.h>
{
int i, j, k = 100;
for(i=0;i<2;i++)
{
printf("One");
for(j=0;k;j++)
{
printf("Two");
k -=50;
}
}
return 0;
}

Outer loop:
The outer for loop executes twice. Because i starts at 0, the condition i<0 is satisfied, so it runs. After it runs i gets incremented to 1, runs again, i gets incremented to 2, then doesn't run because the condition i<2 is no longer satisfied. That is where your two outputs of "one" come from.
Inner loop:
Every time the outer loop runs it creates the inner for loop. j starts at 0 but the condition for the inner loop is just k. At first, k is set to 100. Here's where it gets messy. In order for a for loop to run, the condition must be "not false". False can be either a numerical value of 0 or just null. Since it's not either one of those the inner for loop runs, and unless the condition is manually changed by something outside the for loop, it will run forever. Luckily it is in fact being changed inside the for loop and after running twice (and outputting two twice), the value of k is now 0 and exits the loop.
Put 'em together:
To summarize, the order of execution is:
outer loop (i=0, "one" gets printed)
inner loop (j=0, k=100, "two" gets printed)
inner loop (j=1, k=50, "two" gets printed)
k=0, inner loop completes (notice the j didn't get used here)
outer loop (i=1, "one" gets printed)
k=0, inner loop does not execute even once
i=2, outer loop completes

Related

what happens when increment counter and test counter are interchanged in for-loop syntax? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
please explain why
Case 1:
int main()
{
int i;
for(i=1;i++;i<100)
printf("%d",i);
return 0;
}
results in infinite loop, whereas
Case 2:
int main()
{
int i;
for(i=0;i++;i<100)
printf("%d",i);
return 0;
}
Doesn't run the loop even once?
Please clarify how to interpret this kind of syntax?
The syntax of a for loop in C programming language is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
In First Case:
init set i = 1
conditon - here i = 1 which is true in c. (Post increment increases the value after execution of statment)
body - executes printf("%d",i);
increment - i<100 which is not affecting the value of i.
Now In C for all values from 1 to infinity, its value is true, hence executing infinetly
In Second Case
init set i = 0
conditon - here i = 0 (again Post Increment) which is false in c, therefore the loop gets exit.
Hence it is not executing even once.
Flow diagram of For Loop :
The proper syntax is
for (i=1; i<100; i++) {
something
}
What's actually happening?
The for loop takes three arguments,
1. The initial condition, or initialization that happens at the beginning, before the loop is executed. In this case it's i=1 that is set i as 1
2. The final condition that is checked at the beginning of every loop. If this condition is not met, the loop is broken. In this case it's i<100. So, if at the start of next loop, when i >= 100 the loop is broken.
3. The step or periodic operation at the end of loop. In this case it's i++. At the end of every loop i is incremented by 1.
What's happening with your code
for (i=1; i++; i<100)
The first part is good.
The second is executed at the beginning of each loop. i++ returns the value of i then increments it. (In contrast to ++i, which does the opposite.) Since in your first example i=1, it starts at one, and the second argument always returns a value >= 1 which is interpreted as true. But in your second example, i starts at 0. So during first iteration the second argument returns 0, which is interpreted as false, and the loop never starts.
The third one is executed at the end, and never affects the loop in any way.
int main()
{
int i;
for(i=0;i++;i<100)
printf("%d",i);
return 0;
}
as for loop is having syntax
for(initialize variable; condition check; increment/decrement)
you have initialize variable as i = 0
in condition checking part you have written i++ i.e post increment so i remain 0 which means FALSE and hence it will exit for loop.
Try this :
int main()
{
int i;
for(i=0;i<100;i++)
printf("%d",i);
return 0;
}

Explain the output of the given code

In the below code, variable i has been declared globally as well as locally in the for loop . Due to high precedence of local variable, i will be initialized with the value 10 . But in the first occurrence of the loop, due to i++in the for loop, value of i will become 11, so should it not exit the loop after the first instance only?
#include<stdio.h>
int main(){
int i;
for(i=0;i<5;i++){
int i=10;
printf(" %d",i);
i++;
}
return 0;
}
P.S: The answer is 10 10 10 10 10
Precedence is not just about initialization. The variable i inside the loop body is a different variable from the one outside. It "shadows" the outer i, making it inaccessible in the loop body.
The loop control statement is outside the loop body. Its i is the outer i, and nothing done to the inner i has any effect on it, so it starts at 0 and counts up to 5. At each loop iteration, the inner i is re-initialized to 10, and that's the one that gets printed.
The reason it always prints is because the inner i shadows the outer i. For the same reason the i++; inside the loop increments the inner i, not the i that's used as the for loop counter.
But the i that controls the loop gets incremented after the scope of the inner i is over and has no relation to i++; done inside the loop. It's completely independent of the inner i and thus the loop runs 5 times.
GCC provides an option to warn about such shadowing: -Wshadow.
Yet another answer because there is one aspect missing so far. If you change your code slightly:
#include<stdio.h>
int main(){
int i;
for(i=0;i<5;i++){
static int i=10;
printf(" %d",i);
i++;
}
return 0;
}
You will get a more "expected" result:
10 11 12 13 14
A variable inside a block stops to exist after the block (read: pair of curly braces) is left (and it is left here after every step to execute the control statements of for) ... so with your original code, you get a new inner i each time. Declaring the inner i static still doesn't change the scope (it is only visible inside the loop body), but makes the variable survive and still be available when the same block is entered again.
Yes the answer is correct.
As loop iterates 5 times and for every iteration i inside loop is set to 10 and outer one is overshadowed by inner one. After i=10 its value is printed therefore 5 times 10 is output.

Does checking count-- in a for loop cancels the loop?

Sry I'm new to C language.
Can someone help me understand what happens in the "for" loop:
When I run this code I get nothing, it's not even entering the loop:
for( count=0 ;count--;count--)
{
printf("\n%5d", count);
}
And when I run this code I get infinite entrances to the loop:
for( count=1 ;count--;count--)
{
printf("\n%5d", count);
}
And when I run this code I get 1 entrance to the loop:
for( count=2 ;count--;count--)
{
printf("\n%5d", count);
}
And so on for every count=odd number I get infinite entrances, and for every count=even number I get a limited number of entrances
Can someone explain me why is this hapening?
for(left;middle;right) The middle expression is the condition - an expression which is contextually convertible to bool. This expression is evaluated before each iteration, and if it yields false (or 0 in the case of an int), the loop is exited.
foo-- is a post-operator, which means the value is foo is evaluated first and then it is decremented.
Putting these two together,
Case1: Before entering the loop, count-- is evaluated. Count current value is 0. So loop is not executed.
Case2: count-- evaluates to 1, loop is entered once. count-- is executed at the end of the loop. count-- now evaluates to -1 at the beginning of the loop, so loop is executed again, and so on - ad infinitum
Case3: count-- is 2, end of the loop count-- is 0, so loop exits after 1 iteration.
I think you first need to to know exactly what count-- is. This means that first count will be evaluated as part of the condition, then decremented. This means that count-- is 0 in this case, making the for loop condition evaluate to 0. After the condition is evaluated, count is -1, but this doesn't matter because count was 0 during the condition check so the loop never runs.
for(count = 0;count--;count--)
{
printf("\n%5d", count);
}
The next loop starts count at 1, which means count-- will be evaluated to 1, this makes the condition check of the for loop equal to 1. After the evaluation, count becomes 0. This means the for loop will enter and print out the message. When the code block ends, the statement count-- gets executed, setting count to -1. Then we do the check again. We see that count-- evaluates to -1 so we will loop again. After the evaluation, count will be set to -2 and we will enter the for loop again. This function runs forever because count will always be odd when we get to the for loop check, therefore count can never be 0 and we never break from the loop.
for(count = 1;count--;count--)
{
printf("\n%5d", count);
}
You should now be able to figure out why the last one only runs once:
for( count=2 ;count--;count--)
{
printf("\n%5d", count);
}
Obviously after the first evalution, count gets decremented. Then once the code block gets executed, it is decremented again. Therefore when we get to the conditional check in the for loop, count is 0 and we break.

For loop why the variable out of the loop is "last index" + step?

I was just wondering why this :
int i;
for (i=0; i<5; i++){
printf("%d\n",i)
}
printf("Here i get the result that misleads me : %d\n",i)
The last value is 5.
My logic is :
From 0 to 4 -> printf
If i > 4 (since we are dealing with integers) stop the loop.
But the loop stopped at 4 not 5 ! Why do I get 5 after the loop ? Why does it ever increment ?
Arbitrary ?
Thanks,
There are three clauses in the for statement.
The init-stmt statement is done before the loop is started, usually
to initialize an iteration variable.
The condition expression is tested before each time the loop is
done. The loop isn't executed if the boolean expression is false
(the same as the while loop).
The next-stmt statement is done after the body is executed. It
typically increments an iteration variable.
So, end of each for loop execution, increment operation executed, and, in the 4th iteration, value of i is 5 and the for loop was broke as the value is 5 in 5th iteration.
unroll what's happening
int i = 0;
while( i < 5 )
{
// body of for loop
i++;
}
// i == 5 here as i must be greater than or equal to 5 to break out of while loop
How does for loop works:
for (initialization; condition; increment-decrement)
Statement
Run initialization (i=0)
Check condition (i<5), if true then jump to 3 else jump to 5
Do statement ({ printf("%d\n",i) })
Do increment-decrement (i++), jump to 2
Exit loop
Before last iteration i == 4, then it prints 4, increments i. Therefore after last iteration i == 5, !(5 < 5), i.e. condition is false, exit from loop.
At the end of each iteration, the loop index is incremented. Then the program checks whether to run another loop. It finds "no the index is too big and fails the condition", so it doesn't execute and exits.
Until the index gets too big, the condition doesn't fail. It HAS to get too big (so the loop doesn't execute).
And that is why...
Because after the 4th loop:
i++ is performed, i becomes 5
i<5 is evaluated as false
Thus the loop exits
And then you get i==5 after the end of loop.
Indeed, after each loop, i++ is evaluated before checking for the exit condition, i<5.
for (int i = 0; i < 5; ++i) goes like this:
i <- 0
check whether i < 5, if yes, loop, otherwise stop
do the loop
i <- i + 1
goes to step 2
Let's see this loop:
for (i = 0; 0; i++)
do_smth();
You'll see that this loop doesn't execute at all. Because the condition is false even from the beginning.
Now
for (i = 0; i < 4; i++)
i++;
Clearly increases i twice for every run (once inside the loop and then because of the third part of the for). In the end, i will have the first even value which make the condition false. That is 6. Thus, there is no link between the step and the value of the variable outside the loop.

Difference between "while" loop and "do while" loop

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.

Resources