Lesson 6: Arrays – Organizing Your Data Like a Pro
Welcome back, code adventurer! 👋
Today, we’re diving into the world of arrays — because let’s face it, one variable just isn’t enough sometimes. Imagine you’re at a party and you’re trying to remember the names of everyone there. Instead of creating a separate variable for every person (which would be chaos), you use an array — your trusty list of names all neatly stored together.
An array is like your very own digital notepad where you can keep a bunch of related data in one place. Whether it’s a list of your favorite pizza toppings or the high scores in your latest game, arrays have got your back!
Grab your caffeine fix, and let’s get organized.
What is an Array?
An array is basically a collection of variables, all of the same type, stored in a contiguous block of memory. Think of it as a row of lockers in a school, where each locker can hold one thing (like a backpack or lunch). The key is that all the lockers are in the same hallway (the array) and can only store the same type of item.
Here’s the basic syntax for declaring an array:
data_type array_name[array_size];
Let’s say we want to store the scores of 5 players in a game. We can create an array like this:
#include <stdio.h>
int main() {
int scores[5]; // Array to hold 5 integers
// Assigning values
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;
scores[3] = 99;
scores[4] = 88;
// Printing the scores
for(int i = 0; i < 5; i++) {
printf("Player %d's score: %d\n", i + 1, scores[i]);
}
return 0;
}
Explanation: We created an array scores
that can hold 5 integers. Then, we assigned each element a score and printed it using a for
loop. Easy, right?
Accessing Elements in an Array
Each element in an array has an index — like the locker number in our hallway example. The first element in an array is at index 0, the second is at index 1, and so on. To access or modify an element, you use its index.
For example, if we want to update Player 3’s score to 80, we’d do this:
scores[2] = 80; // Remember, arrays start at index 0!
And if you want to print a specific element, say Player 4’s score, you do this:
printf("Player 4's score: %d\n", scores[3]);
Initializing Arrays
You don’t always have to assign values to an array one by one. You can initialize it all at once like this:
int scores[5] = {85, 92, 78, 99, 88};
In this case, we’re declaring the array and immediately filling it with values. You can even let the compiler figure out the size for you by leaving out the number in the square brackets:
int scores[] = {85, 92, 78, 99, 88}; // The compiler automatically sets the size to 5
Working with Arrays in Loops
Arrays and loops go together like peanut butter and jelly. When you have a collection of data, loops are the perfect way to process each element. Here’s an example of calculating the average score of our players:
#include <stdio.h>
int main() {
int scores[] = {85, 92, 78, 99, 88};
int sum = 0;
int num_players = 5;
for(int i = 0; i < num_players; i++) {
sum += scores[i];
}
float average = sum / (float)num_players; // Calculate average
printf("Average score: %.2f\n", average);
return 0;
}
Explanation: We loop through the array, summing the scores, and then calculate the average. Notice how we cast num_players
to float
to get a precise average with decimals.
Arrays and Functions
You can pass arrays to functions too! Here’s a simple example where we pass our array of scores to a function to find the highest score:
#include <stdio.h>
int find_highest(int scores[], int num_players) {
int highest = scores[0];
for(int i = 1; i < num_players; i++) {
if(scores[i] > highest) {
highest = scores[i];
}
}
return highest;
}
int main() {
int scores[] = {85, 92, 78, 99, 88};
int num_players = 5;
int highest_score = find_highest(scores, num_players);
printf("The highest score is: %d\n", highest_score);
return 0;
}
Explanation: We define a function find_highest
that takes an array of scores and the number of players as arguments. It loops through the array to find and return the highest score.
Multidimensional Arrays: Arrays on Arrays!
So far, we’ve been working with one-dimensional arrays (a simple list). But what if you need to store a grid or a table of data? That’s where multidimensional arrays come in. Here’s how you can declare and use a 2D array (think of it as an array of arrays):
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Printing the matrix
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Explanation: We created a 3x3 matrix (a 2D array). The for
loops go through each element in the array and print it as a grid.
Homework Challenge: Temperature Tracker!
Create a program that:
- Declares an array to hold the temperatures for a week (7 days).
- Prompts the user to enter the temperatures.
- Finds and prints the highest, lowest, and average temperature.
Final Thoughts
You’ve now added arrays to your programming toolkit, mastering how to handle multiple pieces of data in a structured way. Arrays are powerful, and we’ve only scratched the surface of what you can do with them. In Lesson 7, we’ll dive into strings — yes, those magical arrays of characters! See you there! 🎉✨
See also
- Lesson 3 – Arrays and Objects: Your Treasure Chests of Data
- Lesson 7: Strings – Turning Characters Into Words (And Making Sense of Them)
- Lesson 5: Functions – Breaking Down the Chaos (And Avoiding Code Repetition!)
- Lesson 4: Control Structures – Making Decisions (And Telling Your Program What to Do!)
- Lesson 3: Arithmetic Operations – Making Your Variables Work for You!