All Programs
All Programs
#include <iostream>
void main ()
{
int length, width, area;
cout << "The area of the rectangle is " << area << ".\n";
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.
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.
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.
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.
The cin object may be used to gather multiple values at once.cin will read multiple
values of different data types.
3-2 Program:
#include <iostream>
void main()
{
int length, width, area;
cout << "Enter the length and width of the rectangle separated by a space. \n"
cout << "The area of the rectangle is " << area << endl;
Enter the length and width of the rectangle separated by a space.10 20 [Enter] The
area of the rectangle is 200
void main(void)
int whole;
float fractional;
char letter;
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.
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.
#include <iostream>
#include<string>
void main()
string name;
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.
void main()
cout << "Enter your first and last name and I will\n";
cout << last << ", " << first << endl;
3-6 Program Output Enter your first and last names and I will:
reverse them. Johnny Jones [Enter] Jones, Johnny
Notes on Strings If you wish the user to enter a string that has spaces in it, you cannot
use this input method.
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.
#include <iostream>
void main(void)
This program shows the decimal value of a fraction. Enter the numerator: 3
[Enter]Enter the denominator: 6 [Enter]The decimal value is
(unary negation) - * / % + -
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
// The formula for the area of a circle is Pi times the radius squared. Pi is
#include <iostream>
void main(void)
area = * pow(radius,2);
This program calculates the area of a circle. What is the radius of the circle? 10[Enter]
the area is
when an operator’s operands are of different data types, C++ will automatically convert
them to the same data type.
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.
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
#include <iostream>
void main()
testVar = testVar + 1;
testVar = testVar - 1;
#include <iostream>
void main()
float test;
test = 2.0e38 * 1000; // Should overflow test
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
3-11 Program
#include <iostream>
void main()
{
int months, books;
float perMonth;
cout << "How many months will it take you to read them? ";
cout << "That is " << perMonth << " books per month.\n";
How many months will it take you to read them? 7 [Enter] That is books per month.
void main()
3.6 The Power of Constants may be given names that symbolically represent them in a
program.
#include <iostream>
#include <math>
void main()
const float pi = ;
area = pi * pow(radius,2);
}
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 PIis
roughly the same asconst float PI= ;
3-14 Program:
#include <iostream>
#define PI
void main()
Multiple assignment means to assign the same value to several variables with one
statement. A = B = C = D = 12;Store1 = Store2 = Store3 = BegInv;
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>
void main()
{
int begInv, sold, store1, store2, store3;
cout << “at the same time with the same beginning\n";
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: 75Store 2:
85Store 3: 55
Table 3-8
Table 3-9
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>
void main()
cout << “at the same time with the same beginning\n";
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: 75Store 2:
85Store 3: 55
Table 3-12
Formatting Output with Member Functions:
3-24 Program // This program asks for sales figures for 3 days.
The // total sales is calculated and displayed in a table.
#include <iostream>
#include <iomanip>
void main()
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout.width(8);
cout.width(8);
cout << day3 << endl;
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>
#include <iomanip>
void main(void)
cout.setf(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;
return 0;
3-25 Program Output Enter the sales for day 1: 2642.00 [Enter]:
Table 3-13
3.9 Formatted InputThe cin object provides ways of controlling string and character
input.
3-26 Program // This program uses setw with the cin object:
#include <iostream>
#include <iomanip>
void main()
char word[5];
#include <iostream>
#include <iomanip>
void main()
char word[5];
cin.width(5);
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.
cin.getline(line, 20);
#include <iostream>
#include <iomanip>
void main(void)
char sentence[81];
cin.getline(sentence, 81);
3-28 Program OutputEnter 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.
3-29 Program:
#include <iostream>
void main()
char ch;
Program Output with Example InputType a character and press Enter: A [Enter]You
entered A
3-30 Program:
#include <iostream>
void main()
{
char ch;
cin.get(ch);
Program Output This program has paused. Press Enter to continue. [Enter]Thank you!
3-31 Program:
#include <iostream>
void main()
char ch;
cin.get(ch);
cout << "Its ASCII code is " << int(ch) << endl;
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.
3.10 More About Object-Oriented Programming:
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.
Table 3-14
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>
void main(void)
float a, b, c;
cin >> a;
cin >> b;
cout.precision(2);
#include <iostream>
#include <stdlib>
void main()
unsigned seed;
srand(seed);
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 mean 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.
Figure 3-8
Figure 3-9
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.
Table 3-16
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”);
3-36 Program// This program uses the << operator to write information to a // file.
#include <iostream.h>
#include <fstream>
void main()
ofstream outputFile;
outputFile.open("demofile.txt");
cout << "Now writing information to the file.\n"; // Write 4 great names to the file
outputFile.close();
Program Screen OutputNow writing information to the file. Done.Program Output to File
demofile.txtBach Beethoven Mozart Schubert
The stream extraction operator (>>) may be used to read information from a file.inFile
>> name;
3-37 Program// This program uses the >> operator to read information from a // file.
#include <iostream>
#include <fstream>
void main()
ifstream inFile;
inFile.open("dimensions.txt");
cout << "Reading dimensions of 5 rectangles from the file.\n\n"; // Process rectangle 1
// Process rectangle 3
cout << "Area of rectangle 3: " << area << endl; // Process rectangle 4
cout << "Area of rectangle 4: " << area << endl; // Process rectangle 5
cout << "Area of rectangle 5: " << area << endl; // Close the file
inFile.close();
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:
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.