Using a for loop
In this approach, we use a for
loop to iterate through the sequence and add up the numbers from 1 to n. We will store the sum in a variable called sum
.
Add the following code to your main.cpp
file:
#include <iostream>
int main() {
int n, sum = 0;
std::cout << "Enter the value of n: ";
std::cin >> n;
for(int i = 1; i <= n; ++i) {
sum += i;
}
std::cout << "The sum of the sequence is: " << sum << std::endl;
return 0;
}
Here, we use the std::cout
function to display a message asking the user to enter the value of n
. We then use the std::cin
function to read in the value of n
entered by the user. We initialize sum
to 0
before starting the for loop.
The for
loop iterates over values of i
from 1
to n
, adding each value to the sum
. Finally, we display the sum using std::cout
.
Before we can run the program, we need to compile it. In the terminal, navigate to the ~/project
directory and run the following command:
g++ main.cpp -o main && ./main
This will compile and run the program. You should see a message asking you to enter the value of n
. After you enter a value, the program will display the sum of the sequence.