C++ Module Chapter 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

Fundamental of Programming 201

Chapter Two

C++ Basics
2.1 What is C++?

 C++ is a compiled, object-oriented language.


 It is the “successor” to C, a procedural language.
 (The “++” is called the successor operator in C++).
 C was derived from a language called B which was in turn derived from
BCPL.
 C was developed in the 1970’s by Dennis Ritchie of AT&T Bell Labs.
 C++ was developed in the early 1980’s by Bjarne Stroustrup of AT&T
Bell Labs.
 Most of C is a subset of C++.
2.2 Structure of C++ Program

A C++ program has the following structure

[Comments]

[Preprocessor directives]

[The main function]

[Starting of main function]

[Body of function]

[Return the function]

[End of the function]

Ex

#include <iostream.h> //Compiler directive: Tells the compiler what to do before


compiling. This one includes source code from another file.

int main() /*Header for main function

int main() States that: data type for the return value

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 1


Fundamental of Programming 201
O
Identifier for function

list of arguments between parenthesis


(none for this function)*/

{ //It indicates the starting of main function

// Declarations

// Statements /*Declaration and statement are the main body of the


function/program.*/

return 0; /*It returns the function , or it indicates the successful termination of the
program*/

} //It indicates the end of main function

C++ Program Development Process (PDP):

C++ programs typically go through six phases before they can be

executed. These phases are:

1. Edit: The programmer types a C++ source program, and makes

correction, if necessary. Then file is stored in disk with extension

(.cpp).

2. Pre-Processor: Pre-processing is accomplished by the preproceccor before


compilation, which includes some substitution of files and other directories to be include
with the source file.

3. Compilation: Converting the source program into object-code.

4. Linking: A linker combines the original code with library functions to

produce an executable code.

5. Loading: The loader loads the program from the disk into memory.

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 2


Fundamental of Programming 201
O
6. CPU: Executes the program, residing in memory.

These steps are introduced in the figure below

2.3 Showing Sample program

Any meaningful program written in C++ has to contain a number of components: the
main function; some variable declarations; and some executable statements. For example,
the following is a very basic C++ program:
1: #include <iostream.h>
2: int main()
3: {
4: cout << "Hello World!\n";
5: return 0;
6: }
On line 1, the file iostream.h is included in the file. The first character is the # symbol,
which is a signal to the preprocessor. Each time you start your compiler, the preprocessor

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 3


Fundamental of Programming 201
O
is run. The preprocessor reads through your source code, looking for lines that begin with
the pound symbol (#), and acts on those lines before the compiler runs.
include is a preprocessor instruction that says, "What follows is a filename. Find that file
and read it in right here." The angle brackets around the filename tell the preprocessor to
look in all the usual places for this file. If your compiler is set up correctly, the angle
brackets will cause the preprocessor to look for the file iostream.h in the directory that
holds all the H files for your compiler. The file iostream.h (Input-Output-Stream) is used
by cout, which assists with writing to the screen. The effect of line 1 is to include the file
iostream.h into this program as if you had typed it in yourself.
The preprocessor runs before your compiler each time the compiler is invoked. The
preprocessor translates any line that begins with a pound symbol (#) into a special
command, getting your code file ready for the compiler.
Line 2, begins the actual program with a function named main(). Every C++ program has
a main() function. In general, a function is a block of code that performs one or more
actions. Usually functions are invoked or called by other functions, but main() is special.
When your program starts, main() is called automatically.
main(), like all functions, must state what kind of value it will return. The return value
type for main() in HELLO.CPP is int, which means that this function will return an
integer value.
All functions begin with an opening brace ({) and end with a closing brace (}). The
braces for the main() function are on lines 3 and 6. Everything between the opening and
closing braces is considered a part of the function.
The meat and potatoes of this program is on line 4. The object cout is used to print a
message to the screen. cout is used in C++ to print strings and values to the screen. A
string is just a set of characters.
Here's how cout is used: type the word cout, followed by the output redirection operator
(<<). Whatever follows the output redirection operator is written to the screen. If you
want a string of characters written, be sure to enclose them in double quotes ("), as shown
on line 4. A text string is a series of printable characters.

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 4


Fundamental of Programming 201
O
The final two characters, \n, tell cout to put a new line after the words Hello World! On
line 5 all programs declare main() to return an int. This value is "returned" to the
operating system when your program completes. Some programmers signal an error by
returning the value 1. The main() function ends on line 6 with the closing brace.

2.4 Keywords (reserved words)

Reserved/Key words have a unique meaning within a C++ program. These symbols, the
reserved words, must not be used for any other purposes. All reserved words are in
lower-case letters. The following are some of the reserved words of C++.

Asm Auto Bool break Case Catch


const_cast Class Const char Continue default
dynamic_cast Do double delete Else enum
Explicit Extern False float For friend
Goto If Inline int Long mutable
Namespace New operator private Protected public
reinterpret_cast Register Return short Signed sizeof
static_cast Static struct switch Template this
Throw True Try typedef Typeid typename
Union Unsigned Using virtual Void volatile
wchar_t
Notice that main is not a reserved word. However, this is a fairly technical distinction,
and for practical purposes you are advised to treat main, cin, and cout as if they were
reserved as well.

2.5 Identifiers

An identifier is name associated with a function or data object and used to refer to that
function or data object. An identifier must:

 Start with a letter or underscore

 Consist only of letters, the digits 0-9, or the underscore symbol _

 Not be a reserved word

Syntax of an identifier
Letter
Letter
Compiled by: Mr. Mezgebe A. - Dep’t of Computer Science Page 5
Digit
-
Fundamental of Programming 201
O

For the purposes of C++ identifiers, the underscore symbol, _, is considered to be a letter.
Its use as the first character in an identifier is not recommended though, because many
library functions in C++ use such identifiers. Similarly, the use of two consecutive
underscore symbols, _ _, is forbidden.

The following are valid identifiers

Length days_in_year DataSet1 Profit95


Int _Pressure first_one first_1
Although using _Pressure is not recommended.

The following are invalid:

days-in-year 1data int first.val


Throw my__best No## bestWish!
Although it may be easier to type a program consisting of single character identifiers,
modifying or correcting the program becomes more and more difficult. The minor typing
effort of using meaningful identifiers will repay itself many fold in the avoidance of
simple programming errors when the program is modified.

At this stage it is worth noting that C++ is case-sensitive. That is lower-case letters are
treated as distinct from upper-case letters. Thus the word NUM different from the word
num or the word Num. Identifiers can be used to identify variable or constants or
functions. Function identifier is an identifier that is used to name a function.

2.6 Comments

A comment is a piece of descriptive text which explains some aspect of a program.


Program comments are totally ignored by the compiler and are only intended for human
readers. C++ provides two types of comment delimiters:

 Anything after // (until the end of the line on which it appears) is considered a
comment.

 Anything enclosed by the pair /* and */ is considered a comment.

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 6


Fundamental of Programming 201
O
2.7 Input/ Output Statements

The most common way in which a program communicates with the outside world is
through simple, character-oriented Input/ Output (IO) operations. C++ provides two
useful operators for this purpose: >> for input and << for output. We have already seen
examples of output using <<. Example 2.1 also illustrates the use of >> for input.

Example 2.1

#include <iostream.h>
int main (void)
{
int workDays = 5;
float workHours = 7.5;
float payRate, weeklyPay;

cout << "What is the hourly pay rate? ";


cin >> payRate;

weeklyPay = workDays * workHours * payRate;


cout << "Weekly Pay = ";
cout << weeklyPay;
cout << '\n';
}

Analysis
This line outputs the prompt ‘What is the hourly pay rate? ’ to seek user input.

This line reads the input value typed by the user and copies it to payRate. The input
operator >> takes an input stream as its left operand (cin is the standard C++ input stream
which corresponds to data entered via the keyboard) and a variable (to which the input
data is copied) as its right operand.

When run, the program will produce the following output (user input appears in bold):
What is the hourly pay rate? 33.55
Weekly Pay = 1258.125

Both << and >> return their left operand as their result, enabling multiple input or multiple
output operations to be combined into one statement. This is illustrated by example below
which now allows the input of both the daily work hours and the hourly pay rate.

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 7


Fundamental of Programming 201
O

Example
#include <iostream.h>

int main (void)


{
int workDays = 5;
float workHours, payRate, weeklyPay;

cout << "What are the work hours and the hourly pay rate? ";
cin >> workHours >> payRate;

weeklyPay = workDays * workHours * payRate;


cout << "Weekly Pay = " << weeklyPay << '\n';
}

Analysis
This line reads two input values typed by the user and copies them to workHours and
payRate, respectively. The two values should be separated by white space (i.e., one or
more space or tab characters). This statement is equivalent to:

(cin >> workHours) >> payRate;

Because the result of >> is its left operand, (cin >> workHours) evaluates to cin which is
then used as the left operand of the next >> operator.

This line is the result of combining lines 10-12 from example 2.1. It outputs "Weekly Pay
= ", followed by the value of weeklyPay, followed by a newline character. This statement
is equivalent to:

((cout << "Weekly Pay = ") << weeklyPay) << '\n';

Because the result of << is its left operand, (cout << "Weekly Pay = ") evaluates to cout
which is then used as the left operand of the next << operator, etc.

When run, the program will produce the following output:

What are the work hours and the hourly pay rate? 7.5 33.55
Weekly Pay = 1258.125

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 8


Fundamental of Programming 201
O
2.8 Variables, Data Types and Constants

2.8.1 Variables

A variable is a symbolic name for a memory location in which data can be stored and
subsequently recalled. Variables are used for holding data values so that they can be
utilized in various computations in a program. All variables have two important
attributes:

 A type, which is, established when the variable is defined (e.g., integer, float,
character). Once defined, the type of a C++ variable cannot be changed.

 A value, which can be changed by assigning a new value to the variable. The kind
of values a variable can assume depends on its type. For example, an integer
variable can only take integer values (e.g., 2, 100, -12) not real numbers like
0.123.

2.8.1.1 Variable Declaration

Declaring a variable means defining (creating) a variable. You create or define a variable
by stating its type, followed by one or more spaces, followed by the variable name and a
semicolon. The variable name can be virtually any combination of letters, but cannot
contain spaces and the first character must be a letter or an underscore. Variable names
cannot also be the same as keywords used by C++. Legal variable names include x,
J23qrsnf, and myAge. Good variable names tell you what the variables are for; using
good names makes it easier to understand the flow of your program. The following
statement defines an integer variable called myAge:

int myAge;
IMPORTANT- Variables must be declared before used!

As a general programming practice, avoid such horrific names as J23qrsnf, and restrict
single-letter variable names (such as x or i) to variables that are used only very briefly.
Try to use expressive names such as myAge or howMany.

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 9


Fundamental of Programming 201
O
A point worth mentioning again here is that C++ is case-sensitive. In other words,
uppercase and lowercase letters are considered to be different. A variable named age is
different from Age, which is different from AGE.

Creating More Than One Variable at a Time

You can create more than one variable of the same type in one statement by writing the
type and then the variable names, separated by commas. For example:

int myAge, myWeight; // two int variables


long area, width, length; // three longs
As you can see, myAge and myWeight are each declared as integer variables. The second
line declares three individual long variables named area, width, and length. However
keep in mind that you cannot mix types in one definition statement.

2.8.1.2 Variable initialization

You assign a value to a variable by using the assignment operator (=). Thus, you would
assign 5 to Width by writing

int Width;
Width = 5;
You can combine these steps and initialize Width when you define it by writing

int Width = 5;

Initialization looks very much like assignment, and with integer variables, the difference
is minor. The essential difference is that initialization takes place at the moment you
create the variable.

Just as you can define more than one variable at a time, you can initialize more than one
variable at creation. For example:

// create two int variables and initialize them


int width = 5, length = 7;
This example initializes the integer variable width to the value 5 and the length variable
to the value 7. It is possible to even mix definitions and initializations:

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 10


Fundamental of Programming 201
O
int myAge = 39, yourAge, hisAge = 40;
This example creates three type int variables, and it initializes the first and third.

2.8.1.3 VARIABLE SCOPE:

A scope is a region of the program and broadly speaking there are three places,
where variables can be declared:
 Inside a function or a block which is called local variables,
 In the definition of function parameters which is called formal parameters.
 Outside of all functions which is called global variables.
We will learn what a function is, and it's parameter in subsequent chapters. Here
let us explain what local and global variables are.
Local Variables:
Variables that are declared inside a function or block are local variables. They can
be used only by statements that are inside that function or block of code.
Local variables are not known to functions outside their own. Following is the
example using local variables:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 11


Fundamental of Programming 201
O
Global Variables:
Global variables are defined outside of all the functions, usually on top of the
program. The global variables will hold their value throughout the life-time of
your program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. Following is the
example using global variables:

#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
When the above code is compiled and executed, it produces the following result:10
A program can have same name for local and global variables but value of local
variable inside a function will take preference.

2.8.2 Basic Data Types

When you define a variable in C++, you must tell the compiler what kind of variable it is:
an integer, a character, and so forth. This information tells the compiler how much room
to set aside and what kind of value you want to store in your variable.

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 12


Fundamental of Programming 201
O
Several data types are built into C++. The varieties of data types allow programmers to
select the type appropriate to the needs of the applications being developed. The data
types supported by C++ can be classified as basic (fundamental) data types, user defined
data types, derived data types and empty data types. However, the discussion here will
focus only on the basic data types.

Basic (fundamental) data types in C++ can be conveniently divided into numeric and
character types. Numeric variables can further be divided into integer variables and
floating-point variables. Integer variables will hold only integers whereas floating
number variables can accommodate real numbers.

Both the numeric data types offer modifiers that are used to vary the nature of the data to
be stored. The modifiers used can be short, long, signed and unsigned.

The data types used in C++ programs are described in Table 1.1. This table shows the
variable type, how much room it takes in memory, and what kinds of values can be stored
in these variables. The values that can be stored are determined by the size of the variable
types.

Type Size Values/ranges


unsigned short int 2 bytes 0 to 65,535
short int(signed short int) 2 bytes -32,768 to 32,767
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long int) 4 bytes -2,147,483,648 to 2,147,483,647
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
Char 1 byte 256 character values
Float 4 bytes 3.4e-38 to 3.4e38
Double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932
Table C++ data types and their ranges

• 2.8.3.Type int:
 represent integers or whole numbers

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 13


Fundamental of Programming 201
O

 Some rules to follow:

• Plus signs do not need to be written before the number

• Minus signs must be written when using negative #’s

• Decimal points cannot be used

• Commas cannot be used

• Leading zeros should be avoided.

 Signed - negative or positive

 Unsigned - positive

 Short

 Long

2.8.4 Type double, float:

 used to represent real numbers

 many programmers use type float

 avoid leading zeros, trailing zeros are ignored

 long double

2.8.5 Type char:


 used to represent character data

- a single character which includes a space

- 1 byte, enough to hold 256 values

 must be enclosed in single quotes eg. ‘d’


 Escape sequences treated as single char

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 14


Fundamental of Programming 201
O

 ‘\n’ newline

 ‘\’’ apostrophe

 ‘\”’ double quote

 ‘\t’ tab

2.8.6 Type String:

 used to represent textual information

 string constants must be enclosed in double quotation marks eg. “Hello world!”

 empty string “”

 new line char or string “\n”

 “the word \”hello\”” (puts quotes around “hello” )

The following program reads the four different data type inputs and outputs
listed on the above.

#include<iostream.h>

int main( )

int num=3;

cout << “number=”<<num<<”\n”;

char ch=’a’;

cout << “character=”<<ch<<”\n”;

float fa=-34.45;

cout<<”real number=”<<fa<<”\n”;

string name= “hello”;

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 15


Fundamental of Programming 201
O
cout<<”string=”<<name<<”\n”;

return 0;

Output:

Number=3

Character=a

Real number=34.45

String=hello

2.8.7 Defining Constants


There are two simple ways in C++ to define constants:

 Using #define preprocessor.

 Using const keyword.

2.8.7.1 The #define Preprocessor


Following is the form to use #defines preprocessor to define a constant:

#define identifier value

Following example explains it in detail:

#include <iostream.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
cout << area;

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 16


Fundamental of Programming 201
O

cout << NEWLINE;


return 0;
}

When the above code is compiled and executed, it produces the following result:

50

2.8.7.2 The const Keyword


You can use const prefix to declare constants with a specific type as follows:

const type variable = value;

Following example explains it in detail:

#include <iostream.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}

When the above code is compiled and executed, it produces the following result:

50

2.9. Operators

C++ provides operators for composing arithmetic, relational, logical, bitwise, and
conditional expressions. It also provides operators which produce useful side-effects,
such as assignment, increment, and decrement. We will look at each category of

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 17


Fundamental of Programming 201
O
operators in turn. We will also discuss the precedence rules which govern the order of
operator evaluation in a multi-operator expression.

2.9.1 Assignment Operators (=)

The assignment operator assigns a value to a variable.


a = 5;
This statement assigns the integer value 5 to the variable a. The part at the left of the
assignment operator (=) is known as the lvalue (left value) and the right one as the rvalue
(right value). The lvalue has to be a variable where as the rvalue can be either a constant,
a variable, the result of an operation or any combination of these. The most important
rule when assigning is the right-to-left rule: The assignment operation always takes place
from right to left, and never the other way:
a = b;
This statement assigns to variable a (the lvalue) the value contained in variable b (the
rvalue). The value that was stored until this moment in a is not considered at all in this
operation, and in fact that value is lost.
Consider also that we are only assigning the value of b to a at the moment of the
assignment operation. Therefore a later change of b will not affect the new value of a.

The assignment operator is used for storing a value at some memory location (typically
denoted by a variable). Its left operand should be an lvalue, and its right operand may be
an arbitrary expression. The latter is evaluated and the outcome is stored in the location
denoted by the lvalue.

An lvalue (standing for left value) is anything that denotes a memory location in which a
value may be stored. The only kind of lvalue we have seen so far is a variable. The
assignment operator has a number of variants, obtained by combining it with the
arithmetic operators.

2.9.2 Compound assignment (+=, -=, *=, /=, %=, >>=,


<<=, &=, ^=, |=)

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 18


Fundamental of Programming 201
O
When we want to modify the value of a variable by performing an operation on the value
currently stored in that variable we can use compound assignment operators:

Operato Example Equivalent To


r
= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n – 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
&= n &= 0xF2F2 n = n & 0xF2F2
|= n |= 0xF2F2 n = n | 0xF2F2
^= n ^= 0xF2F2 n = n ^ 0xF2F2
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4

An assignment operation is itself an expression whose value is the value stored in its left
operand. An assignment operation can therefore be used as the right operand of another
assignment operation. Any number of assignments can be concatenated in this fashion to
form one expression. For example:

int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;

This is equally applicable to other forms of assignment. For example:

m = 100;
m += n = p = 10; // means: m = m + (n = p = 10);

Exercise:
Rewrite the equivalent statements for the following examples, and find it results.
Assume: X=2 , Y=3 , Z=4 , V=12 , C=8.

Example Equivalent Statement Result


X += 5 X=X+5 X7
Y -= 8
Z *= 5
V /= 4
C %= 3

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 19


Fundamental of Programming 201
O

2.9.3 Arithmetic Operators

C++ provides five basic arithmetic operators. These are summarized in table below

Operator Name Example


+ Addition 12 + 4.9 // gives 16.9
- Subtraction 3.98 - 4 // gives -0.02
* Multiplication 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5
% Remainder 13 % 3 //gives 1
Arithmetic operators.

Except for remainder (%) all other arithmetic operators can accept a mix of integer and
real operands. Generally, if both operands are integers then the result will be an integer.
However, if one or both of the operands are reals then the result will be a real (or double
to be exact).

When both operands of the division operator (/) are integers then the division is
performed as an integer division and not the normal division we are used to. Integer
division always results in an integer outcome (i.e., the result is always rounded down).
For example:

9/2 // gives 4, not 4.5!


-9 / 2 // gives -5, not -4!

Unintended integer divisions are a common source of programming errors. To obtain a


real division when both operands are integers, you should cast one of the operands to be
real:

int cost = 100;


int volume = 80;
double unitPrice = cost / (double) volume; // gives 1.25

The remainder operator (%) expects integers for both of its operands. It returns the
remainder of integer-dividing the operands. For example 13%3 is calculated by integer
dividing 13 by 3 to give an outcome of 4 and a remainder of 1; the result is therefore 1.

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 20


Fundamental of Programming 201
O
It is possible for the outcome of an arithmetic operation to be too large for storing in a
designated variable. This situation is called an overflow. The outcome of an overflow is
machine-dependent and therefore undefined. For example:

unsigned char k = 10 * 92; // overflow: 920 > 255

It is illegal to divide a number by zero. This results in a run-time division-by-zero failure,


which typically causes the program to terminate.

There are also a number of predefined library functions, which perform arithmetic
operations. As with input & output statements, if you want to use these you must put a
#include statement at the start of your program. Some of the more common library
functions are summarised below.

Paramete
Header r Type(s) Result
Function Result
File Type
<stdlib.h> abs(i) Int int Absolute value of i
<math.h> cos(x) Float float Cosine of x (x is in radians)
<math.h> fabs(x) Float float Absolute value of x
<math.h> pow(x, y) Float float x raised to the power of y
<math.h> sin(x) Float float Sine of x (x is in radians)
<math.h> sqrt(x) Float float Square root of x
<math.h> tan(x) Float float Tangent of x

2.9.4 Relational Operators

C++ provides six relational operators for comparing numeric quantities. These are
summarized in table below. Relational operators evaluate to 1 (representing the true
outcome) or 0 (representing the false outcome).

Operator Name Example


== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or Equal 5 <= 5 // gives 1
> Greater Than 5 > 5.5 // gives 0

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 21


Fundamental of Programming 201
O
>= Greater Than or Equal 6.3 >= 5 // gives 1
Relational operators
Note that the <= and >= operators are only supported in the form shown. In particular, =<
and => are both invalid and do not mean anything.

The operands of a relational operator must evaluate to a number. Characters are valid
operands since they are represented by numeric values. For example (assuming ASCII
coding):

'A' < 'F' // gives 1 (is like 65 < 70)

The relational operators should not be used for comparing strings, because this will result
in the string addresses being compared, not the string contents. For example, the
expression "HELLO" < "BYE" causes the address of "HELLO" to be compared to the
address of "BYE". As these addresses are determined by the compiler (in a machine-
dependent manner), the outcome may be 0 or 1, and is therefore undefined. C++ provides
library functions (e.g., strcmp) for the lexicographic comparison of string.

2.9.5 Logical operators: The logical expression is constructed from relational


expressions by the use of the logical operators not(!), and(&&), or(||).

Examples:
Example 1:
a=4, b=5, c=6

(a<b)&&(b<c) (a<b)||(b>c) !(a<b)||(c>b) (a<b)||(b>c)&&(a>b)||(a>c)


T && T T || T !(T) || T T || F && F || F
T T F || T T || F || F
T T || F
T

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 22


Fundamental of Programming 201
O
2.9.6 Increment/decrement operators

The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, adding and subtracting 1 from a numeric variable. These are summarized in
the following table. The examples assume the following variable definition:

int k = 5;
Operator Name Example
++ Auto Increment (prefix) ++k + 10 // gives 16
++ Auto Increment (postfix) k++ + 10 // gives 15
-- Auto Decrement (prefix) --k + 10 // gives 14
-- Auto Decrement (postfix) k-- + 10 // gives 15
Increment and decrement operators
Both operators can be used in prefix and postfix form. The difference is significant.
When used in prefix form, the operator is first applied and the outcome is then used in the
expression. When used in the postfix form, the expression is evaluated first and then the
operator applied. Both operators may be applied to integer as well as real variables,
although in practice real variables are rarely useful in this form.

2.10 Precedence of Operators

The order in which operators are evaluated in an expression is significant and is


determined by precedence rules. These rules divide the C++ operators into a number of
precedenc e levels. Operators in higher levels take precedence over operators in lower
levels.

Level Operator Kind Order


Highest :: Unary Both
() [] -> . Binary Left to Right
+ ++ ! * New sizeof() Unary Right to Left
- -- ~ & delete
->* .* Binary Left to Right
* / % Binary Left to Right
+ - Binary Left to Right

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 23


Fundamental of Programming 201
O
<< >> Binary Left to Right
< <= > >= Binary Left to Right
== != Binary Left to Right
& Binary Left to Right
^ Binary Left to Right
| Binary Left to Right
& Binary Left to Right
&
|| Binary Left to Right
?: Ternary Left to Right
= += *= ^= &= <<= Binary Right to Left
-= /= %= |= >>=
Lowest , Binary Left to Right

For example, in

a == b + c * d

c * d is evaluated first because * has a higher precedence than + and ==. The result is
then added to b because + has a higher precedence than ==, and then == is evaluated.
Precedence rules can be overridden using brackets. For example, rewriting the above
expression as

a == (b + c) * d

causes + to be evaluated before *.

Operators with the same precedence level are evaluated in the order specified by the last
column of Table 2.7. For example, in

a = b += c

the evaluation order is right to left, so first b += c is evaluated, followed by a = b.

Exercise:find the value of A based on precedence rule.

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 24


Fundamental of Programming 201
O
A= 20 - 4 / 5 * 2 + 3 * 5 % 4

Compiled by: Mr. Mezgebe A. Dep’t of Computer Science Page 25

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy