Arrays.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Kernighan/Ritchie: Kelley/Pohl:
Passing Arrays to Functions Programming. COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 2 Passing Arrays as Parameters l Arrays are.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
C++ for Engineers and Scientists Third Edition
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
1 Arrays Chapter 13 Especially read 13.1 – 13.2 Text introduces vectors, which we will not cover, in 13.3.
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.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
CPS120: Introduction to Computer Science Decision Making in Programs.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Final Revision I 1020: Introduction to Programming Mohamed Shehata November 30, 2015.
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.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Variables  A piece of memory set aside to store data  When declared, the memory is given a name  by using the name, we can access the data that sits.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Data Storage So far variables have been able to store only one value at a time. What do you do if you have many similar values that all need to be stored?
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Arrays Chapter 7.
Review 1.
User-Written Functions
Chapter 7 Pointers and C-Strings
EGR 2261 Unit 10 Two-dimensional Arrays
Arrays Low level collections.
An Introduction to Programming with C++ Sixth Edition
© 2016 Pearson Education, Ltd. All rights reserved.
Suppose we want to print out the word MISSISSIPPI in big letters.
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Variables A piece of memory set aside to store data
Numeric Arrays Numeric Arrays Chapter 4.
Pointers and Pointer-Based Strings
New Structure Recall “average.cpp” program
Student Book An Introduction
Passing Arguments to a Function
User-Defined Functions
Arrays & Functions Lesson xx
Arrays, For loop While loop Do while loop
Object Oriented Programming COP3330 / CGS5409
One-Dimensional Array Introduction Lesson xx
7 Arrays.
Arrays Kingdom of Saudi Arabia
EKT150 : Computer Programming
Declaration, assignment & accessing
Lecture 18 Arrays and Pointer Arithmetic
Pointers.
CMSC202 Computer Science II for Majors Lecture 03 – Arrays and Functions Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
7 Arrays.
CS150 Introduction to Computer Science 1
Pointers and Pointer-Based Strings
Arrays Arrays A few types Structures of related data items
C++ Array 1.
1D Arrays and Lots of Brackets
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Arrays

Arrays Up to now, variables have only held a single value. Now we introduce a kind of compound variables, that is variables which can hold multiple values. An array is designed to hold homogeneous values. That is, every value in an array is of the same type. For example: int c[10]; // c is an array of 10 integers. double x[22]; // x is an array of 22 doubles char letters[30]; //letters is an array of 30 characters The size, or dimensionality, of the array must be declared so that compiler knows how much storage to set aside.

Element Reference We can access individual elements of an array (see previous slide) via an index, like: c[3] = 13; x[20] = x[17] - x[3]; Notice that the "first" element of the array actually has index 0. The implication is that there is no such thing as c[10], x[22] or letters[30]. The indices of an array of size n run from 0 to n-1.

Initialization of Arrays Arrays are initialized using an initialization block int a = 3; int fib[10] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55}; Note that it is not necessary to initialize every element of an array. int a[10] = {4, -5, 7, -11, 9}; initializes a[0] through a[4] while leaving a[5] through a[9] uninitialized. As you might expect, specifying too many elements (over specifying) is a compile-time error.

Array Storage Here is a diagram of how an array get's stored in memory. The elements in an array are stored adjacent to one another. The diagram shows a series of contiguous memory locations, each holding a piece of integer data. Underneath each location we show, in square brackets, the index of the piece of data within the array. Don't confuse the two. The index gives the position within the array. It is always an integer!

The data in the boxes represent the value of each element of the array The data in the boxes represent the value of each element of the array. Their type depends on the type of the array. This is an array of integers, so the values are integers, but we could have an array of doubles or characters just as well. In the figure the element at index 6 is 7, while that at 11 is 17. An array is accessed directly, simply by specifying the index of the desired element (this is actually what is meant by the term random access).

Passing Arrays to Functions An array can be passed into a function as an argument For example, in the function prototype below an array of grades is passed in as input and the function returns the average of the grades. double average(int grades[], int size) Because arrays do not know their own size, the size must be passed in as a separate parameter. Obviously the programmer who originally created the array (outside our function) must know how big the array she created is. But our function has to be able to work with classes of any size. So, as part of our contract, we get clients to tell us how big their array is.

We pass arrays by reference. Actually, they are technically passed by address because arrays are an original feature of C and C didn't have pass-by-reference. The difference at your stage is not worth worrying about. Bottom line: any changes to an array passed to a function is permanent after we return from that function

For loops and Arrays For loops and Arrays are like peanut butter and jelly Sandwich int main( ){ const int SIZE_S = 10; const int SIZE_C = 5; double sines[SIZE_S]; double cosines[SIZE_C]; int i; // used to index through both arrays // Fill up the arrays for (i = 0; i < SIZE_S; i++) sines[i] = fabs(sin(2*3.14159*i/SIZE_S)); for (i = 0; i < SIZE_C; i++) cosines[i] = fabs(cos(2*3.14159*i/SIZE_C)); //call function average below cout << "The average of the sines is " << average(sines, SIZE_S) << endl; cout << "& the average of the cosines is " << average(cosines, SIZE_C) << endl; return 0; }

/** average ************************************************ * * @params: data - the array of data to be averaged * size: the number of elements in the data array * Modifies: nothing * @returns: the average of the data ***********************************************************/ double average(double data[], int size){ double sum = 0.; for (int i = 0; i < size; i++) sum += data[i]; return sum/size; } //using while loop double average(double data[], int size){ double sum=0.0; int i=0; while (i<size){ sum+=data[i]; i++; } return sum/size

Problem: build a function to find the position of the largest piece of data in an array of doubles Clearly a loop is involved since I'll have to search the entire array—and for loops are a good match for arrays concentrate on the body of the loop, assume I know the position of the largest piece of data so far We'll hold that in a variable called position, so we should get something like search the whole array ( use: for i = 0, i < arraysize) if data[i] > data[position] then position = i Now all we have to do is get it started—how about we set position to 0? In other words, force an assumption that the largest data is initially at position 0

/. getLargest. @params: data - an array of doubles /** getLargest ****************************************** * * @params: data - an array of doubles * size: number of elements in the data array * Modifies: nothing * @returns: the position of the first occurrence of the * largest value ********************************************************/ int getLargest(double data[], int size){ int position = 0; for (int i = 1; i < size; i++) if (data[i] > data[position]) position = i; return position; }

What would we change if we wanted the last occurrence? Question: What happens if there are two or more largest pieces of data? Where will position end up? It returns the first position of the largest data What would we change if we wanted the last occurrence? if (data[i] >= data[position]) position = i;

Problem: build a function to find how many occurrences there are of the largest piece of data in an array of doubles. int howManyLargest(double data[], int size){ // first occurrence of largest data - see previous slides int position = getLargest( data, size); int count = 1; //we have one occurrence so far //start searching after the 1st occurrence for( int i=position+1; i<size; i++) { if(data[i]==data[position]) count++; } return count; }

Another Solution int howManyLargest(double data[], int size){ int pos=0; int count=1; for (int i=1; i<size; i++){ if(data[i]>data[pos]){ pos=i; count=1; } else if (data[i]==data[pos]) count++; return count;

The break statement The keyword break inside a for loop exists the loop immediately Example: find the first occurrence of the number 3 in an integer array, if it is not found then return -1 int findNum3(int data[], int size) { int pos = -1; for (int i = 0; i<size; i++) if (data[i] == 3) { pos = i; break; } return pos; This code is more efficient because it stops once it found the number 3 and does not keep searching until the end of the array

Things you cannot do with Arrays You cannot return an array from a function. Example: double[ ] foo() { double myArray[3]={4.2, 3.1,12.6}; return myArray; } is not legal. Remember that arrays are pass by reference so the changes are permanent

Things you cannot do with Arrays You cannot assign arrays. double A[3]={4.2, 3.1,12.6}; double B[3]; B = A; The third line is not legal. Instead, write a loop for (int i = 0; i < 3; i++) B[i] = A[i];

Things you cannot do with Arrays When declaring arrays, you must know their size at compile time. For example: void foo(int size){ double A[size]; .... } is not legal since arguments to functions are only known at run time, when the function actually gets called. Another way to think of this is that arrays should be declared with constant sizes. Either of these is legal double A[20]; OR const int SIZE = 30; double B[SIZE];

Example This question deals with digital audio (e.g., music), which is essentially an array of sound samples, where each sample represents the amplitude of the sound wave at a particular instant. A fuzz box creates a distortion effect common in rock guitar music by 'clipping' the maximum amplitude to the given value, as illustrated. Write the prototype and implementation of the header block shown below.

/*** fuzzBox ******************************* * Clip the size samples in snd to a maximum amplitude (magnitude) * @params snd - audio samples array * size - the number of samples in snd * clip - the maximum magnitude in the output * @modifies Any element in snd that has a magnitude greater than clip * will be set to clip or – clip to preserve the sign * @returns The number of samples that had their values changed **/ int fuzzBox(int snd[], int size, int clip) { For loop(traverse all array) Check the current element if it is above the positive threshold clip the value to clip increment the counter Do something similar for the negative threshold return counter } i

/*** fuzzBox ******************************* * Clip the size samples in snd to a maximum amplitude (magnitude) * @params snd - audio samples array * size - the number of samples in snd * clip - the maximum magnitude in the output * @modifies Any element in snd that has a magnitude greater than clip * will be set to clip or – clip to preserve the sign * @returns The number of samples that had their values changed **/ int fuzzBox(int snd[], int size, int clip) { int cnt = 0 ; for ( int i=0 ; i < size; i++) { if(snd[i] > clip){ snd [i] = clip; cnt++; } else if (snd[i]<-clip) { snd[i]= -clip; } return cnt;

Example Write a function named "number_of_matches" that compares the initial parts of two character arrays to see how many pairs of cells match before a difference occurs. For example, if the arrays are The function should return 3 because only the first three characters in the first array matches the corresponding cells in the second array H E L O - 1 2 H E L I C O P T R Example execusion int main() { char s1[10] = { 'H','E','L', 'L', 'O', '-', '1', '0', '2', '0' }; char s1[10] = { 'H','E','L', 'I', 'C', 'O', 'P', 'T', 'E', 'R' }; cout << number_of_matches(s1,s2,10); return 0; } will print 3 on the screen

int number_of_matches (char firstWord[], char secondWord[], int size) { int cnt=0; for ( int i=0 ; i < size; i++) { if(firstWord[i]==secondWord[i]) cnt++; else break; } return cnt; For

Time for a break After all this array stuff, let’s meditate Have fun https://www.youtube.com/watch?v=mE0RQV72r20