Skip to main content

Decision Making Statements in C++.

The smallest Independent Unit in a C++ program is a statement i.e. You can relate it to sentences of a natural language. Because, Just like sentences are terminated with a period (.), similarly the statements are also terminated with semicolon (;)

The simplest form of a program statement is the empty statement i.e.( ;)
(NOTE - I will not be explaining this topic so much because, It is mostly known by every programmer, doesn't not matter if he/she is a beginner or a professional)

Let's discuss the Decision Making Statements one by one.

1.If Statement - These statements are used when you want something to happen if your condition is true. Consider an example like this - If it's rainy outside I will bring an Umbrella with me.

#include<iostream>
using namespace std;
int main()
{
    bool rain = true;

    if(rain == true)        // It can simply be written as if(rain){}
    {
        cout << "Take an Umbrella with you" << endl;
    }
}

Actually inside if( __here__ ), you can create any situation as you want, You can mix Logical operators to make it work for more than one condition in a single if block, you can use relational operators like this - 

#include<iostream>
using namespace std;
int main()
{
    int a = 10;
    
    if(a <= 21)         
        cout << "A is less" << endl;
}

2. If-else Statement - These are equivalent of saying if some particular condition is true than do something, and do something else for every other scenario. Below code demonstrate the idea - 

#include<iostream>
using namespace std;
int main()
{
    int a = 10;

    if(a < 12)      // True if A is less than 12
        cout << "A is less than 12" << endl;
    else            // True if A is equal to 12 or greater than 12
        cout << "A is not less than 12" << endl;

    return 0;
}

3. If - else if statement - These statement blocks are used when you have multiple conditions and you have perform different task for each of this conditions, For example consider the below program - Where I have to print different messages for each of the condition.

#include<iostream>
using namespace std;
int main()
{
    int a = 10;

    if(a < 12)
        cout << "A is less than 12" << endl;
    else if(a == 12)
        cout << "A is equal to 12" << endl;
    else
        cout << "A is greater than 12" << endl;

    return 0;
}

4. Nested - if statements - These are simply if statements that are inside other if statements, In some scenario, we can replace nested if statement with the help of relational operators (But it is not necessarily true for every case), Consider the given program - 

#include<iostream>
using namespace std;
int main()
{
    int a = 10;

    if(a < 12)
    {
        if(a < 10)
            cout << "A is less than 10" << endl;
        else
            cout << "A is less than 12 but greater than or equal to 10" << endl;
    }
    
    return 0;
}

You can see that, I wrote one if - else statement block inside the outside if statement. You, can also relate these nested - if statement blocks as a ladder of if statements.

5. Switch Statements - The application is same but the syntax is little different, and when you have a mess of if-else statements in your program, you should consider it replacing with switch statement.

The basic structure of switch like this - 

switch(n)       // Here n is a predicate/variable on which we check our conditions
{
    case 1: 
        // Do something
        break;
    case 2:
        // Do something
        break;
    .
    .
    .
    default:
        // Do something
        break;
}

Let's try to create a simple calculator using switch statement

#include<iostream>
using namespace std;
int main()
{
    int a, b;
    cout << "Enter first number : " << endl; cin >> a;
    cout << "Enter second number : " << endl; cin >> b;
    cout << "Enter symbol of operation to perform : " << endl;
    cin.ignore();
    cout << flush;
    char c;
    cin >> c;               // We take character input like +, -, / or *

    switch(c)               // switch statement take c as parameter.
    {   
        case '+':
            cout << "Sum of " << a << " + " << b << " = " << a+b << endl;
            break;
        case '-':
            cout << "difference of " << a << " - " << b << " = " << a-b << endl;
            break;
        case '*':
            cout << "Mulitplication of " << a << " * " << b << " = " << a*b << endl;
            break;
        case '/':
            cout << "division of " << a << " / " << b << " = " << a/b << endl;
            break;
    }
}

See example run here.

The example must be difficult to understand, only two things that you could have not familiar with is cin.ignore(), To take an Idea of this, you have to remember my previous blogs where I have said that the input doesn't directly go to the desired variables it first get stored in some input buffer. and to clear that input buffer I used cin.ignore(), Why I would need to clear the input buffer,

For, this think of general case when someone is giving the input to my program, he might, for first two numbers enter the number and then hit "Enter" key, but enter key is also a character (Escape sequence character), But, while entering the second number if We enter the "Enter" Key, it will get stored in the character which has to be used for taking arithmetic operators, Which will effect the execution of our program and cause undesired behaviour, To avoid that first we delete that input buffer containing that "Enter" key then take a character in character "c".

 Stay tuned for the upcoming content. For any query leave a comment below.


Click the Subscribe button at the top, to follow my every post regarding c++.

References -
  • Lippman, Stanley B. c++ primer 3rd edition(april 2, 1998)

Comments

Popular posts from this blog

Introduction to Computer Science.

 Before directly jumping deeply in c++, let's first start by creating the roots of computer science. In this post we will answer the following question. What is Computer and How it works? What is Program and Operating system? Low Level vs High Level Language? Compiler v/s Interpreter? By Knowing All these basic concepts You will be able to understand the upcoming more complex concepts easily. Let's start answering the above questions. What is Computer and How it works? What is computer? If I answer briefly,  what is computer?  then it is just a calculator used for doing simple calculations. If I have to answer where is computer used?, then I could probably say everywhere. We are surrounded by computer, for example mobile, smartwatches, and personal computer (obviously).  The below image is the first mechanical computer that we used for calculation.                                        Abacus How computer works? The computer's internal functionality is a whole separate bra

C-style strings vs String Class.

Here, we are going to learn about, what are C-Style Strings and what is String class . So, let's start by giving you the introduction. C-Style String is nothing but, an array of characters, and from the term array we can surely assume that these are static in size i.e. the size of these C-Style strings cannot be increased or decreased. String Class is a Built-in class that provide us much more functionality than C-Style String. C-STYLE STRINGS Before learning the String class, which is full-fledged feature of C++, we should rather start by taking a look at some important things about C-Style String. C-Style Strings are actually array of characters that are terminated by a null character "\0". If you are confused with, why null character? The reason is that, It helps us to define, upto which index we have some useful data present in our character array, and after null character there may or may not be some garbage values of characters. Let's first start by showing a

Algorithms, Pseduocodes and FlowCharts.

Some Basic Knowledge. C++ is a general purpose programming language, created by Bjarne Stroustrup and was firstly released in  1985. It is an extension to C language, Reason for that is if you are familiar with C language than you must be familiar with the fact that there are no classes, templates etc. present in C language. Due to which when classes are added to C language it is named as "C with Classes", but C++ is considered as default name now.  Extra thing to remember - In "C++" the symbol "++" after C is post increment symbol and therefore, "C++" means that In C additional features are added. Now, let's define, what are algorithms? Algorithms are nothing but set of rules that must be followed to accomplish some task. (Now, What that mean?😕) let's take an example of swapping two numbers, i.e. if a = 10 and b = 20 after swapping a = 20 and b = 10. How will you write the procedure for this?  (There are many such algorithms). Accordin