Upload
hatuong
View
270
Download
3
Embed Size (px)
Citation preview
12/7/2016
1
CHAP 1
ONE DIMENSIONAL ARRAY (1D)
CSC138:
STRUCTURED
PROGRAMMING
LEARNING OBJECTIVES
Introduction to array
Array declaration and initialization
Input / Output values into array
Accessing elements of an array
Array operations using 7 basic algorithms ( min, max, count, total, average, sort (bubble), search (sequential))
Array and function: Passing Array as parameter to function & Passing Array element as parameter to function
12/7/2016
2
Motivations
Often you will have to store a large number of values during the execution of
a program.
Suppose, for instance, that you need to read one hundred numbers,
compute their average, and find out how many numbers are above the
average.
Your program first reads the numbers and computes their average, and then
compares each number with the average to determine whether it is above
the average.
The numbers must all be stored in variables in order to accomplish this task.
You have to declare one hundred variables and repeatedly write almost
identical code one hundred times.
From the standpoint of practicality, it is impossible to write a program this
way. So, how do you solve this problem?
3
LEARNING OBJECTIVES
Introduction to array
12/7/2016
3
Introduction to Array
• Array: a collection of a fixed number of components wherein all of the components have the same data type
• In a one-dimensional array, the components are arranged in a list form
• Syntax for declaring a one-dimensional array:
intExp evaluates to a positive integer
Introduction to Array
6
• Array is a data structure that represents a collection of the same types of data.
• All elements of an array is a set of continuous memory location.
5.6
4.5
3.3
13.2
4.0
34.33
34.0
45.45
99.993
111.23
double myList [10];
myList[0]
myList[1]
myList[2]
myList[3]
myList[4]
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
Element value Array element at
index 5
12/7/2016
4
EXAMPLEEXAMPLEEXAMPLEEXAMPLE
� stores many values in memory using one name with the same data type
� E.g: //to store 6 marks using one name (marks)
int marks[6]; //type is integer
� individual values are identified by number (index / subscript-> starts at zero (0) )
Mark1Mark1Mark1Mark1 Mark2Mark2Mark2Mark2 Mark3Mark3Mark3Mark3 Mark4Mark4Mark4Mark4 Mark5Mark5Mark5Mark5 mark6mark6mark6mark6marks
Mark1Mark1Mark1Mark1 Mark2Mark2Mark2Mark2 Mark3Mark3Mark3Mark3 Mark4Mark4Mark4Mark4 Mark5Mark5Mark5Mark5 mark6mark6mark6mark6marks
[0] [1] [2] [3] [4] [5] Index (use [ ] )
LEARNING OBJECTIVES
Array declaration and initialization
12/7/2016
5
Array Initialization
•You can initialize an array when you
declare it (just like with variables):
int n [5] = { } ;//initialize elements to zero
int foo[5] = { 1,8,3,6,12};
double d[2] = { 0.707, 0.707};
char s[ ] = { 'R', 'P', 'I' };
9
You don’t need to specify a size when initializing,
the compiler will count for you.
1
2
3
int marks [ 5 ] ;
for ( int i = 0; i < 5; i++)
{
cin>>marks [ i ];
}
Q: What is the value of each element in the array? Demonstrate the values by using an array diagram. (Assume the input are: 3, 7, 10, 5, 24)
Using loop to initialize
arrays
12/7/2016
6
• Used to store and manipulate strings
• Can be initialized using string literal.
• E.g:
– char string1 [10] = “first”;
– char string1 [ ] = “ first ” ;
Character Arrays
Initialization
Note:
• The size of the array is determined by the compiler
based on the length of the string (plus the string-
termination character called the null character).
• Null character is ‘ \0 ‘ (backslash followed by zero)
• Array string1 actually contains 6 elements
f i r s t \ 0string1
[ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ]
6 elements
Index /subscript
Character Arrays Initialization
12/7/2016
7
Array DeclarationSyntax:
datatype arrayRefVar[arraySize];
Example: double myList[10];
int age[3]; //to store age of 3 personsfloat salary[10]; //to store 10 salaries
char letter[5]; // to store 5 letters
13
C++ requires that the array size used to declare an array must be a
constant expression. For example, the following code is illegal:
int size = 4;
doublemyList[size]; // Wrong
But it would be OK, if size is a constant as follow:
const int size = 4;
doublemyList[size]; // Correct
Array Declaration
int hours[6];
const int NO_OF_EMPLOYEES = 6;
int hours[NO_OF_EMPLOYEES];
• The contents of each element are of the same type.• Could be an array of int, double, char, Q
This is SIZE of array
Data type is an INT
Must be in CONST1
2
12/7/2016
8
Exercise #1
Given the following declaration:
const int N = 50;
int A[N]; // assume initialization
�Assign 7 to the first element and -25 to
the last element in array A
15
Answer #1
Given the following declaration:
const int N = 50;
int A[N]; // assume initialization
�Assign 7 to the first element and -25 to the last element in array A
A[0] = 7;
A[N-1] = -25; // better than A[49] = -25
16
12/7/2016
9
Arrays Declaration
• Example:
int num[5];
17
dataType arrayName intExpr
Index = always start from ‘0’
� If you declare an array of n elements,
the last one is number n-1.
� If you try to access element number n
it is an error! (Out of bound)
Array Initializers
Declaring, creating, initializing in one
step:
dataType arrayName[arraySize] = {value0, value1, ..., valuek};
Example:
double myList[4] = {1.9, 2.9, 3.4, 3.5};
int n [ ] = { 1, 2, 3, 4, 5 };
char string1 [ ] = { ‘ f ‘ , ‘ i ‘, ‘ r ‘ , ‘ s ‘ , ‘ t ‘ , ‘ \0 ‘ } ;
18
12/7/2016
10
Indexed Variables
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arraySize-1.
Each element in the array is represented using the following syntax, known as an indexed variable:
arrayName[index];
For example, myList[9] represents the last element in the array myList.
19
Using Indexed Variables
After an array is created, an indexed variable can be
used in the same way as a regular variable. For
example, the following code adds the value in
myList[0] and myList[1] to myList[2].
myList[2] = myList[0] + myList[1];
20
12/7/2016
11
No Bound Checking
C++ does not check array’s boundary.
So, accessing array elements using
subscripts beyond the boundary (e.g.,
myList[-1] and myList[11]) does not does
cause syntax errors, but the operating
system might report a memory access
violation.
21
Declaring, creating, initializing
Using the Shorthand Notation
double myList[4] = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following statements:
double myList[4];myList[0] = 1.9;myList[1] = 2.9;myList[2] = 3.4;myList[3] = 3.5;
22
12/7/2016
12
CautionUsing the shorthand notation, you have to
declare, create, and initialize the array all in one
statement. Splitting it would cause a syntax
error. For example, the following is wrong:
double myList[4];
myList = {1.9, 2.9, 3.4, 3.5};
23
Implicit Size
C++ allows you to omit the array size
when declaring and creating an array
using an initializer. For example, the
following declaration is fine:
double myList[] = {1.9, 2.9, 3.4, 3.5};
C++ automatically figures out how many
elements are in the array.24
12/7/2016
13
Partial Initialization
C++ allows you to initialize a part of the
array. For example, the following
statement assigns values 1.9, 2.9 to the
first two elements of the array. The other
two elements will be set to zero. Note that
if an array is declared, but not initialized,
all its elements will contain “garbage”, like
all other local variables.
double myList[4] = {1.9, 2.9};25
Initializing Character
Arrays char city[] = {'D', 'a', 'l', 'l', 'a', 's'};
char city[] = "Dallas";
This statement is equivalent to the preceding statement, except that C++ adds the character '\0', called the null terminator, to indicate the end of the string, as shown in Figure 6.2. Recall that a character that begins with the back slash symbol (\) is an escape character.
26
city[0]
city[1]
'D' 'a' 'l' 'l' 'a' 's' '\0'
city[2]
city[3]
city[4]
city[5]
city[6]
12/7/2016
14
LEARNING OBJECTIVES
Input / Output
values into array
Input & Printing Character
Array For a character array, it can be printed and input using one print statement and one input statement. For example, the following code displays Dallas:
char city[] = "Dallas";
cin>>city;
cout << city;
28
12/7/2016
15
Input values into Array
29
Without arrayint list;
cin>> list
With array int list[10];int i;
cin>> list[1]
index
Solution:
for( int index=0;index<10;index++)cin>>list[index]
Output values of Array
30
Without arrayint list=3;
cout>> list
With arrayint list[10] ={1,2,3};int i;
cout<< list[3]
index
Solution:
for( int index=0;index<10;index++)cout<<list[index]
12/7/2016
16
Input & output array
• You can input using cin>> statement and display using cout<< statement.
• Example:
int age[100];
//input
for(int i=0; i<100; i++)
cin>>age[i];
//output
for(int i=0; i<100; i++)
cout<<age[i];
Printing Array - examplevoid displayMonths();
void main()
{
displayMonths();
getch();
}
void displayMonths()
{
//declare array
string month[12] = {"JAN", "FEB", "MAR",
"APR","JUNE","JULY","AUG","SEPT","OCT", "NOV", "DEC"};
//display contents of array
for(int x=0;x<12;x=x+1)
cout<<month[x]<<endl;
}
12/7/2016
17
Printing Array - exampleResults (displayed on the screen)
JAN
FEB
MAR
APR
JUNE
JULY
AUG
SEPT
OCT
NOV
DEC
Exercise #3
�Print out the 4th through 9th
elements, position 3 through
position 8
34
Answer:
for(i = 3; i < 9; i++)
cout << A[i] << " ";
cout << endl;
12/7/2016
18
Exercise #4
�Read in array elements with odd
indexes
35
Answer:
for(i = 1; i < N; i += 2)
cin >> A[i];
Exercise #5
� Print out all positive values one per line:
36
Answer:
for(i = 0; i < N; i++)
if(A[i] > 0)
cout << A[i] << endl;
12/7/2016
19
LEARNING OBJECTIVES
Accessing elements of an
array
Processing Arrays
�Consider the declaration
int list[100]; //array of size 100
int i;
�Using for loops to access array elements:
for (i = 0; i < 100; i++) //Line 1
//process list[i] //Line 2
�Example:
for (i = 0; i < 100; i++) //Line 1
cin >> list[i]; //Line 2
38
12/7/2016
20
Copying Arrays
Can you copy array using a syntax like this?
list = myList;
This is not allowed in C++. You have to copy individual elements from one array to the other as follows:
for (int i = 0; i < ARRAY_SIZE; i++)
{
list[i] = myList[i];
}39
• The values of an array can be accessed
by using the position of the stored value
• E.g:
marks[0]=10;
marks[1]=50;
marks[5]=77;
Accessing values in an array
10 50 26 86 56 77marks[0] [1] [2] [3] [4] [5]
12/7/2016
21
Accessing elements
41
Accessing Array
Components• Some other valid operation with arrays:
• numbers[0] = 20;
• numbers [a] = 75;
• b = numbers [a +2];
• numbers [1] = numbers [0] + numbers [2];
12/7/2016
22
Accessing Array Components
EXAMPLE
36 51 18 110 89 numbers
[0] [4][3][2][1]
temp = number [0];
number [0] = number [2];
number [2] = temp;
Answer:
numbers
[0] [4][3][2][1]
18 51 36 110 89
Exercise #6
const int SIZE = 10;
double gpa[SIZE];
int i;
cout << "Enter " << SIZE << " gpas: ";
for(i = 0; i < SIZE; i++)
cin >> gpa[i];
gpa[4] = 3.7;
� Based on the program above, illustrate how gpalook like in a memory.
44
12/7/2016
23
Answer #6
�Assume the input is 4.0 for everyone.
Below is a pictorial representation of
what gpa would look like.
45
LEARNING OBJECTIVES
Array operations using 7 basic algorithms
( min, max, count, total, average, sort (bubble),
search (sequential))
12/7/2016
24
• No assignment.
– Use a loop to copy elements from one array to
another. (no direct assignment operation)
• No comparisons.
– Use a loop to compare elements of two arrays.
(no direct comparison between arrays)
• No arithmetic operations.
– Use a loop to perform arithmetic operations between
two arrays.
(no direct arithmetic operations between arrays)
Array operation
• No assignment.
– Use a loop to copy elements from one array to
another. (no direct assignment operation)
Example:
int number[5];
int age[5];
age = number; //cannot do assignment
on arrays
Array operation
12/7/2016
25
• No comparisons.
– Use a loop to compare elements of two arrays.
(no direct comparison between arrays)
Example:
int number[5];
int age[5];
if (number == age) //cannot do
comparison on arrays
Array operation
• No arithmetic operations.
– Use a loop to perform arithmetic operations between
two arrays.
(no direct arithmetic operations between arrays)
Example:
int number[5];
int age[5];
number = age + 1; //cannot do any arithmetic
operations on arrays
Array operation
12/7/2016
26
• Subscription is one of the few operations that can be applied to arrays.
– Assignment, comparison, and arithmetic operations should be performed using the subscript/ index of each element of the arrays.
– Example:• number[2] = age[2];
• number[3]= number[1]
• if (number[0] == number[1])
Array operation
• Min
• Max
• Count
• Total
• Average
• Sort (bubble)
• Search (sequential)
• Min
• Max
• Count
• Total
• Average
• Sort (bubble)
• Search (sequential)
Array operations
using 7 basic
algorithms
Array operation
12/7/2016
27
53
Array operation
1
2
3
4
6 SearchingSearchingSearchingSearchingcin>>target
for(int index = 0; index < arraySize; index ++)
{
if(array[index] == target)
{
cout<<“target found at index:”<<index;
}
}
5 CountCountCountCountfor (index = 0; index < 10; index++)
{ if (number[index] % 2 == 0)
even++;
else
odd++; }
Array operation
54
7 SortingSortingSortingSorting
12/7/2016
28
Calculate the averagevoid displayAverage()
{
//declare variables and array
double total = 0.0;
double avg = 0.0;
int scores[5] = {98, 100, 56, 74, 35};
//accumulate scores
for(int x = 0; x<5; x= x+1)
total = total + scores[x];
//end for
//calculate average and display
avg = total/5.0;
cout<<"Average:"<<avg<<endl;
}
Calculate the averageResults (displayed on the screen)
Average:72.6
12/7/2016
29
Determining the highest valuevoid displayHighest()
{
//declare array
int dollars[5] = {25.6, 30.25, 50.0,
20.0,25.45};
//declare variables
double high = dollars[0]; //store first array value
//in the high variable
int x = 1; //begin search with the
//second value
//search for highest value
while(x<5)
{
if(dollars[x]>high)
high = dollars[x];
//end if
x = x+1;
}//end while
//display highest value
cout<<"Highest:"<<high<<endl;
}
Determining the highest valueResults (displayed on the screen)
Highest:50
12/7/2016
30
Access an array element using its
indexvoid displaySalary();
void main()
{
displaySalary();
getch();
}
void displaySalary()
{
//declare array
int code = 0;
int salaries[6] = {25000, 35000, 55000,
70000,80200, 90500};
//get code, then display corresponding salary
cout<<"enter the salary code (1-6):";
cin>>code;
if(code<1 || code>6)
cout<<"Invalid code"<<endl;
else
cout<<salaries[code - 1]<<endl;
}
Access an array element using its
indexResults (displayed on the screen)
enter the salary code (1-6):3
55000
12/7/2016
31
Exercise #7
• (Analyzing input) Write a program that
reads ten numbers, computes their
average, and finds out how many
numbers are above the average. Here
is a sample run of the program:
Enter ten numbers: 1 2.7 3 4 5 6 7 8 9 10
The average is 5.57
The number of values greater than the
average is 5
Array Operation:
Searching
Definition:
A key is a value that you are
looking for in an array.
Searching Type
BinaryLinear
12/7/2016
32
Introduction • The simplest type of searching process is
the sequential search/brute force/linear.
• In the sequential search, each element of the array is compared to the key, in the order it appears in the array, until the first element matching the key is found.
• If you are looking for an element that is near the front of the array, the sequential search will find it quickly.
• The more data that must be searched, the longer it will take to find the data that matches the key using this process.
64
•Sequential search algorithm
Array Operation:
Searching
12/7/2016
33
65
Sequential Search
• Consider the list unordered (not sorted)
• For a function to search for a targert we must specify
– name of the array to be searched
– length of the list (number of array elements)
– a flag parameter which tells whether or
not the search was successful
– an index value to be returned which tells where in the
list the item was found
scores
scores : 85 79 92 57 68 80 . . .
0 1 2 3 4 5 98 99
5
boolean & found
int & location
66
Sequential Search
• Algorithm example
• Note use of reference parameters for the found
flag and the location
void search (int list[ ], int length, int target,
boolean & found, int &location)
{ location = 0;
while ((location < length) && (target != list[location]))
location++;
found = (index < length); }
// if found == TRUE, location OK
. . .
search (scores, 5, 92, found_it, where_its_at);
scores : 85 79 92 57 68 80 . . .
0 1 2 3 4 5 98 99
12/7/2016
34
Arr[0] Arr[1] Arr[2] Arr[3] Arr[4]
3 0 8 9 16
Arr[5] ={3, 0, 8, 9, 16}
Example
Let say user want to find no 9.So, no 9 can
be found in the 4th location which is in
index 3.
int main()
{
int arrayA[10];
int i;
//assign the array values
arrayA[0]=20; arrayA[1]=40; arrayA[2]=100; arrayA[3]=80; arrayA[4]=10;
arrayA[5]=60; arrayA[6]=50; arrayA[7]=90; arrayA[8]=30; arrayA[9]=70;
cout<< "Enter the number you want to find (from 10 to 100 : ";
int key;
cin>> key;
int flag = 0; // set flag to off
for(i=0; i<10; i++) // start to loop through the array
{
if (arrayA[i] == key) // if match is found
{
flag = 1; // turn flag on
break ; // break out of for loop
}
}
if (flag) // if flag is TRUE (1)
cout<< "Your number is at subscript position " << i <<".\n";
else
cout<< "Sorry, I could not find your number in this
array."<<endl<<endl;
getch();
return 0;
}
Example 1
12/7/2016
35
#include<iostream.h>
#include<conio.h>
int linearSearch(int array[], int size,int searchKey)
{
for(int i=0; i<size;i++)
{
if(searchKey==array[i])
{
return i;
}
}
return -1;
}
int main()
{
int const max=6;
int a[]={9,6,8,90,56,78};
int getSearchNumber,exme ;
cout<<"Enter a Number here"<<endl;
cin>>getSearchNumber;
int result = linearSearch(a,max,getSearchNumber);
if(result>=0)
{
cout<<"The number "<<a[result]<<"======was found @ =====" <<result<< " index
"<<endl;
}
else
{
cout<<"Nothing Found"<<endl;
}
getch();
}
Example 2
Searching arrayvoid searchArray()
{
//declare variables and array
int count = 0; //counter variable
int searchFor = 0; //number to search for
int sales[5] = {45000, 35000, 60000,
70000};
//get number to search for
cout<<"enter the sales amount:";
cin>>searchFor;
//search for numbers greater than searchFor value
for(int x = 0;x<5;x=x+1)
if(sales[x]>searchFor)
count = count +1;
//end if
//end for
//display count
cout<<"Count: "<<count<<endl;
}
12/7/2016
36
Searching arrayResults (displayed on the screen)
enter the sales amount:40000
Count: 2
Sources from:
http://mathbits.com/MathBits/CompSci/Arrays
/Bubble.htm
Array Operation:
Sorting
Definition:
Sorting is the process of putting data in order; either
numerically or alphabetically.
12/7/2016
37
Introduction
• It is often necessary to arrange the elements in an array in numerical order from highest to lowest values (descending order) or vice versa (ascending order).
• If the array contains string values, alphabetical order may be needed (which is actually ascending order using ASCII values).
• The process of sorting an array requires the exchanging of values.
• While this seems to be a simple process, a computer must be careful that no values are lost during this exchange.
Introduction (cont…)• Consider the following dilemma:
• Suppose that grade[1] = 10 and grade[2] = 8 and you want to exchange their
values so that grade[1] = 8 and grade[2] = 10. You could NOT just do this:
grade[1] = grade[2];
grade[2] = grade[1]; // DOES NOT WORK!!!
In the first step, the value stored in grade[1] is erased and replaced
with grade[2].
The result is that both grade[1] and grade[2] now have the same
value. Oops! Then what happened to the value in grade[1]? It is lost!!!
• In order to swap two values, you must use a third variable, (a "temporary
holding variable"), to temporarily
hold the value you do not want to lose:
//swapping variables
temp = grade[1]; // holding variable
grade[1] = grade[2];
grade[2] = temp;
This process successfully exchanges, "swaps", the values of the two variables
(without the loss of any values).
12/7/2016
38
Introduction (cont…)• Ways to sort arrays:
• There are literally hundreds of different ways to sort arrays. The basic
goal of each of these methods is the same: to compare each array
element to another array element and swap them if they are in the
wrong position.
• The bubble sort is one of the easiest algorithms to understand and
we will begin our investigation with this sort.
• Examples of sorting technique:
– Bubble Sort
– Exchange Sort
– Selection Sort
– Insertion Sort
– Shell Sort
– Quick Sort
– Merge Sort
• Click here to see animation about sorting �
https://www.toptal.com/developers/sorting-algorithms
http://cs.usfca.edu/~galles/visualization/ComparisonSort.html
Bubble sort
• In the bubble sort, as elements are sorted they
gradually "bubble" (or rise) to their proper location in the
array, like bubbles rising in a glass of soda.
• The bubble sort repeatedly compares adjacent
elements of an array. The first and second elements are
compared and swapped if out of order. Then the second
and third elements are compared and swapped if out of
order. This sorting process continues until the last two
elements of the array are compared and swapped if out
of order.
12/7/2016
39
Bubble sort (cont…)
• When this first pass through the array is complete, the bubble sort returns to elements one and two and starts the process all over again. So, when does it stop?
• The bubble sort knows that it is finished when it examines the entire array and no "swaps" are needed (thus the list is in proper order). The bubble sort keeps track of occurring swaps by the use of a flag.
• The bubble sort is an easy algorithm to program, but it is slower than many other sorts. With a bubble sort, it is always necessary to make one final "pass" through the array to check to see that no swaps are made to ensure that the process is finished. In actuality, the process is finished before this last pass is made.
Bubble sort (cont…)
• The table below follows an array of numbers before,
during, and after a bubble sort fordescending order. A
"pass" is defined as one full trip through the array
comparing and if necessary,
swapping, adjacent elements. Several passes have to
be made through the array before it is finally sorted.
12/7/2016
40
C++ Programming: From Problem
Analysis to Program Design, Fifth
Edition
79
Example
C++ Programming: From Problem
Analysis to Program Design, Fifth
Edition
80
Example
12/7/2016
41
C++ Programming: From Problem
Analysis to Program Design, Fifth
Edition
81
Example
C++ Programming: From Problem
Analysis to Program Design, Fifth
Edition
82
Example
12/7/2016
42
83
Bubble Sort algorithm
Sorting an array
www.themegallery.com Company Logo
// This program uses the bubble sort algorithm to sort an
// array in ascending order.
#include <iostream>
using namespace std;
// Function prototypes
void sortArray(int [], int);
void showArray(int [], int);
int main()
{
int values[4] = {4,5,1,2};
cout << "The unsorted values are:\n";
showArray(values, 4);
sortArray(values, 4);
cout << "The sorted values are:\n";
showArray(values, 4);
system("pause");
return 0;
}
12/7/2016
43
Displaying array
www.themegallery.com Company Logo
// Definition of function showArray.
// This function displays the contents of array. elems is the
// number of elements.
void showArray(int array[], int elems)
{
for (int count = 0; count < elems; count++)
{
cout << array[count] << " ";
}
cout << endl;
}
Sorting an array
www.themegallery.com Company Logo
// Definition of function sortArray. This function performs an ascending
// order bubble sort on Array. elems is the number of elements in the
array.
void sortArray(int array[], int elems)
{
int swap=1, temp;
do
{
swap = 0;
for (int count = 0; count < (elems - 1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = 1;
}
}
} while (swap != 0);
}
12/7/2016
44
Sorting an arrayResults (displayed on the screen)
The unsorted values are:
4 5 1 2
The sorted values are:
1 2 4 5
Sorting an arrays of string
12/7/2016
45
Example #1 of sorting stringchar temp[10];
int iteration;
int index;
for (iteration = 0; iteration <4; iteration++)
{
for (index=0; index <3; index++)
if (tolower(name[index][0]) > tolower(name[index+1][0]))
{
strcpy(temp,name[index]);
strcpy(name[index],name[index+1]);
strcpy(name[index+1],temp);
}
}
for(int i=0;i<4;i++)
{
cout<<name[i]<<endl;
}
Example #2 of sorting string#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
char str[5][20], t[20];
int i, j;
cout<<"Enter any five string (name) : ";
for(i=0; i<5; i++)
{
cin>>str[i];
}
for(i=1; i<5; i++)
{
for(j=1; j<5; j++)
{
if(strcmp(str[j-1], str[j])>0)
{
strcpy(t, str[j-1]);
strcpy(str[j-1], str[j]);
strcpy(str[j], t);
}
}
}
cout<<"Strings (Names) in alphabetical order : \n";
for(i=0; i<5; i++)
{
cout<<str[i]<<"\n";
}
getch();
}
12/7/2016
46
91
String Library Routines
• String assignment
String comparison:
returns -1 if s1 < s2
returns 0 if they are equal
returns +1 if s1 > s2
Returns length
of the string
To sort a list of string into alphabetical order
92
int main()
{ char
name[5][100]={{'a','l','i'},{'y','a','n','a'},{'a','h','m','a','d'},{'c','i','n','d','y'
}, {'r','a','z','a','k'}};
cout<<"\nBefore Sort:";
for(int row=0;row<5;row++)
{
cout<<name[row]<<endl;
}
char tmp[100];
for(int outloop= 5; outloop>0; outloop--)
for(int inloop=0; inloop<outloop; inloop++)
{
if ( (strcmp(name[inloop],name[inloop + 1])>0) )
{ strcpy(tmp,name[inloop]);
strcpy(name[inloop],name [inloop+1]);
strcpy(name[inloop+1],tmp);
}
}
cout<<"\nAfter Sort:";
for(int row=0;row<5;row++)
cout<<name[row]<<endl;
}
12/7/2016
47
Exercise #8
1. Write a program to input 10 city names into an array and display back the content of the array.
2. Write a program to input 10 names into an array and display whose name is the longest.
(hint: Use strlen function)
3. Write a program to input 10 names and display how many names starts from ‘n’
93
LEARNING OBJECTIVES
Array and function: Passing Array as
parameter to function & Passing Array element
as parameter to function
12/7/2016
48
Array and function
• Basic function:
95
double tambah (double a, double b);
void main()
{
cout<<tambah(2,3);
}
double tambah (double a, double b);
{ double c;
c=a+b;
return c;
}
Function prototype
Function Called
Function definition
Actual parameter
Formal parameter
Array and 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
• Example :
void displayOutput( int list[],int size)
96
12/7/2016
49
Arrays as parameters
(function)• In order to accept arrays as parameters the only thing
that we have to do when declaring the function is to
specify in its parameters the element type of the array,
an identifier and a pair of void brackets [ ]. For
example, the following function:
void procedure (int arrayA[])
• accepts a parameter of type "array of int" called arrayA. In order to pass to this function an array
declared as:
int myArray [40];
• it would be enough to write a call like this:
procedure (myArray);
97
Functions Cannot Return a
Value of the Type Array
• C++ does not allow functions to
return a value of the type array
12/7/2016
50
Array and function
• Passing an array to function
99
void tambah(int list[],int size);
void main()
{ const int size=5;
int list[size]={1,2,3,4,5};
tambah(list,size);
}
void tambah(int list[],int size)
{int total=0;
for (int i=0;i<size;i++)
total=total+list[i];
cout<<total;
}
Function prototype
Function Called
Function definition
Array and function
• Passing an element from array to function
100
void ubah(int list);
void main()
{ const int size=5;
int list[size]={1,2,3,4,5};
ubah(list[1]);
}
void ubah(int list)
{int total=0;
total=list+100;
cout<<total;
}
Function prototype
Function Called
Function definition
12/7/2016
51
Example of passing
parameter� Here you have a complete example:
// arrays as parameters
#include <iostream>
void printarray (int arg[], int length)
{
for (int n=0; n<length; n++)
cout << arg[n] << " ";
cout << "\n";
}
int main ()
{
int firstarray[ ] = {5, 10, 15};
int secondarray[ ] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;
}
101
Output:
5 10 15
2 4 6 8 10
Other Example #include <iostream>
void display(int num[10]);
int main(){
int t[10], i;
for(i=0; i < 10; ++i)
t[i]=i;
display(t); // pass array t to a function
return 0;}
void display(int num[10]){
int i;
for(i=0; i < 10; i++)
cout << num[i] << ' ';
}
12/7/2016
52
Passing Array to a
function
void printArray(int list[], int arraySize);
void main()
{
int numbers[5] = {1,4,3,6,8}
printArray(numbers,5);
}
Passing Array to a function
void printArray(int list[], int arraySize)
{
for(int i = 0; i<arraySize; i++)
cout<<list[i]<<“ ”;
}
Output:
1 4 3 6 8
12/7/2016
53
Passing Array to a functionvoid displayArray(double []);
void main()
{
//declare array
double prices[4] = {25000, 35000, 55000,
70000};
//display the content of the array
displayArray(prices);
getch();
}
//*****function definition******
void displayArray(double dollars[])
{
for(int x = 0; x<4;x=x+1)
cout<<dollars[x]<<endl;
}
Passing Array to a function
Results (displayed on the screen)
25000
35000
55000
70000
12/7/2016
54
Note:
• Passing an array means that the
starting address of the array is passed
to the formal parameter.
• The parameter inside the function
references to the same array that is
passed to the function. No new arrays
are created. This is pass by reference
Pass by reference demovoid m(int, int []);
void main()
{ int x = 1;
int y[10];
y[0] = 1;
m(x,y);
cout<<“x is”<<x<<endl;
cout<<“y[0] is”<<y[0]<<endl;
}
12/7/2016
55
Pass by reference demo
void m(int number, int numbers[])
{
number = 1001;
numbers[0] = 5555;
}
Output:
x is 1
Y[0] is 5555
x is 1
Y[0] is 5555
Exercise #9
Write a program that can calculate and display total marks for
5 subjects.This program has 2 functions:
1) Function add () to save marks in array marks
2) Function Show() to display the all marks and total marks.
110
12/7/2016
56
Answer #9void add(double marks[],int size); // function prototype
void show(double marks[],int size);
void main() // main function
{
const int size=5;
double marks[size];
add(marks,size); // function call
show(marks,size); // function call
}
void add(double marks[],int size) //function header and definition
{
for (int i=0;i<size;i++)
cin>>marks[i];
}
void show(double marks[],int size)
{
double total=0;
for (int i=0;i<size;i++)
{ cout<<marks[i];
total=total+marks[i];
}
cout<<endl<<total;
}111
Array Examples
#include <iostream.h>
void main()
{
int a [10]; // Declare an array of 10 ints
int sum = 0; // Start the sum at 0
cout<<“Please enter 10 integers:”;
for (int i=0; i<n; i++)
{
cin>>a[i];
sum = sum + a[i]; // Add the next element to the sum
}
cout << sum << endl;
}
12/7/2016
57
Accessing elements in an array
(integer)
cout<<num [0]<<endl;
cout<<num [num [1] ]<<endl;
cout<<num [num [num [2]] ]<<endl;
3 2 5 9 15 4num
[ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ]
Tips 3: To sum the values stored in an array
sum=0;
for ( i=0; i<10; i++)
{
sum=sum + marks[i];
}
cout<< “The total values in the array is:”<<sum;
12/7/2016
58
Assign value in Arraystring names [4] = {“barb”, “Nancy”, “Bill”, “Samuel”}
names [1] = “Helen”
Assigns the name Helen to the second element in the names array,
replacing the name Nancy
int sub = 0;
while(sub<4)
{
states[sub] = “ ”;
sub = sub + 1;
}
Assigns the empty string to each element in the
states array
Assign value in Array
for(int x = 1; x<=3; x = x + 1)
nums[x - 1] = x*x;
Assigns the squares of the numbers from 1 through 3 to the nums array,
replacing the data stored in the arrray.
for(int x = 1; x<5; x = x + 1)
{
cout<<“enter price:”;
cin>>prices[x];
}
Assigns the values entered by the user in the prices array, replacing
data stored in the array
12/7/2016
59
Array of characters
• Applied string manipulation function to
store value in variable name.strcpy(name, “Ahmad”)
A h m a d name
[0] [3][2][1] [4]
Array of characters
• The string.h header file contains the string
manipulation function.
12/7/2016
60
Array of characters
• C++ sample program:
• The output: