Loop Assignment 29 โ€” Iterative Binary Search Using a While Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Iterative (Non-Recursive) Binary Search Using a While Loop

๐Ÿ“‘ On this page:
  • How Binary Search Works
  • The Halving Algorithm
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
๐Ÿ“š In this program, you will learn:
  • Why binary search requires sorted input โ€” and what happens if you forget
  • How low, high, and mid divide-and-conquer in a single while loop
  • Why the loop is O(log n) and how 1,000,000 elements are searched in about 20 steps
  • How to avoid the classic (low + high) / 2 integer overflow bug
  • Why the loop condition low <= high matters โ€” and not low < high

How Binary Search Works

Binary search is the "guess the number" game. Someone thinks of a number between 1 and 100. You guess 50. They say "higher." You guess 75. "Lower." You guess 62. In three guesses, you've narrowed the range from 100 to about 12. Binary search works the same way: each iteration eliminates half the remaining search space.

The algorithm maintains three indices: low (the left edge of the search range), high (the right edge), and mid (the middle). Initially low = 0 and high = n - 1, covering the entire array. In each iteration, compute mid, compare arr[mid] to the target, and narrow the range:

  • If arr[mid] == target: found it โ€” return mid.
  • If arr[mid] < target: the target must be to the right, so set low = mid + 1.
  • If arr[mid] > target: the target must be to the left, so set high = mid - 1.

Repeat until either the target is found or low > high (which means the search range is empty โ€” the target isn't in the array). The key insight is that binary search only works on sorted arrays. The "arr[mid] < target means go right" inference relies on the array being ordered. On unsorted data, binary search gives wrong answers silently.

One subtlety in C: writing mid = (low + high) / 2 is the textbook formula, but it overflows for very large arrays. If low and high are both close to INT_MAX, their sum overflows to a negative number, and mid becomes garbage. The safe form is mid = low + (high - low) / 2, which computes the same value without overflow. This bug famously lived in Java's standard library for nine years before being fixed in 2006.

๐Ÿ’ก In one line: each iteration halves the search range by comparing arr[mid] to the target; after at most โŒˆlogโ‚‚ nโŒ‰ iterations, either the target is found or the range is empty.

Diagram showing binary search on a sorted array 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 searching for 40, with the search range shrinking from [0..9] to [0..4] to [3..4] to [3..3] as the mid index is compared

The Halving Algorithm

In pseudocode, iterative binary search is eight lines:

low = 0
high = n - 1
while low <= high:
    mid = low + (high - low) / 2
    if arr[mid] == key:
        return mid
    else if arr[mid] < key:
        low = mid + 1
    else:
        high = mid - 1
return -1
                                

The loop continues as long as low <= high. When low > high, the search range is empty โ€” every possible position has been checked, and the target isn't there. Returning -1 signals "not found." Compare this to linear search, which checks positions one by one and runs in O(n) time. Binary search runs in O(log n), which is exponentially faster for large arrays.

Array size n Linear search (worst case) Binary search (worst case) Speedup
1010 comparisons42.5ร—
100100714ร—
1,0001,00010100ร—
1,000,0001,000,0002050,000ร—
1,000,000,0001,000,000,0003033,000,000ร—

Each additional digit of array size costs about 3.3 more comparisons. That's why binary search is the standard way to search large sorted arrays in every database, every file system, and every binary tree implementation. It's one of the most important algorithms in computer science.

Complete C Program

Program: iterative binary search using a while loop

#include <stdio.h>

int main(void) {
    int n, key;

    printf("Enter the number of elements: ");
    if (scanf("%d", &n) != 1 || n <= 0) {
        printf("Invalid size.\n");
        return 1;
    }

    int arr[n];
    printf("Enter %d sorted integers (ascending):\n", n);
    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    printf("Enter the value to search: ");
    scanf("%d", &key);

    int low = 0, high = n - 1, mid, result = -1;

    while (low <= high) {
        mid = low + (high - low) / 2;   /* safe form */
        if (arr[mid] == key) {
            result = mid;
            break;
        } else if (arr[mid] < key) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    if (result == -1)
        printf("Element %d not found.\n", key);
    else
        printf("Element %d found at index %d (0-based).\n", key, result);

    return 0;
}
                                    

And here's a variant that sorts the array first with a simple bubble sort, so it works even if the user enters unsorted data. Useful for understanding the sorted-input requirement:

Variant with input sorting (educational)

#include <stdio.h>

int main(void) {
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);

    int arr[100];
    printf("Enter %d integers:\n", n);
    for (int i = 0; i < n; i++) scanf("%d", &arr[i]);

    /* Bubble sort โ€” ensures sorted input for binary search */
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                int t = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = t;
            }
        }
    }
    printf("Sorted array: ");
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");

    int key;
    printf("Enter the value to search: ");
    scanf("%d", &key);

    int low = 0, high = n - 1, result = -1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == key) { result = mid; break; }
        else if (arr[mid] < key) low = mid + 1;
        else high = mid - 1;
    }

    if (result == -1) printf("Element %d not found.\n", key);
    else printf("Element %d found at index %d.\n", key, result);
    return 0;
}
                                    

The first version is the one to submit for the assignment โ€” it assumes the user enters a sorted array, as the problem statement specifies. The second version is useful when you're learning or testing: it makes the sorted-array requirement explicit by sorting first and printing the sorted order. Note that the sort costs O(nยฒ) for bubble sort, which dwarfs the O(log n) search โ€” real applications sort once and then do many searches.

Program Output

Enter the number of elements: 8
Enter 8 sorted integers (ascending):
10 20 30 40 50 60 70 80
Enter the value to search: 40
Element 40 found at index 3 (0-based).
                                

Try a few more. Input a value that's not in the array, like 25, and you should get "not found". Try the first element (10, found at index 0) and the last (80, found at index 7). Try an empty array (n = 0) โ€” the program rejects it. Try a single-element array โ€” the loop runs once and either finds it or doesn't.

Enter the number of elements: 8
Enter 8 sorted integers (ascending):
10 20 30 40 50 60 70 80
Enter the value to search: 25
Element 25 not found.
                                

Step-by-Step Explanation

Let's walk through searching for 40 in [10, 20, 30, 40, 50, 60, 70, 80].

1. Setup

low = 0, high = 7 (n โˆ’ 1). The search range is the entire array. result = -1 to start; it becomes mid when the key is found.

2. Iteration 1

mid = 0 + (7 โˆ’ 0) / 2 = 3. arr[3] = 40. That's the key โ€” found at index 3. result = 3, break out of the loop. Print "found at index 3."

3. A harder example: searching for 70

Same array, key = 70.

  1. Iteration 1: low = 0, high = 7, mid = 3. arr[3] = 40 < 70, so low = 4.
  2. Iteration 2: low = 4, high = 7, mid = 4 + (7 โˆ’ 4)/2 = 5. arr[5] = 60 < 70, so low = 6.
  3. Iteration 3: low = 6, high = 7, mid = 6 + (7 โˆ’ 6)/2 = 6. arr[6] = 70. Found at index 6.

Three iterations to search an 8-element array โ€” exactly โŒˆlogโ‚‚(8)โŒ‰ + 1 = 4 upper bound, and we got lucky at 3. For an array of 1,000,000 elements, the worst case is 20 iterations. That's the exponential speedup of halving.

4. What happens when the key isn't found

Search for 25 in the same array. Key = 25.

  1. Iteration 1: low = 0, high = 7, mid = 3. arr[3] = 40 > 25, so high = 2.
  2. Iteration 2: low = 0, high = 2, mid = 1. arr[1] = 20 < 25, so low = 2.
  3. Iteration 3: low = 2, high = 2, mid = 2. arr[2] = 30 > 25, so high = 1.
  4. Now low = 2, high = 1. Condition low <= high is false โ€” loop exits.
  5. result is still โˆ’1, so print "not found."

Notice that in the final iteration, low and high crossed over. That crossover is the loop termination signal: the search range is empty, meaning there's no index left where the target could be.

5. Why low <= high and not low < high

When low == high, there's still one element in the range โ€” the one at index low. The loop body must run once more to check that element. If the loop condition were low < high, the loop would exit before checking the last candidate. That's a classic off-by-one bug. The correct condition is low <= high.

6. Why mid = low + (high โˆ’ low) / 2

For ordinary array sizes, mid = (low + high) / 2 works fine. The overflow bug only manifests when low + high exceeds INT_MAX (about 2.1 ร— 10โน). That requires an array with more than 2 billion elements โ€” but that's not impossible, and the bug is silent and ugly. low + (high โˆ’ low) / 2 computes the same value for all low <= high without overflow, because high โˆ’ low is non-negative and bounded by high, so the addition low + (high โˆ’ low) / 2 is always between low and high. It's the recommended form.

7. Why the loop is O(log n)

Each iteration halves the search range. Starting with size n, after k iterations the range is n / 2แต. The loop exits when the range becomes empty, i.e., when k โ‰ˆ logโ‚‚(n). So the loop runs at most โŒˆlogโ‚‚(n)โŒ‰ + 1 times. For n = 1,000,000, that's 20 iterations. For n = 10โน, that's 30 iterations. For n = 10ยนโธ (larger than any practical array), that's 60. That's why binary search is the standard search algorithm for large sorted datasets.

๐ŸŽฏ Remember this: sorted array required; low <= high not <; mid = low + (high โˆ’ low)/2 not (low + high)/2; return mid on hit, low = mid + 1 or high = mid โˆ’ 1 on miss; โˆ’1 when the loop exits. The whole thing is O(log n).

Frequently Asked Questions

1. What happens if I binary-search an unsorted array?

It gives wrong answers โ€” possibly finding the wrong element, possibly not finding elements that are present, possibly going into an infinite loop if the array is badly disordered. Binary search relies on the invariant that the target is in one specific half based on a single comparison, which is only true if the array is sorted. There's no error message, no crash โ€” just silently wrong results. Always sort first.

2. What's the difference between iterative and recursive binary search?

The algorithm is identical, but recursive uses O(log n) stack space for the call frames, while iterative uses O(1) space. Both are O(log n) time. Iterative is generally preferred in production because it avoids stack overflow on very large arrays and has less overhead per call. The assignment asks for iterative, which is also arguably easier to reason about.

3. Why does the loop condition use low <= high?

Because the search range is inclusive of both endpoints. When low == high, there's still one element to check. If the loop used low < high, it would exit before checking that element โ€” a classic off-by-one bug. You'd find the target in most cases but miss it when it happens to be the last unchecked element.

4. Why use low + (high โˆ’ low) / 2 instead of (low + high) / 2?

Integer overflow. If low and high are both close to INT_MAX, low + high overflows to a negative number, and mid becomes garbage. This requires arrays larger than about 2 billion elements, but the bug is real โ€” it lived in Java's standard library for nine years before being fixed. The safe form low + (high โˆ’ low) / 2 computes the same value without overflow, and it costs nothing extra.

5. Why is binary search O(log n) and not O(n)?

Because each iteration halves the search range. After k iterations, the range has size n / 2แต. The loop exits when the range is empty, i.e., when n / 2แต โ‰ˆ 1, so k โ‰ˆ logโ‚‚(n). That's the log factor. Linear search, in contrast, checks every element one by one and runs in n iterations. For n = 10โถ, binary search does 20 comparisons; linear search does 1,000,000 โ€” a 50,000ร— speedup.

6. Why use int arr[n] (a VLA) instead of a fixed-size array?

Variable-length arrays (VLAs) were added in C99 and allow an array sized at runtime, which is natural here since the user provides n. However, VLAs are optional in C11 and later standards โ€” some compilers (especially MSVC) don't support them. For maximum portability, use a fixed-size array with a compile-time maximum, or allocate dynamically with malloc. For this assignment, the VLA version is fine with GCC and Clang, which are the most common teaching compilers.

๐Ÿ’ก Tip: After this program, try the recursive version โ€” the algorithm is identical, but the while loop becomes a function call. Then try finding the first occurrence of a duplicate key (instead of any occurrence), which requires continuing the search after a hit rather than breaking. That variation is called "lower bound" binary search and appears frequently in coding interviews.

๐Ÿ“– Related Tutorials

  • 27. Generate First N Terms of the Tribonacci Sequence Using a While Loop
  • 28. Find the Largest Prime Factor Using a While Loop
  • 30. Check Amicable Numbers Using a For Loop
  • 1. GCD of Two Numbers Using a While Loop (Euclidean Algorithm)
  • 6. Count the Digits in an Integer Using a While Loop
  • While Loop
  • C FOR Loop
  • All 30 Loop Assignments

Previous Topic: -->> 28. Find the Largest Prime Factor Using a While Loop   ||   Next Topic: -->> 30. Check Amicable Numbers Using a For Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.