19-02-2008, 12:33 AM
|
#412 (permalink)
|
|
Commander in Chief
Join Date: Jul 2005
Posts: 6,658
|
Re: Post ur C/C++ Programs Here
Quote:
Originally Posted by mavihs
Code:
/* WAP to execute the following function:
-> Read an integer & an integer array & search for that integer in the intger array & return its position, incase the number is not there in the list, function should return -1.*/
int search(int siz, int ele, int arr[]);
void main()
{
clrscr();
int arr[25], siz, i, ele, j;
cout<<"Enter the number of elements:";
cin>>siz;
cout<<"Enter the array:";
for(i=0; i<siz; i++)
{
cin>>arr[i];
cout<<"\t";
}
cout<<"Enter the element to be searched";
cin>>ele;
k=search(siz, ele, arr);
if(j==-1)
cout<<"Element not found";
else
cout<<"The element found at"<<j<<"th position";
getch();
}
int search(int siz, int ele, int arr[])
{
int pos=-1;
for(int i=0; i<siz; i++)
{
if(ele==arr[i])
{
pos=i;
break;
}
else
pos=2;
}
if(pos==1)
{
return(i+1);
}
else
{
return(-1);
}
}
|
The entire thing in simple Python: (Thought it might help the bunch of shifters here)
Code:
n = int(raw_input("Enter the no of elements: "))
print "Enter the elements:"
a = [int(raw_input()) for x in range(0,n)]
c = int(raw_input("Enter a number to search: "))
print a.index(c) if c in a else -1
__________________
Harsh J
www.harshj.com
|
|
|