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

5

Uploaded by

2024745461
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

5

Uploaded by

2024745461
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Introduction to

Computer Programming
(CSC425)
Chapter 5: Array

By Muhamad Ridhwan Mohamad Razali


Credit to Dr Afiza Ismail
Objectives
In this chapter you will:
• Learn about arrays.
• Explore how to declare and manipulate data into arrays.
• Discover how to pass an array as a parameter to a function.
• Learn about C-strings.
• Examine the use of string functions to process C-strings.
• Discover how to input data into—and output data from—a C-
string.
Introduction to Array
Array

 Is a collection of a fixed number of components wherein all of the


components have the same data type.
One Dimensional Array
• Is used to store multiple value in a single identifier.
• General array declaration syntax:

data-type array name [number of items]

For example:
• float temp[5] = to store 5 float value in temp.
• int max[4] = to store 4 integer value in max
• char y[20] = to store a string of value
One Dimensional Array (continued)

• Each item in an array is called an element or component.


• Every item has its position in an array, this position is called index or subscript;
always start at 0.
• Example :
• int num[10] store 10 data.
Note : int num[] error!
• int num[]={1,2,3} not error.
num[0] refer to the first data
num[1] refer to the second data
num[2] refer to the third data
One Dimensional Array (continued)

• Input & output :

int num[100] // declaration


cin >> num[20]; // to enter the 21th value
cout << num[20]; // to display the 21th value

//using looping:
for(int i=0; i<5; i++)
cout << num[i];
One Dimensional Array (continued)

• Input & output :

Array can be initialized within their declaration:


int temp[5]={1,2,3,4,5};

char codes[6]={‘s’, ’a’, ’m’, ’p’, ’l’, ’e’}; or

char codes[6]=“sample”;
Note : a string is terminated with a special sentinel,“\0”
the null character.
One Dimensional Array (continued)

NOTE:
• If what we declare doesn’t fulfill what the size of the array wants, for example:
int max[6]={1,2,3}
• we only declare three but the array wants 6; the compiler will assume the next
three integer are zero :
“ 1,2,3,0,0,0 “
• If what we declare exceeds what the array wants, for example:
int max[3]={1,2,3,4,5,6,7,8}
• the array wants three but we declare 8” the compiler will only take the first
three integer :
“1,2,3”
One Dimensional Array (continued)

Array list : int list[10];


One Dimensional Array (continued)

Accessing Array component : list[5];


One Dimensional Array (continued)

List[3] = 10;
List[6] = 35;
List[5] = list[3] + list[6];
One Dimensional Array (continued)

PROCESSING ONE DIMENSIONAL ARRAY :


• Some basic operations performed on a one-dimensional array are:
1) Initialize
2) Input data
3) Output data stored in an array
4) Find the largest and/or smallest element
• Each operation requires ability to step through the elements of the array.
• Easily accomplished by a loop.
One Dimensional Array (continued)

ACCESSING ARRAY COMPONENTS :


• Consider the declaration

int list[100]; //list is an array of the size 100


int i;

• This for loop steps-through each element of the array list starting at the
first element

for (i = 0; i < 100; i++) //Line 1


//process list[i] //Line 2
One Dimensional Array (continued)

ACCESSING ARRAY COMPONENTS :

If processing list requires inputting data into list :

• The statement in Line 2 takes the form of an input statement, such as


the cin statement:

for (i = 0; i < 100; i++) //Line 1


cin >> list[i];
One Dimensional Array (continued)

ACCESSING ARRAY COMPONENTS :

If processing list requires printing data from an array:

• the statement in Line 2 takes the form of an output statement, such


as the cout statement

for (i = 0; i < 100; i++) //Line 1


cout << list[i];
Example of code
//read, print and copy components of an array for(index = 0; index < 10; index++)
{
#include<iostream> cout<<myList[index]<<" "; // print
using namespace std; component
}
int main()
{ cout<<"\n\n The numbers inside the yourList
double myList[10], array are: ";
yourList[10];
int index; for(index = 0; index < 10; index++)
{
cout<<"Enter 10 number: "; yourList[index] = myList[index]; //
copy component
for(index = 0; index < 10; index++) cout<<yourList[index]<<" ";
{ }
myList[index] = 0.0;
cin>>myList[index]; //read component cout<<"\n\n The number in yourList[5] is:
} "<<yourList[5];

cout<<"\n The component inside the myList return 0;


array are: "; }
Example code
//read 5 numbers, find their sum, print the
numbers in reverse orders. cout<<endl;
cout<<"The sum of the numbers is:
#include<iostream> "<<sum<<endl; cout<<"The numbers in
using namespace std; reverse order are: ";

int main() for(counter = 4; counter >= 0; counter--)


{ cout<<item[counter]<<" ";
int item[5]; // Declare an array item
of five components cout<<endl;
int sum, counter;
return 0;
cout<<"Enter 5 number: "; }

for(counter = 0; counter < 5; counter++)


{
cin>>item[counter];
sum = sum + item[counter];
}
One Dimensional Array (continued)
One Dimensional Array (continued)

ARRAYS AS PARAMETERS TO FUNCTION :

• Arrays are passed by reference only.

• The symbol & is not used when declaring an array as a formal parameter.

• The size of the array is usually omitted.


One Dimensional Array (continued)

ARRAYS AS PARAMETERS TO FUNCTION :

• If the size of one-dimensional array is specified when it is declared as a


formal parameter

• It is ignored by the compiler

• The reserved word const in the declaration of the formal parameter can
prevent the function from changing the actual parameter
One Dimensional Array (continued)

Example :

Constant arrays as formal parameters :


//Function to initialize an int array to 0. The array to be initialized and its }
//size are passed as parameters. The parameter listSize specifies the number of
//elements to be initialized. //Function to find and return the sum of the elements of an int array. The
//parameter listSize specifies the number of elements to be added.
void initializeArray(int list[], int listSize)
{ int sumArray(const int list[], int listSize)
int index; {
for (index = 0; index < listSize; index++) int index;
list[index] = 0; int sum = 0;
} for (index = 0; index < listSize; index++)
sum = sum + list[index];
//Function to read and store the data into an int array. The array to store the
//data and its size are passed as parameters. The parameter listSize specifies return sum;
//the number of elements to be read. }

void fillArray(int list[], int listSize) //Function to find and return the index of the first largest element in an int array.
{ //The parameter listSize specifies the number of elements in the array.
int index;
for (index = 0; index < listSize; index++) int indexLargestElement(const int list[], int listSize)
cin >> list[index]; {
} int index;
int maxIndex = 0; //assume the first element is the largest
//Function to print the elements of an int array. The array to be printed and 520 | Chapter 8: Arrays and Strings
//the number of elements are passed as parameters. The parameter listSize for (index = 1; index < listSize; index++)
//specifies the number of elements to be printed. if (list[maxIndex] < list[index])
maxIndex = index;
void printArray(const int list[], int listSize)
{ return maxIndex;
int index; }
for (index = 0; index < listSize; index++)
cout << list[index] << " ";
//Function to copy some or all of the elements list2[], int tar, int numOfElements)
//of one array into another array. Starting at {
//the position specified by src, the elements for (int index = src; index < src +
//of list1 are copied into list2 starting at numOfElements; index++)
//the position specified by tar. The {
//parameter numOfElements specifies the list2[index] = list1[tar];
//number of elements of list1 to be copied into tar++;
//list2. Starting at the position specified by }
//tar, the list2 must have enough components }
//to copy the elements of list1. The following
//call copies all of the elements of list1
//into the corresponding positions in list2:

copyArray(list1, 0, list2, 0, numOfElements);

void copyArray(int list1[], int src, int


Array in Function
#include <iostream> //Initialize listB using the function initializeArray
using namespace std; initializeArray(listB, ARRAY_SIZE);
cout << "listB elements: ";
const int ARRAY_SIZE = 10;
//Output the elements of listB
void initializeArray(int [],int ); printArray(listB, ARRAY_SIZE);
void fillArray(int [],int ); cout << endl << endl;
void printArray(const int [],int); cout << "Enter " << ARRAY_SIZE<< " integers: ";
int sumArray(const int [],int );
int indexLargestElement(const int [],int); //Input data into listA using the
void copyArray(const int [], int [], int); //function fillArray
fillArray(listA, ARRAY_SIZE);
int main() cout << endl;
{ cout << "After filling listA, "<< "the elements are:"
int listA[ARRAY_SIZE] = {0}; //Declare the array listA << endl;
of 10 components and initialize each component to 0.
int listB[ARRAY_SIZE]; //Declare the array listB of 10
components.

cout << "listA elements: "; // Output the elements of


listA using the function printArray
printArray(listA, ARRAY_SIZE);

cout << endl;


//Output the elements of listA << listA[indexLargestElement(listA, ARRAY_SIZE)]
<< endl << endl;
printArray(listA, ARRAY_SIZE);
cout << endl << endl; //Copy the elements of listA into listB using the
//function copyArray
//Find and output the sum of the elements of listA copyArray(listA, listB, ARRAY_SIZE);
cout << "The sum of the elements of "<< "listA is: "
<< sumArray(listA, ARRAY_SIZE) << endl<< endl; cout << "After copying the elements "<< "of listA into listB," <<
endl<< "listB elements are: ";

//Find and output the position of the largest


//Output the elements of listB
//element in listA
printArray(listB, ARRAY_SIZE);
cout << "The position of the largest "
cout << endl;
<< "element in listA is: “
<< indexLargestElement(listA, ARRAY_SIZE)<< endl;
return 0;
}
//Find and output the largest element in listA
cout << "The largest element in "<< "listA is: "
void initializeArray(int list[], int cin>>list[index];
listSize)
}
{
int index;
void printArray(const int list[], int
listSize)
for(index = 0; index < listSize; {
index++)
int index;
list[index] = 0;
}
for(index = 0; index < listSize;
index++)
void fillArray(int list[], int listSize) cout<<list[index]<<" ";
{ }
int index;

for(index = 0; index < listSize;


index++)
int sumArray(const int list[], int listSize) for(index = 0; index < listSize; index++)
{ if(list[maxIndex] < list[index])
int index; maxIndex = index;
int sum = 0;
return maxIndex;
for(index = 0; index < listSize; index++) }
sum = sum + list[index];
void copyArray(const int listOne[], int listTwo[],
int listOneSize)
return sum;
{
}
int index;

int indexLargestElement(const int list[], int


listSize) for(index = 0; index < listOneSize; index++)
{ listTwo[index] = listOne[index];
int index; }
int maxIndex = 0;
One Dimensional Array (continued)
C Strings (Character Arrays)
• Character array - an array whose components are of type char.

• String - a sequence of zero or more characters enclosed in


double quote marks.

• C strings are null terminated (‘\0’).

• The last character in a string is the null character.


C Strings (Character Arrays) (continued)

• There is a difference between 'A' and "A“


• 'A' is the character A

• "A" is the string A

• Because strings are null terminated, "A" represents two


characters, 'A' and '\0‘

• Similarly, "Hello" contains six characters, 'H', 'e', 'l',


'l', 'o', and '\0'
C Strings (Character Arrays) (continued)

• Consider the statement


char name[16];
• Because C strings are null terminated and name has sixteen
components
• The largest string that can be stored in name is 15
• If you store a string of length, say 10 in name
• The first 11 components of name are used and the last 5 are left
unused
C Strings (Character Arrays) (continued)

• The statement
char name[16] = "John";
declares a string variable name of length 16 and stores
"John" in it
• The statement
char name[] = "John";
declares a string variable name of length 5 and stores "John"
in it
C Strings (Character Arrays) (continued)
String Comparison
1. C-strings are compared character by character using the
collating sequence of the system.
2. If we are using the ASCII character set
1. The string "Air" is smaller than the string "Boat“.
2. The string "Air" is smaller than the string "An“.
3. The string "Bill" is smaller than the string "Billy“.
4. The string "Hello" is smaller than "hello“.
char studentName[21];
char myName[16];
char yourName[16];

Statement Effect

strcpy(myName, "Ridhwan Razali"); myName = "Ridhwan Razali"


strlen("Ridhwan Razali"); Returns 13, the length of the string "Ridhwan Razali"
int len; Stores 9 into length
len = strlen("Rainy Day"); yourName = "Adam Azmi"
strcpy(yourName, "Adam Azmi"); studentName = "Adam Azmi"
strcpy(studentName, yourName); Returns a value < 0
strcmp("Sofia", "Adam"); yourName = "Faizul Hussein"
strcpy(yourName, "Faizul Hussein"); myName = "Aqilah Ahmad"
strcpy(myName, "Aqilah Ahmad"); Returns a value > 0
Reading and Writing Strings
String Input

i. Aggregate operations are allowed for string input.


ii. cin >> name; stores the next input string in name.
iii. Strings that contain blanks cannot be read using the
extraction operator >>
Reading and Writing Strings (continued)

To read strings with blanks, use the get function with an input
stream variable, such as cin:

cin.get(str, m+1);

• Stores the next m characters into str but the newline character is not
stored in str.

• If the input string has fewer than m characters, the reading stops at the
newline character
Reading and Writing Strings (continued)

String Output

• The statement cout << name; outputs the content of name


on the screen.
• The insertion operator << continues to write the contents of
name until it finds the null character.
• If name does not contain the null character, then we will see
strange output: << continues to output data from memory
adjacent to name until '\0' is found
#include <iostream> cout<<"Length of this string is:
"<<strlen("my name is Ridhwan");
#include <cstring>
cout<<endl;
using namespace std;

strcpy(str2, str1);
int main()
cout<<"str2 consist of: "<<str2;
{
char str1[30];
return 0;
char str2[15];
}
cin>>str1;
cout<<str1[15];
cout<<"Length of str1 is:
"<<strlen(str1)<<endl;
References
• C++ Programming Program Design Including Data Structures,
Eighth Edition, D.S.Malik
• Jeri R. hanly, Essential C++ for Engineers and Scientists, 2nd
Edition, Addison Wesley
• J. Glenn Brookshear, Computer Science An Overview, 8th
Edition, Pearson Addison Wesley

You might also like