C++ program to find sum of n numbers using while loop
Last updated:27th Aug 2022
In this example, you will learn to find the sum of n numbers in the c++ program by using a while loop.
Example:
input:10 output: 55
sum of 10 number are 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
#include <iostream>
using namespace std;
int main() {
int n, sum = 0,i=1;
cout << "Enter a positive number: ";
cin >> n;
while(i <= n)
{
sum += i;
i+=1;
}
cout << "Sum = " << sum;
return 0;
}
output
working:
Enter a positive number: 5 Sum = 15
- Take a number from the user store in
n
. - Iterate while loop until
i
value equal to n. - Inside while loop adds
i
value in sum value. - When the loop breaks print the sum of the n values.