(C) 在数组中查找一个元素并只打印一次它的位置

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

你好,我尝试使用数组在 C 中练习自己。 首先,我创建了一个二维数组并用一些元素对其进行了初始化,然后我创建了第二个一维数组,我想在其中存储元素的位置(更具体地说是行),但前提是存在于二维数组中。

我将向您展示我的代码以帮助您更好地理解。

代码

#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]); }}}}

输出

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

我如何修复代码以仅存储一次元素的位置(行)?我希望我的输出是:

Number 2 found in rows : 1

Number 2 found in rows : 3

Number 2 found in rows : 5

这是您的代码的更新版本,它实现了@Some programmer dudes 建议:

休息;此处的语句将导致遍历 j 的 for 循环停止其迭代。然后这将增加 i 并搜索下一行。这实现了你正在寻找的东西。

这里是休息时的额外学习: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;
            }
        }
    }
}

这是 运行 时的输出: