CJCoding With Joseph
15free / daySign inCreate account

Mastering C Textbook

Understanding Arrays

In C, an array is a way to store a group of items that are all the same type, like int, double or char, in a single variable.

You can think of it like a row of boxes, where each box holds one item, and you can easily find each item using its position, called an index.

For example, if you create an array called numbers that holds five integers, you can access each number by using numbers[0] for the first item, numbers[1] for the item, and so on.

This makes it easier to keep track of and work with related data all together.


Define An Empty Array

This is how you would create an array of integers with 3 indexes (0 to 2).

Remember that computers start counting from 0.

int myArr[3];
 
myArr[0] = 22;
myArr[1] = 9;
myArr[2] = 230;

printf("%d - %d - %d\n", myArr[0], myArr[1], myArr[2]);

OUTPUT:

22 - 9 - 230


Array With Values

You can also create an array with hard coded values. Notice how we don’t have to specify a size for this array like we did in example 3-A

int arr[] = { 5, 9, 2, 3 };


How To Iterate through an Array

You can use for loops to easily iterate through the indexes of an array. Let’s create a variable called index to use in the For Loop. It will control the number of times the For Loop will run. Using index < 4 will make the loop run from 0 to 3, which are the numerical indexes in our array. It will run until index hits 4 then stops.

Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 11 more lessons in Mastering C Textbook.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.