C++ Counting
To count in C++, you can use a for loop. Here is an example:
#include <iostream>
using namespace std;
int main() {
int count = 0;
for (int i = 1; i <= 10; i++) {
count += i;
}
cout << "The count is: " << count << endl;
return 0;
}
Explanation:
We include the
<iostream>
library to use thecout
andendl
functions.We declare an integer variable
count
and initialize it to 0. This variable will keep track of the total count.We start a for loop with the initialization expression
int i = 1
, the conditioni <= 10
, and the increment expressioni++
. This loop will iterate fromi = 1
toi = 10
, inclusive.Inside the loop, we add the current value of
i
to thecount
variable using the+=
operator. This will increment the count byi
on each iteration.After the loop, we use
cout
to display the final count value by concatenating it with a string message:"The count is: " << count
.Finally, we return 0 to indicate successful program execution.
When you run this code, it will output: "The count is: 55". This is the sum of the numbers from 1 to 10.