C Programming: Understanding Array Traversal 🎯

beginner
13 min

C Programming: Understanding Array Traversal 🎯

Welcome to our deep dive into C Programming! Today, we'll learn about Array Traversal, a fundamental concept that every programmer should master.

Let's start with the basics. In C, an array is a collection of elements of the same data type, stored in contiguous memory locations. To traverse an array, we access each element one by one.

Creating an Array 📝

Before we traverse an array, let's learn how to create one. Here's a simple example:

c
int numbers[5] = {1, 2, 3, 4, 5};

In this example, we've created an array numbers of type int (integer) with 5 elements. We've also initialized it with the values 1, 2, 3, 4, and 5.

Traversing an Array 💡

Now that we have an array, let's learn how to traverse it. We'll use a loop to access each element one by one.

c
#include <stdio.h> int main() { int numbers[5] = {1, 2, 3, 4, 5}; int i; for (i = 0; i < 5; i++) { printf("Element %d: %d\n", i, numbers[i]); } return 0; }

In this example, we've used a for loop to traverse the array. The i variable is used as an index to access each element. The printf function is used to print each element.

Array Sizes and Indexing 📝

Remember, in C, the first element of an array is at index 0, not 1. Also, when initializing an array, the size of the array should be specified.

Advanced Array Traversal 💡

Let's take a practical example to understand advanced array traversal. Suppose we have an array of student scores and we want to find the highest score.

c
#include <stdio.h> #define NUM_STUDENTS 5 int main() { int scores[NUM_STUDENTS] = {85, 67, 90, 78, 89}; int highest = scores[0]; int i; for (i = 1; i < NUM_STUDENTS; i++) { if (scores[i] > highest) { highest = scores[i]; } } printf("The highest score is: %d\n", highest); return 0; }

In this example, we've used a loop to traverse the array and find the highest score. We initialize highest with the first score and then update it with the highest score we encounter during traversal.

Quiz 📝

Quick Quiz
Question 1 of 1

What does the following line of code do?

Quick Quiz
Question 1 of 1

What is the index of the first element in a C array?