NOTE
Control flow = Conditional Statements
if
Use the if
statement to specify a block of C++ code to be executed if a condition is true.
if(condition){
// Block gets executed if the condition is true
// Some logic here
}
#include<iostream>
using namespace std;
int main(){
int phone = 15; // 15k
int money;
cout << "Enter the money you have" << endl;
//Read money
cin >> money;
if(money>=phone){
cout << "Lets buy the phone" << endl;
}
else{
cout << "Lets wait for the sale" << endl;
}
cout << "Thanks for shopping" << endl; // Always get executed
return 0;
}
if-else
else statement
The else
statement is used along with the if
block.
Use the else
statement to specify a block of code to be executed if the condition us false.
if(condition){
// Block gets executed if the condition is true
// Some logic here
}
else{
// Some code, execute when the condition is false
}
Multiple If’s
#include<iostream>
#include<cstring>
using namespace std;
int main(){
int phone = 15; // 15k
string weather;
int money;
cin >> money >> weather;
// cout << "Enter the money you have" << endl;
// Multiple If Blocks
// Shopping
if(money>phone){
cout << "Lets buy the phone" << endl; // condition 1
}
// Picnic
if(weather==pleasant){
cout << "Lets go for a picnic" << endl; // condition 2
}
else{
cout << "Lets play indoor games" << endl;// else block only depends upon condition 2
}
return 0;
}
else-if
Use the else if
statement to specify a new condition if the previous block condition false.
if (condition1){
// Block of code to be executed if condition1 is true
}
else if (condition2){
// Block of code to be executed if the condition1 is false and condition2 is true
}
else {
// Block of code to be executed if the condition1 and condition2 both are false
}
Ternary Operator [?:]
- It consist of three operands, hence the name is ternary operator.
- It is often used to replace simple
if else
statements.
// Syntax
variable = (condition) ? expressionTrue : expressionFalse
#include<iostream>
#include<cstring>
using namespace std;
int main(){
string weather;
int temp;
cin >> temp;
/* Replaceable code
if(temp>30){
weather = "hot";
}
else{
weather = "Pleasant";
}
*/
// Ternary operator
weather = temp > 30 ? "Hot" : "Pleasant";
cout << weather << endl;
return 0;
}
Switch Case
Use the switch
statement to select one of many code blocks to be executed.
switch(expression){
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
- The
switch
expression is evaluated once. - The value of the expression is compared with the values of each case.
- No complex conditions for a case.
- If there is a match, the associated block of code is executed.