Home > database >  Count how many times are numbers in 2d array
Count how many times are numbers in 2d array

Time:11-14

Hot to count how many times are numbers in 2d array in C.

int main(){   
    int counter = 0;
    int one = 0;
    int two = 0;
    int three = 0;
    int five = 0;
    int six = 0;

    char array[3][5] = {
        {'1', '3', '3', '5', '1'},
        {'2', '1', '5', '6', '2'},
        {'6', '2', '5', '5', '2'}
    };

    for(int j = 0; j < 3; j  ){        
        for(int i = 0; i < 5; i  ){   
             if(array[j][i] == array[j][i]){
                 counter  ;
             }
        }
    }

}

I need to print how many times are every number in array. For example like this:

number one is 3 times in array

number two is 4times in array

...

CodePudding user response:

You can do this in multiple ways, a simple way, consistent with what I believe is your current level of programming, is to have a digit counter function and call it for each digit you want to find in the array:

int digit_count(int digit_to_find, int array_element){
    return digit_to_find == array_element;
}

And the loop:

for(int i = 0; i < 3; i  ){              
    for(int j = 0; j < 5; j  ){    
        one  = digit_count('1', array[i][j]);
        two  = digit_count('2', array[i][j]);
        three  = digit_count('3', array[i][j]);
        //etc
    }
}

Note that I switched i and j, usually i represents the rows and j the columns.

I trust you can print the values on your own.

Live demo

CodePudding user response:

#include<stdio.h>
int main(){   
    int i;
    int a[6]={0}; // initialize array with zero values
    char array[3][5] = {
        {'1', '3', '3', '5', '1'},
        {'2', '1', '5', '6', '2'},
        {'6', '2', '5', '5', '2'}
    };
    for(int i = 0; i < 3; i  ){        
        for(int j = 0; j < 5; j  ){   
                 if(array[i][j]=='1') a[0]  ;
                 if(array[i][j]=='2') a[1]  ;
                 if(array[i][j]=='3') a[2]  ;
                 if(array[i][j]=='4') a[3]  ;
                 if(array[i][j]=='5') a[4]  ;
                 if(array[i][j]=='6') a[5]  ;
        }
    }
    for(i=0;i<6;i  ){
        printf("the count of %d is %d\n",i 1,a[i]);
    }
}
/* output : 
the count of 1 is 3
the count of 2 is 4
the count of 3 is 2
the count of 4 is 0
the count of 5 is 4
the count of 6 is 2
*/
  • Related