Home > front end >  Create a square matrix with random integer value generate
Create a square matrix with random integer value generate

Time:02-26

I am trying to create a random square matrix (based on the user's input) with elements that are generated randomly. Here is my code.

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

int generate_random (int lower, int upper);

int main ()
{
    int upper,lower,i,j,M,N,matrix[M][N];
    printf("Enter the number of rows and columns: \n");
    scanf("%d %d",&M,&N);
    printf("Enter the range of random numbers:\nUpper: ");
    scanf("%d",&upper);
    printf("Lower: ");
    scanf("%d",&lower);
    srand(time(NULL));
    for (i=0;i<M;i  )
    {
        for (j=0;j<N;j  )
        {
            matrix[i][j] = generate_random(lower,upper);
            printf("%d ",matrix[i][j]);
        }
        printf("\n");
    }
}

int generate_random (int lower, int upper)
{
    int rand_num;
    rand_num = (rand()%(upper-lower 1)) 1;
    return rand_num;
}

However, I get a very strange output and quite don't understand why? enter image description here

enter image description here

Please help me with this. I'm new to C and really confused right now.

CodePudding user response:

Problem is here in declaration part

int upper,lower,i,j,M,N,matrix[M][N];

M and N is not defined will give segmentation fault. Input the value for M & N first then create the matrix.

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

int generate_random (int lower, int upper);

int main (){
    int M,N;
    printf("Enter the number of rows and columns: \n");
    scanf("%d %d",&M,&N);
    int upper,lower,i,j,matrix[M][N];
    printf("Enter the range of random numbers:\nUpper: ");
    scanf("%d",&upper);
    printf("Lower: ");
    scanf("%d",&lower);
    srand(time(NULL));
    for (i=0;i<M;i  )
    {
        for (j=0;j<N;j  )
        {
            matrix[i][j] = generate_random(lower,upper);
            printf("%d ",matrix[i][j]);
        }
        printf("\n");
    }
}

int generate_random (int lower, int upper)
{
    int rand_num;
    rand_num = (rand()%(upper-lower 1)) 1;
    return rand_num;
}

Output:

$ gcc randgen.c && ./a.out
Enter the number of rows and columns: 
5
5
Enter the range of random numbers:
Upper: 10
Lower: 3
8 8 5 7 2 
6 7 5 4 1 
5 1 7 1 7 
3 6 4 7 5 
3 1 8 6 4 

CodePudding user response:

How to generate a random integer in a desired range (caveats apply) using rand():

int random( int min, int max )
{
  int N = max - min   1;             // N ⟵ magnitude of output range where 1 < N ≤ (RAND_MAX 1)
  int K = ((RAND_MAX   1) / N) * N;  // K ⟵ k × N where k = maximum integer such that kN ≤ (RAND_MAX 1)
  int n;                             // 
  do n = rand(); while (n >= K);     // (discard unwanted pigeons)
  return (n % N)   min;              // n ⟶ output range
}
  •  Tags:  
  • c
  • Related