print all number between a and b in c++
To print all numbers between a
and b
in C++, you can use a loop that iterates from a
to b
and prints each number. Here's the code:
#include <iostream>
int main() {
int a, b;
std::cout << "Enter the values of a and b: ";
std::cin >> a >> b;
for (int i = a; i <= b; i++) {
std::cout << i << " ";
}
return 0;
}
Let's go through each step of the code:
Include the necessary header file:
#include <iostream>
includes the input/output stream library, which provides the necessary functions for input and output operations.Declare variables:
int a, b;
declares two integer variablesa
andb
to store the range of numbers.Get input from the user:
std::cout << "Enter the values of a and b: ";
displays a message asking the user to enter the values ofa
andb
.Read input values:
std::cin >> a >> b;
reads the values entered by the user and assigns them to the variablesa
andb
.Loop through the numbers:
for (int i = a; i <= b; i++)
starts a loop that iterates froma
tob
, withi
as the loop variable.Print each number:
std::cout << i << " ";
prints the value ofi
followed by a space. This will display each number betweena
andb
.End the program:
return 0;
indicates the end of the program.
By following these steps, the program will prompt the user to enter the values of a
and b
, and then it will print all the numbers between a
and b
.