Lab task 1
Lab task 1
Assignment On
Submitted To
Submitted By
ID 2012020076
Batch 53(B)
int main() {
int i = 1;
while (i <= 5) {
std::cout << i << " ";
i++;
}
return 0;
}
Explanation: The while loop is a pre-tested loop in C++. It repeatedly executes a block of code
as long as the given condition (i.e., i <= 5) is true. At first we initialize, then we put a condition
and then we increment. In this example, the loop prints the numbers from 1 to 5.
2) Do While Loop:
#include <iostream>
int main() {
int i = 1;
do {
std::cout << i << " ";
i++;
} while (i <= 5);
return 0;
}
Explanation: The do while loop is a post-tested loop in C++. It first executes the block of code
and then checks the condition (i <= 5). If the condition is true, it repeats the loop. This loop will
also print the numbers from 1 to 5, just like the while loop.
3) For Loop:
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
std::cout << i << " ";
}
return 0;
}
Explanation: The for loop is commonly used when you know the number of iterations required.
It consists of three parts: initialization (int i = 1), condition (i <= 5), and update (i++). The loop
will execute the code block as long as the condition is true. This loop will also print the numbers
from 1 to 5.
4) Nested Loop:
#include <iostream>
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
std::cout << i << "," << j << " ";
}
}
return 0;
}
Explanation: Nested loops are loops inside another loop. In this example, we have two for
loops: the outer loop runs three times, and the inner loop runs two times for each iteration of the
outer loop. It will print the numbers in the format: "1,1 1,2 2,1 2,2 3,1 3,2".
int main() {
int m;
std::cout << "Enter your marks: ";
std::cin >> m;
if (m >= 80) {
std::cout << "Your Grade is: A+";
} else if (m >= 75) {
std::cout << "Your Grade is: A";
} else if (m >= 70) {
std::cout << "Your Grade is: A-";
} else if (m >= 65) {
std::cout << "Your Grade is: B+";
} else if (m >= 60) {
std::cout << "Your Grade is: B";
}
else if (m >= 55) {
std::cout << "Your Grade is: B-";
}else if (m >= 50) {
std::cout << "Your Grade is: C+";
}else if (m >= 45) {
std::cout << "Your Grade is: C";
}else if (m >= 40) {
std::cout << "Your Grade is: D";
}else {
std::cout << "Your are Fail";
}
return 0;
}
Explanation: This program takes the user's marks as input ‘m’ and then uses an if-else ladder to
determine the grade based on the marks.
int main() {
int n, s = 0;
std::cout << "Sum of positive even numbers from 2 to " << n << " is: " << s;
return 0;
}
Explanation: This program calculates the sum of positive even numbers from 2 to the input
number n. We initialize “i=2” because the even number starts from 2. It uses a for loop starting
from 2 and increments by 2 until reaching n. The sum of all even numbers within this range is
then displayed.