簡體   English   中英

(C) 在數組中找到一個元素,只打印一次它的 position

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

您好,我嘗試使用 arrays 在 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]); }}}}

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

我如何修復代碼以僅存儲一次元素的位置(行)? 我希望我的 output 是:

Number 2 found in rows: 1

Number 2 found in rows: 3

Number 2 found in rows: 5

這是實現@Some程序員帥哥建議的代碼的更新版本:

休息; 此處的語句將導致遍歷 j 的 for 循環停止其迭代。 然后這將增加 i 並搜索下一行。 這實現了您正在尋找的東西。

以下是關於 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;
            }
        }
    }
}

這是運行時的 output:

輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM