hey guyz!!! i'm just trying to check my code u all if it's correct. thankz!

the problem is " ask a number (N). calculate and display the value of x, where x = (1*N)+(2*N)+(3*N)...(N*N);
ex. if i input a number 5 the formula of x where: x = (1*N)+(2*N)+(3*N)+(4*N)+(5*N);

this is my code:

``````#include <iostream>
int main ()
{
int n,x,y;
y=0;
cout<<"\nEnter number: ";
cin>>n;

while (y<=n)
{

cout<<"\n"<<y;
y++;
x += (y*n);

}
cout<<"\n\nx = "<<x;

return 0;
}``````
3
Contributors
5
Replies
6
Views
9 Years
Discussion Span
Last Post by vijayan121

>>i'm just trying to check my code u all if it's correct
does it do what its supposed to do ? If yes, then its ok. If not then you need to fix it. One problem though is that your program will produce data overflow errors if the value of n is too large.

not! the display is different with my calculation on my own..
x += (y*n); << i'm not sure with this formula...
can you help me with this?

The value of x is uninitialized, and the value of y should start at 1 not 0. It might be better to use a for loop instead of a while loop.

NICE ONE MAN!! I GOT IT!! THANKS, MORE POWER TO YOU...

i'm using the "for loop" its results, like my calculation...huh!

(1*n)+(2*n)+(3*n)...(n*n) == (1+2+3+..+n)*n == (n+1)/2*n*n