CS1B – Introduction to Programming in C++Topic 4 - ArraysChapter 8 in the shrinkwrapChapter 9 in MalikCS1B – Saddleback CollegeWhy do we need Arrays?int main (){int item0, item1,item2;int sum;cout << “Enter 3 integers”;cin>> item0 >> item1>> item2;What do we do if we have tostore more than 1 piece of information of the same type?We declare different variables.cin>> item0 >> item1>> item2;sum = item0 + item1 + item2;cout << “The sum of the numbers = “ << sum <<endl;cout << “the numbers in reverse order are “;cout << item2 <<“ “ << item1 <<“ “<< item0 << endl;return 0;}2 of 34 Topic 4 - ch 8 - ArraysCS1B – Saddleback CollegeWhat are arrays? A collection of data of the same type– A special group of variables Arrays can hold – many pieces of data – all have the same data type and name, –but different values. –but different values. “Aggregate” data type– Means “grouping” Used for lists of like items– Test scores, temperatures, names, etc.– Avoids declaring multiple simple variables– Can manipulate "list" as one entity3 of 34 Topic 4 - ch 8 - ArraysCS1B – Saddleback CollegeSimple & Composite data types Simple Data Types– Data types that store only one piece of information– What we have been using thus far– Int, float double, char, long Structured / Composite Data types– Each data item is a collection of other data items4 of 34 Topic 4 - ch 8 - ArraysCS1B – Saddleback CollegeDeclaring an ArraySyntax:dataType arrayName[number_of_elements]; Declaring an array allocates the memory for the array Exampleint score[5]; // declares an array of 5 integers named scoreThe number of elements can be…– a literal (e.g. 5)int score[5]– Or a named constantconst int NUMBER_OF_TESTS = 5;int score[NUMBER_OF_TESTS];5 of 34Topic 4 - ch 8 - ArraysCS1B – Saddleback CollegeElements and Indexes Each individual item in an array is called an element– Each element has an index value associated with it An index is a number which indicates which value we are referring to Example:score[0] the first element in our arrayIndexscore[0] the first element in our array The first element is ALWAYS zero So if we have 5 elements our index values would be 0,1,2,3,4or score[0], score[1], score [2], score[3], score[4] Note: The brackets specify the size in the declaration and the subscript or index anywhere else6 of 34 Topic 4 - ch 8 - ArraysCS1B – Saddleback CollegeMemory and Arraysintscore[5];score[0];score[1];4 bytesscore[2];0,1,2,3,4 are in boundsin boundsin boundsin bounds7of 34 Topic 4 - ch 8 - Arraysintscore[5];score[1];score[5];First element always has an index of 0score[4];score[2];score[3];score [5] will not producea compile-time errorIt will produce a run-time error.0,1,2,3,4 are in boundsin boundsin boundsin boundsall other values are out of boundsout of boundsout of boundsout of boundsCS1B – Saddleback CollegeIndexesAn index can be anything that evaluates to an integer– A literal• e.g. score[5]– A variable or a constant•e.g. score[i]•e.g. score[i]– An expression• e.g. score[2 * i - j]8 of 34 Topic 4 - ch 8 - ArraysCS1B – Saddleback CollegeInitializing Arrays Simple variables can be initialized at declaration:int price = 0; // 0 is initial value of after declarationor equivalently in the codeint price;price = 0;Arrays can be initialized at declaration as well:This is not consideredgood style do not do this in this class pleaseArrays can be initialized at declaration as well:int item[3] = {2, 12, 1};or equivalently in the code :int item[3];item[0] = 2;item[1] = 12;item[2] = 1;9 of 34 Topic 4 - ch 8 - Arrays5-99CS1B – Saddleback CollegeInitializing Arrays (2) If you have more elements than values in the list then the extras at the end default to zeroint item[5]={2,12,1}; int item [5] = {2,12,1,0,0}; You can also initialize all the elements to 0 using this methodint item[5]={0}This is not recommended!This is okay!This is okay! If you have more values than elements specified then you will get a compiler errorint item[5]={2,12,1,2,9,5}; compiler error If you don’t specify the number of elements it will default to the number of values in the listint item[]={2,12,1,2,9,5}; children will default to 6 elements10 of 34 Topic 4 - ch 8 - ArraysThis is not recommended!This is okay!CS1B – Saddleback CollegeInitializing using a FOR loop#include <iostream>int main(){float gpa[5]; // an array holding 5 grade point averages – INP.& OUT.// load the array from the keyboardfor(int i= 0; i< 5; i++){cout << "Enter the gpa for student " << i+ 1 << ": ";cin>> gpa[i];This loopinitializes cin>> gpa[i];}// output the contents of the arraycout << "\n\nStudent Grade Point Averages\n";for(int i= 0; i< 5; i++){cout << "\nGPA for student " << i+ 1 <<": " << gpa[i];}return 0;}11 of 34 Topic 4 - ch 8 - ArraysNOTE: For Loops are very useful when you need to access every element in an array.This loopoutputs the arrayinitializes the arrayCS1B – Saddleback CollegeExampleint item[3];int sum;sum=0;for (int i= 0; i< 3 ; i++){cout << “Enter an integer: ”;cin>> item[i];Do a desk check with Inputs 5, 10, 15indexindexindexindex sum sum sum sum indindindindOutputOutputOutputOutputitemitemitemitem0 1 2cin>> item[i];sum = sum + item[i];}cout << “The sum of the numbers = “ << sum << endl;cout << “The numbers in reverse are: “;for (int i= 2 ; i > -1 ; i-- ){cout << item[i] << “, ”;}12 of 34What if we want to have 10 items? What changes will we have to make?CS1B – Saddleback CollegeDefining a Constant as Array Size Always use defined/named constant forarray size Example:const intAR_SIZE = 5;int score[AR_SIZE];Note that it must be declaredas an integer!– NOTE: Can’t do this with a variable Improves readability Improves versatility Improves maintainability13 of 36 Topic 4 - ch 8 - ArraysThe number of elementsmust be known at compile timeUsing a constant is considered a best practiceCS1B – Saddleback Collegeconst int AR_SIZE =10;int item[AR_SIZE];int sum;sum=0;for (int i = 0 ; i < AR_SIZE; i++){cout << “Enter an integer: ”;cin>> item[i];Instead of all those changes we can use a constant and just change the constant.Works well if theycin>> item[i];sum= sum + item[i];}cout << “The sum of the numbers = “ << sum <<endl;cout << “The numbers in reverse order are: “;for (int i = AR_SIZE-1; ind > -1 ; ind--){cout <<
View Full Document