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

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

Computer Science & Engineering 150A Problem Solving Using Computers

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Module 6: Array in C

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Chapter 7 Array. Array. C++, How to Program

BITG 1113: Array (Part 1) LECTURE 8

ARRAYS(II Unit Part II)

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA.

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:

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

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

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

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

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

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays

Unit 7. Functions. Need of User Defined Functions

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

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

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays.

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

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

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Content. In this chapter, you will learn:

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

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

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Introduction to Computer Science Midterm 3 Fall, Points

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

UNIT-I Fundamental Notations

CSE2301. Arrays. Arrays. Arrays and Pointers

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

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

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

Multi-Dimensional arrays

Programming for Engineers Arrays

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example:

Array. Arrays. Declaring Arrays. Using Arrays

Chapter 9 Introduction to Arrays. Fundamentals of Java

How to declare an array in C?

Arrays. Systems Programming Concepts

Why arrays? To group distinct variables of the same type under a single name.

PROGRAMMAZIONE I A.A. 2017/2018

C for Engineers and Scientists: An Interpretive Approach. Chapter 10: Arrays

Array Initialization

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Chapter 7 : Arrays (pp )

Lecture 04 FUNCTIONS AND ARRAYS

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Arrays in C. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur. Basic Concept

COMPUTER APPLICATION

MODULE 3: Arrays, Functions and Strings

Lesson 7. Reading and Writing a.k.a. Input and Output

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

C++ PROGRAMMING SKILLS Part 4: Arrays

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Review of Important Topics in CS1600. Functions Arrays C-strings

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

CHAPTER 4 FUNCTIONS. 4.1 Introduction

ONE DIMENSIONAL ARRAYS

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

CS201 Latest Solved MCQs

Chapter 01 Arrays Prepared By: Dr. Murad Magableh 2013

CSC 1300 Exam 4 Comprehensive-ish and Structs

For example, let s say we define an array of char of size six:

Week 8: Arrays and File I/O. BJ Furman 21OCT2009

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

Computers Programming Course 11. Iulian Năstac

C Programming Review CSC 4320/6320

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

UNIT 6. STRUCTURED DATA TYPES PART 1: ARRAYS

The University Of Michigan. EECS402 Lecture 05. Andrew M. Morgan. Savitch Ch. 5 Arrays Multi-Dimensional Arrays. Consider This Program

Programming for Electrical and Computer Engineers. Pointers and Arrays

APSC 160 Review Part 2

Arrays. int Data [8] [0] [1] [2] [3] [4] [5] [6] [7]

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

Arrays. CSE / ENGR 142 Programming I. Chapter 8. Another Motivation - Averaging Grades. Motivation: Sorting. Data Structures.

First of all, it is a variable, just like other variables you studied

CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers. Kevin Webb Swarthmore College March 1, 2016

Arrays and Pointers (part 1)

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Arrays and Pointers (part 1)

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Procedural Programming

C++ Arrays. To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows

Transcription:

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

What is an Array? Scalar data types use a single memory cell to store a single value. For many problems you need to group data items together. A program that processes exam scores for a class, for example, would be easier to write if all the scores were stored in one area of memory and were able to be accessed as a group. C allows a programmer to group such related data items together into a single composite data structure. In this lecture, we look at one such data structure: the Array. 2

Arrays - Declaration Simple data types use a single memory cell to store variable. Array is a data structure which groups two or more adjacent memory cells. Syntax: element-type aname[size]; element-type aname[size]={initialization list}; e.g., double x[8]; char name[4]; 3

Array The number of elements, or array size must be specified in the declaration. Contiguous space in memory is allocated for the array. Related data items of the same type (i.e. contiguous memory cells are of the same size). Remain same size once created (i.e. they are Fixed-length entries ) 4

Good Practice const int maxaarraysize = 12; int myarray[maxarraysize]; OR #define MAX_ARRAY_SIZE 12 int myarray[max_array_size]; 5

Array Terminology (1) An array is a collection of two or more adjacent memory cells that are: The same type (i.e. int) Referenced by the same name These individual cells are called array elements To set up an array in memory, we must declare both the name and type of the array and the number of cells associated with it double x[8]; This instructs C to associate eight memory cells with the name x; these memory cells will be adjacent to each other in memory. You can declare arrays along with regular variables double cactus[5], needle, pins[7]; 6

Array Terminology (2) Each element of the array x may contain a single value of type double, so a total of eight such numbers may be stored and referenced using the array name x. To process the data stored in an array, we reference each individual element by specifying the array name and identifying the element desired. The elements are numbered starting with 0 An array with 8 elements has elements at 0,1,2,3,4,5,6, and 7 The subscripted variable x[0] (read as x sub zero) refers to the initial or 0th element of the array x, x[1] is the next element in the array, and so on. The integer enclosed in brackets is the array subscript or index and its value must be in the range from zero to one less than the array size. 7

The Elements of Array We use the array subscript to specify the array element being manipulated, which ranges from zero to one less than the number of size. Array size Array subscript 8

9

Array Initialization When you declare a variable, its value isn t initialized unless you specify. int sum; // Does not initialize sum int sum = 1; // Initializes sum to 1 Arrays, like variables, aren t initialized by default int X[10]; //creates the array, but doesn t set any of its values. To initialize an array, list all of the initial values separated by commas and surrounded by curly braces: int X[10] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; The array elements are initialized in the order listed X[0] = 2; X[4] = 11; 10

Array Initialization If there are values in the initialization block, but not enough to fill the array, all the elements in the array without values are initialized to 0 in the case of double or int, and NULL in the case of char. int scores[20] = {0}; // all 20 elements are initialized to 0 int scores[20] = {1, 2, 3}; // First 3 elements are initialized to 1, 2, // 3 and the rest are initialized to 0 If there are values in the initialization block, an explicit size for the array does not need to be specified. Only an empty array element is sufficient, C will count the size of the array for you. int scores[] = {20, 10, 25, 30, 40}; // size of the array score is // automatically calculated as 5 11

Array Initialization We can initialize an array in its declaration. We can omit the size of an array that is being fully initialized since the size can be deduced from the initialization list. e.g., char vowels[] = { A, E, I, O, U }; int prime[]={2, 3, 5, 7, 11, 13, 17, 19, 23}; 12

Visual representation of an Array int x[8]; x[2] = 20; Memory Addresses 342901 342905?? 0 1 Array Index/Subscript 342909 20 2 342913? 3 Array Element 342917? 4 342921? 5 342925? 6 342929? 7 Note: Index starts with 0, not with 1 13

Array Subscripts We use subscripts/indices to differentiate between the individual array elements We can use any expression of type int as an array subscript. However, to create a valid reference, the value of this subscript must lie between 0 and one less than the array size. It is essential that we understand the distinction between an array subscript value and an array element value. int x[2]; int y = 1; x[y] = 5; The subscript is y (which is 1 in this case), and the array element value is 5 C compiler does not provide any array bound checking. As a programmer it is your job to make sure that every reference is valid (falls within the boundary of the array). 14

Access 1. point[1] // the 2 nd element of array point is accessed 2. point[9] = 20; // the 10 th element of array point is assigned // the value 20 3. Want to process all of the elements of an array? Example: Adding the values of all array elements Two alternative style for loops for ( i = 0; i < arraysize; i++) sum += a[i]; for ( i = 0; i <= arraysize-1; i++) sum += a[i]; Note : The array element is a single valued variable of the corresponding type and can be manipulated as a variable of that type. 15

Using for Loops for Sequential Access The elements of an array are usually processed by for loops, because the elements are sequentially stored in the memory, and the for loop is suitable for sequential manipulation. e.g., int square[size], i; for(i=0; i<size; i++) square[i]=i*i; 16

Access (2) int x[5]; // declare an integer array of size 5 int i = 2; x[0] = 20; // valid x[2.3] = 5; // Invalid, index is not int x[6] = 10; // valid, but dangerous x[2*i 3] = 3; // valid, assign 3 to x[1] x[i++]; // access x[2] and then assign 3 to i x[(int) x[1]]; // access x[3] Referencing to an array element outside of the created bounds is possible but rather not recommended. 17

Algorithm for Searching an Array 1.Flag=false 2. foundelementindis=-1 2. Start with the intial array element 3. Repeat while the target is not found and there are more 4. if the current element matches array 5. set flag true 6. Set foundelementindis to current array index 7. else 8. advance to next array element 9. return the array index 18

#include <stdio.h> int main() { int found = 0, i, index=-1, target=8; int arr[10]; for (i=0;i<10;i++)//read values into array arr scanf("%d",&arr[i]); i=0; while (!found && (i <10) ) { if ( arr[i] == target ) { found = 1; index = i; } else i++; } if (index!=-1) //target is found printf("target found at index#:%d",index); } 19

Multidimensional Arrays A multidimensional array is an array with two or more dimensions. We will use two-dimensional arrays to represent tables of data, matrices, and other two-dimensional objects. Thus int x[3][3] would define a three by three matrix that holds integers. Initialization is bit different int x[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}}; Both indices start from 0. x[0][0]=1 x[0][1]=2 x[0][2]=3 Think of it as x[rows][cols]. x[1][0]=4 x[1][1]=5 x[1][2]=6 x[2][0]=7 x[2][1]=8 x[2][2]=9 Row Col inside a row 20

Multidimensional Arrays Multidimensional arrays stand for the arrays with two or more dimensions. Syntax for normal usage: element-type aname[size 1 ][size 2 ] [size n ]; Syntax for parameter in function prototype: element-type aname[][size 2 ] [size n ] e.g., char tictac[3][3]; A 2-dimensional array with three rows and three columns. e.g., tictac[][3]; The declaration for the function prototype. 21

The Memory Allocated for tictac[3][3] The memory allocated for array tictac[3][3] is shown below. The number of total allocated element is 3*3=9 elements. 22

Initialization of Multidimensional Arrays The multidimensional array can also be initialized in declarations. The initialized values are grouped in rows. e.g., char tictac[3][3]={{ a, b, c }, { d, e, f }, {,, }}; We can also declare arrays with more dimensions. e.g., declare a 3-dimensional array. int enroll[course][campus][cls_rank]; 23

2D array in address space How to store a multidimensional array into a one-dimensional memory space. Row major ordering assigns successive elements, moving across the rows and then down the columns, to successive memory locations. Address of a[row][col] = Base_Address + (row * row_size + col) Base_Address is the address of the first element of the array (A[0][0] in this case). char *base = &A[0][0]; 24

Multi-dimensional Arrays Declaration int a[n]; int b[m][n]; int c[l][m][n]; Array element a[i] b[i][j] c[i][j][k] Pointer to element a b[i] c[i][j] Pointer to 1D array of N element Pointer to 2D array of M*N element b c[i] c 25

The Memory Allocated for enroll[100][5][4] enroll[100][5][4] consists of 100*5*4 =2000 elements. 26