Arrays
Learn to work with arrays. Store multiple values, access elements by index, and iterate through collections.
Learning Objectives:
- β’Declare and initialize arrays
- β’Access array elements using indices
- β’Find the length of an array
- β’Iterate through arrays with loops
- β’Perform calculations on array elements
Arrays
Why Arrays Matter
So far, you've worked with individual variables. But what if you need to store many values of the same type?
For example:
- "Store the scores of 100 students"
- "Keep track of temperatures for a week"
- "Store a list of names"
Arrays let you group related values together under one name, and access them by position.
What is an Array?
An array is an ordered collection of elements, all of the same type. Each element is identified by its index (position).
plaintextArray: [10, 20, 30, 40, 50] Index: 0 1 2 3 4
Key facts:
- Indexing starts at 0 (not 1)
- The length of the array is the number of elements
- You access elements using
array[index]
Declaring and Initializing Arrays
Python
python# Create an array with initial values scores = [85, 90, 78, 92, 88] # Create an empty array (list) grades = [] # Create an array of specific size, filled with zeros temperatures = [0] * 7 # Array of strings names = ["Alice", "Bob", "Charlie"]
C
c#include <stdio.h> int main() { // Array with initial values int scores[5] = {85, 90, 78, 92, 88}; // Array of size 10, uninitialized int numbers[10]; // Array of strings char names[3][20] = {"Alice", "Bob", "Charlie"}; return 0; }
Java
javapublic class Main { public static void main(String[] args) { // Array with initial values int[] scores = {85, 90, 78, 92, 88}; // Array of size 10, initialized to 0 int[] numbers = new int[10]; // Array of strings String[] names = {"Alice", "Bob", "Charlie"}; } }
C++
cpp#include <iostream> #include <vector> using namespace std; int main() { // Array with initial values int scores[] = {85, 90, 78, 92, 88}; // Vector (dynamic array) vector<int> numbers = {10, 20, 30}; return 0; }
Accessing Elements
Use the index (position) to access an element.
Python
pythonscores = [85, 90, 78, 92, 88] print(scores[0]) # 85 print(scores[2]) # 78 print(scores[4]) # 88
C
cint scores[5] = {85, 90, 78, 92, 88}; printf("%d\n", scores[0]); // 85 printf("%d\n", scores[2]); // 78 printf("%d\n", scores[4]); // 88
Java
javaint[] scores = {85, 90, 78, 92, 88}; System.out.println(scores[0]); // 85 System.out.println(scores[2]); // 78 System.out.println(scores[4]); // 88
Array Length
To find the number of elements in an array:
Python
pythonscores = [85, 90, 78, 92, 88] print(len(scores)) # 5
C
cint scores[5] = {85, 90, 78, 92, 88}; int length = 5; // In C, you must track this manually printf("%d\n", length);
Java
javaint[] scores = {85, 90, 78, 92, 88}; System.out.println(scores.length); // 5
C++
cppvector<int> scores = {85, 90, 78, 92, 88}; cout << scores.size() << endl; // 5
Iterating Through Arrays
The most common operation is looping through all elements.
Python
pythonscores = [85, 90, 78, 92, 88] for score in scores: print(score)
Or with index:
pythonfor i in range(len(scores)): print(f"Score {i}: {scores[i]}")
C
cint scores[5] = {85, 90, 78, 92, 88}; for (int i = 0; i < 5; i++) { printf("%d\n", scores[i]); }
Java
javaint[] scores = {85, 90, 78, 92, 88}; for (int i = 0; i < scores.length; i++) { System.out.println(scores[i]); } // Or enhanced for loop for (int score : scores) { System.out.println(score); }
Modifying Array Elements
You can change elements by assigning to them:
Python
pythonscores = [85, 90, 78, 92, 88] scores[2] = 92 # Change the element at index 2 print(scores) # [85, 90, 92, 92, 88]
C
cint scores[5] = {85, 90, 78, 92, 88}; scores[2] = 92; printf("%d\n", scores[2]); // 92
Java
javaint[] scores = {85, 90, 78, 92, 88}; scores[2] = 92; System.out.println(scores[2]); // 92
Real-World Example: Find the Sum
Problem: Given an array of numbers, calculate the sum of all elements.
Python:
pythonnumbers = [10, 20, 30, 40, 50] total = 0 for num in numbers: total = total + num print(f"Sum: {total}") # 150
Java:
javaint[] numbers = {10, 20, 30, 40, 50}; int total = 0; for (int num : numbers) { total = total + num; } System.out.println("Sum: " + total); // 150
C:
c#include <stdio.h> int main() { int numbers[5] = {10, 20, 30, 40, 50}; int total = 0; for (int i = 0; i < 5; i++) { total = total + numbers[i]; } printf("Sum: %d\n", total); // 150 return 0; }
Finding the Maximum
Problem: Find the largest element in an array.
Python:
pythonscores = [85, 92, 78, 95, 88] max_score = scores[0] # Start with the first element for score in scores: if score > max_score: max_score = score print(f"Highest score: {max_score}") # 95
Java:
javaint[] scores = {85, 92, 78, 95, 88}; int max_score = scores[0]; for (int score : scores) { if (score > max_score) { max_score = score; } } System.out.println("Highest score: " + max_score); // 95
Reversing an Array
Problem: Print the elements in reverse order.
Python:
pythonnumbers = [10, 20, 30, 40, 50] for i in range(len(numbers) - 1, -1, -1): print(numbers[i]) # Output: 50, 40, 30, 20, 10
Java:
javaint[] numbers = {10, 20, 30, 40, 50}; for (int i = numbers.length - 1; i >= 0; i--) { System.out.println(numbers[i]); } // Output: 50, 40, 30, 20, 10
Key Takeaways
- Arrays store multiple values of the same type under one name
- Indices start at 0 and go up to length - 1
- Access elements using
array[index] - Length is the total number of elements
- Loops are the best way to iterate through arrays
- Reversing an array requires going backward through indices
Summary
Arrays are fundamental to programming. They let you work with collections of data efficiently. Combined with loops, arrays enable powerful programs that process multiple inputs.
Progress: 6/8 chapters complete in Level 1
Exercises
Exercise 1: Declare and Access an Array
Create an array, access its elements, and display the requested values.
Exercise 2: Loop Through an Array
Use a loop to visit and display the elements of an array.
Exercise 3: Sum an Array
Calculate the sum of the values in an array.
Exercise 4: Maximum in an Array
Find the largest value in an array.
Exercise 5: Reverse an Array
Display the array elements in reverse order.
Exercise 6: Rotate an Array
Rotate the array elements as requested by the exercise.