Example:
int arr[5];
Declares an array of 5 integers.
In order to access the elements of an array, we use an index. The index starts from 0.
First element of the array is arr[0], second element is arr[1], and so on.
In order to access all the elements of an array, we usually use a for-loop.
For-loop is a control flow statement that allows code to be executed repeatedly based on a given condition.
Example:
for(int i=0; i<5; i++) {
cout << arr[i] << " ";
}
#include <iostream>
using namespace std;
int main() {
int arr[5];
cout << "Enter 5 numbers: ";
for(int i=0; i<5; i++) {
cin >> arr[i];
}
}
#include <iostream>
using namespace std;
int main() {
int arr[5];
cout << "Enter 5 numbers: ";
for(int i=0; i<5; i++) {
cin >> arr[i];
}
cout << "You entered: ";
for(int i=0; i<5; i++) {
cout << arr[i] << " ";
}
}
Example:
Enter a number: 5
5 10 15 20 25 30 35 40 45 50