loop execution descending order in c++
Here is an example of a loop in C++ that executes in descending order:
#include <iostream>
int main() {
int n = 10;
for (int i = n; i >= 1; i--) {
std::cout << i << " ";
}
return 0;
}
Explanation:
The
#include <iostream>
statement includes the necessary header file for input and output operations in C++.The
int main()
function is the entry point of the program.The variable
n
is initialized with the value 10.The
for
loop is used to execute a set of statements repeatedly. It consists of three parts: initialization, condition, and increment/decrement.In the initialization part, the variable
i
is initialized with the value ofn
. This sets the starting point of the loop.In the condition part, the loop will continue executing as long as the condition
i >= 1
is true. This ensures that the loop will iterate as long asi
is greater than or equal to 1.In the increment/decrement part,
i--
is used to decrement the value ofi
by 1 in each iteration. This ensures that the loop will move towards the desired descending order.Inside the loop, the statement
std::cout << i << " ";
is used to print the current value ofi
followed by a space. This will output the numbers in descending order with spaces separating them.After the loop, the
return 0;
statement indicates the successful termination of the program.
This program will output the numbers from 10 to 1 in descending order.