129
1 Starting Out with C++, 3 rd Edition Chapter 3. Expressions and Interactivity

Chapter 3. Expressions and Interactivity

  • Upload
    gomer

  • View
    64

  • Download
    1

Embed Size (px)

DESCRIPTION

Chapter 3. Expressions and Interactivity. 3.1The cin Object. The cin object reads information types at the keyboard. cin is the standard input object Notice the >> and

Citation preview

Page 1: Chapter 3. Expressions and Interactivity

1

Starting Out with C++, 3rd Edition

Chapter 3. Expressions and Interactivity

Page 2: Chapter 3. Expressions and Interactivity

2

Starting Out with C++, 3rd Edition

3.1 The cin Object

• The cin object reads information types at the keyboard.

• cin is the standard input object• Notice the >> and << operators appear to

point in the direction information is flowing.

Page 3: Chapter 3. Expressions and Interactivity

3

Starting Out with C++, 3rd Edition

Program 3-1#include <iostream.h>void main(void){

int length, width, area;cout <<"This program calculates the area of a rectangle.\n";cout <<"What is the length of the rectangle? ";cin>>length;cout <<"What is the width of the rectangle? ";cin>>width;area = length * width;cout <<"The area of the rectangle is " << area << ".\n";

}

Page 4: Chapter 3. Expressions and Interactivity

4

Starting Out with C++, 3rd Edition

Program Output

This program calculates the area of a rectangle.

What is the length of the rectangle? 10 [Enter]

What is the width of the rectangle? 20 [Enter]

The area of the rectangle is 200.

Page 5: Chapter 3. Expressions and Interactivity

5

Starting Out with C++, 3rd Edition

Program 3-2// This program reads the length and width of a rectangle. // It calculates the rectangle's area and displays // the value on the screen.#include <iostream.h>

void main(void){

int length, width, area;cin >> length;cin >> width;area = length * width;cout << "The area of the rectangle is " << area << endl;

}

Page 6: Chapter 3. Expressions and Interactivity

6

Starting Out with C++, 3rd Edition

Entering Multiple Values

• The cin object may be used to gather multiple values at once.

Page 7: Chapter 3. Expressions and Interactivity

7

Starting Out with C++, 3rd Edition

Program 3-3#include <iostream.h>

void main(void){

int length, width, area;cout <<"This program calculates the area of a rectangle.\n";cout <<"Enter the length and width of the rectangle separated by a space. \n";cin >> length>> width;area = length * width;cout <<"The area of the rectangle is " << area << endl;

}

Page 8: Chapter 3. Expressions and Interactivity

8

Starting Out with C++, 3rd Edition

Program Output

This program calculates the area of a rectangle.

Enter the length and width of the rectangle separated by a space.

10 20 [Enter]The area of the rectangle is 200

Page 9: Chapter 3. Expressions and Interactivity

9

Starting Out with C++, 3rd Edition

Program 3-4// This program demonstrates how cin can read multiple values// of different data types.#include <iostream.h>

void main(void){

int whole;float fractional;char letter;

  cout << "Enter an integer, a float, and a character: ";cin >> whole >> fractional >> letter;cout << "whole: " << whole << endl;cout << "fractional: " << fractional << endl;cout << "letter: " << letter << endl;

}

Page 10: Chapter 3. Expressions and Interactivity

10

Starting Out with C++, 3rd Edition

Program Output

Enter an integer, a float, and a character: 4 5.7 b [Enter]

whole: 4 fractional: 5.7 letter: b

Page 11: Chapter 3. Expressions and Interactivity

11

Starting Out with C++, 3rd Edition

Reading Strings

• cin can read strings as well as numbers.• Strings are stored in character arrays.char Company[12];

Page 12: Chapter 3. Expressions and Interactivity

12

Starting Out with C++, 3rd Edition

Program 3-5#include <iostream.h>#include<string>

void main(void){

string name;cout << "What is your name? ";cin >> name;cout << "Good morning " << name << endl;

}

Page 13: Chapter 3. Expressions and Interactivity

13

Starting Out with C++, 3rd Edition

Program Output

What is your name? Charlie [Enter]Good morning Charlie

Page 14: Chapter 3. Expressions and Interactivity

14

Starting Out with C++, 3rd Edition

Program 3-6// This program demonstrates how cin can read a// string into a character array

#include <iostream.h>

void main(void){

char name[21];

cout << "What is your name? ";cin >> name;cout << "Good morning " << name << endl;

}

Page 15: Chapter 3. Expressions and Interactivity

15

Starting Out with C++, 3rd Edition

Program Output

What is your name? Charlie [Enter]Good morning Charlie

Page 16: Chapter 3. Expressions and Interactivity

16

Starting Out with C++, 3rd Edition

Program 3-7// This program reads two strings into two character arrays.#include <iostream.h>

void main(void){

char first[16], last[16];cout << "Enter your first and last names and I will\n";cout << "reverse them.\n"; cin >> first >> last;cout << last << ", " << first << endl;

}

Page 17: Chapter 3. Expressions and Interactivity

17

Starting Out with C++, 3rd Edition

Program Output

Enter your first and last names and I willreverse them.Johnny Jones [Enter]Jones, Johnny

Page 18: Chapter 3. Expressions and Interactivity

18

Starting Out with C++, 3rd Edition

Notes on strings:

• If a character array is intended to hold strings, it must be at least one character larger than the largest string that will be stored in it.

• The cin object will let the user enter a string larger than the array can hold. If this happens, the string will overflow the array’s boundaries and destroy other information in memory.

• If you wish the user to enter a string that has spaces in it, you cannot use this input method.

Page 19: Chapter 3. Expressions and Interactivity

19

Starting Out with C++, 3rd Edition

3.2 Focus on Software Engineering: Mathematical Expressions

• C++ allows you to construct complex mathematical expressions using multiple operators and grouping symbols.

Page 20: Chapter 3. Expressions and Interactivity

20

Starting Out with C++, 3rd Edition

Program 3-7// This program reads two strings into two character

arrays#include <iostream.h>

void main(void){

char first[16], last[16];

  cout << Enter your first and last names and I will\n";cout << "reverse them.\n";cin >> first >> last;cout << last << ", " << first << endl;

}

Page 21: Chapter 3. Expressions and Interactivity

21

Starting Out with C++, 3rd Edition

Program 3-7 Output with Example Input

Enter your first and last names and I will reverse them.Johnny Jones [Enter]Jones, Johnny

Page 22: Chapter 3. Expressions and Interactivity

22

Starting Out with C++, 3rd Edition

Program 3-8// This program asks the user to enter the numerator// and denominator of a fraction and it displays the// decimal value#include <iostream.h>

void main(void){

float numerator, denominator;

cout << "This program shows the decimal value of ";cout << "a fraction.\n";

cout << “Enter the numerator: “;cin >> numerator;cout << “Enter the denominator: “;cin >> denominator;

cout << “The decimal value is “; cout << (numerator / denominator);}

Page 23: Chapter 3. Expressions and Interactivity

23

Starting Out with C++, 3rd Edition

Program Output for Program 3-8 with Example Input

This program shows the decimal value of a fraction.

Enter the numerator: 3 [Enter]Enter the denominator: 6 [Enter]The decimal value is 0.1875

Page 24: Chapter 3. Expressions and Interactivity

24

Starting Out with C++, 3rd Edition

Table 3-1 Precedence of Arithmetic Operators (Highest to Lowest)

(unary negation) -* / %+ -

Page 25: Chapter 3. Expressions and Interactivity

25

Starting Out with C++, 3rd Edition

Table 3-2 Some Expressions

Expression Value 5 + 2 * 4 13 10 / 2 - 3 2 8 + 12 * 2 - 4 28 4 + 17 % 2 - 1 4 6 - 3 * 2 + 7 - 1 6

Page 26: Chapter 3. Expressions and Interactivity

26

Starting Out with C++, 3rd Edition

Associativity

• If two operators sharing an operand have the same precedence, they work according to their associativity, either right to left or left to right

Page 27: Chapter 3. Expressions and Interactivity

27

Starting Out with C++, 3rd Edition

Table 3-3 Associativity of Arithmetic OperatorsOperator Associativity(unary negation) - Right to left* / % Left to right+ - Left to right

Page 28: Chapter 3. Expressions and Interactivity

28

Starting Out with C++, 3rd Edition

Converting Algebraic Expressions to Programming Statements

AlgebraicExpression

Operation C++ Equivalent

6B 6 times B 6 * B(3)(12) 3 times 12 3 * 124xy 4 times x times y 4 * x * y

Page 29: Chapter 3. Expressions and Interactivity

29

Starting Out with C++, 3rd Edition

No Exponents Please!

• C++ does not have an exponent operator.• Use the pow() library function to raise a

number to a power.• Will need #include <math.h> for pow()

function.area = pow(4,2) // will store 42 in area

Page 30: Chapter 3. Expressions and Interactivity

30

Starting Out with C++, 3rd Edition

Program 3-9// This program calculates the area of a circle.// The formula for the area of a circle is Pi times// the radius squared. Pi is 3.14159.#include <iostream.h>#include <math.h> // needed for the pow function

void main(void){

double area, radius;cout << "This program calculates the area of a circle.\n";cout << "What is the radius of the circle? ";cin >> radius;area = 3.14159 * pow(radius,2);cout << "The area is " << area;

}

Page 31: Chapter 3. Expressions and Interactivity

31

Starting Out with C++, 3rd Edition

Program 3-9 Output With Example Input

This program calculates the area of a circle.What is the radius of the circle? 10[Enter]The area is 314.159

Page 32: Chapter 3. Expressions and Interactivity

32

Starting Out with C++, 3rd Edition

3.3 When you Mix Apples and Oranges: Type Coercion

• When an operator’s operands are of different data types, C++ will automatically convert them to the same data type.

Page 33: Chapter 3. Expressions and Interactivity

33

Starting Out with C++, 3rd Edition

Type Coercion Rules:

• Rule 1: Chars, shorts, and unsigned shorts are automatically promoted to int.

• Rule 2: When an operator works with two values of different data types, the lower-ranking value is promoted to the type of the higher-ranking value.

• Rule 3: When the final value of an expression is assigned to a variable, it will be converted to the data type of the variable.

Page 34: Chapter 3. Expressions and Interactivity

34

Starting Out with C++, 3rd Edition

3.4 Overflow and Underflow

• When a variable is assigned a value that is too large or too small in range for that variable’s data type, the variable overflows or underflows.

• Overflow - when a variable is assigned a number that is too large for its data type

• Underflow - when a variable is assigned a number that is too small for its data type

Page 35: Chapter 3. Expressions and Interactivity

35

Starting Out with C++, 3rd Edition

Program 3-10// This program demonstrates integer underflow and// overflow#include <iostream.h>

void main(void){

short testVar = 32767;cout << testVar << endl;testVar = testVar + 1;cout << testVar << endl;testVar = testVar - 1;cout << testVar << endl;

}

Page 36: Chapter 3. Expressions and Interactivity

36

Starting Out with C++, 3rd Edition

Program Output

32767-3276832767

Page 37: Chapter 3. Expressions and Interactivity

37

Starting Out with C++, 3rd Edition

Program 3-11// This program can be used to see how your system// handles floating point overflow and underflow.

#include <iostream.h>

void main(void){

float test;test = 2.0e38 * 1000; // Should overflow testcout << test << endl;test = 2.0e-38 / 2.0e38;cout << test << endl;

}

Page 38: Chapter 3. Expressions and Interactivity

38

Starting Out with C++, 3rd Edition

3.5 The Typecast Operator

• The typecast operator allows you to perform manual data type conversion.

Val = int(number); //If number is a floating //point variable, it will be //truncated to an integer and //stored in the variable Val

Page 39: Chapter 3. Expressions and Interactivity

39

Starting Out with C++, 3rd Edition

Program 3-12#include <iostream.h>

void main(void){

int months, books;float perMonth;cout << "How many books do you plan to read? ";cin >> books;cout << "How many months will it take you to read them? ";cin >> months;perMonth = float(books) / months;cout << "That is " << perMonth << " books per month.\n";

}

Page 40: Chapter 3. Expressions and Interactivity

40

Starting Out with C++, 3rd Edition

Program Output

How many books do you plan to read? 30 [Enter]

How many months will it take you to read them? 7 [Enter]

That is 4.285714 books per month.

Page 41: Chapter 3. Expressions and Interactivity

41

Starting Out with C++, 3rd Edition

Typecast Warnings

• In Program 3-11, the following statement would still have resulted in integer division:

perMonth = float(books / months);

• Because the division is performed first and the result is cast to a float.

Page 42: Chapter 3. Expressions and Interactivity

42

Starting Out with C++, 3rd Edition

Program 3-13// This program uses a typecast operator to print // a character from a number. #include <iostream.h>

void main(void){

int number = 65;cout << number << endl;cout << char(number) << endl;

}

Page 43: Chapter 3. Expressions and Interactivity

43

Starting Out with C++, 3rd Edition

Program Output

65A

Page 44: Chapter 3. Expressions and Interactivity

44

Starting Out with C++, 3rd Edition

3.6 The Power of Constants

• Constants may be given names that symbolically represent them in a program.

Page 45: Chapter 3. Expressions and Interactivity

45

Starting Out with C++, 3rd Edition

Program 3-14// This program calculates the area of a circle.#include <iostream.h>#include <math.h>

void main(void){

const float pi = 3.14159;double area, radius;cout << "This program calculates the area of a circle.\n";cout << "What is the radius of the circle? ";cin >> radius;area = pi * pow(radius,2);cout << "The area is " << area;

}

Page 46: Chapter 3. Expressions and Interactivity

46

Starting Out with C++, 3rd Edition

The #define Directive• The older C-style method of creating named

constants is with the #define directive, although it is preferable to use the const modifier.

#define PI 3.14159

• is roughly the same asconst float PI=3.14159;

Page 47: Chapter 3. Expressions and Interactivity

47

Starting Out with C++, 3rd Edition

Program 3-15

#include <iostream.h>#include <math.h> // needed for pow function#define PI 3.14159

void main(void){

double area, radius;cout << "This program calculates the area of a circle.\n";cout << "What is the radius of the circle? ";cin >> radius;area = PI * pow(radius, 2);cout << "The area is " << area;

Page 48: Chapter 3. Expressions and Interactivity

48

Starting Out with C++, 3rd Edition

3.7 Multiple Assignment and Combined Assignment

• Multiple assignment means to assign the same value to several variables with one statement.

A = B = C = D = 12;Store1 = Store2 = Store3 = BegInv;

Page 49: Chapter 3. Expressions and Interactivity

49

Starting Out with C++, 3rd Edition

Program 3-16// The program tracks the inventory of three widget stores// that opened at the same time. Each store started with the// same number of widgets in inventory. By subtracting the// number of widgets each store has sold from its inventory,// the current inventory can be calculated.

#include <iostream.h>

void main(void){

int begInv, sold, store1, store2, store3;

cout << “One week ago, 3 new widget stores opened\n";cout << “at the same time with the same beginning\n";cout << “inventory. What was the beginning inventory? ";cin >> begInv;store1 = store2 = store3 = begInv;

Page 50: Chapter 3. Expressions and Interactivity

50

Starting Out with C++, 3rd Edition

Program 3-16 Continued

cout << "How many widgets has store 1 sold? ";cin >> sold;store1 = store1 – sold; //Subtract sold from store1

cout << "How many widgets has store 2 sold? ";cin >> sold;store2 = store2 – sold; //Subtract sold from store2cout << "How many widgets has store 3 sold? ";cin >> sold;store3 = store3 – sold; //Subtract sold from store 3cout << "Store1: " << store1 << endl;cout << "Store2: " << store2 << endl;cout << "Store3: " << store3 << endl;

}

Page 51: Chapter 3. Expressions and Interactivity

51

Starting Out with C++, 3rd Edition

Program 3-16 Output with Example InputOne week ago, 3 new widget stores openedat the same time with the same beginninginventory. What was the beginning inventory?

100 [Enter]How many widgets has store 1 sold? 25 [Enter]How many widgets has store 2 sold? 15 [Enter]How many widgets has store 3 sold? 45 [Enter]

The current inventory of each store:

Store 1: 75Store 2: 85Store 3: 55

Page 52: Chapter 3. Expressions and Interactivity

52

Starting Out with C++, 3rd Edition

Table 3-8

Statement What It Does Value of xafter theStatement

x = x + 4 ; Adds 4 to x 10

x = x - 3 ; Subtracts 3 from x 3

x = x * 1 0 ; Multiplies x by 10 60

x = x / 2 ; Divides x by 2 3

x = x % 4 Makes x the remainder of x / 4 2

Page 53: Chapter 3. Expressions and Interactivity

53

Starting Out with C++, 3rd Edition

Table 3-9

Operator Example Usage Equivalent To+= x += 5; x = x + 5;-= y -= 2; y = y - 2;*= z += 10; z = z + 10;/= a /= b; a = a / b;

%= c %= 3; c = c % 3;

Page 54: Chapter 3. Expressions and Interactivity

54

Starting Out with C++, 3rd Edition

Program 3-17// The program tracks the inventory of three widget stores// that opened at the same time. Each store started with the// same number of widgets in inventory. By subtracting the// number of widgets each store has sold from its inventory,// the current inventory can be calculated.

#include <iostream.h>

void main(void){

int begInv, sold, store1, store2, store3;

cout << “One week ago, 3 new widget stores opened\n";cout << “at the same time with the same beginning\n";cout << “inventory. What was the beginning inventory? ";cin >> begInv;store1 = store2 = store3 = begInv;

Page 55: Chapter 3. Expressions and Interactivity

55

Starting Out with C++, 3rd Edition

Program 3-17 Continued

cout << "How many widgets has store 1 sold? ";cin >> sold;store1 -= sold; //Subtract sold from store1

cout << "How many widgets has store 2 sold? ";cin >> sold;store2 -= sold; //Subtract sold from store2cout << "How many widgets has store 3 sold? ";cin >> sold;store3 -= sold; //Subtract sold from store 3cout << "Store1: " << store1 << endl;cout << "Store2: " << store2 << endl;cout << "Store3: " << store3 << endl;

}

Page 56: Chapter 3. Expressions and Interactivity

56

Starting Out with C++, 3rd Edition

Program 3-17 Output with Example InputOne week ago, 3 new widget stores openedat the same time with the same beginninginventory. What was the beginning inventory?

100 [Enter]How many widgets has store 1 sold? 25 [Enter]How many widgets has store 2 sold? 15 [Enter]How many widgets has store 3 sold? 45 [Enter]

The current inventory of each store:

Store 1: 75Store 2: 85Store 3: 55

Page 57: Chapter 3. Expressions and Interactivity

57

Starting Out with C++, 3rd Edition

3.8 Formatting Output

• The cout object provides ways to format data as it is being displayed. This affects the way data appears on the screen.

Page 58: Chapter 3. Expressions and Interactivity

58

Starting Out with C++, 3rd Edition

Program 3-18#include<iostream.h> 

void main(void){

int num1 = 2897, num2 = 5,num3 = 837, num4 = 34, num5 = 7, num6 = 1623, num7 = 390, num8 = 3456, num9 = 12;

// Display the first row of numberscout << num1 << " "; cout << num2 << " "; cout << num3 << endl;// Display the second row of numberscout << num4 << " "; cout << num5 << " "; cout << num6 << endl;// Display the third row of numberscout << num7 << " ";cout << num8 << " "; cout << num9 << endl;

}

Page 59: Chapter 3. Expressions and Interactivity

59

Starting Out with C++, 3rd Edition

Program Output

2897 5 83734 7 1623390 3456 12

Page 60: Chapter 3. Expressions and Interactivity

60

Starting Out with C++, 3rd Edition

Program 3-19// This program displays three rows of numbers. #include <iostream.h>#include <iomanip.h> // for setw function

void main(void){

int num1 = 2897, num2 = 5, num3 = 837, num4 = 34, num5 = 7, num6 = 1623, num7 = 390, num8 = 3456, num9 = 12;

// Display the first row of numberscout << setw(4) << num1 << " ";cout << setw(4) << num2 << " ";cout << setw(4) << num3 << endl;

Page 61: Chapter 3. Expressions and Interactivity

61

Starting Out with C++, 3rd Edition

Program continues

// Display the second row of numberscout << setw(4) << num4 << " ";cout << setw(4) << num5 << " ";cout << setw(4) << num6 << endl;// Display the third row of numberscout << setw(4) << num7 << " ";cout << setw(4) << num8 << " ";cout << setw(4) << num9 << endl;

}

Page 62: Chapter 3. Expressions and Interactivity

62

Starting Out with C++, 3rd Edition

Program Output

2897 5 837 34 7 1623 390 3456 12

Page 63: Chapter 3. Expressions and Interactivity

63

Starting Out with C++, 3rd Edition

Program 3-20//This program demonstrates the setw manipulator being//used with values of various data types.#include <iostream.h>#include <iomanip.h>

void main(void){

int intValue = 3928;float floatValue = 91.5;char cStringValue[] = "John J. Smith";cout << "(" << setw(5) << intValue << ")" << endl;cout << "(" << setw(8) << floatValue << ")" << endl;cout << "(" << setw(16) << cStringValue << ")" << endl;

}

Page 64: Chapter 3. Expressions and Interactivity

64

Starting Out with C++, 3rd Edition

Program Output

( 3928)( 91.5)( John J. Smith)

Page 65: Chapter 3. Expressions and Interactivity

65

Starting Out with C++, 3rd Edition

Precision

• Floating point values may be rounded to a number of significant digits, or precision, which is the total number of digits that appear before and after the decimal point.

Page 66: Chapter 3. Expressions and Interactivity

66

Starting Out with C++, 3rd Edition

Program 3-21// This program demonstrates how setprecision rounds a// floating point value#include <iostream.h>#include <iomanip.h>

void main(void){

float quotient, number1 = 132.364, number2 = 26.91;

quotient = number1 / number2;cout << quotient << endl;cout << setprecision(5) << quotient << endl;cout << setprecision(4) << quotient << endl;cout << setprecision(3) << quotient << endl;cout << setprecision(2) << quotient << endl;cout << setprecision(1) << quotient << endl;

}

Page 67: Chapter 3. Expressions and Interactivity

67

Starting Out with C++, 3rd Edition

Program Output

4.918774.91884.9194.924.95

Page 68: Chapter 3. Expressions and Interactivity

68

Starting Out with C++, 3rd Edition

Table 3-11

Number Manipulator Value Displayed

28.92786 setprecision(3) 28.9

21 setprecision(5) 21

109.5 setprecision(4) 109.5

34.28596 setprecision(2) 34

Page 69: Chapter 3. Expressions and Interactivity

69

Starting Out with C++, 3rd Edition

Program 3-22//This program asks for sales figures for 3 days.

The// total sales is calculated and displayed in a

table#include <iostream.h>#include <iomanip.h> void main(void){

float day1, day2, day3, total; 

cout << "Enter the sales for day 1: ";cin >> day1;cout << "Enter the sales for day 2: ";cin >> day2;

Page 70: Chapter 3. Expressions and Interactivity

70

Starting Out with C++, 3rd Edition

Program Continues

cout << "Enter the sales for day 3: ";cin >> day3;total = day1 + day2 + day3;cout << "\nSales Figures\n";cout << "-------------\n";cout << setprecision(5);cout << “Day 1: " << setw(8) << day1 << endl;cout << “Day 2: " << setw(8) << day2 << endl;cout << “Day 3: " << setw(8) << day3 << endl;

cout << “Total: " << setw(8) << total << endl;}

Page 71: Chapter 3. Expressions and Interactivity

71

Starting Out with C++, 3rd Edition

Program Output

Enter the sales for day 1: 321.57 [Enter]Enter the sales for day 2: 269.62 [Enter]Enter the sales for day 3: 307.77 [Enter] Sales Figures-------------Day 1: 321.57Day 2: 269.62Day 3: 307.77Total: 898.96

Page 72: Chapter 3. Expressions and Interactivity

72

Starting Out with C++, 3rd Edition

Program 3-23//This program asks for sales figures for 3 days. The // total sales is calculated and displayed in a table.#include <iostream.h>#include <iomanip.h>

void main(void){

float day1, day2, day3, total;cout << "Enter the sales for day 1: ";cin >> day1;cout << "Enter the sales for day 2: ";cin >> day2;cout << "Enter the sales for day 3: ";cin >> day3;total = day1 + day2 + day3;

Page 73: Chapter 3. Expressions and Interactivity

73

Starting Out with C++, 3rd Edition

Program Continues

cout << "\nSales Figures\n";cout << "------\n";cout << setprecision(2) << setiosflags(ios::fixed);cout << “Day 1: " << setw(8) << day1 << endl;cout << “Day 2: " << setw(8) << day2 << endl;cout << “Day 3: " << setw(8) << day3 << endl;cout << "Total: " << setw(8) << total << endl;

}

Page 74: Chapter 3. Expressions and Interactivity

74

Starting Out with C++, 3rd Edition

Program Output

Enter the sales for day 1: 1321.87 [Enter]Enter the sales for day 2: 1869.26 [Enter]Enter the sales for day 3: 1403.77 [Enter]

Sales Figures-------------Day 1: 1321.87Day 2: 1869.26Day 3: 1403.77Total: 4594.9

Page 75: Chapter 3. Expressions and Interactivity

75

Starting Out with C++, 3rd Edition

IOS Flags

• setiosflags manipulator can be used to format output in a variety of ways, depending on which flag is specified.

• setiosflags(ios::fixed) will cause all subsequent numbers to be printed in fixed point notation

Page 76: Chapter 3. Expressions and Interactivity

76

Starting Out with C++, 3rd Edition

Program 3-24// This program asks for sales figures for 3 days. The // total sales is calculated and displayed in a table. #include <iostream.h>#include <iomanip.h>

 void main(void){

float day1, day2, day3, total;cout << "Enter the sales for day 1: ";cin >> day1;cout << "Enter the sales for day 2: ";cin >> day2;

Page 77: Chapter 3. Expressions and Interactivity

77

Starting Out with C++, 3rd Edition

Program continues

cout << "Enter the sales for day 3: ";cin >> day3;total = day1 + day2 + day3;cout << "\nSales Figures\n";cout << "-------------\n";cout << setprecision(2)

<< setiosflags(ios::fixed | ios::showpoint);cout << “Day 1: " << setw(8) << day1 << endl;cout << “Day 2: " << setw(8) << day2 << endl;cout << “Day 3: " << setw(8) << day3 << endl;cout << "Total: " << setw(8) << total << endl;

}

Page 78: Chapter 3. Expressions and Interactivity

78

Starting Out with C++, 3rd Edition

Program Output

Enter the sales for day 1: 2642.00 [Enter]Enter the sales for day 2: 1837.20 [Enter]Enter the sales for day 3: 1963.00 [Enter] Sales Figures-------------Day 1: 2642.00Day 2: 1837.20Day 3: 1963.00Total: 6442.20

Page 79: Chapter 3. Expressions and Interactivity

79

Starting Out with C++, 3rd Edition

Table 3-12Format Flag Descriptionios::left Causes the field to be left-justified with padding spaces printed to

the right.ios::right Causes the field to be right-justified with padding spaces printed to

the left.ios::fixed Causes all subsequent numbers to be displayed in fixed point

notation.ios::scientific Causes all subsequent numbers to be displayed in scientific notation.ios::dec Causes all subsequent integers to be displayed in decimal format.

ios::hex Causes all subsequent integers to be displayed in hexadecimalformat.

ios::oct Causes all subsequent integers to be displayed in octal format.ios::showpoint Forces the decimal point and trailing zeroes to be displayed.ios::showpos Causes a + sign to be displayed in front of positive numbers.ios::uppercase Causes the E in scientific notation numbers, and the X in

hexadecimal numbers to be displayed in uppercase.

Page 80: Chapter 3. Expressions and Interactivity

80

Starting Out with C++, 3rd Edition

Formatting Output With Member Functionscout.width(5); //calls the width member // function, same as // setw(5)

cout.precision(2); //sets precision to // 2 significant // digits

// The next statement works like // setiosflags(ios::fixed)cout.setf(ios::fixed);

Page 81: Chapter 3. Expressions and Interactivity

81

Starting Out with C++, 3rd Edition

Program 3-25// This program asks for sales figures for 3 days. The // total sales is calculated and displayed in a table. #include <iostream.h>#include <iomanip.h> void main(void){

float day1, day2, day3, total; 

cout << "Enter the sales for day 1: ";cin >> day1;cout << "Enter the sales for day 2: ";cin >> day2;cout << "Enter the sales for day 3: ";cin >> day3;

Page 82: Chapter 3. Expressions and Interactivity

82

Starting Out with C++, 3rd Edition

Program continues

total = day1 + day2 + day3; cout.precision(2); cout.setf(ios::fixed | ios::showpoint);

cout << "\nSales Figures\n";cout << "-------------\n";cout << “Day 1: ";cout.width(8);cout << day1 << endl;cout << “Day 2: ";cout.width(8);cout << day2 << endl;

Page 83: Chapter 3. Expressions and Interactivity

83

Starting Out with C++, 3rd Edition

Program continues

cout << “Day 3: ";cout.width(8);cout << day3 << endl;cout << "Total: ";cout.width(8);cout << total << endl;

}

Page 84: Chapter 3. Expressions and Interactivity

84

Starting Out with C++, 3rd Edition

Program Output

Enter the sales for day 1: 2642.00 [Enter]Enter the sales for day 2: 1837.20 [Enter]Enter the sales for day 3: 1963.00 [Enter] Sales Figures-------------Day 1: 2642.00Day 2: 1837.20Day 3: 1963.00Total: 6442.20

Page 85: Chapter 3. Expressions and Interactivity

85

Starting Out with C++, 3rd Edition

Program 3-26// This program asks for sales figures for 3 days. The // total sales is calculated and displayed in a table.#include <iostream.h>#include <iomanip.h>

void main(void){

float day1, day2, day3, total; 

cout << "Enter the sales for day 1: ";cin >> day1;cout << "Enter the sales for day 2: ";cin >> day2;cout << "Enter the sales for day 3: ";cin >> day3;

Page 86: Chapter 3. Expressions and Interactivity

86

Starting Out with C++, 3rd Edition

Program continues

total = day1 + day2 + day3;cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << "\nSales Figures\n";cout << "-------------\n";cout << “Day 1: " << setw(8) << day1 << endl;cout << “Day 2: " << setw(8) << day2 << endl;cout << “Day 3: " << setw(8) << day3 << endl;cout << "Total: " << setw(8) << total << endl;return 0;

}

Page 87: Chapter 3. Expressions and Interactivity

87

Starting Out with C++, 3rd Edition

Program Output

Enter the sales for day 1: 2642.00 [Enter]Enter the sales for day 2: 1837.20 [Enter]Enter the sales for day 3: 1963.00 [Enter] Sales Figures-------------Day 1: 2642.00Day 2: 1837.20Day 3: 1963.00Total: 6442.20

Page 88: Chapter 3. Expressions and Interactivity

88

Starting Out with C++, 3rd Edition

Table 3-13

Member Function Descriptioncout.width Sets the display field width.cout.precision Sets the precision of floating point numbers.cout.setf Sets the specified format flags.cout.unsetf Disables, or turns off, the specified format

flags.

Page 89: Chapter 3. Expressions and Interactivity

89

Starting Out with C++, 3rd Edition

3.9 Formatted Input

• The cin object provides ways of controlling string and character input.

Page 90: Chapter 3. Expressions and Interactivity

90

Starting Out with C++, 3rd Edition

Program 3-27//This program uses setw with the cin object. #include <iostream.h>#include <iomanip.h>

void main(void){ char word[5];  cout << "Enter a word: "; cin >> setw(5) >> word; cout << "You entered " << word << endl;}

Page 91: Chapter 3. Expressions and Interactivity

91

Starting Out with C++, 3rd Edition

Program 3-28//This program uses cin's width member function. #include <iostream.h>#include <iomanip.h>

void main(void){ char word[5];  cout << "Enter a word: "; cin.width(5); cin >> word; cout << "You entered " << word << endl;}

Page 92: Chapter 3. Expressions and Interactivity

92

Starting Out with C++, 3rd Edition

Program Output for Programs 3-27 and 3-28

Enter a word: Eureka [Enter]You entered Eure

Page 93: Chapter 3. Expressions and Interactivity

93

Starting Out with C++, 3rd Edition

Important points about the way cin handles field widths:

• The field width only pertains to the very next item entered by the user.

• cin stops reading input when it encounters a whitespace character. Whitespace characters include the [Enter] key, space, and tab.

Page 94: Chapter 3. Expressions and Interactivity

94

Starting Out with C++, 3rd Edition

Reading a “Line” of Input

cin.getline(line, 20);

Page 95: Chapter 3. Expressions and Interactivity

95

Starting Out with C++, 3rd Edition

Program 3-29//This program demonstrates cin's getline member function.#include <iostream.h>#include <iomanip.h>

void main(void){

char sentence[81];

cout << "Enter a sentence: ";cin.getline(sentence, 81);cout << "You entered " << sentence << endl;

}

Page 96: Chapter 3. Expressions and Interactivity

96

Starting Out with C++, 3rd Edition

Program Output

Enter a sentence: To be, or not to be, that is the question. [Enter]You entered To be, or not to be, that is the question.

Page 97: Chapter 3. Expressions and Interactivity

97

Starting Out with C++, 3rd Edition

Program 3-30#include <iostream.h>

void main(void){

char ch;

cout << "Type a character and press Enter: ";cin >> ch;cout << "You entered " << ch << endl;

}

Program Output with Example InputType a character and press Enter: A [Enter] You entered A

Page 98: Chapter 3. Expressions and Interactivity

98

Starting Out with C++, 3rd Edition

Program 3-31#include <iostream.h>

void main(void){

char ch;

cout << "This program has paused. Press enter to continue.";cin.get(ch);cout << "Thank you!" << endl;

}

Program OutputThis program has paused. Press Enter to continue.

[Enter]Thank you!

Page 99: Chapter 3. Expressions and Interactivity

99

Starting Out with C++, 3rd Edition

Program 3-32#include <iostream.h>

void main(void){

char ch;

  cout << "Type a character and press Enter: ";cin.get(ch);cout << "You entered " << ch << endl;cout << "Its ASCII code is " << int(ch) << endl;

}

 

Page 100: Chapter 3. Expressions and Interactivity

100

Starting Out with C++, 3rd Edition

Program Output

Type a character and press Enter: [Enter] You entered Its ASCII code is 10

Page 101: Chapter 3. Expressions and Interactivity

101

Starting Out with C++, 3rd Edition

Mixing cin >> and cin.get

• Mixing cin.get with cin >> can cause an annoying and hard-to-find problem.

• Pressing the [Enter] key after inputting a number will cause the newline character to be stored in the keyboard buffer. To avoid this, use cin.ignore.

• cin.ignore(20,’\n’); will skip the next 20 chars in the input buffer or until a newline is encountered, whichever comes first

• cin.ignore(); will skip the very next character in the input buffer

Page 102: Chapter 3. Expressions and Interactivity

102

Starting Out with C++, 3rd Edition

3.10 Focus on Object-Oriented Programming:More About Object- Oriented Programming• A member function is a procedure, written in C++

code, that is part of an object. A member function causes the object it is a member of to perform an action

• In this chapter, we have used width, precision, setf, and unsetf for the cout object

• In this chapter we have used width, getline, get, and ignore for the cin object

Page 103: Chapter 3. Expressions and Interactivity

103

Starting Out with C++, 3rd Edition

3.11 More Mathematical Library Functions

• The C++ runtime library provides several functions for performing complex mathematical operations.

• In this chapter we have used width, precision, setf, and unsetf for the cout object

• In this chapter we have used width, getline, get, and ignore for the cin object

Page 104: Chapter 3. Expressions and Interactivity

104

Starting Out with C++, 3rd Edition

Table 3-14ab s Example Usage:

y = a b s (x ); Description Returns the absolute value of the argument. The

argument and the return value are integers. c o s Example Usage:

y = c o s (x ); Description Returns the cosine of the argument. The argument

should be an angle expressed in radians. The return type and the argument are doubles.

e x p Example Usage: y = e x p (x );

Description Computes the exponential function of the argument, which is x . The return type and the argument are doubles.

Page 105: Chapter 3. Expressions and Interactivity

105

Starting Out with C++, 3rd Edition

Table 3-14 continuedfm o d Example Usage:

y = fm o d (x , z ); Description Returns, as a double, the remainder of the first argument

divided by the second argument. Works like the modulus operator, but the arguments are doubles. (The modulus operator only works with integers.) Take care not to pass zero as the second argument. Doing so would cause division by zero.

lo g Example Usage: y = lo g (x );

Description Returns the natural logarithm of the argument. The return type and the argument are doubles.

lo g 1 0 Example Usage: y = lo g 1 0 (x );

Description Returns the base-10 logarithm of the argument. The return type and the argument are doubles.

Page 106: Chapter 3. Expressions and Interactivity

106

Starting Out with C++, 3rd Edition

Table 3-14 continueds in Example Usage:

y = s in (x ); Description Returns the sine of the argument. The argument should be an angle

expressed in radians. The return type and the argument are doubles. sq rt Example Usage:

y = sq rt(x ); Description Returns the square root of the argument. The return type and

argument are doubles.

ta n Example Usage: y = ta n (x ); Description Returns the tangent of the argument. The argument should be an

angle expressed in radians. The return type and the argument are doubles.

Page 107: Chapter 3. Expressions and Interactivity

107

Starting Out with C++, 3rd Edition

Program 3-33// This program asks for the lengths of the 2 sides of a right // triangle. The length of the hypotenuse is then calculated// and displayed.#include <iostream.h>#include <math.h> // For sqrt and pow

void main(void){

float a, b, c; 

cout << "Enter the length of side A: ";cin >> a;cout << "Enter the length of side B: ";cin >> b;c = sqrt(pow(a, 2.0) + pow(b, 2.0));cout.precision(2);cout << "The length of the hypotenuse is ";cout << c << endl;

}

Page 108: Chapter 3. Expressions and Interactivity

108

Starting Out with C++, 3rd Edition

Program Output

Enter the length of side A: 5.0 [Enter]Enter the length of side B: 12.0 [Enter]The length of the hypotenuse is 13

Page 109: Chapter 3. Expressions and Interactivity

109

Starting Out with C++, 3rd Edition

Random numbers

rand() (from the cstdlib library)

Page 110: Chapter 3. Expressions and Interactivity

110

Starting Out with C++, 3rd Edition

Program 3-34// This program demonstrates random numbers.#include <iostream.h>#include <stdlib.h>using namespace std;

void main(void){

unsigned seed;cout << "Enter a seed value: ";cin >> seed;srand(seed);cout << rand() << endl;cout << rand() << endl;cout << rand() << endl;

}

Page 111: Chapter 3. Expressions and Interactivity

111

Starting Out with C++, 3rd Edition

Program Output

Enter a seed value: 517313203621622Program Output with Other Example InputEnter a seed value: 165540296639920

Page 112: Chapter 3. Expressions and Interactivity

112

Starting Out with C++, 3rd Edition

3.13 Optional Section : Introduction to Simple File Input and Output

• What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.

Page 113: Chapter 3. Expressions and Interactivity

113

Starting Out with C++, 3rd Edition

The Process of Using a File

• Using a file in a program is a simple three-step process• The file must be opened. If the file does not yet

exits, opening it means creating it.• Information is then saved to the file, read from

the file, or both.• When the program is finished using the file, the

file must be closed.

Page 114: Chapter 3. Expressions and Interactivity

114

Starting Out with C++, 3rd Edition

Figure 3-8

Page 115: Chapter 3. Expressions and Interactivity

115

Starting Out with C++, 3rd Edition

Figure 3-9

Page 116: Chapter 3. Expressions and Interactivity

116

Starting Out with C++, 3rd Edition

Setting Up a Program for File Input/Output

• Before file I/O can be performed, a C++ program must be set up properly.

• File access requires the inclusion of the fstream.h header file.

Page 117: Chapter 3. Expressions and Interactivity

117

Starting Out with C++, 3rd Edition

Table 3-16

File Type Default Open Mode ofstream The file is opened for output only. Information may be written

to the file, but not read from the file.

ifstream The file is opened for input only. Information may be read from the file, but not written to it.

fstream The file is opened for input and output. Information may be written to the file or read from it.

Page 118: Chapter 3. Expressions and Interactivity

118

Starting Out with C++, 3rd Edition

Opening a File

• Before data can be written to or read from a file, the file must be opened.

ifstream inputFile;inputFile.open(“customer.dat”);

Page 119: Chapter 3. Expressions and Interactivity

119

Starting Out with C++, 3rd Edition

Closing a File

• A file should be closed when a program is finished using it.

outputFile.close();

Page 120: Chapter 3. Expressions and Interactivity

120

Starting Out with C++, 3rd Edition

Writing Information to a File

• The stream insertion operator (<<) may be used to write information to a file.

outputFile << “I love C++ programming !”

outputFile << “Price: “ << price;

Page 121: Chapter 3. Expressions and Interactivity

121

Starting Out with C++, 3rd Edition

Program 3-35// This program uses the << operator to write information to a// file.#include <iostream.h>#include <fstream.h>

void main(void){

ofstream outputFile;

outputFile.open("demofile.txt");cout << "Now writing information to the file.\n";

// Write 4 great names to the fileoutputFile << "Bach\n";outputFile << "Beethoven\n";outputFile << "Mozart\n";outputFile << "Schubert\n"; 

Page 122: Chapter 3. Expressions and Interactivity

122

Starting Out with C++, 3rd Edition

Program 3-35 (continued)// Close the fileoutputFile.close();cout << "Done.\n";

}

Program Screen Output

Now writing information to the file.Done.

Output to File demofile.txt

BachBeethovenMozartSchubert

Page 123: Chapter 3. Expressions and Interactivity

123

Starting Out with C++, 3rd Edition

Reading Information from a File

• The stream extraction operator (>>) may be used to read information from a file.

inFile >> name;

Page 124: Chapter 3. Expressions and Interactivity

124

Starting Out with C++, 3rd Edition

Program 3-36// This program uses the >> operator to read information from a// file.#include <iostream.h>#include <fstream.h>

void main(void){

ifstream inFile;char name[81];

inFile.open("demofile.txt");cout << "Reading information from the file.\n\n";

// Now read name 1 from the fileinFile >> name;cout << name << endl;// Now read name 2 from the fileinFile >> name;cout << name << endl

Page 125: Chapter 3. Expressions and Interactivity

125

Starting Out with C++, 3rd Edition

Program 3-36 (continued)// Now read name 3 from the fileinFile >> name;cout << name << endl;// Now read name 4 from the fileinFile >> name;cout << name << endl;

// Close the fileinFile.close();cout << "\nDone.\n";

}

Program Screen OutputReading information to the file.

BachBeethovenMozartSchubert

Done.

Page 126: Chapter 3. Expressions and Interactivity

126

Starting Out with C++, 3rd Edition

Program 3-37// This program uses the >> operator to read information from a// file.#include <iostream.h>#include <fstream.h>

void main(void){

ifstream inFile;int length, width, area;

inFile.open("dimensions.txt");cout << "Reading dimensions of 5 rectangles from the file.\n\n";

// Process rectangle 1inFile >> length;inFile >> width;area = length * width;cout << "Area of rectangle 1: " << area << endl;

// Process rectangle 2inFile >> length;inFile >> width;area = length * width;cout << "Area of rectangle 2: " << area << endl;

Page 127: Chapter 3. Expressions and Interactivity

127

Starting Out with C++, 3rd Edition

Program 3-37 (continued)// Process rectangle 3inFile >> length;inFile >> width;area = length * width;cout << "Area of rectangle 3: " << area << endl;

// Process rectangle 4inFile >> length;inFile >> width;area = length * width;cout << "Area of rectangle 4: " << area << endl;

// Process rectangle 5inFile >> length;inFile >> width;area = length * width;cout << "Area of rectangle 5: " << area << endl;

// Close the fileinFile.close();cout << "\nDone.\n";

}

Page 128: Chapter 3. Expressions and Interactivity

128

Starting Out with C++, 3rd Edition

Program 3-37Before Program 3-37 is executed, the file dimensions.txt must be created with a text editor (such as Windows Notepad). Here is an example of the file's contents:

 

10 25 718 96 208 3

Page 129: Chapter 3. Expressions and Interactivity

129

Starting Out with C++, 3rd Edition

Program 3-37The program's output is shown below.

 

Program OutputReading dimensions of 5 rectangles from the file.

Area of rectangle 1: 20Area of rectangle 2: 35Area of rectangle 3: 162Area of rectangle 4: 120Area of rectangle 5: 24

Done.