1 / 26

Announcements

Announcements. Homework 1 due Wednesday 19:00 No new homework this week, but there will be recitations About HW1 There must be three inputs only First one is the amount of money Second one is the item name Third one is the item price You have to preserve this order

anaya
Download Presentation

Announcements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Announcements • Homework 1 due Wednesday 19:00 • No new homework this week, but there will be recitations • About HW1 • There must be three inputs only • First one is the amount of money • Second one is the item name • Third one is the item price • You have to preserve this order • No other inputs are allowed • Otherwise, our system cannot process your homework

  2. Tapestry – Chapter 3 • We discussed some parts • cin for input • variables and basic types • We will go over them • More details • More types • Arithmetic operators and expression evaluation rules • More on assignment operator ‘=’ (chapter 4.1 and 4.3.4)

  3. Programs that Respond to Input • Programs without input always give the same results • values are hardcoded • For new values • change the program, compile and run again • not a good programming practice • Allow the user to input values that generate output • from keyboard, using cin • we did this in the first circle area calculation program • Sequential model of programming: input, process, output • Input: information provided from the user (outside world) • Process: Information is processed • Output: display the result

  4. Mac Donald’s farm revisited • We want the user to enter/input values for animal and noise Enter the name of an animal: sheep Enter noise that a sheep makes: 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 baahbaah here And a baahbaah there Here a baah, there a baah, everywhere a baahbaah Old MacDonald had a farm, Ee-igh, Ee-igh, oh! • 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 and then passed to function verse as arguments • see macinput2.cpp

  5. Mac Donald’s farm revisited // other functions goes here (see macinput2.cpp) void Verse(string animal, string noise) { // this function doesn’t change // see the source code for the function code } int main() { string animal; // variable for name of animal string noise; // variable for noise it makes cout << "Enter the name of an animal: "; cin >> animal; cout << "Enter noise that a " << animal << " makes: "; cin >> noise; Verse(animal,noise); return 0; }

  6. Analysis of the Run • input value “sheep” is stored in variable animal • input value “baah” is stored in variable noise • “sheep” and “baah” values are passed to function verse as argumentsas well as used in cout in main

  7. Variables (review from previous lectures) • Variables are used to store values in memory • memory locations that are accessed using a name in the program • Each variable has a type, a name (identifier), and a value • Methods to give values to variables • Assignment, using= • Input, using cin • Definition: typevariable_names_separated_by_comma ;

  8. Where to define variables • You can define variables anywhere within a function • provided that it is defined before the first use • Two common conventions the place of variable definition • 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 that they’re used: { cout << "enter animal "; string animal; cin >> animal; cout << "enter noise a " << animal << " makes "; string noise; cin >> noise; }

  9. Where to define variables • NO GLOBAL VARIABLES • A global variable is a variable defined outside the function bodies • They can be used in all functions without definition • That is why it is the #1 enemy of parameters • If you use global variables, you violate the independence property of functions and may lose your control in big programs • Thus, IT IS FORBIDDEN TO USE GLOBAL VARIABLES • If you use a global variable in hw and exams, your grade will be reduced! • At the end of the course, I will formally teach global variable concept. After that, • you will need to know what global variable is and apply them whenever you are asked for, but not without permission!

  10. Variable Initialization • Variables have garbage (junk values) until • they are assigned a value using assignment operator or • an input is stored into them (using cin statement) • Variables must be given a value before you refer to its value for the first time in an expression or an output statement or as an argument to a function • idea behind this rule: you can never know what is inside of an uninitialized variable! • not a syntax error, compiler may or may not warn you! • You may initialize variables at the declaration int myint = 5; • After initialization, you may change the value stored in a variable several times • that is why they are named as “variable”

  11. Scope of a Variable and Parameter • Not explained in the book in this way • Complex rules.Now I give a simple version! • RULE 1: A variable or parameter can be referred only within the function in which it is declared • e.g. you cannot refer the variable “animal” in function eieio • RULE 2:A specific identifier can be used several times in different functions as variable or parameter names. Those are actually different variables/parameters. • e.g. animal and noise are used both in main and verse • RULE 3: A specific identifier must be unique within a function • Detailed scope rules will be given later in this course

  12. Data Types • string • talked on that • more technically, string is a class • char • for single character • digits, letters, symbols • uses up one byte • range 0 ... 255 • why? one byte (8 bits) can store 28 = 256 different values. • stores the code of the character • e.g. 65 for ‘A’ • character arithmetic is possible (will see later) • char literals are in single quotes (strings are in double quotes) 'z' 'T' '4' '&' • bool • boolean (will see later)

  13. Numeric Types • to represent integer and real numbers • int • integer numbers • sorry! no infinity in computers  • limited range • 2 or 4 bytes (16 or 32 bits) depending on the computer and compiler you use • in our case: 4 bytes (32 bits) • integer range: –32,768 ... 32,767 for 16-bit computers • why? –2,147,483,648 ... 2,147,483,647 for 32-bit computers • why?

  14. Numeric Types (cont’d) • short int (or just short ) • always 16-bit integer • long int (or just long ) • always 32-bit integer • signed versus unsigned integers • you can put signed or unsigned keywords before the type • we discussed signed integers • signed is default • unsigned integers use the same amount of bits but ranges are different • 16-bit: 0 ... 65,535 (216 –1) • 32-bit: 0 ... 4,294,967,295 (232 –1)

  15. Numeric Types (cont’d) • Real numbers in C++ • Real literals • 3.14159 -2.5 5.43e21 • Real data types (their difference is in precision) • float • consumes 4 bytes • Range: 0 U [-1.175494351e–38 ... -3.402823466e+38] U [1.175494351e–38 ... 3.402823466e+38] • Tapestry does not like float • double • consumes 8 bytes • Range: 0 U [-2.2250738585072014e–308 ... -1.7976931348623158e+308] U [2.2250738585072014e–308 ... 1.7976931348623158e+308] • Standard but a bit complex representation • see “floating point representation” item in MSDN Library index

  16. More on C++ types • Check out these items in MSDN Library Index • Fundamental types • more on C++ types • LIMITS.H header file • limits of integer and char types • floating limits • limits for the floating points numbers (float, double) • floating point representation • if you are interested in to learn how the real numbers are represented in computers

  17. Integer vs. Real • Real values can be assigned to Integer variables, but this is not recommended since we loose precision int a; double r; r = 125.879; a = r; • What is the value of a? • 125 • Real value is truncated before storing in an integer variable • Avoid doing this • Compiler may not warn you • Be careful when passing arguments to parameters as well • passing an integer argument to a double parameter causes the same precision problem

  18. Overflow • Overflow occurs when the result of an integer expression is outside the limits • See daysecs.cpp • Run the program with • 365 days • result: 31536000 seconds • correct result and output • 14500 days • result: 1252800000 seconds • correct result and output • 25129 days • result: -2123821696 seconds • incorrect result and output due to overflow • 65400 days • result: 1355592704 seconds • incorrect result and output due to overflow

  19. Arithmetic Operations • Operators: * - + / % • Operands: values that operator combines • variables or literals • Syntax and semantics for arithmetic operations • Addition, subtraction: + and –, • for int, float and double 23 + 4x + yd – 14.0 + 23 • Multiplication: *, for int, floatand double 23 * 4 y * 3.0 d * 23.1 * 4 • Division: /, different for int and real number types (double, float) • for int operands result is the integer part of division 21 / 4 is 5 21 / 4.0 is 5.25 x / y • Modulus: %, remainder of division, only for int 21 % 4 is 1 18 % 2 is 0 x % y

  20. Arithmetic Operations (cont’d) • Mixed type expressions • what if one operator is intbut the other is double? • integer is converted into double before operation 5.0 * 8 is 40.0 5 / 10 is 0 (integer division) 5.0 / 10 is 0.5 (real division) 10 – 8 is 2 (integer) 10 – 8.0 is 2.0 (double)

  21. Expressions with several operators • You can use parentheses in expressions • Open and close parentheses should match • Rule 1: Parenthesized subexpressions are evaluated first • inside to out • Rule 2: Within anexpression/subexpression if there are several operators, use operator precedence, • evaluate * / % before + - • Rule 3: If the operators are in the same expression/subexpressionand at the same precedence level, then associativity rule applies • evaluate operators from lefttoright • Examples (5 - 3 * (7-3)) * 8 is -56 10 / 2 * 6 / 2 + (5 - 3 * (2 - 1)) is 17

  22. Expressions with several operators • Are the following expressions equivalent? (40 – 32) * 5 / 9 (40 – 32) * (5 / 9) • NO, first one is 4, second one is 0 • What about this? (40 – 32.0) * 5 / 9 • Operations are double operations. Result is 4.44444 • Are these operators sufficient? • how to calculate square root? • Later we’ll study functions like sqrt, cos, sin, pow, … • For complicated mathematical operations that you cannot easily do using basic operators • Accessible using #include <cmath> (or <math.h>)

  23. Integer vs. Real (More on Precision) • What is the difference between red and blue parts in the following program (fahrcels.cpp)? • red: integer arithmetic (low precision) • blue: real arithmetic (high precision) int main() { int ifahr; double dfahr; cout << "enter a Fahrenheit temperature "; cin >> ifahr; cout << ifahr << " F = " << (ifahr - 32) * 5/9 << " Celsius" << endl; cout << "enter another temperature "; cin >> dfahr; cout << dfahr << " F = " << (dfahr - 32) * 5/9 << " Celsius" << endl; return 0; }

  24. Reading Assignment • Section 3.3 • Case Study: Pizza Slices • Similar to circle area calculation program • Run the program pizza.cpp

  25. More on Assignment operator (4.1 & 4.3.4) • Assignment operator is = • to store values in variables variable = expression; • first the right hand side expression is evaluated using the current values • then the evaluated expression is stored in variable • Types should be compatible, otherwise • a syntax error may occur (e.g. string variable, integer expression), or • precision is lost (e.g. integer variable, real expression) • Example: what is the value of a after the assignment? int a, b; b = 25; a = 8; a = b – 3 * a + 2; • Answer: 3 • A rule: If you use the left hand side variable in the right hind side expression as well, then the current value is used in the expression on the right hand side.

  26. More on Assignment operator (4.1 & 4.3.4) • Assigning single expression to several variables variable1 = variable2 = variable3 = ... variablen = expression • all variables are assigned the same value of expression • example: int x, y, z; x = y = z = 5; • x, y and z contain 5 • Arithmetic assignment operators += -= *= /= %= • combines arithmetic operation and assignment in one operator • variable += expression is the same as variable = variable + expression • example: x += 1 is the same as x = x + 1 • use analogy for -= *= /= and %=

More Related