C++ for Statement and Array Question

Introduction

Write a program that defines an array of 5 integers.

Use the for-loop to print the array elements and their indexes.

You can use the following code structure.

#include <iostream> 

int main() 
{ 
    //your code here
} 



#include <iostream> 

int main() 
{ 
    int arr[5] = { 3, 20, 8, 15, 10 }; 
    for (int i = 0; i < 5; i++) 
    { 
        std::cout << "arr[" << i << "] = " << arr[i] << '\n'; 
    } 
} 

Here, we defined an array of 5 elements.

Arrays are indexed starting from zero.

So the first array element 3 has an index of 0.

The last array element of 10 has an index of 4.

We used the for-loop to iterate over array elements and print both their indexes and values.

Our for-loop starts with a counter of 0 and ends with a counter of 4.




PreviousNext

Related