【问题标题】:(C) Find an element in array and print its position only one time(C) 在数组中找到一个元素并只打印一次它的位置
【发布时间】:2020-07-22 12:43:08
【问题描述】:

您好,我尝试使用数组练习 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

【问题讨论】:

  • 也许您想了解break 语句?
  • 是的,我忘记了!谢谢!

标签: c arrays store


【解决方案1】:

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

休息;此处的语句将导致遍历 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;
            }
        }
    }
}

这是运行时的输出:

【讨论】:

  • 是的,你是对的,我忘了使用 break 语句!!!非常感谢
  • @vapan 随意将答案标记为已解决,并为评论者提供有用的回复。
猜你喜欢
  • 2021-05-02
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多