Programming for Engineers Arrays

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

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

Multiple-Subscripted Arrays

Arrays and Applications

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

C Arrays. O b j e c t i v e s In this chapter, you ll:

C Arrays Pearson Education, Inc. All rights reserved.

Programming for Engineers Introduction to C

C++ PROGRAMMING SKILLS Part 4: Arrays

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

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

Fundamentals of Programming Session 14

C: How to Program. Week /Apr/23

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

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

Array. Arrays. Declaring Arrays. Using Arrays

Lecture 04 FUNCTIONS AND ARRAYS

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

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

Content. In this chapter, you will learn:

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

Objectives of This Chapter

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

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

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

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

Fundamentals of Programming Session 4

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

ONE DIMENSIONAL ARRAYS

Arrays (Deitel chapter 7)

C Programming for Engineers Functions

by Pearson Education, Inc. All Rights Reserved.

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

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

Array Initialization

Fundamentals of Programming. Lecture 11: C Characters and Strings

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

Computer Science & Engineering 150A Problem Solving Using Computers

C: How to Program. Week /Mar/05

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

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

Arrays. Systems Programming Concepts

Introduction to C Final Review Chapters 1-6 & 13

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Module 6: Array in C

Introduction to Computer Science Midterm 3 Fall, Points

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Instructor: Eng.Omar Al-Nahal

Chapter 2 - Introduction to C Programming

C: How to Program. Week /Apr/16

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

UIC. C Programming Primer. Bharathidasan University

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

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

Objectives. In this chapter, you will:

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

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

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

INTRODUCTION 1 AND REVIEW

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

The C++ Language. Arizona State University 1

Chapter 3: Arrays and More C Functionality

Principles of Programming. Chapter 6: Arrays

Write a C program using arrays and structure

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

EC312 Chapter 4: Arrays and Strings

A Fast Review of C Essentials Part I

Programming for Engineers Iteration

Decaf Language Reference Manual

UNIT- 3 Introduction to C++

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

Advanced C Programming Topics

Arrays. Week 4. Assylbek Jumagaliyev

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

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

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

Fundamental of Programming (C)

ARRAYS(II Unit Part II)

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

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

Fundamentals of Programming. Lecture 3: Introduction to C Programming

M.CS201 Programming language

Full file at C How to Program, 6/e Multiple Choice Test Bank

PROGRAMMAZIONE I A.A. 2017/2018

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.

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

by Pearson Education, Inc. All Rights Reserved. 2

1 Lexical Considerations

Chapter 7 : Arrays (pp )


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

Array. Prepared By - Rifat Shahriyar

Transcription:

Programming for Engineers Arrays ICEN 200 Spring 2018 Prof. Dola Saha 1

Array Ø Arrays are data structures consisting of related data items of the same type. Ø A group of contiguous memory locations that all have the same type. Ø To refer to a particular location or element in the array Array s name Position number of the particular element in the array 2

Example Array 3

Array indexing Ø The first element in every array is the zeroth element. Ø An array name, like other identifiers, can contain only letters, digits and underscores and cannot begin with a digit. Ø The position number within square brackets is called an index or subscript. Ø An index must be an integer or an integer expression array_name[x], array_name[x+y], etc. Ø For example, if a = 5 and b = 6, then the statement o c[a + b] += 2; adds 2 to array element c[11]. 4

Array in memory Ø Array occupies contiguous space in memory Ø The following definition reserves 12 elements for integer array c, which has indices in the range 0-11. o int c[12]; Ø The definition o int b[100]; double x[27]; reserves 100 elements for integer array b and 27 elements for double array x. Ø Like any other variables, uninitialized array elements contain garbage values. 5

Initializing array Output 6

Use of size_t Ø Notice that the variable i is declared to be of type size_t, which according to the C standard represents an unsigned integral type. Ø This type is recommended for any variable that represents an array s size or an array s indices. Ø Type size_t is defined in header <stddef.h>, which is often included by other headers (such as <stdio.h>). Ø [Note: If you attempt to compile Fig. 6.3 and receive errors, simply include <stddef.h> in your program.] 7

Initializing with initializer list Output 8

Initializing with fewer initializers Ø If there are fewer initializers than elements in the array, the remaining elements are initialized to zero. Ø Example: // initializes entire array to zeros int n[10] = {0}; Ø The array definition o int n[5] = {32, 27, 64, 18, 95, 14}; causes a syntax error because there are six initializers and only five array elements. 9

Initializing without array size Ø If the array size is omitted from a definition with an initializer list, the number of elements in the array will be the number of elements in the initializer list. Ø For example, o int n[] = {1, 2, 3, 4, 5}; would create a five-element array initialized with the indicated values. 10

Initializing to even list Output 11

Preprocessor Ø The #define preprocessor directive is introduced in this program. Ø #define SIZE 5 defines a symbolic constant SIZE whose value is 5. Ø A symbolic constant is an identifier that s replaced with replacement text by the C preprocessor before the program is compiled. Ø Using symbolic constants to specify array sizes makes programs more modifiable. 12

Adding elements of an array 13

Using Arrays to Summarize Poll (1) 14

Using Arrays to Summarize Poll (2) 15

Histogram with Array elements (1) 16

Histogram with Array elements (1) 17

Character Arrays & String Representation Ø Store strings in character arrays. Ø So far, the only string-processing capability we have is outputting a string with printf. Ø A string such as "hello" is really an array of individual characters in C. Ø A character array can be initialized using a string literal. Ø For example, o char string1[] = "first"; initializes the elements of array string1 to the individual characters in the string literal "first". 18

Size of Character Array Ø In this case, the size of array string1 is determined by the compiler based on the length of the string. Ø The string "first" contains five characters plus a special string-termination character called the null character. Ø Thus, array string1 actually contains six elements. Ø The character constant representing the null character is '\0'. Ø All strings in C end with this character. 19

Character Array Indexing Ø The preceding definition is equivalent to o char string1[] = {'f', 'i', 'r', 's', 't', '\0'}; Ø Because a string is really an array of characters, we can access individual characters in a string directly using array index notation. Ø For example, string1[0] is the character 'f' and string1[3] is the character 's'. 20

Scanning string Ø Ø Ø Ø Ø o We also can input a string directly into a character array from the keyboard using scanf and the conversion specifier %s. For example, char string2[20]; creates a character array capable of storing a string of at most 19 characters and a terminating null character. o The statement scanf("%19s", string2); reads a string from the keyboard into string2. The name of the array is passed to scanf without the preceding & used with nonstring variables. The & is normally used to provide scanf with a variable s location in memory so that a value can be stored there. 21

Scanning string Ø Function scanf will read characters until a space, tab, newline or end-of-file indicator is encountered. Ø The string2 should be no longer than 19 characters to leave room for the terminating null character. Ø If the user types 20 or more characters, your program may crash or create a security vulerability. Ø For this reason, we used the conversion specifier %19s so that scanf reads a maximum of 19 characters and does not write characters into memory beyond the end of the array string2. 22

Memory Management in Scanning String Ø It s your responsibility to ensure that the array into which the string is read is capable of holding any string that the user types at the keyboard. Ø Function scanf does not check how large the array is. Ø Thus, scanf can write beyond the end of the array. Ø You can use gets(text) to get the text from user. 23

Printing String Ø A character array representing a string can be output with printf and the %s conversion specifier. Ø Ø The array string2 is printed with the statement o printf("%s\n", string2); Ø Function printf, like scanf, does not check how large the character array is. Ø The characters of the string are printed until a terminating null character is encountered. 24

Treating Character Arrays as String (1) 25

Treating Character Arrays as String (2) 26

Passing Arrays to Functions Ø Ø Ø Ø To pass an array argument to a function, specify the array s name without any brackets. For example, int hourlytemperatures[hours_in_a_day]; modifyarray(hourlytemperatures, HOURS_IN_A_DAY); the function call passes array hourlytemperatures and its size to function modifyarray. The name of the array evaluates to the address of the first element of the array. The called function can modify the element values in the callers original arrays. 27

Passing Array to Functions (1) 28

Passing Array to Functions (2) 29

Passing Array to Functions (3) 30

Passing Array to Functions (4) 31

Protecting Array Elements Ø Function trytomodifyarray is defined with parameter const int b[], which specifies that array b is constant and cannot be modified. Ø The output shows the error messages produced by the compiler the errors may be different for your compiler. 32

Classwork Assignment Ø Search an Array: Write a program to initialize an array of size S with an initializer list. Also get a value for num1 from user. Pass the array as well as num1 to a function. Within the function, check each element of array whether it matches num1. If it matches, return 1, else return 0 to the main function. 33

Binary Search searching in a sorted array Ø The linear searching method works well for small or unsorted arrays. Ø However, for large arrays linear searching is inefficient. Ø If the array is sorted, the high-speed binary search technique can be used. Ø The binary search algorithm eliminates from consideration one-half of the elements in a sorted array after each comparison. 34

Binary Search searching in a sorted array Ø The algorithm locates the middle element of the array and compares it to the search key. Ø If they re equal, the search key is found and the index of that element is returned. Ø If they re not equal, the problem is reduced to searching one-half of the array. Ø If the search key is less than the middle element of the array, the first half of the array is searched, otherwise the second half of the array is searched. 35

Demo Ø Demo from Princeton https://www.cs.princeton.edu/courses/archive/fall06/cos226/demo/demobsearch.ppt 36

Binary Search C code (1) 37

Binary Search C code (2) 38

Binary Search C code (3) 39

Binary Search C code (4) 40

Binary Search C code (5) 41

Binary Search C code (6) 42

Binary Search C code (7) 43

Multidimensional Arrays Ø Arrays in C can have multiple indices. Ø A common use of multidimensional arrays is to represent tables of values consisting of information arranged in rows and columns. Ø Multidimensional arrays can have more than two indices. 3x4 Array 44

Initialization Ø Where it is defined Braces for each dimension o int b[2][2] = {{1, 2}, {3, 4}}; If there are not enough initializers for a given row, the remaining elements of that row are initialized to 0. o int b[2][2] = {{1}, {3, 4}}; If the braces around each sublist are removed from the array1 initializer list, the compiler initializes the elements of the first row followed by the elements of the second row. o int b[2][2] = {1, 2, 3, 4}; 45

Multidimensional Array Example Code (1) 46

Multidimensional Array Example Code (2) 47

Two Dimensional Array Manipulation Ø Example Ø studentgrades[3][4] Row of the array represents a student. Column represents a grade on one of the four exams the students took during the semester. The array manipulations are performed by four functions. Function minimum determines the lowest grade of any student for the semester. Function maximum determines the highest grade of any student for the semester. Function average determines a particular student s semester average. Function printarray outputs the two-dimensional array in a neat, tabular format. 48

2D Array Manipulation Code (1) 49

2D Array Manipulation Code (2) 50

2D Array Manipulation Code (3) 51

2D Array Manipulation Code (4) 52

2D Array Manipulation Code (5) 53

2D Array Manipulation Code (6) 54

2D Array Manipulation Code (7) 55

Lab Assignment Ø Matrix Addition/Subtraction two matrices should have same number of rows and columns. Addition Subtraction https://en.wikipedia.org/wiki/matrix_addition 56

Matrix Multiplication Ø If A is a n m matrix and B is a m p matrix, then Matrix Multiplication is given by following formula https://en.wikipedia.org/wiki/matrix_multiplication 57

Matrix Multiplication - Illustrated 58

Variable Length Array Ø In early versions of C, all arrays had constant size. Ø If size is unknown at compilation time Use dynamic memory allocation with malloc Ø The C standard allows a variable-length array An array whose length, or size, is defined in terms of an expression evaluated at execution time. 59

Variable Length Array Code (1) 60

Variable Length Array Code (2) 61

Variable Length Array Code (3) 62

Variable Length Array Code (4) 63

Variable Length Array Code (5) 64

Scan string with space Ø Function scanf will read characters until a space, tab, newline or end-of-file indicator is encountered. Ø Use fgets function. char *fgets(char *str, int n, FILE *stream) str character array n maximum number of characters to be read stream where we are reading the data from 65

Classwork Ø Reverse an array 66

Classwork Ø Represent a 2D array by a 1D array 67

Classwork Ø Insert an element in a sorted array 68

Classwork Ø Find second minimum 69