Principles of Programming. Chapter 6: Arrays

Similar documents
Functions. Arash Rafiey. September 26, 2017

Arrays and Strings. Arash Rafiey. September 12, 2017

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #04

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

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

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Computer Science & Engineering 150A Problem Solving Using Computers

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

More Arrays. Last updated 2/6/19

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.

Lecture 04 FUNCTIONS AND ARRAYS

Arrays. Week 4. Assylbek Jumagaliyev

Computer Programming: C++

Sample Examination. Family Name:... Other Names:... Signature:... Student Number:...

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

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

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

Programming for Engineers Arrays

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

Content. In this chapter, you will learn:

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

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

EENG 212 Lab 2. Recursive Functions

Objectives of This Chapter

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

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

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

Introduction to C Final Review Chapters 1-6 & 13

Two Dimensional Array - An array with a multiple indexs.

Module 6: Array in C

Basic and Practice in Programming Lab7

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

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

How to declare an array in C?

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number:

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

C library = Header files + Reserved words + main method

AMCAT Automata Coding Sample Questions And Answers

Procedural Programming

Programming in OOP/C++

Arrays and Applications

Government Polytechnic Muzaffarpur.

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

C: How to Program. Week /Apr/23

C++ PROGRAMMING SKILLS Part 4: Arrays

Chapter 6: Using Arrays

Introduction to Computer Science Midterm 3 Fall, Points

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Computer Programming Lecture 14 Arrays (Part 2)

Materials covered in this lecture are: A. Completing Ch. 2 Objectives: Example of 6 steps (RCMACT) for solving a problem.

CSCI 2132 Software Development. Lecture 17: Functions and Recursion

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Introduction to Scientific Computing and Problem Solving

One Dimension Arrays 1

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

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

ARRAYS(II Unit Part II)

CSCI 2132 Software Development. Lecture 18: Functions

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

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

Last Class. More on loops break continue A bit on arrays

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

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

C Arrays Pearson Education, Inc. All rights reserved.

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays. Dr. Madhumita Sengupta. Assistant Professor IIIT Kalyani

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

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

BITG 1113: Array (Part 1) LECTURE 8

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

Two Dimensional Array - An array with a multiple indexs.

PROGRAMMING IN C AND C++:

LAB 1 Binary Numbers/ Introduction to C. Rajesh Rajamani. ME 4231 Department of Mechanical Engineering University Of Minnesota

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

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?

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

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Unit 3. Operators. School of Science and Technology INTRODUCTION

More Pointers Week 11

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

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

Solutions to Chapter 8

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Array. Arrays. Declaring Arrays. Using Arrays

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

C: How to Program. Week /Mar/05

Dept. of CSE, IIT KGP

Q1: Functions / 33 Q2: Arrays / 47 Q3: Multiple choice / 20 TOTAL SCORE / 100 Q4: EXTRA CREDIT / 10

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

COMPUTER APPLICATION

Lab Session # 5 Arrays. ALQUDS University Department of Computer Engineering

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

CS16 Exam #1 7/17/ Minutes 100 Points total

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

Lecture 9 - C Functions

Transcription:

Chapter 6: Arrays In this chapter, you will learn about Introduction to Array Array declaration Array initialization Assigning values to array elements Reading values from array elements Simple Searching Simple Sorting 2 Dimensional arrays Working with matrices S1 2017/18 1

Introduction to Array In C, a group of items of the same type can be set up using Array An array is a group of consecutive memory locations related by the fact that they all have the same name and the same type. The compiler must reserve storage (space) for each element/item of a declared array. The size of an array is static (fixed) throughout program execution. To refer to a particular location or element in the array, we specify the name of the array and its index (the position number of the particular element in the array). 2

Let say we have an array called a. Name of the array The position number within the square brackets is formally called a subscript. A subscript can be an integer or an integer expression. For example if x = 1 and y = 2, then a[x+y] is equal to a[3]. a[0] a[1] a[2] a[3] a[4] a[5] a[6] Notice that the position starts from 0. -10 99-8 100 27 10 1976 3 a[7] a[8] -2020 1

Array Declaration Array declaration is made by specifying the data type, it s name and the number of space (size) so that the computer may reserve the appropriate amount of memory. General syntax: data_type array_name[size]; Examples: int my_array[100]; char name[20]; double bigval[5*200]; int a[27], b[10], c[76]; 4

Array Initialization Principles of Programming There are 2 ways to initialize an array: during compilation and during execution. During compilation: int arr[ ] = 1, 2, 3, 4, 5; Unsized array : We can define how many elements that we want since the array size is not given. int arr[3] = 90, 21, 22; We can define only 3 elements since the array size is already given. int arr[5] = 2,4; Initialize the first two elements to the value of 2 and 4 respectively, while the other elements are initialized to zero. int arr[5] = 0; Initialize all array elements to zero. 5

Array Initialization cont During execution: Using loop to initialize all elements to zero int arr[3], index; for (index = 0; index < 3; index++) arr[index] = 0; Using loop and asking the user to specify the value for each element. int arr[3], index; for (index = 0; index < 3; index++) printf ( arr[%d]:,index); scanf( %d,&arr[index]); 6

Assigning value to array element We can assign a value to a specific array element by using its index number. Example: let s say we have an array that represents the number of inhabitants in 5 apartment units. int apartment[5]=3,2,6,4,5; The above initialization indicates that there are 3 people living in apartment 0, 2 people living in apartment 1 and so on. Let say that we have a new born in apartment 3, so we need to change the number of inhabitants living in apartment three. apartment[3] = apartment[3] + 1; Now, we have the following values in our array: apartment [0] [1] [2] [3] [4] 3 2 6 5 5 Principles of Programming 7

Reading values from array elements Principles of Programming We can read a value from a specific array element by referring to the index. For example, let s say we want to know how many people leaving in apartment 3, we could simple do this: int apartment[5] = 3,2,6,4,5; int no_of_people; no_of_people = apartment[3]; printf( Apartment 3 has %d people,no_of_people); The above C code will produce the following output: Apartment 3 has 4 people Press any key to continue Remember that array s index starts at 0! 8

Example 1: finding total inhabitants #include <stdio.h> #define size 5 int main(void) int apartment[size] = 3,2,6,4,5; int index, total = 0; for (index = 0; index < size; index++) total = total + apartment[index]; Principles of Programming printf("there are total of %d inhabitants",total); return(0); There are total of 20 inhabitants Press any key to continue 9

Example 2: list down number of inhabitants in each apartment #include <stdio.h> int main(void) int apartment[5] = 3,2,6,4,5; int index, total = 0; printf("%s\t%s\n","apt No", "No of people"); for (index = 0; index < 5; index++) printf("%d\t%d\n",index, apartment[index]); return(0); 10 Apt No 0 3 1 2 2 6 3 4 4 5 No of people Press any key to continue

Exercise 1 Modify from example 1, write a program that prints the average number of inhabitants. Principles of Programming 11

Exercise 2 Principles of Programming Given the following ordered list of floating point numbers, write a program that determines its median and standard deviation. Standard deviation formula, : 1.0, 6.0, 18.0, 39.0, 86.0 12

Data Searching Searching is the process of determining whether an array contains a value that matches a certain key value/search key. The process of finding a particular element of an array is called searching. There are more than one algorithms that can be used to do a search. The most commonly used searching techniques are linear search and binary search. Here, we will discuss how to do searching by using linear search on an array. Principles of Programming 13

Linear Search Search key is a data element of the same type as the list elements. If search key == list element value, the search is said to be successful. Otherwise, it is unsuccessful. Linear search is a simple searching algorithm where: data are stored in an array a search key is compared with each elements in the array starting from the first element. 14

#include <stdio.h> Example: Linear Search int main(void) int list[ ] = 34, 53, 21, 23, 4; int i, search_key, found = 0; printf( Enter the number that you want to find: ); scanf( %d, &search_key); for (i = 0; i < 5; i++) if (list[i] = = search_key) found = 1; printf( %d is found at index %d\n, search_key, i); if (found = = 0) printf( %d cannot be found in the list\n,search_key); return(0); 15 Enter the number that you want to find: 53 53 is found at index 1 Press any key to continue

Sorting Sorting is the process of placing data into a particular order such as ascending or descending. The following example shows the C code for sorting unsorted list to a list sorted in ascending order. Explanation for the working program and the concept behind it will be done during lecture hour (so please attend the class!!!!). Principles of Programming 16

Example: Simple Sort void main(void) int pivot, checker, temp, list[]=3, 2, 5, 4, 1; for (pivot = 0; pivot < (size - 1); pivot++) for (checker = (pivot + 1); checker < size; checker++) if (list[checker] < list[pivot]) /* swap the elements */ temp = list[pivot] ; list[pivot] = list[checker]; list[checker] = temp; for(int i=0; i<5; i++) printf("%d ", list[i]); 17

Two-Dimensional Array It is possible to create an array which has more than one dimension. For example: 2D array: int array[4][2]; Graphical representation of a 2D array: Principles of Programming int myarray[4][2] = 1,2,3,4,5,6,7,8; Row 1 Row 2 Row 3 Row 4 1 2 3 4 5 6 7 8 Col 1 Col2 This array has 4 rows and 2 columns. 18

Two-Dimensional Array cont Principles of Programming Variable initialization can also be done this way: int myarray[4][2] = 1,2,3,4,5,6,7,8; This method is less confusing since we can see the rows and columns division more clearly. To initialize a 2D array during execution, we need to use a nested for loop: for (row = 0; row < 4; row++) for (column = 0; column < 2; column++) myarray[row][column] = 0; Although it is possible to create a multi-dimensional array, arrays above 2-dimensions are rarely used. 19

Matrices Principles of Programming A matrix is a set of numbers arranged in a rectangular grid with rows and columns. Below is an example of a matrix with four rows and three columns, specified as 4 x 3 matrix 1 0 0 1 1 0 A = 1 2 3 0 2 1 Be careful when translating equations in matrix notation into C statements because of the difference in subscripting, i.e. in matrix, row and column numbers begin with 1. 20

Example Write program that perform dot product from the following vectors. A = 4 1 3 Principles of Programming B = 2 5 2 int main (void) int k, product=0, A[] = 4, -1, 3, B[] = -2, 5, 2; for (k=0; k<size-1;k++) product += A[k]*B[k]; printf( %d, product); return 0; 21

Exercise Write a program that can perform addition and subtraction of two same size matrices. 22

Beyond Two-Dimensional Array Declaration of 3 dimensional array 3D array: int array[2][3][4]; Principles of Programming Four-dimensional array? 23

Summary In this chapter, we have looked at: Array declaration and initialization Reading and writing from/to array elements Passing array to function Simple search Simple sort 2 dimensional array Working with matrices 24

Exercise Assume the following array declaration float number[5] = 2.3, 4.2, 5.0, 7.9, 6.2; What will be the output of the following statement? a) printf( %f, number[2+2] ); b) printf( %f, number[2]+2 ); c) printf( %f, number[1*2] ); d) printf( %f, number[1]*2 ); 25

Exercise Assume the following array declaration int result[5] = 56, 69, 89; int i = 2; What will be the output of the following statement? a) printf( %d, result[1]); b) printf( %d, result[4]); c) printf( %d, result[0] + result[1]); d) printf( %d %d, i, result[i]); 26

Exercise Assume the following array declaration int result[3*2]; a) Write C statements that would read the values for the array element from the user. b) Write C statements that would list down all the values in the array. c) Write C statements that would sum up all the values in the array. 27