C++ Exercises: Add all the numbers from 1 to a given number
C++ Basic: Exercise-66 with Solution
Pictorial Presentation:
Write a C++ program to add all the numbers from 1 to a given number.
Sample Solution:
C++ Code :
#include <iostream> // Including input-output stream header file
using namespace std; // Using the standard namespace
// Function to calculate the sum of numbers from 1 to n
int Add_1_to_given_number(int n) {
int total = 0; // Variable to store the total sum
// Loop to add numbers from 1 to n
for (int x = 1; x <= n; x++) {
total += x; // Adding each number to the total sum
}
return total; // Returning the final total sum
}
int main() {
// Printing the sum of numbers from 1 to 4 by calling the Add_1_to_given_number function with argument 4
cout << "\nAdd 1 to 4: " << Add_1_to_given_number(4);
// Printing the sum of numbers from 1 to 100 by calling the Add_1_to_given_number function with argument 100
cout << "\nAdd 1 to 100: " << Add_1_to_given_number(100);
return 0; // Indicating successful completion of the program
}
Sample Output:
Add 1 to 4: 10 Add 1 to 100: 5050
Flowchart:
C++ Code Editor:
Previous: Write a C++ program to check whether given length of three side form a right triangle.
Next: Write a C++ program to which prints the central coordinate and the radius of a circumscribed circle of a triangle which is created by three points on the plane surface.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/cpp-exercises/basic/cpp-basic-exercise-66.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics