c++ programmingsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · data types...

78
C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Upload: others

Post on 06-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

C++ PROGRAMMING For Industrial And Electrical Engineering

Instructor: Ruba A. Salamh

Page 2: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

CHAPTER TWO:

Fundamental Data Types

Page 3: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Chapter Goals

• In this chapter, you will learn how to work with numbers

and text, and how to write simple programs that perform

useful tasks with them.

Page 4: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

2.1 Variables

• A variable: is a storage location in a computer

program. Each variable has a name and holds a value.

• is used to store information.

• can contain one piece of information at a time.

• has an identifier (name):

The programmer picks a good name

• A good name describes the contents of the variable or what

the variable will be used for

Page 5: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

The following statement defines a variable.

int cans_per_pack = 6;

cans_per_pack is the variable’s name.

Variable Definitions

int indicates that the variable cans_per_pack

will be used to hold integers.

= 6

indicates that the variable cans_per_pack

will initially contain the value 6.

Page 6: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Must obey the

rules for valid

names

Variable Definitions

Page 7: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Variable Definitions

Page 8: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Data Types

• In C++, there are several different types of numbers.

• You use the integer number type, called int in C++, to

denote a whole number without a fractional part.

• When a fractional part is required (such as in the number

0.355), we use floating point numbers. The most

commonly used type for floating-point numbers in C++ is

called double.

• To store text and characters we have the char and string

data types.

double can_volume = 0.355;

Page 9: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Number Types

A number written by a programmer is called a number literal.

int cans_per_pack = 6 ;

There are rules for writing literal values:

Page 10: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Number Types

Page 11: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Variable Names

• When you define a variable, you should pick a name

that explains its purpose.

• For example, it is better to use a descriptive name, such

as can_volume, than a terse name, such as cv.

Page 12: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Variable Names • In C++, there are a few simple rules for variable

names:

1. Variable names must start with a letter or the

underscore ( _ ) character, and the remaining

characters must be letters numbers, or underscores.

2. You cannot use other symbols such as $ or %.

3. Spaces are not permitted inside names; you can use

an underscore instead, as in can_volume.

Page 13: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Variable Names

4. Variable names are case-sensitive, that is,

can_volume and can_Volume are different names.

For that reason, it is a good idea to use only lowercase

letters in variable names.

5. You cannot use reserved words such as double or

return as names; these words are reserved exclusively

for their special C++ meanings.

Page 14: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Variable Names

Page 15: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

The Assignment Statement

• The contents in variables can “vary” over time

• Variables can be changed by:

• assigning to them

• The assignment statement

• using the increment or decrement operator

• inputting into them

• The input statement

• An assignment statement stores a new value in a variable, replacing the previously stored value.

Page 16: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

cans_per_pack = 8;

• This assignment statement changes the value stored in

cans_per_pack to be 8.

• The previous value is replaced.

• The variable cans_per_pack has to be already declared.

The Assignment Statement

Page 17: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

The Assignment Statement

This is a Declaration statement

Page 18: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

The Assignment Statement

• There is an important difference between a variable definition

and an assignment statement:

int cans_per_pack = 6; // Variable definition

...

cans_per_pack = 8; // Assignment statement

• The first statement is the definition of cans_per_pack.

• The second statement is an assignment statement.

An existing variable’s contents are replaced.

Page 19: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

counter = 11; // set counter to 11

counter = counter + 2; // increment

cout << counter << endl;

13 is shown

The Assignment Statement

1. Look up what is currently in counter (11)

2. Add 2 to that value (13)

3. copy the result of the addition expression

into the variable on the left, changing counter

Page 20: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Constants • Sometimes the programmer knows certain values just from

analyzing the problem, for this kind of information,

programmers use the reserved word const.

• The reserved word const is used to define a constant.

• A const is a variable whose contents cannot be changed and

must be set when created. (Most programmers just call them

constants, not variables.)

• Constants are commonly written using capital letters to

distinguish them visually from regular variables:

const double BOTTLE_VOLUME = 2;

Page 21: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Constants • It is good programming style to use named constants in your

program to explain the meanings of numeric values. For

example, compare the statements:

double total_volume = bottles * 2;

double total_volume = bottles * BOTTLE_VOLUME;

• A programmer reading the first statement may not understand

the significance of the number 2 (magic number). The second

statement, with a named constant, makes the computation much

clearer.

Page 22: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Constants

And it can get even worse …

• Suppose that the number 2 appears hundreds of

times throughout a five-hundred-line program?

Now we need to change the BOTTLE_VOLUME

to 2.23 (because we are now using a bottle with a

different shape)

How to change only some of those magic

numbers?

Page 23: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Constants

Constants to the rescue!

const double BOTTLE_VOLUME = 2.23;

const double CAN_VOLUME = 2;

...

double bottle_volume = bottles * BOTTLE_VOLUME;

double can_volume = cans * CAN_VOLUME;

(Look, no magic numbers!)

Page 24: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Comments • As your programs get more complex, you should add comments,

explanations for human readers of your code. Here is an example:

const double CAN_VOLUME = 0.355; // Liters in a 12-ounce can

• The compiler does not process comments at all. It ignores everything

from a // delimiter to the end of the line.

• You use the // syntax for single-line comments.

• If you have a comment that spans multiple lines, enclose it between

/* and */ delimiters. For example:

/* This program computes the volume (in liters) of a six-

pack of soda cans and the total volume of a six-pack and a

two-liter bottle */

Page 25: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Example

• The following program shows the use of variables,

constants, and the assignment statement. The program

displays the volume of a six-pack of cans and the total

volume of the six-pack and a two-liter bottle.

Page 26: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Example

Page 27: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Common Error Using Undefined Variables

• You must define a variable before you use it for the first time.

For example, the following sequence of statements would not

be legal:

double can_volume = 12 * liter_per_ounce;

double liter_per_ounce = 0.0296;

• In your program, the statements are compiled in order. When

the compiler reaches the first statement, it does not know that

liter_per_ounce will be defined in the next line, and it

reports an error.

Page 28: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Common Error

Using Uninitialized Variables

• If you define a variable but leave it uninitialized, then your

program can act unpredictably.

int bottles; // Forgot to initialize

int bottle_volume = bottles * 2;

• The compiler won’t report an error, it’s a run time error,

the Result is unpredictable.

• There is no way of knowing what value will be computed.

Page 29: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Numeric Types In C++ • In addition to the int and double types, C++ has several other numeric

types.

Page 30: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Numeric Ranges And Precisions • The int type has a limited range: On most platforms, it can represent

numbers up to a little more than two billion. For many applications,

this is not a problem

• If a computation yields a value that is outside the int range, the result

overflows. No error is displayed. Instead, the result is truncated to fit

into an int, yielding a useless value. For example:

int one_billion = 1000000000;

cout << 3 * one_billion << endl;

displays –1294967296.

• In situations such as this, you can switch to double values.

Page 31: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Arithmetic Operators

C++ has the same arithmetic

operators as a calculator:

* for multiplication: a * b

(not a . b or ab as in math)

/ for division: a / b

(not ÷ or a fraction bar as in math)

+ for addition: a + b

- for subtraction: a – b

Page 32: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Arithmetic Operations

• You must write a * b to denote

multiplication. Unlike in mathematics, you

can not write ab, a . b or a × b. Similarly,

division is always indicated with a /, never

a ÷ or a fraction bar.

• For example: becomes (a + b) /

2.

Page 33: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Arithmetic Operations

• Parentheses are used just as in algebra: to indicate in

which order the subexpressions should be computed.

• For example, in the expression (a + b) / 2, the sum a + b is

computed first, and then the sum is divided by 2. In

contrast, in the expression a + b / 2

• only b is divided by 2, and then the sum of a and b / 2 is

formed.

Page 34: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Arithmetic Operations

• Multiplication and division have a higher precedence than

addition and subtraction.

• For example, in the expression a + b / 2, the / is carried out

first, even though the + operation occurs further to the left.

• If both arguments of an arithmetic operation are integers,

the result is an integer. If one or both arguments are

floating point numbers, the result is a floating-point

number.

• For example, 4 * 0.5 is 2.0.

Page 35: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Increment and Decrement

• Changing a variable by adding or subtracting 1 is so

common that there is a special shorthand for it, namely

counter++;

counter--;

• The ++ increment operator gave the C++ programming

language its name. C++ is the incremental improvement

of the C language.

Page 36: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Combining Assignment and Arithmetic

In C++, you can combine arithmetic and assignments.

For example, the statement:

total += cans * CAN_VOLUME;

is a shortcut for

total = total + cans * CAN_VOLUME;

Similarly,

total *= 2;

is another way of writing

total = total * 2;

Many programmers prefer using this form of coding.

Page 37: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Integer Division And Remainder

• Division works as you would expect, as long as at

least one of the numbers involved is a floating-point

number.

• That is, 7.0 / 4.0, 7 / 4.0, and 7.0 / 4 all yield 1.75.

• However, if both numbers are integers, then the

result of the division is always an integer, with the

remainder discarded.

• That is: 7 / 4 evaluates to 1 because 7 divided by 4 is 1 with a

remainder of 3 (which is discarded).

Page 38: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Integer Division And Remainder

• If you are interested in the remainder only, use the %

operator.

• The remainder of the integer division of 7 by 4 is 3

x = 7 % 4 ; x is assigned the value 3

• The operator % is called modulus symbol, it has no

analog in algebra.

• Note: you can use the modulus operator with intger

division only, that is: the two operands has to be integers.

Page 39: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Integer Division and Remainder

Example:

You want to determine the value in dollars and cents stored in the piggy bank. You obtain the dollars through an integer division by 100. The integer division discards the remainder. To obtain the remainder, use the % operator:

int pennies = 1729; // value in cents int dollars = pennies / 100; // Sets dollars to 17 int cents = pennies % 100; // Sets cents to 29

(yes, 100 is a magic number)

Page 40: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Integer Division and Remainder

dollars = / 100;

cents = % 100;

Page 41: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Converting Floating-Point Numbers to Integers

• When a floating-point value is assigned to an integer variable,

the fractional part is discarded:

double price = 2.55;

int dollars = price; // Sets dollars to 2

• You probably want to round to the nearest integer.

To round a positive floating-point value to the nearest

integer, add 0.5 and then convert to an integer:

int dollars = price + 0.5; // Rounds to the nearest integer

Page 42: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

How to write the following mathematical expression in

C++

Powers and Roots

1001

rn

bx

Page 43: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Powers and Roots

• In C++, there are no symbols for powers and roots.

To compute them, you must call functions.

• The C++ library defines many mathematical functions

such as sqrt (square root) and pow (raising to a power).

• To use the functions in this library, called the cmath

library, you must place the line: #include <cmath>

at the top of your program file.

• It is also necessary to include using namespace std;

at the top of your program file.

Page 44: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Powers and Roots The power function has the base followed by a comma followed

by the power to raise the base to: pow(base, exponent)

Using the pow function we can write:

x = b * pow(1 + r / 100, n);

1001

rn

bx

Page 45: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Other Mathematical Functions

Page 46: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer
Page 47: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Common Error – Unintended Integer Division • If both arguments of / are integers,

the remainder is discarded:

7 / 3 is 2, not 2.5

• but

7.0 / 4.0

7 / 4.0

7.0 / 4

• all yield 1.75.

Page 48: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Common Error – Unintended Integer Division

It is a common error to use integer division by accident.

Consider this segment that computes the average of three

integers:

cout << "Please enter your last three test scores: ";

int s1;

int s2;

int s3;

cin >> s1 >> s2 >> s3;

double average = (s1 + s2 + s3) / 3;

cout << "Your average score is " << average << endl;

Page 49: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Common Error – Unintended Integer Division The remedy is to make the numerator or denominator

into a floating-point number:

double total = s1 + s2 + s3;

double average = total / 3;

or

double average = (s1 + s2 + s3) / 3.0;

Page 50: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Common Error – Unbalanced Parentheses

Consider the expression:

(-(b * b - 4 * a * c) / (2 * a)

What is wrong with it?

The parentheses are unbalanced.

This is very common with complicated expressions.

?

Page 51: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Common Error – Forgetting Header Files

Every program that carries out input or output needs the <iostream> header.

If you use mathematical functions such as sqrt, you need to include <cmath>.

If you forget to include the appropriate header file, the compiler will not know symbols such as

cout or sqrt.

If the compiler complains about an undefined function or symbol, check your header files.

Page 52: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Common Error – Forgetting Header Files Sometimes you may not know which header file to include.

Suppose you want to compute the absolute value of an integer using the abs function.

As it happens, this version of abs is not defined in the <cmath> header but in <cstdlib>.

How can you find the correct header file?

Why do you think Tim Berners-Lee invented going online?

A reference site on the Internet such as: http://www.cplusplus.com

is a great help.

Page 53: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Input • Sometimes the programmer does not know what should be

stored in a variable – but the user does.

• The programmer must get the input value from the user

Users need to be prompted

(how else would they know they need to type something?

Prompts are done in output statements

The keyboard needs to be read from

This is done with an input statement

cout << "Enter the number of bottles: ";

cin >> bottles // bottles should be already declared

Page 54: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Input

• Note: bottles doesn’t need to be initialized

Page 55: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Input • You can read more than one value in a single input statement:

cout <<"Please enter the number of bottles and cans:";

cin >> bottles >> cans;

• The user can supply both inputs on the same line:

Please enter the number of bottles and cans: 2 6

• Alternatively, the user can press the Enter key after each input:

Please enter the number of bottles and cans: 2

6

Page 56: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Formatted Output

• When you print the result of a computation, you often

want some control over its appearance.

• For example, when you print an amount you usually want

it to be rounded to two significant digits. That is, you want

the output to look like:

Price per ounce: 0.04

instead of

Price per ounce: 0.0409722

Page 57: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Formatted Output

• The following command instructs cout to use two digits

after the decimal point for all floating-point numbers:

cout << fixed << setprecision(2);

• This command does not produce any output

• it just manipulates cout to change the output format.

• The values fixed and setprecision are called manipulators.

• To use manipulators, you must include the <iomanip>

header in your program: #include <iomanip>

Page 58: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Formatted Output • You can combine the manipulators and the values to be displayed into

a single statement.

cout << fixed << setprecision(2)<< "Price per ounce:

" << price_per_ounce << endl;

• When you display several rows of data, you usually want the columns

to line up. If you want columns of certain widths, use the setw

manipulator

• You use the setw manipulator to set the width of the next output

field. cout<< setw(8)<< volume;

• The width is the total number of characters used for showing the

value, including digits, the decimal point, and spaces.

Page 59: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Formatted Output Example:

price_per_ounce_1 = 10.2372;

price_per_ounce_2 = 117.2;

price_per_ounce_3 = 6.9923435;

cout << setprecision(2);

cout << setw(8) << price_per_ounce_1;

cout << setw(8) << price_per_ounce_2;

cout << setw(8) << price_per_ounce_3;

cout << "--------" << endl;

produces this output:

10.24

117.20

6.99

--------

Page 60: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Formatted Output

There is a notable difference between the

setprecision and setw manipulators.

Once you set the precision, that width is used for all

floating-point numbers until the next time you set the

precision.

But setw affects only the next value.

Subsequent values are formatted without added spaces

Page 61: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String

• Many programs process text, not numbers.

• Text consists of characters: letters, numbers,

punctuation, spaces, and so on.

• A string is a sequence of characters.

• For example, the string "Harry" is asequence of five

characters.

Page 62: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String

• You can define variables that hold strings.

string name = "Harry";

• The string type is a part of the C++ standard. To use it,

simply include the header file,<string>:

#include <string>

using namespace std;

Page 63: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String

• Unlike number variables, string variables are guaranteed

to be initialized even if you do not supply an initial value.

• By default, a string variable is set to an empty string: a

string containing no characters "".

• The definition:

string response;

has the same effect as

string response = "";

Page 64: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Concatenation • Given two strings, such as "Harry" and "Morgan", you can

concatenate them to one long string.

• The result consists of all characters in the first string, followed by all

characters in the second string.

• Example:

string fname = "Harry";

string lname = "Morgan";

string name = fname + lname;

results in the string "HarryMorgan“

name = fname + " " + lname;

results in the string "Harry Morgan“

Page 65: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Common Error – Concatenation of literal strings

string greeting = "Hello, " + " World!";

// will not compile

Literal strings cannot be concatenated.

C++ for Everyone by Cay Horstmann

Copyright © 2012 by John Wiley & Sons. All rights reserved

Page 66: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Input • You can read a string from the console:

cout << "Please enter your name: ";

string name;

cin >> name;

When a string is read with the >> operator,

only one word is placed into the string variable.

For example, suppose the user types

Harry Morgan

This input consists of two words.

Only the string "Harry" is placed into the variable name.

Page 67: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Input

You can use another input to read the second word.

cout << "Please enter your name: ";

string fname, lname;

cin >> fname >> lname;

gets Harry

gets Morgan

Page 68: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Functions • The number of characters in a string is called the length of the

string. For example, the length of "Harry" is 5.

• You can compute the length of a string with the length function.

• Unlike the sqrt or pow function, the length function is invoked

with the dot notation.

int n = name.length();

• Many C++ functions require you to use this dot notation, and

you must memorize (or look up) which do and which don’t.

These functions are called member functions.

Page 69: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Functions

• Once you have a string, you can extract substrings by

using the substr member function.

s.substr(start, length)

returns a string that is made from the characters in the

string s, starting at character start, and containing

length characters. (start and length are integer

values).

Page 70: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Functions

Example:

string greeting = "Hello, World!";

string sub = greeting.substr(0, 5);

// sub contains "Hello“

Page 71: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Functions

• The first position in a string is labeled 0, the second one 1, and

so on. And don’t forget to count the space character after the

comma—but the quotation marks are not

• The position number of the last character is always one less

than the length of the string.

The ! is at position 12 in "Hello, World!".

The length of "Hello, World!" is 13.

Page 72: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Functions

If you do not specify how many characters to take, you get all the

rest.

string greeting = "Hello, World!";

string w = greeting.substr(7);

// w contains "World!"

To have the last three characters in a string you can use:

string w = greeting.substr(greeting.length()-3);

// w contains "ld!"

Page 73: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Functions

string greeting = "Hello, World!";

string w = greeting.substr();

// w contains "Hello World!"

• If you omit the starting position and the length, you get all the

characters.

(not much of substring!)

Page 74: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Operations

Page 75: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

String Operations

Page 76: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Example • Write a simple program that asks the user to enter his name

and the name of his significant other. It then prints out their

initials.

Sample: if the user enter Amal and Heba the output will be

A&H

Solution:

• The operation first.substr(0, 1) makes a string consisting of one

character, taken from the start of first.

• The program does the same for the second.

• Then it concatenates the resulting one-character strings with the string

literal "&" to get a string of length 3.

Page 77: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

Example Continue…..

Page 78: C++ PROGRAMMINGsite.iugaza.edu.ps/rsalamah/files/2010/02/lecture2.pdf · 2014-09-29 · Data Types •In C++, there are several different types of numbers. •You use the integer

End Chapter Two