Programming Fundamental: Lecture-11
Programming Fundamental: Lecture-11
Lecture-11
Today’s Lecture
➢ Arrays
2
Arrays
Introduction
➢ In the previous lectures we worked with simple data types. A data type is
called simple if it can hold one value at a time.
➢ We also discussed decision making statements and repetition statements
with simple data types.
➢ We write our functions and used system defined function with simple data
types
➢ One data types we have not discussed so far is structured data type
➢ In contrast to simple data types, in a structured data type, each data item is
collection of other data items.
➢ Simple data types are building block for structured data type
➢ The first structured data type that we will discussed is an array.
3
Arrays
Introduction
➢ Before formally defining an array, let us consider the following problem.
We want to write a C++ program that reads five numbers, finds their sum,
and prints the numbers in reverse order.
Introduction
➢ Note the following in the previous program:
1. Five variables must be declared because the numbers are to be printed
in reverse order.
2. All variables are of type int—that is, of the same data type.
3. The way in which these variables are declared indicates that the
variables to store these numbers all have the same name—except the
last character, which is a number.
➢ Statement 1 tells you that you have to declare five variables.
➢ Statement 3 tells you that it would be convenient if you could somehow
put the last character, which is a number, into a counter variable and use
one for loop to count from 0to 4 for reading and another for loop to count
from 4 to 0 for printing.
➢ The data structure that lets you do all of these things in C++ is called an
5
array
Arrays
What is an Array?
➢ An array is a collection of a fixed number of components all of the same
data type.
➢ An array is used to process a collection of data of the same type
Examples: A list of names
A list of temperatures
➢ Why do we need arrays?
❖ Imagine keeping track of 5 test scores, or 100, or 1000in
memory How would you name all the variables?
How would you process each of the variables?
➢ A one-dimensional array is an array in which the components are arranged
in a list form.
6
Arrays
Declaring an Array
➢ The general form for declaring a one-dimensional array is:
dataType arrayName[intExp];
in which intExp is any constant expression that evaluates to a positive
integer. Also, intExp specifies the number of components in the array.
➢ An array, named num, containing five variables of type int can be declared
as
int num[ 5 ];
➢ This is like declaring 5 variables of type int:
num[0], num[1], … , num[4]
➢ The value in brackets is called
A subscript
An index 7
Arrays
8
Arrays
10
Arrays
12
Types of Arrays
13
Single Dimensional Arrays