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.
Before we traverse an array, let's learn how to create one. Here's a simple example:
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.
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.
#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.
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.
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.
#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.
What does the following line of code do?
What is the index of the first element in a C array?