I want to generate an array of length 15 containing random numbers
between 0 and 10
- create an array of size
15
- use a for loop to populate the array using
rand()
function.
Note :
- use
rand()%9+1
to return a random number between 0
and 10
(0
,10
not included ) and don't send any arguments into rand()
function.
int array[15]; //array of size 15
for(int index=0; index<15; index++)
{
array[index] = (rand()%9)+1; //randomly generates a number between 0 and 10
}
prompt the user for a number in that range and print out the number of times that number appears
- most of what you want to achieve can be achieved by using
for
loop
here, we scan a number from user and store in number
and loop over array to find the number of times number
appears and each time it appears we increase the value of count
which is initially set to 0
.
int number,count=0;
printf("enter a number between 0 and 10 : ");
scanf("%d",&number); //scanning user prompted number
for(int index=0; index<15; index++)
{
if(array[index]==number) //checking if array element is equal to user's input
count++; //if yes increase the count
}
printf("the number appeared %d times\n",count); //printing number of times the number appeared
I then want to print out the array with an asterisk(*) indicating each instance of that number in that array
for(int index=0; index<15; index++)
{
if(array[index]==number)
printf("* ");
else
printf("%d ",array[index]);
}
So altogether your code would be :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int array[15];
//populating array with random elements between 0 and 10
for(int index=0; index<15; index++)
{
array[index] = (rand()%9)+1;
}
int number,count=0;
//scanning user prompted input
printf("enter a number between 0 and 10 : ");
scanf("%d",&number);
//printing number of times the user entered number appeared
for(int index=0; index<15; index++)
{
if(array[index]==number)
count++;
}
printf("the number appeared %d times\n",count);
// printing the array with * in place of user entered input
for(int index=0; index<15; index++)
{
if(array[index]==number)
printf("* ");
else
printf("%d ",array[index]);
}
}