Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout << “Please enter grade 1”; cin >>

Slides:



Advertisements
Similar presentations
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Advertisements

1 Various Methods of Populating Arrays Randomly generated integers.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Array Must declare a variable to reference the array double [] mylist; // cannot double list[20]; Or double mylist[]; The declaration doesn’t allocate.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Chapter 8 Arrays and Strings
CSE202: Lecture 14The Ohio State University1 Arrays.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 7 Single-Dimensional.
Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II.
1 Chapter 7 Single-Dimensional Arrays. 2 Arrays Array is a data structure that represents a collection of the same types of data elements. A single-dimensional.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 8 Arrays and Strings
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
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.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
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.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
IAS 1313: OBJECT ORIENTED PROGRAMMING Week 3: Data Type, Control Structure and Array Prepared by: Mrs Sivabalan1.
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.
Searching Arrays Linear search Binary search small arrays
Passing Objects to Methods
Chapter 7: Single-Dimensional Arrays
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade.
Chapter 7 Single-Dimensional Arrays
Lecture 14 Searching and Sorting Richard Gesick.
The Ohio State University
Chapter 6 Arrays.
Chapter 7 Single-Dimensional Arrays
Chapter 7 Single-Dimensional Arrays
New Structure Recall “average.cpp” program
Chapter 6 Arrays.
Chapter 6 Arrays.
Chapter 7 Single-Dimensional Arrays
Chapter 7 Arrays Data structures Related data items of same type
Chapter 6 Arrays Solution Opening Problem
One-Dimensional Array Introduction Lesson xx
ARRAYS Lecture
Introducing Arrays Array is a data structure that represents a collection of the same types of data.
Chapter 5 Arrays Introducing Arrays
Review for Final Exam.
Lecture 11 Searching and Sorting Richard Gesick.
Review of Arrays and Pointers
Chapter 7 Single-Dimensional Arrays
Chapter 7 Single-Dimensional Arrays
24 Searching and Sorting.
Data Structures (CS212D) Week # 2: Arrays.
Chapter 7 Single-Dimensional Arrays and C-Strings
Review for Final Exam.
Chapter 6 Arrays.
Arrays Lecture 11.
Single-Dimensional Arrays chapter6
CS150 Introduction to Computer Science 1
Single-Dimensional Arrays
CS150 Introduction to Computer Science 1
Chapter 6 Arrays.
CS150 Introduction to Computer Science 1
Chapter 7 Single-Dimensional Arrays
Chapter 7 Single-Dimensional Arrays
Presentation transcript:

Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout << “Please enter grade 1”; cin >> grade1; cout << “Please enter grade 2”; cin >> grade2; cout << “Please enter grade 3”; cin >> grade3; cout << “Please enter grade 4”; cin >> grade4; cout << “Please enter grade 5”; cin >> grade5; cout <<“Thank you”; cout << “The grades are ” << grade1 << “ ” << grade2 << “ ” << grade3 << “ ” << grade4 << “ ” << grade5 << endl; double avg = (grade1 + grade2 + grade3 + grade4 + grade5)/5.0; cout << “Their average is ” << avg;

Chapter 7 Arrays An array is a data structure that represents a collection of the same type of data (homogeneous data). Declaring an array: datatype arrayRefVar[size]; Example: //declare an array of double named myList // with room for 10 elements double myList [10];

double myList[10]; myList[0] references the first element in the array. myList[9] references the last element in the array. Assigning values to array elements: myList[0] = 5.6; myList[1] = 4.5; myList[2] = 3.3; myList[3] = 13.2; myList[4] = 4.0; myList[5] = 34.33; myList[6] = 34.0; myList[7] = 45.45; myList[8] = 99.993; myList[9] = 111.23;

The array elements are accessed through the index The array elements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayRefVar.length-1. In our example, myList holds ten double values and the indices are from 0 to 9. Each element in the array is represented using the following syntax, known as an indexed variable: myList[0] = 0; myList[1] = 4; myList[2] = 8; … myList[9] = 36; First element is at index 0 and last element is at index 9 (one less than the number of elements) Exercise: Declare an array of type char called firstName And create the array so it contains exactly the number of letters in your first name.

This shorthand notation is equivalent to the following statements: 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]; Declaring, and initializing in one step: double theList[4] = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double theList[4]; theList[0] = 1.9; theList[1] = 2.9; theList[2] = 3.4; theList[3] = 3.5;

Exercise Fill in the values of the elements of this array. A int A[5]; A[2] = A[0] + A[1]; A[3] = A[1] + A[2]; A[4] = A[2] + A[3]; A 0 1 2 3 4

Solution Fill in the values of the elements of this array. A int A[5]; A[2] = A[0] + A[1]; A[3] = A[1] + A[2]; A[4] = A[2] + A[3]; A 1 2 3 5 8 0 1 2 3 4

What is the output? int first[8]; int second[8]; int third[8]; for (int j = 0; j < 8; j++) { first[j] = 2*j; second[j] = j + first[j]; third[j] = first[j] *second[j]; } //for j for (int k = 0; k < 8; k++) cout << third[k]) << endl; } //for k

Exercise Can you find a way to print out all of the elements of the given array A without us having to write the cout statement lots of times? A 1 2 3 5 8 0 1 2 3 4

Exercise Can you find the average temperature for the week without having to write out a separate addition for each element? temperature 65 68 64 68 70 68 70 0 1 2 3 4 5 6

Average Temperature double sum = 0.0; for(int i = 0; i < 7; i++) sum = sum + temperature[i]; double avg = sum / 7.0; cout << “Week average “ << avg;

Exercise Write a loop to find the values of the highest temperature and the lowest temperature for the week.

Solution // Initialize double max = temperature[0]; double min = temperature[0]; for(int i = 1; i < 7; i++) { if(temperature[i] > max) max = temperature[i]; if(temperature[i] < min) min = temperature[i]; }

Exercise Assume that cards is an array of 52 type int values that has been created. Assume all elements have been assigned a value. Write C++ statements to count how many even values are stored in the array. Declare needed variables

Solution int numEvens = 0; for(int i = 0; i < 52; i++) { if(cards[i] % 2 == 0) numEvens++; }

Exercise Assume that an array is created. int list[10]; Write a loop to fill the array by prompting the user to enter an integer and assigning it into the next un-filled array slot.

Solution int list[10]; int n; for(int i = 0; i < 10; i++) { cin >> n; list[i] = n; }

Index Out of Bounds Create & initialize an array. int cards[5] = { 7, 10, 4, 8, 9 }; Each of these statements will crash your program with an array index out of bounds exception cout << cards[5]; cards[6] = cards[6] + 1; cards[-1] = 0; cards[-7] = 10;

Exercise Assume two arrays of integers named a and b are created and initialized. Assume both arrays have the same length. (length) Write a loop to count how many corresponding pairs of elements are identical. If a[0] equals b[0] increase count by one Etc…

Solution int count = 0; for(int i = 0; i < length; i++) if(a[i] == b[i]) count = count + 1;

Exercise Given that m is an array of type char with length elements that has been initialized. Write C++ statements to count how many times the letters X, Y, or Z are found in array m.

Solution Write C++ statements to count how many times the letters X, Y, or Z are found in array m. int count = 0; for(int i = 0; i < length; i++) if(m[i] == ‘X’ || m[i] == ‘Y’ || m[i] == ‘Z’) count++;

Exercise Given that m is an array of type char elements of size length that has been initialized. Write C++ statements to declare and create a new array named copyOfM that is a duplication of the array named m.

Solution char copyOfM[length]; for(int i = 0; i < length; i++) copyofM[i] = m[i];

findSum Function Write a function named findSum that accepts an array of integer values (assuming all elements are initialized) and return the integer sum of all elements in the given array.

findSum Method int findSum(int w[],int length) { int sum = 0; for(int i = 0; i < length; i++) sum = sum + w[i]; return sum; }

Calling findSum int findSum(int [], int) int main() { int grades[4] = {89, 73, 90, 94}; //call the method findSum with grades int sum = findSum(grades, 4); cout << “Grade Sum: “ << sum; return 0; } int findSum(int w[], int length) int sum = 0; for(int i = 0; i < length; i++) sum = sum + w[i]; return sum;

Exercise Write a method named countN that receives an array of type int values , the length of the array and a given integer value n, and return the number of times where the given value n appears in the given array.

Solution int countN(int data[],length, int n) { int numFound = 0; for(int i = 0; i < length; i++) if(data[i] == n) numFound++; return numFound; }

Exercise Write a function named indexOfFound that receives an array of type int elements, the size of the array and a target integer value t, and returns the index of such an integer value if t is in the array; otherwise return -1. Example: int list[5] ={1, 2, 3, 4, 5}; Then int index=indexOfFound(list, 5, 2); index=indexOfFound(list, 5, 6);

Solution int indexOfFound (int array[], int length, int t) { int s = -1; for (int i = 0; i < length; i++) if (array[i] == t) s = i; return s; }

Exercise Write a function named compare that receives two arrays of type char values, and returns the type bool value true if two arrays are the same; otherwise, returns false.

Solution bool compare(char list1[], char list2[], int length) { // innocent until proven guilty bool sameArray = true; for (int i=0; I < length; i++) if (list1[i] != list2[i]) sameArray = false; return sameArray; }

We can pass arrays to functions, but it’s different from passing “primitive” parameters. For a parameter of a primitive type value (int, float, double, etc.), the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method. pass-by-value For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument. pass-by-reference

What is the output? int main(String[] args) { int x = 1; int length = 5 int y [length]= {1, 2, 3, 4, 5}; int a = 0; cout << "x is " << x; for (a = 0; a < length; a++) cout << "y[" << a << "] = " << y[a]); effect(x, y); for (a = 0; a < 5; a++) } //main void effect(int num, int nums[]) num = 1001; nums[0] = 5555; nums[3] = 3333; } //effect

What is the Output? void foo(int [], int, int); void printArray(int [], int); int main() { int a[5] = { 1, 2, 3, 4, 5 }; cout << “Before” << endl; printArray(a); foo(a, 5, 2); cout << “After” << endl; } void foo(int g[], int length, int n) for(int i = 0; i < length; i++) g[i] = g[i] * n; void printArray(int[] w, int size) for(int i = 0; i < size; i++) cout << w[i] << endl;

Swap Given two integer variables a and b. How can you swap their values? Before example a = 5; b = 9; After a will be 9 and b will be 5

Swap Use a third integer variable int temp; temp = a; a = b; b = temp;

Using swapFirstLast Contents of A after the call… 1, 4, 3, 2, 5 int[] a = { 5, 4, 3, 2, 1 }; swapFirstLast(a, 5); Contents of A after the call… 1, 4, 3, 2, 5

Solution void swapFirstLast(int[] data, int length) { int temp; temp = data[0]; data[0] = data[length-1]; data[length-1] = temp; }

Exercise Write a function named swap that receives an array of type int values and integer index i and integer index j, and swaps the values contained in array slots with indices i and j. Example: int A[5] = { 5, 4, 3, 2, 1 }; // Swap values in slots #0, #4 swap(A, 0, 4); Contents of A after the call… 1, 4, 3, 2, 5 What would swap the 2nd with 4th ? swap(A, ____, _____ );

Solution void swap(int data[], int i, int j) { int temp; temp = data[i]; data[i] = data[j]; data[j] = temp; }

What does this code do? int findIndex(int [], int); int main() { int a[6] = {10, 8, 5, 2, 6, 13 }; int x = findIndex(a, 5); int y = findIndex(a, 4); int z = findIndex(a, 3); return 0; } int findIndex(int[] data, int startAt) int large = data[startAt]; int index = startAt; for(int i = 0; i < startAt; i++) if(data[i] > large) large = data[i]; index = i; return index;

What does this code do? int main() { int a[6] = {10, 8, 5, 2, 6, 13}; int x = findIndex(a, 5); swap(a, 5, x); //the array a={10, 8, 5, 2, 6 ,13} x = findIndex(A, 4); swap(a, 4, x); //the array a={6, 8, 5, 2, 10, 13} return 0; }

What does this code do? int main() { int size = 5; int a[size] = {10, 8, 5, 2, 6, 13}; int x; for(int i = size - 1; i > 0; i--) x = findIndex(a, i); if (x != i) swap(a, i, x); } return 0;

Searching Arrays Linear search – simply starts at the beginning and looks at each element to see if it matches the search item. int linearSearch(const int list[], int size, int item) { int i = 0; while (i < size && list[i] != item) i++; if (i == size) i = -1 return i }

Binary Search The array must be sorted from smallest to largest high starts as the last index in the array; low starts at 0 A midpoint is calculated (high + low)/2 and the search item compared to it. If the item is smaller than the element at the midpoint, high is set to mid -1 If the item is larger than the element at the midpoint, low is set to mid + 1 Mid is recalculated and the comparison done again until they match or high < low

Binary Search int binarySearch (const int list[], int size, int item) { int low=0; int high = size-1; int mid = (low + high) / 2; while (high >= low && item != list[mid]) if (item < list[mid]) high = mid – 1; else low = mid + 1; mid = (low + high) / 2; } if (item != list[mid]) mid = -1; return mid;

Selection Sort Sorts elements of array into order of smallest to largest. At each step find the largest value among the portion of the array not yet sorted. Swap that largest value with the element with the largest index among the portion of the array not yet sorted.

Selection Sort void selectionSort (double list[], int size) { for (int i = 0; i < size; i++) double currentMin = list[i]; int currentMinIndex = i; for (int j = i+1; j < size; j++) if (currentMin > list[j]) currentMin = list[j]; currentMinIndex = j; } } // for j if(currentMinIndex != i) list[currentMinIndex] = list[i]; list[i] = currentMin; } // for i