MUCLecture 2023 4426617
MUCLecture 2023 4426617
Kareem
Computer Skills & Programming I I MSc. Murtada A. Mahdi
In C++ programming language, there are three loop statements, these looping
statements and loop control statements help to execute a block of code iteratively in
a loop and control the loop execution respectively.
while (conditional)
{
Block_of_statements ;
}
Example1: In this example, we shall write a while loop that prints numbers from 1
to 5. The while loop contains a statement to print a number; the condition checks if
the number is within the limits.
#include <iostream>
using namespace std;
1
MSc. Baraa H. Kareem
Computer Skills & Programming I I MSc. Murtada A. Mahdi
int main() {
int n = 5;
int i = 1;
while (i<=n) {
cout << i << "\n";
i++;
}
}
#include <iostream>
using namespace std;
int main() {
int n = 5;
int factorial = 1;
int i = 1;
while (i<=n) {
factorial *= i;
i++;
}
do {
// statement(s)
} while (condition);
2
MSc. Baraa H. Kareem
Computer Skills & Programming I I MSc. Murtada A. Mahdi
In this example, we shall write a do-while loop that prints the string Hello five
times.
#include <iostream>
using namespace std;
int main() {
int i=0;
do {
cout << "Hello" << endl;
} while (++i < 5);
}
#include <iostream>
using namespace std;
int main() {
int n = 5;
int factorial = 1;
int i = 1;
do {
factorial *= i;
3
MSc. Baraa H. Kareem
Computer Skills & Programming I I MSc. Murtada A. Mahdi
C++ for-Loop
For Loop can execute a block of statements in a loop based on a condition. It is
similar to a while loop in working, but the only difference is that for loop has
provision for initialization and update in its syntax.
The for-loop Syntax is:
At the start of for loop execution, initialization statement is executed and then the
condition is checked. If the condition is true, statement(s) inside for block are
executed. And the update statement is executed. The condition is checked again. If it
evaluates to true, the statement(s) inside the for loop are executed. This cycle goes
on. If at all, the condition evaluates to false, for loop execution is deemed completed
and the program control comes out of the loop. And the program continues with the
execution of statements after for loop if any.
4
MSc. Baraa H. Kareem
Computer Skills & Programming I I MSc. Murtada A. Mahdi
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << "\n";
}
}
#include <iostream>
using namespace std;
int main() {
int n=5;
int factorial = 1;