dimanche 3 novembre 2019

Trying to write a program to fill an array with random numbers in C

So my issue is that I am getting segmentation fault (core dumped) each time I try, I have yet to clean up my code, but I am stumped. I must enter the values in with the compiler e.g "./filename 0 100" whereby 0 is min and 100 is max. It must then fill the array of 10 elements with random numbers (0-100). I am so close, just can't fathom the main function.

Also, how can I print the array {0,1,2,3} in format "[0,1,2,3]" including the commas, without it looking like "[0,1,2,3,]"

Thanks!!

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

int getRandom(int min, int max);  void fillArray(int data[], int size, int min, int max);  void printArray(int data[], int size);


int main(int argc, char *argv[]) {
     int a;   int b;






  if (argc>=3){
    a = atoi(argv[1]);
    b = atoi(argv[2]);
    int arr[10];
    printf("\t An array with random values from 0 to 100 \n");
    fillArray(arr,10 ,a, b);
    printArray(arr, 10);


  }   else{
    printf("Incorrect number of arguments - please call with assignment min max\n");

      }
    return 0; }

int getRandom(int min, int max) {   int result = 0;   int low = 0;   int high = 0;

    if(min<max)     {   low = min;  high = max+1;   }   else{   low = max + 1;  high = min;     }

result = (rand() % (high-low)) + low; return result;

}


void fillArray(int data[], int size, int min, int max){   int i;   for(i=min ; i < max+1; i++){
    data[i] = getRandom(min,max);   }

}    void printArray(int data[], int size){   int i;   printf("[");   for(i=0; i<size; i++){
    printf("%d,", data[i]);   }   printf("]");

}



Aucun commentaire:

Enregistrer un commentaire