Table of contents
- Introduction :
- Control Statements
- C++ if, if...else and Nested if...else
- C++ if Statement
- C++ if...else
- C++ if...else...else if statement
- C++ Nested if...else
- Loops :
- For Loop
- While Loop
- Do-while Loop
- Break Statement
- Continue Statement
- Switch Case Statement
- Congratulations!
- Credit To The Following Resource I Referenced :
Introduction :
Welcome to my first series on #Hashnode where I will be documenting my journey of learning C++ from scratch to advance to develop my programming skills and later make some interesting projects. In this blog, I will be sharing what I learnt in C++ since I wrote my previous blog . In this tutorial, we can study the control statements withinside the C++ language. In our last lesson, I mentioned the different Data Types, Header Files and Operators in ++. Do check it out to be up to date with what I will be sharing in this one.
Control Statements
A C++ control statement redirects the flow of a program to execute additional code. These statements come in the form of conditionals (if-else, switch) and loops (for, while, do-while). Each of them relies on a logical condition that evaluates to a boolean value to run one piece of code over another.
C++ if, if...else and Nested if...else
In computer programming, we use the if...else
statement to run one block of code under certain conditions and another block of code under different conditions.
There are three forms of if...else
statements in C++.
if
statementif...else
statementif...else if...else
statement
C++ if Statement
The syntax of the if
statement is:
if (condition) {
// body of if statement
}
How if Statement Works :
The if
statement evaluates the condition
inside the parentheses ( )
.
If the
condition
evaluates totrue
, the code inside the body ofif
is executed.If the
condition
evaluates tofalse
, the code inside the body ofif
is skipped.
Note: The code inside { }
is the body of the if
statement.
C++ if...else
The if
statement can have an optional else
clause. Its syntax is:
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
The if..else
statement evaluates the condition
inside the parenthesis.
How if...else Statement Works
If the condition
evaluates true
,
the code inside the body of
if
is executedthe code inside the body of
else
is skipped from execution
If the condition
evaluates false
,
the code inside the body of
else
is executedthe code inside the body of
if
is skipped from execution
C++ if...else...else if statement
The if...else
statement is used to execute a block of code among two alternatives. However, if we need to choose between more than two alternatives, we use the if...else if...else
statement.
The syntax of the if...else if...else
statement is:
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
How if...else if...else Statement Works
Here,
If
condition1
evaluates totrue
, thecode block 1
is executed.If
condition1
evaluates tofalse
, thencondition2
is evaluated.If
condition2
istrue
, thecode block 2
is executed.If
condition2
isfalse
, thecode block 3
is executed.
Note: There can be more than one else if
statement but only one if
and else
statements.
C++ Nested if...else
Sometimes, we need to use an if
statement inside another if
statement. This is known as nested if
statement.
Think of it as multiple layers of if
statements. There is a first, outer if
statement, and inside it is another, inner if
statement. Its syntax is:
// outer if statement
if (condition1) {
// statements
// inner if statement
if (condition2) {
// statements
}
}
Notes:
We can add
else
andelse if
statements to the innerif
statement as required.The inner
if
statement can also be inserted inside the outerelse
orelse if
statements (if they exist).We can nest multiple layers of
if
statements.
Loops :
In computer programming, loops are used to repeat a block of code.
For example, let's say we want to show a message 100 times. Then instead of writing the print statement 100 times, we can use a loop.
That was just a simple example; we can achieve much more efficiency and sophistication in our programs by making effective use of loops.
There are 3 types of loops in C++.
for
loopwhile
loopdo...while
loop
For Loop
A for loop allows for a block of code to be executed until a conditional becomes false. For loops are usually used when a block of code needs to execute a fixed number of times. Each loop consists of 3 parts, an initialization step, the conditional, and an iteration step. The initialization is run before entering the loop, the condition is checked at the beginning of each run through the loop ( including the first run ), and the iteration step executes at the end of each pass through the loop, but before the condition is rechecked. It is usual practice to have the iteration step move the loop one step closer to making the condition false, thus ending the loop, but this does not need to be the case.
The syntax of for-loop
is:
for (initialization; condition; interation) {
// body of-loop
}
Here,
initialization
- initializes variables and is executed only oncecondition
- iftrue
, the body offor
loop is executed
iffalse
, the for loop is terminatediteration
- updates the value of initialized variables and again checks the condition
Example: Printing Numbers From 1 to 10
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
cout << i << " ";
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
While Loop
A while loop is a simple loop that will run the same code over and over as long as a given condition is true. The condition is checked at the beginning of each run through the loop ( including the first one ). If the conditional is false for the beginning, the while loop will be skipped altogether.
The syntax of the while
loop is:
while (condition) {
// body of the loop
}
Here,
A
while
loop evaluates thecondition
If the
condition
evaluates totrue
, the code inside thewhile
loop is executed.The
condition
is evaluated again.This process continues until the
condition
isfalse
.When the
condition
evaluates tofalse
, the loop terminates.
Example: Display Numbers from 1 to 10
#include <iostream>
using namespace std;
int main() {
int i = 1;
// while loop from 1 to 10
while (i <= 5) {
cout << i << " ";
i++;
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
Do-while Loop
A do-while loop acts just like a while loop, except the condition is checked at the end of each pass through the loop body. This means a do-while loop will execute at least once.
The syntax for Do-while
loop is:
do {
// body of loop;
}
while (condition);
Here,
The body of the loop is executed at first. Then the
condition
is evaluated.If the
condition
evaluates totrue
, the body of the loop inside thedo
statement is executed again.The
condition
is evaluated once again.If the
condition
evaluates totrue
, the body of the loop inside thedo
statement is executed again.This process continues until the
condition
evaluates tofalse
. Then the loop stops.
Example: Display Numbers from 1 to 10
#include <iostream>
using namespace std;
int main() {
int i = 1;
// do...while loop from 1 to 10
do {
cout << i << " ";
i++;
}
while (i <= 10);
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
Break Statement
Break is a useful keyword that allows the program to exit a loop or switch statement before the expected end of that code block. This is useful in error checking or if the outcome of a loop is not certain.
The syntax of the break
statement is:
break;
Example: break with for loop
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// break condition
if (i == 4) {
break;
}
cout << i << endl;
}
return 0;
}
Output
1
2
3
Continue Statement
In computer programming, the continue
statement is used to skip the current iteration of the loop and the control of the program goes to the next iteration.
The syntax of the continue
statement is:
continue;
Example: continue with for loop
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// condition to continue
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}
Output
1
2
4
5
Switch Case Statement
The switch
statement allows us to execute a block of code among many alternatives.
The syntax of the switch
statement in C++ is:
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
How does the switch statement work?
The expression
is evaluated once and compared with the values of each case
label.
If there is a match, the corresponding code after the matching label is executed. For example, if the value of the variable is equal to
constant2
, the code aftercase constant2:
is executed until the break statement is encountered.If there is no match, the code after
default:
is executed.
Notice!! that the break
statement is used inside each case
block. This terminates the switch
statement.
If the break
statement is not used, all cases after the correct case
are executed.
Example: Create a Calculator using the switch Statement
#include <iostream>
using namespace std;
int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
cout << "Error! The operator is not correct";
break;
}
return 0;
}
Output 1
Enter an operator (+, -, *, /): +
Enter two numbers:
2.3
4.5
2.3 + 4.5 = 6.8
Output 2
Enter an operator (+, -, *, /): -
Enter two numbers:
2.3
4.5
2.3 - 4.5 = -2.2
Congratulations!
You just learnt about control statements in C++ !!!
Thank you for joining me in my quest to conquer C++. In the next blog, we’ll be talking more about arrays and pointers in a C++ program, see you there, till then keep coding and keep learning.