Binary Search (Iterative)



	#include <stdio.h>

	// Function Prototypes
	int binSearch(int arr[], int target, int len);

	// Returns 1 if target is in array, otherwise returns 0
	int binSearch(int arr[], int target, int len) {
		int left = 0;
		int right = len - 1;
		int mid;
		while (left <= right) {
			mid = (left + right) / 2;
			if (arr[mid] == target)
				return 1;
			if (target < arr[mid])
				right = mid - 1;
			else
				left = mid + 1;
		}
		return 0;
	}

	int main(void) {
		int len = 20;
		int arr[] = {3,  6,  7,  11, 25, 32,  33,  33,  46,  52,
								 79, 83, 88, 91, 94, 101, 107, 112, 122, 148};
		int choice = 0;
		while (choice >= 0) {
			printf("Enter positive integer to see if it exists in the array\n(Enter "
						 "negative value to exit)\n:");
			scanf("%d", &choice);
			if (choice < 0)
				break;
			printf("%d is %sin the array.\n\n", choice,
						 binSearch(arr, choice, len) ? "" : "NOT ");
		}
		return 0;
	}
						
						

Academic Notice: The code shown here is provided solely as a learning reference. Copying and pasting is intentionally disabled to encourage independent practice. Students should implement solutions on their own to demonstrate understanding. This material is not intended for direct submission in assignments.

Additionally: This code was written by a former CS1 student and may not reflect your professor’s intended solution or instructional approach. For coursework, students are expected to follow examples, conventions, and requirements presented in class and in professor-assigned materials.