You also didn't likely get a '23' as one of the random numbers.
Also, don't forget to randomize.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int array[20];
int i, npositive;
srand(time(NULL));
// Fill my array with random numbers in [-50,50]
for(i = 0; i < 20; i++)
{
array[i] = (rand() % 101)-50;
}
// Show the user the numbers
puts( "The generated array:" );
display( array, 50 );
// Count the number of positive elements
npositive = 0;
for (i = 0; i < 20; i++)
{
...
}
printf( "The number of positive elements is %d\n", npositive );
|
Now, I do not understand requirement 2. What is the "sum of array
located after the last zero element"?
Does that mean the sum of all elements following the last zero element?
1 2 0 3 4 0 5 6 --> 11
Does that mean the sum of all elements before the last zero element?
1 2 0 3 4 0 5 6 --> 10
Keep in mind that there may not be a zero element. What are you supposed to output?
1 2 3 4 5 6 --> 21
1 2 3 4 5 6 --> 0
(Both answers are correct. Ask your professor for clarification on which one he wants.)
To transform the array you are doing what is called
partitioning it. Any element less than one must come before any element not less than one:
1 -2 3 -4 5 0 -7 --> -2 -4 0 -7 1 3 5
It does not matter what order the elements are except that the ones less than one come before the ones that are not less than one. The following are all correct:
-4 -2 -7 0 5 1 3
-7 -4 -2 0 1 3 5
0 -2 -4 -7 5 3 1
etc.
You can do this two different ways.
1. using an additional array:
copy all the elements less than one into the new array
copy all the elements not less than one into the new array
copy new array to overwrite the original array
2. in-place
for each element less than one, swap it with element
array[20-num_swaps]
I recommend you try method 1.
Good luck!