Meee
Meee

Reputation: 9

Sum of even numbers in 2D array

The code won't print the sum of even numbers. Here's my code

#include <stdio.h> 

int main() {     
    int row=2,col=5;
    int array[row][col];         
    int a,b; int sum=0;  
    
    printf("Enter the elements: \n"); 
    
    for(a=0;a<row;a++)          
        for(b=0;b<col;b++)          
            scanf("%d",&array[a][b]);   
    
    printf("\nThe elements are: \n ");
    
    for(a=0;a<row;a++) { 
        for(b=0;b<col;b++) {         
            printf("%d\t",array[a][b]); 
        }         
        printf("\n"); 
    }   
    
    for(a=0;a<row;a++) {         
        for(b=0;b<col;b++) {              
            if(array[row][col]%2==0){                    
                sum=sum+array[row][col];   
            }
        }
    }
    
    printf("\nequal even numbers: %d",sum);         
    return 0; 
}

Upvotes: 0

Views: 2446

Answers (2)

Sagre
Sagre

Reputation: 482

The problem lies in at the place, where you check for even and uneven numbers.

    for(a=0;a<row;a++) { 

    for(b=0;b<col;b++) {      

        if(array[row][col]%2==0){   

You are trying to iterate over all elements of the array, however in the if condition you are always accessing memory out-of-bounds of the array (max indexes are [row-1] and [col-1]. Replace [row][col] with [a][b]

Upvotes: 1

MarkSouls
MarkSouls

Reputation: 999

if (array[row][col] % 2 == 0) {
    sum = sum + array[row][col];

You have to get array[a][b] to calculate modulo, not array[row][col].

if (array[a][b] % 2 == 0) {
    sum = sum + array[a][b];

Upvotes: 3

Related Questions