Chapter 10 - Arrays
Chapter 10 - Arrays
INTRODUCTION TO PROGRAMMING
Chapter 10
Arrays
Learning Objectives
At the end of the session, student should be able to:
data_type array_name[array_size];
Example: size is the number of elements we want
to store in the array
datatype variable_name [size];
Once we declare the 1D Array, it will look
like as shown in the picture below:
int a[5];
Example:
string cars[4] = {“Volvo”, “BMW”, “Ford”, “Mazda”};
cars Volvo BMW Ford Mazda
0 1 2 3
int main()
{
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
return 0;
}
#include <iostream>
Example using namespace std;
int main()
{
// Declaration and initialization of an integer array
int numbers[5] = {1, 2, 3, 4, 5};
// Accessing and printing array elements
cout << "Array elements: ";
for (int i = 0; i < 5; i++)
{
cout << numbers[i] << " ";
}
cout << endl;
// Modifying an array element
numbers[2] = 10;
// Accessing and printing modified array elements
cout << "Modified array elements: ";
for (int i = 0; i < 5; i++)
{ Output:
cout << numbers[i] << " "; Array elements: 1 2 3 4 5
} Modified array elements: 1 2 10 4 5
cout << endl;
return 0;
}
Initialize Array
▪ There are several ways to initialize an array in C++.
▪ Here are some common methods:
int numbers[5];
for (int i = 0; i < 5; i++)
{
numbers[i] = i + 1;
}
Initialize Array
▪ Initializing an array with zero.
int matrix[3][3];
int numbers[n];
cout << "Enter " << n << " numbers: ";
for (int i = 0; i < n; i++) {
cin >> numbers[i];
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += numbers[i];
}
cout << "The sum of the " << n << " numbers is: " << sum << endl;
return 0;
}
#include <iostream>
Answer using namespace std;
int main()
{
int n;
cout << "Enter the number of elements: ";
cin >> n;
int numbers[n];
cout << "Enter " << n << " numbers: ";
for (int i = 0; i < n; i++)
{
cin >> numbers[i];
}
cout << "Array elements: ";
for (int i = 0; i < n; i++)
{
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}
*** The End ***