Arrays
Real-world Scenario PLU code is missing for a product you are buying at the grocery counter. Associate may use a cheat sheet showing PLU code for each product – it works like an array.
Historical snippets … BASIC & FORTRAN : array index started at 1 COBOL? Modern languages use index starting at 0 How about Visual Basic?
Array index start with 0 or 1? "Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration." -- Stan Kelly-Bootle
Array index start with 0 or 1?
Scenario: Max price Let us say we want to read list of prices from the user and find the max price. Do we need an array?
Find max price: pseudocode item_number = 0 DOWHILE not eof item_number = item_number + 1 read item_price[item_number] ENDDO max_price_item = 0 max_price = 0.00 FOR i = 1 to item_number do IF max_price < item_price[i ] THEN max_price_item = i; max_price = item_price[i ]; ENDIF ENDFOR print max_price_item, max_price
Find max price: no arrays item_number = 0 max_price_item = 0 max_price = 0.00 DOWHILE not eof item_number = item_number + 1 read item_price IF max_price < item_price THEN max_price_item = i; max_price = item_price; ENDIF ENDDO print max_price_item, max_price
When arrays are needed? Only if we are going to use all those individual input values again.
Do we need arrays? Mortgage amortization table expansion – show the output for user-specified year
Do we need arrays? Compute total ticket sales/donations for the day
Do we need arrays? Find max, min, average air-fare paid by customers
Do we need arrays? Find the median air-fare paid by customers
Do we need arrays? Output all the airfare amounts in sorted order
Do we need arrays? Keeping track of your score at Golf course
Arrays Easy access Fixed size When bigger size is needed, we need to allocate new array and copy the current contents over. Use ArrayList for varying array sizes (not covered in this course)
Multi-dimensional arrays Students’ scores in one assignment int scores[student_index]
Multi-dimensional arrays Students’ scores in all assignments int scores[assignment_index][student_index]
Multi-dimensional arrays Students’ scores in all assignments for several sessions of that course int scores[session_index][assignment_index][student_index]