Skip to content

Task 1: Student Lookup

Difficulty: Simple

Problem to Solve

A university keeps related information about each student: an ID, a name, and a major. Instead of storing these values in separate arrays, use a structure to keep each student's information together.

Create a file named student_lookup.c inside a folder named student-lookup. The program must search a small student directory by ID and print the matching record.

Use this data:

ID Name Major
101 Amina Computer Science
102 Farid Mathematics
103 Madina Economics
104 Rustam Design
105 Zebo Computer Science

Requirements

  • Define a structure named Student containing:
    • an integer named id;
    • a character array named name; and
    • a character array named major.
  • Create and initialize an array containing the five records shown above.
  • Prompt with Student ID: and read an integer ID.
  • Search the array from beginning to end.
  • If the ID exists, print the student's name and major.
  • If the ID does not exist, print Student not found..
  • Keep all program logic inside main; do not create additional functions.
  • Use only standard C libraries.

Expected Output

When the student exists:

$ ./student_lookup
Student ID: 103
Name: Madina
Major: Economics

When the student does not exist:

$ ./student_lookup
Student ID: 999
Student not found.

Starter Code

#include <stdio.h>

typedef struct
{
    int id;
    char name[50];
    char major[50];
} Student;

int main(void)
{
    Student students[] = {
        {101, "Amina", "Computer Science"},
        {102, "Farid", "Mathematics"},
        {103, "Madina", "Economics"},
        {104, "Rustam", "Design"},
        {105, "Zebo", "Computer Science"}
    };

    // Calculate the number of students.

    // Read the ID to search for.

    // Search for a matching student.

    // Print the result.
}
Calculate the array length

Calculate the number of records from the array itself:

int student_count = sizeof students / sizeof students[0];

This avoids writing the number 5 directly into the search loop.

Search hint

Create an integer named found_index and initialize it to -1. Visit each student with a for loop. When an ID matches, save its index and stop the loop with break.

After the loop, an index of -1 means that no match was found. Any other value identifies the matching element of the students array.

Compile and Test

From the student-lookup folder, run:

cc student_lookup.c -o student_lookup
./student_lookup

If your system provides gcc instead of cc, run gcc student_lookup.c -o student_lookup.

Test all five valid IDs as well as 0, 100, and 999.

Continue with Task 2: Sorted Student Directory.