Search code examples
carraysstore

(C) Find an element in array and print its position only one time


Hello i try to practice myself in C using arrays. Firstly i create an 2D array and i initialize it with some elements, then i create a second 1D array in which i want to STORE the position(more specifically the row) of an element but only if exists in the 2d array.

I will show you my code to help you understand better.

CODE

#include<stdio.h>

 #define N 11

int main(){

/* 2d array */  

int arr[5][3] = {
    {2, 1, 2},
    {15, 15, 11},
    {10, 2 , 2},
    {9, 9 , 10},
    {3, 2,  3}
    };

int elmFound[N];  /* 1d array in which i want to store the position of an element */ 

int i ,j;

int x = 2; /* The element i want to search in 2d array if exists*/ 

for (i = 0 ; i< 5; i++){

for(j = 0; j<3; j++){

if(arr[i][j] == x){

elmFound[i] = i+1;  

printf("Number %d found in rows : %d \n" , x , elmFound[i]); }}}}

OUTPUT

Number 2 found in rows : 1

Number 2 found in rows : 1

Number 2 found in rows : 3

Number 2 found in rows : 3

Number 2 found in rows : 5

How i can fix the code to store the position(row) of an element only one time? I want my output to be:

Number 2 found in rows : 1

Number 2 found in rows : 3

Number 2 found in rows : 5


Solution

  • Here is an updated version of your code that implements @Some programmer dudes suggestion:

    The break; statement here will cause the for loop iterating through j to cease its iteration. This will then increment i and search the next row. This achieves what you are looking for.

    Here is additional learning on break : Break Statement Tutorial

    #include<stdio.h>
    
    #define N 11
    
    int main()
    {
    
        /* 2d array */  
        int arr[5][3] = 
        {
            {2,  1,  2},
            {15, 15, 11},
            {10, 2 , 2},
            {9,  9 , 10},
            {3,  2,  3}
        };
    
        int elmFound[N];  /* 1d array in which i want to store the position of an element */ 
        int i ,j;
        int x = 2; /* The element i want to search in 2d array if exists*/ 
    
        for (i = 0 ; i< 5; i++)
        {
            for(j = 0; j<3; j++)
            {
                if(arr[i][j] == x)
                {
                    elmFound[i] = i+1;  
                    printf("Number %d found in rows : %d \n" , x , elmFound[i]); 
                    break;
                }
            }
        }
    }
    

    Here is the output when ran:

    Output