C PROGRAMMING PROGRAM • ARRAYS, SEARCHING & SORTING
Search an Array Using Linear Search
Learn how to search an array using linear search using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
6 8 2 9 4 7 1 4
Sample output
Found at position 4
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int size, values[100], target, position = -1;
scanf("%d", &size);
if (size < 1 || size > 100) return 1;
for (int index = 0; index < size; index++) scanf("%d", &values[index]);
scanf("%d", &target);
for (int index = 0; index < size; index++) {
if (values[index] == target) { position = index; break; }
}
if (position >= 0) printf("Found at position %d\n", position + 1);
else printf("Not found\n");
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Found at position 4
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Compare the target with elements from left to right and stop at the first match.
- Display the computed result.
Compare the target with elements from left to right and stop at the first match.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
