Chapter 2 Basic Elements of C++

Download Report

Transcript Chapter 2 Basic Elements of C++

CHAPTER 2
BASIC ELEMENTS OF C++
The Basics of a C++ Program
 A C++ program is a collection of one or more subprograms,
called functions.
 Roughly speaking, a subprogram or a function (like a
program) is a collection of statements and when it is
activated (that is, executed) it accomplishes something.
 Every C++ program has a function called main.
Example 2-1
#include <iostream>
using namespace std;
int main()
{
cout<<"Welcome to C++ Programming"<<endl;
return 0;
}
Output:
Welcome to C++ Programming
 To write meaningful programs, we learn the special symbols,
words, and the syntax rules of the programming language.
 The syntax rules tell us which statements (instructions) are legal,
that is, accepted by the programming language and which are not.
 Programming Language: A set of rules, symbols, and special
words.
 Semantic- The semantic rules determine the meaning of the
instructions.
 Metalanguage- A language used to write the syntax rules.
Syntax template of the function main is:
int main()
{
statement1
.
.
.
statementn
return 0;
}
• In these slides, reddish color indicate a part of the syntax that may or
may not appear.
 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.
Identifier
Identifier: 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-2
The following are legal identifiers in C++.
first
conversion
payRate
counter1
Data Types and Arithmetic Operators
Data Type: A set of values together with a set of operations is called a
data type.
C++ data types fall into three categories
• Simple Data Type.
• Structured Data Type.
• Pointers.
Simple Data Type
C++ simple data can be classified into three categories
1. Integral, which is a data type that deals with integers, or numbers
without a decimal part.
2. Floating-point, which is a data type that deals with decimal numbers.
3. Enumeration type, which is a user-defined data type.
Integral data types
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.
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.
Floating-Point Data Types
• Scientific notation
43872918 = 4.3872918 *10^7
.0000265 = 2.65 * 10^(-5)
five},
47.9832 = 4.7983 * 10^1
{10 to the power of seven},
{10 to the power of minus
{10 to the power of one}
• To represent real numbers C++ uses scientific notation called
floating-point notation.
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 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.
Example 2-3
String
Position of a Character
in the Sting
"William Jacob" Position of 'W' is 0.
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
Position of
Position of
Position of
Position of
Position of
‘M'
'i'
'c'
'k'
'e'
'y'
is
is
is
is
is
is
0.
1.
2.
3.
4.
5.
Length of the String
13
6
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 expressions
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2
Rules to evaluate a mixed expression
1. When evaluating an operator in the mixed expression:
a. If the operator has the same types of operands (that is, either
both integers or both floating-point numbers), the operator is
evaluated according to the type of the operands.
b. If the operator has both types of operands (that is, one is an
integer and the other is a floating-point number) then during
calculation the integer is changed to a floating-point number
with the decimal part of zero and the operator is evaluated.
The result is a floating-point number.
2. The entire expression is evaluated according to the precedence
rules; the multiplication, division, and modulus operators are
evaluated before the addition and subtraction operators.
Operators having the same level of precedence are evaluated
from left to right. Grouping is allowed for clarity.
Example 2-9
(a) 3 / 2 + 5.0
= 1 + 5.0
= 6.0
(3 / 2 = 1)
(1 + 5.0 = 1.0 + 5.0= 6.0)
(b) 15.6 / 2 + 5
= 7.8 + 5
= 12.8
(15.6 / 2 = 15.6 / 2.0 = 7.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)
 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.
Example 2-10
static_cast<int>(7.9) =
7
static_cast<int>(3.3) =
3
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<double>(15/2) = static_cast<double>(7)
= 7.0
static_cast<int>(7.8 + static_cast<double>(15)/2)
= static_cast<int>(7.8 + 7.5)
= static_cast<int>(15.3)
= 15
static_cast<int>(7.8 + static_cast<double>(15/2)
= static_cast<int>(7.8 + 7.0)
= static_cast<int>(14.8)
= 14
x = 15
y = 23
z = 3.75
Expression
Value
static_cast<int>(7.9 + 6.7)
14
static_cast<int>(7.9)
+ static_cast<int>(6.7)
13
static_cast<double>(y / x) + z
4.75
static_cast<double>(y) / x + z
5.28333
INPUT
Storing data in the computer’s memory is a two step process.
• Instruct the computer to allocate memory.
• Include statements in the program to put data into the allocated
memory.
Allocating Memory with Constants and Variables
• Named Constant: A memory location whose content is not allowed
to change during program execution.
• Variable: A memory location whose content may change during
program execution.
Named Constant: The syntax to declare a named constant is
const dataType identifier = value;
• In C++, const is a reserved word.
Example 2-11
const
const
const
const
double conversion = 2.54;
int noOfStudents = 20;
char blank = ' ';
double payRate = 15.75;
Variable
The syntax for declaring one variable or multiple variables is
dataType identifier, identifier, . . .;
Example 2-12
double amountDue;
int
counter;
char
ch;
int
x, y;
string name;
1. In C++, all identifiers must be declared before they can be
used. If we refer to an identifier without declaring it, the
compiler will generate an error message indicating that the
identifier is not declared.
2. A data type is called simple if the variable (or named constant)
of that type can store only one value at a time. For example, if
x is an, say, int variable. Then at a given time only one value
can be stored in x.
Putting Data into Variables
• In C++ there are two ways that data can be placed into a
variable:
1. Using C++’s assignment statement, and
2. Use input (read) statements.
Assignment Statement
The assignment statement takes the form
variable = expression;
• The expression is evaluated and its value is assigned to the
variable on the left side.
• In C++, = is called the assignment operator.
Examples 2-13
int I, J;
double sale;
char first;
string str;
I = 4;
J = 4 * 5 - 11;
sale = 0.02 * 1000;
first = 'D';
str = "It is a sunny day. ";
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;
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.
 The statement
cin>>miles;
causes the computer to get a value of the type double and place it
in the memory cell 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;
gets two integers (entered at the keyboard) and places them in the
memory location feet and inch, respectively.
Variable Initialization
 Assignment statement
 Read statement
int feet;
 We can initialize feet to a value 35 either by using the assignment
statement
feet = 35;
or by executing the statement
cin>>feet;
 C++ does not automatically initialize the variables when they are
declared.
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.
Example 2-17
Statement
1. cout<<29/4;
2. cout<<"Hello there. ";
3. cout<<12;
4. cout<<"4+7";
5. cout<<4+7;
6. cout<<"A";
Output
7
7. cout<<"4 + 7 = "<<4 + 7;
4 + 7 = 11
8. cout<<2+3*5;
9. cout<<"Hello \nthere. ";
17
Hello
there.
•\n is called new line escape sequence.
•\ (back slash) is called the escape character.
Hello there.
12
4+7
11
A
The output of the C++ statement
cout<<a;
is meaningful provided the variable a has been given a value. For
example, the sequence of C++ statements,
a = 45;
cout<<a;
will produce an output of 45.
• The new line character, '\n'.
cout<<"Hello there.";
cout<<"My name is Goofy.";
Output
Hello there.My name is Goofy.
Now consider the following C++ statements.
cout<<"Hello there.\n";
cout<<"My name is Goofy.";
Output
Hello there.
My name is Goofy.
• When \n is encountered in the string, the cursor is positioned at the
beginning of the next line.
• \n may appear anywhere in the string.
The output of the statement
cout<<"\n";
is equivalent to the output of the statement
cout<<endl;
which is equivalent to the output of the statement
cout<<'\n';
The output of the sequence of statements:
cout<<"Hello there.\n";
cout<<"My name is Goofy.";
is equivalent to the output of the sequence statements:
cout<<"Hello there."<<endl;
cout<<"My name is Goofy.";
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.
The general syntax to include a header file (provided by the SDK) in a
C++ program is
#include <headerFileName>
The preprocessor directive
#include <iostream>
causes the preprocessor to include the header file iostream in the
program.
• In Standard C++, header files have the file extension .h
• In Standard C++, the descriptions of the functions needed to perform
I/O are contained in the header file iostream.h
#include <iostream.h>
#include <math.h>
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>.
Using the string Data Type in a Program
• To use the string data type in a program, your must include the
following preprocessor directive:
#include <string>
PROGRAMMING EXAMPLE: CONVERT LENGTH
Write a program that takes as input a given length expressed in feet
and inches. It then converts and outputs the length in centimeters.
Input: Length in feet and inches.
Output: Equivalent length in centimeters.
Problem Analysis and Algorithm Design
The lengths are given in feet and inches, and you need to find the
equivalent length in centimeters. One inch is equal to 2.54
centimeters. The first thing the program needs to do is convert the
length given in feet and inches to all inches. Then you can use the
conversion formula, 1 inch = 2.54 centimeters, to find the
equivalent length in centimeters. To convert the length from feet and
inches to inches, you multiply the number of feet by 12, as 1 foot is
equal to 12 inches, and add the given inches.
For example, suppose input is 5 feet and 7 inches. Then total inches are
given by
totalInches = 12 * feet + inches
= 12 * 5 + 7 = 67
We now apply the conversion formula, that is, 1 inch = 2.54
centimeters to find the length in centimeters.
centimeters = totalInches * 2.54
= 67 * 2.54
= 170.18
The above discussion translates into the following algorithm:
1. Get the length in feet and inches.
2. Convert the length into total inches.
3. Convert total inches into centimeters.
4. Output centimeters.
Variables
int feet;
//variable to hold given feet
int inchs;
//variable to hold given inches
int totalInches; //variable to hold total inches
double centimeters; // variable to hold length
//in centimeters.
Named Constant
const double conversion = 2.54;
const int inchesPerFoot = 12;
Main Algorithm
1. Prompt the user for the input. (Without a prompt line, the user will
be staring at a blank screen and will not know what to do.)
2. Get the data.
3. Echo the input—that is, output what the program read as input.
(Without this step, after the program has executed, you will not
know what the input was.)
4. Find the length in inches.
5. Output the length in inches.
6. Convert the length to centimeters.
7. Output the length in centimeters.
Putting it Together
• The program will begin with comments that document its purpose and
functionality.
• There is both input to this program (the length in feet and inches) and
output (the equivalent length in centimeters), you will be using system
resources for input/output.
• The program will use input statements to get data into the program
and output statements to print the results.
• The data will be entered from the keyboard and the output will be
displayed on the screen, the program must include the header file
iostream.
• The first statement of the program, after the comments as described
above, will be the preprocessor directive to include this header file.
• This program requires two types of memory locations for data
manipulation: named constants and variables.
• Named constants are usually placed before the function main so that
they can be used throughout the program.
• This program has only one function, the function main, which will
contain all of the programming instructions in its body.
• The program needs variables to manipulate data, and these variables
will be declared in the body of the function main.
• The body of the function main has the following form:
int main ()
{
declare variables
statements
return 0;
}
In order to write the complete C++ program:
1. Begin the program with comments for documentation.
2. Include header files, if any are used in the program.
3. Declare named constants, if any.
4. Write the definition of the function main.
Complete Program Listing in ANSI/ISO Standard
C++
//*************************************************
//
Program Convert: This program converts
// measurements in feet and inches into centimeters
// using the approximation that 1 inch is equal to
// 2.54 centimeters.
//*************************************************
//header file
#include <iostream>
using namespace std;
//named constants
const double conversion = 2.54;
const int inchesPerFoot = 12 ;
int main ()
{
//declare variables
int feet;
int inches;
int totalInches;
double centimeter;
//Statements: Step 1 - Step 7
cout<<"Enter two integers, one for feet, "
<<"one for inches: ";
//Step 1
cin>>feet>>inches;
//Step 2
cout<<endl;
cout<<"The numbers you entered are "<<feet
<<" for feet "<<"and "<<inches
<<" for inches. "<<endl;
//Step 3
totalInches = inchesPerFoot * feet + inches;
//Step
cout<<endl;
cout<<"The total number of inches = "
<<totalInches<<endl;
//Step
centimeter = conversion * totalInches;
//Step
cout<<"The number of centimeters = "
<<centimeter<<endl;
//Step
return 0;
}
4
5
6
7
Sample Run: In this sample run, the user input is in red
Enter two integers, one for feet, one for inches: 15 7
The numbers you entered are 15 for feet and 7 for inches.
The total number of inches = 187
The number of centimeters = 474.98