even number program in c++ using for loop stack overflow
Certainly! Here is a C++ program that uses a for loop to print even numbers, along with explanations for each step:
#include <iostream>
int main() {
int n;
std::cout << "Enter a number: ";
std::cin >> n;
std::cout << "Even numbers up to " << n << " are: ";
for (int i = 2; i <= n; i += 2) {
std::cout << i << " ";
}
return 0;
}
Step-by-step Explanation:
We start by including the
<iostream>
header file, which allows us to use the input/output stream objects likestd::cout
andstd::cin
.The
main()
function is the entry point of the program.We declare an integer variable
n
to store the user input.The line
std::cout << "Enter a number: ";
displays a prompt to the user, asking them to enter a number.The line
std::cin >> n;
reads the user input and stores it in the variablen
.The line
std::cout << "Even numbers up to " << n << " are: ";
displays a message indicating that we will print even numbers up ton
.The
for
loop is used to iterate from2
ton
with a step size of2
(since even numbers are divisible by 2).Inside the loop, the line
std::cout << i << " ";
prints the value ofi
, which represents the current even number.After the loop finishes, the
main()
function returns0
, indicating successful execution of the program.
The program prompts the user to enter a number and then uses a for
loop to print all the even numbers from 2
up to the user-specified number.