310 likes | 426 Views
ㅎㅎ. Arrays. Handout2 References C++ Arrays. Handout 02. Exercise 1 1) Write a function that computes the value of the binomial coefficient. 2) Embed your function into a little program that reads two integers n and r from
E N D
ㅎㅎ Arrays • Handout2 • References • C++ Arrays
Handout 02 • Exercise 1 1) Write a function that computes the value of the binomial coefficient 2) Embed your function into a little program that reads two integers n and r from std::cin and writes the value of the binomial coefficient to std::cout
Handout 02 • Exercise 1
Handout 02 • Exercise 2 Write a function permutNumbers that prints all n! many permutations of the numbers 1 to n on std::out. Example: the output for permutNumbers(3) shall be: 123, 132, 213, 231, 312, 321
Handout 02 • Exercise 2
So far we looked at functions that get a copy of what the caller passed in. - This is call-by-value, as the value is what gets passed in (the value of a variable). We can also define functions that are passed a reference to a variable. - This is call-by-reference, the function can change a callers variables directly. Call-by-value vs Call-by-reference
A reference variable is an alternative name for a variable. A shortcut. A reference variable must be initialized to reference another variable. Once the reference is initialized you can treat it just like any other variable. Call-by-value vs Call-by-reference
[explain1] defining and using a reference [ex1] & is not the address operator as part of the type identifier & is the address operator &rodents representing the address of the variable to which rodents refers
[explain2] swapping with references and with pointers [ex2] rats = bunnies;
C++ Arrays indexing start at 0 !!!!!!! • The first element is the 0th element! • 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! • The element numbers are called subscripts. foo[i] Array name subscript A subscript can be any integer expression: These are all valid subscripts: foo[17] foo[i+3] foo[a+b+c]
Initialization Rules for Arrays //valid Ο • int cards[4] = {3, 6, 8, 10}; Ο • inthand[4]; //valid //invalid X • hand[4]; O //valid – hotelTips[0] = 5.0, hotelTips[1] = 2.5 • float hotelTips[5] = {5.0, 2.5}; Ο • long totals[500] = {0}; //valid • short things[] = {1, 5, 3, 8}; //valid Ο
[explain4] small arrays of integers [ex4] 7 * 20 = 140 8 * 30 = 240 9 * 5 = 45
[practice7] 2-D array [ex7]
[explain7] 2-D array [ex7]
Sorting of Arrays • Simple Algorithm for sorting arrays:Bubble-Sort • The basic idea is to repeatedly compare neighboring objects and to swap them if they are in the wrong order. • Elements move upwards to their final positions like air-bubbles in water
[practice8] Bubble Sort [ex8]
[explain8] Bubble Sort [ex8]