2012-12-25 108 views
0

在此代码中,如果必须找到元素'7',它指向array = 2的位置, 但是如何获取多个位置,如果数组有[4, 7,7,8,9],则答案应指向的位置作为阵列= 1个&阵列= 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"); 
} 
+0

你可以把一些'printf'环内(即体内的第一个'if') –

回答

1

试试这个..

#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"); 
} 
+0

谢谢,这就是我期待的.. – Reshmy

+0

如果这是你的答案,那么将其标记为正确答案.. :) –

0

您的POS变量只是一个整数,而不是一个数组,所以它将存储只有一个值。相反,将它作为一个数组,然后将每个创建结果的值存储到pos数组中。

+0

谢谢你,你可以请更详细地说明在如何收集结果值。 – Reshmy