just reading through some C++ books and I'm just wondering if somebody could double check this, would these two pieces of code, both do the same?
if (x > 5)
if(y > 5)
cout << "something";
else
cout <<"something else";
if (x > 5) && (y > 5)
cout <<"something";
else
cout <<"something else";
Am I right in thinking these two both do the same thing just differently written, one friend told me they were another told me they weren't so just thought best ask here
Thanks.
These two statements are not the same. The former prints nothing at all if x <= 5.
The first example also has incorrect indentation (and is a great argument for why you should always include braces). The equivalent with braces is
if (x > 5) {
if (y > 5) {
cout << "something";
} else {
cout <<"something else";
}
}
This should make it obvious that if x <= 5 it executes nothing.
They do not.
Consider the sample data of x=y=0.
The first snippet will print nothing, while the second one will print "something else".
Related
I'm a newbie here and I just started college. We are learning C++ and I find it a little bit difficult, because of the way the teachers explain.
Yesterday we did a task that says to create a program, which finds greatest common divisor of 2 numbers. So, the teacher started writing the code, but the explanation wasn't enough for me and I really need some help right now.
(I putted comments on the things I don't understand.)
Here is the code:
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int a, b;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "GCD (" << a << ", " << b << ") is ";
if (a != 0 && b != 0){
size_t min = abs(a) < abs(b) ? abs(a) : abs(b); //What's that after (?)?
size_t max = abs(a) > abs(b) ? abs(a) : abs(b);
size_t diff = max - min; //What is that variable used for?
while (diff > 0)
{
min = diff < min ? diff : min;
max = diff > min ? diff : min;
diff = max - min;
}
cout << min << endl;
}
else{
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
else
cout << "not possible!!!\n";
}
system("pause");
return 0;
}
QUESTION: When should I put {} on if's, while's etc.?
This is the syntax for an if-statement
if ( condition ) statement-true else statement-false
statement-true is either one statement or a block of statements in {...}
So you can use if without {...} if there is only one line. But it is better to always use {...}.
It is necessary when you need more that one line/statement to be executed by the if/else/while. Valid examples:
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
if (a != 0 || b != 0) cout << (a>b ? a : b) << endl;
if (a != 0 || b != 0) {
cout << (a>b ? a : b) << endl;
a++; }
If you did:
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
a++;
The the a++; would be executed regardless of the if condition.
Some programmers like to use {} even for single statements because they believe it leads to more usable and maintainable code. I do not belong to that group but I can see the arguments on either side.
size_t min = abs(a) < abs(b) ? abs(a) : abs(b); //What's that after (?)?
C and C++ have a construct that is similar to an if-else statement. This line basically says that if abs(a) is smaller than abs(b), then min should take the value of abs(a); otherwise, it should take the value of abs(b).
size_t diff = max - min; //What is that variable used for?
It's not clear what you mean here. If you mean diff, the code essentially uses it in the subsequent while loop to perform division by repeated subtraction. This is a very strange thing to do, especially because it is so inefficient, and division would have been more compact and efficient in the loop. It's even stranger given that earlier the author uses ?: (which you asked about); that construction is used mainly because it's more compact and efficient than an if-else statement, but this is rather strange code, anyway.
When should I put {} on if's, while's etc.?
You should do it by default. You don't have to do it if only one statement is to be performed when the condition is true (resp. false) but people usually do as a matter of good style and to assist readability. For instance, this code
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
else
cout << "not possible!!!\n";
could just as easily be
if (a != 0 || b != 0) {
cout << (a>b ? a : b) << endl;
} else {
cout << "not possible!!!\n";
}
...and a lot of instructors would actually require the latter from learners.
In addition to the other answers:
//What's that after (?)?
foo ? bar : qux;
Is the use of the ternary operator.
If foo is true the expression evaluates to bar else it evaluates to qux.
Just adding my two cents...
This
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
is equivalent to
if (a != 0 || b != 0) {
cout << (a>b ? a : b) << endl;
}
The big difference comes when you realize that code is not something static that you write once and then never change again. Lets change the example a little bit (intentially weird intendation)
if ( x ) // (I)
y = a;
z = b;
is not the same as
if ( x ) { // (II)
y = a;
z = b;
}
Using brackets allows you to focus on only the part you care about. Consider that you later decide to swap the two lines, then
if ( x ) {
z = b;
y = a;
}
is still ok (its the same as (II), apart from swapping the two instructions), while
if ( x )
z = b;
y = a;
is doing something completely different as the version above (I). If you use the brackets you dont need to care whether those two lines are inside a if block. To decide if you can swap them you need to look at nothing more than those two lines. This is not the case if you do not use the brackets. This may seem like a minor thing, though I have seen countless bugs caused by not putting brackets where there could be some.
For 1 line of code following if, else, else if, while, etc
if (<some condition>)
//1 line of code`
and
if (<some condition>)
{
//1 line of code
}
...are equivalent and it is up to you (personal style,developer choice,readability etc.) to make that decision.
For > 1 line of code following if, else, else if, while, etc
{} is required if you want code completely scoped to the condition statement. It is up to you the developer to make sure to scope these lines of code (i.e. the compiler will not warn you about this.. it will not know if the intent was 1 line or multiple lines).
So an example
if(<some condition>)
{
//line of code 1
//line of code 2
}
the compiler will let you do this...
if(<some condition>)
// line of code 1
// line of code 2
but //line of code 2 has no relation to the if condition since it was not scoped with {} and will be executed regardless of the if statement condition.
I am writing this program which will guess the number user is thinking about. After days of work, I could not figure out what is wrong in it.
Also my proposed grade for the assignment is not what I expected.
Please help.
User can guess 100, but my program uses mid-point rule so can only go up to 99. How can I make 100 inclusive?
If I keep pressing 'l' the program will eventually break out of loop and prints If you want to try again?
Is there a better way to code this program? Example please.
Here is the actual program:
Write a program in that can figure out a number chosen by a human user. The human user will think of a number between 1 and 100. The program will make guesses and the user will tell the program to guess higher or lower. The program should find the midpoint of the two numbers and ask if the number is higher or lower.
#include <iostream>
using namespace std;
int main() {
char check;
char tryagain;
do {
int midpoint;
const int MAX = 100;
const int MIN = 1;
int y = MAX;
int x = MIN;
cout << "Think of a number between 1 and 100." << endl;
midpoint = (x + y) / 2;
while (x != y || y != x) {
cout << endl << "Is it" << " " << midpoint << " " << "?";
cin >> check;
if (check == 'l' || check == 'L') {
y = midpoint;
midpoint = (x + y) / 2;
}
else if (check == 'h' || check == 'H') {
x = midpoint;
midpoint = (x + y) / 2;
}
else if (check == 'c' || check == 'C') {
break;
}
else {
cout << "Incorrect choice." << endl;
}
}
cout << "Great! Do you want to try again? (y/n)";
cout << endl;
cin >> tryagain;
} while (tryagain == 'y' || tryagain != 'n');
return 0;
}
Your problem is just a mis-think in the calculation of x and y like Alf suggested in the comments.
It should read
y = midpoint - 1;
and
x = midpoint + 1;
respectively. The reason is simple. You use midpoint as the guess. The guess is then no longer part of the available guesses. Your first guess is 50, x or y should then be either 51 or 49 as the new min or max in the interval.
This will also make 100 included in the available guesses. The last step in the calculation will be when midpoint was 99 and the user selects 'h'.
x = 99 + 1;
lower bound is 100, and the midpoint guess evaluates to
midpoint = (100 + 100) / 2;
which is correct.
As for better ways to write this program. This would depend on what your course has taught you, what's in the curriculum, and so on. You might want to check out code-review
When your x and y are too close, the division of their sum produces an incorrect midpoint. 100 + 99 / 2 = 99 (which is 99.5 rounded down). You need to check for this special case. At the end of the loop before the closing bracket insert:
if ( y-x < 2) midpoint = y;
User can guess 100, but my program uses mid-point rule so can only go up to 99. How can I make 100 inclusive?
Division of integers in c++ discards any decimal. It always rounds down. Consider what happens when midpoint is 99. You get midpoint = (99 + 100) / 2 which is 199 / 2 which is 99.5. Discarding the decimal leaves you with 99 every time. One possible solution is to change y = midpoint; to y = midpoint - 1; and x = midpoint; to x = midpoint + 1; This will prevent your application from guessing the same value more than once. With this change, when midpoint is 99, x will first be incremented to 100 giving us a new midpoint (100 + 100) / 2 which evaluates to 100.
If I keep pressing 'l' the program will eventually break out of loop and prints If you want to try again?
If the user keeps pressing l then eventually the only possible solution is 1. It seems that you chose not to propose your guess at that point and assume the user followed the rules. Add an extra print when the answer is deduced.
if (x == y) {
// Answer was deduced
cout << "You guessed " << x << ".\n";
}
Is there a better way to code this program? Example please.
See the first two parts of this answer. Other than that, it's difficult to say objectively what "better way to code this" means. You might want to consider a system to detect when the user is lying. For example, if midpoint == x then the user can't select l without lying.
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
int main(){
string Whitelist[4] = {"Stian", "Mathias", "Modaser"};
for (int x = 0; x < 3; x++){
cout << x + 1<< ". " << Whitelist[x] << endl;
if (Whitelist[x] == "Stian" && "Mathias" && "Modaser"){
cout << "" << Whitelist[x] << " is here" << endl;
}
else{ cout << "no one is here" << endl; }
}
cin.get();
return 0;
}
//so yeah basically im just trying to loop through my array and see if any of these names are there. so i guess u can pretty much read what the code does since most of u are pros :P. but when i asked my friend, whos been coding for 1-2 years, he said that i couldnt loop through arrays like this and told me to use a vector. what does he mean by that? and my code works?
This set of code is wrong
if (Whitelist[x] == "Stian" && "Mathias" && "Modaser"){
cout << "" << Whitelist[x] << " is here" << endl;
}
Why? because suppose the first condition of the if statement evaluates to true like this:
if (true && "Mathias" && "Modaser")
{
//...
}
Then the code wouldn't make sense. In an if statement, you have to check for every condition separately, like this:
if (Whitelist[x] == "Stian" && Whitelist[x] =="Mathias" && Whitelist[x] =="Modaser"){
cout << "" << Whitelist[x] << " is here" << endl;
}
But since any 1 string cannot be three names at the same time, this condition will fail, (you used &&). Fix your code using the || operator, like this, for your final code (Also, remove << "", that is just redundant, and unnecessary):
if (Whitelist[x] == "Stian" || Whitelist[x] =="Mathias" || Whitelist[x] =="Modaser"){
cout << Whitelist[x] << " is here" << endl;
}
BTW: As a recommendation, use a std::vector<std::string>, not a raw array, so you get easier and more capabilities than an array.
Lastly, you also have 4 elements in your array, of which one is unused. It might be a typo, so make your array size 3.
There is nothing fundamentally wrong with looping over an array like this.
We can only guess what your friend meant, but I can perform my own review of your code.
However, you have four array elements and only loop over three of them, which may be a mistake; if it is, it's evidence that you'd be better off using iterators, rather than hard-coding numbers that you can get wrong.
Furthermore, your if conditional is wrong: did you mean || ("or"), instead of && ("and")? And you have to write out the adjoined conditions in full, so:
if (Whitelist[x] == "Stian" || Whitelist[x] =="Mathias" || Whitelist[x] =="Modaser")
I'm not sure why you're comparing against all these values, when they're the only ones in the array. Well, except for that empty fourth element; perhaps you're trying to catch that. We don't know, because you didn't tell us. Did you mean to search Whitelist while iterating over some other array? We have no way of knowing. Maybe that's what your friend really meant? Again, I couldn't say.
Streaming "" to std::cout just waits resources and does literally nothing else. Remove it.
Finally, and somewhat tangentially, it would be better not to block waiting for input as a means to keep your console window open. That is not your program's job.
I have this function:
void m(int n)
{
if(n > 0)
m(--n);
cout << n << " "; //for n = 5 --> output is: 0 0 1 2 3 4
}
I have a problem with understanding how it works.
For example:
n(input) = 5
output: 0 0 1 2 3 4
My question is: Why does it show zero twice?
When I add brackets like this:
void m(int n)
{
if(n > 0)
{
m(--n);
cout << n << " "; // now, it shows 0 1 2 3 4 (n = 5)
}
}
So, what brackets cause in this code, that "0" exists only once?
And when I change pre-decrement (--n) to post-decrement (n--) it shows nothing. Why?
Could somebody help me to understand how it works?
First thing to note is : in C++ if you don't put brackets after an if statement, only the next line will be in the statement.
Example :
if(x > 0)
cout << 1;
cout << 2;
Here cout << 2 will always be executed no matter the value of x
The correct way of writing this is
if(x > 0)
{
cout << 1;
cout << 2;
}
Same thing goes for else statements
So this was for the brackets.
My wild guess for the post decrement is the following :
if you do m(n--), the value passed will be 5, the value of n will only change after the function call and go out of scope (so it won't matter). So what will happen is an infinite number of m(5) calls and that's why nothing is appearing. (I'm not sure about that part so please tell me if wrong) !
Hope it helped !
Looks like you confused with Python syntax, where scope of if is determined by indent. In C (and C++, C#, Java an many other languages) the scope is one statement (which ends with ;) unless you use curly brackets { and }. In the 1st variant of your code cout << n << ... will be always performed, regardless of value of n. In second variant it will be performed only if(n > 0)
I have searched for this error but noone seems to be having the same problem as me. I am trying to make a basic text based RPG game in C++ to learn, and I want the user to be able to type what they want to do, for example if they type ATTACK they will attack the monster, but my if statement:
if((current_move == "ATTACK") || (current_move == "attack"))
returns false!
Here is the full function below:
while(monster_health > 0)
{
std::cin >> current_move;
std::cout << current_move;
if((current_move == "ATTACK") || (current_move == "attack"))
{
std::cout << "You attacked the monster!\n";
double damage = return_level(xp) * 1.2;
std::cout << "You did " << damage << " damage!\n";
monster_health -= damage;
if(monster_health < 0)
{
monster_health = 0;
break_out = true;
}
}
else if(current_move == "FLEE")
{
std::cout << "You ran away...\n";
break_out = true;
}
else
{
std::cout << "Sorry, I didn't understand, what will you do? ATTACK or FLEE?\n";
}
}
I just keep getting "Sorry, I didn't understand" message;
Please let me know of any other errors or bad practises as I've only just started learning :)
What's the type of current_move? If it's char* (or char[]), you are comparing pointers, not strings. Better use std::string for current_move, then the comparison with == will work intuitively.
You need to add #include <string>. (In MSVC certain parts of strings also work without that, but it's nonstandard and leads to errors e.g. when passing strings to cout).
If you're using a C string (char[]), you need to use strcmp() to compare it. If the two strings are equivalent, it will return 0.
if (strcmp(current_move, "ATTACK") == 0) will return true if they match.
You need to do current_move==string("attack") otherwise you will be comparing pointers. String operator == or strncmp, either one or the other...
Your problem is that you are comparing C strings. When you do == on them, you are comparing the pointer of the two, which in this code is useless to do.
My suggestion would be to just change the type of current_move to std::string and it will just work. Then you will be comparing the contents, not the pointers.