Mark As Completed Discussion

In C++, control flow is crucial to the way a program runs. It dictates how and in which sequence the code statements will be executed. The if-else statement forms the basis of control flow in C++, allowing the program to make decisions. It's quite similar to making decisions in finance: where to invest? Tesla or Apple? Exactly in the same way, if-else allows your code to choose between different execution paths based on certain conditions.

An if-else statement in C++ begins with an if keyword, followed by a boolean condition, followed by a block of code that is executed if the condition is true. If the condition is false, the control is passed to the else block (if there is one), and its code is executed.

Here's an example. Let's say you are a senior engineer building an AI to decide when to invest in stocks. You can use an if-else statement to decide based on the stock price:

TEXT/X-C++SRC
1int stockPriceTesla = 650;  
2int stockPriceApple = 150; 
3
4// If-else Decision making
5if (stockPriceTesla > stockPriceApple) {
6  cout<<"Invest in Apple!";
7} else {
8  cout<<"Invest in Tesla!";
9}

This bit of logic can help you decide where to invest depending on the condition specified in the if statement. If the condition is true (Tesla's price is greater than Apple's), you invest in Apple. Otherwise, you invest in Tesla (controlled by the else statement).

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment