Lab 01
Lab 01
Objective:
In this lab, we will learn to work with arrays i.e to perform different operation on arrays.
Introduction:
In C++, an array is a variable that can store multiple values of the same type. For example,
Suppose a class has 27 students, and we need to store the grades of all of them. Instead of creating 27
separate variables, we can simply create an array:
Int array[27];
Here, grade is an array that can hold a maximum of 27 elements of double type.
In C++, the size and type of arrays cannot be changed after its declaration.
Array Declaration:
dataType arrayName[arraySize];
For example,
int x[6];
Here,
array[index];
• The array indices start with 0. Meaning x[0] is the first element stored at index 0.
• If the size of an array is n, the last element is stored at index (n-1). In this example, x[5] is the
last element.
• Elements of an array have consecutive addresses. For example, suppose the starting address
of x[0] is 2120d. Then, the address of the next element x[1] will be 2124d, the address
of x[2] will be 2128d and so on.
Here, the size of each element is increased by 4. This is because the size of int is 4 bytes.
Array Initialization:
In C++, it's possible to initialize an array during declaration. For example,
return 0;
Here, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we have printed numbers[i].
int main() {
int numbers[5];
return 0;
Output:
Enter 5 numbers:
11
12
13
14
15
Once again, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we took an input
from the user and stored it in numbers[i].
Then, we used another for loop to print all the array elements.
Example 3: Display Sum and Average of Array Elements Using for Loop
#include <iostream>
int main() {
int i,count=0;
double sum = 0;
double average;
for (i=0;i<=5;i++) {
cout<<numbers[i]<<" ";
sum = sum+numbers[i];
count=count+1;
return 0;
Output:
The numbers are: 7 5 6 3 1 2
Their Sum = 24
Their Average = 4
In this program:
We have initialized a double array named numbers but without specifying its size. We also declared
three double variables sum, count, and average.
Then we used a for loop to print the array elements. In each iteration of the loop, we add the current
array element to sum.
We also increase the value of count by 1 in each iteration, so that we can get the size of the array by the
end of the for loop.
After printing all the elements, we print the sum and the average of all the numbers. The average of the
numbers is given by average = sum / count
In-Lab Tasks
In-Lab Task 1:
Take an array from the user and then swap its first and last values.
In-Lab Task 2:
Take an element of an array from user, display its location and then take a new element from the user
to replace the previous element.
Post-Lab Tasks
Post-Lab Task:
Take an element of an array from the user to delete it and then display the new array.