0
0
Cprogramming~20 mins

Return inside loops in C - Mini Project: Build & Apply

Choose your learning style9 modes available
Return inside loops
📖 Scenario: Imagine you are checking a list of numbers to find the first even number. Once you find it, you want to stop checking and return that number immediately.
🎯 Goal: You will write a function that looks through an array of numbers and returns the first even number it finds using a return statement inside a loop.
📋 What You'll Learn
Create an integer array called numbers with the values 3, 7, 10, 15, 20
Create an integer variable called size and set it to 5
Write a function called find_first_even that takes the array and its size as parameters
Inside the function, use a for loop with variable i to check each number
Return the first even number found inside the loop using return
If no even number is found, return -1
In main, call find_first_even with numbers and size
Print the returned value
💡 Why This Matters
🌍 Real World
Finding the first item that meets a condition quickly is common in many programs, like searching for the first available seat or the first error in a log.
💼 Career
Understanding how to return early from loops helps write efficient code and is a common pattern in software development.
Progress0 / 4 steps
1
Create the array and size variable
Create an integer array called numbers with the values 3, 7, 10, 15, 20. Also create an integer variable called size and set it to 5.
C
Need a hint?

Use int numbers[] = {3, 7, 10, 15, 20}; to create the array and int size = 5; for the size.

2
Write the function header
Write a function called find_first_even that takes an integer array called arr and an integer n as parameters and returns an integer.
C
Need a hint?

Use int find_first_even(int arr[], int n) to start the function.

3
Implement the loop and return inside the function
Inside the find_first_even function, use a for loop with variable i from 0 to n - 1. Check if arr[i] is even. If it is, return arr[i] immediately. After the loop, return -1 if no even number is found.
C
Need a hint?

Use for (int i = 0; i < n; i++) and inside check if (arr[i] % 2 == 0). Return the number if even, else return -1 after the loop.

4
Call the function and print the result
In the main function, call find_first_even with numbers and size. Store the result in an integer variable called result. Then print result using printf.
C
Need a hint?

Use int result = find_first_even(numbers, size); and then printf("%d\n", result); to print the first even number.