OneBite.Dev - Coding blog in a bite size

If Else Conditional Statement In C++

Code snippet for how to If Else Conditional Statement In C++ with sample and detail explanation

Conditional statements play a crucial role in any programming language, and in C++, the if-else statement is a basic, yet powerful, tool for controlling the flow of code. This article will give you an understanding of how the if-else statement works in C++, along with an illustrative example.

Code snippet for if-else Conditional Statement

Below, you will find a simple code snippet demonstrating an if-else statement in C++:

#include <iostream>
using namespace std;

int main() {
    int number = 10;

    if (number > 0) {
        cout << "Number is positive." << endl;
    }   
    else {
        cout << "Number is not positive." << endl;
    }

    return 0;
}

Code Explanation for if-else Conditional Statement

To fully understand the code snippet above, we should break it down.

  1. #include <iostream>: This is a preprocessor directive that includes the iostream standard file. This file is needed for input and output operations.

  2. using namespace std;: This line enables the program to understand cout and other elements that are part of the standard C++ library without requiring us to write std:: before each one.

  3. int main(): This is the main function where the execution of any C++ program begins.

  4. int number = 10;: Here, we are declaring an integer variable named ‘number’ and assigning it the value 10.

  5. if (number > 0): This initiates the if-else conditional statement. It checks if the condition within the parenthesis (number > 0) is true. As ‘number’ is 10 which is greater than 0, the condition is indeed true.

  6. cout << "Number is positive." << endl;: Since the condition is true, this line will output the string “Number is positive.” to the console.

  7. else: This is executed if the initial if condition proves to be false. In our case, because the number is positive, this part of the statement is ignored.

  8. cout << "Number is not positive." << endl;: This line is part of the ‘else’ statement and would be executed if number was not greater than 0.

  9. return 0;: This line ends the main function and returns 0, indicating that the program has run without errors.

In conclusion, the if-else statement is used to perform different actions based on different conditions. The ‘if’ checks a condition; if it is true, it executes a block of code. If the condition is false, it executes the ‘else’ block. This tutorial has walked you through the basic structure and application of the if-else statement in C++.

c-plus-plus