Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
If...else Statement | Introduction to Program Flow
C++ Introduction
course content

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Variables and Data Types
3. Introduction to Operators
4. Introduction to Program Flow
5. Introduction to Functions

bookIf...else Statement

The if...else construct in programming allows your program to take different paths and manage various potential outcomes.

It consists of two essential components: a condition and the corresponding actions or consequences based on that condition.

Here's an illustration:

cpp

main

copy
123456789101112131415161718192021222324
#include<iostream> int main() { int var = 13; /* If my variable equals 13, then print "OKAY", and change variable to 15 */ if (var == 13) { std::cout << "13 == 13, it is OKAY" << std::endl; var = 15; } /* New value of variable (15) doesn't equal 13, then print "NOT OKAY" */ if (var != 13) { std::cout << "15 != 13, it is NOT OKAY" << std::endl; } }

Here, we use the 2-lines comment.

There is also a handling of the "opposite" case using else:

cpp

main

copy
12345678910111213141516171819202122
#include<iostream> int main() { int var = 200; /* If my variable equals 13, then print "OKAY" */ if (var == 13) { std::cout << "My variable equals 13, it is OKAY" << std::endl; } /* If my variable doesn`t equal 13, then print "NOT OKAY" */ else { std::cout << "My variable doesn't equal 13, it is NOT OKAY" << std::endl; } }

There can be other if...else inside the if...else:

cpp

main

copy
123456789101112131415161718192021222324
#include<iostream> int main() { int var = 15; if (var == 15) { //then var = 15 + 200; if (var == 300) { //then std::cout << "OKAY" << std::endl; } // otherwise else { std::cout << "NOT OKAY" << std::endl; } } }

You can also use the else if construct:

cpp

main

copy
1234567891011121314151617181920212223
#include<iostream> int main() { int var = 50; if (var == 15) { std::cout << "var equals 15" << std::endl; } else if (var == 50) { std::cout << "var equals 50" << std::endl; } else if (var == 89) { std::cout << "var equals 89" << std::endl; } else if (var == 215) { std::cout << "var equals 215" << std::endl; } }
What will the program output?

What will the program output?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 1
some-alt