Lecture 17 Arrays
Lecture 17 Arrays
Motivation of arrays
Initialization of Arrays
Sample Programs
- Average age of students
- Count the number of positive integers
- Sum of the square of array elements
- Copying
- Linear search
Use of #define SIZE 100
Use of rand() and srand(time(NULL))
Motivation of arrays:
Let us consider an example about calculation of average age of 10 students. At first, we will declare
10 variables to store the age of each student and then sum up all the ages and divide this with 10 to
get the average age. Suppose, we have 100 students instead of 10, we have to declare 100 variables
i.e. one for each student’s age. Is there any other way to deal with this problem? Arrays are possible
solution to the problem.
Arrays:
Array is a special data-type. If we have a collection of data of same type as in the case of storage of
ages of 100 students, arrays can be used. Arrays are data structure in which identical data types are
stored. The concept of arrays is being explained furtherin the following parts of the lecture.
• Arrays are like the data structure in which identical data types are
stored.
• An array has a name, data type, and size
• They occupy the consecutive area of memory
Syntax: name
OR
// initialization of array
do
{
cout <<"Entered the positive number (enter -1 for end of input):";
cin >> input;
if (input != -1)
{
a[i] = input;
}
i++;
} while (input != -1 && i < 100);
cout <<"The sum of the square of array elements are: " << sumOfSquare;
return 0;
}
int arr[SIZE]
for (i = 0; i < SIZE; i++)
{
arr[i] = i;
}
return 0;
}
Example 5: Linear search (Guess a number)
int main()
{
int arr[SIZE];
int num=0, flag = 0, i = 0;
return 0;
}
Example 6: Use the random function
• The function is rand() and is in the standard library.
• To access this function, we need to include <cstdlib> library in our program.
• This function will return a random number.
The number can be between 0 and 32767.
#include <iostream>
#include<cstdlib> // for rand() and srand()
#define SIZE 10
int main()
{
srand(time(0));// To make rand() as the real random number generator
int arr[SIZE];
int num = 0, flag = 0, i = 0;
arr[i] = rand();
}
return 0;
}
What is the output of the following expression:
rand() % 6
1+ rand() % 6 => Use to make fair dice
rand() % 2
1+ rand() % 2 = > Use to make fair coin
Homework:
• Reverse the array elements from arrayA and store them in arrayB
• Comparing the two arrays (identical or not)
• Sort the array elements in ascending and descending order