In: Computer Science
How to inhabit the int array num with random numbers using a function that you then invoke from the main method.
I already created a function that generates an array of 5 random integers.
/* int i;
int arrayName[5];
for(i= 0;i < 6; i++ ){
//type arrayName[arraysize];
arrayName[i] = rand()% 200;
printf("array[%d] = %d\n",i,arrayName[i]);
*/
// use rand() % some_number to generate a random
number
int num[5];
int main(int argc, char **argv)
{
// hint
// function invocation goes here
return 0;
}
Basically here you want to store the randomly generated numbers from the function into the int num array. So in order to do that, there should be a function return type and you should return the int array. In C, functions cant return arrays. But there are 3 ways in which we can return array. I am using static array to do that. You can also use dynamic allocated array or struct to do that. Let us see that in the following code.
#include <stdio.h>
#include<stdlib.h>
int* generate() //return type is pointer
{
int i;
static int arrayName[5]; //declare it as static
for(i= 0;i < 6; i++ ){
arrayName[i] = rand()% 200; //generate random integers and store it in the arrayName
//printf("array[%d] = %d\n",i,arrayName[i]);
}
return arrayName; ///return arrayName
}
int* num;
int main(int argc, char **argv)
{
int i;
num=generate();//invoke the function here. Now the values of arrayName will be stored in int array pointer
//optional. i used for loop here to check the array values
for(i= 0;i < 6; i++ ){
printf("array[%d] = %d\n",i,num[i]);//now print the values
}
//optional
return 0;
}
I am also attaching the output and code screenshot for your reference.
Output and code screenshot:
#Please don't forget to upvote if you find the solution
helpful. Feel free to ask doubts if any, in the comments section.
Thank you.