while loop

Sep 12, 2015 at 6:05pm
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 Sep 12, 2015 at 6:06pm
Sep 12, 2015 at 6:22pm
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 Sep 12, 2015 at 6:23pm
Sep 12, 2015 at 7:00pm
closed account (48T7M4Gy)
Write pseudo code first based on Codewriter's suggestion.

Then write the program.
Sep 12, 2015 at 7:38pm
Topic archived. No new replies allowed.