CS 161 Introduction to Programming and Problem Solving Chapter 19 Single-Dimensional Arrays Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied.

Slides:



Advertisements
Similar presentations
Programming and Data Structure
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
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Kernighan/Ritchie: Kelley/Pohl:
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
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.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Introduction of Arrays. Arrays Array form an important part of almost all programming language. It provides a powerful feature and can be used as such.
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
ECE 103 Engineering Programming Chapter 10 Variables, AKA Objects Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
A First Book of ANSI C Fourth Edition
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify.
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
ICS103 Programming in C Lecture 11: Arrays I
 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.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Computer Programming for Engineers
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
ECE 103 Engineering Programming Chapter 23 Multi-Dimensional Arrays Herbert G. Mayer, PSU CS Status 6/24/2014 Initial content copied verbatim from ECE.
CS 161 Introduction to Programming and Problem Solving Chapter 17 Nested Loops Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
© 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.
CS 161 Introduction to Programming and Problem Solving Chapter 12 C++ Statements Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied verbatim.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
1 Principles of Computer Science I Honors Section Note Set 3 CSE 1341.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Windows Programming Lecture 03. Pointers and Arrays.
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?
C LANGUAGE UNIT 3. UNIT 3 Arrays Arrays – The concept of array – Defining arrays – Initializing arrays.
ARRAYS.
1-d Arrays.
Chapter 6 Arrays in C++ 2nd Semester King Saud University
BASIC ELEMENTS OF A COMPUTER PROGRAM
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
EKT150 : Computer Programming
ECE 103 Engineering Programming Chapter 25 C Strings, Part 1
ECE 103 Engineering Programming Chapter 35 C Pointers, Part 1
ECE 103 Engineering Programming Chapter 38 C Pointers, Part 2
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Presentation transcript:

CS 161 Introduction to Programming and Problem Solving Chapter 19 Single-Dimensional Arrays Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied verbatim from ECE 103 material by prof. Phillip PSU

Syllabus Introduction to Arrays Declaring 1-D Arrays Variable-Length Array Accessing 1-D Arrays Arrays and Memory Addresses (1-D) Examples

2 Introduction to Arrays A simple variable (AKA scalar) stores a single item of a specified data type:  A single memory cell is reserved An array variable stores multiple items of the same data type:  A block of identical memory cells is reserved In C, arrays are stored in row-major order Fortran, by contrast, stores in column-major order

3 Each array item is called an element Elements are stored consecutively in memory in C++ An element is accessed by using the array name with an index value, AKA subscript element #0 element #1 element #2 : element #n address A address A + sizeof( element ) address A + 2·sizeof( element ) address A + n·sizeof( element )

4 Declaring 1-D Arrays Declaration: datatype array_name[size]; datatype can be:  Standard type (e.g., char, int, float, or double)  User-defined type  Or another array or struct array_name follows the same naming rules as simple variables

5 size is the maximum number of items the array should hold; specified in square brackets Example: /* Homework 1 grades for up to 20 students */ int HW1_grade[ 20 ]; /* Homework 2 grades for up to 20 students */ int HW2_grade[ 20 ]; size is a constant positive integral value The array size is fixed and must be known at compile-time (C90)

6 Example: /* OK: 10 is a literal constant */ int v[ 10 ]; /* OK: ARY_SIZE is a macro constant */ #define ARY_SIZE 10 int v[ ARY_SIZE ]; /* ERROR: if ary_size is a variable */ int ary_size = 10; int v[ ary_size ]; // Compile-time error C does not automatically initialize all arrays to zero when first declared; only static ones

7 Variable Length Arrays C99 allows the size of an array to be determined at run-time: // C99 VLA Example #include int main( void ) { // main int sz; printf( "Enter desired 1-D array size: ” ); scanf( "%d", &sz ); int b[ sz ]; for( int i = 0; i < sz; i++ ) { b[ i ] = 0; } //end for return 0; } //end main C99

8 An array can be declared and initialized at the same time by using braces { } Example: double x[3] = { 1.0, 2.5, 6.2 }; // double x[3] = { 1.0, 2.5 }; // double x[3] = { 0.0 }; // The size can be omitted if the 1-D array is initialized during declaration Example: int grades[ ] = { 85, 89, 88, 95, 100, 54 }; Size is automatically set to 6, with low-bound 0 and high- bound 5

9 Accessing an Array (1-D) Each array element is assigned an index Lowest index starts at zero (0) If size is the declared array size, then the highest index is size -1 When declaring an array, brackets indicate the maximum size you want When referencing an element of an array, brackets specify which element to access

10 Example: int v[ 5 ]; Array elements are: v[0], v[1], v[2], v[3], v[4] First index is 0. Last index is 4 The array index is any expression that evaluates to an integer value Example: Assume j and k contain integers: v[2] or v[k] or v[j+k] or v[j+k*2] Usually the index is a positive integer or zero. Negative indices are legal, but result in undefined behavior

11 Warning: Using an array index outside the declared range (bounds) may access incorrect or illegal memory areas. Memory corruption results! Example: int A[3] = {2, 4, 6}; /* Legal indices: 0,1,2 */ /* Accesses memory that does not belong to A */ sum = 0; for( k = 0; k <= 3; k++ ) { sum = sum + A[k]; } //end for // Now we overwrite memory that does not belong to A[] A[-1] = 0; A[3] = 0; C does not perform run-time bounds checking

12 Initialize array elements before accessing them! Example: #define N 4 int v[N], s = 0; v[0]=1; v[1]=3; v[2]=-5; v[3]=2;/* Initialize */ for( k = 0; k < N-1; k++ ) { s += v[k] * 2; // Accessing value of element v[k] = k; // Assigning value to element } //end for

13 In C++ (or in C) an array cannot be copied to another array with a single assignment operator That is one of the language weaknesses To copy an array, each element must be individually copied (either one at a time or with a loop) Example: int a[3], b[3] = {2, 1, 0}; /* a = b will NOT work!!! */ /* This works */ a[0]=b[0]; a[1]=b[1]; a[2]=b[2]; /* This also works */ for( k = 0; k < 3; k++ ) a[k] = b[k];

14 Example: /* Program to calculate Body Mass Index (BMI) */ #include #define N 100 int main( void ) { // main float w[N], h[N], BMI[N]; /* Weight, height, BMI arrays */ int k = 0, i; while( k++ < N ) { printf("[%2d] Enter weight (lb): ", k); scanf("%f", &w[k]); if (w[k] <= 0) break; printf("[%2d] Enter height (in): ", k); scanf("%f", &h[k]); BMI[k] = w[k] / (h[k]*h[k]) * 703; } //end for for( i = 1; i < k; i++ ) { // Display BMI results printf("[%2d] %5.2f %5.2f : %3.1f\n", i,w[i],h[i],BMI[i] ); } //end for return 0; } //end main

15 Arrays and Memory Addresses (1-D) When a program runs, a block of memory is allocated to hold the contents of the array  The block has a base address in memory  Array elements are stored consecutively in the block starting at the base address. The address assigned to an element depends on both the index and the data type size

16 Example: /* Assuming 1 byte characters */ char M[3] = { 40, 30, 20 }; /* Assuming 1 byte characters */ char name[3] = { 'C', 'a', 't’ }; AddressEX: base=620Array IndexContents base base base AddressEX: base=738Array IndexContents base base base

17 Example: /* Assuming 4 byte integers */ int x[3] = { 1024, -2048, 4096 }; /* Assuming 8 byte doubles */ double y[3] = { 1.0, 5.25, -3.1e15 }; AddressEX: base=1200Array IndexContents base base base AddressEX: base=8192Array IndexContents base base base e15

18 The array name by itself is the address of the first element in the array Example: Note: & is also used as “address-of” operator in C In the prior example for array M :  M is the name of the array  M has the value 620  M[0] is the first element of the array  M[0] has the value 40  &M[0] is the address of M[0] &M[0] has the value 620  Therefore, M is equivalent to &M[0] AddrIndexCont