Organizing Programs and Data 2 Lecture 7 Hartmut Kaiser

Slides:



Advertisements
Similar presentations
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Advertisements

Agenda Definitions Evolution of Programming Languages and Personal Computers The C Language.
Lecture 2 Introduction to C Programming
Introduction to C Programming
What Data Do We Have? Sections 2.2, 2.5 August 29, 2008.
Engineering Problem Solving With C++ An Object Based Approach Fundamental Concepts Chapter 1 Engineering Problem Solving.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Libraries Programs that other people write that help you. #include // enables C++ #include // enables human-readable text #include // enables math functions.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
C++ Programming Language Day 1. What this course covers Day 1 – Structure of C++ program – Basic data types – Standard input, output streams – Selection.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Introducing Java.
© Janice Regan, CMPT 128, Jan CMPT 128 Introduction to Computing Science for Engineering Students Creating a program.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Chapter 8 Technicalities: Functions, etc. John Keyser’s Modifications of Slides by Bjarne Stroustrup
Organizing Programs and Data Lecture 5 Hartmut Kaiser
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
 2006 Pearson Education, Inc. All rights reserved Arrays.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Chapter 1 Working with strings. Objectives Understand simple programs using character strings and the string library. Get acquainted with declarations,
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Defining New Types Lecture 21 Hartmut Kaiser
1 C++ Syntax and Semantics, and the Program Development Process.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Engineering Computing I Chapter 4 Functions and Program Structure.
COP4020 Programming Languages Names, Scopes, and Bindings Prof. Xin Yuan.
Working with Batches of Data Lecture 4 Hartmut Kaiser
Looping and Counting Lecture 3 Hartmut Kaiser
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
I/O and Data Formatting Introduction to Class Concepts INFSY 307 Spring 2003 Lecture 3.
Taking Strings Apart (and putting them together) Lecture 11 Hartmut Kaiser
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 6 Writing a Program Hartmut Kaiser
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
Writing Generic Functions Lecture 20 Hartmut Kaiser
Chapter 3 Working with Batches of Data. Objectives Understand vector class and how it can be used to collect, store and manipulate data. Become familiar.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Using Sequential Containers Lecture 8 Hartmut Kaiser
11 Introduction to Object Oriented Programming (Continued) Cats.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
C language + The Preprocessor. + Introduction The preprocessor is a program that processes that source code before it passes through the compiler. It.
CSCI 161 Lecture 3 Martin van Bommel. Operating System Program that acts as interface to other software and the underlying hardware Operating System Utilities.
Chapter 4 Organizing Programs and Data. Objectives Understand the use of functions in dividing a program into smaller tasks. Discover how parameters can.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
Some of the utilities associated with the development of programs. These program development tools allow users to write and construct programs that the.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 8 Technicalities: Functions, etc. Hartmut Kaiser
Working with Batches of Data
Information and Computer Sciences University of Hawaii, Manoa
Organizing Programs and Data
Compilation and Debugging
Compilation and Debugging
Organizing Programs and Data 2
7 Arrays.
C Preprocessor(CPP).
Defining New Types Lecture 22 Hartmut Kaiser
C++ Compilation Model C++ is a compiled language
Focus of the Course Object-Oriented Software Development
7 Arrays.
SPL – PS1 Introduction to C++.
Presentation transcript:

Organizing Programs and Data 2 Lecture 7 Hartmut Kaiser

Programming Principle of the Day Abstraction Principle  Related to DRY as it aims to reduce duplication  Each significant piece of functionality in a program should be implemented in just one place in the source code.  The basic mechanism of control abstraction is a function or subroutine.  Data abstractions include various forms of type polymorphism. 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 2

Abstract We will discuss data structures as the main means of organizing data. We extend the student grades example to work with more than one student’s grades. We will introduce the concept of partitioning the program into several files, separate compilation, and linking. 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 3

Language technicalities Are a necessary evil  A programming language is a foreign language  When learning a foreign language, you have to look at the grammar and vocabulary Because:  Programs must be precisely and completely specified  A computer is a very stupid (though very fast) machine  A computer can’t guess what you “really meant to say” (and shouldn’t try to)  So we must know the rules  Some of them (the C++ standard is 782 pages) However, never forget that  What we study is programming  Our output is programs/systems  A programming language is only a tool 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 4

Technicalities Don’t spend your time on minor syntax and semantic issues. There is more than one way to say everything  Just like in English Most design and programming concepts are universal, or at least very widely supported by popular programming languages  So what you learn using C++ you can use with many other languages Language technicalities are specific to a given language  But many of the technicalities from C++ presented here have obvious counterparts in C, Java, C#, etc. 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 5

Organizing Data Let’s revise student grades program for a whole course (many students) Read grades from a file: Smith Carpenter We want to produce output (overall grade) Carpenter 90.4 Smith 86.8  Alphabetical, formatting vertically lining up 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 6

Organizing Data Need to store all student data  Sorted by name  Line up: find longest name Let’s assume we can store all data about one student (student_info)  All students data: vector Set of auxiliary functions to work with that data  Solve the overall problem using those 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 7

Organizing Data We need to hold all data items related to one student together: // hold all information related to a single student struct student_info { string name; // students name double midterm, final; // midterm and final exam grades vector homework; // all homework grades }; This is a new type holding four items (members)  We can use this type to define new objects of this type  We can store the information about all students in a vector students; 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 8

Reading Data for one Student Very similar to what we already have: // read all information related to one student istream& read(istream& in, student_info& s) { // read the students name, midterm and final exam grades in >> s.name >> s.midterm >> s.final; // read all homework grades for this student return read_hw(in, s.homework); } Any input error will cause all subsequent input to fail as well  Can be called repeatedly 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 9

Reading all Student Records Invoke read() as long as we succeed: vector students; // all student records string::size_type maxlen = 0; // length of longest name // read and store all the records, find the length of // the longest name student_info record; while (read(cin, record)) { maxlen = max(maxlen, record.name.size()); students.push_back(record); } Function std::max() is peculiar  Both arguments need to have same type 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 10

Calculate Final Grade Again, we rely on existing function: // Calculate the final grade for one student double grade(student_info const& s) { return grade(s.midterm, s.final, s.homework); } Any exception thrown by underlying function grade() will be left alone  Nothing else to do  Handling left to whatever is calling this function 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 11

Sort Student Data We know that sorting can be done using sort(): vector vec; sort(vec.begin(), vec.end()); Let’s do the same for all students: vector students; sort(students.begin(), students.end()); Not quite right, why?  What criteria to use for sorting?  What does it mean to sort the vector of students?  How to express the need to sort ‘by name’? 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 12

Sorting Student Data Normally, sort() uses the operator < to determine order  Makes no sense for student_info’s! We can teach sort() how to order by specifying a predicate  A function returning a bool taking two arguments of the type to be compared  Returns true if the first argument is smaller than the second (whatever that means) 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 13

Sorting Student Data We can teach sort() how to order by specifying a predicate: // compare two student_info instances, return whether 'x‘ // is smaller than 'y' based on comparing the stored names // of the students bool compare(student_info const& x, student_info const& y) { return x.name < y.name; } Now, we can use this function as: vector students; sort(students.begin(), students.end(), compare); 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 14

Sorting Student Data Alternatively, we could define an appropriate operator // compare two student_info instances, return whether 'x‘ // is smaller than 'y' based on comparing the stored names // of the students bool operator<(student_info const& x, student_info const& y) { return x.name < y.name; } Now, we can use this function as: vector students; sort(students.begin(), students.end()); 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 15

Sorting Student Data Alternative: lambda function (g++ 4.2, VC2010): // sorting the student data using a lambda function sort(students.begin(), students.end(), [](student_info const& x, student_info const& y) { return x.name < y.name; } ); Much nicer! Everything is in one place Note: no return type  Although, it could be specified ( -> bool )  Possible if body is ‘simple’ (one return statement) 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 16

Generating the Report Now we’re ready to generate the report: for (vector ::size_type i = 0; i != students.size(); ++i) { // write the name, padded on the right side to maxlen + 1 characters cout << students[i].name << string(maxlen students[i].name.size(), ' '); // compute and write the grade try { double final_grade = grade(students[i]); streamsize prec = cout.precision(); cout << setprecision(3) << final_grade << setprecision(prec); } catch (domain_error e) { cout << e.what(); } cout << endl; } 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 17

Generating the Report Now we’re ready to generate the report: for (student_info const& si: students) { // write the name, padded on the right side to maxlen + 1 characters cout << si.name << string(maxlen si.name.size(), ' '); // compute and write the grade try { double final_grade = grade(si); streamsize prec = cout.precision(); cout << setprecision(3) << final_grade << setprecision(prec); } catch (domain_error e) { cout << e.what(); } cout << endl; } 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 18

Temporary Objects We can create nameless (temporary objects): string(maxlen students[i].name.size(), ' ') Creates a string of spaces padding the name to length maxlen + 1 Object has no name  It’s a temporary object, which ‘lives’ until the semicolon  Equivalent to creating a named object instead 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 19

Putting it all together Look at that source file!  Even if the program is not very complex, the file is too large already Separate compilation  Example: the median function  It’s useful on it’s own, even outside the scope of this particular program Put part of sources into separate file, which is compiled separately 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 20

Separate Compilation File median.cpp (source or implementation file): #include // std::vector #include // std::domain_error #include // std::sort, std::max #include "median.hpp" using std::domain_error; using std::vector; using std::sort; // definition of function median double median(vector vec) { //... } 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 21

Separate Compilation File median.hpp (header file): #include // std::vector // declaration of function median double median(std::vector ); Makes function median available to other files: #include #include "median.hpp" int main() { /* use median() */ } 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 22

Header File Guards Ensure that inclusion of header more than once does no harm: #ifndef GUARD_MEDIAN_HPP #define GUARD_MEDIAN_HPP #include // std::vector // declaration of function median double median(std::vector ); #endif 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 23

Source files A header file (here, median.hpp) defines an interface between user code and implementation code (usually in a library) The same #include declarations in both.cpp files (definitions and uses) ease consistency checking 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 24 #include // std::vector // declaration of function median double median(std::vector ); #include "median.hpp" //definitions double median(std::vector ) { /* … */ } #include "median.hpp" /* … */ double grade = median(grades); median.hpp median.cpp: use.cpp:

Compile Single Source File Compile: g++ -std=c++11 -o main main.cpp Input is ‘main.cpp’, source code Human readable text Output is ‘main’, executable binary (-o output_name) Machine readable binary code All externals resolved Relocatable code (not bound to a particular address) Binding to memory address is done by OS loader Behind the scenes: Creating binary object file Looking up used symbols in standard libraries known to the compiler 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 25

Compile Single Source File Compile: g++ -std=c++11 -c main.cpp Input is ‘main.cpp’, source code Output is ‘main.o’, object binary Machine readable code Relocatable code Externals not resolved Link: ld –o main main.o –lstdc++ Input is ‘main.o’, object binary Input is ‘libstdc++.a, C++ runtime library (.a stands for ‘archive’) -lstdc++ is shortcut for libstdc++.a Output is ‘main’, executable binary Behind the scenes: Linker knows where to look for standard libraries 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 26

Compile Multiple Source Files Compile: g++ -std=c++11 -o main main.cpp module.cpp Input files are ‘main.cpp’ and module.cpp, source code Human readable text Output is ‘main’, executable binary (-o output_name) Machine readable binary code All externals resolved Relocatable code (not bound to a particular address) Binding to memory address is done by OS loader Behind the scenes: Creating binary object files Looking up used symbols in standard libraries known to the compiler Resolving symbols between the input files 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 27

Compile Multiple Source Files 2/10/2015, Lecture 7 CSC 1254, Spring 2015, Organizing Programs and Data (2) 28 Compile: g++ -c main.cpp module.cpp Input file are ‘main.cpp’ and ‘module.cpp’, source code Main contains references to symbols from module.cpp (or v.v.) Output files are ‘main.o’ and ‘module.o’, object binaries Machine readable code Relocatable code Externals not resolved Link: ld –o main main.o module.o –lstdc++ Input files are ‘main.o’ and ‘module.o’, object binaries Input is ‘libstdc++.a, C++ runtime library (.a stands for ‘archive’) -lstdc++ is shortcut for libstdc++.a Output is ‘main’, executable binary Behind the scenes: Linker knows where to look for standard libraries