Home >Documents >Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static...

Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static...

Date post:20-Dec-2015
Category:
View:232 times
Download:7 times
Share this document with a friend
Transcript:
  • Slide 1
  • Computer programming1 Arrays
  • Slide 2
  • Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef
  • Slide 3
  • Computer programming3 Motivation Suppose we want to compute the average of 20 marks. Do we need to declare 20 variables mark1, mark2, , mark20 ? Do we need to write 20 cout s and 20 cins ? How about sorting a large number of ints? This is where arrays come in!
  • Slide 4
  • Computer programming4 Introduction to Arrays An array is a fundamental data structure used to store objects of a particular type in contiguous memory locations. Arrays allow us to randomly access this contiguous memory via indexing. There are essentially two ways to declare arrays in C++: statically and dynamically (until pointers are covered).
  • Slide 5
  • Computer programming5 Static Arrays Static array declaration typeName arrayName[sizeOfTheArray] typeName is the base type of the particular type of the elements of the array. Can be any type (primitive or user-defined) arrayName is the name of the array. Any valid C++ identifier sizeOfTheArray is the size or the capacity of the array The above declaration is equivalent to declaring sizeOfTheArray variables. Each variable is an indexed variable, a variable referenced using an index between 0 and sizeOfTheArray arrayName[0] is an indexed variable at the index 0 arrayName[1] is an indexed variable at the index 1 arrayName[sizeOfTheArray-1] is an indexed variable at the index sizeOfTheArray-1
  • Slide 6
  • Computer programming6 Static arrays - Declaration An array consisting of 5 variables of type int is declared: int score[5]; Such a declaration creates 5 int type variables which are accessed as score[0], score[1], score[2], score[3], score[4] l These are called indexed variables, also called subscripted variables. l The number in the brackets is called an index or subscript. l Array subscripts start at 0 and run to one less than size of the array, which is 4. l Be careful not to confuse the size in a declaration of an array with the index value in an array reference. int score[size]; score[index]; // 0
  • Computer programming9 Referencing and using arrays Array references may be used anywhere an ordinary variable is used. cin >> score[4] >> score[2]; cout
Popular Tags:
of 23/23
Computer programming 1 Arrays
Embed Size (px)
Recommended