How to write a function that search a value in int array in C

2 Answers

0 votes
#include <stdio.h> 
 
int arraySearch(int arr[], int findVal, int size);
 
int main(void)
{
    int numbers[] = { 10, 40, 60, 30, 20, 50, 80, 70, 90 };
  
    if (arraySearch(numbers, 60, sizeof(numbers)/sizeof(numbers[0])) != -1)
        printf("Found\n");
    else
        printf("NOT found\n");
        
    if (arraySearch(numbers, 798, sizeof(numbers)/sizeof(numbers[0])) != -1)
        printf("Found\n");
    else
        printf("NOT found\n");
 
    
    return 0;
}
int arraySearch(int arr[], int findVal, int size)
{
    int i;
    
    for (i = 0; i < size; i++)
        if (arr[i] == findVal) return i;

    return -1;
}

/*
run:
   
Found
NOT found

*/


answered Mar 1, 2015 by avibootz
0 votes
#include <stdio.h> 
 
#define A_SIZE(array) (sizeof(array)/sizeof((array)[0])) 
 
int arraySearch(int arr[], int findVal, int size);
 
int main(void)
{
    int numbers[] = { 10, 40, 60, 30, 20, 50, 80, 70, 90 };
  
    if (arraySearch(numbers, 60, A_SIZE(numbers)) != -1)
        printf("Found\n");
    else
        printf("NOT found\n");
        
    if (arraySearch(numbers, 798, A_SIZE(numbers)) != -1)
        printf("Found\n");
    else
        printf("NOT found\n");
 
    
    return 0;
}
int arraySearch(int arr[], int findVal, int size)
{
    int i;
    
    for (i = 0; i < size; i++)
        if (arr[i] == findVal) return i;

    return -1;
}

/*
run:
   
Found
NOT found

*/


answered Mar 1, 2015 by avibootz
...