CS 141 Computer Programming 1 1 Arrays. Outline  Introduction  Arrays  Declaring Arrays  Examples Using Arrays  Sorting Arrays  Multiple-Subscripted.

Slides:



Advertisements
Similar presentations
2000 Prentice Hall, Inc. All rights reserved. 1 Capitolo 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
Advertisements

1 Arrays, Strings and Collections [1] Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by.
Chapter 7: Arrays In this chapter, you will learn about
Monday, Jan 20, 2002Kate Gregory with material from Deitel and Deitel Week 3 Questions from Last Week Hand in Lab 1 Arrays Pointers Strings Lab 2.
Introduction to C Systems Programming Concepts. Introduction to C A simple C Program A simple C Program –Variable Declarations –printf ( ) Compiling and.
Programming In C++ Spring Semester 2013 Lecture 6 Programming In C++, Lecture 6 By Umer Rana.
CS 240 Computer Programming 1
EC-111 Algorithms & Computing Lecture #7 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
The simple built-in data types of the C language such as int, float, - are not sufficient to represent complex data such as lists, tables, vectors, and.
Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
Structure.
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
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.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
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 Lecture Today’s topic Arrays Reading for this Lecture: –Chaper 11.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 11P. 1Winter Quarter Arrays Lecture 11.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Chapter 3 Data Structures and Abstract Data Type Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
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.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Topics to be covered  Introduction to array Introduction to array  Types of array Types of array  One dimensional array One dimensional array  Declaration.
Algorithm and Programming Array Dr. Ir. Riri Fitri Sari MM MSc International Class Electrical Engineering Dept University of Indonesia 15 March 2009.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays.
Array Cs212: DataStructures Lab 2. Array Group of contiguous memory locations Each memory location has same name Each memory location has same type a.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CHAPTER 6 ARRAYS IN C++ 2 nd Semester King Saud University College of Applied studies and Community Service CSC 1101 By: Fatimah Alakeel Edited.
CHAPTER 7: Arrays CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (Feb 2012)
Arrays An array is an indexed data structure which is used to store data elements of the same data type. An array is an indexed data structure which is.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Arrays in java Unit-1 Introduction to Java. Array There are situations where we might wish to store a group of similar type of values in a variable. Array.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Windows Programming Lecture 03. Pointers and Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline 1 Introduction 2 Arrays 3Declaring Arrays 4Processing Array Contents 5 Multiple-Subscripted.
C LANGUAGE UNIT 3. UNIT 3 Arrays Arrays – The concept of array – Defining arrays – Initializing arrays.
Chapter 6 Arrays in C++ 2nd Semester King Saud University
CSC 113: Computer Programming (Theory = 03, Lab = 01)
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
7 Arrays.
Chapter 9 - Arrays Outline 6.1 Introduction 6.2 Arrays
Arrays Kingdom of Saudi Arabia
CS-161 Computer Programming Lecture 14: Arrays I
Introduction To Programming Information Technology , 1’st Semester
To refer to an element, specify
Arrays Arrays A few types Structures of related data items
Arrays.
CS149D Elements of Computer Science
Lecture 14: Problems with Lots of Similar Data
Programming Fundamental
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

CS 141 Computer Programming 1 1 Arrays

Outline  Introduction  Arrays  Declaring Arrays  Examples Using Arrays  Sorting Arrays  Multiple-Subscripted Arrays 2

Introduction  Structures of related data items  Static entity (same size throughout program execution ) 3 Arrays

4  Consecutive group of memory locations  Same name and type (int, char, etc.)  To refer to an element  Specify array name and position number (index).  Format: arrayname [ position number ]  First element at position 0.  N-element array c.  c[ 0 ], c[ 1 ] … c[ n - 1 ].  Nth element as position N-1.

Arrays Name of the array is c Position number of the element within the array (Index) c [ 0 ] c [ 1 ] c [ 2 ] c [ 3 ] c [ 4 ] c [ 5 ] c [ 6 ] c [ 7 ] c [ 8 ] c [ 9 ] c [ 10 ] c [ 11 ] value Name of the individual array element Array of 12 elements

Arrays  Array elements like other variables  Assignment, printing for an integer array c  Can perform operations inside subscript  If we assume that variable a is equal to 5 and that variable b is equal to 6, then the statement Add 2 to array element c[11] 6 c[ 0 ] = 3; cout << c[ 0 ]; c[ 5 – 2 ] same as c[3] C [ a + b ] +=2; same as c[11]+=2 ;

Declaring Arrays  When declaring arrays, specify:  Name  Type of array  Any data type  Number of elements 7 type arrayName [ arraySize ]; Syntax Example int c[ 10 ]; // array of 10 integers float d[ 3284 ]; // array of 3284 floats int c[ 10 ]; // array of 10 integers float d[ 3284 ]; // array of 3284 floats

 Declaring multiple arrays of same type  Use comma separated list, like regular variables 8 Declaring Arrays int b[ 100 ], x[ 27 ];

Examples Using Arrays  For loop  Set each element  Initializer list  Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 };  The number of initializers must be less than or equal to the array size.  If not enough initializers, rightmost elements 0.  If too many syntax error. 9 Initializing arrays

 To initialize all array elements to 0 int n[ 5 ] = { 0 }; OR int n[ 5 ] = {};  If array size omitted, initializers determine size int n[] = { 1, 2, 3, 4, 5 };  5 initializers, therefore 5 element array 10 Examples Using Arrays Initializing arrays

Examples // Initializing an array. #include using namespace std; Void main() { int n[ 10 ]; // n is an array of 10 integers // initialize elements of array n to 0 for ( int i = 0; i < 10; i++ ) n[ i ] = 0; // set element at location i to 0 cout << "Element" << setw( 13 ) << "Value" << endl; // output contents of array n in tabular format for ( int j = 0; j < 10; j++ ) cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl; } Declare a 10-element array of integers. Initialize array to 0 using a for loop. Note that the array has elements n[0] to n[9]. 11

Examples // Initializing an array with a declaration. #include using namespace std; int main() { // use initializer list to initialize array n int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; cout << "Element" << setw( 13 ) << "Value" << endl; // output contents of array n in tabular format for ( int i = 0; i < 10; i++ ) cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl; return 0; // indicates successful termination } // end main Note the use of the initializer list. 12

Examples Element Value Output

Examples Using Arrays  Array size.  Can be specified with constant variable (const) const int size = 20;  Constants cannot be changed.  Constants must be initialized when declared. 14 Specifying an Array’s Size

Example // Initialize array s to the even integers from 2 to 20. #include using namespace std; int main() { // constant variable can be used to specify array size const int arraySize = 10; int s[ arraySize ]; // array s has 10 elements for ( int i = 0; i < arraySize; i++ ) // set the values s[ i ] = * i; cout << "Element" << setw( 13 ) << "Value" << endl; Note use of const keyword. Only const variables can specify array sizes. The program becomes more scalable when we set the array size using a const variable. We can change arraySize, and all the loops will still work (otherwise, we’d have to update every loop in the program). 15

Example // output contents of array s in tabular format for ( int j = 0; j < arraySize; j++ ) cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl; return 0; // indicates successful termination } // end main 16

Example Element Value Output

Example 1 // 2 // A const object must be initialized. 3 4 int main() 5 { 6 const int x; // Error: x must be initialized 7 8 x = 7; // Error: cannot modify a const variable 9 10 return 0; // indicates successful termination } // end main d:\cpphtp4_examples\ch04\Fig04_07.cpp(6) : error C2734: 'x' : const object must be initialized if not extern d:\cpphtp4_examples\ch04\Fig04_07.cpp(8) : error C2166: l-value specifies const object Uninitialized const results in a syntax error. Attempting to modify the const is another error. 18 Compiler error message

// Compute the sum of the elements of the array. #include using namespace std; int main() { const int arraySize = 10; int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int total = 0; // sum contents of array a for ( int i = 0; i < arraySize; i++ ) total += a[ i ]; cout << "Total of array element values is " << total << endl; return 0; // indicates successful termination } // end main Total of array element values is Example

// Student poll program. #include using namspace std; int main() { // define array sizes const int responseSize = 40; // size of array responses const int frequencySize = 11; // size of array frequency // place survey responses in array responses int responses[ responseSize ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 }; // initialize frequency counters to 0 int frequency[ frequencySize ] = { 0 }; 20 Example

26 // for each answer, select value of an element of array 27 // responses and use that value as subscript in array 28 // frequency to determine element to increment 29 for ( int answer = 0; answer < responseSize; answer++ ) 30 ++frequency[ responses[answer] ]; // display results 33 cout << "Rating" << setw( 17 ) << "Frequency" << endl; // output frequencies in tabular format 36 for ( int rating = 1; rating < frequencySize; rating++ ) 37 cout << setw( 6 ) << rating 38 << setw( 17 ) << frequency[ rating ] << endl; return 0; // indicates successful termination } // end main responses[answer] is the rating (from 1 to 10). This determines the index in frequency[] to increment. 21

Example Rating Frequency Output

Examples Using Arrays  Arrays of characters  All strings end with null ('\0')  Example  char string1[] = "hello";  Null character implicitly added  string1 has 6 elements  char string1[] = {'h','e','l','l','o','\0’};  Subscripting is the same  String1[ 0 ] is 'h'  string1[ 2 ] is 'l' 23 Strings

Examples Using Arrays  Input from keyboard  char string2[ 10 ];  cin >> string2;  Puts user input in string  Stops at first whitespace character  Adds null character  If too much text entered, data written beyond array  Will be avoided.  Printing strings  cout << string2 << endl;  Does not work for other array types  Characters printed until null found 24

// Treating character arrays as strings. #include int main() { char string1[ 20 ], // reserves 20 characters char string2[] = "string literal"; // reserves 15 characters // read string from user into array string2 cout << "Enter the string \"hello there\": "; cin >> string1; // reads "hello" [space terminates input] // output strings cout << "string1 is: " << string1 << "\nstring2 is: " << string2; cout << "\nstring1 with spaces between characters is:\n"; Two different ways to declare strings. string2 is initialized, and its size determined automatically. Examples of reading strings from the keyboard and printing them out. 25 Example

24 // output characters until null character is reached 25 for ( int i = 0; string1[ i ] != '\0'; i++ ) 26 cout << string1[ i ] << ' '; cin >> string1; // reads "there" 29 cout << "\nstring1 is: " << string1 << endl; return 0; // indicates successful termination } // end main Enter the string "hello there": hello there string1 is: hello string2 is: string literal string1 with spaces between characters is: h e l l o string1 is: there Can access the characters in a string using array notation. The loop ends when the null character is found. 26 Output

 Sorting is the process of putting data in order descending or ascending) ; either numerically or alphabetically.  The process of sorting an array requires the exchanging “swapping” of values.  Sorting algorithms examples:  Bubble sort.  Insertion sort  Selection sort  Quick sort. 27 Sorting Arrays

int x = 3, y = 4; y = x; x = y; What happened?  Both x and y are 3!  Need a temporary variable Solution int x = 3, y = 4, temp = 0; temp = x; // temp gets 3 x = y; // x gets 4 y = temp; // y gets 3 28 Swapping variables

 The array is scanned and two adjacent elements are interchanged if they are out of order.  First, items data[ 0 ] and data[ 1 ] are compared and swapped if they are out of order.  Next, data[ 1] and data[ 2] are compared and swapped if they are out of order and so on up to data[n-2] and data[n-1]. 29 Sorting Arrays Bubble Sort

// This program sorts an array's values into ascending order. #include using namespace std; int main() { const int arraySize = 10; // size of array a int a[ arraySize ] = {2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; int hold; // temporary location used to swap array elements cout << "Data items in original order\n"; // output original array for ( int i = 0; i < arraySize; i++ ) cout << setw( 4 ) << a[ i ]; 30 Example

24 // bubble sort 25 // loop to control number of passes 26 for ( int pass = 0; pass < arraySize - 1; pass++ ) // loop to control number of comparisons per pass 29 for ( int j = 0; j < arraySize - 1; j++ ) // compare side-by-side elements and swap them if 32 // first element is greater than second element 33 if ( a[ j ] > a[ j + 1 ] ) { 34 hold = a[ j ]; 35 a[ j ] = a[ j + 1 ]; 36 a[ j + 1 ] = hold; } // end if 39 Do a pass for each element in the array. If the element on the left (index j ) is larger than the element on the right (index j + 1 ), then we swap them. Remember the need of a temp variable. 31 Example

40 cout << "\nData items in ascending order\n"; // output sorted array 43 for ( int k = 0; k < arraySize; k++ ) 44 cout << setw( 4 ) << a[ k ]; cout << endl; return 0; // indicates successful termination } // end main Data items in original order Data items in ascending order Output Example

33 Question Write a program that reads an array of n integers and an integer number then searches for it in the array. If its found print its location, otherwise print “ NOT FOUND ” Note: the maximum array size is 20 Question #1 How many integers you want to enter: 7 Enter the numbers: Which number you want to find its position: is at position(index) 2

34 Examples

35 Examples