I'm trying out a for loop. I added an if statement to stop the loop once it reaches 30.
I have seen that i <= 10 will run 11 times, since the loop will still run when it reaches 10.
Why does the code below run 11 times (first print line) if there is an if statement that sets i back to 0 when it reaches 10? Shouldn't it only print 10 asterisks instead of 11 - since it never reaches the 11th loop? Also, the second if sets i back to 10, which should let the loop run one more time, through the first if, which would and then set the i back to 0?
int j = 0;
for (int i = 0; i <= 10; i++)
{
Console.Write("*");
if (i == 10)
{
j++;
Console.WriteLine("");
i = 0;
}
if (j == 30)
{
i = 10;
}
}
On the first loop, the line has 11 stars, because i iterates from 0 through 10, which is a total of 11 iterations.
Whenever i becomes the value 10, j is incremented, a newline is printed, and i becomes 0.
However, when i is set to 0 within the loop, the loop makes i iterate from 1 to 10, for a total of 10 iterations.
This is because i is incremented just before the next iteration starts.
A for loop with this structure:
for (INIT; CONDITION; INCREMENT) {
BODY
}
is more or less equivalent to this while loop:
INIT
while (CONDITION) {
BODY
INCREMENT
}
The caveat is when BODY has a continue statement, it actually jumps down to the INCREMENT part.
Related
Change the value of index from o to 1. loop is printing value. Why it is not printing any value when index is assigned to 0?
Currently i = 0 - No Output
Make i = 1 - infinite loop
#include<stdio.h>
int main()
{
for(int i = 0;i++;i<100)
{
printf("Mahesh\n");
}
}
enter code here
C for loop structure:
for ( init; condition; increment )
You have actually added i++ in the place of condition and i<100 in the place of increment.
Flow Control of for loop in C:
init step is executed first and only once.
Condition is evaluated next and if it is True, the body of the loop is executed. If False, the body of the loop doesn't execute and the flow jumps to the next statement after the for loop.
After the body of the loop executes once, the flow control jumps to increment statement and then condition is evaluated again.
Body of loop, Condition and increment steps are repeated in the same order till the condition becomes False after which the for loop terminates.
Your loop is:
for(int i = 0;i++;i<100)
In this, you have i++ as the condition. Now, in this i is evaluated first followed ++. Since, i is 0, it leads to the loop exiting as the condition evaluates to False. But, if you change i to 1, the condition (i.e. i) evaluates to True and it enters the loop.
If you have not done this deliberately, you need the loop like below:
for (int i = 0; i < 100; i++)
The syntax for a for loop in C is as follows:
for ( init; condition; increment ) {
statement(s);
}
-init: initialising the index variable with the value you would like to start the iteration at.
-condition: the condition for the iteration to continue until met
-incremenet: indicating how much you want the program to incremenet your index by
Hence in your example is should be:
for(int i = 0; i < 100; i++){
//yourcode
}
Hope that helps
The parameters of for loop are:
for(initialization; Condition; Next iteration initialization){
//code
}
The initialization(s) can be more than one separated by commas.
The condition will continue if have 1 (or the value TRUE which means the same thing as 1) or will break if the condition is not met i.e the value 0 (or FALSE). You can have multiple conditions as well by the use of && or || or commas.
The third parameter is what you want to do in the next iteration. It can have multiple commands too. I suggest you run the following code and change it to observe the results:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;
for( i=0,j=0;i<10 || j<5;i++,j++)
printf("%d\t%d\n",i,j);
return 0;
}
#include<stdio.h>
int main()
{
int i = 0;
// Postfix Increment Operator
for (i = 0; i++; i<100) // Condition is false, Because the i is Zero
{
printf("Mahesh");
}
printf("%d", i); // i outputs One here
// Prefix Increment Operator
for (i = 0; ++i; i<100) // Condition is True, Because the i is One
{
printf("Mahesh");
}
}
The following program was cited as going into an infinite loop:
#include<stdio.h>
int main()
{
int n;
for(n = 7; n!=0; n--)
printf("n = %d", n--);
getchar();
return 0;
}
On analyzing, I do find that at one point the value of n does become 0 and right then, the loop should terminate.
Won't it happen such that when it enters the loop for the first time, the value is 7, then it becomes 6, and since that there are 2 post-decrements per iteration?
But, why does that not happen?
Each loop iteration actually decreases n by two, and the comparison n != 0 always sees an odd value for i and hence never terminates.
In particular, just before the iteration in question, n is first decremented to 1 by n-- in the loop header (since this must occur after the end of the previous iteration, just before evaluation of the condition n!=0).
Then, printf("n = %d", n--); is evaluated, printing n = 1, while postdecrementing n to zero. After the end of the loop body, n is decremented again by n-- in the loop header, making it -1, just before the condition n!=0 is evaluated to determine whether the loop should continue.
As a result, n!=0 is true every time it is evaluated (in particular, it is not evaluated at the instant that n is zero, since the n-- in the loop header must first complete)
It's because of the second decrement in the print here:
for(n = 7; n!=0; n--)
printf("n = %d", n--);
That makes the sequence of checks against n go 7, 5, 3, 1, -1, ... There are an even number of values for an int so this will form a cycle upon underflow that leaves out the even numbers, including 0.
Remember that the for loop condition is evaluated just before each loop iteration, and after the decrement in the loop itself. It isn't tested while the loop is running.
try doing this
#include<stdio.h>
int main()
{
int n;
for(n = 7; n>=0; n--)
printf("n = %d", **--n**);
getchar();
return 0;
}
int i;
for(i=0; i<10; )
{
i=i++;
printf("Hello\n");
}
the following code is running into infinite loop. Can any one help me understand why?
Its an infinite loop due to the line i = i++ which works as follows. (Suppose i = 1)
1) 'i' is increased by 1. (So i = 2)
2) The value of i++ i.e. value before increment is assigned to 'i'. (So i = 1)
So, the value of 'i' won't change, condition 'i < 10' will never be false thereby leading to an infinite loop.
In the code below,
#include<stdio.h>
int main()
{
int k,sum;
for(k=7;k>=0;sum=k--)
printf("%d \n",sum);
return 0;
}
The output is:
0
7
6
5
4
3
2
1
I want to know how this loop executes and why isn't printing 0 in the last?
On first iteration sum is uninitialized. It has indeterminate value.
C11: 6.7.9 Initialization:
If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate.
Section 6.3.2.1 says that the behavior is undefined in this case.
In short, the sum variable is updated to be the same as k. After that update, k is decremented by 1 and then the loop runs
What that means is...
First loop, sum is uninitialised (hence the first 0)
the last time the loop runs, sum is set to k (1), k is decremented to 0. The loop runs. The condition is tested so the loop exits.
It all comes down the this: sum=k--. If you were to do sum=--k, k would be decremented before its value is assigned to sum.
Your program has undefined behaviour, since it is reading from an uninitialized variable in the first round of the loop (cf. C11 6.3.2.1/2).
Following code :
for(k =7; k >= 0; sum = k--)
//your code here printf("%d \n",sum);
can be expanded as:
k=7;
for(; k >= 0; ){
//your code here printf("%d \n",sum);
sum = k--;
}
In first run sum is uninitialized so your program have undefined behavior.
Try this
#include<stdio.h>
int main()
{
int k=7,sum;
for(sum=k=7;k>=0;sum=--k)
printf("%d \n",sum);
return 0;
}
The loop starts by taking the initial value of the sum which in this case is by default equal to zero as a result the first iteration displays 0 however on the second iteration init of sum takes place and it starts from 7 to onward 0
When k=1 then value of k is assigned to sum and it gets decremented to 0 . Thus sum = 1 and k = 0.
Now k=0 and as per the loop condition k>=0 is true. So it enters into loop body and prints value of sum as 1 . Now value of k is get assigned to sum and k decrements . Thus sum = 0 and k = -1 . But -1>=0 is false and loop execution stops .
Hence program is not printing 0 in the last.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n;
printf("Please give me an integer greater than zero!\n");
n=GetInt();
if(n<0)
{
printf("You are giving me a bad value!\n");
return 1;
}
for(int i=n-1;i<n;n--)
printf("%d\n",n);
return 0;
}
I would like to know why the loop is not going to infinity if the user enters in a number for n. Lets say that the user puts in 40 for n; wouldn't i always be n-1, so 39 and n being 40, then i becomes 38 when n becomes 39 and so on — so wouldn't that make an infinite loop?
for(int i=n-1;i<n;n--)
Lets draw a (really short) table for n = 40:
i | n
-----+-----
39 | 40 i < n ? true
39 | 39 i < n ? false
Thus, we'll exit the loop after the 1st iteration.
Clarification:
I guess you're confused because you think that i is updated in each iteration, but that's the point - it doesn't, its value is fixed and only n is changing.
This loop only runs once. Consider:
for(int i=n-1;i<n;n--)
With n == 40, on the first iteration, i = 39.
The condition i < n is true (39 < 40 == true), so we go in to the loop for the first time.
At the end of the first loop, n gets decremented to 39
The condition i < n is false (39 < 39 == false), so we don't get a second time through the loop.
Now, what happens if we make n increase instead of decrease? Will that run forever?
for(int i=n-1;i<n;n++)
The answer is "maybe, but probably not":
Eventually, n will reach the largest value that can be stored in an integer, INT_MAX (defined in limits.h, and on my system it is 2,147,483,647).
Making an integer larger than INT_MAX causes integer overflow.
The result of integer overflow on a signed integer is undefined, which means the result could be anything (and indeed, your program could crash).
On most systems, however, the value will probably wrap around to INT_MIN, or -2,147,483,648.
If this happens, i < n will be false, and your loop will terminate.
But, since integer overflow on signed integers is undefined behaviour, you can't be sure that this will happen. It is better to write your program to avoid this situation.
If you really want it to run forever - just write:
while(1) { ... }
or
for(;;) { ... }
These two loops have the advantage that they are common ways to write an infinite loop, and so they are easy for other programmers to read.
The reason is that i is never decremented, so it does only 1 loop:
i=39 n=40
i=39 n=39 -> stop
In order to decrement also i you should write:
for(int i = n-1;i<n;n--,i--)
i is only ever set once at the start of the loop. For example if the user enters 10 then i is 9 for the 1st iteration. By the 2nd iteration n is decremented by 1 and i is still 9.
n will underflow somewhen because int is signed and has a value range of -2147483648 to 2147483647 for example (x86).
Somewhen n will get more positive than i.
Edit:
The loop has at most 1 iteration.
Edit 2:
The loop would have no iterations if n would have the value -2147483648 for example because -2147483648 - 1 will make the value positive (two complement integer arithmetic). But this could never the case because the pre condition is that n may not be negative.
Your for loop:
for(int i=n-1;i<n;n--) {
printf("%d\n",n);
}
Translates into the following while loop:
{
int i = n - 1;
while (i < n) {
printf(%d\n", n);
n--;
}
}
The first clause of the for statement performs initialization. It is not repeated at each iteration, but only once. Thus, i never changes value, and so the loop ends after a single iteration.
This happens because you are decrementing n. At the second iteration i < n is false, you are exiting from the loop.
What will happen is:
//Example n = 100
for (int i = 100 - 1; 99 < 100; 100--)
//We now have 99 < 99 on the next loop
//After that you will have 99 < 98 etc.. it will only run once
To make the loop you want use:
for(int i = n-1; i > n ; n--)
To make an endless loop use:
for(;;) //or while(true)
your condition is wrong in the for loop..in your loop i is not changing only n is changing
try this
for(i=n-1;i<n;i--)
{
printf("%d\n",i);
}
you written perfect for loop...
for(int i=n-1;i
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
for(i=0;;)
{
printf("%d",i);
}
return 0;
}
or you can do anything else....
to put in infinite simply make ;; in the other two condition in loop.