((C)在数组中找到一个元素并仅打印其位置一次

问题描述 投票:0回答:1

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

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

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

输出

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

c arrays store
1个回答
0
投票

这里是实现@Some程序员帅哥建议的代码的更新版本:

此处的语句将导致for循环迭代j停止其迭代。然后,这将使i递增并搜索下一行。这样就可以实现您想要的。

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

这是运行时的输出:

Output

© www.soinside.com 2019 - 2024. All rights reserved.