Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.1 kB
42
Indexable
Never
#include <stdio.h>

/*
    Input: A sorted array in increasing order and a target element. Return the index of the target element
    Case1: The target elt is found 
    Case2: Target elt is not in the array. So return the index where it is appropriate
    Case3: The given target elt is present more than once, return -1

*/
int fndcoin(int a[], int n, int target) {
    for(int i=0;i<n;i++) {
        
        //if the target is found return index
        if(a[i] == target && a[i+1] != target) {
            return i;
           
        }
        //if the array has target value more than once
        else if(a[i] == target && a[i+1] == target) {
            return -1;
        }

        //if target is not found return index where it should be inserted
        else if(target > a[i] && target < a[i+1]) {
            return i+1;
            
        }
    }
}

int main() {
    int n;
    scanf("%d", &n);
    int a[n];
    for(int i=0;i<n;i++) {
        scanf("%d", &a[i]);
    }
    int target;
    scanf("%d", &target);
    int result = fndcoin(a, n, target);
    printf("Index : %d\n", result);
}
Leave a Comment