1 More C++ Basics Chapter 3 Lecture CSIS 10A. 2 Agenda Review C++ Standard Numeric Types...

54
1 More C++ Basics Chapter 3 Lecture CSIS 10A

Transcript of 1 More C++ Basics Chapter 3 Lecture CSIS 10A. 2 Agenda Review C++ Standard Numeric Types...

1

More C++ BasicsChapter 3 Lecture

CSIS 10A

2

Agenda

Review C++ Standard Numeric Types

Arithmetic–way more than you want!

Character (char) data type

For Loop

Syntax, Run-time and Logical Errors

3

Review:Standard Program Structure

To solve most problems, your main() program will generally look like this (conceptually)

1. Declare variables for input, result and intermediate data

2. Ask for data (cout)3. Input data (cin)4. Calculate result5. Output result (cout)

4

An interactive C++ program://circle.cpp Calculate area of a circle// given a radius value#include <iostream>using namespace std;int main(){ int area, radius;cout << "enter a radius: ";cin >> radius;area = radius * radius * 3.14;cout << "the area is " << area << endl;

return 0;}

5

A small problem…

Run circle.cpp:

But according to our code, it should be 3.14

What happened?

enter a radius: 1

the area is 3

Press any key to continue . . .

6

We used the wrong data type!

Go back, change:

int area, radius;

To:

float area, radius;

Now it works…the lesson?

1) Data types are important!

2) Testing is important!

7

Agenda

Review

C++ Standard Numeric Types Arithmetic–way more than you want!

Character (char) data type

For Loop

Syntax, Run-time and Logical Errors

8

Basic C++ Data Types

int – Represents integers

float – Represents real (floating point) numbers

char – Represents characters (single letters)

9

Integers only store whole numbers

int a=4; // puts 4 in a

int a=4.579132; // puts 4 in a

INTS are great for loop counters, representing inventory, numbers of “things”

10

Trivia—other integer types

uses range of values

short..............(2 bytes)….-32,767 to 32767

long …….….(4 bytes)…-2 bill to +2 billion

int ………….(depends)…long (sometimes short)

unsigned short (2 bytes)…0 to 65535

unsigned long ...(4 bytes) …0 to 4 billion

11

Beware Integer wraparound

// wrap.cpp

int a, b, c;

a = 2000000000;

b = 2 * a;

c = 3 * a;

cout << "b is " << b << endl;

cout << "c is " << c << endl;

b is -294967296

c is 1705032704

12

FLOATING-POINT Types

float is used to represent numbers with a

fractional part such as 2.543 or 6.45 etc…

or really big numbers that won’t fit inside ints

uses range precision

float...........(4 bytes)……10-38 to 1038……..6 digits

double…...(8 bytes)……10-308 to 10308…...15 digits

long double (10 bytes)....10-4932 to 104932…19 digits

13

What does floating point mean?

Consider a number like 123.45

“Float” the point so that all the digits are on its right

(here the point is shifted 3 digits to the left)

123.45 = 0.12345 x 10 3

E-notation: the letter ‘e’= “x10 to the power of”

You can actually enter or display data using ‘e’:

123.45 same as 0.12345e3 same as 1.2345e2

14

Fine…. How is this stored in a float variable ??

The mantissa .12345 and the exponent 3 are stored separately (in a variable)

For a 32 bit float type :

23 bit mantissa + 8 bit exponent + 1 sign bit

For a 64 bit double type :

52 bit mantissa + 11 bit exponent + 1 sign bit

15

Implications for Accuracy(round-off error)

A float only stores about 6 digits of mantissafloat PI=3.1415926535897932384626;PI really contains 3.14159float x=50000000000000.0, y=10000.0;x=x+y; DOES NOT CHANGE X!!! (no room)

Use a double if you need more precisiondouble PI=3.141592653589793;About 16 digits of mantissadouble x=50000000000000.0, y=10000.0;x=x+y; DOES CHANGE X!!! (now there’s room)

16

Q1) Practice your Scientific Notation (answers at end of slides)

1234.56 = ____________ x 10 ____

.03413= ____________ e ____

6.78 x 107 = ____________

5.32e-5 = ____________

17

Displaying Floating Point data

cout << 4.5 << endl;cout << -.375 << endl;cout << 10.6666666 << endl;cout << 67800000.0 << endl;cout << 523000000000 << endl;cout << 523000000000. << endl;cout << 0.000098 << endl;

Output

4.5

-0.375

10.6667

6.78e+07

3308957184

5.23e+11

9.8e-05

This is an integer, no ‘.’

18

Formating Floating Point Outputcout<<fixed<<showpoint<<setprecision(2);

cout << 4.5 << endl;cout << -.375 << endl;cout << 10.6666666 << endl;cout << 67800000.0 << endl;cout << 523000000000 << endl;cout << 523000000000. << endl;cout << 0.000098 << endl;

You can use this on problem 8

Output

4.50

-0.38

10.67

67800000.00

3308957184

523000000000.00

0.00

For this to work, #include<iomanip>

19

Constants are “variables” -- that never change

Use the keyword “const” in front of declaration

You MUST provide initial value at declarationconst double PI=3.141592653589793;

const double METERS_PER_YARD = 0.9144;

const int MAX=1000;

Now you can say: area = PI * radius * radius;

Don’t over do it: const int SECONDS_PER_MINUTE = 60;

You can use a constant for problem 7

20

Agenda

Review

C++ Standard Numeric Types

Arithmetic–way more than you want! Character (char) data type

For Loop

Syntax, Run-time and Logical Errors

21

Arithmetic in C++

Basic operations + - * /

Math formulas need to be converted into C++ syntax:

FORMULA Equivalent C++A = r2 area=3.14*radius*radius;

F = (v -a) force=(v-a)/(v+a);

(v+a)

22

More C++ Math Formulas

23

Arithmetic -- Order of Precedence

* and / are done first, then + and –Equal levels are done left to rightExample:

3 * 4 + 2 = 142 + 3 * 4 = 146 + 4 / 2 + 3 = 6 + 2 + 3 =

8 + 3 = 11

Parentheses have highest precedence (use if you want different order)

(6 + 4) / (2 + 3) = 2

24

Q2) Practice Arithmetic Precedence

Evaluate the following

1+2 * 3 + 4 = _______

5 + 6 / 2 * 3 = _______

1 + 2 * (3 + 4) = _______

(7 + 5) / (2 * 3) = _______

25

Mixed-type Expressions

Expressions involving int and float will give a result of type float (the most inclusive type)

Suppose you have

int n; float x;

Then

n + x results in float

n * 4 results in int

n + 4.0 results in double (4.0 is double)

(default for floating pt literals)

26

Mixed-type Assignments

Assigning int to float is perfectly safe

Assigning float to int may lose fractional partSuppose you have

int n; float x;

Then

1. x = 15; stores 15 in x

2. n = 4.5; stores 4 in n -- Compiler Warning!

To satisfy the compiler for (2.) simply explain

your intentions: n = int(4.5);

27

Q3) Can you guess what is stored in these variables?

int m, n; double x,y;

m = 3.0;

n = 12.7;

x = m;

x = x + 0.5

m = m + 1;

y = x + 1;

m n x y

? ? ? ?

28

Integer Division

CAUTION—this is a common C++ error

When both sides are int, the result MUST be int

9 / 2 = 4 9 / 10 = 0

Sometimes this is what we want (convert inches to inches and feet)

Usually causes programming errors

When one side is float, the answer is float9 / 2.0 = 4.5 9.0 / 10 = 0.9

29

Q4) Can you guess what is stored in these variables?

int m, n; double x,y;

m = 10 / 3;

n = 30 / 7;

x = n * m;

y = 3 / 4 * x;

y = x * 3 / 4;

y = (x + 3) / 4;

m n x y

? ? ? ?

30

One more thing…type-casting

If you want to perform floating point division on a pair of integer variables, you can…but you have to temporarily convert one of them to float first:

int m=3, n=4; float y;y = float(m) / n; ( y = 0.75)

WRONGy = float(m/n); ( y = 0)

31

Break Time!

Download Lab2MoreBasics.cpp

Work on problems 1-4, 7,8

Call me over if you have questions

32

Remainder % operator

The expression 10 / 3 gives the quotient, 3

We use 10 % 3 to get the remainder, 1

4 / 3 = 1 12 % 6 = 0

4 % 3 = 1 13 % 6 = ____

2 / 3 = 0 14 % 6 = ____

2 % 3 = 2 23 % 7 = _____

Only use % on integers

33

What good is % operator?You can use it to subdivide something into hierarchical units:

int feet, inches;cout << "Enter inches: ";cin >> inches;feet = inches / 12;inches = inches % 12;cout << feet << " ft. " << inches << " in.";

This is used in things like time, weight, length, change, etc.

Use this slide on Problem 9

Enter inches: 75

6 ft. 3 in.

34

Arithmetic Assignment Operators

Numeric operators +, -, *, /, % can be combined with the assignment operator =

Saves time and typing

Only when you want to store result in one of operands

a += b a = a + b

a -= b a = a - b

a *= b a = a * b

a /= b a = a / b

a %= b a = a % b

35

Q5) Arithmetic Assign Operator Table START: int x=0;

Shorthand Same as Result

x+=5;

x*=2;

x/=5;

x-=2;

x+=10;

x*=3;

x%=8

x/=5;

x=x+5;

x=x*2;

x=x/5;

x=x-2;

5

10

2

0

36

Agenda

Review

C++ Standard Numeric Types

Arithmetic–way more than you want!

Character (char) data type For Loop

Syntax, Run-time and Logical Errors

37

CHARACTER types (see Lab3-1)

char……………... (1 byte)

unsigned char…….(1 byte)

A char stores a single letter

What is actually stored is the binary sequence corresponding to a letter’s ASCII code

You can either store a letter, or the numeric code for the letter in a char

38

Check this out….#include <iostream.h>void main(){ both a and c contain 65 or ‘A’char a = 65, c = 'A'; cout << “ c = “ << c << endl;cout << “ a = “ << a << endl;}Output…..c = Aa = A (in other words, ‘A’ is same as 65)

39

Decimal ASCII Table

40

Character InputRead 2 chars

char grade1, grade2;cin>>grade1>>grade2;cout<<“Grade 1 is ”<<grade1<<endl;cout<<“Grade 2 is ”<<grade2<<endl;NOTE• white space ignored: type AB, A B, A (enter)

B same result• Another interesting topic, character escape and

control sequences, p 53/54

41

Agenda

Review

C++ Standard Numeric Types

Arithmetic–way more than you want!

Character (char) data type

For Loop Syntax, Run-time and Logical Errors

42

Bored with single execution programs?

Add a for loop to repeat your code several times:for (int k=1; k<=final_value; k=k+1)

{

statements to repeat

}

43

Example Looped code

Add a for loop to repeat your code several times:int main(){ for (int k=1; k<=3; k=k+1) {

cout<<“Testing”<<k<<endl; }}

Testing 1

Testing 2

Testing 3

Or k++ for short

44

Example Application (for challenge)

Calculate pay for 3 employees: int hrs; double rate;

for (int emp=1; emp<=3; emp++)

{

cout<<“Enter hours & rate: ”;

cin>> hrs>> rate;

cout<<“Pay = $”<< hrs * rate <<endl;

}

See p57 to let user determine the number of iterations

45

Agenda

Review

C++ Standard Numeric Types

Arithmetic–way more than you want!

Character (char) data type

For Loop

Syntax, Run-time and Logical Errors

46

Types of ErrorsSyntax: an error in your C++ language/grammar (covered last week)

confuses compiler (The dog his paw)forgetting a ; misspelling a variable name datha=3.14;

Runtime: when you do something illegal during program execution temp=0.0;rate=1.0/temp; // dividing a number by zero –crash!

Logical (or Semantic): When you say something illogical A paw ate his dog. ( Good grammar, illogical

meaning) avg = b + c / 2;

47

Tracking them down

Syntax—double click on error message,

it takes you to line of code

Look at or above that line for possible errors

Runtime & LogicalYou detect them by checking output against test plan

Pinpoint them by displaying variables during intermediate steps (cout)

OR Use debugger to step through program, put watch on variables

48

LIST OF KEYWORDS…..asmautoboolbreakcasecatchcharclassconstconst_castcontinue

defaultdeletedodoubledynamic_

castelseenumexplicitexportextern

false

floatforfriendgotoifinlineintlongmutablenamespace

newoperator

private protectedpublicregisterreinterpret

_castreturnshortsignedsizeofstatic

static_caststructswitchtemplatethisthrowtruetrytypedeftypeidtypenameunionunsignedusing

virtualvoid

volatilewchar_twhile

49

That’s a wrap !

What we learned today:Data Types

Rules of Arithmetic

For loops

How to debug your program

50

A1) Answers to Scientific Notation

1234.56 = 1.23456 x 103

.03413= 3.413 e -2

6.78 x 107 = 67800000

5.32e-5 = 0.0000532

51

A2) Arithmetic Precedence

Evaluate the following

1+2 * 3 + 4 = 11

5 + 6 / 2 * 3 = 14

1 + 2 * (3 + 4) = 15

(7 + 5) / (2 * 3) = 2

52

A3) Answer:

int m, n; double x,y;

m = 3.0;

n = 12.7;

x = m;

x = x + 0.5

m = m + 1;

y = x + 1;

m n x y

? ? ? ?

3

12

3.0

3.5

4

4.5

53

A4) Integer Division

int m, n; double x,y;

m = 10 / 3;

n = 30 / 7;

x = n * m;

y = 3 / 4 * x;

y = x * 3 / 4;

y = (x + 3) / 4;

m n x y

? ? ? ?

3

4

12

0

9

3.75

54

A5) Arithmetic Assign Operator Table START: int x=0;

Shorthand Same as Result

x+=5;

x*=2;

x/=5;

x-=2;

x+=10;

x*=3;

x%=8

x/=5;

x=x+5;

x=x*2;

x=x/5;

x=x-2;

x=x+10;

x=x*3;

x=x%8; x=x/5;

5

10

2

0

10

306

1