C bootcamp · Lab 32

Linear search

mediumArrays12 minLesson: C Arrays

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

The first number is n, then n integers, then a target.

Print the 0-based index of the first time the target appears, or -1 if it is missing.

Input. n, then n integers, then target — whitespace-separated.

Output. One integer: the index, or -1.

Constraints

  • 1 ≤ n ≤ 100

Examples

Example 1
Input
5
3 1 8 2 4
8
Output
2
Example 2
Input
4
1 2 3 4
9
Output
-1
Hint
  1. Walk i from 0 to n-1. On a hit, print i and return.
  2. If the loop finishes, print -1.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

int main(void) {
  int n, target;
  int nums[100];
  if (scanf("%d", &n) != 1 || n < 1 || n > 100) return 1;
  for (int i = 0; i < n; i++) scanf("%d", &nums[i]);
  scanf("%d", &target);
  int found = -1;
  for (int i = 0; i < n; i++) {
    if (nums[i] == target) { found = i; break; }
  }
  printf("%d\n", found);
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.