Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3. Expressions and Interactivity

Similar presentations


Presentation on theme: "Chapter 3. Expressions and Interactivity"— Presentation transcript:

1 Chapter 3. Expressions and Interactivity

2 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.

3 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"; }

4 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.

5 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; }

6 Entering Multiple Values
The cin object may be used to gather multiple values at once.

7 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; }

8 This program calculates the area of a rectangle.
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

9 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; }

10 Program Output Enter an integer, a float, and a character: b [Enter] Whole: 4 Fractional: 5.7 Letter: b

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

12 Program 3-5 #include <iostream.h> void main(void) {
char Name[21]; cout << "What is your name? "; cin >> Name; cout << "Good morning " << Name << endl; }

13 What is your name? Charlie [Enter] Good morning Charlie
Program Output What is your name? Charlie [Enter] Good morning Charlie

14 Program 3-6 // 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; }

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

16 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.

17 3.2 Focus on Software Engineering: Mathematical Expressions
C++ allows you to construct complex mathematical expressions using multiple operators and grouping symbols.

18 Program 3-7 #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); }

19 Program Output This program shows the decimal value of a fraction. Enter the numerator: 3 [Enter] Enter the denominator: 16 [Enter] The decimal value is

20 Table 3-1 Precedence of Arithmetic Operators (Highest to Lowest)
(unary negation) - * / % + -

21 Table 3-2 Some Expressions

22 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

23

24 Converting Algebraic Expressions to Programming Statements

25 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

26 Program 3-8 #include <iostream.h> #include <math.h>
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 = * pow(Radius,2); cout << "The area is " << Area; }

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

28 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.

29 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.

30 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

31 Program 3-9 #include <iostream.h> void main(void) {
short TestVar = 32767; cout << TestVar << endl; TestVar = TestVar + 1; TestVar = TestVar - 1; }

32 Program Output 32767 -32768

33 Program 3-10 #include <iostream.h> void main(void) { float Test;
Test = 2.0e38 * 1000; // Should overflow Test cout << Test << endl; Test = 2.0e-38 / 2.0e38; }

34 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

35 Program 3-11 #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"; }

36 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 books per month.

37 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.

38 Program 3-12 // 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; }

39 Program Output 65 A

40 The Power of Constants Constants may be given names that symbolically represent them in a program.

41 Program 3-13 #include <iostream.h> #include <math.h>
void main(void) { const float Pi = ; 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; }

42 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 is roughly the same as const float PI= ;

43 Program 3-14 #include <iostream.h>
#include <math.h> // needed for pow function #define PI   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; }  

44 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;

45 Table 3-8

46 Table 3-9

47 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.

48 Program 3-17 #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 numbers cout << Num1 << " "; cout << Num2 << " "; cout << Num3 << endl; // Display the second row of numbers cout << Num4 << " "; cout << Num5 << " "; cout << Num6 << endl; // Display the third row of numbers cout << Num7 << " "; cout << Num8 << " "; cout << Num9 << endl; }

49 Program Output

50 Program 3-18 // This program displays three rows of numbers.
#include <iostream.h> #include <iomanip.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 numbers cout << setw(4) << Num1 << " "; cout << setw(4) << Num2 << " "; cout << setw(4) << Num3 << endl;

51 Program continues // Display the second row of numbers
cout << setw(4) << Num4 << " "; cout << setw(4) << Num5 << " "; cout << setw(4) << Num6 << endl; // Display the third row of numbers cout << setw(4) << Num7 << " "; cout << setw(4) << Num8 << " "; cout << setw(4) << Num9 << endl; }

52 Program Output

53 Program 3-19 // 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 StringValue[14] = "John J. Smith"; cout << "(" << setw(5) << IntValue << ")" << endl; cout << "(" << setw(8) << FloatValue << ")" << endl; cout << "(" << setw(16) << StringValue << ")" << endl; }

54 Program Output ( 3928) ( ) ( John J. Smith)

55 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.

56 Program 3-20 // This program demonstrates how setprecision rounds a // floating point value.   #include <iostream.h> #include <iomanip.h> void main(void) { float Quotient, Number1 = , 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; }

57 Program Output 4.9188 4.919 4.92 4.9 5

58 Table 3-11

59 Program 3-21 // 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;

60 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; }

61 Program Output Enter the sales for day 1: [Enter] Enter the sales for day 2: [Enter] Enter the sales for day 3: [Enter] Sales Figures Day 1: Day 2: Day 3: Total:

62 Program 3-22 #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;

63 cout << "\nSales Figures\n"; cout << "------\n";
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; }

64 Program Output Enter the sales for day 1: 1321.87 [Enter]
Sales Figures Day 1: Day 2: Day 3: Total:

65 IOS Flags setiosflags manipulator can be used to format output in a variety of ways, depending on which glad is specified. setiosflags(ios::fixed) will cause all subsequent numbers to be printed in fixed point notation

66 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;

67 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; }

68 Program Output Enter the sales for day 1: 2642.00 [Enter]
Sales Figures Day 1: Day 2: Day 3: Total:

69 Table 3-12

70 Formatting Output With Member Functions
cout.width(5); //calls the width member function, //same as setw(5) cout.precision(2); //sets precision to 2 significant //digits cout.setf(ios::fixed); //same as setiosflags(ios::fixed)

71 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; cout << "Enter the sales for day 3: "; cin >> Day3;

72 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 << Day2 << endl;

73 Program continues cout << "Day 3: "; cout.width(8);
cout << Day3 << endl; cout << "Total: "; cout << Total << endl; }

74 Program Output Enter the sales for day 1: 2642.00 [Enter]
Sales Figures Day 1: Day 2: Day 3: Total:

75 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;

76 cout.setf(ios::fixed | ios::showpoint);
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; }

77 Program Output Enter the sales for day 1: 2642.00 [Enter]
Sales Figures Day 1: Day 2: Day 3: Total:

78 Table 3-13

79 3.9 Formatted Input The cin object provides ways of controlling string and character input.

80 Program 3-26 // This program uses setw with the cin object.
#include <iostream.h> #include <iomanip.h> void main(void) { char String[5]; cout << "Enter a word: "; cin >> setw(5) >> String; cout << "You entered " << String << endl; }

81 Program 3-27 // This program uses cin's width member function.
#include <iostream.h> #include <iomanip.h> void main(void) { char String[5]; cout << "Enter a word: "; cin.width(5); cin >> String; cout << "You entered " << String << endl; }

82 Program Output for Programs 3-26 and 3-27
Enter a word: Eureka [Enter] You entered Eure

83 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.

84 Reading a “Line” of Input
cin.getline(String, 20);

85 Program 3-28 // This program demonstrates cin's getline member function. #include <iostream.h> #include <iomanip.h> void main(void) { char String[81]; cout << "Enter a sentence: "; cin.getline(String, 81); cout << "You entered " << String << endl; }

86 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.

87 Reading a character #include <iostream.h>
#include <iomanip.h> void main(void) { char Ch; cout << "Type a character and press Enter: "; cin >> Ch; cout << "You entered " << Ch << endl; } Program Output with Example Input Type a character and press Enter: A [Enter] You entered A

88 Program 3-29 #include <iostream.h> #include <iomanip.h>
void main(void) { char Ch; cout << "Type a character and press Enter: "; cin >> Ch; cout << "You entered " << Ch << endl; } Program Output Type a character and press Enter: A [Enter] You entered A

89 Program 3-30 #include <iostream.h> #include <iomanip.h>
 void main(void) { char Ch; cout << "This program has paused. Press enter to continue."; cin.get(Ch); cout << "Thank you!" << endl; } Program Output This program has paused. Press Enter to continue. [Enter] Thank you!

90 Program 3-31 #include <iostream.h> #include <iomanip.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; }

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

92 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

93 3.10 More Mathematical Library Functions
The C++ runtime library provides several functions for performing complex mathematical operations.

94 Table 3-14

95 Table 3-14 continued

96 Table 3-14 continued

97 Program 3-32 #include <iostream.h>
#include <math.h> // For sqrt 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; }

98 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

99 Random Numbers rand() (from the stdlib.h library)

100 Program 3-33 // This program demonstrates random numbers.
 #include <iostream.h> #include <stdlib.h> void main(void) { unsigned Seed; cout << "Enter a seed value: "; cin >> Seed; srand(Seed); cout << rand() << endl; }

101 Program Output Enter a seed value: 5 1731 32036 21622 Program Output with Other Example Input Enter a seed value: 16 5540 29663 9920


Download ppt "Chapter 3. Expressions and Interactivity"

Similar presentations


Ads by Google