printf("What do you do?\n1. Walk Away.\n2. Jump.\n3. Open Door.\n\n");
scanf("%d",&Choice);
printf("\n\n\n");
while(4<=Choice,Choice<=0);
{
printf("That is not a choice.\n");
printf("What do you do?\n1. Walk Away.\n2. Jump.\n3. Open Door.\n\n");
scanf("%d",&Choice);
printf("\n\n\n");
}
So this is my program. It works but what I want it to do is to repeat until an answer of 1, 2, or 3 is put in. But no matter what the answer is it has it go through the while loop then continue regardless of the next choice. (Also, I did declare "Choice"; I just didn't want to show the whole program.)
There are two problems in your code. Your while-loop expression is incorrect. The comma does not do what you think it does: in C/C++, the comma executes the left-hand expression and evaluates to the right-hand expression, meaning that in your case you are only checking the second condition. You probably want:
while(4<=Choice || Choice<=0)
The || is the OR operator, which returns true if either of the expressions around it are true.
Secondarily, there is a misplaced semicolon at the end of the while loop:
while(4<=Choice,Choice<=0); //<-- this should not be here
This marks the end of the loop, meaning that your code is parsed as:
while(4<=Choice,Choice<=0); //loop body is empty
{
//and we have a random unnamed block following it
}
Remove the semicolon and your while loop should execute correctly.
C and C++ have a comma operator, which has the lowest precedence of all operators. It evaluates the left operand and throws the result away, and then evaluates the right operand. Thus, your while condition is equivalent to:
while (Choice <= 0)
You also have a bug because there is a semicolon immediately after the condition, which makes for an infinite loop if Choice is not strictly positive (because nothing in the loop changes the value of Choice).
What you probably intended to write was:
while (Choice >= 4 || Choice <= 0)
{
...
}
The comma operator , doesn't test both conditions, it simply returns the second of the two. So your while loop is the equivalent of:
while(Choice<=0) ;
and since there's a ; following the statement, it is in fact an infinite loop if the condition is met. Good thing you didn't enter a choice of -1.
Related
This is a model solution code of the following problem;
"The input consists of T test cases. The first line of the input is given a T.
Each test case consists of three rows of integers separated by a single space, each consisting of three random points of x and y coordinates. The coordinates of the top left pixel in the browser viewport are (1, 1) and the coordinates of the bottom right pixel are (1000, 1000). All coordinates are located within the viewport and the positions of each point are different."
And here is the sample of the input.
2
5 5
5 7
7 5
30 20
10 10
10 20
7 7
30 10
The last two lines are the answers of the problem.
And here is my three questions.
1) What happened when we use cin statement in initialization?? It receives how many actions it will perform from the user in the initialization of for loop. I understand that this cin statement works properly. I cannot understand how this code knows how many times this for loop has to be repeated. This is because there is no action on T after initialization with a value of T from the user. There is no actrion in 'increment/decrement' also.
2) After googling, I understand when there is cin in condition, the loop ends when there is no more inputs or the inputs' type does not match the variables' type. But in this code, the for loop ends when the repeated time (T) is over. How could this happen???
3) Finally, the outcomes should be presented after all inputs are finished not by one-by-one. Then how could this for loop memorize the outcome of each set(3 inputs)??
I'm not English speaker T.T Thank you for reading my question.
#include<iostream>
int main()
{
int T,a,b,c,A,B,C;
for(std::cin>>T; std::cin>>a>>A>>b>>B>>c>>C; printf("%d %d\n",a^b^c,A^B^C));
}
What happened when we use cin statement in initialization??
That part of for() loop can contain any simple statement, not
just initialization statement. This statement is done only once. For
loop
for ( init condition ; iteration )
statement
is actually equivalent of this code:
{
init
while ( condition )
{
statement
iteration;
}
}
But in this code, the for loop ends when the repeated time (T) is
over. How could this happen???
The operator >> overloaded for streams return stream it acted on. Class
ios_base which is common parent of all streams, contains this
operator
std::ios_base::operator bool()
This operator is an equivalent of good() method. When >> fails to read and parse values from input stream, good() returns false,
loop breaks. T is not used in the provided code.
Then how could this for loop memorize the outcome of each set(3
inputs)??
It doesn't. It prints result after reading each set.
PS. People who read\proof-check code after programmer, would tend to have murderous intent toward those who write for() loops like that.
If we use a cin statement as our initialization, we execute this once. It will receive the input and place the value in the variable T. You are completely right; there is no action on T after initialization such as incrementing or decrementing its value.
This is not true. The code does not end when the it repeated T times. As long as (valid) input is given, this for-loop will continue. This is because the condition part of your for-loop consist of a cin statement. That is, as long as your cin statement succeeds, the for-loop will continue.
It cannot. Each time the loop runs, you overwrite the variables a, A, b, B, c and C. Hence, the old values are lost.
I would like some confirmation (or refutation) about something.
I was just busy with a simple exercise placing statements inside loop conditionals. Basically I created an array of 5 elements and then have the user input 5 values that will be stored in the array. Pretty basic stuff. But then I started wondering: What if I replaced the a[i++] in my code with simply a[i]? So I did, and the resultant output was that I (i.e. the user) just kept inputting values seemingly infinitely, i.e. not stopping at only 5 inputs.
Now then I made the assumption that what might be happening is that now the program simply replaces every new input value with the previous one and storing it in element 0 of the array, over and over, hence it not stopping at 5.
Is this assumption of mine is correct? If not, then please shed some light on what exactly is happening here. This might be a very nonsensical thing to be concerned about, but I'd really like to know either way.
//array test
#include <iostream>
int main()
{
int a[5] = { 0 };
int i = 0;
while(std::cin >> a[i++] && i < 5);
return 0;
}
So, you are basicly asking what's the difference between i and i++? It's rather basic C/C++ (note the ++ here!). I suggest you google for "C++ postincrement operator" :)
If you remove the i++ and replace it with only i, you are replacing a[0] indefinitely.
a[i++] evaluaves to a[i], and AFTER that increases i by one. So when i reaches 5, the second part of your condition (i<5) is not true and exits from the while loop.
Yes, you're correct.
Just test it, remove the ++ and run.
If you want "having a loop with no code inside", do not use std::cin >> a[i++] expression as condition (I think it will always true). Better use comma operation, e.g.:
while(std::cin >> a[i++], i < 5);
Moreover, in the condition expression like (std::cin >> a[i++]) && (i < 5) left part (i.e. (std::cin >> a[i++])) can be skipped because optimization done by compiler (so i++ will not be executed).
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
I came across this on codegolf
Please explain the usage of ? and : and why is there no statement following the while loop? As in why is there a ; after the parenthesis.
There is a boolean operation going on inside the parentheses of the while loop:
while (boolean);
Since the ternary operator is a boolean operator, it's perfectly legal.
So what's this doing? Looks like modular arithmetic, printing going on over a range up to 101.
I'll agree that it's cryptic and obscure. It looks more like a code obfuscation runner up. But it appears to be compilable and runnable. Did you try it? What did it do?
The ?: is a ternary operator.
An expression of form <A> ? <B> : <C> evaluates to:
If <A> is true, then it evaluates to <B>
If <A> is false, then it evaluates to <C>
The ; after the while loop indicates an empty instruction. It is equivalent to writing
while (<condition>) {}
The code you posted seems like being obfuscated.
Please explain the usage of ? and :
That's the conditional operator. a ? b : c evaluates a and converts it to a boolean value. Then it evaluates b if its true, or c if its false, and the overall value of the expression is the result of evaluating b or c.
So the first sub-expression:
assigns t-i%10 to i. The result of that expression is the new value of i.
if i is not zero, the result of the expression is i/10
otherwise, print j, and the result of the expression is zero (since printf returns a non-zero count of characters printed, which ! converts to zero).
Then the second sub-expression, after ||, is only evaluated if the result of the first expression was zero. I'll leave you to figure out what that does.
why is there no statement following the while loop?
There's an empty statement, ;, so the loop body does nothing. All the action happens in the side effects of the conditional expression. This is a common technique when the purpose of the code is to baffle the reader; but please don't do this sort of thing when writing code that anyone you care about might need to maintain.
This is the Conditional Operator (also called ternary operator).
It is a one-line syntax to do the same as if (?) condition doA else (:) doB;
In your example:
(i=t-i%10 ? i/10 : !printf("%d\n",j)
Is equivalent to
if (i=t-i%10)
i/10;
else
!printf("%d\n",j);
?: is the short hand notation for if then else
(i=t-i%10 ? i/10 : !printf("%d\n",j)<br>
equals to
if( i= t-i%10 )
then { i/10 }
else { !printf("%d\n",j) }
Your while loop will run when the statement before the || is true OR the statement after the || is true.
notice that your code does not make any sense.
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
in the most human-readable i can do it for u, it's equivalent to:
while (i < 101)
{
i = (t - i) % 10;
if (i > 0)
{
i = i / 10;
}
else
{
printf("%d\n",j);
}
i = ++j;
if (i < 0)
{
i = i - j;
}
else
{
i = j;
}
}
Greetings.
I am the proud perpetrator of that code. Here goes the full version:
main()
{
int t=getchar()-48,i=100,j=-i;
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
}
It is my submission to a programming challenge or "code golf" where you are asked to create the tinniest program that would accept a digit as a parameter and print all the numbers in the range -100 to 100 that include the given digit. Using strings or regular expressions is forbidden.
Here's the link to the challenge.
The point is that it is doing all the work into a single statement that evaluates to a boolean. In fact, this is the result of merging two different while loops into a single one. It is equivalent to the following code:
main()
{
int i,t=getchar()-'0',j=-100;
do
{
i = j<0? -j : j;
do
{
if (t == i%10)
{
printf("%d\n",j);
break;
}
}
while(i/=10);
}
while (j++<100);
}
Now lets dissect that loop a little.
First, the initialisation.
int t=getchar()-48,i=100,j=-i;
A character will be read from the standard input. You are supposed to type a number between 0 and 9. 48 is the value for the zero character ('0'), so t will end up holding an integer between 0 and 9.
i and j will be 100 and -100. j will be run from -100 to 100 (inclusive) and i will always hold the absolute value of j.
Now the loop:
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
Let's read it as
while ( A || B ) /* do nothing */ ;
with A equals to (i=t-i%10?i/10:!printf("%d\n",j)) and B equals to (i=++j<0?-j:j)<101
The point is that A is evaluated as a boolean. If true, B won't be evaluated at all and the loop will execute again. If false, B will be evaluated and in turn, if B is true we'll repeat again and once B is false, the loop will be exited.
So A is the inner loop and B the outer loop. Let's dissect them
(i=t-i%10?i/10:!printf("%d\n",j))
It's a ternary operator in the form i = CONDITION? X : Y; It means that first CONDITION will be evaluated. If true, i will be set to the value of X; otherwise i will be set to Y.
Here CONDITION (t-i%10) can be read as t - (i%10). This will evaluate to true if i modulo 10 is different than t, and false if i%10 and t are the same value.
If different, it's equivalent to i = i / 10;
If same, the operation will be i = !printf("%d\n",j)
If you think about it hard enough, you'll see that it's just a loop that checks if any of the decimal digits in the integer in i is equal to t.
The loop will keep going until exhausting all digits of i (i/10 will be zero) or the printf statement is run. Printf returns the number of digits printed, which should always be more than zero, so !printf(...) shall always evaluate to false, also terminating the loop.
Now for the B part (outer loop), it will just increment j until it reaches 101, and set i to the absolute value of j in the way.
Hope I made any sense.
Yes, I found this thread by searching for my code in google because I couldn't find the challenge post.
I'm asking the user for an input, but I want the question to stay on screen until the input meets one of the allowed inputs. Here's my code
string input = "";
string departure = "";
cout << "Please enter an airport code: ";
do
{
getline(cin,input);
stringstream(input) >> departure;
} while(departure.compare("MAN") != 0 || departure.compare("EMA") != 0 || departure.compare("LHR") != 0 );
}
I want it to loop until the user enters MAN or EMA or LHR; also if they are lowercase I would like for it to be accepted aswell.
Every time I run this, even if I enter a correct input, it just keeps taking words in and doesn't do anything else.
The condition
departure.compare("MAN") != 0 || departure.compare("EMA") != 0 || departure.compare("LHR") != 0
is always true, regardless of what departure is.
compare returns 0 on equality. So what you're basically telling the compiler is
Run the loop while departure is different than "MAN" OR different than "EMA" OR different than "LHR".
You need && instead of || in your condition.
This condition always returns true since it can't not be all 3 at once.
The && will return false as soon as the input is one of the 3 accepted.
Consider using boost::to_upper to convert the input into upper case before you perform the comparison in the while(...) statment. This will resolve the lowercase/uppercase issue.
http://www.boost.org/doc/libs/1_41_0/doc/html/boost/algorithm/to_upper.html
Also, when dealing with C++ strings, I recommend you simply do
departure == "MAN" || departure == "EMA" || departure == "LHR"
You don't need to do string.compare in C++, unlike some other languages (for example Java), as the == operator is overloaded to compare the /content/ of the string, rather than the string object itself.
Also somebody else beat me to it about the compare method returning 0 when equal.
First Your conditional for the while loop is incorrect. Right now it reads, while departure is not 'MAN' or is not "EMA" or is not "LHR", continue looping. Because departure cannot be all three of them simultaneously, the loop never ends. I would suggest replacing your OR's (||) with AND's (&&)
As well, each execution of the loop you need to clear the value in departure, otherwise the previously entered lines persist and your comparison will fail even when a correct airport code is entered.
our main problem is that the string is being compared incorrectly. Let's say we type in "MAN".
The departure.comare("MAN") != 0 will be true if the string is not "MAN". Fine, we typed in "MAN", so it's false. Now we OR that with departure.compare("EMA") != 0 - which is true, because "MAN" is not equal to "EMA". So you need to combhine your condition with &&, not ||.
To fix for "owercase", there are two choices. Either convert the input string to uppercase, or compare with all different combinations of lower and upper case (Man, MaN, mAn, etc) - the latter gets very tedious very quickly.
Have a look at this one for some options of comparing strings in a case-insensitive way:
Case insensitive string comparison C++
In C/C++, what does the following mean?
for(;;){
...
}
It's an infinite loop, equivalent to while(true). When no termination condition is provided, the condition defaults to false (i.e., the loop will not terminate).
In C and C++ (and quite a few other languages as well), the for loop has three sections:
a pre-loop section, which executes before the loop starts;
an iteration condition section which, while true, will execute the body of the loop; and
a post-iteration section which is executed after each iteration of the loop body.
For example:
for (i = 1, accum = 0; i <= 10; i++)
accum += i;
will add up the numbers from 1 to 10 inclusive.
It's roughly equivalent to the following:
i = 1;
accum = 0;
while (i <= 10) {
accum += i;
i++;
}
However, nothing requires that the sections in a for statement actually contain anything and, if the iteration condition is missing, it's assumed to be true.
So the for(;;) loop basically just means:
don't do any loop setup;
loop forever (breaks, returns and so forth notwithstanding); and
don't do any post-iteration processing.
In other words, it's an infinite loop.
Loop until some break, exit, throw etc. statement inside the loop executes. Basically, you can think of a for loop as consisting of:
for (setup; test; advance)
...
If the "test" is empty it's considered to be true, and the loop keeps running. Empty "setup" and "advance" simply do nothing.
An infinite loop which continues until there is a break, exit, or goto statement.
Even if this answer suggests that both constructs are equivalent, there's a subtle difference between both for(;;) and while(1) (which both create infinite loops) in the C language (and possibly compiler-dependent).
Some compilers (Windriver DIABData for instance) complain about "condition is always true" when using while(1).
Changing to for(;;) allows to get rid of the warning, probably because the latter expression is semantically stronger to create an infinite loop on purpose, and there is no "always true" condition at all (plus it's shorter to write).
On the other hand, the C++ language doesn't make a difference about both constructs as Adrian stated in comments:
The C++ standard states that a missing condition makes the implied while clause equivalent to while(true) and for ( for-init-statement condition opt ; expression opt ) statement is equivalent to { for-init-statement while ( condition ) { statement expression ; } }