0% found this document useful (0 votes)
4 views

Chapter One Array

This document provides an overview of arrays in C++, including definitions, memory requirements, declaration, initialization, and types of arrays. It explains one-dimensional and two-dimensional arrays, their syntax, and how to access and process their elements. Additionally, it includes examples of array initialization, accessing elements, and processing contents using loops.

Uploaded by

natnaeldagnew00
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter One Array

This document provides an overview of arrays in C++, including definitions, memory requirements, declaration, initialization, and types of arrays. It explains one-dimensional and two-dimensional arrays, their syntax, and how to access and process their elements. Additionally, it includes examples of array initialization, accessing elements, and processing contents using loops.

Uploaded by

natnaeldagnew00
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Fundamental programming II

C++

CHAPTER ONE
ARRAY

03/05/2025 1
What is array
• An array is a sequence of objects all of which have
the same type. The objects are called the elements
of the array and are numbered consecutively 0, 1, 2,
3, . . . .
• These numbers are called index values or subscripts
of the array. The term “subscript” is used because as
a mathematical sequence, an array would be
written with subscripts: a0, a1, a2, . . . .

• These numbers locate the element’s position within


the array, thereby giving direct access into the array.
03/05/2025 2
Cont’d…
• If the name of the array is a, then a [ o ] is the name
of the element that is in position 0.
• a [1] is the name of the element that is in position
1, etc.
• In general, the ith element is in position i-1.
• So if the array has n elements,their names are a[O],
a[l], a[2], . . . . a[n-I].

03/05/2025 3
Memory Requirements of Arrays
• The amount of memory used by an array depends
on the array’s data type and the number of
elements.
• The hours array, defined here, is an array of six
shorts.
short hours[6];
• On a typical PC, a short uses two bytes of memory,
so the hours array would occupy 12 bytes. This is
shown in Figure below.

03/05/2025 4
Cont’d…

The size of an array can be calculated by


multiplying the size of an individual element by
the number of elements in the array. Table below
shows the typical sizes of various arrays.

03/05/2025 5
Cont’d…

03/05/2025 6
Array declaration
• The syntax for an array declaration is
type array-name[array-size];
where type is the array’s element type and array-size is
its number of elements. The declaration
double a[SIZE];
• declares a to be an array of 5 elements, each of type
double. Standard C++ requires array-size to be a positive
integer constant. So it must be either a symbolic constant
or an integer literal like this:
double a[5]; int studentlist[90];
• Generally, it is better to use a symbolic constant since the
same
03/05/2025
size value is likely to be used in for loops that 7
Array Initialization
• Arrays may be initialized when they are defined.
• Like regular variables, C++ allows you to initialize an
array’s elements when you create the array. Here is
an example:
• int MONTHS = 12;
• int days[MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31,
30, 31, 30, 31};
• The series of values inside the braces and separated
with commas is called an initialization list.
• These values are stored in the array elements in the
order they appear in the list.
03/05/2025 8
Cont’d…
• If you initialize an array when it is declared, you can
omit the size of the array, and the array will
automatically be declared to have the minimum size
needed for the initialization values.
• For example, the following declaration
int b[] = {5, 12, 11};
is equivalent to
int b[3] = {5, 12, 11};

03/05/2025 9
Cont’d…
// array initialization
#include <iostream.h>

int main()
{
int days[12];
days[0] = 31; // January
days[1] = 28; // February
days[2] = 31; // March
days[3] = 30; // April
days[4] = 31; // May
days[5] = 30; // June
days[6] = 31; // July
days[7] = 31; // August
days[8] = 30; // September
days[9] = 31; // October
days[10] = 30; // November
days[11] = 31; // December
for (int count = 0; count < 12; count++)
{
cout << "Month " << (count + 1) << " has ";
cout << days[count] << " days.\n";
} 03/05/2025 10
Cont’d…
 After initializing an array, its elements are counted from left to
right. Each element of the array, also called a member of the
array, has a specific and constant position.

 The position of an item is also called its index.

 The first member of the array, the most left, has an index of 0.

 The second member of the array has an index of 1.

 Since each array has a number of items which can be


specified as n, the last member of the array has an index of n-
1.03/05/2025 11
Cont’d…
• The individual elements are accessed by specifying
the name of the array variable, and the position of
the element within the array this process is called
indexing or subscripting.
• The general form (syntax) used for accessing an
array component is:
arrayName[indexExp]
in which indexExp, called the index, is any
expression whose value is a nonnegative integer.
• The index value specifies the position of the
component in the array.
03/05/2025 12
Cont’d…
For example
int days[MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31};
• (The first value, 31, is stored in days[0], the second
value, 28, is stored in days[1], and so forth.) Figure
below shows the contents of the array after the
initialization.

03/05/2025 13
Cont’d…
// Accessing array element by using index
#include <iostream.h>
int main()
{
double score[] = {44.5, 72.52, 96.08, 68.78, 66.28};

cout << "1st member = " << score[0] << endl;


cout << "2nd member = " << score [1] << endl;
cout << "3rdd member = " << score [2] << endl;
cout << "4th member = " << score [3] << endl;
cout << "5th member = " << score [4] << endl;
return
03/05/2025
0; 14
Partial Array Initialization
• When an array is being initialized, C++ does not
require a value for every element.
• It’s possible to only initialize part of an array, such
as:
• int numbers[7] = {1, 2, 4, 8};
This definition initializes only the first four elements
of a seven-element array, as illustrated below.

03/05/2025 15
Types of Array
There are two types of array in c++ program.
1. One dimensional array
2. Two dimensional array

• One-dimensional array is an array in which the


components are arranged in a list form.

• Two-dimensional array: A collection of a fixed


number of components arranged in rows and
columns (that is, in two dimensions), wherein all
components are of the same type.
03/05/2025 16
Cont’d…
//one-dimensional array example
#include <iostream.h>
void main(void)
{
int days[12] = {31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31};
for (int count = 0; count < 12;
count++)
{
cout << "Month " << (count + 1) << "
has ";
cout << days[count] << " days.\n";
}
03/05/2025 17
Initializing with Strings
• When initializing a character array with a string, simply
enclose the string in quotation marks, as shown here:
char name[7] = "Warren";
• Although there are six characters in the string “Warren,”
the array must have enough elements to also
accommodate the null terminator at the end of the
string.
• It’s important to note that anytime a string literal is used
in C++, the null terminator is automatically included.
That’s why name is defined above with seven elements.
• Figure below shows the contents of name after the
initialization:
03/05/2025 18
Cont’d…

‘\0’ represents the null terminator. ‘\0’ is an escape


sequence that is stored in memory as a single character.
Its ASCII code is 0.
The null terminator is not automatically included when an
array is initialized with individual characters. It must be
included in the initialization list, as shown below:

char name[7] = {'W', 'a', 'r', 'r', 'e', 'n', '\0'};


03/05/2025 19
Cont’d…
// This program displays the contents of two char arrays.
//This program shows two character arrays initialized with
strings.
#include <iostream.h>
int main()
{
char name1[] = "Holly";//string : defined with double coat
char name2[] = {'W', 'a', 'r', 'r', 'e', 'n', '\0'};
cout << name1 << endl;
cout << name2 << endl;
return 0;
} 03/05/2025 20
Processing array contents
• Individual array elements are processed like any other
type of variable.
• Processing array elements is no different than processing
other variables. For example, the following statement
multiplies hours[3] by the variable rate:
pay = hours[3] * rate;
• And the following are examples of pre-increment and
post-increment operations on array elements:
• int score[5] = {7, 8, 9, 10, 11};
• ++score[2]; // Pre-increment operation on the value in
score[2]
• score[4]++; // Post-increment operation on the value in
03/05/2025 21
score[4]
Cont’d…
#include <iostream.h>
int main()
{
int counter = 5;
int page[counter];
cout << "Enter the number of pages of your books\n"; cout <<
"Book 1: ";
cin >> page[0];
cout << "Book 4: ";
cin >> page[3];
cout << "\nSummary of books";
cout << "\nBook 1: " << page[0] << " pages";
cout03/05/2025
<< "\nBook 4: " << page[3] << " pages\n"; 22
Cont’d…
#include <iostream.h>
int main() {
const int max = 10;
int number[max]; // We will calculate their sum
int sum = 0;
cout << "Please type 10 integers.\n";
for( int i = 0; i < max; i++ ) {
cout << "Number " << i + 1 << ": ";
cin >> number[i];
sum += number[i]; }
cout << "\n\n The sum of these numbers is " << Sum << "\n\n";
return 0;
} 03/05/2025 23
Cont’d…
/ Example of finding the minimum member of an array
#include <iostream.h>
int main() {
// The members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int minimum = numbers[0];
int a = 8;
// Compare the members
for (int i = 1; i < a; ++i)
{
if (numbers[i] < minimum)
minimum = numbers[i];}
// Announce the result
cout << "The lowest member value of the array is " << minimum << "." <<
endl;
03/05/2025 24
return 0; }
Two-Dimensional Arrays
• Two-dimensional array: A collection of a fixed
number of components arranged in rows and
columns (that is, in two dimensions), where in all
components are of the same type.

• It’s best to think of a two dimensional array as having


rows and columns of elements.
• The syntax for declaring a two-dimensional array is:
dataType arrayName[arraysize1][arraysize2];

• Where in arraysize1 and arraysize2 are constant


03/05/2025 25
Cont’d…
• The two expressions, arraysize1 and arraysize2,
specify the number of rows and the number of
columns, respectively, in the array.
The statement:
double sales[10][5];
declares a two-dimensional array sales of 10 rows
and 5 columns, in which every component is of
type double.
• As in the case of a one-dimensional array, the rows
are numbered from 0. . .9 and the columns are
numbered from 0. . .4
03/05/2025 26
Cont’d…
• To define a two-dimensional array, two size
declarators are required.
• The first size declarator specifies the number of
rows, and the second size declarator specifies the
number of columns.

When processing the data in a two-dimensional


array, each element has two subscripts:
one for its row and another for its column.
03/05/2025 27
Cont’d…
• In the scores array defined above, the elements in
row 0 are referenced as

03/05/2025 28
Cont’d…
#include <iostream.h>
int main()
{
int SomeArray[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
for (int i = 0; i<5; i++)
for (int j=0; j<2; j++)
{
cout << "SomeArray[" << i << "][" << j << "]: ";
cout << SomeArray[i][j]<< endl;
}
return 0;
03/05/2025 29
Multidimensional array initialation

int temp[4][3] = {{50, 70, 60}, {48, 75, 62},


{51, 69, 60}, {52, 78, 63}};

int t2[7][4] = {{50, 70, 60}, {48, 75, 62},


{51, 69, 60}, {52, 78, 63}};

int temp[][3] = {{50, 70, 60}, {48, 75, 62},


{51, 69, 60}, {52, 78, 63}};

int temp[][3] = {50, 70, 60, 48, 75, 62, 51,


69, 60, 52, 78, 63};
03/05/2025 30
Processing two dimensional array
• To sum all the elements of a two-dimensional array, you can use a pair of nested loops to
add the contents of each element to an accumulator.
#include<iostream.h>
const int NUM_ROWS = 5; // Number of rows
const int NUM_COLS = 5; // Number of columns
int total = 0; // Accumulator
int numbers[NUM_ROWS][NUM_COLS] = {{2, 7, 9, 6, 4},
{6, 1, 8, 9, 4},
{4, 3, 7, 2, 9},
{9, 9, 0, 3, 1},
{6, 2, 7, 4, 1}};
// Sum the array elements.
for (int row = 0; row < NUM_ROWS; row++)
{
for (int col = 0; col < NUM_COLS; col++)
total += numbers[row][col];
}
// Display
03/05/2025the sum. 31
Cont’d…
Summing the Rows of a Two-Dimensional Array
• Sometimes you may need to calculate the sum of
each row in a two-dimensional array.
• For example, suppose a two-dimensional array is
used to hold a set of test scores for a set of
students.
• Each row in the array is a set of test scores for one
student. To get the sum of a student’s test scores
(perhaps so an average may be calculated), you use
a loop to add all the elements in one row.

03/05/2025 32
Cont’d…
const int NUM_STUDENTS = 3; // Number of students
const int NUM_SCORES = 5; // Number of test scores
double total; // Accumulator is set in the loops
double average; // To hold each student's average
double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94},
{86, 91, 78, 79, 84},
{82, 73, 77, 82, 89}};
// Get each student's average score.
for (int row = 0; row < NUM_STUDENTS; row++)
{
// Set the accumulator.
total = 0;
// Sum a row.
for (int col = 0; col < NUM_SCORES; col++)
total += scores[row][col];
// Get the average.
average = total / NUM_SCORES;
// Display the average.
cout << "Score average for student "
<<03/05/2025
(row + 1) << " is " << average <<endl; 33
Cont’d…
#include <iomanip.h>
#include<iostream.h>
main()
{
int i,j;
int nrows,ncols, X[10][10];
cout<<"No of rows : ";
cin>>nrows;
cout<<"No of Columns : ";
cin>>ncols;
for (i =0; i<nrows;i++)
{
for(j =0; j<ncols;j++)
{
X[i][j] = 2*i + 3*j;
}
}
cout<<" The matrix is given below "<<endl;
for (i =0; i<nrows;i++)
{
for(j =0; j<ncols;j++)
{
cout<<setw(5)<<X[i][j];
}
03/05/2025 34
cout<<endl;
Arrays of Strings
• A two-dimensional array of characters can be used
as an array of strings.
• Because strings are stored in single-dimensional
character arrays, an array of strings would be a
two-dimensional character array.

03/05/2025 35
cont`d
• Just as the name of an array represents the array’s
address, a two-dimensional array with only the row
subscript represents the address of that row.
• For instance, in the array defined above,
scientists[0] represents the address of row 0,
scientists[1] represents the address of row 1, and so
forth.
• The following cout statement will display the string
“Einstein” on the screen:
cout << scientists[3];
03/05/2025 36
Cont’d…
// two-dimensional character array to hold the names of the months and a one-dimensional
integer array to hold
// the number of days in each month.
#include <iostream.h>
int main(){
const int NUM_MONTHS = 12; // The number of months
const int STRING_SIZE = 10; // Maximum size of each string
// Array with the names of the months
char months[NUM_MONTHS][STRING_SIZE] =
{ "January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December" };
// Array with the number of days in each month
int days[NUM_MONTHS] = {31, 28, 31, 30,
31, 30, 31, 31, 30, 31, 30, 31};
// Display the months and their numbers of days.
for (int count = 0; count < NUM_MONTHS; count++){
cout << months[count] << " has ";
cout03/05/2025
<< days[count] << " days.\n"; } 37
Cont’d…
#include<iostream.h>
int main()
{
const int ROWS = 4;
const int COLS = 8;

for (int i = 0; i < ROWS; i++)


{
for (int j = 0; j < COLS; j++)
{
cout << "*";
}
cout << endl;
}
cout << endl;
return 0;
03/05/2025 38

You might also like