arrays basic

29
1 Arrays and Strings IIT [Delhi]

Upload: anshu-kumar

Post on 11-Nov-2015

232 views

Category:

Documents


0 download

DESCRIPTION

array basic in RDBMS

TRANSCRIPT

  • Arrays and StringsIIT [Delhi]

  • "All students to receive arrays!" reports Dr. Austin.scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99

  • Simple vs Structured Data TypesSimple data type => data element contains a single value Structured data type => a data element contains a collection of data values

  • ArraysArrays are Structured Data TypesThey have a means of accessing individual componentsValues can be retrieved from and stored in the structurescores : 85 79 92 57 68 800 1 2 3 4 5

  • One Dimensional ArrayStructured collection of componentsAll of the same typeStructure given a single nameIndividual elements accessed by index indicating relative position in collectionType of elements stored in an array can be just about anythingIndex of an array must be an integer

  • Use of Array for Our ProblemStore elements in array as read inGo back and access for deviations

  • Declaring ArraysSyntax: Data_type Array_name [constant];Note declaration from our example

  • Declaring ArraysExample specifies an arrayeach element is an integerthere is space for 100 elementsthe are numbered 0 through 99scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99

  • Accessing Individual ComponentsUse the name of the arrayFollowed by an integer expression inside the square brackets [ ]

    scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99max = scores[0]; for (x = 0; x < 100; x++) if (scores[x] > max) max = scores[x];Index can be: - constant - variable - expression MUST be an integer

  • Initializing Arrays in DeclarationsPossible to declare the size & initialize Possible to omit size at declarationCompiler figures out size of arrayint results [5] = {14, 6, 23, 8, 12 }float prices [ ] = { 2.41, 85.06, 19.95, 3.91 }

  • Arrays as ParametersThis is one task that CAN be done to the WHOLE arrayC++ always passes arrays by reference

  • Arrays as ParametersThe name of the array is a pointer constantThe address of the array is passed to the functionSize of the array also passed to control loop

  • Arrays as ParametersNote the empty brackets in parameter list A number can be placed here but it will be ignored

  • Initializing StringsWhen a character array is declared, it is legal to use the assignment operator to initialize Note : use of the = operator only legal for char array initializationBut : aggregate array assignment is NOT

  • String OutputStrings (character arrays) are handled differently than other types of arraysThis would NOT be allowed

    This is legal:int num_list [100]; . . . cout

  • String InputDeclare strings 1 element bigger than planned size to allow for \0

    When input takes place, C++ automatically places the \0 in memory at the end of the characters typed in

  • Using StringsInstead of hard coding file name for the open ( ) command, use a string variable, use keyboard entry with cin.getline()program more flexible, good for different filesifstream inFile; char fname[31]; cout ; cin.getline (fname, 30, \n); inFile.open (fname);

  • String Library RoutinesRecall that we could not use the aggregate assignment of one string to anotherC++ provides some string handling functions to do this (and other similar tasks)Found in or

  • Contrast/Compare Strings and C-StringsAssignment is OK string s; s = "hi mom";Comparison OK if (s < "geek") I/O allowed cin >> s; cin.getline(s,'\n'); cout
  • Working with C-StringsFunctions provided in #include

  • Another ProblemSome functions require C-strings as parametersThe .open() command for filesC-strings are terminated by the null character (character 0)Such functions are looking for thatString objects are built differently

  • Solving the File Open ProblemOne of the functions available for a string object will convert it to a C-StringThe function is c_str()Remember that string functions are called by usingThe variableThe member operator var.c_str()The name of the functionView example

  • Design ProblemConsider the task of keeping track of data about parts for manufacturepart number, description, qty needed, unit price

  • Design ProblemUse Parallel arraysOne array each for part num, descrip, qty, pricenth item in any one of the arrays associated with same nth item of all the arrays

  • Testing and Debugging HintsRange of legal index values is 0 to array_size - 1Individual elements of the array are of the component typeNo aggregate operations in arraysyou must write the code to do thisIf array parameter is incoming, specify formal parameter as const prevents function from modifying

  • Testing and Debugging HintsOmitting array size in declarationwhen array declared formal parameterwhen array initialized at declarationDont pass component when function expects entire arrayDeclare array size as max ever neededprocess only part of array which is usedPass array name and length to functions which process array or sub array

  • Testing and DebuggingBe sure to account for null character when you manipulate characters individually in a stringRemember proper use of the = correct for initialization at declarationtimeINCORRECT for aggregate assignmentAggregate input/output allowed for strings but NOT for other array types

  • Testing and DebuggingIf you use the >> for string input, make sure string is declared large enoughstring will have no white spacesThe >> operator stops at, but does not consume the first trailing white spacesuch as \n or a spaceThe cin.getline (whatever, 30, \n ) function stops when reading the \nconsumes the \nhas problems when \n is still in the input stream

  • Testing and DebuggingWhen using the strcpy ( ), make sure that the destination array is declared long enoughChoose test data carefully for string handling programsinclude strings that are too largeinclude strings with whitespace