problem no 17: Linear search.

 QUESTION:

Given an array Arr of N elements and a integer K. Your task is to return the position of first occurence of K in the given array.
Note: Position of first element is considered as 1.

Example 1:

Input:
N = 5, K = 16
Arr[] = {9, 7, 2, 16, 4}
Output: 4
Explanation: K = 16 is found in the
given array at position 4.

Example 2:

Input:
N = 7, K = 98
Arr[] = {1, 22, 57, 47, 34, 18, 66}
Output: -1
Explanation: K = 98 isn't found in
the given array.

 

ANSWER:

int search(int arr[], int n, int k) {
        int found=0;
        for(int i=0;i<n;i++)
        {
            if(arr[i]==k)
            {
                return i+1;
                found=1;
            }
        }
        if(found==0)
        {
            return -1;
        }
    }

Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.