CHAPTER 2 BASIC ELEMENTS OF C++

36
CHAPTER 2 BASIC ELEMENTS OF C++

description

CHAPTER 2 BASIC ELEMENTS OF C++. In this chapter, you will: Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers Explore simple data types and examine the string data type Discover how to use arithmetic operators - PowerPoint PPT Presentation

Transcript of CHAPTER 2 BASIC ELEMENTS OF C++

Page 1: CHAPTER 2 BASIC ELEMENTS OF C++

CHAPTER 2

BASIC ELEMENTS OF C++

Page 2: CHAPTER 2 BASIC ELEMENTS OF C++

In this chapter, you will: Become familiar with the basic components of a C++

program, including functions, special symbols, and identifiers

Explore simple data types and examine the string data type

Discover how to use arithmetic operators Examine how a program evaluates arithmetic expressions Learn what an assignment statement is and what it does Discover how to input data into memory using input

statements Become familiar with the use of increment and decrement

operators Examine ways to output results using output statements Learn how to use preprocessor directives and why they

are necessary Explore how to properly structure a program, including

using comments to document a program Learn how to write a C++ program

Page 3: CHAPTER 2 BASIC ELEMENTS OF C++

Example 2-1

#include <iostream>

using namespace std;

int main()

{

cout<<"Welcome to C++ Programming"<<endl;

return 0;

}

Output:

Welcome to C++ Programming

Page 4: CHAPTER 2 BASIC ELEMENTS OF C++

The smallest individual unit of a program written in any language is called a token.

Special-Symbols The following are some of the special symbols

+ - * /

. ; ? ,

<= != == >=

Word-symbols

int, float, double, char, void, return

These are called reserved words, or keywords. (p.1033)

Page 5: CHAPTER 2 BASIC ELEMENTS OF C++

IdentifierIdentifier: A C++ identifier consists of letters, digits, and the under score character (_), and must begin with a letter or underscore.

C++ is case sensitive—uppercase and lower case letters are different. Some of the predefined identifiers are cout and cin. Unlike reserved words, pre-defined identifiers may be redefined, but it would not be wise to do so.

•Example 2-2The following are legal identifiers in C++.

First conversion payRate counter1

Page 6: CHAPTER 2 BASIC ELEMENTS OF C++

Integral data types

Page 7: CHAPTER 2 BASIC ELEMENTS OF C++
Page 8: CHAPTER 2 BASIC ELEMENTS OF C++

int Data Type

-6728, -67, 0, 78, 36782, +763,...

• Positive integers do not have to have a + sign in front of them.

• No commas are used within an integer.

• In C++ commas are reserved for separating items in a list. So 36,782 would be interpreted as two integers 36 and 782.

The bool Data Type

• The data type bool has two values, true and false. The central purpose of this data type is to manipulate logical (Boolean) expressions. We call true and false the logical (Boolean) values.

• In C++, bool, true, and false are reserved words.

Page 9: CHAPTER 2 BASIC ELEMENTS OF C++

char Data Type char is the smallest integral data type. char data type is used to represent characters, that is letters, digits

and special symbols. Each character is enclosed within single quote marks. Some of the

values belonging to char data type are:

'A', 'a', '0', '*', '+', '$', '&'

Blank space is a character and is written ' ', with a space left between the single quotes.

Page 10: CHAPTER 2 BASIC ELEMENTS OF C++

ASCII Character Set - p.1037

Each of the 128 values of the ASCII character set represents a different character.

The value 65 represents 'A', and the value 43 represents '+'.

The value representing 'B' is 66, so 'A' is smaller than 'B'.

'+' is smaller than 'A' since 43 is smaller than 65.

The first 32 characters in the ASCII character set are nonprintable. The 14th character in the set is the new line character. In C++, the new line character is represented as '\n'. The horizontal tab character is represented in C++ as '\t'. The null character is represented as '\0'.

Page 11: CHAPTER 2 BASIC ELEMENTS OF C++

Floating-Point Data Types

• Scientific notation

43872918 = 4.3872918 *10^7 {10 to the power of seven},.0000265 = 2.65 * 10^(-5) {10 to the power of minus

five},47.9832 = 4.7983 * 10^1 {10 to the power of one}

• To represent real numbers C++ uses scientific notation called floating-point notation.

Page 12: CHAPTER 2 BASIC ELEMENTS OF C++

float: The data type float is used in C++ to represent any real number between -3.4E+38 and 3.4E+38.The memory allocated for the float data type is 4 bytes.

double: The data type double is used in C++ to represent any real number between -1.7E+308 and 1.7E+308.The memory allocated for the double data type is 8 bytes.

On most newer compilers, the data types double and long double are the same. The maximum number of significant digits—that is, the number of decimal

places—in float values is 6 or 7. The maximum number of significant digits in values belonging to the double

type is 15. The maximum number of significant digits is called the precision. float values are called single precision double values are called double precision. 2

Page 13: CHAPTER 2 BASIC ELEMENTS OF C++

The string Type The data type string is a programmer-defined type and is not part

of the C++ language. The C++ standard library supplies it. A string is a sequence of zero or more characters. Strings in C++ are enclosed in double quote marks. A string with no characters is called a null or empty string.

"William Jacob"“Mickey""”

"" is the empty string. Every character in a string has a relative position in the string. The position of the first character is 0, position of the second

character is 1, and so on. The length of a string is the number of characters in it.

Page 14: CHAPTER 2 BASIC ELEMENTS OF C++

Example 2-3String Position of a Character Length of the String

in the Sting

"William Jacob" Position of 'W' is 0. 13

Position of the first 'i' is 1.

Position of ' '

(the space) is 7.

Position of 'J' is 8.

Position of 'b' is 12.

“Mickey" Position of ‘M' is 0. 6

Position of 'i' is 1.

Position of 'c' is 2.

Position of 'k' is 3.

Position of 'e' is 4.

Position of 'y' is 5.

Page 15: CHAPTER 2 BASIC ELEMENTS OF C++

ARITHMETIC OPERATORS AND OPERATOR PRECEDENCE

• Arithmetic Operators

+ addition

- subtraction

* multiplication

/ division

% remainder (mod operator)

• Arithmetic Expressions3 + 4

2 + 3 * 5

5.6 + 6.2 * 3

x + 2 * 5 + 6 / y

x and y are some unknown numbers

Page 16: CHAPTER 2 BASIC ELEMENTS OF C++

• Unary operator: An operator that has only one operand.

• Binary Operator: An operator that two operands.

In the expression

–5

– has only one operand, which is 5 and so - acts as a unary operator.

In the expression

+27

+ is a unary operator.

Page 17: CHAPTER 2 BASIC ELEMENTS OF C++

Example 2-4

Arithmetic

Expression Result Description

2 + 5 7

45 - 90 -45

2 * 7 14

5/2 2 In the division 5/2, the quotient is

2

34 % 5 4 In the division 34/5, the quotient is 6 and

the remainder is 4.

5.0 + 3.5 8.5

5.0/2.0 2.5

Page 18: CHAPTER 2 BASIC ELEMENTS OF C++

Order of Precedence

The precedence rules of arithmetic operators are:

*, /, %

are at a higher level of precedence than

+ , -

• Operators *, /, and % have the same level of precedence.

• Operators + and - have the same level of precedence.

When operators are all on the same level, they are performed from left to right.

To avoid confusion, the grouping symbol can be used. For example,

Page 19: CHAPTER 2 BASIC ELEMENTS OF C++

EXPRESSIONS• If all operands (that is, numbers) in an expression are integers, the

expression is called an integral expression. • If all operands in an expression are floating-point numbers, the

expression is called a floating-point or decimal expression.

• An integral expression yields an integral result; a floating-point expression yields a floating-point result.

Mixed Expressions• An expression that has operands of different data types is called a

mixed expression.

• A mixed expression contains both integers and floating-point numbers.

Examples of mixed expressions2 + 3.5

6 / 4 + 3.9

5.4 * 2 – 13.6 + 18 / 2

Page 20: CHAPTER 2 BASIC ELEMENTS OF C++

Example 2-9(a) 3 / 2 + 5.0

= 1 + 5.0 (3 / 2 = 1)

= 6.0 (1 + 5.0 = 1.0 + 5.0= 6.0)

(b) 15.6 / 2 + 5

= 7.8 + 5 (15.6 / 2 = 15.6 / 2.0 = 7.8)

= 12.8 (7.8 + 5.0 = 12.8)

(c) 4 * 3 + 7 / 5 – 25.6

= 12 + 7 / 5 – 25.6 (4 * 3 = 12)

= 12 + 1 – 25.6 (7 / 5 = 1)

= 13 – 25.6 (12 + 1 = 13)

= -12.6 (13 – 25.6 = 13.0 – 25.6

= - 12.6)

Page 21: CHAPTER 2 BASIC ELEMENTS OF C++

Implicit Type Coercion Cast operator (type conversion or type casting)

Syntax Cast operator

static_cast<dataTypeName>(expression)

•Expression is evaluated and its value is converted to value of the type specified by the dataTypeName.

Page 22: CHAPTER 2 BASIC ELEMENTS OF C++

Example 2-10static_cast<int>(7.9) = 7

static_cast<double>(25) = 25.0

static_cast<double>(5+3) = static_cast<double>(8)

= 8.0

static_cast<double>(15)/2 = 15.0/2 = 15.0/2.0

= 7.5

static_cast<int>(7.8 + static_cast<double>(15)/2)

= static_cast<int>(7.8 + 7.5)

= static_cast<int>(15.3) = 15

Page 23: CHAPTER 2 BASIC ELEMENTS OF C++

Variable The syntax for declaring one variable or multiple variables is

dataType identifier, identifier, . . .;•Example 2-12int counter;

char ch;

int x, y;

string name;

Named Constant: The syntax to declare a named constant is

const dataType identifier = value;

• In C++, const is a reserved word.•Example 2-11const int noOfStudents = 20;

const char blank = ' ';

const string str = "It is a sunny day. ";

Page 24: CHAPTER 2 BASIC ELEMENTS OF C++

Declaration and Initializing Variables

Variables can be initialized when they are declared

int first, second;char ch;double x, y;

first = 13;second = 10;ch = ' ';x = 12.6;y = 123.456;

Equivalently, we can write the following C++ statements.

int first=13, second=10;char ch=' ';double x=12.6, y=123.456;

Page 25: CHAPTER 2 BASIC ELEMENTS OF C++

Input (Read) Statement

Syntax of cin together with >>:

cin>>variable>>variable. . .;

In C++, >> is called the extraction operator.

Suppose miles is a variable of the type double.

cin>>miles;

By using more than one variable in cin, more than one value can be read at a time.

Suppose feet and inch are variables of the type int. A statement like

cin>>feet>>inch;

Page 26: CHAPTER 2 BASIC ELEMENTS OF C++

INCREMENT AND DECREMENT OPERATORS

Increment operator - increment the value of a variable by 1Decrement operator- decrement the value of a variable by 1.

Pre Increment: ++variablePost Increment: variable++

++count; or count++;increments the value of count by 1.

Pre Decrement: --variablePost Decrement: variable--

--count; or count--;decrements the value of count by 1.

Page 27: CHAPTER 2 BASIC ELEMENTS OF C++

1. x = 5;y = ++x;

• After the second statement both x and y are 6.

2. x = 5;y = x++;

• After the second statement y is 5 and x is 6.

Example 2-16Suppose a and b are int variables.

a = 5; b = 2 + (++a);

After the second statement a is 6 and b is 8.

Page 28: CHAPTER 2 BASIC ELEMENTS OF C++

OUTPUT The syntax of cout together with << is

cout<<expression or manipulator<<expression or manipulator...;

In C++, << is called the insertion operator. expression (that is, expression) is evaluated and its value is

printed at the current cursor position on the screen. manipulator manipulates the output. The simplest manipulator is endl (the last character is the letter el), which causes the cursor to move to the beginning of the next line.

This is called an output statement. Sometimes this is also called a cout statement.

In C++, << is called the stream insertion operator. Strings and expressions involving only one variable or a single

value are evaluated to itself.• \n is called new line escape sequence. • \ (back slash) is called the escape character.

Page 29: CHAPTER 2 BASIC ELEMENTS OF C++

Example 2-18

int a, b, c, d;a = 65 ;b = 78 ;

cout<<29/4<<endl; 7cout<<3.0/2<<endl; 1.5cout<<"Hello there.\n"; Hello there.cout<<"a"<<endl; 65cout<<b<<‘\n’; 78cout << endl;

•The following statement is illegal in C++.

cout<<"It is sunny, warm, and not a windy day. Let us go golfing."<<endl;

Page 30: CHAPTER 2 BASIC ELEMENTS OF C++

cout<<"The newline escape sequence is \\n"<<endl;The new line escape sequence is \n

cout<<"The tab character is represented as \'\\t\'"<<endl;

The tab character is represented as '\t'

cout<<"The string \"Sunny\" contains five characters\n";

The string "Sunny" contains five characters

Page 31: CHAPTER 2 BASIC ELEMENTS OF C++

Preprocessor Directives

Only a small number of operations are explicitly defined in C++. Many of the functions and symbols that are necessary to run a C++

program are provided as a collection of libraries. Every library has a name and is referred as a header file. For

example, the descriptions of the functions needed to perform I/O are contained in the header file iostream.

The descriptions of some very useful mathematics functions such as power, absolute, sine, etc., are contained in the header file cmath.

Preprocessor directives are commands supplied to the preprocessor. All preprocessor commands begin with #. There is no semicolon at the end of these commands since these are

preprocessor commands not C++ commands. #include <cmath>

#include <iostream>

#include <string>

Page 32: CHAPTER 2 BASIC ELEMENTS OF C++
Page 33: CHAPTER 2 BASIC ELEMENTS OF C++

Using cin and cout in a Program and namespace

• One way to use cin and cout in a program is to refer them as std::cin and std::cout.

• Another option is to include the following statement in your program:

using namespace std;

• The using statement appears after the statement

#include <iostream>.

Page 34: CHAPTER 2 BASIC ELEMENTS OF C++

Documentation

Comments• Single line comments

• Single line comments begin with // anywhere in the line.

• Multiple line comments. • Multiple line comments are enclosed between /* and */.

Page 35: CHAPTER 2 BASIC ELEMENTS OF C++

Prompt Lines

cout<<"Please enter a number between 1 and 10 and"

<<" press the return key"<<endl;

cin>>num;

When these two statements execute in the order given, first the cout statement causes the following line of text to appear on the screen:

Please enter a number between 1 and 10 and press the return key

After seeing this line, users know that they must enter a number and press the return key.

Page 36: CHAPTER 2 BASIC ELEMENTS OF C++

Compound assignment operator

op=

where op is any of the arithmetic operators.

• Using the compound assignment operator, the simple assignment statement

variable = variable op (expression);

can be rewritten as

variable op= expression;

and is called the compound assignment statement.

I = I + 5;

I += 5;