34
©2017 Gilbert Ndjatou Page 25 Chapter 2 Basic Elements of C++ Programming Language In this chapter, we discuss the formal specifications of the following basic elements of the C++ programming language: identifiers, variables and the C++ basic data types, C++ constant data, the assignment statement, arithmetic expressions, output and formatted output with the cout object, input with the cin object, and naming constants. We also discuss arithmetic and random number generator library functions. 2.1 Identifiers An identifier is a name that you give to a C/C++ object such as a variable or a function. The rules for writing valid identifiers follow: 1. An identifier must begin with a letter of the alphabet (a to z or A to Z), or the underscore character _ 2. After the first character, an identifier may include a letter of the alphabet, a digit (0 to 9), or the underscore character _ . 3. There is no limit on the number of characters that an identifier may have. But, most compilers only recognize the first 31 characters as significant. Valid identifiers: a) letter_l b) username c) _sysflag d) C3PO e) Rate f) A_Big_number g) x5 Invalid identifiers: a) sum$value - contains an illegal character, ( $ ) b) 3spencer - does not begin with a letter or the underscore c) two-by-two - contains an illegal character, ( - ) d) piece flag - contains a blank character C/C++ is case-sensitive: Sum, sum, and SUM are all distinct identifiers.

Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 25

Chapter 2

Basic Elements of C++ Programming Language

In this chapter, we discuss the formal specifications of the following basic elements of the C++

programming language: identifiers, variables and the C++ basic data types, C++ constant data, the

assignment statement, arithmetic expressions, output and formatted output with the cout object, input with

the cin object, and naming constants. We also discuss arithmetic and random number generator library

functions.

2.1 Identifiers

An identifier is a name that you give to a C/C++ object such as a variable or a function.

The rules for writing valid identifiers follow:

1. An identifier must begin with a letter of the alphabet (a to z or A to Z), or the underscore character _

2. After the first character, an identifier may include a letter of the alphabet, a digit (0 to 9), or the

underscore character _ .

3. There is no limit on the number of characters that an identifier may have. But, most compilers only

recognize the first 31 characters as significant.

Valid identifiers:

a) letter_l

b) username

c) _sysflag

d) C3PO

e) Rate

f) A_Big_number

g) x5

Invalid identifiers:

a) sum$value - contains an illegal character, ( $ )

b) 3spencer - does not begin with a letter or the underscore

c) two-by-two - contains an illegal character, ( - )

d) piece flag - contains a blank character

C/C++ is case-sensitive: Sum, sum, and SUM are all distinct identifiers.

Page 2: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 26

By convention, if an identifier consists of two or more words you may do one of the following:

o Separate the words with the underscore characters.

Examples: interest_rate sum_of_dice

o Concatenate all the words and capitalize the first character of each word except the first.

Examples: interestRate sumOfDice

Keywords

A keyword is a word that already has a meaning for the compiler.

You must not use a keyword as an identifier.

Examples of keywords are auto, do, while, int, float, long, and const.

C++ keywords are provided in Appendix 1.

Standard identifiers

A standard identifier is a word that is used to name an object that comes with the compiler.

Examples: scanf and printf

You may use a standard identifier as an identifier only if you do not want to use the object with that

name that comes with the compiler.

Exercise 2.1

Indicate whether each of the following words is an invalid identifier and also provide your justifications.

a) income

f) c3po

b) 8times

g) income#1

c) int

h) item_5

d) tom’s3

i) char

e) two fold

j) _pf99

Page 3: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 27

2.2 Variables and Basic Data Types

In chapter 1, you were told that a variable is used to represent a memory location in a C++ program.

You were also told that you must first define a variable before you can use it to hold values.

You define a variable by using a declaration statement as follows:

<data-type> <variable-name>;

Where <data-type> is the data type of the variable being defined and <variable-name> is an

identifier.

The data type of a variable specifies to the compiler the type of data that will be stored in the

corresponding memory location.

The size of the memory location reserved for a variable and the range of values that it can hold

depend on its data type and on the computer being used.

You can use the following basic data types in your C++ programs.

Basis Data Types

Data Types Type of Data

char single character

int positive and negative whole numbers (integers)

float single precision floating point numbers

double double precision floating point numbers

bool true and false

Data type Size on IBM PC Range of Values

char 1 byte

int 4 bytes -2,147,483,648 to 2,147,483,647

float 4 bytes 1.18x10-38 to 3.4x1038

double 8 bytes 2.2x10-308 to 1.8x10308

Page 4: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 28

Processing the definition of Variables

Variable Definition Representation in Memory (in bytes)

char letter; letter

int num1; num1

float fnum; fnum

double dnum; dnum

Two or more variables with the same data type can be defined in the same declaration statement: for

example, integer variables num, number, and sum can be defined as follows:

int num, number, sum;

It is a good programming practice to follow each variable definition with a comment in order to remind

yourself and anybody else reading your program the purpose of that variable as follows:

int num, // to hold the first value

number, // to hold the second value

sum; // to hold their sum

Exercise 2.2

1. Draw boxes to illustrate the processing of each of the following definition of variables on an IBM PC

and compatible computers.

a. char grade; b. int idnum; c. float score; d. double dscore;

2. Rewrite the definitions of the following variables using only four declaration statements.

char letter;

int num1;

double score;

char grade;

int IdNum;

float fnum;

char initial;

double PayRate;

Page 5: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 29

2.3 Constants and Data Representation

The data to be processed by a C/C++ program are either

specified in the text of the program, or

read (or input) from the keyboard or a file.

The data specified in the text of a program are referred to as constant data.

There are five types of constant data in C++:

character constants,

integer constants,

floating-point constants,

strings constants, and

Boolean constants: true and false.

Character Constant

a character constant is either

a single printable character enclosed between single quotes, or

an escape sequence enclosed between single quotes.

Examples of printable characters: 'A', '$', '8', ‘ ’ (space bar), 'z'.

Examples of escape sequences: '\n', '\t', '\'', '\\', ‘\”’, '\?'.

Escape sequences are used to represent characters that you can not type from the keyboard or characters

that have a meaning for the compiler such as a single quote or a double quote.

Three major codes are used to represent characters inside computers:

the ASCII (American Standard Code for Information Interchange) code (8 bits)

the EBCDIC (Extended Binary Coded Decimal Interchange Code) code (8 bits)

the unicode (16 bits)

The ASCII code is provided in Appendix 2 and the most commonly used escape sequences with their

ASCII codes are provided as follows:

Page 6: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 30

Commonly used Escape Sequences

Sequence Character ASCII Code What it does

\a BEL 0000 0111 Audible bell

\b BS 0000 1000 Backspace

\f FF 0000 1100 Formfeed

\n LF 0000 1010 Newline (linefeed)

\r CR 0000 1101 Carriage return

\t HT 0000 1001 Tab (horizontal)

\\ \ 0101 1100 Backslash

\' ' 0010 1100 Single quote (apostrophe)

\" " 0010 0010 Double quote

\? ? 0011 1111 Question mark

\0 0000 0000 Null character

\% % 0010 0101 percent sign

The following are the ASCII codes of some printable characters.

ASCII Codes of some Printable Characters

Character Code Character Code

A 0100 0001 0 0011 0000

B 0100 0010 1 0011 0001

K 0100 1011 6 0011 0110

. 0010 1110 9 0011 1001

a 0110 0001 space 0010 0000

+ 0010 1011 # 0010 0011

$ 0010 0100 ! 0010 0001

Integer Constants

An integer constant is a positive or negative whole number.

A positive integer constant may be preceded with a plus ( + ) sign.

Commas, decimal point and special symbols such as the dollar sign are not allowed in an integer

constant.

Examples of valid decimal integer constants are 0, -5, 643, -72, and +23.

A leading zero such as in 024 is not allowed in a decimal integer constant.

Page 7: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 31

Floating-point constants

A floating-point constant may be written either in

decimal notation or

exponential notation.

Decimal Notation: <decimal integer>.<decimal fraction>

Exponential Notation:

<decimal integer>.<decimal fraction>E<decimal integer>

or

<decimal integer>.<decimal fraction>e<decimal integer>

The <decimal integer> part, or the <decimal fraction> part, may be omitted, but not both.

The letter e or E in the exponential notation stands for 10 and the number following it is a signed integer

that represents the exponent of the number.

The period and the <decimal fraction> part may also be omitted in the exponential notation.

Examples of Valid Floating-Point Constants

Constant Value

0.42 0.42

.5 0.5

38. 38.0

+14.984 14.984

-6.2 -6.2

0. 0

.0 0

23.45e6 23.45 x 106

2E-5 2.0 x 10-5

-3.45E8 -3.45 x 108

.45E+12 0.45 x 1012

Precision

A Floating-point value is represented inside a computer by a binary approximation of its actual value.

The precision of a representation is the number of meaningful digits (including digits in front of the

decimal point) in that representation.

The precision of the single precision representation is 7 decimal digits, and that of the double precision

representation is 15.

Page 8: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 32

String constant

A string constant is a sequence of zero or more characters (including escape sequences) enclosed

between double quotes.

String constants form a special class of constants because they do not correspond to a C++ data type.

Inside the computer, the characters of a string constant are represented in consecutive bytes with a null

(\0) terminating character.

Examples of String Constants

String Constants Length Representation in Memory

"A" 1

A

\0

"5g" 2

5

g

\0

"" 0

\0

"\nJo\'s mug" 9

\n

J

o

\’

s

m

u

g

\0

The length of a string constant is the number of characters that it contains.

The Null string is the string with no character. Its length is zero.

Exercise 2.3

Which of the following values are illegal C++ language constants? Justify your answers.

15 .6E+2

1,250

-4 e 5

25

12. 47

- 34

1.75

$30

- 2.36

‘A’

3.

‘\n’

- .47

‘7’

0.75

Page 9: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 33

‘\0’

3.5E-4

Z

0.25

‘@’

“10 / 5”

‘,’

“ “

“W”

“num + 5”

‘AB’

“\nResult:\t”

‘%’

“Jo’s tape”

2.4 Assignment Statement

An assignment statement is used to store a value into a memory location.

Its syntax is: <variable-name> = <value>;

Where <value> is the value to be stored into the memory location created for variable <variable-name>.

Examples

Assignment Statements Representations in Memory

letter = 'A'; letter

A

num1 = 25; num1

25

fnum = 4.25; fnum

4.250000

dnum = 4.25; dnum

4.25000000000000

num1 = 10; num1

10

When you store a new value into a memory location, the new value replaces the old one.

Page 10: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 34

Initial value

The initial value of a variable is the value that you specify when that variable is defined as follows:

<data-type> <variable-name> = <initial-value>;

Examples

Variable Definitions Representations in Memory

char letter = 'A'; letter

A

int num1 = 25; num1

25

float fnum = 4.25; fnum

4.250000

double dnum = 4.25; dnum

4.25000000000000

The statement: int num1 = 25;

says the same thing as the following sequence of two statements:

int num1;

num1 = 25;

Initial values may also be specified in a declaration statement in which two or more variables are defined

as follows:

a) int num1 = 25,

num2,

sum = 0;

b) char letter , grade = 'A';

Page 11: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 35

Exercise 2.4

1. Show the output after the execution of each of the following sequences of statements:

a) int n = 2 , m = 5, p; b) int j = 5, k = 7 , l;

m = m + n; l = k + j;

p = m + n ; k = l + 2;

cout << p; cout << k;

Output: ________________ Output:___________________

2. Rewrite the following statements using only three declaration statements (with or without initial values):

int num1;

char letter;

double dnum1;

int num2;

char grade;

double dnum2

num1 = 45;

letter = ‘P’;

dnum2 = -12.64;

grade = ‘B’;

Page 12: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 36

2.5 Arithmetic Expressions

C++ arithmetic operations are defined in the following table.

Operation

Operator

Example

Operand

Result

Addition

+

A + B

Both integers

-------------------

One operand is not

integer

Integer

------------------

Double precision

floating-point Subtraction

-

A – B

Both integers

------------------------------

One operand is not

integer

Integer

-------------------------

Double precision

floating-point Multiplication

*

A * B

Both integers

------------------------------

One operand is not

integer

Integer

-------------------------

Double precision

floating-point Division

/

A / B

Both integers

------------------------------

One operand is not

integer

Integer

-------------------------

Double precision

floating-point Modulus

(Remainder)

%

A % B

Both integers

Integer

Negation

-

-A

integer

------------------------------

is not integer

integer

-------------------------

double precision

floating-point

Page 13: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 37

Evaluating Simple Arithmetic Expressions

Arithmetic expression Result

12 + 9 21

18 - 13 5

14.78 + 3.51 18.29

12.50 * 4 50.00

15 / 2 7

15 % 2 1

15. / 2 7.50

8 / 3.0 2.666....

Rules for Writing Valid Arithmetic Expressions

A basic element is one of the following:

An integer or a floating-point constant. For example 24, -2.57, and 17.3.

A single variable. For example num1, and fnum.

An arithmetic expression enclosed in parentheses.

For example (num + 5), (fnum * 3), and ((fnum1 - fnum2) * (num / 6)).

An arithmetic expression is one of the following:

A basic element

A basic element proceeded by the minus sign (-).

For examples:

o – num

o - 2

o - (num / 5)

Two or more basic elements separated by single arithmetic operators.

For examples:

o num1 + 2 - num2

o num1 + num2 * 5 - 6

o (num1 + 3) * ( num2 + (num1 % 5) - 24) + 10

Page 14: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 38

Rules for Evaluating Arithmetic Expressions

1. First evaluate all sub-expressions in parentheses from left to right, starting with the inner most

parentheses.

2. Then, evaluate unary operations from right to left.

3. Then, evaluate multiplication, division and modulus operations from left to right.

4. And finally, evaluate addition and subtraction operations from left to right.

Evaluation of Arithmetic Expressions

a. 3 + 11 * 2 - 5

step 1: 11 * 2 = 22

step 2: 3 + 22 = 25

step 3: 25 - 5 = 20

b. 81 - 4 * 13 / 2 * 3

step 1: 4 * 13 = 52

step 2: 52 / 2 = 26

step 3: 26 * 3 = 78

step 4: 81 - 78 = 3

c. 25.3 + 13 / 2 - 4

step1: 13 / 2 = 6

step 2: 25.3 + 6 = 31.3

Step 3: 31.3 - 4 = 27.3

d. 34 - ((21 + 6) / 3 - (37 % 5 + 4) + 7)

step 1: 21 + 6 = 27

step 2: 37 % 5 = 2

step 3: 2 + 4 = 6

step 4: 27 / 3 = 9

step 5: 9 - 6 = 3

step 6: 3 + 7 = 10

step 7: 34 - 10 = 24

Page 15: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 39

e. 25 + 13.0 / 2 - 4

step 1: 13.0 /2 = 6.5

Step 2: 25 + 6.5 = 31.5

Step 3: 31.5 - 4 = 27.5

Exercise 2.5

List the operations performed at each step in the evaluation of each of the following arithmetic expressions:

a. 24 - 10 – 5 b. 3 * 10 / 2 – 4 c. 34/5/3 d. 24 * 3 / 5 % 4 e. 2.5 + 13 / 4 - 2.5

f. 5 + 23 / 2.0 – 6 g. 4 * 5/ 3 + 5 + 12 / 5 * 2.5 h. 35 - (3 * ( 25 / 2 - 5) + 4)

i. (4 * 5 / ( 2 * 5)) + 3 + 4 * 5 / 2

Arithmetic Expressions and the Assignment Statement

you may specify an arithmetic expression in an assignment statement as follows:

<variable-name> = <arithmetic-expression>;

The arithmetic expression is first evaluated and its value is stored in the corresponding memory location.

Tracing the Execution of Assignment Statements

Statements Memory Locations

num1 num2 num3

1) int num1 = 5 , num2 , num3; 5 ? ?

2) num2 = - num1; 5 -5 ?

3) num3 = num1 * 6; 5 -5 30

4) num1 = num3 + num2; 25 -5 30

5) num3 = num3 - 12; 25 -5 18

6) num2 = num1 - num3; 25 7 18

7) num2 = num2 + 1; 25 8 18

Page 16: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 40

Exercise 2.6

Trace the execution of the following statements:

1) int num1 = 10, num2, num3 = 9;

2) num2 = num1 * num3;

3) num1 = num1 + 5;

4) num3 = num3 / 2;

5) num2 = num1 * num3;

6) num1 = num1 + num2 - num3;

Operations on Character Values

You can add or subtract an integer value from the ASCII code of a character in order to get the ASCII

code of another character.

The result of subtracting the ASCII code of a character from that of another character is an integer value.

Assuming that variables ch1, ch2, ch3, and num are defined as follows:

char ch1 = ‘P’, ch2, ch3;

int num;

The execution of the following statements will have the specified effects:

a) ch2 = ch1 + 2; // the new value in Ch2 is the character ‘R’

b) ch3 = ch1 - 3; // the new value in ch3 is the character ‘M’

c) num = ‘E’ - ‘A’; // the new value in num is the integer value 4

Exercise 2.7

Assuming that variables ch1, ch2, ch3, and num are defined as follows:

char ch1 = ‘G’, ch2, ch3;

int num;

Specify the effect(s) of the execution of each of the following statements:

a. ch2 = ch1 +10; ch2 d. ch2 = 85; ch2

b. ch3 = ch1 - 4; ch3 e. num = ‘9’ – ‘2’; num

c. ch1 = ch1 + 32; ch1

Page 17: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 41

2.6 Stream Output with cout Object

Output to the monitor may be performed by using the output stream object cout.

Its declaration statement is provided in the header file iostream.

You must therefore include this file in any source file in which you perform output using the stream

object cout.

Examples of cout Statements with String Constants

a) cout << "Hello World!";

Output |Hello World!_

b) cout << "\nEnter a number:\t";

Output |Enter a number: _

c) cout << "\n\nJohn\'s tape\n";

Output |

|John's tape

|_

d) cout << “\nI love” << “candies”;

Output |I lovecandies

e) cout << “\nI love”;

cout << “candies”;

Output |I lovecandies

f) cout << “\nI love” << “\ncandies”;

Output |I love

|candies

g) cout << "\nDid you have fun\?\n Bye bye";

Output |Did you have fun?

|Bye bye_

cout Statements with Arithmetic Expressions

When the name of a variable appears in a string constant in a cout statement, it is not replaced by its

value in the output stream.

Arithmetic expressions that you specify in a cout statement are replaced with their values in the output

stream.

Page 18: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 42

In order to prevent operator precedence conflicts between the operators in an expression and the stream

insertion operator <<, expressions are usually enclosed in parentheses.

Examples

Assume that the variables are defined and initialized as follows:

int inum = 125;

char ch = 'Z';

float fnum = 42.75;

double dnum = 347.874;

Each of the following cout statements will produce the specified output.

a) cout << "\nThe value in inum is:\t" << inum;

Output |The value in inum is: 125_

b) cout << "\nI have chosen the value:\t” << 47

<< “ and the value of ch is:\t" << ch;

Output |I have chosen the value: 47 and the value of ch is: Z_

c) cout << "\nThe value of fnum is:\t” << fnum

<< “\n and that of dnum is:\t" << dnum;

Output |The value of fnum is: 42.75

|and that of dnum is: 347.874_

d) cout << "\n12 + 23 =\t" << (12 + 23); Output |12 + 23 = 35_

e) cout << “\ninum - 25 =\t” << (inum - 25); Output |inum - 25 = 100_

f) cout << inum << ch << “ ” << fnum; Output |125Z 42.75_

Page 19: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 43

Exercise 2.8.

Assuming that the variables are defined and initialized as follows:

char letter = ‘Z’;

int num = 15;

float fnum = 7.24;

double dnum = 3.25;

1. Show the output produced by the following statements. Use the underscore ( _ ) character to indicate the cursor

position, and the vertical bar ( | ) character to indicate the left edge of the screen.

a. cout << endl << “Programming is cool\nand I want to be good at it”;

b. cout << “\nHello!” << “Dear friend\n\n” << “Have a nice day!”;

c. cout << “\nThe value in num is:\t" << num;

d. cout << endl << "\n letter =\t" << letter

<< endl << “fnum + 5=\t” << (fnum + 5)

<< “and the value of dnum is:\t” << dnum;

e. cout << endl << “num \% 7 =\t” << (num % 7)

<< “\nand 15 + 4 is:\t” << (15 + 4);

2.a. Write one cout statement that will produce the following output:

|Good Job

|have a nice day

b. Write one cout statement that will produce the following output:

|num + 10 = <the value of the expression num + 10>

|and letter is: <the value of variable letter>

c. write four cout statements that will produce the following output in which 42 is an integer constant, ‘P’ is a

character constant, and 7.50 is a double precision floating-point constant:

I like the C language

Mr. Green is 42 year old

Mr. Brown’s initial is P

John’s pay rate is: $17.50

Formatted Output

Manipulators setw(n) and setprecision(n) defined in the header file iomanip are provided for output

formatting.

You must therefore include this header file in your program before you can use these manipulators:

#include <iomanip>

Page 20: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 44

Manipulator setw(n) sets to n the (minimum) field width of the next output value. If n is greater than

the number of characters in the output value, spaces are added by default to the left of the value.

Manipulator setprecision(n) sets to n the number of digits to be displayed after the decimal point for all

floating-point values to be output (in the fixed-point format): After the appearance of the manipulator

setprecision(n) , all floating-point values are output with n digits after the decimal point until another

setprecision( ) with a different value appears in the program.

Using setw(n) and setprecision(n) Manipulators

The following cout statements will produce the specified output in which the character b/ represents a single space.

1. cout << endl << “Start” << setw(4) << 10

<< endl << setw(4) << 20 << endl << setw(6) << 30;

Output

|Startb/b/10

|b/b/20

|b/b/b/b/30

2. cout << setw(10) << “\n LIST OF PRICES\n”

<< setw(15) << “ITEM” << setw(15) << “PRICE”;

Output |LIST OF PRICES

|b/b/b/b/b/b/b/b/b/b/b/ ITEMb/b/b/b/b/b/b/b/b/b/PRICE

3. cout << setprecision(2) << 10.341 << endl << 20.16545;

Output |10.34

|20.17

4. cout << setprecision( 2 );

cout << 10.341;

cout << 20.16545;

Output |10.34

|20.17

Note that unlike the setw( ) manipulator, the effect of a setprecision( ) manipulator remains until it is

changed to some other value by another setprecision( ) manipulator.

Page 21: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 45

The fixed Manipulator

Floating-point values are printed either in fixed-point notation (or decimal) or in scientific notation.

The stream manipulator fixed forces cout to print floating-point values in fixed-point notation.

When the fixed manipulator is used in a cout statement, all floating values that are subsequently printed

will be displayed in fixed-point notation.

Examples:

1. cout << setprecision(2) << fixed << 10.341 << endl << 20.16545;

Output |10.34

|20.17

2. cout << setprecision( 2 ) << fixed;

cout << 10.341;

cout << 20.16545;

Output |10.34

|20.17

The showpoint Manipulator

By default, floating-point values are not printed with trailing zeroes, and floating-point values that do not

have a fractional part are not displayed with a decimal point.

Example:

cout << setprecision(2) << fixed << 10.3 << endl << 25.0;

Output |10.3

|25

When the showpoint manipulator is used in a cout statement, all floating values that are subsequently

printed will be displayed with padded zeroes (if necessary).

Examples:

cout << setprecision(3) << fixed << showpoint << 10.3 << endl << 25.0 ;

Output |10.300

|25.000

Page 22: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 46

The left and right Manipulators

When the setw( ) manipulator is used in a cout statement to specify the number of spaces to use for an

output value, that output value is right justified (aligned to the right): that means that any extra spaces

are added to the left of the output value.

When the left manipulator is used in a cout statement, all values that are subsequently printed will be left

justified (aligned to the left): any extra spaces will be added to the right of the output value.

The right manipulator causes subsequent output to be right justified (aligned to the right) as in the

default case.

Examples:

1.

cout << setprecision(2) << fixed << showpoint;

cout << endl << “Start” << setw(4) << 10

<< endl << setw(4) << 20 << endl << setw(6) << 30

<< endl << setw(7) << 10.3 << endl << setw(8) << 25.0;

Output

|Startb/b/10

|b/b/20

|b/b/b/b/30

|b/b/10.30

|b/b/b/25.00

2.

cout << setprecision(2) << fixed << showpoint << left;

cout << endl << “Start” << setw(4) << 10

<< endl << setw(4) << 20 << endl << setw(6) << 30

<< endl << setw(7) << 10.3 << endl << setw(8) << 25.0;

Output

|Start10b/b/

|20b/b/

|30b/b/b/b/

|10.30b/b/

|25.00b/b/b/

Exercise 2.9

Assuming that variables ch, num, and dnum are defined and initialized as follows:

char ch = ‘P’;

int num = 5306;

double dnum = 12.5;

1. What is the output produced by each of the following statements:

Page 23: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 47

a. cout << endl << setw(10) << “START” << “Hello!”;

b. cout << endl << setw(2) << “Name:” << setw(10) << “John Doe”

c. cout << endl << setw(4) << ch << endl << setw(3) << num;

d. cout << setprecision(2) << fixed

<< endl << setw(6) << dnum << endl << setw(4) << 15.0;

e. cout << setprecision (3) << fixed << showpoint

<< endl << “num =” << setw(8) << num

<< endl << “dnum =” << setw(8) << dnum

<< endl << “dnum + 0.2324 =” << setw(8) << (dnum + 0.2324)

<< endl << “dnum + 0.2327 =” << setw(8) << (dnum + 0.2327)

<< endl << “dnum + 0.5 =” << setw(8) << (dnum + 0.5);

f. cout << setprecision(2) << fixed << showpoint << left;

cout << endl << “Hello!” << setw(4) << 15

<< endl << setw(8) << “score:” << endl << setw(6) << 30

<< endl << setw(7) << 10.3 << endl << setw(8) << 25.0;

cout << setw (10) << “TEST” << setw(10) << “SCORE”;

2. Write a cout statement that will produce each of the following output:

a. |b/b/b/b/b/b/b/b/ ITEMb/b/b/PRICE

b. |num + 3=b/b/b/b/b/15 (Note: 15 is the value of the expression: num + 3)

c. |dnum=b/b/b/234.50 (Note: 234.5 is the value of variable dnum)

d. |Doe, b/ Johnb/b/b/b/b/

e. |NAMEb/b/b/b/b/ IDb/b/b/b/b/PRICE

2.7 Stream Input with cin Object

Input from the keyboard may be performed by using the input stream object cin.

Its declaration statement is provided in the header file iostream.

You must therefore include this file in any source file in which you perform input using the object cin.

The syntax of the cin statement is:

cin >> <variable-name1> >> <variable-name2> >> . . . ;

Using Stream Object cin to input Values from the Keyboard

Assuming that the variables are defined as follows:

char ch1 , ch2;

int inum1 , inum2;

float fnum;

double dnum1 , dnum2;

Page 24: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 48

123

123.45 00

123.450000000000

123

45

6.75000000000000

12

6

3.4E5

For each of the following cin statements, we show the status of the input stream before values are extracted

from it, and the contents of the memory location(s) where the input value(s) extracted from the input stream

are stored.

a) cin >> ch1;

Input |b/b/K

Memory ch1 K

b) cin>>num1;

Input |b/b/123

Memory inum1

c) cin >> fnum1;

Input |b/b/123.45

Memory fnum

d) cin >> dnum1;

Input |b/b/123.45

Memory dnum1

e) cin >> inum1 >> inum2 >> dnum1;

Input |b/b/123 b/b/45b/6.75

Memory inum1

inum2

dnum1

f) cin >> inum1 >> ch1 >> fnum;

cin >> inum2;

Input |b/12A3.4E5b/6B78

Memory inum1

inum2

fnum

ch1

Input Stream After the extraction of values: B78

A

Page 25: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 49

Exercises 2.10

Assuming that variables num1, num2, letter, and dnum are defined as follows:

char letter;

int num1, num2;

double dnum;

And that the user has typed the following input line: Input |452.25E+5G456.85

a. Show the contents of the memory locations that correspond to these variables after the execution of the

following cin statements:

cin >> num1 >> dnum >> letter; num1 dnum letter

cin >> num2; num2

b. What is the status of the input stream after the execution of the above cin statements?

Input |_______________

Exercises 2.11

Which of the following statements are incorrect? Also describe the error(s).

a) num = num + 1;

b) num = 5

c) num + 5 = num2;

d) cin >> num - 2;

e) cout << num;

f) cout << (num +2) , ‘A’;

g) cout << (num + 5) << “Jo”;

h) cin >> num1, num2;

i) cin >> num1 >> num2;

j) int num1;

k) int num1; num2;

l) char letter, grade;

2.8 Naming Constants

The following program reads the radius of a circular tile and then computes and prints its area and price.

The price of the tile is its unit price times its area. The unit price of the tile is $3.14 per square inch and

we use 3.14 as the value of PI.

The problem with this program is that by just reading it, we do not know what 3.14 represents: in one

expression, it represents the value of PI and in another one it represents the unit price of the tile. Also, if

we would like to change the value of PI to 3.1415, both values may be changed to 3.1415.

Page 26: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 50

These problems may be avoided in C++ by naming these two constants.

You can name a constant in C++ in one of the following two ways:

o By using the #define directive or

o By using a const variable.

Program with two Constants without a name

Line Number

1 /********************************************************************

2 Program to read the radius of a circular tile and to compute its area

3 and price. Its unit price is $3.14 per square inch.

4 ********************************************************************/

5 #include <iostream>

6 #include <iomanip>

7 using namespace std;

8

9 int main()

10 {

11 double radius, // to hold the radius of the tile

12 area; // to hold its area

13

14 /*-------------read the radius of the tile-------------*/

15 cout << “\nEnter the radius of the tile:\t”;

16 cin >> radius;

17

21 /*--------compute and print the area of the tile-------*/

19 area = 3.14 * radius * radius;

20 cout << setprecision(2) << fixed << showpoint;

21 cout << “\n\nThe area of the circle is:\t”

22 << area;

23

24 /*---------compute and print its price---------------*/

25 cout << “\n\nIts price is:\t” << 3.14 * area;

26

37 return 0;

38 }

#define Directive

The #define directive is used to associate a name to a constant as follows:

#define <name> <constant>

After this association is done, <name> can be used in the program in any place where <constant> will

normally be used.

The preprocessor will replace all occurrences of <name> in the program with <constant> before the

program is compiled.

Page 27: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 51

Using Symbolic Constants

Line Number

1 /********************************************************************

2 Program to read the radius of a circular tile and to compute its area

3 and price. Its unit price is $3.14 per square inch.

4 ********************************************************************/

5 #include <iostream>

6 #include <iomanip>

7 using namespace std;

8

9 #define PI 3.14

10 #define UNITPRICE 3.14

11

12 int main()

13 {

14 double radius, // to hold the radius of the tile

15 area; // to hold its area

16

17 /*-------------read the radius of the tile-------------*/

18 cout << “\nEnter the radius of the tile:\t”;

19 cin >> radius;

20

21 /*--------compute and print the area of the tile-------*/

22 area = PI * radius * radius;

23 cout << setprecision(2) << fixed << showpoint;

24 cout << “\n\nThe area of the circle is:\t”

25 << area;

26

27 /*---------compute and print its price---------------*/

28 cout << “\n\nIts price is:\t” << UNITPRICE * area;

29

30 return 0;

31 }

const Variables

A const variable is a variable that is defined and initialized as follows:

const <data-type> <variable-name> = <constant>;

<constant> is the constant value to be named, and

<data-type> is its data type.

The compiler creates a memory location that corresponds to <variable-name>, and initializes it with

that constant value.

The value of a const variable can not be changed in a program: any attempt to change the value of a

const variable will cause the compiler to generate an error message.

Page 28: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 52

Using const Variables

Line Number

1 /********************************************************************

2 Program to read the radius of a circular tile and to compute its area

3 and price. Its unit price is $3.14 per square inch.

4 ********************************************************************/

5 #include <iostream>

6 #include <iomanip>

7 using namespace std;

8

9 int main()

10 {

11 const double PI = 3.14; // the value of PI

12 const double UNITPRICE = 3.14; // the unit price of the tile

13 double radius, // to hold the radius of the tile

14 area; // to hold its area

15

16 /*-------------read the radius of the tile-------------*/

17 cout << “\nEnter the radius of the tile:\t”;

18 cin >> radius;

19

20 /*--------compute and print the area of the tile-------*/

21 area = PI * radius * radius;

22 cout << setprecision(2) << fixed << showpoint;

23 cout << “\n\nThe area of the circle is:\t”

24 << area;

25

26 /*---------compute and print its price---------------*/

27 cout << “\n\nIts price is:\t” << UNITPRICE * area;

28

29 return 0;

30 }

Exercise 2.12

1. Define the following constants as symbolic constants:

a. the pay rate of $15.50

b. the best grade of ‘A’

c. the maximum number of hours of 48

d. the string constant “Excellent student”

2. Define the following constants using const variables:

a. the pay rate of $15.50

b. the best grade of ‘A’

c. the maximum number of hours of 48

3. The content of the header file test.h is given as followed:

Page 29: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 53

/*------------------------------------ test.h -------------------------------- */

double compute( ); // to evaluate the expression

const int FLAG = 0;

double myabsolute(double); // to compute an absolute value

and the content of the file myprog.cpp is given as followed:

/*---------------------------- program file -----------------------------------*/

#include <test.h>

#define MAXVALUE 50 /* the maximum value */

int main ( )

{

int num1 = 15, result1, result2;

const int VALT = 15;

result1 = num1 + MAXVALUE;

result2 = VALT * 4;

cout << (MAXVALUE / 7) << (VALT - 6);

return ( 0 );

}

Show the content of the file myprog.cpp after it has been processed by the preprocessor.

2.9 Arithmetic and Random Number Generator Library

Functions

The following arithmetic and random number generator library functions are available in all C++

implementations.

Library functions abs( ), rand( ), and srand( ) are declared in the header file cstdlib; and the other

functions are declared in the header file cmath.

Note that if a function is declared in a header file, that header file must be included into any source

module in which that function is called.

Page 30: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 54

Function Declaration Description Example

double abs (double d ); returns the absolute value of d cout << abs( 25);

double sqrt (double d); returns the square root of d cout << sqrt (num + 5);

double pow(double d , int i); returns d to the power of i cout << pow (5.25, 7);

double ceil (double d); returns the smallest integer value not

less than d

cout << ceil(17.24);

double floor (double d); returns the largest integer value not

greater than d

cout << floor(24.21);

double exp (double d); returns the exponent (base e) of d cout << exp(24.2);

double log (double d); returns the (base e) logarithm of d cout << log(5.25);

double log10 (double d); returns the (base 10) logarithm of d cout << log10( 35.4);

int rand( ); returns a pseudo random number

between 0 and RAND_MAX

(predefined integer constant)

double num;

num = rand( );

cout << num / RAND_MAX;

void srand(int s); reinitializes the random number

generator with seed s (positive value)

srand (10);

Example

Write a program to read two floating point values a and b and to compute and print the following

expressions:

a. | a – b |

b. a5 - b3

c. a2 + b4

/*---------------------------- program file -----------------------------------*/

#include <iostream>

#include <iomanip>

#include <cstdlib>

#include <cmath>

using namespace std;

Page 31: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 55

int main ( )

{

int num1, // to hold the first value: a

num2; // to hold the second value: b

double dnum; // to hold the partial result of question c

/*-------------------------- read the values ----------------------------*/

cout << endl << “Enter the first value:\t”;

cin >> num1;

cout << endl << “Enter the second value:\t”;

cin >> num2;

cout << setprecision( 2 ) << fixed << showpoint;

/*----- compute and print the absolute value of the difference of the first minus the second -----*/

cout << endl << “Result of question a is:\t” << abs( num1 – num2);

/*----- compute and print the expression in question b -----*/

cout << endl << “Result of question b is:\t” << pow( num1, 5) – pow( num2, 3);

/*----- compute and print the expression in question c -----*/

dnum = pow( num1, 2 ) + pow( num2, 4);

cout << endl << “Result of question c is:\t” << sqrt( dnum );

return ( 0 );

}

Exercise 2.13

1. Write the sequence of statements to read two floating point values into the variables num1 and num2 and

to compute and print the expression:

num14 - num23

2. Write the sequence of statements to read two floating point values into the variables num1 and num2 and

to compute and print the expression: (num1 - num2) 3

3. Write the sequence of statements to read two floating point values into the variables num1 and num2 and

to compute and print the expression:

num1 + num2

4. Write the sequence of statements to read floating point values a, b, and c into variables num1, num2, and

num3 respectively, and to compute and print the expression:

a + b4 + 3ac

| b2 - 2c |

Page 32: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 56

2.10 Class string

The C++ programming language does not have a basic data type to store and manipulate character

strings. However, the string class may be used to store and process character strings in a way similar

to a basic data type.

A class is a data type that is defined by a C++ programmer. In order to use the string class, you

must first include the header file string in your program:

#include <string>

You declare string variables in the same way you declare variables of any other data types.

Example:

string firstName,

lastName,

name1,

name2,

day = “Monday”,

address;

You can use an assignment statement to store a character string into a string variable.

Example:

address = “300 Pompton Road, Wayne, NJ 07470”;

You can use a cout statement to output the content of a string variable.

Example:

cout << endl << “Today is:\t” << day;

cout << “\nMy address is:\t” << address;

OUTPUT

Today is: Monday

My address is: 300 Pompton Road, Wayne, NJ 07470

You can use a cin statement to read a word (sequence of characters that does not contain a

whitespace) into a string variable.

Page 33: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 57

123

John

Example:

cin >> name1 >> name2:

Input |b/b/123 b/b/ Johnb/Doe

Memory name1

name2

Input Stream after Input: Doe

Note: A whitespace character is a character that you produce when you press the space bar, the

Return key, or the Tab key.

You can combine two character strings into one by using the concatenation operator +.

Example:

string lastName = “Doe”

firstName = “John”

name;

name = “Mr. “ + firstName + “ “ + lastName;

cout << name;

OUTPUT

Mr. John Doe

Exercise 2.14

1. Given the following code segment:

string word1, word2;

cout << endl << “Enter a line of input:\t”;

cin >> word1 >> word2;

cout << word1 << word2 << “ THAT\’s ALL”;

If the dialog begins as follows, what will be the next line of output? __________________________

Enter a line of intput: Have a nice day!

2. Given the following definitions of variables word1, word2, and word3: (4 pts)

string word1 = “Happy”,

word2 = “to you!”,

word3;

Write a statement that uses the concatenation operator + and the contents of the variables word1 and

word2 to assign the following string to the variable word3: Happy birthday to you!

Page 34: Chapter 2 Basic Elements of C++ Programming LanguageThe data to be processed by a C/C++ program are either specified in the text of the program, or read (or input) from the keyboard

©2017 Gilbert Ndjatou Page 58