C++ Arrays

C++ Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To declare an array, define the variable type, specify the name of the array followed by square brackets and specify the number of elements it should store:

string cars[4];

We have now declared a variable that holds an array of four strings. To insert values to it, we can use an array literal – place the values in a comma-separated list, inside curly braces : Continue reading C++ Arrays

C Arrays – Examples

Real-Life Example

To demonstrate a practical example of using arrays, let’s create a program that calculates the average of different ages:

Example

// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;
int i;

// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);

// Loop through the elements of the array
for (i = 0; i < length; i++) {
  sum += ages[i];
}

// Calculate the average by dividing the sum by the length
avg = sum / length;

// Print the average
printf("The average age is: %.2f", avg);

Continue reading C Arrays – Examples

C Arrays

Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To create an array, define the data type (like int) and specify the name of the array followed by square brackets [].

To insert values to it, use a comma-separated list inside curly braces, and make sure all values are of the same data type:

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

We have now created a variable that holds an array of four integers. Continue reading C Arrays