Home > Mobile >  How to fill a 2D array with a result from division of 2 random numbers in 2 different ranges but the
How to fill a 2D array with a result from division of 2 random numbers in 2 different ranges but the

Time:01-31

I need to fill a 2D array with result from division of 2 random numbers in 2 different ranges but the result can't be in range (-2,2). Ranges of two random numbers are (-15,5) and (-2,2). When I Compile & Run the program it it does not work properly. It outputs just a few lines or nothing and finishes itself. I am using Dev-C .

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

int main() {

int array[11][11];
int num1 = 0;
int num2 = 0;
int res = 0;
srand(time(NULL));  
for (int i = 0;i < 11;i  ) {
    for (int j = 0;j < 11;j  ) {
        do {
            num1 = (rand() % (5   15   1)) - 15;
            num2 = (rand() % (2   2   1)) - 2;
            res = num1 / num2;
            printf("%d/%d=%d\t", num1, num2, res);

        } while (res >= -2 && res <= 2);
        array[i][j] = res;
        printf("\narray[%d][%d]=%d",i,j, array[i][j]);
        printf("\n");
    }
  }
}

Ouput:

-15/-1=15
array[0][0]=15
-2/2=-1 5/-2=-2 1/1=1   -13/1=-13
array[0][1]=-13
-6/-2=3
array[0][2]=3
-12/1=-12
array[0][3]=-12

--------------------------------
Process exited after 4.478 seconds with return value 3221225620
Press any key to continue . . .

CodePudding user response:

You are almost there. You need to avoid dividing with 0. Let's change your do-while to the following:

        do {
            num1 = (rand() % (5   15   1)) - 15;
            num2 = (rand() % (2   2   1)) - 2;
            res = (num2 != 0) ? (num1 / num2) : 0; //we default to 0 if the division was with 0
            printf("%d/%d=%d\t", num1, num2, res);

        } while (res >= -2 && res <= 2);
  • Related