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
Related
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.)
So I'm working on a square root calculator and I don't know if a while loop is better suited compared to a do while loop.
double x, y = 1.0, newY, squareRoot;
bool end = true;
printf("Enter a positve number: ");
scanf("%lf", &x);
//So here is the loop so which loop would be more effective and why?
do{
newY = x / y;
squareRoot = (newY + y) / 2.0;
if (fabs(y - newY) < 0.00001)
end = false;
else
y = squareRoot;
} while (end != false);
printf("The square root is %.5f\n", y);
If you are iterating over a known range of things, use a for loop. If you are iterating and are not sure how many things you have, but know when to stop, use a while loop.
In your example, a while loop is a good choice, because you know you'll do some number of iterations (with do...while, at least one), and you know what the termination condition is: fabs(y - newY) < 0.00001.
As a side note, this code assumes you will for sure always converge. If you were not absolutely sure, you'd want to add a iteration count, increment it inside the loop, and make the end-the-loop condition check it as well: while( fabs(y - newY) >= 0.00001 && iterations < SOME_LIMIT). And of course that condition could be the while condition; you don't have to have the end boolean to stop the while.
do-while is an exit control loop and while is an entry control loop.
There are cases where you want to execute the statement inside the loop at least once. For e.g. taking input from a user and if the input is invalid then ask the user for valid input otherwise exit loop. do-while loop is more suitable in such kind of scenario.
On the other hand, in while loop condition is checked before entering into the loop. So if the condition is false for the first time, the statements inside while loop will not execute.
There could be many complex problems where the number of iterations depend upon a certain condition and can't be predicted beforehand, while loop is preferable in those situations.For e.g. reading a file, you don't know how big the file is but you know at some time you will hit end-of-file.
Similarly, in your case, you know the loop termination condition -
if (fabs(y - newY) < 0.00001)
end = false;
but you don't know how many iterations are required beforehand. Also, there are scenarios where you don't need to execute any statement of the loop body, like if the user gives input 1.
So, while loop is more appropriate in your case.
You should use a do-while when the break condition may be true on first evaluation and you still want to execute the body of the loop at least once. E.g.
bool temp = false;
while (temp == true)
{
printf("Hello from the while!\n");
}
do {
printf("Hello from the do!\n");
} while (temp == true);
The do-while in this case will always execute the body of its scope at least once, where as the while loop will always evaluate its conditional before running the code contained in its body.
Output of program:
Hello from the do!
I just started programming in C, and while practicing with for loops, I came up with the following piece of code:
#include <stdio.h>
int main()
{
int x;
for (x=0;x=10;x=x+1)
printf("%d\n",x);
return 0;
}
When I run the code, I fall into an infinite loop. In my C manual it says that the condition x =10 is always true, but I can't get my head around it. If I give the variable x a value of 0 at the beginning, should the for loop not even start, or when the value of x reaches 10, shouldn't the loop stop?
Thanks in advance!
The condition part of your for loop is wrong. What you are doing is :
for (x = 0; x = 10; x = x +1) {
// Operations
}
The condition you have got here is x = 10 which is an affectation. So x = 10 will return 10, which also means true. Your for loop is equivalent to :
for (x = 0; true; x = x + 1) {
// Operations
}
This is why you have got an infinite loop, you should replace the affectation operator = by the comparason one with two equals sign ==. This means the for will loop while x is equals to 10.
EDIT : As Virgile mentioned in comments, for the second for loop, x will go from 0 to INT_MAX, then the behavior is undefined. So, your code is more likely to look like :
for (x = 0; true; x = 10) {
// Operations
}
When entering a for loop, the initialization part is performed first. So after the loop initialization x is 0.
Before entering the body of the loop, even the first time, the condition is checked. The "condition" in this case does not compare x to 10 but sets it to 10 since you are using = instead of ==.
Since an assignment as an expression has the value of the variable after assignment, the conditional expression has a value of 10 since that is what was assigned to x. Because this value is non-zero, it evaluates to true, and always will.
The problem here is, Take a close look on the condition part(2), in this what x=10, means is it is just assigning the value 10 to x, and it returns "True" always, so no problem what you have incrementing, it comes to 10 always, Thus infinite loop.
What you are trying to do is, you are implicitly converting int to bool in this line:
for (x=0;x=10;x=x+1)
^^^^
here, x=10; results true
So, it prints 10 everytime as you are using the = assignment operator.
for(int x=0;true;x=x+1)
What you could do to maintain the loop?
Use relational operators:
for (x=0;x!=10;x=x+1)
for (x=0;x==10;x=x+1)
for (x=0;x<10;x=x+1)
I have a doubt about the for loop of the following code in C:
main()
{
int i=1;
for(;;)
{
printf("%d",i++);
if(i>10)
break;
}
}
I saw this code in a question paper. I thought that the for loop won't work because it has no condition in it. But the answer says that the code has no error. Is it true ? If true, how ?
The regular for loop has three parts:
Initialization
Condition
Increment
Usually they are written like this:
for (initialization; condition; increment) { statements }
But all three parts are optional. In your case, all parts are indeed missing from the for loop, but are present elsewhere:
The initialization is int i=1
The condition is if (i>10) break
The increment is i++
The above code can be equivalently written as:
for (int i=1; i <= 10; i++) {
printf("%d", i);
}
So all the parts necessary for a for loop are present, except they are not inside the actual for construct. The loop would work, it's just not a very readable way to write it.
The for (;;) loop is an infinite loop, though in this case the body of the loop takes actions that ensure that it does not run forever. Each component of the control is optional. A missing condition is equivalent to 1 or true.
The loop would be more clearly written as:
for (int i = 1; i < 11; i++)
printf("%d", i);
We can still debate whether the output is sensible:
12345678910
could be produced more easily with:
puts("12345678910");
and you get a newline at the end. But these are meta-issues. As written, the loop 'works'. It is syntactically correct. It also terminates.
You are not specifying any parameters or conditions in your for loop, therefore, it would be an endless loop. Since there is a break condition based on another external variable, it would not be infinite.
This should be re-written as:
for (int i = 1; i <= 10; i++)
printf("%d",i++);
It's an infinite loop. When there is not a condition in for and we use ;; the statements in the body of for will be executed infinitely. However because there is a break statement inside it's body, if the variable i will be greater than 10, the execution will be stopped.
As it is stated in MSDN:
The statement for(;;) is the customary way to produce an infinite loop which can only be exited with a break, goto, or return statement.
For further documentation, please look here.
Even if a for loop is not having any condition in it, the needed conditions are specified inside the for loop.
The printf statement has i++ which keeps on increasing the value of i and next we have if statement which will check if value of i is less than 10. Once i is greater than 10 it will break the loop.
Several books show me how to correctly write for, while, and do loops.
Lots of online articles compare them to each other.
But I haven't found any place that tells me what not to do. For example, would it screw things up if I change the value of the counter or condition variable within the loop?
I would like an answer that is not machine dependent.
Yes you can change the counter within a loop and it can sometimes be very useful. For example in parsing command line arguments where there is an option flag followed by a value. An example of this is shown below:
Enter the following command:
program -f filename -o option -p another_option
Code:
#include <string.h>
int main(int argc, char** argv)
{
char *filename, *option, *another_option;
if(argc > 1){
for(int i=1; i<argc; i++){
if(strcmp(argv[i],"-f")==0){
filename = argv[++i];
} else if(strcmp(argv[i],"-o")==0){
option = argv[++i];
} else if(strcmp(argv[i],"-p")==0){
another_option = argv[++i];
} else {
printf("Option \"%s\" not recognized, skipping\n",argv[i]);
continue;
}
}
} /* end if argc > 1 */
return 0;
}
The example program automatically increments the counter to access the correct command line string. There are of course ways to incorporate counters etc., but they would only make the code more cumbersome in this case.
As others have pointed out, this is where many people write bugs and one must be careful when incrementing counters within loops, particularly when the loop is conditional upon the counter value.
It is not invalid to change a loop counter inside a loop in C.
However, it is probably confusing to future readers and that's a good reason not to do it.
It depends on what you mean by "screw things up".
If you know what you are doing, you can change counter. The language has no restrictions on this.
Changing the counter variable in the loop is allowed, but be careful to know what you are doing to not create infinite loops by decreasing the variable when you shouldn't be.
Some algorithms actually benefit from this, but of course if you do this it makes your code less readable so make sure you comment what you are doing also.
Yes, you can change the counter and condition variables. They will just be evaluated with the next iteration of the loop.
Definiteley you can.But be careful not to make the loop disorder. Alter a conter in the loop happens a lot in do...while and while.
do{
counter++;
some expressions;
}
while(counter < SOMEVALUE);
Yes, in C/C++/C# You can change the counter etc. in the loop.
Like many other techniques, as long as you know what do you do, it's fine.
For example, this code:
int i;
for (i=0;i<5;i++)
printf("%d\n",i--);
is an infinity loop, but this version of bubble sort:
int *arr,n;
//allocate memory, assign values, and store the length of the array in n
int i;
for (i=0;i<n-1;i++)
if (arr[i]>arr[i+1]) {
int temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
if (i) i-=2;
}
is fine. (It's not exactly bubble sort. Instead of using nested loops, I go back in the array after swapping members in it)
Be careful changing counter variable inside a loop, not all loops are the same, "while" loop behaves differently. see this example?
No, it is NOT an infinite loop (on some compilers). run it, and see...
i=5;
while (i--)
{
i=100;
printf("%d \n",i)
}
We can change the counter value inside the loop but the final counter value wont be reflected as the for loop wont override the counter value.
here is the example in QTP VB script.
iLast = 4
For i= 1 to iLast
iLast=2
Next
Here the for loop should execute only for 2 times as iLast value is updated to 2 inside the loop but it is executing for 4 times.