Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC138: Structured Programming

Similar presentations


Presentation on theme: "CSC138: Structured Programming"— Presentation transcript:

1 CSC138: Structured Programming
Topic 1: 1D Array

2 Introduction to array Array declaration and initialization Input / Output values into array Accessing elements of an array

3 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?

4 Introducing Arrays Array is a data structure that represents a collection of the same types of data.

5 Array Initialization You can initialize an array when you declare it (just like with variables): int foo[5] = { 1,8,3,6,12}; double d[2] = { 0.707, 0.707}; char s[ ] = { 'R', 'P', 'I' }; You don’t need to specify a size when initializing, the compiler will count for you.

6 Declaring Array Variables
Syntax: datatype arrayRefVar[arraySize]; Example: double myList[10]; 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; double myList[size]; // Wrong But it would be OK, if size is a constant as follow: const int size = 4; double myList[size]; // Correct

7 Array declaration 1 2 int hours[6]; const int NO_OF_EMPLOYEES = 6;
This is SIZE of array Data type is an INT Must be in CONST 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, … 1 2

8 Arrays declaration Example: int num[5]; dataType arrayName intExpr

9 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.

10 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];

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.

12 Array Initializers Declaring, creating, initializing in one step:
dataType arrayName[arraySize] = {value0, value1, ..., valuek}; double myList[4] = {1.9, 2.9, 3.4, 3.5};

13 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;

14 CAUTION Using 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};

15 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.

16 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};

17 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.

18 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;

19 for(int i=0; i<10; i++) cout<<”*”; cout<<”#”;
cout<<”\n”; 2. for(int i=0; i<10; i++) { cout<<”*”; }

20 4. for(int i=0; i<10; i++) } cout<<”\n”;

21 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 cout<<age[i];

22 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]; }

23 Array operations using 7 basic algorithms
Min Max Count Total Average Sort (bubble) Search (sequential)

24 Quick Test Given the following program, show the values of the array in the following figure: int main() { int values[5] = {4}; for (int i = 1; i < 5; i++) values[i] = i; values[0] = values[1] + values[4]; }

25 What is the different between declaration, initialization and accessing?

26 Basic Operations double sales[10]; int index;
double largestSale, sum, average; //initializing an array: >>>>>> have another way to initial (think!!!!) for (index = 0; index < 10; index++) sales[index] = 0.0; //reading data into an array: cin >> sales[index] ; //printing an array: cout << sales[index] << “ ”; Basic Operations

27 Operations int i; double average, sum = 0; for(i = 0; i < 10; i++)
Total or Sum & Average Find summation of values in array Use a simple loop to add together array elements: int i; double average, sum = 0; for(i = 0; i < 10; i++) sum = sum+sales[i]; Q1: Find the summation of even number in array sales? Q2: Find the summation of odd index in Q3: Find the average of all values in sales?

28 Operations Use a simple loops to count element: Count int i;
int count = 0; for(i = 0; i < 10; i++) count = count+1; Q1: Count even number in array sales? Q2: Count number highest than 3? Count

29 Operations Use a simple loops find min and max elements: Min & Max

30 Definition: A key is a value that you are looking for in an array.
Searching Definition:  A key is a value that you are looking for in an array.

31 Introduction The simplest type of searching process is the sequential search.  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.

32 Searching Sequential search algorithm
C++ Programming: From Problem Analysis to Program Design, Fifth Edition

33 Example 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;

34 Operations Use a simple loops to search element in array: Search
Find the element input by the user. If element exist in array sales, display “found”. If not, display, “not found”. int i, count=0; double no; cin>no; for(i = 0; i < 10; i++){ if(no= =sales[i]) count++; } if(count==0) cout<<“not found”; else cout<<“found”; Search

35 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 5 boolean & found int & location scores :

36 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 :

37 Sorting an arrays of string

38 Buble 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. 

39 Buble 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.

40 Bubble Sort

41 Bubble Sort int a[6] = {84, 69, 76, 86, 94, 91}; int temp;
for(int i =5; i>=0; i--){ for(int j =0; j<i; j++){ if(a[j]<a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; }

42 Example C++ Programming: From Problem Analysis to Program Design, Fifth Edition

43 Example C++ Programming: From Problem Analysis to Program Design, Fifth Edition

44 Example C++ Programming: From Problem Analysis to Program Design, Fifth Edition

45 Example C++ Programming: From Problem Analysis to Program Design, Fifth Edition

46 Bubble Sort algorithm C++ Programming: From Problem Analysis to Program Design, Fifth Edition

47 PASSING ARRAY TO FUNCTION
Arrays can be passed as parameters to a function. Normally, two formal parameters is needed : Array name with data type specified The number of elements of the array being passed. FUNCTION DEFINITION returnType functionName(dataType arrayName[], int size){ } Example void display(int list[ ], int n){ } This function is to display all elements in array list with n size Note: a function can receive arrays as parameter but cannot return an array to the calling function

48 PASSING ARRAY TO FUNCTION
While calling the function need to pass just the array name of actual array belonging to the calling program and the number of elements in the array. FUNCTION CALL functionName(arrayName, size); Example int list[10]; If list is an array declared in the calling program, then invoking function display() by passing the array list is as follows: display(list, 10); Array name without square bracket

49 INPUT OUTPUT SUMMATION

50 Example of sorting string
char 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;

51 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

52 To sort a list of string into alphabetical order
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:"; C++ Programming: From Problem Analysis to Program Design, Fourth Edition

53 Exercise on c-String Write a program to input 10 city names into an array and display back the content of the array. Write a program to input 10 names into an array and display whose name is the longest. (hint: Use strlen function) Write a program to input 10 names and display how many names starts from ‘n’ C++ Programming: From Problem Analysis to Program Design, Fourth Edition

54 Array and function Passing Array as parameter to function
Passing Array element as parameter to function

55 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);

56 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; Output:

57 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] << ' '; }


Download ppt "CSC138: Structured Programming"

Similar presentations


Ads by Google