Sei sulla pagina 1di 20

19

CHAPTER 2
INTRODUCTION TO
C++ PROGRAMMING

OBJECTIVES:
At the end of the chapter the students should be able to:

1. Familiarize themselves with the Microsoft(MS) Visual


C++ Integrated Development Environment (IDE).
2. Understand the basic components of a C++ program.
3. Classify identifiers, keywords, constants, and variables.
4. Enumerate and apply the basic data types of C++.
5. Identify the different operators to be used.
6. Know the precedence of operators.
20

C++ was developed mainly for an object-oriented programming (OOP) approach.


However, it can process both OOP and structured programming, with the latter being the
focus of this book’s discussions.

2.1The Integrated Development Environment (IDE)

Before we get our hands dirty, it would be better for us to navigate the editor that we will
be using in programming C++.

TitleBar MenuBar ToolBar

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

 Automatic syntax highlighting colors keywords, comments, and other source


code in different colors.
 Automatic “smart” indenting helps line up your code into easy-to-read columns.
 Auto-Completion automatically displays a menu of items to help you finish C++
statements.
 Parameter Help displays the parameters for Windows functions as you type.
 Integrated keyword help enables you to get help on any keyword just by pressing
F1.
 Drag-and-drop editing enables you to move text easily by dragging it with the
mouse.
 Integration with the compiler’s error output helps you step through the list of
errors reported by the compiler and positions the cursor at every error.

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 Document Window / Editor Area

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 Project Workspace Window

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

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

A Simple C++ Program

Let us look at a very simple example of a C++ program:

/* This is a simple C++ program */


/* declaration of header file */
#include <iostream.h>

/* start of main program */


void main(void)
{
cout << "Welcome to C++!!!\n";
}

Source Code 2.1


“Welcome to C++!!!”

Source Code 2.1 is what is referred to as a program source code. It is made up of a


combination of letters, numbers and other symbols. We will be writing and executing
programs using the MS Visual C++ IDE.

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.

It is possible to write several lines of comments inside /* */. For example:


24

#include <iostream.h>

/* The following is
an example
of a very simple C program */

void main(void)
{
cout << "Welcome to C++!!!\n";
}

Source Code 2.2


Block Comment

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";
}

Source Code 2.3


Single Line Comment
25

Identifiers, Keywords, Constants, and Variables

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:

1. Names are made up of letters and digits.


2. The first character must be a letter or an underscore (_). However, an underscore
is not recommended to be used as the first character in a name since some of C+
+’s internal identifiers begin with underscores.
3. C++ is case-sensitive, i.e., the lower-case letter ‘a’ is not the same as the
uppercase letter ‘A’.
4. At least the first 31 characters of a name are significant.

Valid Invalid Identifiers


Identifiers Names Error Description
a 1 must start with a character
A 1_ab must start with a character
main a& & symbol cannot be used in a name
salary_per_day xyz_% % cannot be used in a name
Student_1
Student1
Table 2.1
Examples of Valid and Invalid Names in C++

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

break Enum operator template


bool explicit private this
case Extern protected throw
catch False public true
char Float register try
class For reinterpret_cast typedef
const Friend return typeid
const_cast Goto short typename
continue If signed union
default Inline sizeof unsigned
delete Int static using
do Long volatile virtual
double mutable static_cast void
dynamic_cast namespace struct while
else New switch
Table 2.2
C++ Keywords

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.

Numeric Constants Literal Constants


1 'A'
123 "A"
-123 "Welcome to C++!!!"
3.1416 "The quick brown fox jumps over the lazy dog."
Table 2.3
Examples of C++ Constants
27

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

Basic Data Types in C++


A data type specifies the kind of values can be assumed by a variable of that type, the
range of values that can be assumed by a variable of that type, and the amount of memory
(in bytes) needed by a variable to store a value of that type.
There are five basic data types in C++, namely:

 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";
}

Source Code 2.4


The sizeof Operator

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 variable declaration is an “action” by which a variable is “introduced” to a


program/function. All variables in a C++ program must be declared. If you forgot to do
so, the compiler will report a syntax error. The syntax for declaring a variable is as
follows:

<data type> <variable name>;

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:

char ch1, ch2;


bool b1, b2;
int x, y, z;
float degree_celsius, degree_fahrenheit, degree_kelvin;
double numerator, denominator;

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:

<variable name> = <expression>;

In the syntax above, variable name can be any valid identifier in C++, while expression
can be a constant, variable or a valid expression.

2.6.1 THE ASSIGNMENT OPERATOR

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.

/* a sample program demonstrating the use of assignment statement */


void main(void)
{
// declaration of variables
char ch;
bool b;
int i;
float f;
double d;

ch = ‘A’; // assign a char value to char variable


b = false; // assign a false value (0) to bool variable
i = 5; // assign an int value to int variable
f = 1.25; // assign a float value to float variable
d = 3.14159; // assign a double value to double variable
}

Source Code 2.5


The Use of the Assignment Statement

It is also possible to assign a value of a variable to another variable of a compatible data


type. For example:

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).

2.6.2 THE ARITHMETIC OPERATORS

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;

cout << "a = " << a << "\n";


cout << "b = " << b << "\n";
cout << "c = " << c << "\n";
cout << "d = " << d << "\n";
cout << "e = " << e << "\n";
}

Source Code 2.6


The Use of Arithmetic Operators

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:

18.0 / 8 will result into 2.25

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:

(<data type>) <expression>

or

<data type> (<expression>)

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:

 Assigning a variable to a constant is syntax error. For example:

12345 = x;

 Assigning the value of a variable to a variable of the same name is syntactically


correct, but practically useless and does not make any sense. For example:

a = 12345;
a = a; // a get the value of a, which is 12345

 It is usual in programming to assign a value of an expression to a variable,


wherein the old value of the variable is also used in the expression. For example:

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.

When an expression has sequence of arithmetic operations, it is evaluated following the


MDAS rule, wherein multiplication or division should be performed first before addition
or subtraction. To override this usual priority of operation, a pair of parentheses should
be used. For example, given the expression:

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

Earlier, we were presented a C++ statement a = a + 1; which simply means increment


the value of the variable a by 1. In the same way, if we intend to decrement a variable,
say a, by 1 we can use the statement a = a - 1;. However, C++ provides a shortcut in
performing such operations: the unary operators ++ (double plus) and -- (double minus).
34

The ++ is used to increment the value of an integer variable by 1. The -- is used to


decrement the value of an integer variable by one. Source Code 2.7 illustrates the use of
the ++ and – operators.

#include <iostream.h>

void main (void)


{
char ch1, ch2;
int a, b;

a = 2;
a++;
cout << "a = " << a << "\n";

b = 4;
b--;
cout << "b= " << b << "\n";

ch1 = 'A'; // ch1 = 65


ch1++;
cout << "ch1= " << ch1 << "\n";

ch2 = 'Z'; // ch2 = 90


ch2--;
cout << "ch2= " << ch2 << "\n";
}

Source Code 2.7


The ++ and -- Operators

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>

void main (void)


{
int a, b;

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";
}

Source Code 2.8


The Use of the Prefix/Suffix ++ and -- Operators

In the sample program above, the output after the statement b = a++; yields

a = 11
b = 10

while the output after the statement b = ++a; yields

a = 11
b = 11

2.6.3 THE RELATIONAL/COMPARISON OPERATORS


The relational/comparison operators in C++ are as follows:
36

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.

The program below shows a very simple implementation of relational operators.

#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);

cout << “a = ” << a << “\n”;


cout << “b = ” << b << “\n”;
cout << “c = ” << c << “\n”;
cout << “d = ” << d << “\n”;
cout << “e = ” << e << “\n”;
cout << “f = ” << f << “\n”;
}

Source Code 2.7


The Use of Relational Operators
37

2.6.4 THE LOGICAL OPERATORS

The logical operators in C++ are as follows:

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 AND 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";

/* 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";
}

Source Code 2.9


The Use of Logical Operators
38

2.6.5 THE PRECEDENCE OF OPERATORS

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

Potrebbero piacerti anche