Download presentation
Presentation is loading. Please wait.
1
Chapter 3: Expressions & Interactivity
2
3.1 The cin Object The cin object reads information typed from the keyboard. cin is the standard input object. The cin object causes a program to wait until information is typed at the keyboard and the [Enter] key is pressed. cin automatically converts the information read from the keyboard to the data type of the variable used to store it. You must include the iostream.h file in any program that uses cin.
3
3-1 Program #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
3-1 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
>> and << Operators
Notice the >> and << operators appear to point in the direction information is flowing. The >> operator indicates information flows from cin to a variable. The << operator shows that information flows from a variable (or constant) to cout.
6
3.1 The cin Object Continued
cin is smart enough to know a value like 10.7 cannot be stored in an integer variable. If the user enters a floating point value into an integer variable, the part of the number after the decimal point is thrown away. When part of a value is discarded, it is truncated. cin truncates floating point numbers that are to be stored in integer variables.
7
Users of Your Programs Always explain to the user what the program is or what information is needed. Always be courteous and prompt the user to enter exactly what the program needs. Users do not want to see your source code.
8
Entering Multiple Values
The cin object may be used to gather multiple values at once. cin will read multiple values of different data types.
9
3-3 Program #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; }
10
3-3 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
11
3-4 Program // 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; }
12
3-4 Program Output Enter an integer, a float, and a character: b [Enter] whole: 4 fractional: 5.7 letter: b
13
Reading Strings cin can read strings, as well as, numbers.
In C++, C-strings are commonly stored in character arrays. An array is like a group of variables with a single name, located together in memory.
14
Character Array An example of a character array declaration: char company[12]; The number inside the brackets indicates the size of the array. The name of the array is company, and it is large enough to hold 12 characters. Remember that C-strings have the null terminator at the end, so this array is large enough to hold a C-string that is 11 characters long.
15
3-5 Program //This program shows how cin may
//be used to read a string into a //character array #include <iostream.h> #include<string> void main(void) { string name; cout << "What is your name? "; cin >> name; cout << "Good morning " << name << endl; }
16
3-5 Program Output What is your name? Charlie [Enter]
Good morning Charlie
17
char name[21]; The name of the array is name and it is large enough to hold 21 characters. The null terminator at the end of a C-string is a character, so the longest string that may be stored in this array is 20 characters. 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.
18
3-6 Program //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 name and I will\n"; cout << "reverse them.\n"; cin >> first >> last; cout << last << ", " << first << endl; }
19
3-6 Program Output Enter your first and last names and I will
reverse them. Johnny Jones [Enter] Jones, Johnny
20
Notes on Strings If you wish the user to enter a string that has spaces in it, you cannot use this input method.
21
3.2 Mathematical Expressions
C++ allows you to construct complex mathematical expressions using multiple operators and grouping symbols. Mathematical expressions are evaluated from left to right. When two operators share an operand, the operator with the highest precedence works first. Multiplication and division have higher precedence than addition and subtraction.
22
Expression An expression is a programming statement that has a value.
Usually, an expression consists of an operator and its operands. Sum = : Since has a value, it is an expression. Its value, 24, is stored in the variable sum. Expressions do not have to be in the form of mathematical operations. number = 3; 3 is an expression.
23
3-7 Program // 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); }
24
3-7 Program Output 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
25
Precedence of Arithmetic Operators (Highest to Lowest)
(unary negation) - * / % + -
26
Table 3-2 Some Expressions with their Values
27
Associativity If two operators sharing an operand have the same precedence, they work according to their associativity. Associativity is either right to left or left to right. It is the order in which an operator works with its operands. The associativity of the division operator is left to right, so it divides the operand on its left by the operand on its right.
28
Table 3-3 Associatively of Arithmetic Operators
Grouping with Parentheses: Parts of a mathematical expression may be grouped with parentheses to force some operations to be performed before others.
29
Converting Algebraic Expressions to Programming Statements
In algebra it is not always necessary to use an operator for multiplication. However, C++ requires an operator for any mathematical operation. The above table shows some algebraic expressions that perform multiplication and the equivalent C++ expression.
30
area = pow(4,2) // will store 42 in area
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
31
pow function Must include math.h header file.
The variable used to store pow’s return value should be declared as a double or a float. The pow function is designed to return a double. Remember that a double value will fit in a float variable if the value is small enough. If the arguments of the pow function are large enough to cause pow to produce a value outside the range of a float, a double variable should be used to store its return value.
32
3-8 Program // This program calculates the area of a circle.
// The formula for the area of a circle is Pi times // the radius squared. Pi is #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 = * pow(radius,2); cout << "The area is " << area; }
33
3-8 Program Output with Example Input
This program calculates the area of a circle. What is the radius of the circle? 10[Enter] The area is
34
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.
35
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.
36
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
37
3-9 Program // This program demonstrates integer underflow and
// overflow #include <iostream.h> void main(void) { short testVar = 32767; cout << testVar << endl; testVar = testVar + 1; testVar = testVar - 1; }
38
3-9 Program Output 32767 -32768
39
3-10 Program // 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 test cout << test << endl; test = 2.0e-38 / 2.0e38; }
40
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
41
3-11 Program #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"; }
42
3-11 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.
43
perMonth = float(books / months);
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.
44
3-12 Program //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; }
45
3-12 Program Output 65 A
46
3.6 The Power of Constants Constants may be given names that symbolically represent them in a program.
47
3-13 Program // This program calculates the area of a circle.
#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; }
48
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= ;
49
3-14 Program #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; }
50
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;
51
3-15 Program // 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;
52
3-15 Program 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? "; store2 = store2 – sold; //Subtract sold from store2 cout << "How many widgets has store 3 sold? "; store3 = store3 – sold; //Subtract sold from store 3 cout << "Store1: " << store1 << endl; cout << "Store2: " << store2 << endl; cout << "Store3: " << store3 << endl; }
53
3-15 Program Output with Example Input
One week ago, 3 new widget stores opened at the same time with the same beginning inventory. 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: 75 Store 2: 85 Store 3: 55
54
Table 3-8
55
Table 3-9
56
3-16 Program // 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;
57
3-16 Program 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? "; store2 -= sold; //Subtract sold from store2 cout << "How many widgets has store 3 sold? "; store3 -= sold; //Subtract sold from store 3 cout << "Store1: " << store1 << endl; cout << "Store2: " << store2 << endl; cout << "Store3: " << store3 << endl; }
58
3-16 Program Output with Example Input
One week ago, 3 new widget stores opened at the same time with the same beginning inventory. 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: 75 Store 2: 85 Store 3: 55
59
Table 3-12
60
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 // The next statement works like // setiosflags(ios::fixed) cout.setf(ios::fixed);
61
3-24 Program // 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;
62
3-24 Program Continued 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;
63
3-24 Program Continued cout << “Day 3: "; cout.width(8);
cout << day3 << endl; cout << "Total: "; cout << total << endl; }
64
3-24 Program Output Enter the sales for day 1: 2642.00 [Enter]
Sales Figures Day 1: Day 2: Day 3: Total:
65
3-25 Program // 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;
66
3-25 Program Continued 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; }
67
3-25 Program Output Enter the sales for day 1: 2642.00 [Enter]
Sales Figures Day 1: Day 2: Day 3: Total:
68
Table 3-13
69
3.9 Formatted Input The cin object provides ways of controlling string and character input.
70
3-26 Program // 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; }
71
3-27 Program // 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; }
72
3-26 and 3-287 Program Output Enter a word: Eureka [Enter]
You entered Eure
73
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.
74
Reading a “Line” of Input
cin.getline(line, 20);
75
3-28 Program // 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; }
76
3-28 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.
77
3-29 Program #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 Input Type a character and press Enter: A [Enter] You entered A
78
3-30 Program #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 Output This program has paused. Press Enter to continue. [Enter] Thank you!
79
3-31 Program #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; }
80
3-31 Program Output Type a character and press Enter: [Enter]
You entered Its ASCII code is 10
81
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.
82
3.10 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.
83
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.
84
Table 3-14
85
Table 3-14 Continued
86
Table 3-14 Continued
87
3-32 Program // 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; }
88
3-32 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
89
rand() (from the cstdlib library)
Random numbers rand() (from the cstdlib library)
90
3-33 Program // 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; }
91
3-33 Program Output Enter a seed value: 5 1731 32036 21622
Program Output with Other Example Input Enter a seed value: 16 5540 29663 9920
92
3.13 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.
93
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.
94
Figure 3-8
95
Figure 3-9
96
Setting Up a Program for File Input/Output (I/O)
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.
97
Table 3-16
98
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”);
99
Closing a File A file should be closed when a program is finished using it. outputFile.close();
100
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;
101
3-36 Program // 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 file outputFile << "Bach\n"; outputFile << "Beethoven\n"; outputFile << "Mozart\n"; outputFile << "Schubert\n";
102
3-36 Program Continued // Close the file outputFile.close(); cout << "Done.\n"; } Program Screen Output Now writing information to the file. Done. Program Output to File demofile.txt Bach Beethoven Mozart Schubert
103
Reading Information from a File
The stream extraction operator (>>) may be used to read information from a file. inFile >> name;
104
3-37 Program // 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 1 inFile >> length; inFile >> width; area = length * width; cout << "Area of rectangle 1: " << area << endl; // Process rectangle 2 inFile >> length; inFile >> width; area = length * width; cout << "Area of rectangle 2: " << area << endl;
105
Program 3-37 Continued // Process rectangle 3 inFile >> length; inFile >> width; area = length * width; cout << "Area of rectangle 3: " << area << endl; // Process rectangle 4 inFile >> length; inFile >> width; area = length * width; cout << "Area of rectangle 4: " << area << endl; // Process rectangle 5 inFile >> length; inFile >> width; area = length * width; cout << "Area of rectangle 5: " << area << endl; // Close the file inFile.close(); cout << "\nDone.\n"; }
106
3-37 Program Before 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:
107
3-37 Program Output Reading dimensions of 5 rectangles from the file. Area of rectangle 1: 20 Area of rectangle 2: 35 Area of rectangle 3: 162 Area of rectangle 4: 120 Area of rectangle 5: 24 Done.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.