Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The program should get the sum of all array memory locations, but it is only sho

ID: 3640360 • Letter: T

Question

The program should get the sum of all array memory locations, but it is only showing me one randomly generated number.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define RANGE 10

int main()
{
int r[1000];
int num;
int count;
int sum;

for ( count = 0; count < 1000; count++ )
{

r[ count ] = 0;
}

for ( count = 0; count < 1000; count++ )

{


srand((unsigned)time(NULL));

num = rand() % RANGE + 1;

r[ count ] = num;

}


for ( count = 0; count < 1000; count++)

{

sum = r[ count] + sum;

printf("%i", %sum);

}

return(0);

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define RANGE 10

int main()
{
   int r[1000];
   int num;
   int count;
   int sum;

   sum = 0; //you forgot to initialize sum
   srand((unsigned)time(NULL)); //you only need to seed one time

   for (count = 0; count < 1000; count++)
   {
      r[count] = 0;
   }

   for (count = 0; count < 1000; count++)
   {
      num = rand() % RANGE + 1;
      r[count] = num;
   }

   for (count = 0; count < 1000; count++)
   {
      sum += r[count]; //you can use operator +=
   }

   //take total result out of the loop
   printf("%i", sum); //sum not %sum

   return(0);
}