C loop while - beginner - c

My first question here on forum. I'm not sure why the output of the code is "hi" whereas I'm thinking it should be null. I might be missing here something badly. Help appreciated.
#include <stdio.h>
int main(void)
{
int i = 0;
while (i == 0)
{
printf("hi\n");
i++;
}
}

Your while loop will run what you have enclosed in it up until the stopping condition is false. you have int i = 0 as your starting value and your while loop condition says while (i == 0) to print "hi". Since i = 0, your condition is true one time and will print "hi" once before i increments and becomes false on the next pass.

The output of your code is correct, the while loop is entered because i == 0 and then i changes to 1 so the condition is false on the second iteration which makes the loop end and thus the program too.

You are confusing while loops with until loops (which C doesn't have). The while loop will execute its body while a condition is true, not until it is true. So if you want to print "hi" 10 times, you will need to write
int i = 1;
while (i <= 10) {
printf("hi\n");
++i;
}

#include <stdio.h>
int main(void)
{
int i = 0;
while (i == 0)
{
printf("hi\n");
i++;
}
}
while loop works in such a way that the loop executes only if the condition inside the parenthesis is true. In the above code, the value of 'i' is initially set to 0, which satisfies the condition of the while loop. It enters inside the loop, goes on to print 'hi' and then increments the value of 'i'.
Now the condition of while is again checked. Since the condition fails this time ,as the value of 'i' has been incremented, it exits out of the loop and the program terminates. I hope it answers your question.

like #iharob said, i==0 returns 1 which creates an infinite loop running and printing hi hi hi hi hi
if i was to do them, I would put in an if statement inside the while loop to check if i is still 0 or changed. if its 0, print hi, else, return 0;

it is obvious that the syntax that your are looking for is a do ... while loop
because programs run from up to down and left to right, the moment that your program reaches the while checks the i and it is still 0 but for the next loop it won't print anything because i=1.

Related

Issue in incrementing numbers in Do while loop

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.

I did not understand why this for loop end with 1. why not 0 or -1 or something else

I think it would be an infinite loop because the value of i is decremented. but the loop stops when it returns 1. why?
int i ;
for (i = 5; i; i--){
printf("%d\n",i);
}
return 0;
}
In C, any nonzero integer or non-null pointer used in a conditional evaluates to true, and any zero value or null pointer evaluates to false. So, for example:
if (5) {
printf("This always executes.\n");
}
if (0) {
printf("You will never see this.\n");
}
In your case, the loop is
for (i = 5; i; i--) {
/* ... */
}
The loop condition is i, which means "loop while i is not zero, and stop once i becomes zero." As a result, once i drops to zero, the loop stops running. That means the last time you'll see the loop run is when i = 1, since after that it drops to zero.
Note the for loop syntax
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
The second part is a testExpression. You testExpression is to test whether i is true(non-zero) or false(zero.)
After 1 is printed (i==1) and the loop back to the start point with updateStatement (i--) , i is set to 0. Your testExpression is 0 which is viewed as false. So the loop exists immediately. ( 0 will not be printed either.)
If you want your codes to be an loop to print i infinitely, you can leave the testExpression empty.
There are 3 parts to a for loop:
The initialisation (executed before the first iteration of the loop), in your example i = 5
The condition (executed before each iteration of the loop), in your example i
The final expression (executed after each iteration of the loop), in your example i--
In most for loops you'll find that the condition is a comparison, e.g. i > 0, however in your example the condition is a value of 0.
In most languages 0 is considered as false, so it would stop the execution of the for loop once it reaches that number.

Execution of for loop in C

How this for loop is working
int main(){
char i=0;
for(i<=5 && i>=-1; ++i ;i>0)
printf("%d \n",i);
printf("\n");
return 0;
}
Ahh thanks for the clarification.
Your asking why the for loop in your example is executing, even though the increment operand and loop condition have been swapped, and the fact that the variable is a char. Lets consider the proper structure of a for loop:
for (initialise variable; for condition; increment variable)
{
//Do stuff
}
The answer to your question is simple:
Your condition increases i by 1, but as you have pointed out, i is a char. Using operands on a char can convert it to another type, including int (refer C comparison char and int)
A loop will continue until its condition == false.
Your loop will continue running until i=0, which means it will continue to increase by 1 until it reaches 128, at which point it will overflow to -128 and continue to increase until it reaches 0 again.
Lets name parts of the for loop:
for( Expr1; Expr2; Expr3 )
DoStuff;
This is how a for loop works:
1. It executes Expr1 first. in your loop does nothing in fact, since it doesn't check the result of this execution.
Then it executes Expr2 and treat it's result as a condition if it's 0 terminates the loop, if it's "not 0" go to step 3. In your loop this means that i will be incremented, thus it's now 1, so result is true.
Then it runs the DoStuff part, in your case print out i value
Next it executes Expr3, no check, just run it, in your case does nothing again, since it's a condition and its result isn't used.
Next it goes back to Expr2 executes it and check it's result. now i is 2, still a true condition.
Again execute the DoStuff part and go to step 4
The loop will stop once i value changes back to 0.
When? since it's type is char, after reaching 127 it will overflow to -128 and then increment back to -1 and then 0. and stop.
Whenever you want to understand for loop in this kind of situation you can convert for loop into while to understand it.
The for syntax is:
for (initialization; condition; operation)
...
It can be converted into while as:
initialization;
while (condition) {
...
operation;
}
So in your case
i <= 5 && i >= -1; // Initialization
while(++i) { //condition
printf("%d \n", i);
i > 0; // operation
}
Initialization part will be execute once it will check for condition.Here in your case it is ++i so increment every time.Here i>0 means if i==0 then loop will stop it does not matter i is positive or negative Thumb rule to remember in this kind of situation is if (i == 0 ) then true else false. i>0 remains true)in every case after that so loop is infinite.
To understand for loop best answer I have seen in SO is this
There's not rule about the order of for loop condition and increment operation, the latter even don't need to be an increment operation. What it's expected to do is determined by you. The code is just same as the following semantically.
char i = 0;
i <= 5 && i >= -1; // Run before the loop and only once. No real effect here.
while (++i) { // Condition used to determine the loop should continue or break
printf("%d \n", i);
i > 0; // Run every time inside the loop. No real effect here.
}
BTW: It'll be an infinite loop (because ++i is a nonzero value until overflow).

Bound by confusion, needs clear explanation of post increment

guys i'm new at programming and i was surprised by the result of post increment value, now i'm bound by confusion after i found out and executed the code below, if for loop says
1. initialize
2. check for condition if false terminate
3. incrementation.
where does i++ happens? where does i value is equal to 1?
int main()
{
int i, j;
for (int i =0; i<1; i++)
{
printf("Value of 'i' in inner loo[ is %d \n", i);
j=i;
printf("Value of 'i' in outter loop is %d \n", j);
// the value of j=i is equals to 0, why variable i didn't increment here?
}
//note if i increments after the statement inside for loop runs, then why j=i is equals to 4226400? isn't spose to be 1 already? bcause the inside statements were done, then the incrementation process? where does i increments and become equals 1?
//if we have j=; and print j here
//j=i; //the ouput of j in console is 4226400
//when does i++ executes? or when does it becomes to i=1?
return 0;
}
if Post increment uses the value and add 1? i'm lost... Please explain... thank you very much.
I'm not really sure what you're asking, but sometimes it's easier for beginners to understand if rewritten as a while loop:
int i = 0;
while (i < 1)
{
...
i++; // equivalent to "i = i + 1", in this case.
}
Your loop declares new variable i and it shadows the i declared earlier in main(). So if you assign i to j outside of the loop, you are invoking undefined behaviour because i is not initialised in that context.
Prior to the first iteration, i is initialised to 0. This is the "initialize" phase, as you called it.
The loop condition is then evaluated. The loop continues on a true value.
The loop body is then executed. If there's a continue; statement, that will cause execution to jump to the end of the loop, just before the }.
The increment operator is then evaluated for it's side-effects.
Hence, it is after the first iteration that i changes to 1. i keeps the value 1 for the entirety of the second iteration.
It looks like you have a clash of variable names: i is declared before the loop, and also inside the loop.
The i that is declared in the for statement is the only one that will ever be 1. It will be one just after the body of the loop is executed.
Try setting a breakpoint and using the debugger to step through the loop whilst you watch the value of the variable (here's a video of what I mean by stepping with the debugger).
To remove the ambiguitity of having two variables called i you could change the for loop to:
for (i = 0; i < 1; i++) // remove the `int`
this will ensure that there is only one i in your code.
A comment on #CarlNorum's answer which wouldn't look good as a comment:
The C Standard defines
for ( A; B; C ) STATEMENT
as meaning almost the same thing as
{
A;
while (B) {
STATEMENT
C;
}
}
(where a {} block containing any number of statements is itself a kind of statement). But a continue; statement within the for loop will jump to just before the next statement C;, not to the next test of expression B.
for (i=0; i<x; i++)
Is equivalent to
i=0;
while(i<x) {
// body
i = i + 1;
}

exiting a while loop with a negative integer

I want to exit a while() when the user enters a negative number of any size. What kind of condition would I need at the start of the loop to get the loop to exit when the user enters a negative number?
Well, what is a negative number? It's a number (call it x) that is less than zero, or symbolically, x < 0. If x is less than zero, then this is true. If not, then it is false.
You can loop endlessly and break when this condition is met:
while (1) {
if (x < 0) {
break;
}
...
}
But I prefer to just use the opposite of that condition in the while loop itself:
while (x >= 0) {
...
While the condition is true, then the loop continues. When it is false (and your original condition is true, as these two are opposite), the loop breaks.
Use an if condition to know the number is less than 0 or not. And if yes, just use break statement inside it, which will bring you out of the loop. Learn more about break statement from MSDN.
int i = -1;
do
{
i = magic_user_input();
//simple enough? get a decent programming book to get the hang of loops
}
while(i > -1)
edit: sorry, my mistake: 'i' wasn't declared properly :) now it should be fine to use
Do not define your variable as unsigned variable. As suggested in other answers use if statement and break with if statement.
example:
int main(void)
{
int i;
while(1){
/*here write an statement to get and store value in i*/
if(i<0)
{
break;
}
/*other statements*/
return(0);
}
}

Resources