954,164 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

adding a bunch of random numbers

hi i need some help with adding a bunch of random numbers.
i dont understand how to add them all.
heres the code:

#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
int i,x;
srand (time (NULL));
for (i=1; i<=10; i++){
x=rand()%10+1;
cout<<x<<endl;
}
system ("pause");
return 0;
}


i wanna know how to add up all 10 random numbers generated from this.
thank you.

blahbla
Newbie Poster
24 posts since Sep 2009
Reputation Points: 11
Solved Threads: 1
 

Hi blahbla,

It seems to me that your best bet would be to create a new variable before you start your loop that you use to add all of your random numbers together. I would suggest doing the addition right before the end of your for loop so that every iteration of the loop ends by adding the new random number to the accumulation variable.

See compound operators for the correct usage:
http://www.cplusplus.com/doc/tutorial/operators/

-D

dgr231
Junior Poster in Training
76 posts since Aug 2009
Reputation Points: 55
Solved Threads: 7
 

set a variable at the beginning then add them all up:

eg.

int total = 0;

for ( int i = 0; i < 10; i++ )
{
  total = total + i;
}

cout << total;
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

thank you to both of you for answering i understand it now.

blahbla
Newbie Poster
24 posts since Sep 2009
Reputation Points: 11
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You