码迷,mamicode.com
首页 > 其他好文 > 详细

Search an Element in an array

时间:2017-10-18 21:41:02      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:ios   log   xpl   contains   实现   cin   main   name   traints   

Given an integer array and an element x, find if element is present in array or not. If element is present, then print index of its first occurrence. Else print -1.

Input:

First line contains an integer, the number of test cases ‘T‘ Each test case should contain an integer, size of array ‘N‘ in the first line. In the second line Input the integer elements of the array in a single line separated by space. Element X should be inputted in the third line after entering the elements of array.

Output:

print the output in a separate line returning the index of the element X.If element not present then print -1.

Constraints:

1 <= T <= 100

1 <= N <= 100

1 <= Arr[i] <= 100

Example:

Input:
1
4
1 2 3 4
3

Output:
2

Explanation:
There is one test case with array as {1, 2, 3 4} and element to be searched as 3.  Since 3 is present at index 2, output is 2

我的代码实现:

#include <iostream>

using namespace std;

int main()
{
    int T;
    cin>>T;
    while(T--){
        int N,j,X,index=-1;
        cin>>N;
        int *Arr=new int[N];
        for(j=0;j<N;j++)
        {
            cin>>Arr[j];
        }
        cin>>X;
        for(j=0;j<N;j++)
        {
            if(Arr[j]==X)
            {
                index=j;
                break;
            }
        }
        cout<<index<<endl;
    }
    return 0;
}

  

Search an Element in an array

标签:ios   log   xpl   contains   实现   cin   main   name   traints   

原文地址:http://www.cnblogs.com/wongyi/p/7688842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!