In: Computer Science
how to write a cpp program that takes a number from a user, and print the sum of all numbers from one to that number on screen? using loop interation as basic as possible.
#include <iostream>
using namespace std;
int main() {
cout<<"Enter the number"<<endl;
int n; // variable n to be taken as input from user
cin>>n; // taking the number as input from the user
long long sum1 = 0; // to display the sum from 1 to n
// 1st method - using for loop (iteration)
// time complexity of this method is O(n)
for(int i = 1;i <= n; i++){
sum1 += i;
}
cout <<"sum from method 1 is -> "<< sum1<<endl;
// 2nd method - using maths
// time complexity of this mehod is O(1)
//mathematical formula to be used is sum = n*(n+1)/2;
long long sum2 = n*(n+1)/2;
cout <<"sum from method 2 is -> "<< sum2<<endl;
}
i have also attached the screenshot for the sample input and output.Thanks for the question. Happy Coding and Stay Safe.