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);
}
}
Related
So I've seen this used before some of my profs code aswel as in some of my friends who have more experience with programming.
int number = 0;
while(number) {
a bunch of code
}
My understanding is that this while loop is essentially running with no condition, i feel like it should be
while(number = 0) {
Isnt this essentially creating an infinite loop? but in the cases I've seen it used it can break out of the loop somehow.
edit:
do while that uses the argument in question. Note that the 2 functions being called in the switch case will call searchpatientdata again once they have completed.
This code is not currently wokring, but was working in a previous build and this function was the same. They also do not change the selection variable either.
The condition in a while loop can be any expression of scalar (numeric or pointer) type. The condition is treated as false if the result of evaluating the expression is equal to zero, true if it's non-zero. (For a pointer expression, a null pointer is equal to zero).
So while (number) means while (number != 0).
As a matter of style, I prefer to use an explicit comparison unless the variable is logically a Boolean condition (either something of type bool or _Bool, or something of some integer type whose only meaning values are true and false) -- but not everyone shares my opinion, and while (foo) is a very common way to write while (foo != 0).
The same applies to the condition in an if, a do-while, or a for statement.
Note that in your example:
int number = 0;
while(number) {
// a bunch of code
}
the body of the loop will never execute, because number is equal to zero when the loop is entered. More realistically, you might have:
int number = some_value;
while (number) {
// a bunch of code *that can change the value of number*
}
Any place in C where a Boolean value is required, any number will be evaluated like this:
zero → false
not zero → true
From C reference
Executes a statement repeatedly, until the value of expression becomes equal to zero. The test takes place before each iteration.
How it works?
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
Come to point as per OP's question yes
While (Variable_name) evaluated as True
In below Example While loop executes until condition is true
Example:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num=1;
while(true)
{
if(num==5)
{
break;
}
printf("%d\n",num);
num++;
}
return 0;
}
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!
int main(){
char s[10];
int t,n,i,a,w;
scanf("%d",&t);
while(t--)
{
w=0;
scanf("%d%s",&n,s);
for(i=0;i<n;i++)
{
scanf("%d",&a);
if(a%2==0)
w++;
}
if(n==1 && w==1 && strcmp(s,"Dee") == 0)
printf("Dee\n");
else
printf("Dum\n");
}
return 0;}
while(t--)?
Is this while(t=t-1)?
That is never true for any given integer of t?
while (t--) {
...
}
means evaluate whether t be true or false, then decrement t afterwards. So if you input a value of 1 for t, then the above loop will actually iterate once, then terminate.
If, on the other hand, you had the following loop:
while (--t) {
...
}
if you entered 1 for t then the loop would not even execute once, because t would become zero before it is evaluated by the loop.
t=t-1 and --t are both same. --t is just a short notation.
while() exits if either it is false or 0.Any number other than 0(may be positive or negative) in the loop is always true After every loop execution/iteration t value gets decremented by 1 value. It continues till the value of t becomes 0 and exits the loop.
t-- is called as post decrement. It first checks and then decrements the value.
--t is called as pre decrement. It first decrements the value and then checks.
while (t--) is almost equivalent to for(t = x; t>0; t--) , except for the case t<0. when, t<0, for loop doesn't execute, but the while loop executes for unlimited time and the code crashes.
Here, x is the value by which t is initialized before running the while loop.
In a while loop while(x){ ---- }, if x>=1 , then loop will be executed but when x becomes <=0 , loop will be terminated.
So, in this question, let us say t=2, as in while condition statement the value is 2 , the loop will be executed but before that t is decremented to 1. Similarly, t is decremented to 0 and loop will run one more time.
Now, 3rd time when loop tries to run value of t is already 0, so it will be terminated
while(t--)
{
//code
}
This loop will execute till the value of t becomes 0.
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.
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).