Sunday, August 2, 2009

How do i find the index of particular element in an array without using loop in c/c++?

You need to look for each element manualy or you have to use recursive function.


Manually as follows


i=0;


if(a[i]==5)


cout%26lt;%26lt;i;


else


i++;


if(a[i]==5)


cout%26lt;%26lt;i;


i++;





and so on


Otherwise you can see example of recursive function at my blog


http://codesbyshariq.blogspot.com

How do i find the index of particular element in an array without using loop in c/c++?
void main()


{


int num[5]={5,4,3,2,1};


int n,i;


cout%26lt;%26lt;"Enter the number whose index is to be found:"


cin%26gt;%26gt;n;


if(num[i]==n)


cout%26lt;%26lt;"The index is:"%26lt;%26lt;i;


else


cout%26lt;%26lt;"Number not in array!"





getch();


}
Reply:if condition..


thats looping right? LOL
Reply:If the size of the array is small, then you can use this type of checking. Pseudo C code.


if a[0] == elem then index = 0


else if a[1] == elem then index = 1


else if a[2] == elem then index = 2


else if a[3] == elem then index = 3


else if a[4] == elem then index = 4


else if a[5] == elem then index = 5


else if a[6] == elem then index = 6


else if a[7] == elem then index = 7


else if a[8] == elem then index = 8


else if a[9] == elem then index = 9


else output "element not found"


For larger arrays, you need a loop to detect when you found the element and store the index of the found element.


Hope this answers your question.


No comments:

Post a Comment