The most basic kind of conditional branch in C++ is the if statement. An if statement takes the form:
if (expression)
statement
or
if (expression)
statement
else
statement2
If the expression evalutes to true (non-zero), the statement executes. If the expression evaluates to false, the else statement is executed if it exists.
Here is a simple program that uses an if statement:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
cout << nX << "is greater than 10" << endl;
else
cout << nX << "is not greater than 10" << endl;
return 0;
}
Note that the if statement only executes a single statement if the expression is true, and the else only executes a single statement if the expression is false. In order to execute multiple statements, we can use a block:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
{
// both statements will be executed if nX > 10
cout << "You entered " << nX << endl;
cout << nX << "is greater than 10" << endl;
}
else
{
// both statements will be executed if nX <= 10
cout << "You entered " << nX << endl;
cout << nX << "is not greater than 10" << endl;
}
return 0;
}
It is possible to chain if-else statements together:
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
cout << nX << "is greater than 10" << endl;
else if (nX < 5)
cout << nX << "is less than 5" << endl;
// could add more else if statements here
else
cout << nX << "is between 5 and 10" << endl;
return 0;
}
It is also possible to nest if statements within other if statements:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
// it is bad coding style to nest if statements this way
if (nX < 20)
cout << nX << "is between 10 and 20" << endl;
// who does this else belong to?
else
cout << nX << "is greater than 20" << endl;
return 0;
}
The above program introduces a source of potential ambiguity called a dangling else problem. Is the else statement in the above program matched up with the outer or inner if statement?
The answer is that an else statement is paired up with the last unmatched if statement in the same block. Thus, in the program above, the else is matched up with the inner if statement.
To avoid such ambiguities when nesting complex statements, it is generally a good idea to enclose the statement within a block. Here is the above program written without ambiguity:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
{
if (nX < 20)
cout << nX << "is between 10 and 20" << endl;
else // attached to inner if statement
cout << nX << "is greater than 20" << endl;
}
return 0;
}
Now it is much clearer that the else statement belongs to the inner if statement.
Encasing the inner if statement in a block also allows us to explicitly attach an else to the outer if statement:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
{
if (nX < 20)
cout << nX << "is between 10 and 20" << endl;
}
else // attached to outer if statement
cout << nX << "is less than 10" << endl;
return 0;
}
The use of a block tells the compiler that the else statement should attach to the if statement before the block. Without the block, the else statement would attach to the nearest unmatched if statement, which would be the inner if statement.
If statements are commonly used to do error checking. For example, to calculate a square root, the value passed to the square root function should be a non-negative number:
#include <iostream>
#include <cmath> // for sqrt()
void PrintSqrt(double dValue)
{
using namespace std;
if (dValue >= 0.0)
cout << "The square root of " << dValue << " is " << sqrt(dValue) << endl;
else
cout << "Error: " << dValue << " is negative" << endl;
}
If statements can also be used to do early returns, where a function returns control to the caller before the end of the function. In the following program, if the parameter nValue is negative, the function returns a symbolic constant or enumerated value error code to the caller right away.
int DoCalculation(int nValue)
{
// if nValue is a negative number
if (nValue < 0)
// early return an error code
return ERROR_NEGATIVE_NUMBER;
// Do calculations on nValue here
return nValue;
}
If statements are also commonly used to do simple math functionality, such as a min() or max() function that returns the minimum or maximum of it’s parameters:
int min(int nX, int nY)
{
if (nX > nY)
return nY;
else
return nX;
}
Note that this last function is so simple, it can also be written using the arithmetic if operator (?:):
int min(int nX, int nY)
{
return nX > nY ? nY : nX;
}
5.3 — Switch statements
|
Index
|
5.1 — Control flow introduction
|
5.3 — Switch statements
Index
5.1 — Control flow introduction
Hi, great website btw!
However, whenever i try to use a char variable in an if statement (e.g :
if(a = “Hello”)
cout << “Hello there”;
it does not compile correctly.
can anyone help? if so please email me on fight.the.purple@hotmail.co.uk or leave a comment
many thanks
First off, = is for assignment, not comparison. You would normally use == to do comparisons, except == doesn’t work on string literals (which is anything inside double quotes). Probably the best way is to declare your a variable as a std::string instead of a char. Then it will work as you expect. This is covered in lesson 6.6.
[...] 2007 Prev/Next Posts « 4.7 — Structs | Home | 5.2 — If statements » Wednesday, June 20th, 2007 at 9:37 [...]
[...] 2007 Prev/Next Posts « 5.2 — If statements | Home | 5.4 — Goto statements » Thursday, June 21st, 2007 at 6:41 [...]
I’m trying to write a code, in which the user will enter a number, enter another number than write whether the 1st number was greater than, less than, or equal to, the 2nd number number. All numbers work, except when the 1st and 2nd numbers are both 0. In that case, it says nothing. My code is below; can you see the problem?
using namespace std;
cout <> nX;
cout << “You entered ” << nX << endl;
using namespace std;
cout <> nY;
cout << “You entered ” << nY < nY)
cout << nX << ” is greater than ” << nY << endl;
else if (nX < nY)
cout << nX << ” is less than ” << nY << endl;
else if (nX = nY)
cout << nX << ” is equal to ” << nY << endl;
Thanks.
Try this
#include "stdafx.h"
#include <iostream>
int main()
{
using namespace std;
int nX;
int nY;
cout << "Please enter a number: " << endl;
cin >> nX;
cout << "You entered: " << nX << endl;
cout << "Please enter another number: " << endl;
cin >> nY;
cout << "You entered: " << nY << endl;
if (nX > nY)
cout << nX << " is greater than " << nY << endl;
else if (nX < nY)
cout << nX << " is less than " << nY << endl;
else if (nX == nY)
cout << nX << " is equal to " << nY << endl;
else
cout << "YOU DID NOT ENTER A VALID NUMBER" << endl;
return 0;
}
Sorry, this is correct code.
using namespace std;
cout <> nX;
cout << “You entered ” << nX << endl;
using namespace std;
cout <> nY;
cout << “You entered ” << nY < nY)
cout << nX << ” is greater than ” << nY << endl;
else if (nX < nY)
cout << nX << ” is less than ” << nY << endl;
else if (nX = nY)
cout << nX << ” is equal to ” << nY << endl;
the problem is that you have if(nX = nY) instead of if(nX == nY).
with the single =, you are doing and assignment (of the value 0), which means that you end up with if(0), so it doesn’t ever evaluate.
this is not correct code cout nX;
I saw in the previous comment
.
Is this correct??
P.S. Great tutorials!!!
No. :) There is no <> operator in C++.
Hi, i am a bit confused.
int DoCalculation(int nValue) { // if nValue is a negative number if (nValue < 0) // early return an error code return ERROR_NEGATIVE_NUMBER; // Do calculations on nValue here return nValue; }If nValue is negative, and the function returns ERROR_NEGATIVE_NUMBER. How do you know its an error?
Because ERROR_NEGATIVE_NUMBER could = 3 right?
So when calling this function, if you wanted to make sure there was no error you
would do sometihng like
if (!DoCalculation(9)) {
}
sorry, I accidntly posted before I was finnished writing. What I was saying is Wouldn’t the error codes be the same as correct output?
So how would know if the output was an error or an answer?
or are error code usually more obscure, like ERROR_NEGATIVE_NUMBER = E-0f96
just going off the previous lesson about enums.
Hope this makes sence, sorry I might be way off!
Actually you’re pretty accurate, the example is rather ambiguous on this point, but it wasn’t meant to be usable code. ERROR_NEGATIVE_NUMBER would have to be a value that would not normally be returned by DoCalculation. For example, since DoCalculation does not accept negative numbers, it most likely doesn’t return negative numbers, therefore in that case ERROR_NEGATIVE_NUMBER could be -1.
I think that learn from this way of explanation is very directly, whithout hesitating…
I read books for C++, but I spend time more than ussual, because no colours , no tabels,and no
orders of information like in your wwww. Maybe the books must be in electron formats for faster
learning and training, with colours and pictures..
THANK YOU…
MANY GOOD JOBS…
where is my bug in my code:
#include <iostream> int main() { using namespace std; cout<<"choose a percent of your mood:"<<endl; cout<<"1)50% 2)100%"<<endl; int nX; cin>>nX; if (nX=1) cout<<"your mood is :("<<endl; else if (nX=2); cout<<"your mood is :)"<<endl; else cout<<"please, choose 1 or 2"<<endl; return 0; }another thing i can’t do:
can i press my choose 1 or 2 without press enter key?
remove the ; after
and both if statements should be
please send for me c ++ program to print number of days for a given month in GC.
by using switch statment and c++ program to print roots of qudratic equation
[...] To fully complete this example, you’ll need to utilize if statements. You’re welcome to take a stab at it now if you’re feeling [...]
Great Site, I have written a page concerning what language a newbie should start with. Check out http://www.6pie.com/c++/?p=5 and learn what the best road is to learning to program in Windows platform.
I have a question. I have used this ‘if’ statement and i get something weird.This is the code i have:
int main ()
{
cout << "Please enter a number: \n" <> nA;
if ((nA > 0)&&(nA < 9)) {
cout << "You entered " << nA<< endl;
} else {
cout << "You should enter numbers only, not symbols" << endl;
}
cin.get();
cin.get();
return 0;
}
Now, if the user inputs a number it works fine… but if the user inputs a character then it crashes. Can you tell me where is the problem with this?
i m weak in CP, any ane tell me wht i do for ths, my exm wll be held on 15th MAY, i cant understand the programng espacialy Function typ,
Is it possible for you to set more than one required parameter for the ‘if’ statement to pass? Such as – to see what attack a player chose and if they have the ability to use it?
Yes it is, though your example is bad, as it can be done with a single if parameter.
but here’s an example -
bool something (bool a, bool b)
{ if ( a == true && b == false )
{ do something();
return true;
}
}
Alex,
you gotta fix the first program snippet. The inequality sign should be reversed.
I suppose these errors are left due to reverting to older site version after the cyber attacks.
uh, now its correct. May be my mistake
hi everyone. I am super new to programming and am trying to write a program for an assignmet but am having a really hard time., i am hoping someone can take a look at what i have to far and maybe steer me in the right direction. i have a test next week and i feel overwhelmed.. ok so the assignmemt is :An Internet service provider has three different subscription packages for its customers:
Package A: For $9.95 per month 10 hours of access are provided. Additional hours are $2.00 per hour.
Package B: For $14.95 per month 20 hours of access are provided. Additional hours are $1.00 per hour.
Package C: For $19.95 per month unlimited access is provided.
Write a program that calculates a customer’s monthly bill. It should input customer name, which package the customer has purchased, and how many hours were used. It should then create a bill that includes the input information and the total amount due. The bill should be written to a file.
Input Validation: Be sure the user only selects package A, B, or C. Also, the number of hours used in a month cannot exceed 744.
21.
Modify the program in problem 20 so it also displays how much money Package A customers would save if they purchased packages B or C, and how much money package B customers would save if they purchased package C. If there would be no savings, no message should be printed……
this is what i have so far…
#include
#include
#include
using namespace std;
int main()
{
string name;
char package;
int hours;
const double pack_a = 9.95;
const double pack_b = 14.95;
const double pack_c = 19.95;
float total;
cout<<"Enter customer name:"<> name;
getline(cin,name);
cout<>package;
if (!((package==’A') || (package== ‘B’) || (package== ‘C’)))
cout<<" Invalid, Available packages are A,B or C, only."<<endl;
else
cout<<"How many hours were used?"<744)
cout<< "invalid, hours can not exceed 744"<<endl;
else if
(package=='A')
total= (hours-10)*2.00;
cout<<total<<endl;
if
(package=='B')
total=(hours-20)*1.00;
system ("pause");
return 0;
}
i forgot to type #include
and so forth in the previos post.. i know that much lol
ok so wrked on it a little more and now this is what i have now im stuck:
#include
#include
#include
using namespace std;
int main()
{
string name;
char package;
int hours;
const double pack_a = 9.95;
const double pack_b = 14.95;
const double pack_c = 19.95;
double total;
cout<<"Enter customer name:"<> name;
getline(cin,name);
cout<>package;
if (!((package==’A') || (package== ‘B’) || (package== ‘C’)))
cout<<" Invalid, Available packages are A,B or C, only."<<endl;
else {
cout<<"How many hours were used?"<744){
cout<< "invalid, hours can not exceed 744"<<endl;
}
else if
(package=='A'){
total= (hours-10)*2.00+pack_a;
cout<<total<<endl;
}
else if
(package=='B'){
total=(hours-20)*1.00+pack_b;
cout<<total<<endl;
}
else if (package=='C')
{ total==pack_c;
cout<<total<<endl;
How do you check if a char variable equals a certain character?
[...] To fully complete this example, you’ll need to utilize if statements, which we won’t cover for a while, but you’re welcome to take a sneak-peak at [...]
[...] To fully complete this example, you’ll need to utilize if statements, which we won’t cover for a while, but you’re welcome to take a sneak-peak at [...]
Hi. I didn´t understand this example in chapter 6.7
if (pnPtr)
cout << "pnPtr is pointing to an integer.";
else
cout << "pnPtr is a null pointer.";
I don´t know what´s the condition for the if statement.
Thanks in advance.
[...] To fully complete this example, you’ll need to utilize if statements, which we won’t cover for a while, but you’re welcome to take a sneak-peak at [...]
Hello!
I have a problem in setting the bin content of a histogram using the if- statement:
(Using root so I will skip the unnecessary part here)
Suppose we have a histogram named : h1, with N bins
int val;
for (i=0;iGetNbinsX();i++)
{
val[i] = h1->GetBinContent(i);
if ( val[i] = 40)
{
h1->SetBinContent(i,0.001);
}
cout<<" for bin "<<i<<" Bin Content is "<<val[i]<<endl;
}
It just doesn't change the bin Content.
What might I be doing wrong?
Thank you very much for your time,