user3462414
user3462414

Reputation: 7

Finding the total number of a specific element in a 2D array

Lets say you have a 5 x 5 array and there are random integers in that array. How would you find the how many 2's there are in the first column? I tried something like this and I got an answer like 222. How can I modify the code for it to just say: there are three 2's in the first coloumn

for (i = 0; i<5; ++i)
{
    for (j = 0; j<1; ++j)
    {
        if (matrix[i][0]==2)
            printf("%d", matrix[i][j]);

    }
}

Upvotes: 0

Views: 32

Answers (1)

shree.pat18
shree.pat18

Reputation: 21757

Add a counter variable to keep track of the count. Increment each time you find a 2, then print it out in the end. Also, if you are only looking at a specific column, you don't need 2 loops. You can just do this:

int counter = 0;

for (i = 0; i<5; ++i)
 {
   if (matrix[i][0]==2)
        counter++;
  }
printf("%d", counter);

Upvotes: 1

Related Questions