Change values of variables in for loop - c

Why is it that the variable 'a' changes along the first declaration of a=x (for x=-6) as the for-loop continues, and why doesn't it change for the decrementation of x?
In short, why is a=-4 at the end of the loop and not a=-8?
int main()
{
int x,a;
for (x=-6,a=x;x>-10;--x,a++)
x--;
printf ("%d %d",x,a);
return 0;
}

Due to the double decrementation of x, the loop runs twice, not four times. Hence a=-4 is correct. (In any case, a=-8 would never occur, as a is incremented from -6.)

Related

C programming, Is this an infinite loop?

What would happen if the follow lines were a part of a compiled program?
void main() {
int x = 5;
while (x == 5);
}//end main
I believe it is, I have compiled it, and the screen just stays the same, I also tried to add after the while statement
int y = 10;
printf("%i", y);
and then end main. However it never prints. So I am fairly certain that its an infinite loop but I would just like to be sure.
Yes it is, but it could actually leave the loop in some scenarios:
There is a thread that changes the x variable.
An external program modifies the program memory.
As tadman said, a bitflip occurs on the memory itself, which is very unlikely but also a possibility.
There must be other cases where the loop can end, but those are the ones I could think of.
If you're interested, you can try to do so with Cheat Engine to change the value of x.
Yes it is an infinite loop since the condition to exit the loop will never be met: as the variable x is never changed inside the loop, the loop's condition will always be true.
Yes, it's an infinite loop. Remember, while the condition is true the while loop will continue. As 5 will always be equal to 5 the condition will always be true, even if you don't do anything inside the while loop.
try:
void main() {
int x = 5;
while (x == 5){
printf("%d\n", x);
}
}
Use format %d for doubles

C program recursive call to main() with and without parameters

Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?
#include <stdio.h>
int main()
{
static int i = 2;
if (i<7)
{
main();
printf("%d ", i);
i++;
//main(10);
}
}
-
#include <stdio.h>
int main()
{
static int i = 5;
if (--i)
{
//main();
printf("%d ", i);
main(10);
}
}
You are calling main() first and then incrementing i
if (i<7)
{
main(); // <-- main called when i still 2
printf("%d ", i);
i++; // <-- statement never reached
//main(10);
}
Hence, while main() calls main() recursively, the statement i++ is never reached.
You should increment i before calling main()
if (i<7)
{
i++;
main();
printf("%d ", i);
//main(10);
}
1st case the i++ after the call of main(), that means the program has no chance to add the i, and into infinity loop, and stackoverflow! haha....
but the 2nd case, it's reduce the i before you call the main.
TL;DR StackOverflow (Pun or no pun, it's true both ways).
First: Some important information
This case has nothing to do with passing an argument to main() or not. Actually, as per the latest C standard, C11, for a hosted environment, the conforming signature of main() is int main(void) and following that, main(10); is wrong, altogether.
Now, coming to the actual problem here,
In the first case, change of i value happens after the call to main(), so in effect, the value of i never get changed because the control never reaches the statement which modifies i. Hence, it's an infinite loop, and because of the recursive call to main(), stack overflow happens.
In later case, i value gets updated before call to main(), so that value actually reflects. Thus, at some point (after 4 occurrences, actually), the if condition meets a FALSE condition and the recursive call ends and the stack unwinds.
First case:
i++ is positionned after the call to main. So i will always be equal to 2, as you never reach this part of the code. You are then calling your main function everytime, leading to an infinite recursion, and thus to the segmentation fault. The fix for this case would be to increase i before calling the main function.
if (i<7)
{
i++; // Increment before calling the main function, so i value is changed
main();
printf("%d ", i);
}
Do note that it will lead to something which looks like your second case, except that you will print several "7".
Seconde case:
In the second case, you are decreasing the value of i everytime you enter your if condition. When you finally can't enter your if condition anymore, it means i is equal to 0 (as if(0) is equivalent to if(false)). Everytime you will return to the previous called main function, i will still be equal to 0, explaining why you are displaying "0" everytime. If you want to print the different values, you can place your printf before the call to the main function for instance.
In the first case:
"i" is never incremented therefore you run in an infinite loop and get an overflow.
In the second case:
You call the recursion before displaying the value of "i", after four calls "i" equals to 0 and your recursion stack unwinds.
Modify your condition and perform outputs before the recursion call.
In the first case, i is never incremented, hence, the main keeps getting called and soon enough there is no more stack memory available to the program.
In the second case, the last updated value of i is intact throughout the lifetime of i. As i is static, program is referring to the same memory address on all the iterations. While printing i you see the last updated value, that is 0, as output.

How to get value of a variable before a loop after loop is executed?

I would like to know if there is a way to get the value of an integer variable before it entered the loop, after the loop has been executed.
For example:
#include <stdio.h>
int main(){
int x;
x = 1;
printf("%d\n", x);
while(x < 2000){
x++;
printf("%d\n", x);
}
printf("before the loop, X had a value of %d", x);
}
Is there a way to have the final printf() print the value of xwhich the x was holding before entering the while() loop? Or is the only way to create a copy of x using another variable before the loop?
In the abstract context you would typically have two options:
"Think ahead" approach: store the original value beforehand, i.e. create a copy before applying any modifications to the original value.
"Turn back time" approach: use the new value as a starting point to "revert" all modifications and thus arrive at the original value.
In general case there are trade-offs associated with each approach.
Applied to your specific simple example, these two approaches involve either storing the copy of the variable before the loop, or "undoing" the changes done by the loop (by using your intimate knowledge of this loop's semantics). The latter in this case boils down to
printf("before the loop, X had a value of %d", x - 1999);
No, there's no magical way to get the initial (any previous state, for that matter) value of a variable, once it is modified. You have to create (maintain) a copy yourself.
Assign the old value before the loop to another variable:
int x;
int old_x;
x = 1;
printf("%d\n", x);
old_x = x;
while(x < 2000){
x++;
printf("%d\n", x);
}
printf("before the loop, X had a value of %d", old_x);
Or vice versa, use different variable forthe loop and keep original untouched.
There is no magic the compiler could do it for you.

for(++i;++i;++i) the second argument is < or <=?

In this for loop statement
#include<stdio.h>
int main()
{
static int i;
for(++i;++i;++i) {
printf("%d ",i);
if(i==4)
break;
}
return 0;
}
Variable i is at first 0. The arguments in the for-loop at 1st round are 1st ++i: i = 0 + 1 = 1 2nd ++i: i=1+1=2 So, in first loop I have this for(i=1; i<2; ++i); or for(i=1; i<=2; ++i);?EDIT I found this example online in a test about C. I run this (inside the for-loop , I have a break point so after some loops it breaks) but I was just guessing the behavior of that so I asked it here to be sure. I am learning now C so stupid questions exists for me. Its better to ask, than not.
In the second argument it is actually ++i!=0, The loop is interpreted as
for(++i;++i!=0;++i)
If you start with a positive i or 0, it will be an infinite loop and will invoke undefined behavior when i reaches INT_MAX.
If i was -Ve initially the loop may stop at a defined run.
EDIT: As you changed your question, Your code will not crash, but you can clearly understand the dry-run by replacing the second ++i with ++i!=0.
So the 1st iteration becomes:
(i=1;2!=0;++i/*this will execute later*/)
2nd iteration becomes:
i=3 //this is from the 1st iteration last part.
(/*initialization is done 1st time only*/;4!=0;++i/*again, this will execute after this iteration*/)
It will print 2 4.
Before the for loop, i will be 0. It hasn't been assigned anything yet, and static variables are guaranteed to be zero initialized before they are first used.
It will execute the first ++i in the for loop, since that expression is evaluated once at the beginning of the loop. i will be 1.
It will execute the second ++i, because that is evaluated BEFORE every loop to see if it should run an iteration of the loop. i will be 2.
It will run the loop body. This will print 2.
The if condition won't be true so it won't break.
It will execute the third ++i in the for loop statement, since it evaluates that AFTER every iteration. i will be 3.
It will execute the second ++i again, since it needs to see if it needs to run another loop. It will be nonzero, so it will run another loop. i will be 4.
It will print 4.
The if condition will be true, it will break out of the loop.
However, it is a nonsense way to do it. This is a more appropriate way to do that:
int i;
for (i = 2; i <= 4; i += 2)
printf("%d ", i);
or better yet:
printf("2 4 ");
static int i;
While the C standard guarantees that variables with static storage duration are initialized to 0, you should not abuse that. Always initialize your variables, either at the line where they are declared or in runtime. So change this to static int i=0;
The first ++i is indeed equivalent to having i=1 there. Esentially your loop does this:
for(i=1; loop_until_program_crash; i++)
If you have a break inside the loop, then the loop is likely poorly written. If you know in advance when the loop should end, then that condition should be inside the for loop condition. If you don't know in advance, then use a while loop instead.
It should be :
for(i=1; i<=2; ++i);
static int i=0;
for(++i;++i<=2;++i)
{
printf("4rth :%d\n",i);
}
see : http://ideone.com/TGLYlL

Explain the output of a c program

#include<stdio.h>
main()
{
static int i=1;
printf("\nSoftware");
for(;i<5;i++)
main();
return 0;
}
The output comes out to be an infinite loop. Please explain.
You are calling a main function from your main function. After you call new main function it will print some string and then again it will call main function.
Your i variable will not be incremented at all, because it is not incremented in the first iteration of for loop. After you call main, it will never return to previous main to next iteration of for loop to happen. So the loop will be infinite and i will be equal to 1. Even if you changed the for loop to any other loop, the loop will be still infinite.
I'm including your repaired code, just for the fun of it:
#include<stdio.h>
int main()
{
static int i=0;
if(i>=5) return 0;
i++;
printf("\nSoftware %i", i);
main();
return 0;
}
When one iteration of Loop finishes then value of i is incremented. But in your case before increment it is again calling the main() function. Hence your Code is in infinite loop.
It is not an infinite loop.
Your are recursively calling main but never give an end to it. This results in a stack overflow.
i++ is never evaluated, because you never reach the end-of-scope of the for loop.
This isn't seem to be any difficult or different.In this program for loop do not matter much, so whenever a main() is called inside the same it is definitely a infinite loop.With use of Conditional statements you can restrict the infinite loop. Also that static int do not matter at all.So obviously main get called infinite number of times until time out occurs.
This is infact self explanatory
Calling main function in a loop eats up all your memory and causes stack overflow.
Yeah definitely the output comes out to be infinite because in for(;i<5;i++) the increment of i occurs only at the last line of the for loop. So, here the value of i never incremented.
for example:
for(i=0;i<5;i++)
{
int a,b; // just an example
a=10;
b=20;
printf("%d",i);
printf("%d %d",a,b);
// increment of i takes place here at the last line of for loop
}
Same as here also:
main()
{
static int i=1;
printf("\nSoftware");
for(;i<5;i++)
{
main();
// increment of i takes place here.But compiler never comes at this line .That's why i never incremented .
}
return 0;
}
the code call main function, again and again
for(;i<5;i++)
main();
i<5 call main()
i<5 call main()
i<5 call main()
...
If u want to call some function 5 times.
include
void myFunc()
{
printf("\nSoftware");
}
main()
{
static int i=1;
for(;i<5;i++)
myFunc();
return 0;
}
Im used to c++ so it could be a some small mistake.
Its a kind of Recursive Call. Your main function is calling itself resulting into an infinite loop.

Resources