Computer Science & Engineering 150A Problem Solving Using Computers

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

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

Lecture 6 Sorting and Searching

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

Introduction to Computer Science Midterm 3 Fall, Points

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

Computer Programming: C++

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

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

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

Make sure the version number is marked on your scantron sheet. This is Version 1

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

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

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

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.

Principles of Programming. Chapter 6: Arrays

ESC101N: Fundamentals of Computing End-sem st semester

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

Subject: Fundamental of Computer Programming 2068

C Arrays Pearson Education, Inc. All rights reserved.

LECTURE 17. Array Searching and Sorting

Programming for Engineers Arrays

Functions. Arash Rafiey. September 26, 2017

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

Solutions to Chapter 8

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays

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

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

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

C++ PROGRAMMING SKILLS Part 4: Arrays

Array. Arrays. Declaring Arrays. Using Arrays

Two Dimensional Array - An array with a multiple indexs.

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

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

How to declare an array in C?

CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays

Multiple-Subscripted Arrays

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

Lecture 04 FUNCTIONS AND ARRAYS

Arrays. Systems Programming Concepts

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):

Introduction to Scientific Computing and Problem Solving

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

Government Polytechnic Muzaffarpur.

Arrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Lecture 04 Introduction to pointers

Arrays and Applications

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Lecture06: Pointers 4/1/2013

SYSC 2006 C Winter 2012

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

One Dimension Arrays 1

Arrays and Pointers (part 1)

Function Pointers. Function Pointers

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

Array Initialization

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

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

Pointers and Arrays 1

CSCI 2132 Software Development. Lecture 17: Functions and Recursion

Goals of this Lecture

C Programming Review CSC 4320/6320

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

Objectives of This Chapter

ARRAYS(II Unit Part II)

CS 261 Data Structures. Big-Oh Analysis: A Review

by Pearson Education, Inc. All Rights Reserved.

Two Dimensional Array - An array with a multiple indexs.

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

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \

Programming for Electrical and Computer Engineers. Pointers and Arrays

Sums. Here's a (poor) program to add three numbers

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

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional 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

Pointers. Introduction

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

Arrays and Pointers (part 1)

Decision Making -Branching. Class Incharge: S. Sasirekha

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

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

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

Final CSE 131B Spring 2004

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

Computers Programming Course 11. Iulian Năstac

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

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Pace University. Fundamental Concepts of CS121 1

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

Module 4: Decision-making and forming loops

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Pointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 CMPE13. Cyrus Bazeghi

Agenda / Learning Objectives: 1. Map out a plan to study for mid-term Review the C++ operators up to logical operators. 3. Read about the tips

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

n Group of statements that are executed repeatedly while some condition remains true

Transcription:

Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009

Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using For Loops for Sequential Access 8.4 Using Array Elements as Function Arguments 8.5 Array Arguments 8.6 Searching and an Array 8.7 8.9 Programming 2 / 30

Simple data types use a single memory cell to store a variable Collections of data should be logically grouped Example: 75 students in the class; should we declare 75 separate variables to hold grades? Grouping related data items together into a single composite data structure is done using an array 3 / 30

Declaring I An array is a collection of two or more adjacent memory cells, called array elements All elements in an array are associated with a single variable name Each element is individually accessed using indices 4 / 30

Declaring II To set up an array in memory, we declare both the name of the array and the number of cells associated with it: double my_first_array[8]; int students[10]; The first one instructs C to associate 8 memory cells of type double with the name my_first_array The second one instructs C to associate 10 memory cells of type int with the name students In all cases, the memory cells will be adjacent to each other in memory 5 / 30

Array Elements I To process the data stored in an array, each individual element is associated to a reference value By specifying the array name and identifying the element desired, we can access a particular value The subscripted variable x[0] (read as x sub zero) references the first element 6 / 30

Array Elements II Other elements can be accessed similarly: x[1], x[2],... myarray[0] = 8; printf("value of second element=%d",myarray[1]); scanf("input a number: %d",&anotherarray[9]); For an array of size n, we index 0, 1,..., n 1 Think of index as an offset from base address An array size must be an integer (no such thing as half an element) Similarly, each index is also an integer 7 / 30

Array Elements I Pitfall Take care that you do not reference an index outside the array: 1 double grades [75]; 2... 3 printf ("75 th grade is %f\n", grades [74]); 4 printf (" 76 th grade is % f\ n", grades [75]); Illegal 5 printf (" -1th grade is %f\n", grades [ -1]); Illegal 6 7 int i; 8 for (i =0; i <76; i ++) 9 printf ("%d-th grade is %f\n", (i+1), grades [i ]); 10 Illegal on last iteration 8 / 30

Array You can declare multiple arrays along with regular variables: double cactus[5], needle, pins[7]; We can initialize a simple variable when we declare it: int sum = 0; Same with arrays: 1 int array [ SIZE ]; 2 for (i =0; i < SIZE ; i ++) 3 array [i] = 0; 9 / 30

Array Declaration & We can declare and initialize an array If we initialize when we declare, we can omit the size 1 int primenumberslessthanhundred [] = { 2 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 3 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 4 89, 97 }; 10 / 30

Using for Loops for Sequential Access Elements of an array are processed in sequence, starting with element zero. This processing can be done easily using an indexed for loop: a counting loop whose loop control variable runs from zero to one less than the array size. Using the loop counter as an array index (subscript) gives access to each array element in turn. 1 for (i =0; i < SIZE ; i ++) { 2 printf ("%d ",array [i ]); 3 } 11 / 30

Using Array Elements as Function Arguments You can use scanf with array elements just like with regular variables 1 int x [10]; 2 int i = 0; 3 scanf ("%d", &x[i ]); 4 printf ("Hey, I read %d\n", x[i ]); 12 / 30

as Arguments You can also use entire arrays as function arguments Passing arrays as arguments to a function means: The function can access any value in the array The function can change any value in the array Syntax: specify an array as a parameter by using the square brackets: int sum(int array[], int size); Note: what is actually being passed is a pointer to the first element of the array! We could equivalently define: int sum(int *array, int size); 13 / 30

Full Example 1 # include <stdio.h> 2 3 int sum ( int array [], int size ); 4 5 int main ( void ) 6 { 7 int foo [] = {1,2,3,4,5,6,7,8,9,10}, i; 8 printf (" sum of all array elements is %d\n",sum (foo, 10)); 9 return 0; 10 } 11 12 int sum ( int a[], int size ) 13 { 14 int i, summation = 0; 15 for (i =0; i< size ; i ++) 16 { 17 summation += a[i]; 18 } 19 return summation ; 20 } 14 / 30

Formal Array Parameter It was necessary to pass an additional variable size to sum An array does not have an explicit size associated with it C does not allocate space in memory for arrays; the operating system does this at runtime As programmers, we are responsible for: Memory management For keeping track of the size of an array For ensuring that we do not access memory outside the array If a function accesses an array, it needs to be told how big it is 15 / 30

as Input Arguments Since arrays are passed by reference (like scanf), functions can modify their values Sometimes, we would like to pass arrays as arguments, but do not want to change their values. We can do this by using the const quantifier in the function declaration: int sum(const int foo[], int size)... Specifies to the compiler that the array is to be used only as an input The function does not intend to modify the array The compiler enforces this: any attempt to change an array element in the function as an error 16 / 30

an Array Result C only allows us to return a single item It is not possible to return an array (a collection of items) We can, however, return a pointer to an array We cannot return a pointer to a local array (dangerous; undefined behavior) Requires knowledge of dynamic memory and malloc More later this semester; for now: simply declare an array large enough for your purposes Might need two controlling variables: one for max array size and one for number of cells used 17 / 30

Searching and an Array Two common problems with array processing: 1 Searching - Finding the index of a particular element in an array 2 - rearranging array elements in a particular order 18 / 30

Searching an Array 19 / 30 1 2 3 4 5 6 7 8 9 10 11 12 Assume the target has not been found Start with the initial array element, a[0] while the target is not found and there are more array elements do if the current element matches array then set flag true and store the array index end advance to next array element end if flag is set to true then return the array index end return -1 to indicate not found Algorithm 1: Searching Algorithm

Searching an Array C code 20 / 30 1 int search ( int array [], int size, int target ) 2 { 3 int found = 0, index = -1; 4 while (! found && (i < size ) ) 5 { 6 if ( array [ i] == target ) { 7 found = 1; 8 index = i; 9 } 10 else { 11 i ++; 12 } 13 } 14 if( found ) 15 return index ; 16 else 17 return -1; 18 }

an Array - Selection 1 foreach index value i = 0,..., n 2 do 2 Find the index of the smallest element in the subarray a[i,..., n 1] 3 Swap the smallest element with the element stored at index i 4 end Algorithm 2: Selection Sort Algorithm 21 / 30

an Array - Selection 22 / 30 1 void selectionsort ( int *a, int size ) 2 { 3 int i, j, minimum_index, temp ; 4 for (i =0; i<size -2; i ++) 5 { 6 minimum_ index = i; 7 for (j=i +1; j< size ; j ++) 8 { 9 if(a[ minimum_index ] > a[j]) 10 { 11 index_ of_ min = j; 12 } 13 } 14 temp = a[ i]; 15 a[i]] = a[ minimum_index ]; 16 a[ minimum_ index ] = temp ; 17 } 18 }

an Array - Bubble Sort 1 while i n 1 do 2 while j n 1 do 3 if a[j] > a[j + 1] then 4 Swap a[j] and a[j + 1] 5 end 6 end 7 end Algorithm 3: Bubble Sort Algorithm 23 / 30

an Array - Bubble Sort C code 24 / 30 1 void bubblesort ( int * a, int size ) 2 { 3 int i, j, temp ; 4 for (i =0; i<size -1; i ++) 5 { 6 for (j =0; j<size -1; j ++) 7 { 8 if (a[j] > a[j +1]) 9 { 10 temp = a[j]; 11 a[j] = a[j +1]; 12 a[j +1] = temp ; 13 } 14 } 15 } 16 }

I A multidimensional array is an array with two or more dimensions Two-dimensional arrays represent tables of data, matrices, and other two-dimensional objects Declare multidimensional arrays similar to regular arrays: int myarray[10][20]; This declares a 10 20 sized array Interpretation: 10 rows, 20 columns 25 / 30

II Each row/column is still indexed 0,..., n 1 and 0,..., m 1 Last row, last column: myarray[9][19] = 29; When iterating over a multidimensional array, use nested for loops 1 int a [10][10]; 2 for (i =0; i <10; i ++) 3 for (j =0; j <10; j ++) 4 a[i][j] = 1 + i + j; 26 / 30

of You can initialize multidimensional arrays when declaring 1 char tictactoe [][3] = { {,, }, 2 {,, }, 3 {,, } }; This would initialize a 3 3 the array with all blank spaces. 27 / 30

of When declaring and initializing, you must still provide all dimensions except the outer-most The compiler is able to deduce the outer-most dimension at compile time Not sophisticated enough to deduce the rest 28 / 30

Programming Most common error: out-of-range access error Segmentation fault, Bus error Error may not be caught in some situations: unexpected results Use correct syntax when passing arrays as parameters 29 / 30

Write the following functions and write a main driver program to test them. void printarray(int *array, int size) prints the elements of an integer array void printmatrix(int **array, int rows, int columns) prints the elements of an integer array double average(int *array, int size) computes the average of all elements in the array 30 / 30