CSIS 113A Lecture 10 Arrays Glenn Stevenson CSIS 113A MSJC.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-1 Concordia University Department of Computer Science and Software Engineering COMP345.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Introduction to Arrays.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Arrays Programming COMP102 Prog. Fundamentals I: Arrays / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g.,
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
Topic 9A – Arrays as Function Arguments. CISC105 – Topic 9A Arrays as Function Arguments There are two ways to use arrays as function arguments: Use an.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
1 Arrays & functions Each element of an array acts just like an ordinary variable: Like any ordinary variable, you can pass a single array element to a.
Arrays.
Templates Overload function: define more than one function With same function name Different parameter type Different type Different number of parameter.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
 CS105 C++ Lecture 2 Arrays. Parameter passing  2 types  Pass-by-value  Pass-by-reference 2.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Chapter 7 Arrays. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays.
Arrays One-Dimensional initialize & display Arrays as Arguments Part I.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
C/C++ Basics (IV) Array, Pointers and Dynamic Arrays Berlin Chen 2003 Textbook: 1. Walter Savitch, “Absolute C++,” Addison Wesley, 2002 開發代理 2. Walter.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Arrays Arrays in C++ An array is a data structure which allows a collective name to be given to a group of elements which all have.
CSIS 113A Lecture 8 Parameters.  Two methods of passing arguments as parameters  Call-by-value  ‘copy’ of value is passed  Call-by-reference  ‘address.
Defining a 2d Array A 2d array implements a MATRIX. Example: #define NUMROWS 5 #define NUMCOLS 10 int arr[NUMROWS][NUMCOLS];
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Static arrays.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Copyright Curt Hill Arrays in C/C++ More on usage.
Function Overloading Two different functions may have the same name as long as they differ in the number or types of arguments: int max(int x, int y) and.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
CSCI 161 Lecture 14 Martin van Bommel. New Structure Recall “average.cpp” program –Read in a list of numbers –Count them and sum them up –Calculate the.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
1 Understanding Arrays and Pointers COSC1567 C++ Programming Lecture 2.
© Janice Regan, CMPT 128, January CMPT 128: Introduction to Computing Science for Engineering Students Introduction to Arrays.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
L what is a void-function? l what is a predicate? how can a predicate be used? l what is program stack? function frame? l what’s call-by-value? l what’s.
ARRAYS (C) KHAERONI, M.SI. OVERVIEW Introduction to Arrays Arrays in Functions Programming with Arrays Multidimensional Arrays.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
1 Principles of Computer Science I Honors Section Note Set 3 CSE 1341.
L what is a void-function? l what is a boolean function? l is it possible for a function to have no parameters? l what is program stack? function frame?
Review 1.
Lecture 11 Multi-dimensional Arrays
Chapter 7 Arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Advanced Program Design with C++
Previous Lecture Review
Review of Everything Arrays
CMSC202 Computer Science II for Majors Lecture 03 – Arrays and Functions Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Chapter 7 Arrays. Chapter 7 Arrays Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional.
Presentation transcript:

CSIS 113A Lecture 10 Arrays Glenn Stevenson CSIS 113A MSJC

What is an array A contiguous group of homogeneous elements Might be easier to think of it as a series of like data that can be accessed using one name ie. Grades, Scores, temperatures This our first aggregate type –Combine atomic types to make a new type Atomic, int, float, double, etc Glenn Stevenson CSIS 113A MSJC

Array Depicted Glenn Stevenson CSIS 113A MSJC

Declaring Arrays  Declare the array  allocates memory int score[5];  Declares array of 5 integers named ‘score’  Similar to declaring five variables: int score[0], score[1], score[2], score[3], score[4]  Individual parts called many things:  Indexed or subscripted variables  ‘Elements’ of the array  Value in brackets called index or subscript  Numbered from 0 to size - 1 Glenn Stevenson CSIS 113A MSJC

Accessing Arrays  Access using index/subscript  cout << score[3];  Note two uses of brackets:  In declaration, specifies SIZE of array  Anywhere else, specifies a subscript  Size, subscript need not be literal  int score[MAX_SCORES];  score[n+1] = 99;  If n is 2, identical to: score[3] Glenn Stevenson CSIS 113A MSJC

Access Depicted Glenn Stevenson CSIS 113A MSJC

Arrays & Memory Glenn Stevenson CSIS 113A MSJC

Initialize At Declaration Just like any other variables, arrays can be initialized at declaration time. –A little trickier Glenn Stevenson CSIS 113A MSJC

A simple program Glenn Stevenson CSIS 113A MSJC #include using namespace std; int main() { double d[] = {3.44, 2.22, 1.22, 5.55, 1.89, 99.99}; for(int i = 0; i < 6; i++) cout << d[i] << endl; }

for-loops with Arrays  Natural counting loop  Naturally works well ‘counting thru’ elements of an array  Example: for (idx = 0; idx<5; idx++) { cout << score[idx] << “off by “ << max – score[idx] << endl; }  Loop control variable (idx) counts from 0 – 5 Glenn Stevenson CSIS 113A MSJC

Major Array Pitfall  Array indexes always start with zero!  Zero is ‘first’ number to computer scientists  C++ will ‘let’ you go beyond range  Unpredictable results  Compiler will not detect these errors!  Up to programmer to ‘stay in range’ Glenn Stevenson CSIS 113A MSJC

Major Array Pitfall Example  Indexes range from 0 to (array_size – 1)  Example: double temperature[24]; // 24 is array size // Declares array of 24 double values called temperature  They are indexed as: temperature[0], temperature[1] … temperature[23]  Common mistake: temperature[24] = 5;  Index 24 is ‘out of range’!  No warning, possibly disastrous results Glenn Stevenson CSIS 113A MSJC

Defined Constant as Array Size  Should try to use defined/named constant for array size  Example: const int NUMBER_OF_STUDENTS = 5; int score[NUMBER_OF_STUDENTS];  Improves readability  Improves versatility  Improves maintainability Glenn Stevenson CSIS 113A MSJC

Uses of Defined Constant  Use everywhere size of array is needed  In for-loop for traversal: for (idx = 0; idx < NUMBER_OF_STUDENTS; idx++) { // Manipulate array }  In calculations involving size: lastIndex = (NUMBER_OF_STUDENTS – 1);  When passing array to functions (later)  If size changes  requires only ONE change in program! Glenn Stevenson CSIS 113A MSJC

Filling An Array Glenn Stevenson CSIS 113A MSJC #include #include using namespace std; int main() { int array[20]; srand(time(0)); // Fill the array!! for(int i = 0; i < 20; i++) array[i] = rand() % 101; // print the array for(int i = 0; i < 20; i+=2) cout << array[i] << "\t" << array[i+1] << endl; return 0; }

Indexed Variables as Arguments  Indexed variable handled same as simple variable of array base type  Given this function declaration: void myFunction(double par1);  And these declarations: int i; double n, a[10];  Can make these function calls: myFunction(i);// i is converted to double myFunction(a[3]);// a[3] is double myFunction(n);// n is double Glenn Stevenson CSIS 113A MSJC

Subtlety of Indexing  Consider: myFunction(a[i]);  Value of i is determined first  It determines which indexed variable is sent myFunction(a[i*5]);  Perfectly legal, from compiler’s view  Programmer responsible for staying ‘in-bounds’ of array Glenn Stevenson CSIS 113A MSJC

Entire Arrays as Arguments  Formal parameter can be entire array  Argument then passed in function call is array name  Called ‘array parameter’  Formal parameter entire array is placed Glenn Stevenson CSIS 113A MSJC void foo(int ar[]) { } Int main() { int myArray[5]; foo(myArray); return 0; }

Arguments To Functions Arrays get passed to function by reference. – In actuality, it is a copy of the base address (Address of Element 0) of the array that gets passed. Glenn Stevenson CSIS 113A MSJC

#include #include using namespace std; void fillArray(int ar[], int size); void printArray(int ar[], int size); int main() { int array[20]; fillArray(array, 20); printArray(array, 20); return 0; } void fillArray(int ar[], int size) { srand(time(0)); // Fill the array!! for(int i = 0; i < size; i++) ar[i] = rand() % 101; } void printArray(int ar[], int size) { for(int i = 0; i < size; i+=2) cout << ar[i] << "\t" << ar[i+1] << endl; }

Depicted Glenn Stevenson CSIS 113A MSJC

Passing Array Pitfall It is possible to write pass the end of the array –BAD things may happen Compiler will issure NO warnings or errors –Could cause your program to crash unexpectedly –Best to see example Glenn Stevenson CSIS 113A MSJC

#include #include using namespace std; void fillArray(int ar[], int size); int main() { int array[20]; fillArray(array); return 0; } void fillArray(int ar[]) { srand(time(0)); // Fill the array!! for(int i = 0; i < 21; i++) ar[i] = rand() % 101; }

Pass the Size In C++ when you pass an array, you should also pass the size so the function knows how many it can act on. –Makes function generic Glenn Stevenson CSIS 113A MSJC void fillArray(int ar[], int size) { }

Glenn Stevenson CSIS 113A MSJC #include #include using namespace std; void fillArray(int ar[], int size); void printArray(int ar[], int size); int main() { int array[20]; fillArray(array, 20); printArray(array, 20); return 0; } void fillArray(int ar[], int size) { srand(time(0)); // Fill the array!! for(int i = 0; i < size; i++) ar[i] = rand() % 101; } void printArray(int ar[], int size) { for(int i = 0; i < size; i+=2) cout << ar[i] << "\t" << ar[i+1] << endl; }

Returning Arrays As it stands right now arrays cannot be returned from a function –The are created on the stack and get destroyed when function returns We will learn how to do it later on Glenn Stevenson CSIS 113A MSJC

Read Only Arrays Passing arrays can be dangerous because the function they are passed to can always modify them. In the previous program, the printArray function only needs the ability to read the variables. –Since it is only printing the array, it shouldn't be given permission to modify it. – In these instances, you want to use the const keyword. Glenn Stevenson CSIS 113A MSJC

#include #include using namespace std; void fillArray(int ar[], int size); void printArray(const int ar[], int size); int main() { int array[20]; fillArray(array, 20); printArray(array, 20); return 0; } void fillArray(int ar[], int size) { srand(time(0)); // Fill the array!! for(int i = 0; i < size; i++) ar[i] = rand() % 101; } void printArray(const int ar[], int size) { for(int i = 0; i < size; i+=2) cout << ar[i] << "\t" << ar[i+1] << endl; }