CHAPTER 2 Intro To C++ Programming
CHAPTER 2 Intro To C++ Programming
CHAPTER 2 Intro To C++ Programming
CHAPTER 2
INTRODUCTION TO
C++ PROGRAMMING
OBJECTIVES:
At the end of the chapter the students should be able to:
Before we get our hands dirty, it would be better for us to navigate the editor that we will
be using in programming C++.
Wiz
ard
Bar
Project
Workspace
Editor Window
Output Window
Figure 2.1
The Microsoft Visual C++ IDE
Figure 2.1 illustrates the C++ editor, commonly called the Integrated Development
Environment or IDE. An IDE is a program that hosts the compiler, debugger, and
application-building tools. You can create programs, access the online help, and perform
debugging without leaving the IDE. Below are some of the common features of the MS
Visual C++ IDE:
21
Like any other Windows application, the MS Visual C++ Environment has its own title
bar, menu bar, and toolbars to help users perform programming tasks fast and easy. It
also has three separate windows which perform different functions: document or editor,
project workspace, and output.
The area on the right side of the IDE is the editor area. This is the area where you
perform all your editing when using MS Visual C++.
The workspace, as it is normally called, appears on the left side of the IDE. It allows you
to navigate the various parts of your development code, and can be viewed in two
different ways:
1. The Class View, which allows you to navigate and manipulate your source code
on a C++ class level; and
2. The File View, which allows you to view and navigate all the files that make up
your application.
The output window appears at the bottom of the IDE and remains open until you choose
to close it. It provides information such as compiler progress statements, warnings, and
error messages.
22
In this book, we will write C++ programs using the following format:
<header files>
void main(void)
{
<variable declarations>
<statements>
}
HEADER FILES
Like other programming languages, C++ has a large collection of pre-defined functions.
You may think of a function as a group or sequence of statements. In some cases,
programmers refer to functions as subprograms. The word “pre-defined” means that users
or programmers can use the function without knowing or concerning themselves how
they were written. For the meantime, we will only be using the header file iostream.h,
which stores the standard input/output functions of C++.
23
FUNCTIONS
All statements should be written inside a user-defined function. The word “user-defined”
means that it is the user who defined (or wrote) the description of a function. In Source
Code 2.1, there is only one user-defined function – the main() function. Take note that all
C++ programs must have a main() function.
STATEMENTS
All C++ programs are made up of a sequence of instructions. In C++, instructions are
also called statements, wherein a semicolon terminates each statement.
In Source Code 2.1 above, there is only one statement -- the cout statement. cout is the
standard output operator of C++ that is stored in the header file iostream.h.
THE { } SYMBOLS
The symbols { (open brace or open curly bracket) and } (close brace or close curly
bracket) are used for grouping purposes. In the example program above, the open and
close curly brackets signify the beginning and the end of the main() function respectively.
Take note however that the curly brackets must always come in pair. A missing curly
bracket is one of the most common causes of syntax errors. A syntax error is a
programming error violating the rules that specify how a command or instruction should
be written.
As we shall see later on, the curly brackets are used to group several statements.
THE /* */ SYMBOLS
The symbols /* and */ are used for block comments inside the program. Comments
simply provide additional information such as what the program is doing: what are the
inputs, what are the outputs, etc. Think of /* as the beginning of a comment, and the */ as
the end a comment. Just like the curly brackets, they symbols always come in pair.
Comments are optional and maybe placed anywhere within the program source code.
#include <iostream.h>
/* The following is
an example
of a very simple C program */
void main(void)
{
cout << "Welcome to C++!!!\n";
}
Note that comments cannot be nested, i.e. you cannot put /* */ inside /* */. For example,
the following will cause a syntax error:
/*
this is a comment
/* this is one more comment – which will cause an error */
*/
Another option that can be used in inserting comments is by using // (double slash) for
single line comments. This is so because the comment terminates at the end of the
current line. For example:
#include <iostream.h>
// The following is
// an example
// of a very simple C program
void main(void)
{
cout << "Welcome to C++!!!\n";
}
NAMING CONVENTIONS
Data and instructions to manipulate data are referred to by their names, also called
identifiers. In C++, the following are rules and conventions to follow in giving a name:
Table 2.1 above shows some examples of valid and invalid names in C++.
KEYWORDS
MS Visual C++ has its own set of keywords. These names are reserved and cannot be
used for other purposes such as in naming user-defined variable names. In the example
source codes above, the name void is a keyword. The MS Visual C++ language has a
total of 59 keywords shown below.
26
It is important to note that main is a not a keyword in C++. However, although the name
cout is actually not a C++ keyword and is not really part of the language, it is a name pre-
defined in the standard input/output library, thus, it cannot be used as an identifier in C++
like main.
CONSTANTS
Constants are entities whose value does not change. A constant can either be numeric
constant or a literal constant. In C/C++, a numeric constant can be an integer or floating
point number, while a literal constant can be a single character or a string, i.e. a constant
with more than one character. A single character is written such that it is enclosed in a
pair of single quotes. A string is written enclosed in a pair of double quotes.
The Table 2.3 shows some examples of numeric and literal constants. It is important to
note that even if 'A' and "A" contains the same value, they are of different types. The
former is a character while the latter is a string.
VARIABLES
A program is made of data and instructions to manipulate those data. Note that data have
to be stored somewhere, and thus will need some memory space in the Random Access
Memory (RAM). In a C++ program, a variable is the entity that holds data. A variable, as
the name suggests, is a varying entity depending on the actual data it holds. Without
variables, it would be impossible to store data. A variable has the following
characteristics:
1. a symbolic name;
2. an associated physical memory space (portion in a RAM);
3. a data type;
4. a value that depends on the data type;
5. a scope; and
6. a lifetime
char – the character data type. The char data type is used to
represent/store/manipulate character data values. The range of values that can be
assumed by a char value is from 0 to 255. The number-to-character coding that is
used in the American Standard Code for Information Interchange (ASCII).
int – the integer data type. The int data type is used to represent/store/manipulate
signed whole numbers. The range of values that can be assumed by an int value
is from -2147483648 to 2147483647.
float – the single precision floating point data type. The float data type is used to
store single precision signed real numbers. The appropriate range of values that
can be assumed by a float value is from 3.4 X 10-38 to 3.4 X 1038.
double – the double precision floating point data type. The double data type is
used to store double precision signed real numbers. The appropriate range of
values that can be assumed by a double value is from 1.7 X 10 -308 to 1.7 X 10308.
bool – the Boolean data type. The bool data type is used to represent Boolean
values true or false.
28
The amount of memory space required to store an int, a float and double is platform-
dependent (depends on the machine and the software). For compilers such as the
Microsoft Visual C++ compiler, a char and bool requires 1 byte of memory each, an int
and float requires 4 bytes of memory each, while a double requires 8 bytes of memory.
Note that a char data type is actually numeric (from 0 to 255), and is treated as a subset
of int values. Any operation on integer values can also be performed on characters.
The following program can be used to print the sizes of the basic data types:
#include <iostream.h>
void main(void)
{
cout << "Size of char: " << sizeof(char) << "\n";
cout << "Size of int: " << sizeof(int) << "\n";
cout << "Size of float: " << sizeof(float) << "\n";
cout << "Size of double: " << sizeof(double) << "\n";
cout << "Size of bool: " << sizeof(bool) << "\n";
}
The sizeof is a keyword in C++. It is an operator that yields the size in number of bytes
of the specified data type.
Variable Declaration
A semicolon signifies the end of a declaration. A missing semicolon will cause the
compiler to generate a syntax error. Variables should be named following the C++
naming conventions. For example:
29
char ch;
bool b;
int i;
float f;
double d;
It is possible to declare several variables of the same type on the same line. In such a
case, a comma should be inserted between two variables. A missing comma will generate
a syntax error. For example:
In general, C++ allows the user to declare variables in any part of the program code
before they can be used, but this is not advisable, especially for long programs.
Although we can use any name for the variables, it is recommended, however, as a good
programming practice for you to use a name that is descriptive or suggestive. For
example, if you know that a variable will represent a temperature in degree Celsius, then
don’t use names such as x or c1. It is better to use a variable name such as celsius or
degree_celsius. Note that the use of the underscore makes reading the variable name easy
to read.
By default, the value of a variable in C++ is GARBAGE, i.e., there is something stored in
that memory space but that something is invalid for the intended use. The use of a
variable with a garbage value will cause a logical error. Unlike syntax errors, the
compiler is not capable of detecting logical errors since these are errors committed by the
programmer on the program or logic flow. To avoid such instance, we must assign a
valid value to a variable before performing any operation on the variable.
Operators
Operators are symbols representing operations that can be performed on constants and
variables. There are four basic operations available in C++ language.
1. Assignment Operation
2. Arithmetic Operation
3. Relational Operation
4. Logical Operation
30
The assignment operator is denoted by the equal symbol (=). It is used to store (i.e.,
assign) a value to a variable. The syntax of an assignment operation is:
In the syntax above, variable name can be any valid identifier in C++, while expression
can be a constant, variable or a valid expression.
The assignment operation is also a statement, thus a semicolon should terminate it.
Source Code 2.5 below shows how to use the assignment statement. Expect, however,
that if you run the program, there will be no output will be produced.
ch1 = ‘Z’;
ch2 = ch1;
x = 5;
y = x;
31
If in some cases we assign a value whose data type is different from the data type of the
receiving variable, the data type of the value will be converted to the data type of the
variable (either demoted or promoted).
MS Visual C++ supports a number of operators. The basic arithmetic operations, plus
some other operations are available in C++ language. These are as follows:
OPERATOR DESCRIPTION
+ (plus) addition (returns the sum of two operands)
- (minus or dash) subtraction (returns the difference of two operands)
* (asterisk) multiplication (returns the product of two operands)
/ (slash) division (returns the quotient of two operands)
% (percent) modulus operator (returns the remainder)
++ (double plus) increment (returns the value of an operand plus 1)
-- (double minus) decrement (returns the value of an operand minus 1)
TABLE 2.4
C++ Basic Arithmetic Operators
The +, -, *, / , ++, and – (we will elaborate more on the ++ and – operators later) can be
used for operands of type int, float and double data types. Actually, they can also be used
on char since char is a subset of int. The % operator can be used only with integer
operands. The first five operators in Table 2.4 are called binary operators because they
require two operands, while the increment and decrement operators are referred to as
unary operators because they require only one operand.
The following program shows how to use the arithmetic operators with integer operands:
32
#include <iostream.h>
void main(void)
{
int a, b, c, d;
float e;
a = 10 + 15;
b = 27 - 13;
c = 4 * 6;
d = 24 % 5;
e = 18 / 8;
In the example above, the statement e = 18 / 8; will result into a 2 instead of 2.25 (i.e.,
the fractional part .25 is discarded). This is what we refer to as integer division, which
occurs when the operands of the division operator are both whole numbers: char or
integer values.
When one of the operands is a float or double, the division is a real number division. For
example:
C++ also provides a casting function which can be used to force a variable or an
expression to be of a specific data type. The syntax for type casting is as follows:
or
Thus, the following operations can be used to retain the fractional part .25 from the
previous example:
33
(float)18 / 8
float(18) / 8
18 / float(8)
18 / (float)8
There are some important notes to remember in the use of C++ operators:
12345 = x;
a = 12345;
a = a; // a get the value of a, which is 12345
a = 50;
a = a + 1;
The statement a = 50; means the value 50 is assigned to a. The next statement adds 1 to
this value resulting to 51, which is then assigned as the new value of a.
A+B*C
Here the multiplication operation will be performed first before the addition. To perform
the addition before multiplication, we have to write the arithmetic expression as:
(A+B)*C
#include <iostream.h>
a = 2;
a++;
cout << "a = " << a << "\n";
b = 4;
b--;
cout << "b= " << b << "\n";
Used in a statement by themselves, the operators can be placed before or after a variable
yielding same results. On the other hand, using the operators in a more complex
expression will produce a different output. Source Code 2.8 shows an application of this
behavior.
35
#include <iostream.h>
a = 10;
b = a++; // suffix ++
cout << "a = " << a<< "\n";
cout << "b = " << b << "\n";
a = 10;
b = ++a; // prefix ++
cout << "a = " << a << "\n";
cout << "b = " << b << "\n";
}
In the sample program above, the output after the statement b = a++; yields
a = 11
b = 10
a = 11
b = 11
OPERATOR DESCRIPTION
== (double equal sign) equal to
!= (exclamation and equal sign) not equal to
> (greater than sign) greater than
< (less than sign) less than
>= (greater than and equal sign) greater than or equal to
<= (less than and equal sign) less than or equal to
TABLE 2.5
Basic C++ Relational/Comparison Operators
The relational operators can be performed on all the basic data types. In C++, the result
of a relational operation is either a 0 (zero) or a 1 (one). A zero means that the relation is
FALSE and a one means that it is TRUE. All the relational/comparison operators are
binary operators.
It is important to remember that the test for equality uses two equal symbols. Forgetting
one of the equal sign is a very common logical error.
#include <iostream.h>
void main(void)
{
int a, b, c, d, e, f;
int x, y;
x = 12;
y = 34;
a = (x == y);
b = (x != y);
c = (x > y);
d = (x < y);
e = (x >= y);
f = (x <= y);
OPERATOR DESCRIPTION
! (exclamation mark) not
&& (double ampersand) and
|| (double bar) or
TABLE 2.6
C++ Basic Logical Operators
The logical operators are normally used in conjunction with relational operators to test
for multiple conditions. The logical NOT is a unary operator, it is used with only one
operand to its right. The remaining operators are binary operators. The logical NOT
operation is performed before logical AND, before logical OR.
An actual C++ program that shows the result of the operators is presented below.
#include <iostream.h>
void main(void)
{
/* logical NOT operator */
cout << "!0 = " << !0 << "\n";
cout << "!1 = " << !1 << "\n";
/* logical OR operator */
cout << "0 || 0 = " << (0 || 0) << "\n";
cout << "0 || 1 = " << (0 || 1) << "\n";
cout << "1 || 0 = " << (1 || 0) << "\n";
cout << "1 || 1 = " << (1 || 1) << "\n";
}
The precedence of operators depends on their priority and associativity (i.e. is the
expression evaluated from left to right or right to left). The table below presents the
precedence and associativity of operators from highest to lowest. Operators that appear
together have equal precedence and are evaluated according to their associativity.
OPERATOR ASSOCIATIVITY
( ) postfix++ postfix-- Left to right
! prefix++ prefix-- & sizeof Right to left
type casting Right to left
* / % Left to right
+ - Left to right
< <= > >= Left to right
== != Left to right
&& Left to right
|| Left to right
= *= /= %= += -= Right to left
Table 2.7
Precedence of Operators