top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are the decision making statements in C++? Explain if statement with an example?

+1 vote
480 views
What are the decision making statements in C++? Explain if statement with an example?
posted Aug 8, 2017 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The decision making statements in C++ language are used to perform operations on the basis of condition and when program encounters the situation to choose a particular statement among many statements.

Decision making statements lets you evaluate one or more conditions and then take decision whether to execute a set of statements or not.
enter image description here

Following are the decision control statements available in C++ :-
a) if statement
b) if-else & else-if statement
c) switch-case statements

If statement: The code inside if body executes only when the condition defined by if statement is true. If the condition is false then compiler skips the statement enclosed in if’s body. We can have any number of if statements in a C++ program.

If-else statement: Here, we have two block of statements. If condition results true then if block gets execution otherwise statements in else block executes. else cannot exist without if statement.

Switch-case statement: This is very useful when we have several block of statements, which requires execution based on the output of an expression or condition. switch defines an expression (or condition) and case has a block of statements, based on the result of expression, corresponding case gets execution. A switch can have any number of cases, however there should be only default handler.

if statement consists of a boolean expression followed by one or more statements
Syntax:

if(boolean_expression) {
   // statement(s) will execute if the boolean expression is true
}

enter image description here
// Program to print positive number entered by the user
// If user enters negative number, it is skipped

#include <iostream.h>
using namespace std;

int main() 
{
    int number;
    cout << "Enter an integer: ";
    cin >> number;

    // checks if the number is positive
    if ( number > 0) 
    {
        cout << "You entered a positive integer: " << number << endl;
    }

    cout << "This statement is always executed.";
    return 0;

}

Output 1

Enter an integer: 5
You entered a positive number: 5
This statement is always executed.

Output 2

Enter a number: -5
This statement is always executed.
answer Aug 9, 2017 by Piyush Jain
...