gpt4 book ai didi

c - 查找数组中的元素

转载 作者:行者123 更新时间:2023-11-30 15:52:53 25 4
gpt4 key购买 nike

在这段代码中,如果我必须找到一个元素“7”,它指向 array=2 的位置,但如何获得多个位置,如果数组有 [4,7,7,8,9] 那么答案应该将位置指向 array=1 & array=2..

#include<stdio.h>


int main()
{
int i;
int a[5]={4,5,7,8,9};
int ele,temp=0,pos=0;
printf("Enter the element to be search\n");
scanf("%d",&ele);


// searching for the element

for (i=0; i<5; i++)
{
a[i]=a[i];
if (a[i]==ele)
{
temp=1;
pos=i;
}


}

if (temp==1)
printf("Element found %d , position==%d,",ele,pos);
else
printf("Element not found\n");
}

最佳答案

试试这个..

#include<stdio.h>


int main()
{
int i;
int a[5]={4,5,7,8,9};
int found_indices[5]; // array used to store indices of found entries..
int count = 0; //n entries found;
int ele;
printf("Enter the element to be search\n");
scanf("%d",&ele);


// searching for the element

for (i=0; i<5; i++)
{
//a[i]=a[i];
if (a[i]==ele)
{
found_indices[count ++] = i; // storing the index of found entry
}
}

if (count!=0) {
for (i=0; i<count; i++)
printf("Element found %d , position==%d,", ele, found_indices[i]);
}
else
printf("Element not found\n");
}

关于c - 查找数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14028955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com