while loop

Using while loops, write programs that calculates the sum of the first n counting numbers: 1 + 2 + 3 + .. + n
If user input 4, output=10
If user input 3, output=6

#include <iostream>

using namespace std;

int main()
{
int n,z=1,sum=0,y=1;
cout<<"n= ";
cin>>n;
while ( z<=n)
{

while(y<=z)
{
sum=sum+z;

}
z=z+1;
}
cout<<sum;
}


I'm not getting sum output!
help!
Last edited on
It looks like a random program with some loops thrown in and a pinch of hope it will work?
Make it clear in your mind how you would do it with pen and paper and then convert it to code.
You only need one loop. Within the loop you add z to sum and increment z while z < n.
Last edited on
closed account (48T7M4Gy)
Write pseudo code first based on Codewriter's suggestion.

Then write the program.
Topic archived. No new replies allowed.