To become familiar with array manipulation, searching, and sorting.

Similar documents
o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Why Is Repetition Needed?

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Multiple-Subscripted Arrays

VARIABLES & ASSIGNMENTS

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Lab 10: Alternate Controls

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

CSCE 206: Structured Programming in C++

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Chapter 1 - What s in a program?

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

The American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010

Chapter 10 - Notes Applications of Arrays

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

LESSON 3 CONTROL STRUCTURES

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Lab # 02. Basic Elements of C++ _ Part1

Chapter Four: Loops II

Sorting. Bubble Sort. Selection Sort

C++ Programming Lecture 1 Software Engineering Group

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Chapter 5: Control Structures II (Repetition)

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

Arrays. Week 4. Assylbek Jumagaliyev

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

C/C++ Programming Lecture 18 Name:

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

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

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Exam 1. CSI 201: Computer Science 1 Fall 2018 Professors: Shaun Ramsey

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 17 - Notes Recursion

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

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

REPETITION CONTROL STRUCTURE LOGO

C++ PROGRAMMING SKILLS Part 4: Arrays

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

In this chapter you will learn:

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Algorithm Design and Recursion. Search and Sort Algorithms

Computers in Engineering COMP 208. Where s Waldo? Linear Search. Searching and Sorting Michael A. Hawker

! Search: find an item in an array, return the. ! Sort: rearrange the items in an array into some. ! There are various methods (algorithms) for

Outline. For loops, nested loops and scopes. Calculate x y. For loops. Scopes. Nested loops. Algorithm: repeated multiplication x x x x

Searching for Information. A Simple Method for Searching. Simple Searching. Class #21: Searching/Sorting I

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Measuring algorithm efficiency

Unit 7. 'while' Loops

(Refer Slide Time: 00:26)

Week 4 EECS 183 MAXIM ALEKSA. maximal.io

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Final Examination Semester 2 / Year 2005

Problem Solving: Storyboards for User Interaction

University of Michigan EECS 183: Elem. Programming Concepts Fall 2011 Exam 1: Part 1: Form 1. Professors: ML Dorf, Elliot Soloway

Introduction to Programming using C++

Chapter 2 Basic Elements of C++

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Dr. Khalil Exam II Fall 2011

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Loops (while and for)

Lecture 6 Sorting and Searching

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

C++ for Python Programmers

LAB: FOR LOOPS IN C++

C++ Programming: From Problem Analysis to Program Design, Third Edition

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

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

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

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

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

PIC 10A. Review for Midterm I

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Security Coding Module Integer Error You Can t Count That High CS1

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

LAB: WHILE LOOPS IN C++

ENGR 1181 MATLAB 09: For Loops 2

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

DATA STRUCTURES/UNIT 3

Transcription:

ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation, searching, and sorting. 1. Filling and Manipulating Arrays (5 marks) 2. Searching Arrays (3 marks) 3. Sorting Arrays (9 marks) 4. Searching Sorted Arrays (3 marks) INSTRUCTIONS: Carry out the coding experiment and submit your results on this paper at next week s lab. 1. FILLING AND MANIPULATING ARRAYS In Lab 1 we started to use control structures such as if, for, etc. to begin to analyze data. We will continue by first creating some new data to manipulate. Generally we could use a series of random numbers but since there are a variety of C++ compilers in use by the students it will be difficult to get the same results as these compilers generate random numbers differently. We will simplify our approach by generating a series of 20 (adjustable by modifying the #define entries line) predictable numbers which will appear random by are really not. Please begin by copying this code into a new project. If you are using Visual C++ make sure you add it after the #include stdafx.h. #include <iostream> #include <iomanip> using namespace std; #define entries 20 int main() int i,j,v; int list1[entries], list2[entries]; for(i = 0, j = 0; i < entries; i++, j += 1299827) v = (j % 1024); /* set array values here */ return 0; Your task is to add code which will set the ith element of list1 and list2 to v, for i s from 0 to entries-1. Write only that code below: 06-88-211 Laboratory #2 1/5

Just above the return 0 add code which will print out contents of list1 and list2 preceded by its element index (one element index per line). Write only that code below: Now we will begin to do a little data manipulation using the skills we have developed so far. Add code before where you print the contents of the lists that will add the ith and ith+1 entry of list1 together and store it in the ith entry of list2 and subtract the ith+1 entry from the ith entry of list1 and store it in the ith+1 entry of list2. You should start at the first entry, 0 and skip every two entries when performing this task. Write only that code below: Verify that your output is correct by doing some mental math. It is easy to use software to manipulate numbers mathematically. It is just a matter of knowing what is necessary to do and then apply it in the proper order when writing software. 2. SEARCHING ARRAYS Remove the above code fragment from your base code. We will now write some code which will search for the largest element in list2 (we will leave list1 in its original state so we can use it to compare our results later). There are a number of approaches which can be used for searching, but given that our data is not sorted in any specific order, this leaves us with far fewer options. We will use an approach where we keep track of the largest element by remembering its element number or index in the array not necessarily its value (we can just reference the array to find that out). We will use a new integer for this, it is essentially a flag; call it whatever you like but make sure it is initially set to 0. This will imply that the largest element is the first one in the list, a reasonable assumption at this point. To guarantee that this index refers to the largest value in list2 then we have to compare it with all the other items in list2. We need a loop for this; it should start at the second element (since we already said the first is currently the largest) and go all the way to the last. Every time we find a value that is larger than the current one, we will replace it with the new index of the larger value. When your loop is done we will know which entry in list2 has the largest value. Write only this code below: 06-88-211 Laboratory #2 2/5

Given that we have 20 items in our list, it took 19 comparisons to find the largest one. It would take a similar number of comparisons, on average, if we were to look for a particular value or range of values. This is because the list of items is not sorted. We know that when we need to access information often the best way to do this is when it is sorted. For example, if you need to look-up a word in a dictionary or thesaurus we simply look at the first few letters of the word to determine its location. If the words in either of these books were unsorted it could take a very long time to find them. So we will modify our code to sort the items in list2 from highest to lowest. Just like searching for information there are a number of methods to sort information. We will examine a simple approach which may take more time than other methods but it is easier to understand and it is based on the method we used to search for the largest value. 3. SORTING ARRAYS At this point we know the index of the largest value so we now need to place the largest value into the first index. To do this we will swap the two elements, the current first value and the largest value. It is possible that the first value is already the largest value so we could place a condition on our swapping code not to actually swap them if it is already in the proper place. To do a swap we move information from one location which we will call position1 into another which we call position2, and the original information in position2 must be moved to position1. Computers don t have short term memory like us so we have to properly instruct them on how to swap the values. To do this properly we must save the information in position2 first before we overwrite it from that of position1. We will therefore need a temporary variable to hold this, so copy the information in position2 first to the temporary location, then copy the information in position1 to position2, and then copy the information in the temporary variable to position1. Write the code below that does this: At this point the first element in list2 should be the highest but all the other elements are unsorted. To completely sort of all elements in the list we do the same operation as we did before but we start at the second item. Again we use our flag to indicate that this is the largest value and search the remaining items to see if any of those are larger. If this is the case, we update our flag and move on. When this loop is done, we swap the largest element with the second one in the list and now our list has the two largest items at the top of the list. We continue to do this until we are on the second last item. Our loop at this point will only compare it to the last, and will swap them if necessary. This approach is called a selection sort since we are selecting the largest item in our list and moving it to the beginning of our list. To code this we need two nested loops. The outer loop will go from the first to the second last elements (0 to entries-2 inclusively). Inside this loop you will place your code for searching for and swapping the largest value. Be careful to change the references from the first element, 0, to the value of the outer loop counter. Your inner loop should go from the current outer loop element plus 1 to the last (entries-1) inclusively. Write your code below that does this: 06-88-211 Laboratory #2 3/5

Your output should show the index and values of list1 and list2 side by side such that list1 is unsorted and list2 is sorted. If we wanted to make is so that list2 was sorted smallest to largest, what single line change would be required in the above code to do this? Write only that modified line below: Now that we have sorted data, we can search it easier. Apply the above change so that the code will generate lists sorted smallest to largest for the next lab section. Before moving on we will examine the number of repetitions that occurred in this sorting loop. Add a new variable, n, and initialize it to 0 before sorting the array, then increment n each time we perform one iteration of the inner loop. Indicate the value of n below given the 20 values in our array. Now increase the elements in our array to something larger (ie. change value on #define line). How has n changed? Can you predict the value of n based on the number of elements in the array? 4. SEARCHING SORTED ARRAYS We have seen previously that searching an unsorted array in a linear order for a particular item takes approximately n iterations. Once the array is sorted however the number of iterations on average drops to n/2 06-88-211 Laboratory #2 4/5

since we can stop searching once we have exceeded those values in the list. Using whatever value for the number of elements, add the following to your code just before the return 0; line and run it. for (j = 0; j < entries; j++, n++) if (i == list1[j]) break; cout << "Iterations for linear search in unsorted array: " << n << endl; for (j = 0; j < entries; j++, n++) if (i <= list2[j]) break; cout << "Iterations for linear search in sorted array: " << n << endl; The first part of the code searches the unsorted array for all values between 0 and 1023 (our range of data) and then reports the total number of iterations. The second part of the code searches the sorted array for the same values and reports the number of iterations. Enter your results below along with the number of iterations for both cases. Based on the number of elements in the array, do these results corroborate with the earlier statements? When dealing with sorted arrays it is clear that performing a linear search is not the most efficient method to find information. One of the most efficient approaches is called a binary search; this is typically what we do when we search for something, we just aren t aware of it. An excellent example of this is the number guessing game where all you are told is whether your guess is lower or higher than the target. If you are asked to guess a number between 1 and 16, what is the best first choice? 8 of course since it is the mid-point between 1 and 16. If you were told that your guess was lower than the target value, you would then proceed to guess the mid-point between 8 and 16 which is 12. If you were then told lower, you would guess the mid-point between 8 and 12 which is 10. And finally if you were told higher, you would select the mid-point between 10 and 12 which is 11 the correct answer. It only took 4 tries with 16 elements with a binary (2) search. Remember this for later. Add the following code before the return 0 which illustrates the binary search with our sorted array and run it. int u = entries, l = 0; while (l<u) n++; j = l + (u - l) / 2; if (i < list2[j]) u = j; else if (i > list2[j]) l = j+1; else break; cout << "Iterations for binary search in sorted array: " << n << endl; This code searches the array using a binary search for all values between 0 and 1023. Your result should be far less than the linear search on the sorted array. Determine the relationship between the number of iterations and elements in the array for the binary search? 06-88-211 Laboratory #2 5/5