A Computer Science Tapestry 3.1 Programs that Respond to Input l Programs in chapters one and two generate the same output each time they are executed.

Slides:



Advertisements
Similar presentations
Chapter 3: Expressions and Interactivity. Outline cin object Mathematical expressions Type Conversion and Some coding styles.
Advertisements

C Language Elements (II) H&K Chapter 2 Instructor – Gokcen Cilingir Cpt S 121 (June 22, 2011) Washington State University.
COSC 120 Computer Programming
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Your First C++ Program Aug 27, /27/08 CS 150 Introduction to Computer Science I C++  Based on the C programming language  One of today’s most.
If You Missed Last Week Go to Click on Syllabus, review lecture 01 notes, course schedule Contact your TA ( on website) Schedule.
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
Introduction to C++ Programming
Copyright 2003 Scott/Jones Publishing Brief Version of Starting Out with C++, 4th Edition Chapter 1 Introduction to Computers and Programming.
COMPUTER SCIENCE I C++ INTRODUCTION
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Chapter 1 Introduction to Computers and C++ Programming Goals: To introduce the fundamental hardware and software components of a computer system To introduce.
CPS120: Introduction to Computer Science
Overview of C++ Chapter C++ Language Elements t Comments make a program easier to understand t // Used to signify a comment on a single line.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Course websites CS201 page link at my website: Lecture slides Assistant’s Information Recitations Office Hours Make-up.
CSC 221: Computer Programming I Fall 2001  C++ basics  program structure: comments, #include, main, return  output: streams, cout, endl  input: variables,
A Computer Science Tapestry 3.1 Programs that Respond to Input l Programs in chapters one and two generate the same output each time they are executed.
Beginning C++ Through Game Programming, Second Edition
C++ Programming: Basic Elements of C++.
Fundamental Programming: Fundamental Programming Introduction to C++
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Chapter 2 Overview of C++. 2 Overview  2.1 Language Elements  2.2 Reserved Words & Identifiers  2.3 Data Types & Declarations  2.4 Input/Output 
THE BASICS OF A C++ PROGRAM EDP 4 / MATH 23 TTH 5:45 – 7:15.
CompSci Today’s topics Parsing Java Programming Reading Great Ideas, Chapter 3 & 4.
CS201 Introduction to Sabancı University 1 Announcements l Midterm Dates ä First Midterm Exam: November 7, 2015, Saturday, 14:00 – 16:00 ä.
CompSci Today’s topics Parsing Java Programming Notes from Tammy Bailey Reading Great Ideas, Chapter 3 & 4.
C++ Basics. Compilation What does compilation do? g++ hello.cpp g++ -o hello.cpp hello.
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 9, 2005 Lecture Number: 6.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
CPS120: Introduction to Computer Science Variables and Constants.
A Computer Science Tapestry 3.1 Tools we have, Tools we need l We know about output  Streams, we’ve seen strings, we’ll see numbers  Streams support.
CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding.
Brief Version of Starting Out with C++ Chapter 1 Introduction to Computers and Programming.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
Today’s topics Java Input More Syntax Upcoming Decision Trees More formal treatment of grammers Reading Great Ideas, Chapter 2.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Arithmetic, Functions and Input 9/16/13. Arithmetic Operators C++ has the same arithmetic operators as a calculator: * for multiplication: a * b – Not.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
1 8/30/06CS150 Introduction to Computer Science 1 Your First C++ Program.
A Sample Program #include using namespace std; int main(void) { cout
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 09/10/04CS150 Introduction to Computer Science 1 What Actions Do We Have Part 2.
Fundamentals of Programming I Overview of Programming
TK1913 C++ Programming Basic Elements of C++.
Chapter Topics The Basics of a C++ Program Data Types
Computing and Statistical Data Analysis Lecture 2
Chapter 3 Assignment and Interactive Input.
Completing the Problem-Solving Process
Announcements Homework 1 is due on February 22nd, this Wednesday, at 19:00 Submit to SUCourse Strictly follow the submission guideline provided in the.
Computing Fundamentals
Basic Elements of C++.
Chapter 2 Assignment and Interactive Input
Introduction to C++ October 2, 2017.
Basic Elements of C++ Chapter 2.
Announcements Homework 1 is due on October 4th, this Wednesday, at 19:00 Submit to SUCourse Strictly follow the submission guideline provided in the homework.
Introduction to C++ Programming
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Course websites CS201 page link at my website: Lecture slides
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
Summary of what we learned yesterday
Programs that Respond to Input
Announcements Homework 1 will be assigned this week
Presentation transcript:

A Computer Science Tapestry 3.1 Programs that Respond to Input l Programs in chapters one and two generate the same output each time they are executed.  Old MacDonald doesn’t get new animals without editing and recompiling the program Drawbacks in editing and recompiling?  Allow the user to input values that generate output Calculators respond to buttons pressed by users, programs respond to values entered by users l Sequential model of programming: input, process, output  Interactive model of programming: entities communicate with each other continuously  We’ll start with IPO, input, process, output

A Computer Science Tapestry 3.2 C++ Review, Programming Process l C++ programs begin execution in main  Statements are executed (can you identify a statement?)  Sometimes expressions are evaluated : cout << "gpa = " << grades/totalCourses << endl ;  Function calls execute a group of statements that embody an abstraction (e.g., Verse, EiEiO, …) C++ programs must import needed declarations via #include directives (not statements, why not?)  Streams in, used for ???  Strings in, used for ???  Built-in types include int (integer), double (real number) and many operators like +, -, *, … are NOT imported

A Computer Science Tapestry 3.3 C++ and Programming Review l Functions have prototypes (or signatures) that indicate to both the compiler and the programmer how to use the function  Later functions will return values, like square root  For now, void means no value is returned  Every function has a parameter list, but it’s possible to have no parameters Hello(); Verse(“pig”,”oink”); What do prototypes look like for these calls? l Function must appear before it’s called, either the function declaration (prototype only) or definition (implementation)

A Computer Science Tapestry 3.4 Programming Review l You’ll design and implement C++ programs  Written in a high-level language, should run on many platforms, e.g., Windows, Unix, Mac, …  Compiler translates C++ into low-level machine language  Different compilers generate different low-level programs Efficiency concerns, portability concerns, proprietary… To execute, programs must link libraries --- implementations of what’s imported via #include directives  iostream library, string library, many more “standard”  Tapestry library l Errors can result if when programs use libraries incorrectly  Fail to include, fail to link, fail to use properly

A Computer Science Tapestry 3.5 Toward a User-controlled Barnyard #include using namespace std; void Verse(string animal, string noise) { … cout << "on his farm he had a " << animal << endl; } int main() { Verse("pig","oink"); Verse("elephant","hrruyaahungh"); return 0; } l What can we do to allow user to enter animal and noise?

A Computer Science Tapestry 3.6 Desired Program Behavior l We want the user to enter/input values Enter animal name: sheep Enter noise: baah Old MacDonald had a farm, Ee-igh, Ee-igh, oh! And on his farm he had a sheep, Ee-igh, ee-igh, oh! With a baah baah here And a baah baah there Here a baah, there a baah, everywhere a baah baah Old MacDonald had a farm, Ee-igh, Ee-igh, oh! l We’ll pass the user-entered values to the Verse function  The input stream cin takes input from the keyboard using operator >>  Values that are input are stored in variables (aka objects)

A Computer Science Tapestry 3.7 Input values are stored in variables void Verse(string animal, string noise) { // this function doesn’t change } int main() { string animal; // variable for name of animal string noise; // variable for noise it makes cout << "enter animal "; cin >> animal; // what goes here?? Verse(animal,noise); return 0; } l Each variable has a type, a name /identifier, and a value

A Computer Science Tapestry 3.8 Variables and Parameters l Both are placeholders for values. Each has a type and a name  Parameters are given values when arguments passed in a function call: void Verse(string animal, string noise){…} Verse("duck", "quack");  Variables are given values when initially defined, or as a result of executing a statement string animal; // defined, no value supplied cout << "enter animal "; cin >> animal; // user-entered value stored

A Computer Science Tapestry 3.9 Define variables anywhere, but … l Two common conventions for where to define variables.  At the beginning of the function in which they’re used: { string animal,noise; cout << "enter animal "; cin >> animal; cout << "enter noise a " << animal << " makes "; cin >> noise; }  Just before the first place they’re used: string animal; cout << "enter animal "; cin >> animal; string noise; cout << "enter noise a " << animal << " makes "; cin >> noise;

A Computer Science Tapestry 3.10 Defensive programming l When your program fails, you want to be able to find the cause quickly and without tearing your hair out  Give each variable a value when it is defined string animal = “UNASSIGNED”; cout << "enter animal "; cin >> animal; //…  If, for some reason, the extraction >> fails, animal will have an identifiable value.  What is the value if no initial assignment and extraction fails? l Read > as “extract” ???

A Computer Science Tapestry 3.11 Using numbers in a program #include using namespace std; int main() { double degrees; cin << "enter temperature in degrees F. "; cin >> degrees; cout << degrees << " F = " << (degrees-32) * 5 / 9 << endl; return 0; } l User can enter 80 or 80.5  There are two types for numbers, double and int, why?  Are parentheses needed in (degrees-32)? Why?

A Computer Science Tapestry 3.12 Some arithmetic details l C++ adheres to traditional order of operations  * and / have higher precedence than + and – int x = * 6; int y = (3 + 5) * 6;  Parentheses are free, use them liberally l Arithmetic expressions are evaluated left-to-right in the absence of parentheses int x = 3 * 4 / 6 * 2; int y = (3*4)/(6*2); l There are limits on int and double value, be aware of them.

A Computer Science Tapestry 3.13 Variables and Parameters for Numbers l The type string is not a built-in type, technically it’s a class  What must you do to use strings in your programs?  What alternatives are there if strings not supported? l There are many numerical types in C++. We’ll use two  int, represents integers: {…-3,-2,-1,0,1,2,3,…} Conceptually there are an infinite number of integers, but the range is limited to [-2 31, ] (on most systems) A lternatives? Why is range limited?  double, represents real numbers like ,  2 Not represented exactly, so expressions like 100*0.1 may yield unexpected results Double precision floating point numbers, another type float exists, but it’s a terrible choice (generates poor results)

A Computer Science Tapestry 3.14 GIGO: program as good as its data? l In calculations involving floating point numbers it’s easy to generate errors because of accumulated approximations:  What is ?  When is (x + y) + z different from x + (y + z) ? The type int is severely constrained on 16-bit computers, e.g., running DOS, largest value is 32,767 ( )  Even on 32-bit machines, how many seconds in a millennium? 60*60*24*365*1000, problems?  On UNIX machines time is measure in seconds since 1970, problems?  What was Y2K all about?

A Computer Science Tapestry 3.15 What arithmetic operations exist? l Syntax and semantics for arithmetic operations  Addition, subtraction: + and –, int and double x + y d –  Multiplication: *, int and double 23 * 4 y * 3.0 d * 23.1 * 4  Division: /, different for int and double 21 / 4 21 / 4.0 x / y  Modulus: %, only for int 21 % 4 17 % 2 x % y l Mixed type expressions are converted to “higher” type  Associativity of operators determines left-to-right behavior l Use parentheses liberally  Without () use operator precedence, *,/, % before +,-

A Computer Science Tapestry 3.16 Comparing Dominos to Pizza Hut to … void SlicePrice(int radius, double price) // compute pizza statistics { // assume all pizzas have 8 slices cout << "sq in/slice = "; cout << *radius*radius/8 << endl; cout << "one slice: $" << price/8 << endl; cout << "$" << price/( *radius*radius); cout << " per sq. inch" << endl; } l How can we call this several times to compare values? l Are there alternatives to the 8 slices/pie convention? l What about thickness?

A Computer Science Tapestry 3.17 Parameter, compiler, warning, trouble l What if argument types don’t match parameter types? void SlicePrice(int radius, double price); l Consider the calls below, which are ok?  SlicePrice(12, 18.99);  SlicePrice(12, 18);  SlicePrice(18.99, 12);  SlicePrice(12, “18.99”); l What is a compiler warning as opposed to an error? Should you pay attention to warnings?

A Computer Science Tapestry 3.18 Compiling and linking, differences // string.cpp // stuff we can’t // understand #include int main() { string s = “hi”; } hello.cpp … hello.o … string.o hello Link

A Computer Science Tapestry 3.19 A Question of Style Coding style can be a personal thing but there do exist a number of good guideline Elements  Indentation / White space  Meaningful identifiers Variables: What is it? Functions: What does it do?  Use case to indicate what type of identifier (e.g. variables lowercase and functions uppercase)  Commenting Abstraction comments: What does it do? Implementation comments: How does it do it? Choose one style that is comfortable to you and be consistent!

A Computer Science Tapestry 3.20 Think about it Puzzle: Toggling Frogs  You have 100 light switches, numbered 1-100, and 100 frogs, also numbered  Whenever a frog jumps on a light switch, it toggles a light between on and off. All lights are initially off. frog #1 jumps on every light switch (ie turning them all on). frog #2 jumps on every 2nd light switch, toggling some of them back off.... frog #k jumps on every kth light switch.  After 100 frogs, which lights are on? Game: Don’t be last  You and a friend have a stack of 10 coins.  On each person's turn, they remove either 1 or 2 coins from the stack.  The person who removes the last coin wins.  What is a winning strategy? Should you go first or second?