Organizing Programs and Data 2

Slides:



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

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.
1 Engineering Problem Solving With C++ An Object Based Approach Fundamental Concepts Chapter 1 Engineering Problem Solving.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
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 2 Lecture 7 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.
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.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Engineering Computing I Chapter 4 Functions and Program Structure.
Working with Batches of Data Lecture 4 Hartmut Kaiser
Chapter 0 Getting Started. Objectives Understand the basic structure of a C++ program including: – Comments – Preprocessor instructions – Main function.
Looping and Counting Lecture 3 Hartmut Kaiser
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Taking Strings Apart (and putting them together) Lecture 11 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.
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.
Using Sequential Containers Lecture 8 Hartmut Kaiser
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
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.
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 8 Technicalities: Functions, etc. Hartmut Kaiser
Lecture 3 Translation.
Bill Tucker Austin Community College COSC 1315
C++ Memory Management – Homework Exercises
Working with Batches of Data
Information and Computer Sciences University of Hawaii, Manoa
Organizing Programs and Data
Andy Wang Object Oriented Programming in C++ COP 3330
User-Written Functions
Compilation and Debugging
Compilation and Debugging
Functions, locals, parameters, and separate compilation
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Stack Data Structure, Reverse Polish Notation, Homework 7
Object Oriented Programming COP3330 / CGS5409
Phil Tayco Slide version 1.0 Created Oct 2, 2017
7 Arrays.
Chapter 8 Technicalities: Functions, etc.
Chapter 8 Technicalities: Functions, etc.
C Preprocessor(CPP).
Defining New Types Lecture 22 Hartmut Kaiser
Andy Wang Object Oriented Programming in C++ COP 3330
Type & Typeclass Syntax in function
C++ Compilation Model C++ is a compiled language
CISC/CMPE320 - Prof. McLeod
CSE 303 Concepts and Tools for Software Development
Focus of the Course Object-Oriented Software Development
7 Arrays.
Chapter 8 Technicalities: Functions, etc.
Variables in C Topics Naming Variables Declaring Variables
SPL – PS1 Introduction to C++.
Presentation transcript:

Organizing Programs and Data 2 Lecture 7 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/˜hkaiser/fall_2012/csc1254.html

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. http://en.wikipedia.org/wiki/Abstraction_principle_(programming) 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (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. 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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. 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

Organizing Data Let’s revise student grades program for a whole course (many students) Read grades from a file: Smith 93 91 47 90 92 73 100 87 Carpenter 75 90 87 92 93 60 0 98 We want to produce output (overall grade) Carpenter 90.4 Smith 86.8 Alphabetical, formatting vertically lining up 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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<student_info> Set of auxiliary functions to work with that data Solve the overall problem using those 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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<double> 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<student_info> students; 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

Reading all Student Records Invoke read() as long as we succeed: vector<student_info> 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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

Sort Student Data We know that sorting can be done using sort(): vector<double> vec; sort(vec.begin(), vec.end()); Let’s do the same for all students: vector<student_info> 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’? 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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) 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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<student_info> students; sort(students.begin(), students.end(), compare); 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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<student_info> students; sort(students.begin(), students.end()); 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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 Possible if body is ‘simple’ (one return statement) 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

Generating the Report Now we’re ready to generate the report: for (vector<student_info>::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 + 1 - 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; 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

Temporary Objects We can create nameless (temporary objects): string(maxlen + 1 - 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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

Separate Compilation File median.cpp (source or implementation file): #include <vector> // std::vector #include <stdexcept> // std::domain_error #include <algorithm> // std::sort, std::max #include "median.hpp" using std::domain_error; using std::vector; using std::sort; // definition of function median double median(vector<double> vec) { // ... } 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

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

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

Source files median.hpp #include <vector> // std::vector // declaration of function median double median(std::vector<double>); median.cpp: use.cpp: #include "median.hpp" //definitions double median(std::vector<double>) { /* … */ } #include "median.hpp" /* … */ double grade = median(grades); 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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

Compile Single Source File Compile: g++ -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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

Compile Single Source File Compile: g++ -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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

Compile Multiple Source Files Compile: g++ -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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)

Compile Multiple Source Files 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 9/26/2013, Lecture 7 CSC 1254, Fall 2013, Organizing Programs and Data (2)