dimanche 21 février 2021

Generate random numbers with Array

I am learning C and i keep mixing up array and matrix. and I can't seem to understand where i am doing wrong with my code. I have made 2 different version of it and the only feedback i am getting is, I have mixed array with matrix.

was wondering if anyone could help me understand exactly where I went wrong, since I am not getting anywhere with my prof and his explanation about it. ( sorry in advanced) This is the first code, But both of them are really similar.

  #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main ()
    {
        int array[100];
        int max = 0, min = 1;
        int fro;
    
        fro=(int)time(NULL);
        srand(fro);
   
     for(int i = 0; i < 100; i++){
     array[i] = rand() % (400 + 1 - 100) + 100;
     if(array[i] <= min) {
     min = array[i];
     }
     if(array[i]  >= max)
     max = array[i];
     }
     
     printf("Array\n");
     for(int row = 0; row < 10; row++) {
     for(int col = 0; col < 10; col++) {
     printf(" %i ", array[row*10+col]);
     }
     printf("\n");
     }
return 0; 
     }

This is another version, but I got similar feedback as the first one. I am mixing up Array and matrix..

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


int main ()
{
    int tal[10][10];
    int array[100];
    int max = 0, min = 1;
    int fro;
    
    fro=(int)time(NULL);
    srand(fro);
// Version 3 of the array slump generation

    for(int row = 0; row < 10; row++) {
        //printf("Yttre loop row %i\n", row);
        
        for(int col = 0; col < 10; col++) { // row = 1, col = 0
            tal[row][col] = rand() % (400 + 1 - 100) + 100;
            // printf("tal[%i][%i] = %i\n", row, col, tal[row][col]);
            
            // Get max
            if(tal[row][col] >= max) {
                max = tal[row][col];
            }
            // Get min
            if (tal[row][col] <= min) {
                min = tal[row][col];
            }
            // printf("tal[%i][%i] = %i\n", row, col, tal[row][col]);
        }
    }
    
    // Printar ut hela matrisen i row-major order
    for(int row = 0; row < 10; row++){
        for(int col = 0; col < 10; col++){
            printf(" %i ", tal[row][col]);
        }
        printf("\n");
    }
    
    return 0;
}

I mean both of them works and I think I am using array :/ We haven't even gone trough matrix yet...




Aucun commentaire:

Enregistrer un commentaire