LAB: STRUCTURES, ARRAYS,

Similar documents
LAB: WHILE LOOPS IN C++

LAB: FOR LOOPS IN C++

Lesson 19: The Graph of a Linear Equation in Two Variables is a Line

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

Section 1.5. Finding Linear Equations

LAB: INTRODUCTION TO FUNCTIONS IN C++

College Prep Algebra II Summer Packet

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

Section 7D Systems of Linear Equations

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

Four Types of Slope Positive Slope Negative Slope Zero Slope Undefined Slope Slope Dude will help us understand the 4 types of slope

Introduction to Algorithms and Programming (COMP151)

3-1 Writing Linear Equations

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

QUIZ Lesson 4. Exercise 4: Write an if statement that assigns the value of x to the variable y if x is in between 1 and 20, otherwise y is unchanged.

Lab 2.1: Fixing a C++ program

Chapter 12. Streams and File I/O

Lesson 19: The Graph of a Linear Equation in Two Variables Is a Line

Scientific Computing

= 3 + (5*4) + (1/2)*(4/2)^2.

Programming II with C++ (CSNB244) Lab 10. Topics: Files and Stream

Math-2. Lesson 3-1. Equations of Lines

Outline of what we will cover

File I/O CS 16: Solving Problems with Computers I Lecture #9

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:

CPE Summer 2015 Exam I (150 pts) June 18, 2015

Come and join us at WebLyceum

CS 103 Unit 11. Linked Lists. Mark Redekopp

CS 1044 Programming in C++ Test 1 Spring 2011 Form B Page 1 of 12 READ THIS NOW!

C++ Input/Output: Streams

Introduction To Computer Programming C++ Mr. Clausen Program C11A, C11B

CS 1044 Project 1 Fall 2011

Lesson 20: Every Line is a Graph of a Linear Equation

What we will learn about this week:

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

LAB: SWITCH STATEMENTS

Sample Final Exam. 1) (24 points) Show what is printed by the following segments of code (assume all appropriate header files, etc.

HFCC Math Lab Intermediate Algebra 1 SLOPE INTERCEPT AND POINT-SLOPE FORMS OF THE LINE

2.2 Graphs Of Functions. Copyright Cengage Learning. All rights reserved.

10-2 Circles. Warm Up Lesson Presentation Lesson Quiz. Holt Algebra2 2

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

SNAP Centre Workshop. Graphing Lines

3, 10,( 2, 4) Name. CP Algebra II Midterm Review Packet Unit 1: Linear Equations and Inequalities. Solve each equation. 3.

Functions! Objectives! 1E3! Topic 9! programming! n This topic should allow students to! n Read chapter 6 of the textbook now.!

Lab: Supplying Inputs to Programs

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

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

Declaring a 2D Array

CSci 1113 Midterm 1. Name: Student ID:

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory

Lesson 18: There is Only One Line Passing Through a Given Point with a Given

Arrays in C++ Instructor: Andy Abreu

CSci 1113 Midterm 2. Name: Student ID:

Algebra Unit 2: Linear Functions Notes. Slope Notes. 4 Types of Slope. Slope from a Formula

Honors Computer Science C++ Mr. Clausen Program 6A, 6B, 6C, & 6G

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

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.

Using Excel for Graphical Analysis of Data

Functions. Copyright Cengage Learning. All rights reserved.

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

1 Getting started with Processing

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

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

This sheet must be the cover page for every programming assignment. Total

NAMESPACES IN C++ You can refer the Programming with ANSI C++ by Bhushan Trivedi for Understanding Namespaces Better(Chapter 14)

Why Use Graphs? Test Grade. Time Sleeping (Hrs) Time Sleeping (Hrs) Test Grade

Scatterplot: The Bridge from Correlation to Regression

C++ Structures Programming Workshop 2 (CSCI 1061U)

Pointers II. Class 31

CS 102 Lab 3 Fall 2012

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Exercise: Graphing and Least Squares Fitting in Quattro Pro

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

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

Lecture 4. 1 Statements: 2 Getting Started with C++: LESSON FOUR

Lab - Create User Accounts in Windows 8

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

MAT 003 Brian Killough s Instructor Notes Saint Leo University

cd h: mkdir -p CS101 cd CS101 curl -O unzip zipfile cd CS101_Exam4

Simple File I/O.

Appendix M: Introduction to Microsoft Visual C Express Edition

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

Lab Instructor : Jean Lai

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions

Note. The above image and many others are courtesy of - this is a wonderful resource for designing circuits.

Question 2. [2 points] True False By default, structures are passed-by-reference.

The following is a typical execution run of this program:

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

Intro. To Graphing Linear Equations

CS 103 Unit 11. Linked Lists. Mark Redekopp

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

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Question 2. [5 points] Given the following symbolic constant definition

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Transcription:

LAB: STRUCTURES, ARRAYS, AND FILES IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2008-2016 VERSION 3.3

PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 2 Introduction This lab will provide students with an introduction to the use of structures, arrays, and files in the C++ programming language. The focus of this lab is on how to solve complex problems using data structures. At the end of this module, students will Be able to solve simple problems using simple data structures Understand the use of the struct keyword in C++ Understand the use C++ data structures to solve analysis problems. For those exercises which ask you to write code, structure your storage drive in the following manner. There should be a palms folder, and within that folder there should be a LabStructs folder. All coding exercises (and related folders) for this lesson should be placed in the LabStructs folder. As always, be sure to properly document your code. Consult the C++ Coding Guidelines document for proper coding standards. Use good design principles and design the solution before attempting to write code. Let s begin! Example: Line of Best Fit A common procedure in data analysis is the computation of the line of best fit for a set of (x, y) coordinate data. Suppose you have a set of data on the amount of CO 2 emissions in the United States for the years 1960-2009. Plotting this data on an (x, y) coordinate plan would give us the following: 7000000 Emissions (kt) 6000000 5000000 4000000 3000000 Emissions (kt) 2000000 1000000 1950 1960 1970 1980 1990 2000 2010

PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 3 Suppose we wanted to determine the line of best fit, i.e. the trend line that best fits the points on the graph (which is really a scatterplot). We could write a C++ program to assist us. This program would necessarily involve the following elements: Reading the data (years and emissions, in kilotons) from a text file; Storing the data into one or more arrays; Processing the arrays to compute the line of best fit coordinates Producing an output file with the coordinates for the line of best fit. We will begin this process by first writing some code to echo-print the emissions data from a text file using a new data type. Next, we will extend this code to perform the line of best fit calculations. Finally, we will be produce an output file of the line of best fit coordinates. Exercise 1: We could begin by creating a new C++ source file called LineOfBestFit.cpp. Make sure that you include the <fstream> library. Besides the normal program structure (a set of library includes, a main function) we would want to add the following new type definition to the area above the main function: struct CO2Record int year; the year for the data double emissions; the amount of emissions (kilotons) ; This new type CO2Record is a C++ struct ( structure ) definition. A C++ struct is a data structure, i.e. a set of distinct data elements grouped under one name. One-dimensional arrays are homogeneous data structures (all elements of the same type) whereas a struct is considered a heterogeneous data structure (all elements can be of different types). Once the new type declaration has been added, add some code to main to do the following: Create a CO2Record variable named data. Create an ifstream variable called ifs. Review the ifstream tutorial if necessary. Using the ifs variable, open a file named CO2.txt and check to see if the open worked. If it did not, inform the user. If the open worked, output a simple message to the user indicating that the file is now open. The CO2.txt will be provided by the instructor. Close the file associated with the ifs variable. Compile and run your program to verify it works as it should. Exercise 2: Add code to your LineOfBestFit.cpp file to read the CO2.txt file. You will want to read the file one token at a time. Since each line of the file contains two tokens one for the

PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 4 year, one for the emissions in kilotons you can use the data variable created in Exercise 1 to store the two pieces of data. After reading a complete line of the file, echo-print the data to the screen like so: 1960 2890696.100000 1961 2880505.510000 1962 2987207.870000 1963 3119230.870000 1964 3255995.310000 1965 3390922.570000 1966 3561878.110000 1967 3695708.940000 1968 3831354.940000... Press any key to continue... You will need a while loop to read the entirety of the file. Inside the while loop, make two reads (one for year, one for emissions) and print out the data. Remember that you can use the >> operator to read a token from a file. For example, to read the year, you could have this code: get the next year... ifs >> data.year; Exercise 3: Change the declaration of data to be an array of 50 elements, all of type CO2Record. Modify the file read performed in Exercise 2 to fill the contents of this array. Instead of echoprinting the file as you go, remove the cout statement from inside your while loop. Add a second loop to output the contents of the data array after the file has been completely read. The output should be exactly the same as in the previous exercise, but the code will be different. Once you have verified that the program successfully echo-prints the contents of the file, remove the for loop which outputs the contents of the array we will not need it again. Making the Calculations We will use the Least Square Method to determine an equation for our line of best fit. Read over the following link before moving on to the next exercise: Line of Best Fit (Least Square Method) Hotmath.com Exercise 4: Add the following function to your LineOfBestFit.cpp file; don t forget to add a function prototype!

PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 5 / FUNCTION NAME: computesumofx PARAMETERS: CO2Record list[] -- the array of data int size -- number of elements in the array RETURN TYPE: double PURPOSE: Sums and returns the "year" values in the array. / double computesumofx( CO2Record list[], int size ) double sum = 0.0; stores the sum for (int i = 0; i < size; i++) add the year to the sum... sum += list[i].year; return sum; return the sum value Compile your program to check for any syntax errors. Exercise 5: Add the following function to your LineOfBestFit.cpp file; don t forget to add a function prototype! / FUNCTION NAME: computesumofy PARAMETERS: CO2Record list[] -- the array of data int size -- number of elements in the array RETURN TYPE: double PURPOSE: Sums and returns the "emissions" values in the array. / double computesumofy( CO2Record list[], int size ) double sum = 0.0; stores the sum for (int i = 0; i < size; i++) add the emissions to the sum... sum += list[i].emissions; return sum; return the sum value Compile your program to check for any syntax errors.

PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 6 Exercise 6: Add the following functions to your LineOfBestFit.cpp file: double computesumofxsquared( CO2Record list[], int size ); calculates the sum of the squares of the year values found in list double computesumofxtimesy( CO2Record list[], int size ); calculates the sum of the ( year * emissions ) values found in list double computeslope( double sum_xy, double sum_x_squared, double sum_x, double sum_y, int size); calculates the slope using the given values. Hint: The computesumofxsquared and computesumofxtimesy functions are very similar to the functions created in Exercise 4 and Exercise 5 (and to each other). Compile your program to check for any syntax errors. Exercise 7: Add the following functions to your LineOfBestFit.cpp file: double computexmean( CO2Record list[], int size ); calculates the mean of the year values found in list double computeymean( CO2Record list[], int size ); calculates the mean of the emissions values found in list Hint: You can use the computesumofx and computesumofy functions to simplify the calculations. You don t even need for loops! Compile your program to check for any syntax errors. Exercise 8: Add the following function to your LineOfBestFit.cpp file; don t forget to add a function prototype! / FUNCTION NAME: computeyintercept PARAMETERS: double mean_x -- the mean X value double mean_y -- the mean Y value double slope -- the slope RETURN TYPE: double PURPOSE: Computes and returns the Y-intercept. / double computeyintercept( double mean_x, double mean_y, double slope ) return the y-intercept... return mean_y - ( slope * mean_x ); Compile your program to check for any syntax errors.

PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 7 Exercise 9: Add the following code to your main function, just after the while loop which performs the file read. The purpose of this code is to test the functions you wrote in Exercises 4 through 8. Computing the relevant values... double sum_x = computesumofx( data, 50 ); sum of X values double sum_y = computesumofy( data, 50 ); sum of Y values double sum_x2 = computesumofxsquared( data, 50 ); sum of X^2 values double sum_xy = computesumofxtimesy( data, 50 ); sum of X*Y values double mean_x = computexmean( data, 50 ); mean X value double mean_y = computeymean( data, 50 ); mean Y value slope value... double m = computeslope( sum_xy, sum_x2, sum_x, sum_y, 50 ); y-intercept... double b = computeyintercept( mean_x, mean_y, m ); cout.precision(2); cout.setf(ios::fixed); two digits of precision always show the decimal point output the values... cout << "Sum of X: " << setw(20) << sum_x << endl << "Sum of Y: " << setw(20) << sum_y << endl << "Sum of X^2: " << setw(18) << sum_x2 << endl << "Sum of X*Y: " << setw(18) << sum_xy << endl << "Mean of X: " << setw(19) << mean_x << endl << "Mean of Y: " << setw(19) << mean_y << endl << "Slope: " << setw(23) << m << endl << "Y-Intercept: " << setw(17) << b << endl << endl; Once the code is typed in, compile and run your program to verify that the following output is produced. Sum of X: 99225.00 Sum of Y: 234537062.62 Sum of X^2: 196922425.00 Sum of X*Y: 465985502345.57 Mean of X: 1984.50 Mean of Y: 4690741.25 Slope: 52504.35 Y-Intercept: -99504147.38 Press any key to continue... If one or more of the numbers produced by your program do not match those listed above, go back to that function and check your logic. Correct any errors before moving on to the next exercise.

PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 8 Exercise 10: We will next want to add in the code to compute the line of best fit coordinates. Add a new 50-element array of type CO2Record to your main function; name it new_data_points. Next add the following function to your file; don t forget to add a function prototype! / FUNCTION NAME: computelineofbestfit PARAMETERS: CO2Record list[] -- the array of data CO2Record new_list[] -- the array of "new" data int size -- number of elements in the array double slope -- the "m" value double yint -- the "b" value RETURN TYPE: void PURPOSE: Fills the "new_list" array with the "line of best fit" values. / void computelineofbestfit( CO2Record list[], CO2Record new_list[], int size, double slope, double yint ) Begin Loop through the array... set the "x" coordinate (year) of the "new" array element to be the "old" element s year. set the "y" coordinate (emissions) of the "new" array element using the formula y = mx + b. End loop You will need to complete the code for this function. Use the comments as a guide. Once your function is complete, add a line of code to the main function to call computelineofbestfit. The function call should occur just after the code you added in Exercise 9. Creating the New File Our final step is to create a new file on disk containing the original data AND the new emissions values for the line of best fit. Exercise 11: Picking up where you left off in the previous exercise, add some code to main to do the following: Create an ofstream variable named ofs. Review the ofstream tutorial if necessary Using the ofs variable, open a file named CO2_LOBF.TXT and check to see if the open worked. If it did not, inform the user. If the open worked, create a for loop which writes the following data to the file, three parts per line, 50 lines in all: o The year (from the data array) o The original emissions value (from the data array) o The new emissions value (from the new_data_points array) Close the file associated with the ofs variable.

PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 9 Compile and run your program to verify it works as it should. Your CO2_LOBF.txt file should contain the data found on the next page. In the end, the points your program produced could be graphed like so: 7000000 Emissions (kt) 6000000 5000000 4000000 3000000 Emissions (kt) Trend 2000000 1000000 1950 1960 1970 1980 1990 2000 2010

PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 10 CO2_LOBF.TXT Contents 1960 2890696.100000 3404384.602565 1961 2880505.510000 3456888.955619 1962 2987207.870000 3509393.308674 1963 3119230.870000 3561897.661728 1964 3255995.310000 3614402.014783 1965 3390922.570000 3666906.367837 1966 3561878.110000 3719410.720892 1967 3695708.940000 3771915.073946 1968 3831354.940000 3824419.427001 1969 4024748.850000 3876923.780055 1970 4328904.500000 3929428.133110 1971 4356770.030000 3981932.486164 1972 4564952.960000 4034436.839219 1973 4770194.950000 4086941.192273 1974 4598487.670000 4139445.545328 1975 4406329.540000 4191949.898382 1976 4613100.670000 4244454.251437 1977 4742292.750000 4296958.604491 1978 4889112.090000 4349462.957546 1979 4900373.450000 4401967.310600 1980 4721170.830000 4454471.663655 1981 4531792.280000 4506976.016709 1982 4300598.930000 4559480.369764 1983 4334925.720000 4611984.722818 1984 4470326.020000 4664489.075873 1985 4486460.820000 4716993.428927 1986 4491176.590000 4769497.781982 1987 4684431.150000 4822002.135036 1988 4888664.720000 4874506.488091 1989 4951084.390000 4927010.841145 1990 4879376.210000 4979515.194200 1991 4870238.040000 5032019.547254 1992 4876006.230000 5084523.900309 1993 5167485.060000 5137028.253363 1994 5227176.490000 5189532.606418 1995 5237968.470000 5242036.959472 1996 5343512.060000 5294541.312527 1997 5501365.410000 5347045.665581 1998 5449077.660000 5399550.018636 1999 5528149.180000 5452054.371690 2000 5713450.020000 5504558.724745 2001 5601368.170000 5557063.077799 2002 5650957.010000 5609567.430854 2003 5681664.470000 5662071.783908 2004 5790761.390000 5714576.136963 2005 5826393.620000 5767080.490017 2006 5737615.550000 5819584.843072 2007 5828696.500000 5872089.196126 2008 5656838.880000 5924593.549181 2009 5299563.070000 5977097.902235