Hello I am trying to write a program in C. For the program I am trying to print an array of 10 random numbers (using function rand();) while set the srand(); seed to 5 (1,2,3,4,5). Then, I need to sort the 10 random numbers in the array into decreasing order and print the output. I am getting a incorrect output of random numbers and descending order and I do not know why. Can someone please let me know why or modify my code to print an array of 10 random numbers (using function rand();) while set the srand(); seed to 5 (1,2,3,4,5). Then, I need to sort the 10 random numbers in the array into decreasing order and print the output?
The output that I am getting when I compile and run the code is:
Initial random numbers: -2145088480
Descending: 966378722
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[10]; //declare an array 'arr' of size 10 to hold integers
int i,n,j,tmp; //declare the variable i to increment
srand(5); //Seed the random number generator to 5, as specified 'set
//the seed to be 12345'
for (i = 0; i < 10; i++)
{
arr[i] = rand(); //Use the function rand()
}
printf("Initial random numbers : %d ",arr[i]);
for (int i = 0; i < n; i++) //Loop for descending //ordering
{
for (int j = 0; j < n; j++) //Loop for comparing other values
{
if (arr[j] < arr[i]) //Comparing other array //elements
{
int tmp = arr[i]; //Using temporary variable //for storing last value
arr[i] = arr[j]; //replacing value
arr[j] = tmp; //storing last value
}
}
}
printf("\n\nDescending : "); //Printing message
for (int i = 0; i < n; i++) //Loop for printing array //data after sorting
{
printf(" %d ", arr[i]); //Printing data
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
constint N = 10 ;
int arr[N]; //declare an array 'arr' of size 10 to hold integers
srand(12345); // 'set the seed to be 12345'
puts( "Initial random numbers: " ) ;
int i, j ;
for( i = 0; i < N ; ++i )
{
arr[i] = rand(); //Use the function rand()
printf( "%d ", arr[i] );
}
puts("") ;
// sort the 10 random numbers in the array in decreasing order
for( i = 0; i < N ; ++i )
{
for( j = i+1 ; j < N ; ++j ) // for each position after i
{
if( arr[j] > arr[i] ) // in descending order
{
constint tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
puts( "\nsorted in descending order: " ) ;
for( i = 0; i < N ; ++i ) printf( "%d ", arr[i] );
puts("") ;
}
At line 19, you weren't printing the contents of the array. You were printing the value of arr[10]. This is one element past the end of the array, so it's just printing whatever happened to be in memory, which is why you're getting a garbage value.