APSC 160 Review Part 2

Similar documents
Pointers. September 13, 2017 Hassan Khosravi / Geoffrey Tien 1

Linked Memory. Pointers Linked Lists. January 19, 2018 Cinda Heeren / Geoffrey Tien 1

Linked Memory. Pointers Linked Lists. September 21, 2017 Cinda Heeren / Geoffrey Tien 1

APSC 160 Review. CPSC 259: Data Structures and Algorithms for Electrical Engineers. Hassan Khosravi Borrowing many questions from Ed Knorr

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Lab 3. Pointers Programming Lab (Using C) XU Silei

Fundamental of Programming (C)

COMPUTER APPLICATION

FORM 2 (Please put your name and form # on the scantron!!!!)

Goals of this Lecture

Pointers. Memory. void foo() { }//return

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

CS201- Introduction to Programming Current Quizzes

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers

2-D Arrays. Of course, to set each grid location to 0, we have to use a loop structure as follows (assume i and j are already defined):

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Merge Sort. Algorithm Analysis. November 15, 2017 Hassan Khosravi / Geoffrey Tien 1

Pointers, Dynamic Data, and Reference Types

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Procedural programming with C

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

FOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;

Dynamic memory allocation

Introduction to Scientific Computing and Problem Solving

Arrays. Dr. Madhumita Sengupta. Assistant Professor IIIT Kalyani

Arrays and Strings. Arash Rafiey. September 12, 2017

Chapter 7 Functions. Now consider a more advanced example:

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Computer Programming Unit 3

Exam 3 Chapters 7 & 9

C Pointers. 6th April 2017 Giulio Picierro

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Two Dimensional Array - An array with a multiple indexs.

Language comparison. C has pointers. Java has references. C++ has pointers and references

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

2. C99 standard guarantees uniqueness of characters for internal names. A. 12 B. 26 C. 31 D. 48

STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Arrays in C. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

Arrays. Eng. Mohammed Abdualal

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

Two Dimensional Array - An array with a multiple indexs.

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

EM108 Software Development for Engineers

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

CS201 Latest Solved MCQs

Stream Model of I/O. Basic I/O in C

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

COMP 2355 Introduction to Systems Programming

Lecture06: Pointers 4/1/2013

Fundamentals of Programming Session 19

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

Fall 2018 Discussion 2: September 3, 2018

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Arrays and Applications

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Decimal Representation

High Performance Programming Programming in C part 1

Pointers and Arrays 1

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga

Final CSE 131B Spring 2004

BSM540 Basics of C Language

Principles of Programming. Chapter 6: Arrays

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

Memory and C++ Pointers

Multi-Dimensional arrays

Sorting. Quicksort analysis Bubble sort. November 20, 2017 Hassan Khosravi / Geoffrey Tien 1

CSC 2400: Computer Systems. Using the Stack for Function Calls

DECLARAING AND INITIALIZING POINTERS

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Queues. October 20, 2017 Hassan Khosravi / Geoffrey Tien 1

Arrays and Linked Lists

Unit 7. Functions. Need of User Defined Functions

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Pointers (1A) Young Won Lim 3/5/18

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

Object oriented programming C++

Tutorial 10 Pointers in C. Shuyue Hu

Final CSE 131B Spring 2005

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Principles of C and Memory Management

Write a C program using arrays and structure

Arrays and Pointers. CSC209: Software Tools and Systems Programming (Winter 2019) Furkan Alaca & Paul Vrbik. University of Toronto Mississauga

QUIZ: loops. Write a program that prints the integers from -7 to 15 (inclusive) using: for loop while loop do...while loop

Pointers, Arrays, and Strings. CS449 Spring 2016

Government Polytechnic Muzaffarpur.

16.216: ECE Application Programming Fall 2011

Content. In this chapter, you will learn:

Learning C Language. For BEGINNERS. Remember! Practice will make you perfect!!! :D. The 6 th week / May 24 th, Su-Jin Oh

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Basic and Practice in Programming Lab7

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

Transcription:

APSC 160 Review Part 2 Arrays September 11, 2017 Hassan Khosravi / Geoffrey Tien 1

Arrays A collection of data elements of the same type Stored in consecutive memory locations and each element referenced by an index Declared like ordinary variables, followed by [] containing the size of the array Size must be a constant or a literal integer int age[100]; const int DAYS = 365; double temperatures[days]; 0 1 2 3 4 5 6 7 8 9 September 11, 2017 Hassan Khosravi / Geoffrey Tien 2

Array elements Arrays can be initialised directly when declared or by using a loop int fib[] = {0,1,1,2,3,5,8,13} int marks[10]; for (int i = 0; i < 10; i++) marks[i] = -1; Values can be assigned from input, or other operation int marks[10]; for (int i = 0; i < 10; i++) scanf("%d", &marks[i]); for (int i = 0; i < 10; i++) arr1[i] = arr1[i] * 3; Arrays cannot be assigned to an existing array int arr1[4]; int arr2[4];... arr1 = arr2; // can't do this arr1 = {1,3,5,7}; // or this September 11, 2017 Hassan Khosravi / Geoffrey Tien 3

Arrays in loops Consider the following code segment What is the value of sum after the code segment has completed execution? int data[] = {2, 4, 8, 16, 32, 64}; int sum = 0; int index = 1; a) sum = 30 b) sum = 60 c) sum = 32 d) sum = 14 e) None of the above while (index < 4) { sum += data[index]; index++; } September 11, 2017 Hassan Khosravi / Geoffrey Tien 4

Arrays parameters An array parameter can be passed like an array variable size is not specified between [] The array itself does not know its size thus the size is usually passed as an additional variable to prevent outof-bounds errors e.g. a function prototype and a call to the function: int sum(int arr[], int size) { // prototype... }... int arr1[4];... sum(arr1, 4); // function call September 11, 2017 Hassan Khosravi / Geoffrey Tien 5

Array parameters Consider the following code function int dosomething(int data[], int size, int someval) { int found = -1; for (int index = 0; index < size; index++) { if (data[index] == someval) found = index; } return found; } a) It returns true if someval is found in the first size entries of data, and false otherwise b) If someval is contained in the first size entries of data, it returns the value someval, otherwise it returns -1 c) If someval is contained in the first size entries of data, it returns the index of the last slot where someval is found, otherwise it returns -1 d) If someval is contained in the first size entries of data, it returns the index of the first slow where someval is found, otherwise it returns -1 September 11, 2017 Hassan Khosravi / Geoffrey Tien 6

Array variable details An array variable records the address of the first element of the array This address cannot be changed after the array has been declared It is therefore a constant pointer (more about pointers later) As effects of this: Existing array variables cannot be reassigned Arrays passed to functions can be modified by those functions (unlike the last example from the previous lesson) September 11, 2017 Hassan Khosravi / Geoffrey Tien 7

Array parameters Consider the following code segment Fill the blanks to show what is output to the screen when the program runs #define SIZE 3 void process(int data[]); int main() { int data[size] = {5, -1, 2}; process(data); for (int index = 0; index < SIZE; index++) { printf("%d", data[index]); } } void process(int data[]) { for (int index = 0; index < SIZE; index++) data[index] = 0; } Answer: September 11, 2017 Hassan Khosravi / Geoffrey Tien 8

Function parameters Pass by reference In some cases, parameters may be passed by reference ("callby-reference") The address (rather than the value) of the actual parameter is copied to the formal parameter when the function is called Making a change to the value of the formal parameter effectively changes the value of the actual parameter This is what occurs with array parameters, which are passed by reference by default More about this when we get to pointers September 11, 2017 Hassan Khosravi / Geoffrey Tien 9

Multi-dimensional arrays A two-dimensional array is specified using two indices First index denotes the row, second index denotes column int marks[3][4]; col row 0 1 2 0 1 2 3 C stores a two-dimensional array contiguously like a 1D array 0,0 0,1 0,2 0,3 1,0 1,1 1,2 1,3 2,0 2,1 2,2 2,3 Multi-dimensional arrays passed as parameters in same way void myfunction(int data[][numcols], int numrows); September 11, 2017 Hassan Khosravi / Geoffrey Tien 10

Searching in arrays Consider a situation where we have one array containing n integers and another array containing 2n integers. The arrays are unordered A number x is randomly located at some (different) position in both arrays On average the ratio of the number of operations it takes to locate x in the array of size 2n when compared to the array of size n is: a) The same amount of time is needed b) Twice as much time is needed to find x in the array of size 2n c) Three times as much time is needed to find x in the 2n array d) Four times as much time is needed to find x in the 2n array e) Eight times as much time is needed to find x in the 2n array September 11, 2017 Hassan Khosravi / Geoffrey Tien 11

Pointers Pointers Arrays Dynamic Memory Allocation September 11, 2017 Hassan Khosravi / Geoffrey Tien 12

Addresses and pointers Every storage location in memory (RAM) has an address associated with it The address is the location in memory where a given variable or identifier stores its data Can think of address in memory like a mailbox number Use the address to find where the mailbox is Look inside the mailbox to access the contents/value September 11, 2017 Hassan Khosravi / Geoffrey Tien 13

Variable declaration Each byte of memory has a unique address 0 int a; char c; a = 5; a++; 201 202 203 204 205 206 207 208 209 a c At compile time, the compiler knows how much memory to allocate to each variable (e.g. 4 bytes for int, 1 byte for char, etc) September 11, 2017 Hassan Khosravi / Geoffrey Tien 14

Addresses, &, and pointers You have already encountered addresses with the scanf function scanf requires us to provide the address of a location using the "address of" operator, & e.g. scanf("%d", &a) This allows the scanf function to modify the value of the variable a, which is defined outside of scanf's call stack A pointer is a data type that contains the address of the object in memory, but it is not the object itself int a = 5; int* p = &a; a is an integer variable with the value 5 p is a pointer variable storing the address of a September 11, 2017 Hassan Khosravi / Geoffrey Tien 15

Declaring pointers Pointer variables are declared as follows: datatype* identifier e.g. int* ptr; or int * ptr; or int *ptr; Note that the type of a pointer is not the same as the type it points to e.g. ptr is a pointer to an int, but is itself not an int Warning! The declaration int* var1, var2; declares var1 as a pointer, but var2 as an integer! To declare both as pointers, either declare individually, or: int *var1, *var2; September 11, 2017 Hassan Khosravi / Geoffrey Tien 16

Address operator and dereferencing Pointers can be assigned the address of an existing variable Using the address operator, & The value which a pointer points to can be accessed by dereferencing the pointer Using the * operator p x 4096 23 47 38 0 1 2 12 2 20-1 int x = 23; int* p = &x; x = 47; *p = 38; September 11, 2017 Hassan Khosravi / Geoffrey Tien 17

Pointers as parameters Function parameters can be passed by reference using pointers int getarraysum(int arr[], int size, int* pcount) { int sum = 0; for (int i = 0; i < size; i++) { if (arr[i] > 0) (*pcount)++; sum += arr[i]; } return sum; } int numpositive = 0; int numbers[] = {3, 7, -9, 5, -4}; int result = getarraysum(numbers, 5, &numpositive); printf("array sum: %d\n", result); printf("number of positive elements: %d\n", numpositive); Array sum: 2 Number of positive elements: 3 September 11, 2017 Hassan Khosravi / Geoffrey Tien 18

Pointers as parameters What is out after the code on the right is executed? What is on the call stack for each function call? void f1(int arg) { arg = 22; printf("f1 arg: %d\n", arg); } void f2(int* arg) { *arg = 410; printf("f2 arg: %d\n", arg); } int x = 45; f1(x); printf("x after f1: %d\n", x); f2(&x); printf("x after f2: %d\n", x); September 11, 2017 Hassan Khosravi / Geoffrey Tien 19

Readings for this lesson Thareja Chapter 3 Arrays Chapter 1.11 Pointers Lab #1 available on course website September 11, 2017 Hassan Khosravi / Geoffrey Tien 20