lab 4
lab 4
LAB REPORT # 4
INTRODUCTION: 3
TYPES OF LOOPS: 3
For loop: 3
While loop: 4
Do-while loop: 4
MY TASKS 5
CONCLUSION 10
Table of figures:
Figure 1: for loop.........................................................................................................................................3
Figure 2: while loop.....................................................................................................................................4
Figure 3: do-while loop................................................................................................................................5
Types of loops:
For loop
While loop
Do-while loop
For loop:
The for loop in C++ is a control flow statement that allows us to execute a block of code repeatedly for a
specific number of iterations.
It is used when we know how many times we want a block of code is executed.
Syntax:
// Code to execute
While loop:
The while loop in C++ is a control flow statement that allows you to execute a block of code repeatedly
as long as a specified condition is true. Unlike the for loop, which is typically used when the number of
iterations is known, the while loop is more suitable when the number of iterations is unknown or
depends on a condition that may change during runtime.
Syntax:
while (condition) {
// Code to execute
}
Figure 2: while loop
Do-while loop:
The do-while loop in C++ is a control flow statement that allows you to execute a block of code
repeatedly as long as a specified condition is true. Unlike the while loop, which checks the
condition before executing the loop body, the do-while loop checks the condition after executing the
loop body. This means that the loop body is guaranteed to execute at least once, even if the condition is
initially false.
Syntax:
do {
// Code to execute
} while (condition);
My tasks
Task 1: Find out all proper factors of a number
The user was asked to enter an integer to find out its proper factors. I used for loop for this code.
Code:
#include <iostream>
int main()
int n;
cin>>n;
if (n%i==0)
cout<<i<<endl;
return 0;
Output:
Code:
#include <iostream>
int n=0;
int sum=0;
cin>>n;
if (n%i==0)
sum+=i;
if (sum==n)
else
return 0;
Output:
Code:
#include <iostream>
int n;
cin>>n;
bool prime=true;
if (n<=1){
prime=false;
}else {
if (n % i == 0) {
prime=false;
break;
if (prime){
}else {
return 0;
Output:
Code:
#include <iostream>
int main() {
int n;
cin>>n;
factorial *= i;
cout << "Factorial of " << n << " = " << factorial << endl;
return 0;
Output:
Code:
#include <iostream>
int main ()
{
int num;
int i=1;
cin>>num;
while (i<=10) {
cout<<num<<"x"<<i<<"="<<num*i<<endl;
i++;
return 0;
Output:
Conclusion:
Loops are a fundamental concept in C++ programming that allow us to execute code repeatedly. By
understanding the differences between for, while, and do-while loops, we can choose the right tool for
the task at hand. Each one serves an important purpose depending on the type of condition we want the
code to meet.