Lecture 3: Arrays & Pointers

Slides:



Advertisements
Similar presentations
Chapter 7: Arrays In this chapter, you will learn about
Advertisements

Introduction to Programming Lecture 39. Copy Constructor.
Kernighan/Ritchie: Kelley/Pohl:
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Lecture 2 Pointers Pointers with Arrays Dynamic Memory Allocation.
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 8 Arrays and Strings
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
1 STRUCTURES AND POINTERS. 2 A VARIABLE OF THIS COMPOSITE TYPE CAN HAVE MORE THAN ONE VALUE, GROUPED TOGETHER TO DESCRIBE AN ENTITY. THE COMPONENTS OF.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
Review 1 List Data Structure List operations List Implementation Array Linked List.
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.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Arrays.
Module 1: Array ITEI222 - Advance Programming Language.
Opening Input/Output Files ifstream infile; ofstream outfile; char inFileName[40]; char outFileName[40]; coutinFileName;
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING 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.
1 Multidimensional Arrays Chapter 13 2 The plural of mongoose starts with a "p" Initializing a multidimensional array Processing by.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Arrays in C. What is Array? The variables we have used so far can store a single value. Array is a new type of variable capable of storing many values.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
C++ Review Data Structures.
Constructors and Destructors
Arrays Chapter 7.
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
Hassan Khosravi / Geoffrey Tien
Array, Strings and Vectors
Numeric Arrays Numeric Arrays Chapter 4.
Pointer Data Type and Pointer Variables II
ECE Application Programming
Passing Arguments to a Function
C++ Data Types Simple Structured Address Integral Floating
11/10/2018.
14th September IIT Kanpur
Chapter 10: Pointers 1.
Chapter 15 Pointers, Dynamic Data, and Reference Types
7 Arrays.
Pointers, Dynamic Data, and Reference Types
EKT150 : Computer Programming
Lecture 18 Arrays and Pointer Arithmetic
Chapter 15 Pointers, Dynamic Data, and Reference Types
Operators.
Pointer Data Type and Pointer Variables III
Introduction To Programming Information Technology , 1’st Semester
Constructors and Destructors
Multidimensional Arrays
MSIS 655 Advanced Business Applications Programming
Arrays Chapter 7.
7 Arrays.
Dr Tripty Singh Arrays.
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Peer Instruction 4 Control Loops.
EECE.2160 ECE Application Programming
C++ Array 1.
Arrays and Pointers CSE 2031 Fall May 2019.
Arrays and Pointers CSE 2031 Fall July 2019.
Pointers, Dynamic Data, and Reference Types
Arrays and Pointers.
Introduction to Pointers
Presentation transcript:

Lecture 3: Arrays & Pointers Object Oriented Programming (C++) Lecture 3: Arrays & Pointers

Contents 3.1 One-Dimensional Arrays 3.2 Two-Dimensional Arrays 3.3 Pointer

3.1 One-Dimensional Arrays 3.1.1 Declaring Arrays 3.1.2 Initialize Arrays in Declarations 3.1.3 How to Set Values 3.1.4 Passing Arrays as Arguments 3.1.5 Arrays of Records

3.1.1 Declaring Arrays One-dimensional array A structured collection of components, with the same type, is gived a single name. Each component(array element) is accessed by an index that indicates the component’s position within the collection. The index is zero-based.

DataType ArrayName[ConstIntExpression]; 3.1.1 Declaring Arrays Syntax template describing one-dimensional array declaration: ArrayDeclaration DataType ArrayName[ConstIntExpression];

3.1.2 Initialize Arrays in Declarations Two form of intializing arrays 1. You learned in chapter 8 that c++ allows you to initialize a variable in its declaration; int delta=25; The value 25 is called an initializer. You also can initialize an array in its declaration, using a special syntax for the initializer . int age[5]={23,10,16,37,12};

3.1.2 Initialize Arrays in Declarations Two form of initializing arrays 2. An interesting feature of C++ is that you are allowed to omit the size of an array when you initialize it in a declaration: float temperature[]={0,12.37,98.6};

3.1.3 How to Set Values Here is a loop to zero out our 100- element alpha array(i is an int variable); for (i=0;i<100;i++) Alpha [i]=0.0; We could also write the first line as for(i=0;i<=99;i++)

3.1.4 Passing Arrays as Arguments Base address The memory address of the first element of an array. It is impossible to pass a C++ array by value; Arrays are always passed by reference. Therefore, you never use & when declaring an array as a parameter. When an array is passed as an argument that’s base address.

3.1.4 Passing Arrays as Arguments Example void ZeroOut(float arr[],int numElements) { int i; for(i=0;i<numElements;i++) arr[i]=0; }

3.1.4 Passing Arrays as Arguments Example Void ZerOut(float[],int); …… int main() { float velocity[30]; float refractionAngle[9000]; ZeroOut(velocity,30); ZeroOut(refractionAngle,9000); }

3.1.5 Arrays of Records Arrays of Records const int MAX_STUDENTS=150; enum GradeType{A,B,C,D,F}; Struct StudentRec { string stuName; float gpa; int examScore[4]; GradeType courseGrade; }; studentRec gradeBook[MAX_STUDENTS]; int count;

3.1.5 Arrays of Records Select member An element of gradeBook is selected by an index. For example, gradeBook[2] is the third component in the array gradeBook. Each component of gradeBook is a record of type StudentRec. To access the course grade of the their student, we use the following expression: gradeBook[2].courseGrade

3.2 Two-Dimensional Arrays A collection of components, all of the same type, structured in two dimensions. Each component is accessed by a pair of indexes that represent the component’s position in each dimension.

3.2.1 Initialize the Array Initialize the array As with one-dimensional arrays, we can initialize a two-dimensional array either by initializing it in its declaration or by using assignment statements. If the array is summit, it is simplest to initialize it in its declaration.

3.2.1 Initialize the Array Initialize the Array We can use the following declaration to initialize an array: int arr[2][3]= { {14,3,-5}, {0,46,7} };

3.2.2 Print the array Sum the row Suppose we want to sum the row of number 3 in the array and print the result. We can do this easily with a for loop: total=0; for (col=0;col<NUM_COLS;col++) { total=total+arr[3][col]; cout<<“Row sum:”<<total<<endl; }

3.2.2 Print the array Sum the Columns Suppose we want to sum and print each column. The code to perform this task follows. Again, we have generalized the code to sum only the portion of the array that contains valid data.

3.2.2 Print the array Sum the Columns for (col=0;col<colsFilled;col++) { total=0; for (row=0;row<rowsFilled;row++) total=total+arr[row][col]; cout<<“Column sum:”<<total<<endl; }

3.2.2 Print the array Print the array If we wish to print out an array with one row per line, then we have another case of row processing: #include<iomanip> …… for(row=0;col<NUM_COLS;col++) { cout<<setw(15)<<arr[row][col]; cout<<endl; }

3.3 Pointers Statements Since C++ is a compiling language, that means the variables in the program should be explained in advance in order to allocate memory for them before the program executing. C++ supports dynamic allocating memory mechanism. It is used by the pointer operators new and delete.

Pointers (cont.) pointer=new type; delete operator new operator It is used to apply the memory for the variables, as follows: pointer=new type; delete operator It is used to free the memory to the operating system, as follows: delete pointer;

Pointers (cont.) Example: #include <iostream.h> void main() { int *pi; cout<<“Before allocation pi is”<<pi<<endl; pi=new int; *pi=5; cout<<“After allocation pi is”<<pi<<endl; cout<<“The value is”<<*pi<<endl; delete pi; }

Pointers (cont.) Notes: A variable/object created by new exists until it is explicitly destroyed by delete. All the variables/objects created by new should be manually freed using delete. Otherwise, there will be memory leakage. We must pay attention to the pointer that should be the original allocation before we free the memory assigned to the pointer

Pointers (cont.) void main() { int *p= new int(3); Wrong example: void main() { int *p= new int(3); cout<<*p<<endl; p+=3; // other operations delete p; }

Pointers (cont.) Correct example: void main() { int *p= new int(3); int *q; q=p; cout<<*p<<endl; p+=3; // other operations delete q; }

Pointers (cont.) type *pointer_name =new type[size]; Arrays and pointers type *pointer_name =new type[size]; delete [] pointer_name ; The ‘‘plain’’ operator delete is used to delete individual objects; delete [] is used to delete arrays.

Pointers (cont.) delete p; delete []q; } Example 1: void f(int n) { int *p=new int(n); //individual object int *q=new int[n]; //array //…… delete p; delete []q; }

The End