Lab 15 Review of Arrays, Array of Objects and Vector Dr. John Abraham, Professor

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

The following is a typical execution run of this program:

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

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

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

Lab 6. Review of Variables, Formatting & Loops By: Dr. John Abraham, Professor, UTPA

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

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

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

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.

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

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

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

CSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors

I/O Streams and Standard I/O Devices (cont d.)

Lab 12 Object Oriented Programming Dr. John Abraham

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

CS2255 HOMEWORK #1 Fall 2012

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

Arrays in C++ Instructor: Andy Abreu

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

Functions, Arrays & Structs

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Honors Computer Science C++ Mr. Clausen Program 4A, 4B, 4C (4D, 4G)

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

do { statements } while (condition);

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

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

CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

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

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

CSCE Practice Midterm. Data Types

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Pointers. Variable Declaration. Chapter 10

1st Midterm Exam: Solution COEN 243: Programming Methodology I

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

Lab Instructor : Jean Lai

System Design and Programming II

Definition Matching (10 Points)

Functions, Arrays & Structs

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

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

Exam 3 Chapters 7 & 9

ET 181. Purpose: The purpose of this lab is to become familiar with using arrays in C++.

BENG (HONS) ELECTRONIC ENGINEERING BENG (HONS) TELECOMMUNICATIONS. Cohort: BEE/10A/FT, BEE/10B/FT &BTEL/10B/FT

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Program Organization and Comments

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

CS 1044 Program 2 Spring 2002

Ch 6. Functions. Example: function calls function

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++

Example 3. #include <iostream> using namespace std; int main()

C/C++ Programming Lecture 7 Name:

Department of Computer and Mathematical Sciences. Lab 10: Functions. CS 1410 Intro to Computer Science with C++

Getting started with C++ (Part 2)

Week 3: Pointers (Part 2)

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

Summary of basic C++-commands

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

Sample Code: OUTPUT Daily Highs & Lows

BITG 1113: Array (Part 1) LECTURE 8

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

PIC 10A. Final Review: Part I

Control Structures. Repetition (Loop) Structure. Repetition (Loop) Structure. Repetition (Loop) Structure. CS225: Slide Set 8: C++ Loop Structure

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

BITG 1233: Introduction to C++

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

PIC 10A. Final Review

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

PASS$MOCK$EXAM$ $FOR$PRACTICE$ONLY$

Expressions, Input, Output and Data Type Conversions

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

Week 3: File I/O and Formatting 3.7 Formatting Output

TEST 1 CS 1410 Intro. To Computer Science Name KEY. October 13, 2010 Fall 2010

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

Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92

CS101 PLEDGED SPRING 2001

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Computer Programming : C++

A. Incorrect! This would be the negative of the range. B. Correct! The range is the maximum data value minus the minimum data value.

C++ Input/Output: Streams

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

1. To introduce and allow students to work with arrays 2. To introduce the typedef statement 3. To work with and manipulate multidimensional arrays

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

File I/O Christian Schumacher, Info1 D-MAVT 2013

Chapter Four: Loops II

Name SECTION: 12:45 2:20. True or False (12 Points)

Add Subtract Multiply Divide

Lesson 13 - Vectors Dynamic Data Storage

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:

Transcription:

Lab 15 Review of Arrays, Array of Objects and Vector Dr. John Abraham, Professor I have noticed over the years that students have great deal of difficulty dealing with composite and abstract data types. Therefore we are going spend an extra lab review material we have already learned. Vector data type, a variation of array, will be introduced as well. Vector data type (Vector Class) can be used when you need an array that grows dynamically. However, C++ does not allow us to declare size of an array dynamically like some other languages. It is important for you to declare the maximum size you will need. Suppose you are writing a program to keep grades. You have to predict the maximum class size you will have. At our university, UTPA, in computer science department we will not have more than 150 students. Most of our classrooms can only hold less than 100 students. So it would appropriate to declare an array size of 150, if you are writing a program to keep grades. When you declare an array, declare it for the maximum size you will ever need. But, keep track of how many of array elements that were used. The remaining elements are assumed to have random values (garbage). Students often forget to keep the count of actual elements used in an array. So, when you pass an array, make it a practice to pass the array along with the number of elements used. A sentinel value is used to mark the end of valid elements. For example, if you are keeping grades: 88 78 77 99 100 68 87 67 89-1; the -1 is the sentinel value. Even though 10 values are entered including -1, only 9 valid numbers are entered. You can populate an array various ways. The simplest is to assign a value to each of the locations such as: grades[0]=88; grades[1]=78; grades[2]=77; Alternatively, you may read these grades in: cin >> grades[0]; cin >> grades[1]; cin >> grades[2]; It would be easier to read the values in a loop: For (i=1; i<=8; i++) cin >> grades[i];

For loop can only used if you know how many values we are dealing with. If you want to read an unknown number of values and stop reading when a sentinel value is entered, the while loop or do while loop should be used. In the following program 15-1, we have grades[] and n to keep track of the array and the number of actual grades. Pay particular attention to passing of an array. Declaring a function with array parameters is similar to function with simple data types except to include the [], to indicate the array. Let us look at the function getgrades. It returns the number of actual grades entered (does not count the sentinel value entered). The function receives a parameter, int grades[]. When an array is passed, a pointer to the memory where the first element of the array can be found, is passed. Do not pass arrays as reference parameter, like int& grades[]. When this function is called in the main, n=getgrades(grades), the number of grades is received into n; note that the argument is grades, not grades[]. Once an array is declared, use its name and the compiler is aware that it is an array. When we display the grades both the array and the number of grades are passed. Program 15-1 /************************************************* Read into an Array By Dr. John Abraham Created for 1370 students **************************************************/ #include <iostream> using namespace std; int getgrades (int grades[]); void displaygrades(int grades[], int); //--------------main------------------------------------ int main () int grades[150]; int n; // number of scores read excluding negative number. n = getgrades(grades); //go get the scores and how many cout <<"\nhere are the scores entered:\n"; displaygrades(grades,n); return(0); //--------------function getscores---------------------- int getgrades(int grades[]) int n=1; cout << "ENTER A SCORE AND PRESS ENTER. YOU QUIT ANY TIME BY ENTERING A NEG NUMBER!\n";

cout << "Enter score# " << n << " "; cin >> grades[n]; while (grades[n] >= 0) n++; cout << "Enter score# " << n <<" "; cin >> grades[n]; return n-1; //n-1 actual scores read (ignore negative score). //-------------function display scores------------------ void displaygrades(int grades[], int n) int i; for (i=1; i<=n; i++) cout << grades[i] <<endl; Now that I have discussed reading into an array, we will turn to processing elements in an array. For this I refer you to the standard deviation program where we work with three arrays, one to store the data, the second one to find the difference of each score from the mean and the third one to find store the square of deviation of each score. The mean is calculated by adding all valid scores stored in the array and dividing by the number of scores. The deviation of each score is obtained by subtracting the score from the mean. Since this program drills you in array processing, I would ask all students to know this program thoroughly. Standard deviation is calculated using the following formula: Lower case sigma means 'standard deviation'. Capital sigma means 'the sum of'. x bar means 'the mean' Program 15-2 /************************************************* Read scores from a file into an array. Keep track of number of scores entered.

Find difference of each score from the Mean. Square the differences and add the squares. find stadard deviation create a table Teaching objective - Pass Array as a parameter. By Dr. John Abraham Created for 1370 students **************************************************/ #include <iostream> #include <fstream> #include <iomanip> #include <cmath> //for square root function. using namespace std; int getscores (int scores[]); float calcmean (int scores[], int); float sumsquares (int, int scores[], float diff[], float diffsq[],float); float stddeviation(int, float); void Table(int, int scores[], float diff[], float diffsq[], float, float); //mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm int main () int scores[90];float diff[90], diffsq[90]; int n; // n for number of scores. float mean, sumsq, stdev; n = getscores(scores); //go get the scores and how many mean = calcmean(scores, n); sumsq = sumsquares (n,scores,diff,diffsq,mean); stdev = stddeviation(n, sumsq); Table(n, scores, diff,diffsq, mean, stdev); cin >>n; return(0); //mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm int getscores(int scores[]) ifstream infile; infile.open("scores1.dta"); if (!infile) cout << "Data file does not exist!"; int n=0; while(!infile.eof()) n++; infile >> scores[n]; return n; //n-1 actual scores read.

//ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff float calcmean(int scores[], int n) int sum=0; int i; //use for counter float m; //local variable for mean for (i=1; i <=n; i++) sum += scores[i]; //add all scores m = float(float(sum)/n); return m; //fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff float sumsquares (int n, int scores[], float diff[], float diffsq[],float mean) int i; float ss=0.0; for (i=1; i <=n; i++) diff[i] = scores[i]-mean; diffsq[i] = diff[i] * diff[i]; ss += diffsq[i]; return ss; //fffffffffffffffffffffffffffffffffffffffffffffffffff float stddeviation(int n, float sumsq) float variance; variance = sumsq/(n-1); return (float(sqrt(variance))); //fffffffffffffffffffffffffffffffffffffffffffffffffff void Table(int n, int scores[], float diff[], float diffsq[], float mean, float stdev) int i; float ss=0; cout << "\nstadard Deviation for " << n<<" Scores. Mean: "<<mean <<endl; cout <<"-----------------------------------------------------------\n"; cout <<setw(10) <<"Score"<<setw(10) <<"Dev" <<setw(10) << "Dev Sq" <<" Sum of dev2)\n"; cout <<"-----------------------------------------------------------\n"; cout << setiosflags(ios::fixed); for (i = 1; i<=n; i++) ss += diffsq[i]; cout << setw(10) << setprecision(2) << scores[i] << setw(10) << setprecision(2) << diff[i] << setw(10) << setprecision(2) << diffsq[i]

<< setw(10) << setprecision(2) << ss << endl; cout <<"-----------------------------------------------------------\n"; cout <<"Standard Deviation "<< setprecision(2) <<stdev <<endl; The last program I would like to discuss with you dealing with array is the card shuffling program. Here we have an array with names of a deck of card. We do not actually shuffle this array, instead we create an array of integers (shuffled[]) and place random numbers from 1 to 52 in it. Once we have the random numbers, we just display the card names in that order. string cards[52]= "CA","C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ","CQ","CK", "DA","D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ","DQ","DK", "HA","H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ","HQ","HK", "SA","S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ","SQ","SK"; cout<<"\n\nhere is the suffled Deck: \n"; for (i=0;i <52;i++) if (i%13==0) cout<<endl; cout <<cards[shuffled[i]] << " "; -------------- Vector Class The vector is more flexible than arrays as it can grow in size dynamically. The array can be accessed using the subscript operator just like in array. However, to add an element into a vector use the method push_back as shown in the program below. You can remove the last element by using pop_back. #include <iostream> #include <string> #include <vector> using namespace std; int getnames (vector<string> &namevector ); void displaynames(int, vector<string> &namevector); int main ()

vector<string> namevector; int n; n = getnames(namevector); cout << "\n*******************************\n"; displaynames(n, namevector); return 0; int getnames (vector<string> &namevector) string name; int n=1; cout << "Enter a name or 'quit' to stop entry-> "; cin >> name; while (name!= "quit") namevector.push_back(name); cout << "--------------------\n"; n++; cout << "Enter a name or 'quit' to stop entry-> "; cin >> name; return n-1; void displaynames(int n, vector<string> &namevector) int i; for (i=0; i<n; i++) cout << namevector[i] << endl; Assignment: Complete the cards program without referring to the program you have done in the past. Write the standard deviation program without the aid of the notes. Create an object (use the previous notes), Make an array of these objects and read into these objects. Caveat: It is important that you are able to do these programs without any help. I will be placing great deal of emphasis on these programs on the final exam.