CSC138: Structured Programming

Slides:



Advertisements
Similar presentations
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Advertisements

1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 7 Single-Dimensional.
Chapter 8 Arrays and Strings
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 6 Arrays.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 7 Single-Dimensional Arrays and C-Strings.
Chapter 5: ARRAYS ARRAYS. Why Do We Need Arrays? Java Programming: From Problem Analysis to Program Design, 4e 2  We want to write a Java program that.
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Arrays Chapter 7.
Arrays.
EGR 2261 Unit 9 One-dimensional Arrays
An Introduction to Programming with C++ Sixth Edition
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
Chapter 6 Arrays DDC 2133 Programming II.
Chapter 6 Arrays Lecturer: Mrs Rohani Hassan
Chapter 7 Part 1 Edited by JJ Shepherd
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
New Structure Recall “average.cpp” program
Arrays in C.
Siti Nurbaya Ismail Senior Lecturer
Arrays … The Sequel Applications and Extensions
Arrays, For loop While loop Do while loop
Chapter 7 Single-Dimensional Arrays
Chapter 6 Arrays Solution Opening Problem
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
C Arrays.
Arrays Skill Area 315 Part A
Arrays Kingdom of Saudi Arabia
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Chapter 5 Arrays Introducing Arrays
EKT150 : Computer Programming
Review for Final Exam.
Arrays Outline Introduction Arrays Declaring Arrays
Chapter 7 Single-Dimensional Arrays and C-Strings
Review for Final Exam.
Chapter 6 Arrays.
7 Arrays.
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays Arrays A few types Structures of related data items
Introducing Arrays Array is a data structure that represents a collection of the same types of data. From resourses of Y. Daniel Liang, “Introduction.
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

CSC138: Structured Programming Topic 1: 1D Array

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

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?

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

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.

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

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

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

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.

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

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.

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

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;

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

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.

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

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.

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;

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

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

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

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

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

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

What is the different between declaration, initialization and accessing?

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

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?

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

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

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.

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.

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

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;

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

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 : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99

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

Sorting an arrays of string

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. 

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.

Bubble Sort

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

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

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

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

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

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

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

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

INPUT OUTPUT SUMMATION

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;

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

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

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

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

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: 5 10 15 2 4 6 8 10

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