Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "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 >>"— Presentation transcript:

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

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

3 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] = ; myList[9] = ;

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

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

6 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

7 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

8 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

9 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

10 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

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

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

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

14 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

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

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

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

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

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

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

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

22 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++;

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

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

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

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

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

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

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

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

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

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

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

34 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

35 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

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

37 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

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

39 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

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

41 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, ____, _____ );

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

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

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

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

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

47 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

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

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

50 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


Download ppt "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 >>"

Similar presentations


Ads by Google