C Language Practice: Number Search - Binary Search

From Eric & Company
Jump to navigation Jump to search

Search for a Number - Binary Search

  • Step 1: Define a number binary search function
  • Step 2: Get all the arguments needed in main
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int findnum(int totalnum, int numcheck, int numlist[totalnum])
{
    int i, place = totalnum / 2;

    for (i = 0; i <= totalnum; i++)
    {
        if (numlist[place] == numcheck)
        {
            printf("The number %d is found at position: %d\n", numcheck, place + 1);
            return place + 1;
        }
        else if (numlist[place] < numcheck)
        {
            place = place + place / 2;
        }
        else
        {
            place = place / 2;
        }
    }
    
    printf("Number not found.\n");
    return 0;
}

int main(void)
{
    int totalnum;
    printf("How many numbers do you want to test: \n");
    scanf("%d", &totalnum);
    int numlist[totalnum];
    printf("Please input %d numbers: \n", totalnum);
    for (int i = 0; i < totalnum; i++)
    {
        scanf("%d", &numlist[i]);
    }
    int numcheck;
    printf("What number are you looking for?: \n");
    scanf("%d", &numcheck);

    findnum(totalnum, numcheck, numlist);

    return 0;
}