Reputation: 5
In this code, If I have to find an element '7', it points to the position of array=2, but how to get the multiple positions, if array has [4,7,7,8,9] then the answer should point the position as 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");
}
Upvotes: 0
Views: 99
Reputation: 1601
Try this..
#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");
}
Upvotes: 1
Reputation: 431
your pos variable is just an integer, not an array, so it will store only one value. Instead, make it an array and then store the value of each founded result into the pos array.
Upvotes: 0