In the university I had a quiz today. The quiz is over but I can't understand some of its questions are their correct answers.
Note: I am not asking this to solve my quiz. Quiz is over I am just confused in some questions.
Question 1:
Consider the following variable declarations:
int catHeight = 6;
int dogHeight = 7;
string dogName = "Rover";
string catName = "Sylvester";
float catWeight = 15.0;
float dogWeight = 20.0;
bool dogRabies = true;
bool catRabies = false;
Choose Boolean expressions equivalent to following statements.
the cat has rabies and does not weigh 20 pounds or less
catRabies && catWeight > 20
!( catRabies && catWeight <=20)
! catRabies && catWeight >=20(This was marked as correct. I think the first option is correct)
the cat height and the dog height are not 10 (Hint: more than 1 answer)
catHeight > 10 && dogHeight >10
(catHeight && dogHeight) != 10
catHeight !=10 && dogHeight != 10
2nd and third are were marked as correct in result. But I think that only third one is correct. Please explain if I am wrong.
Question 2:
if numNeighbors >= 3 || numNeighbors = 4
++numNeighbors;
cout << "You are dead" << endl;
else
--numNeighbors;
What is wrong with the following if statement (there are at least 3 errors). The
indentation indicates the desired behavior
syntax error; else without previous if(marked as correct)
syntax error; value required of left operand (marked as correct)
syntax error; Parenthesis missing (marked as corrent)
syntax error; statement missing
I understand why 1 and 3 are correct but can't get the meaning of second one. Kindly explain it.
3 errors in question 2:
missing ( ) around the if condition
in the second part of the if condition there must be double ==
{ } are missing
To be a valid code it must be set like this:
if (numNeighbors >= 3 || numNeighbors == 4)
{
++numNeighbors;
cout << "You are dead" << endl;
}
else
--numNeighbors;
This was marked as correct. I think the first option is correct
Yes, you're right.
But I think that only third one is correct.
You're also right here.
Question 2
This one does not make sense unless you are trying to parse like a compiler. For instance, "else without previous if" only makes sense if you consider the current state of the code and not what you are trying to achieve. But the question tells you what you are trying to achieve.
syntax error; value required of left operand (marked as correct)
This means the condition is being parsed as (numNeighbors >= 3 || numNeighbors) = 4; which makes clear that the left side is not something you can assign to.
Your understanding of (1.1) and (1.2) seems to be correct.
In (2), if you fix the other errors,
if (numNeighbors >= 3 || numNeighbors = 4)
will be parsed as
if ((numNeighbors >= 3 || numNeighbors) = 4)
For this GCC outputs error: lvalue required as left operand of assignment, which reads similar to "value required of left operand".
Related
This question already has answers here:
If statements without brackets
(3 answers)
Closed 10 months ago.
Does the indentation in an if else statement have any bearing on the execution of the code or is it just something to do for cleaner code?
Example from the book Accelerated C++ written by Andrew Koening:
while(c != cols) {
if(r == pad + 1 && c == pad + 1) {
cout << greet;
c += greet.size();
} else {
if(r == 0 || r == rows - 1 || c == 0 || c == cols - 1)
cout << "*";
else
cout << " ";
++c;
}
}
The prefix increment of c is executed regardless of whether r=0 or not, but I don’t understand why.
If the if statement turns true, an asterisk is printed. If not, a blank space is printed and c is incremented.
That’s how I am reading it, but c gets incremented regardless of what the values of r or c are.
This is what it says in the book, but there isn’t any explanation I could find:
Notice how the different indentation of
++c;
draws attention to the fact that it is executed regardless of whether we are in the
border.
Whitespace does not affect C++ runtime behavior. (Unlike certain other languages, like Python).
I should mention that in your else block, you do not use braces. So, only the first statement (cout << " ";) will be part of the else clause. The subsequent ++c; will execute regardless of the value of r and c.
Note that this last point is subjective, so take it with a grain of salt... As you can see, when braces are omitted from if ... else ... blocks, there is potential for confusion. Some would argue that it leads to more concise code, but many (including myself) would argue that you should always use braces. This is especially important when you work on a large team because code tends to grow over time. I've seen many cases in production code where an if statement was missing the braces and someone added a second line to the if clause without remembering to add braces. This didn't work as expected and caused wasted time debugging fails, just because the braces were omitted.
Both C and C++ are not affected by white space in their interpretation of the code. That does not mean the programmer should not care about its misuse.
The best way to illustrate what the above code actually represents is to explicitly define all of the inferred braces as below. Note that the if statement that had no braces only has one line of code affected by the 'if then' or 'else' clause.
This is one of the reasons that people try to insist on
'good coding practices' to ensure that other people are able to clearly interpret the flow and intent of the programmer.
while(c != cols) {
if(r == pad + 1 && c == pad + 1) {
cout << greet;
c += greet.size();
} else {
if(r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {
cout << "*";
} else {
cout << " ";
}
++c;
}
}
In C++ the length of indentation does not affect the interpretation of the statements. Sometimes whitespace is needed to separate characters, e.g., in int a. Other times it is not needed, e.g. in a=b+c;.
The if statement is defined that after the condition if(condition) can only be one statement.
If we want more statements we have to group them with braces {...}
Unlike Python, C++ does not care about indentation.
But your else applies only on the first line. To apply to a block, it should be within { }
else
{
cout << " ";
++c;
}
Indentation is not your problem here.
OK so obviously this question might sound dumb for more experienced people, but, for the following lines the result I get is 0:
int x = 2,
y = -2;
cout << (x++ - y && (--x + y));
I understand it means that either one of these two expressions equals 0, but how? As far as I understand, this should be (3 && -1)?
Also, a little subquestion: when does x++ exactly take effect? On the next occurance of x within the same expression, after the left-shift operator within the same line, or in the next statement?
Thank you!
As far as I understand, this should be (3 && -1)?
you understand wrong:
first left side is fully evaluated, as it is necessary for short circuit evaluation with logical and (details can be found here)
x++ - y == 4 // as result of x++ == 2 so (2-(-2)), after that x == 3
result is true so right side is evaluated:
--x + y == 0 // as result of --x == 2 so (2+(-2)), after that x == 2
result on the right is false so result of and is false as well which printed by std::ostream as 0
Note: short circuit evaluation of logical or and and operations make such code valid (making them sequenced) but you better avoid such questionable expressions. For example simple replacing logical and to binary would make it UB.
I am new to C++ and I have a problem where i have to transform a pseudocode in C++ / C / Pascal language. The answer at the end of the book written in Pascal.
The problem in my C++ code is that at the line 12, I get the error which can be found in the title. Any idea?
Pascal Code:
var n,x:integer;
begin
n:=0;
repeat
write('x=');read(X);
if x<>0 then
if x mod 5 = 0 then
n:=n+1
else
n:=n-1;
until x=0;
if n=0 then
write('yes')
else
write('no')
end;
My C++ Code:
int main()
{
int x,n;
cin>>x;
while(x>0)
{
if(x>0)
{
if(x%5=0){
n=n+1;
} else {
n=n-1;
}
}
if(n=0){
cout<<"Yes"<<;
} else {
cout<<"No"<<;
}
}
}
You have a simple typo: if(x%5=0){ is an attempt to assign 0 to x % 5 (due to operator precedence modulus is computed before assignment). x % 5 cannot be assigned to (it's not an lvalue) and the compiler is telling you that.
The fix, of course, is to write x % 5 == 0.
You're lucky in this case that the error is picked up at compile-time. Something like if (n = 0) (on line 18) might not be, since x = 0 is an expression with value 0.
Two ways to guard against that:
Ensure that your compiler warnings are as aggressive as you can bear. With gcc, I use -Wall -Wextra, and that combination is enough to catch this common problem.
Some developers will write if (0 == x) since an errant if (0 = x) would be picked up at compile time as an attempt to assign to 0. Personally, I find that obfuscating.
Assignment operator requires lvalue means the left side operand need to be a variable/location that can hold a value.
This is what is meant by the error.
What you need in your if statement is == likely not assignment as mentioned by other answers
You need to use == in conditions (while, if, ...) for equality check in C++.
if(x%5 = 0)
should be
if(x%5 == 0)
"x%5" is not an lvalue in that you can not assign a value to it, hence the error.
I have a sample midterm question that I am not too sure about. Here it is:
#include <iostream.h>
void f( int i )
{
if( i = 4 || i = 5 ) return;
cout << "hello world\n" ;
}
int main()
{
f( 3 );
f( 4 );
f( 5 );
return 0;
}
So I understand that the logical OR operator has a higher precedence and that it is read left to right. I also understand that what's being used is an assignment operator instead of the relational operator. I just dont get how to make sense of it all. The first thing the compiler would check would be 4 || i? How is that evaluated and what happens after that?
Let's add all the implied parentheses (remembering that || has higher precedence than = and that = is right-associative):
i = ((4 || i) = 5)
So, it first evaluates 4 || i, which evaluates to true (actually, it even ignores i, since 4 is true and || short-circuits). It then tries to assign 5 to this, which errors out.
As written, the code doesn't compile, since operator precedence means it's i = ((4 || i) = 5) or something, and you can't assign to a temporary value like (4 || i).
If the operations are supposed to be assignment = rather than comparison == for some reason, and the assignment expressions are supposed to be the operands of ||, then you'd need parentheses
(i = 4) || (i = 5)
As you say, the result of i=4 is 4 (or, more exactly, an lvalue referring to i, which now has the value 4). That's used in a boolean context, so it's converted to bool by comparing it with zero: zero would become false, and any other value becomes true.
Since the first operand of || is true, the second isn't evaluated, and the overall result is true. So i is left with the value 4, then the function returns. The program won't print anything, whatever values you pass to the function.
It would make rather more sense using comparison operations
i == 4 || i == 5
meaning the function would only print something when the argument is neither 4 nor 5; so it would just print once in your example, for f(3).
Note that <iostream.h> hasn't been a standard header for decades. You're being taught an obsolete version of the language, using some extremely dubious code. You should get yourself a good book and stop wasting time on this course.
The compiler shall isuue an error because expression 4 || i is not a lvalue and may not be assigned.
As for the expression itself then the value of it is always equal to true because 4 is not equal to zero.
I am trying to make a program generating random numbers until it finds a predefined set of numbers (eg. if I had a set of my 5 favourite numbers, how many times would I need to play for the computer to randomly find the same numbers). I have written a simple program but don't understand the outcome which seems to be slightly unrelated to what I expected, for example the outcome does not necessarily contain all of the predefined numbers sometimes it does (and even that doesn't stop the loop from running). I think that the problem lies in the logical operator '&&' but am not sure. Here is the code:
const int one = 1;
const int two = 2;
const int three = 3;
using namespace std;
int main()
{
int first, second, third;
int i = 0;
time_t seconds;
time(&seconds);
srand ((unsigned int) seconds);
do
{
first = rand() % 10 + 1;
second = rand() % 10 + 1;
third = rand() % 10 + 1;
i++;
cout << first<<","<<second<<","<<third<< endl;
cout <<i<<endl;
} while (first != one && second != two && third != three);
return 0;
}
and here is out of the possible outcomes:
3,10,4
1 // itineration variable
7,10,4
2
4,4,6
3
3,5,6
4
7,1,8
5
5,4,2
6
2,5,7
7
2,4,7
8
8,4,9
9
7,4,4
10
8,6,5
11
3,2,7
12
I have also noticed that If I use the || operator instead of && the loop will execute until it finds the exact numbers respecting the order in which the variables were set (here: 1,2,3). This is better however what shall I do make the loop stop even if the order is not the same, only the numbers? Thanks for your answers and help.
The issue is here in your condition:
} while (first != one && second != two && third != three);
You continue while none of them is equal. But once at least one of them is equal, you stop/leave the loop.
To fix this, use logical or (||) rather than a logical and (&&) to link the tests:
} while (first != one || second != two || third != three);
Now it will continue as long as any of them doesn't match.
Edit - for a more advanced comparison:
I'll be using a simple macro to make it easier to read:
#define isoneof(x,a,b,c) ((x) == (a) || (x) == (b) || (x) == (c))
Note that there are different approaches you could use.
} while(!isoneof(first, one, two, three) || !isoneof(second, one, two, three) || !isoneof(third, one, two, three))
You have a mistake in your logical condition: it means "while all numbers are not equal". To break this condition, it is enough for one pair to become equal.
You needed to construct a different condition - either put "not" in front of it
!(first==one && second==two && third==three)
or convert using De Morgan's law:
first!=one || second!=two || third!=three