Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

Arrays

Arrays

Arrays serve to store multiple values within a single variable, eliminating the need to declare separate variables for each value.

To instantiate an array, define the data type (such as int) and specify the array’s name followed by square brackets [ ].

To populate it with values, employ a comma-separated list enclosed within curly braces:

int myNumbers[] = {25, 50, 75, 100};

We’ve established a variable capable of containing an array of four integers.

Access the Elements of an Array

To access an element within an array, reference its index number.

Array indexes commence with 0: [0] corresponds to the first element, [1] to the second element, and so forth.

This statement retrieves the value of the first element [ 0 ] in myNumbers:

Example

int myNumbers[] = {25, 50, 75, 100};
printf(“%d”, myNumbers[0]);

// Outputs 25

Change an Array Element

To modify the value of a particular element, specify its index number:

Example

myNumbers[0] = 33;

Example

int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;

printf(“%d”, myNumbers[0]);

// Now outputs 33 instead of 25

Loop Through an Array

You can iterate through the array elements using a for loop.

The subsequent example displays all elements in the myNumbers array:

Example

int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {
  printf(“%d\n”, myNumbers[i]);
}

Set Array Size

Another prevalent method of creating arrays involves specifying the array size initially and then adding elements subsequently:

Example

// Declare an array of four integers:
int myNumbers[4];

// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;

When employing this approach, it’s necessary to determine the number of array elements beforehand to ensure sufficient memory allocation by the program.

Once created, you cannot alter the size of the array.