The if Statement in C++

By: Priya Emailed: 1674 times Printed: 2154 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Normally, your program flows along line by line in the order in which it appears in your source code. The if statement enables you to test for a condition (such as whether two variables are equal) and branch to different parts of your code, depending on the result.

The simplest form of an if statement is this:

if (expression)
     statement;

The expression in the parentheses can be any expression at all, but it usually contains one of the relational expressions. If the expression has the value 0, it is considered false, and the statement is skipped. If it has any nonzero value, it is considered true, and the statement is executed. Consider the following example:

if (bigNumber > smallNumber)
     bigNumber = smallNumber;

This code compares bigNumber and smallNumber. If bigNumber is larger, the second line sets its value to the value of smallNumber.

Because a block of statements surrounded by braces is exactly equivalent to a single statement, the following type of branch can be quite large and powerful:

if (expression)
{
     statement1;
     statement2;
     statement3;
}

Here's a simple example of this usage:

if (bigNumber > smallNumber)
{
     bigNumber = smallNumber;
     cout << "bigNumber: " << bigNumber << "\n";
     cout << "smallNumber: " << smallNumber << "\n";
}

This time, if bigNumber is larger than smallNumber, not only is it set to the value of smallNumber, but an informational message is printed. Listing below shows a more detailed example of branching based on relational operators.

A demonstration of branching based on relational operators.

1:  // Listing 4.4 - demonstrates if statement
2:  // used with relational operators
3:  #include <iostream.h>
4:  int main()
5:  {
6:        int RedSoxScore, YankeesScore;
7:        cout << "Enter the score for the Red Sox: ";
8:        cin >> RedSoxScore;
9:
10:       cout << "\nEnter the score for the Yankees: ";
11:       cin >> YankeesScore;
12:
13:       cout << "\n";
14:
15:       if (RedSoxScore > YankeesScore)
16:            cout << "Go Sox!\n";
17:
18:       if (RedSoxScore < YankeesScore)
19:       {
20:            cout << "Go Yankees!\n";
21:            cout << "Happy days in New York!\n";
22:       }
23:
24:       if (RedSoxScore == YankeesScore)
25:       {
26:            cout << "A tie? Naah, can't be.\n";
27:            cout << "Give me the real score for the Yanks: ";
28:            cin >> YankeesScore;
29:
30:            if (RedSoxScore > YankeesScore)
31:                 cout << "Knew it! Go Sox!";
32:
33:            if (YankeesScore > RedSoxScore)
34:                 cout << "Knew it! Go Yanks!";
35:
36:            if (YankeesScore == RedSoxScore)
37:                 cout << "Wow, it really was a tie!";
38:       }
39:
40:       cout << "\nThanks for telling me.\n";
41:        return 0;
42: }
Output: Enter the score for the Red Sox: 10

Enter the score for the Yankees: 10

A tie? Naah, can't be
Give me the real score for the Yanks: 8
Knew it! Go Sox!
Thanks for telling me.

Analysis: This program asks for user input of scores for two baseball teams, which are stored in integer variables. The variables are compared in the if statement on lines 15, 18, and 24.
If one score is higher than the other, an informational message is printed. If the scores are equal, the block of code that begins on line 24 and ends on line 38 is entered. The second score is requested again, and then the scores are compared again.

Note that if the initial Yankees score was higher than the Red Sox score, the if statement on line 15 would evaluate as FALSE, and line 16 would not be invoked. The test on line 18 would evaluate as true, and the statements on lines 20 and 21 would be invoked. Then the if statement on line 24 would be tested, and this would be false (if line 18 was true). Thus, the program would skip the entire block, falling through to line 39.

In this example, getting a true result in one if statement does not stop other if statements from being tested.


C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(8)


1. View Comment

w0w amazing

View Tutorial          By: elvin at 2009-01-05 01:00:13
2. View Comment

Can we use the if sttmt l;ike this::
if (a==b==c==d==e)
i.e., multiple equality operators together??


View Tutorial          By: Anubhav at 2010-11-14 08:15:04
3. View Comment

#include<iostream>
#include<conio.h>
using namespace std;

main()
{
float Call_Amount, Call_Duration;
Call_Amount = 3.99;
cout<<"Please input the duration of call(in minutes):";
cin>>Call_Duration;
If (Call_Duration > 3)
{
Additional_Minutes = Call_Duration - 3;
Additional_Charge = Additional_Minutes * 0.45;
Call_Amount = Additional_Charge + Call_Amount;
}
cout<<"Call lasted for "<<Call_Duration<<" minutes. Call amount is "<<Call_Amount<<".";

getch();

}


What's wrong with this?


View Tutorial          By: XavioR at 2011-01-31 00:53:11
4. View Comment

#include<iostream>
#include<conio.h>
using namespace std;

void main()
{
float Call_Amount, Call_Duration,Additional_Minutes,Additional_Charge;
Call_Amount = 3.99;
cout<<"Please input the duration of call(in minutes):";
cin>>Call_Duration;
if (Call_Duration > 3)
{
Additional_Minutes = Call_Duration - 3;
Additional_Charge = Additional_Minutes * 0.45;
Call_Amount = Additional_Charge + Call_Amount;
cout<<Call_Amount<<endl;
cout<<"Call lasted for "<<Call_Duration<<" minutes. Call amount is "<<Call_Amount<<".";
}
else {
cout<<"wrong data";
}
getch();

}


View Tutorial          By: Zohaib Farooq at 2011-05-23 07:58:44
5. View Comment

#include<iostream>
#include<conio.h>
using namespace std;

void main()
{
float Call_Amount, Call_Duration,Additional_Minutes,Additional_Charge;
Call_Amount = 3.99;
cout<<"Please input the duration of call(in minutes):";
cin>>Call_Duration;
if (Call_Duration > 3)
{
Additional_Minutes = Call_Duration - 3;
Additional_Charge = Additional_Minutes * 0.45;
Call_Amount = Additional_Charge + Call_Amount;
cout<<Call_Amount<<endl;
cout<<"Call lasted for "<<Call_Duration<<" minutes. Call amount is "<<Call_Amount<<".";
}
else {
cout<<"wrong data";
}
getch();

}


View Tutorial          By: Zohaib Farooq at 2011-05-23 12:47:54
6. View Comment

# include <iostream.h>
int main ()
{
int x,y
cout<<"enter your year:\n";
cin>>x;
cout<<"enter your year:\n";
cin>>y;
cout<<the sum of two no# is:\n";
return 0;
{


View Tutorial          By: nazarine at 2011-07-06 06:17:10
7. View Comment

cool.

View Tutorial          By: Fahad Palomo at 2011-08-03 06:19:56
8. View Comment

it is very good website for IT students

View Tutorial          By: jeecee at 2013-03-21 12:23:46

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Priya
Getting started with ASP
EJB Entity Beans
Error Handling - Stderr and Exit - sample program in C
Pointers and Arrays in C
Data Types and Sizes in C
virtual inheritance example in C++
ctime() sample program in C++
TextBox sample program in J2ME
Advantages of Java Beans
list() contents of a Directory - sample program in Java
File example program in Java
continue and break statements in C++
Use of 'throw' in Java
Passing parameters to a function by value in C++
Demonstrating global and local variables in C++

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Using cout.width() in C++
Calculating total based on the given quantity and price in C++
Using peek() and putback() with cin in C++
C++ Recursion function explained using Fibonacci series
The indirection operator (*) - dereference operator.
Using cout in C++
The Stack and the Free Store in C++
ctime() sample program in C++
Using cout.fill() in C++
Calculate average using Two-Dimensional Array in C++
A Brief History of C++
Difference between Procedural, Structured, and Object-Oriented Programming
The if Statement in C++
Advanced if Statements in C++
The Birth, history and need for C++
Most Emailed Articles (in C++)
Looping with the keyword goto in C++
Default arguments in C++
Compiling and Linking Multiple Source Files in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Tutorial on Classes and Members in C++
for Loops in C++
Using switch Statements in C++
Operator Precedence in C++
How to handle Exceptions in C++
strcpy() and strncpy() sample program in C++
assert() example program in C++
Using peek() and putback() with cin in C++
Function overloading in C++
File in C++ - Writing text to a file in C++
Pass by Reference vs Pass Value in C++ functions