introduction to algorithms and programming...2 1 introduction to algorithms what is an algorithm?...

48
College of Arts and Sciences Department of Mathematical And Physical Sciences Section: Computer Sciences Introduction to Algorithms and Programming (COMP151 - 3hrs Lectures, 2hrs Labs)

Upload: others

Post on 26-Mar-2020

32 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

College of Arts and Sciences

Department of Mathematical And Physical Sciences

Section: Computer Sciences

Introduction to Algorithms

and Programming

(COMP151 - 3hrs Lectures, 2hrs Labs)

Page 2: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

2

1 Introduction to

Algorithms

What is an algorithm?

Our text defines an algorithm to be any well-defined computational procedure that

takes some values as input and produces some values as output. An algorithm

provides a step-by-step method for solving a computational problem.

An algorithm is an unambiguous sequence of simple, mechanically executable instructions.

Algorithm is a corruption of the name of the 9th century Persian mathematician Abu ’Abd

Allah Muh.ammad ibn Musa al-Khwarizmı, which literally translates as “Mohammad, father

of Adbdulla, son of Moses, the Kwarizmian” (Kwarizm is an ancient city located in what is

now the Xorazm Province of Uzbekistan.) Al-Khwˆarizmˆı is perhaps best known as the

writer of the treatise Kitab al-jabr wa’l-Muqˆabala, from which the modern word algebra

derives. The word algorithm is a corruption of the older word algorism.

Unlike programs, algorithms are not dependent on a particular programming

language, machine, system, or compiler. They are mathematical entities, which can be

thought of as running on some sort of idealized computer with an infinite random

access memory and an unlimited word size. Algorithm design is all about the

mathematical theory behind the design of good programs.

Why study algorithm design?

Programming is a very complex task, and there are a number of aspects of

programming that make it so complex. The first is that most programming projects are

very large, requiring the coordinated efforts of many people. (This is the topic a

course like software engineering.) The next is that many programming projects

involve storing and accessing large quantities of data efficiently. (This is the topic of

courses on data structures and databases.) The last is that many programming projects

involve solving complex computational problems, for which simplistic or naive

solutions may not be efficient enough. The complex problems may involve numerical

Page 3: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

3

data (the subject of courses on numerical analysis), but often they involve discrete

data. This is where the topic of algorithm design and analysis is important.

Although the algorithms discussed in this course will often represent only a tiny

fraction of the code that is generated in a large software system, this small fraction

may be very important for the success of the overall project. An unfortunately

common approach to this problem is to first design an inefficient algorithm and

data structure to solve the problem, and then take this poor design and attempt to fine-

tune its performance. The problem is that if the underlying design is bad, then often

no amount of fine-tuning is going to make a substantial difference.

The focus of this course is on how to design good algorithms. In some advanced

courses (Design and analysis of algorithms), you will study how to analyze their

efficiency. This is among the most basic aspects of good programming.

Issues in Algorithm Design:

Algorithms are mathematical objects (in contrast to the must more concrete notion of

a computer program implemented in some programming language and executing on

some machine). As such, we can reason about the properties of algorithms

mathematically.

fundamental issues When designing an algorithm

When designing an algorithm there are two fundamental issues to be considered:

o Correctness,

o Efficiency.

Algorithm Correctness

It is important to justify an algorithm’s correctness mathematically. For very complex

algorithms, this typically requires a careful mathematical proof, which may require

the proof of many lemmas and properties of the solution, upon which the algorithm

relies.

Algorithm Efficiency

Establishing efficiency is a much more complex endeavor. Intuitively, an algorithm’s

efficiency is a function of the amount of computational resources it requires,

measured typically as execution time and the amount of space, or memory, that the

algorithm uses. The amount of computational resources can be a complex function of

Page 4: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

4

the size and structure of the input set. In order to reduce matters to their simplest

form, it is common to consider efficiency as a function of input size.

Algorithm Presentation

Throughout out this course, when you are asked to present an algorithm, this means

that you need to do three things:

Present a clear, simple and unambiguous description of the algorithm

(in a flowchart or pseudo-code). They key here is “keep it simple.”

Uninteresting details should be kept to a minimum, so that the key

computational issues stand out.

Present a justification or proof of the algorithm’s correctness. Your

justification should assume that the reader is someone of similar

background as yourself, say another student in this class, and should be

convincing enough make a skeptic believe that your algorithm does

indeed solve the problem correctly. Avoid rambling about obvious or

trivial elements. A good proof provides an overview of what the

algorithm does, and then focuses on any tricky elements that may not

be obvious.

Note that the presentation does not need to be in this order. Often it is good to begin

with an explanation of how you derived the algorithm, emphasizing particular

elements of the design that establish its correctness and efficiency. Then, once this

groundwork has been laid down, present the algorithm itself. If this seems to be a bit

abstract now, don’t worry. We will see many examples of this process throughout the

semester.

Algorithm Writing Methods

There are three types of Algorithms:

Human Language Description,

Flowchart,

Pseudo-code.

Human Language Description

To design an algorithm, we can use here the following tools:

Page 5: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

5

o words and expressions derived from the human language,

o Mathematical Relations and equations,

o Both above tools.

Flowchart

Flowcharts also called "program flowcharts". The main symbols used in flowcharts

are the followings:

Operation /

Proccessing

Input / Output

Link

Start / End

Condition

Pseudo-code

Writing algorithms in pseudo-code, is better and clearer than using human

language description which can lead to misunderstood. In pseudo-code

algorithms, we can use the following words and expressions:

o Read

o Write

o Assignment symbols ) , :=(

o if/then/else

o for...do, While/do, Repeat/until.

Example:

Function F(x)

F(x)= x ;

Read x;

If 0x

F(x)=x

Else

F(x)= -x

Endif

Print (x, F(x))

End.

Page 6: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

6

Algorithm Characteristics

An algorithm must have the following characteristics:

o Precise, clear, determined and can be divided into sequenced defined steps

which can lead to the result.

o The algorithm must run and stopped after A limited and a defined number of

steps.

o The algorithm must be efficient (must lead to the right solution).

o The algorithm must be unique even there are many different processing

methods,

o The algorithm must not be dependent to any programming language.

o The algorithm must be general and acceptable to solve all identical problems.

Page 7: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

CHAPTER – 2

INTRODUCTION TO C++ PROGRAMMING

1

Page 8: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Introduction to C++ Programming Bjarne Stroustrup of AT&T Bell Laboratories

developed C++ in the early 1980s. Stroustrup designed C++ to be a better C. Most of C is a subset of C++, and so most C programs are also C++ programs. (The reverse is not true; many C++ programs are definitely not C programs.) Unlike C, C++ has facilities for classes and so can be used for object-oriented programming. C++ Program structure : Example C++ Program // My first program in C++ /*To Explain the C++ program structure This is the Best Example Program*/ #include<iostream> using namespace std; int main( ) { cout<<"This is the First Program \n"; cout<<"University of Nizwa"; return(0); } Output This is the First Program University of Nizwa 1. Comment Lines // my first program in C++ /*To Explain the C++ program structure This is the Best Example Program*/ - Explain programs to other programmers - Improve program readability - Ignored by compiler

– Single-line comment • Begin with // • Example

– // This is a text-printing program. – Multi-line comment

• Start with /* • End with */

2

Page 9: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Note: The programmer can also use them to include short explanations or observations within the source code itself. 2. Preprocessor Directive #include<iostream> is a preprocessor directive, which is the message to the C++ preprocessor. Lines that begin with # are processed by the preprocessor before the program is compiled. This line notifies the preprocessor to include in the program the contents of the input/output stream header file<iostream>. This file must be included for any program that outputs data to the screen or inputs data from the keyboard using c++ style stream input/output. 3. using namespace std All the identifiers (variables, functions, classes and objects) in the ANSI standard header files are part of the std namespace. This rule is almost as recent as the ANSI standard itself(1997) and many older compilers do not comply with this rule. In ANSI C++, cin and cout are written as std::cin and std::cout. If you do not wish to specify std:: with cin or cout (or any of the ANSI standard identifiers), you must write the following statement in your program: using namespace std; 4. Function main C++ programs begin executing at function main, even if main is not the first function in the program.

– A part of every C++ program • Exactly one function in a program must be

main – Can “return” a value – Example

• int main() – This main function returns an integer

(whole number) – Body is delimited by braces ({ })

3

Page 10: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

• Statements – Instruct the program to perform an action – All statements end with a semicolon (;)

• Stream insertion operator << – Example

• cout<<"Hello"; • Inserts the string "Hello" into the

standard output • Displays to the screen

• Escape characters – A character preceded by "\"

• Indicates “special” character output Character Name Purpose

\n New line Position the cursor to the beginning of the next line.

\t Horizontal tab Move screen cursor to the next tab stop

\\ Backslash Used to print backslash character

\’ Single quote Used to print single quote \" Double quote Used to print double quote \? Question mark Used to print question mark

Common Programming Error

• Omitting the semicolon at the end of a C++ statement is a syntax error.

• A syntax error occurs when the compiler encounters code that violates C++’s language rules (i.e., its syntax).

• The compiler normally issues an error message to help the programmer locate and fix the incorrect code.

• You will be unable to execute your program until you correct all the syntax errors in it.

4

Page 11: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Good Programming Practice Many programmers make the last character printed

by a function a new line (\n). This ensures that the function will leave the screen cursor positioned at the beginning of a new line. Identifiers

The names for variables, functions and constants are called identifiers Variables

– Location in memory where value can be stored – Common data types (fundamental, primitive or

built-in) • int – integer numbers • char – characters • float, double – floating point numbers

– Declare variables with name and data type before use

• int integer1; • int integer2; • int sum;

– Can declare several variables of same type in one declaration

• Comma-separated list • int integer1, integer2, sum;

Rules for Variable names • Valid identifier • Series of characters (letters, digits, underscores) • Cannot begin with digit • Case sensitive (ie Both Small letters and Capital

letters allowed. But both are not same variable. Example: int age,Age,AGE; Here variable age, Age and AGE are not same. All are different variable. • Can not have same name as reserved keywords. But

the Keywords in Capital Letters are allowed.

5

Page 12: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

The standard reserved keywords are: struct int double auto

switch long else break typedef register enum case union return extern char unsigned short float const void signed for continue volatile sizeof goto default while static if do

Very important:

The C++ language is a "case sensitive" language. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. These are three different variable identifiers. Note:

C++ allows identifiers of any length, but your C++ implementation may impose some restrictions on the length of identifiers. Use identifiers of 31 characters or fewer. Good Programming Practice

Choosing meaningful identifiers helps make a program self-documenting—i.e a person can understand the program simply by reading it rather than having to refer to manuals or comments.

Avoid identifiers that begin with underscores and double underscores, because C++ compilers may use names like that for their own purposes internally.

6

Page 13: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Example C++ Program: Adding Integers // program to add two integer numbers #include<iostream> using namespace std; int main( ) { int number1,number2,sum; cout<<"Enter number1 \n"; cin>>number1; cout<<" Enter number2 \n"; cin>>number2; sum=number1+number2; cout<<"Sum is :"<<sum<<endl; return(0); } Output Enter number1 12 Enter number2 5 Sum is:17 Program Explanation

• Input stream object – cin from <iostream.h>

• Usually connected to keyboard • Stream extraction operator >>

– Waits for user to input value, press Enter key

– Stores value in variable to right of operator

– Converts value to variable data type • Example

– cin>>number1; • Reads an integer typed at the

keyboard • Stores the integer in variable

number1

7

Page 14: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

• Assignment operator = – Assigns value on left to variable on right – Binary operator (two operands) – Example:

• sum=number1+number2; – Add the values of number1 and

number2 – Store result in sum

• Stream manipulator endl – Outputs a newline

• Concatenating stream insertion operations – Use multiple stream insertion operators in a

single statement – Stream insertion operation knows how to output

each type of data – Also called chaining or cascading – Example

• cout<<"Sum is :"<<sum<<endl; – Outputs "Sum is:" – Then, outputs sum of number1 and

number2 which is written in sum – Then, outputs newline

• Variable names – Correspond to actual locations in computer's

memory – Every variable has name, type, size and value – When new value placed into variable, overwrites

old value – Example

• sum=number1+number2; – Value of sum is overwritten

8

Page 15: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Common (or) fundamental (or) primitive (or) built-in Data types

Type Size Range of Values

Char 1 byte signed: -128 to 127

unsigned: 0 to 255

short int 2 bytes signed: -32768 to 32767 unsigned: 0 to 65535

int 4 bytes signed: -2147483648 to 2147483647

unsigned: 0 to 4294967295

long int 4 bytes signed: -2147483648 to 2147483647

unsigned: 0 to 4294967295

bool 1 byte true or false

float 4 bytes 3.4x10-38 to 3.4x1038

double 8 bytes 1.7x10-308 to 1.7x10308

long double 8 bytes 1.7x10-308 to 1.7x10308

Note: Some compilers use 10 bytes for long double. This allows a range of 3.4x10-4932 to 1.1x104932

Declaration of variables

In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float...) followed by a valid variable identifier. For example:

int a; float number1;

These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the

9

Page 16: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

identifier number1. Once declared, the variables a and number1 can be used within the rest of their scope in the program.

If you are going to declare more than one variable of the same type, you can declare all of them in a single statement by separating their identifiers with commas. For example: int a, b, c;

This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as: int a; int b; int c;

The integer data types char, short, long and int can be either signed or unsigned depending on the range of numbers needed to be represented. Signed types can represent both positive and negative values, whereas unsigned types can only represent positive values (and zero). This can be specified by using either the specifier signed or the specifier unsigned before the type name. For example: unsigned short int age; signed int balance;

By default, if we do not specify either signed or unsigned most compiler settings will assume the type to be signed, therefore instead of the second declaration above we could have written: int balance; with exactly the same meaning (with or without the keyword signed)

10

Page 17: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Example Program //operating with variables #include<iostream> using namespace std; int main() { //declaring variables: int a, b; int result; //process: a=5; b=2; a=a+1; result=a-b; //print out the result: cout<<result; //terminate the program: return(0); } Output 4 Scope of Variables: All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous code at the beginning of the body of the function main when we declared that a, b, and result were of type int. A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.

11

Page 18: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

#include<iostream> using namespace std; int a; char name[50]; Global variables unsigned int numberofsons; int main() { unsigned int age; Local Variables float average,percentage; cout<<”Enter your age:”; cin>>age; Instructions … } Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration. The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa. Initialization of variables

When declaring a regular local variable, its value is by default undetermined. But you may want a variable to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable. There are two ways to do this in C++:

The first one, known as c-like, is done by appending an equal sign followed by the value to which the variable will be initialized: type identifier=initial_value;

12

Page 19: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write: int a=0;

The other way to initialize variables, known as

constructor initialization, is done by enclosing the initial value between parentheses (): type identifier(initial_value) ; For example: int a(0); Both ways of initializing variables are valid and equivalent in C++. Example Program //initialization of variables #include<iostream> using namespace std; int main() { int a=5; //initial value=5 int b(2); //initial value = 2 int result; //initial value undetermined a=a+3; result=a-b; cout<<result; return(0); } Output 6

13

Page 20: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Constants Constants are expressions with a fixed value.

There are 3 types of Constants 1. Literals 2. Defined Constant 3. Declared Constant

1. Literals Literals are used to express particular values within

the source code of a program. We have already used these previously to give concrete values to variables or to express messages we wanted our programs to print out, for example, when we wrote: a=5; the 5 in this piece of code was a literal constant.

Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values. Integer Numerals 1776 707 -273

They are numerical constants that identify integer decimal values. Notice that to express a numerical constant we do not have to write quotes (") nor any special character. There is no doubt that it is a constant: whenever we write 1776 in a program, we will be referring to the value 1776.

In addition to decimal numbers (those that all of us are used to use every day) C++ allows the use as literal constants of octal numbers (base 8) and hexadecimal numbers (base 16). If we want to express an octal number we have to precede it with a 0 (zero character). And in order to express a hexadecimal number we have to precede it with the characters 0x (zero,x). For example,

14

Page 21: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

the following literal constants are all equivalent to each other: 75 // decimal 0113 // octal 0x4b // hexadecimal

All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal numeral and hexadecimal numeral, respectively. Literal constants, like variables, are considered to have a specific data type. By default, integer literals are of type int. However, we can force them to either be unsigned by appending the u character to it, or long by appending l: 75 // int 75u // unsigned int 75l // long 75ul // unsigned long Note: In both cases, the suffix can be specified using either upper or lowercase letters. Example Program #include<iostream> using namespace std; int main() { int a; long b; unsigned long c; short int d; a=45; b=189000; c=4294967295; d=12; cout<<"Memory size of integer is"<<sizeof(a)<<endl; cout<<"Value of a is"<<a<<endl; cout<<"Memory size of long integer is"<<sizeof(b)<<endl; cout<<"Value of b is"<<b<<endl; cout<<"Memory size of unsigned long integer is"<<sizeof(c)<<endl;

15

Page 22: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

cout<<"Value of c is"<<c<<endl; cout<<"Memory size of short integer is"<<sizeof(d)<<endl; cout<<"Value of d is"<<d<<endl; return(0); } Output Memory size of integer is4 Value of a is45 Memory size of long integer is4 Value of b is189000 Memory size of unsigned long integer is4 Value of c is4294967295 Memory size of short integer is2 Value of d is12 Character and string literals There also exist non-numerical constants, like: 'z' 'p' "Hello world" "How do you do?"

The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes ("). Note: When writing both single character and string literals, it is necessary to put the quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions: x 'x' x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'.

16

Page 23: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Example Program #include<iostream> using namespace std; int main() { char letter; letter='A'; cout<<letter<<endl; letter='B'; cout<<letter<<endl; cout<<"The size of char is"<<sizeof(letter)<<endl; return(0); } Output A B The size of char is1 Relation between Character and Integer Data type

We can use integer data type to store characters, because characters are internally represented by numbers. Each printable and nonprintable characters, is assigned a unique number. The most commonly used method for encoding characters is ASCII, which stands for American Standard Code for Information Interchange.

When a character is stored in memory, it is actually the numeric code that is stored. When the computer is instructed to print the value on the screen, it displays the character that corresponds with the numeric code.

Notice that the number 65 is the code for ‘A’, 66 is the code for ‘B’ and so on. For small letter ‘a’ the code is 97, and for ‘b’ 98 and so on. For the character ‘0’(zero when it is the character type) the code is 48, for the character ‘1’(one when it is character type) the code is 49 and so on.

17

Page 24: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Example Program #include<iostream> using namespace std; int main() { char letter; int n; letter=48; cout<<letter<<endl; letter=97; cout<<letter<<endl; n='9'; cout<<n<<endl; n='Z'; cout<<n<<endl; return(0); } Output 0 a 57 90 Floating Point Numbers

Floating point numbers are stored in a manner similar

to scientific notation. Take the number 47,281.97. In scientific notation this number is 4.728197 x 104. (104 is equal to 10,000, and 4.728197 x 10,000 is 47,281.97). The first part of the number 4.728197 is called the mantissa. The mantissa is multiplied by a power of ten. Computers typically use E notation to represent floating point values. In E notation, the number 47,281.97 would be 4.728197E4. The part of the number before the E is the mantissa, and the part after the E is the power of 10. When the floating point number is stored in memory, it is stored as the mantissa and the power of 10.

18

Page 25: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Decimal Notation Scientific Notation E notation 247.91 2.4791 x 102 2.4791E2 0.00072 7.2 x 10-4 7.2E-4 2,900,000 2.9 x 106 2.9E6

In C++ there are three data types that can represent floating point numbers. They are

float double long double The float type is considered single precision. The

double data type is usually twice as big as float, so it is considered double precision. As you have probably guessed, the long double is intended to be larger than the double. The default type for floating point literals is double. If you explicitly want to express a float or long double numerical literal, you can use the f or l suffixes respectively: 3.14159L // long double 6.02e23f // float Example Program #include<iostream> using namespace std; int main() { float distance; double mass; distance=1.495979E11f; mass=1.989E30; cout<<"The Sun is"<<distance<<"meters away \n"; cout<<"The Sun's mass is"<<mass<<"kilograms \n"; cout<<"The size of float is"<<sizeof(distance)<<endl; cout<<"The size of double is"<<sizeof(mass)<<endl; cout<<"The size of long double is"<<sizeof(long double)<<endl; return(0); } Output The Sun is 1.49598e+011meters away

19

Page 26: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

The Sun’s mass is 1.989e+030 kilograms The size of float is4 The size of double is8 The size of long double is8 Note: in the source code the literals were written as 1.495979E11 and 1.989E30, but the program printed them as 1.49598e+011 and 1.989e+030. The two sets of numbers are equivalent. (The plus sign in front of the exponent is also optional). Note: Any of the letters than can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters without any difference in their meanings. Boolean literals

There are only two valid Boolean values: true and false. These can be expressed in C++ as values of type bool by using the Boolean literals true and false. The bool data type allows you to create small integer variable that are suitable to holding true or false values. Example Program #include<iostream> using namespace std; int main() { bool va; va=true; cout<<va<<endl; va=false; cout<<va<<endl; return(0); } Output 1 0 As you can see from the program output, the value true is represented in memory by the number 1, and the false is represented by 0.

20

Page 27: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

2. Defined constants (#define) You can define your own names for constants that

you use very often without having to resort to memory consuming variables, simply by using the #define preprocessor directive. Its format is: #define identifier value For example: #define PI 3.14159265 #define NEWLINE '\n'

This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code as if they were any other regular constant, for example: Example Program //defined constants: calculate circumference #include<iostream> using namespace std; #define PI 3.14159 #define NEWLINE '\n' int main() { double r=3.5; double circle; circle=2*PI*r; cout<<circle; cout<<NEWLINE; return(0); } Output: 21.9911

In fact the only thing that the compiler preprocessor does when it encounters #define directives is to literally replace any occurrence of their identifier (in the previous example, these were PI and NEWLINE) by the code to

21

Page 28: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

which they have been defined (3.14159265 and'\n' respectively).

Note: The #define directive is not a C++ statement but a directive for the preprocessor; therefore it assumes the entire line as the directive and does not require a semicolon (;) at its end. If you append a semicolon character (;) at the end, it will also be appended in all occurrences within the body of the program that the preprocessor replaces. 3. Declared constants (const)

With the const prefix you can declare constants with a specific type in the same way as you would do with a variable: const int pathwidth = 100; const char tabulator = '\t';

Here, pathwidth and tabulator are two typed

constants. They are treated just like regular variables except that their values cannot be modified after their definition. Any attempt to alter the value of a variable defined with const will give an error from the compiler. Manipulators:

Manipulators are operators used with the insertion operator << to modify or manipulate the way of data display. 1. The endl Manipulator:

This is a manipulator that causes a linefeed to be inserted into the stream. It has the same effect as sending the single ‘\n’ character. 2. The setw(n) Manipulator:

You may think of each value displayed by cout as occupying a field: an imaginary box with a certain width. The default field is just wide enough to hold the value. That is, the integer 567 will occupy a field three characters

22

Page 29: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

wide, and the string “pajamas” will occupy a field seven characters wide. However, in certain situations this may not lead to optimal results. Here’s an example. The width1 program prints the names of three cities in one column, and their populations in another. Example Program 1 //width1.cpp //demonstrates need for setw manipulator #include<iostream> using namespace std; int main() { long int pop1=2425785,pop2=47,pop3=9761; cout<<”LOCATION ”<<”POPULATION”<<endl; cout<<”Portcity ”<<pop1<<endl; cout<<”Hightown ”<<pop2<<endl; cout<<”Lowville ”<<pop3<<endl; return(0); } Output L O C A T I O N P O P U L A T I O N P o r t c i t y 2 4 2 5 7 8 5 H i g h t o w n 4 7 L o w v i l l e 9 7 6 1

Unfortunately, the output of this program is not ideal. It’s hard to compare the numbers. It would be better if they lined up to the right. Also, we had to insert spaces into the names of the cities to separate them from numbers. This is an inconvenience.

Here’s a variation of this program, width2, that uses setw manipulator to eliminate these problems by specifying field widths for the names and numbers:

23

Page 30: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Example Program 2 //width2.cpp //demonstrate the setw manipulator #include<iostream> #include<iomanip> using namespace std; int main() { long int pop1=2425785,pop2=47,pop3=9761; cout<<setw(8)<<”LOCATION”<<setw(12)<<”POPULATION”<<endl; cout<<setw(8)<<”Portcity”<<setw(12)<<pop1<<endl; cout<<setw(8)<<”Hightown”<<setw(12)<<pop2<<endl; cout<<setw(8)<<”Lowville”<<setw(12)<<pop3<<endl; return(0); } Output L O C A T I O N P O P U L A T I O N P o r t c i t y 2 4 2 5 7 8 5 H i g h t o w n 4 7 L o w v i l l e 9 7 6 1

The setw manipulator causes the number or string that follows it in the stream to be printed within a field n characters wide, where n is the argument to setw(n). The value is right-justified within the field. If we want to display the output in left justified manner we can do the same with setw() manipulator. The keyword left should be given after setw(n). Once the default (right justified) is changed with left alignment then all the setw(n) follows the left alignment. Again if you want to change the right then you have to give the right keyword after the corresponding setw(n).Since this is the default, it is only used to override the effects of left. Only useful after setw(n).

24

Page 31: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Example Program #include<iostream> #include<iomanip> using namespace std; int main() { cout<<setw(10)<<left<<"Hello"<<setw(10)<<"Hello"<<endl//1st hello and 2nd hello both aligned in left manner cout<<setw(10)<<left<<"Hello"<<setw(10)<<right<<"Hello"<<endl; //1st hello is left aligned and 2nd hello right aligned return(0); } Output H e l l o H e l l o H e l l o H e l l o 3. setprecision(n) Manipulator This manipulator sets the number of digits printed to the right of the decimal point. This applies to all subsequent floating point numbers written to that output stream. Example program #include<iostream> #include<iomanip> using namespace std; int main() { double b=0.234009; cout<<setprecision(2)<<b<<endl; return(0); } Output 0.23 Note: When you use these manipulators you must insert #include<iomanip> header file in your program.

25

Page 32: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Exercises: 1. A function name must be followed by____ - 1 Mark 2. A function body is delimited by_________ - 1 Mark 3. Why is the main() function special? - 1 Mark 4. Specify how many bytes are occupied by the following

data types in Microsoft C/C++ - 2 Marks a).Type int b).Type long double c).Type float b).Type long int

5. True or False: A variable of type char can hold the value 301 - 1 Mark

6. What kind of program elements are the following? a).12 - 2 Marks b).’a’ c).4.28915 d).JungleJim e).JungleJim()

7. Write statements that display on the screen - 3 Marks a).The character ‘x’ b).The name Jim c).The number 509

8. What header file must you #include with your source file to use cout and cin? - 1 Mark

9. Write a statement that gets a numerical value from the keyboard and places it in the variable temp. - 1 Mark

10. What header file must you #include with your program to use setw? - 1 Mark 11. True or False: 1. Local variables can be accessed anywhere in the program. 2.constant variable values can be modified in the program - 2 Marks 12. Write a program that generates the following table:

1990 135 - 2 Marks 1991 7290 1992 11300

1993 16200 1994 1123467

26

Page 33: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

13. Write a program to display the following - 2 Marks # ## ### #### 14. Write a program to display the following - 2 Marks 1 1 2 1 2 3 1 2 3 4 15. Which of the following is(are) proper identifier(s)? Give

the reason also - 3 Marks a).3digit b)._name c).State d).signed e).ABC f).REGISTER g).Form23 h).Distance_to_calculate i).hEllO 16. Write a program to display the following - 2 Marks ???? ??? ?? ? 17. Identify the following literals - 3 Marks a).123.45 b).5.64567L c).90L d).45u e).79uL f).1.23e12f g).-456 h).0xAA i).062 j).”hai”

27

Page 34: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

CHAPTER - 3

OPERATORS IN C++

1

Page 35: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Operators Once we know of the existence of variables and

constants, we can begin to operate with them. For that purpose, C++ integrates operators. Unlike other languages whose operators are mainly keywords, operators in C++ are mostly made of signs that are not part of the alphabet but are available in all keyboards. This makes C++ code shorter and more international, since it relies less on English words, but requires a little of learning effort in the beginning. Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by the C++ language are: + Addition - Subtraction * Multiplication / Division % Modulo

Operations of addition, subtraction, multiplication and division literally correspond with their respective mathematical operators. The only one that you might not be so used to see is modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the remainder of a division of two values. For example, if we write: a = 11 % 3; the variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3. Common Programming Error Attempting to use the modulus operator (%) with non-integer operands is a compilation error

2

Page 36: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

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 whereas 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 the value of b to a. So the value of a is overwritten by the value of b.

Example program //assignment operator #include<iostream> using namespace std; int main() { int a,b; a=10; b=4; a=b; b=7; cout<<"a="<<a<<endl; cout<<"b="<<b; return(0); } Output a=4 b=7

3

Page 37: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

This code will give us as result that the value contained in a is 4 and the one contained in b is 7. Notice how a was not affected by the final modification of b, even though we declared a = b earlier (that is because of the right-to left rule). Compound assignment (or) Arithmetic assignment operators (+=, -=, *=, /=, %=): d-=4 means (d = d - 4) e*=5 means (e = e * 5) f/=3 means (f = f / 3) g%=9 means (g = g % 9)

Assignment operator

Sample expression

Explanation Assigns

Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += c += 7 c = c + 7 10 to c -= d -= 4 d = d - 4 1 to d *= e *= 5 e = e * 5 20 to e /= f /= 3 f = f / 3 2 to f %= g %= 9 g = g % 9 3 to g

// compound assignment operators Example Program #include<iostream> using namespace std; int main () { int a, b=3; a=b; a+=2; // equivalent to a=a+2 cout<<a; return(0); }

4

Page 38: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Output 5 Increment and Decrement Operators

• Increment operator ++ – Increments variable by one

• Example c++ means c=c+1 or c+=1;

• Decrement operator -- – Decrement variable by one

• Example c--means c=c-1 or c-=1;

• Pre-increment

– When the operator is used before the variable (++c) Value of the variable c is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression

• Post-increment – When the operator is used after the variable (c++)

Value stored in variable c is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression.

Operator Called Sample expression Explanation

++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides.

++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.

-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.

-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.

5

Page 39: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Example 1 B=3; A=++B; // A contains 4, B contains 4 Example 2 B=3; A=B++; // A contains 3, B contains 4

In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased. Good Programming Practice

Unlike binary operators, the unary increment and decrement operators should be placed next to their operands, with no intervening spaces. Example Program //Pre-incrementing and Post-incrementing.#include<iostream> using namespace std; int main() { int c; // demonstrate post-increment c=5; // assign 5 to ccout<<c<<endl; // print 5 cout<<c++<<endl; // print 5 then post-incrementcout<<c<<endl; // print 6cout<<endl; // skip a line// demonstrate pre-incrementc=5; // assign 5 to ccout<<c<<endl; // print 5cout<<++c<<endl;// pre-increment then print 6cout<<c<<endl; // print 6return(0); }

6

Page 40: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Output 5 5 6 5 6 6

Note:

• If c = 5, then – cout<<++c;

• c is changed to 6 • Then prints out 6

– cout<<c++; • Prints out 5 (cout is executed before the

increment) • c then becomes 6

• When variable is not in an expression – Pre-incrementing and Post-incrementing have

same effect • Example

• ++c; cout<<c; and c++; cout<<c; are the same

Relational and equality operators ( ==, !=, >, <, >=, <= )

In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result. We may want to compare two expressions, for

7

Page 41: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in C++: == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to Here there are some examples: (7==5) // evaluates to false. (5>4) // evaluates to true. (3!=2) // evaluates to true. (6>=6) // evaluates to true. (5<5) // evaluates to false.

Of course, instead of using only numeric constants, we can use any valid expression, including variables. Suppose that a=2, b=3 and c=6 (a==5) // evaluates to false since a is not equal to 5. (a*b>=c) // evaluates to true since (2*3 >= 6) is true. (b+4>a*c) // evaluates to false since (3+4 > 2*6) is false. ((b=2)==a) // evaluates to true. Common Programming Error

• A syntax error will occur if any of the operators ==, !=, >= and <= appears with spaces between its pair of symbols.

• Confusing the equality operator == with the assignment operator = results in logic errors.

• The equality operator should be read “is equal to,” and the assignment operator should be read “gets” or “gets the value of” or “is assigned the value of.”

• Some people prefer to read the equality operator as “double equals.”

8

Page 42: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Logical operators ( !, &&, || ) ! Operator The operator ! is the C++ operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand.

For example: !(5 ==5) // evaluates to false because the expression at its right (5 == 5) is true. !(6<= 4) // evaluates to true because (6<=4) would be false. !true // evaluates to false !false // evaluates to true.

&& OPERATOR

The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a&&b:

9

Page 43: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

|| OPERATOR The operator || corresponds with Boolean logical

operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. Here are the possible results of a || b:

For example: ((5==5)&&(3>6)) // evaluates to false (true && false). ((5==5)||(3>6)) // evaluates to true (true || false). Conditional operator ( ? : ) or Ternary Operator

The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is: condition ? result1 : result2 If condition is true the expression will return result1, if it is not it will return result2. 7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5. 7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2. 5>3 ? a : b // returns the value of a, since 5 is greater than 3. a>b ? a : b // returns whichever is greater, a or b.

10

Page 44: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Example Program //conditional operator #include<iostream> using namespace std; int main() { int a,b,c; a=2; b=7; c=(a>b)?a:b; cout<<c; return(0); } Output 7

In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true, thus the first value specified after the question mark was discarded in favor of the second value (the one after the colon) which was b, with a value of 7. Explicit type casting operator

Type casting operators allow you to convert a datum of a given type to another. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses ()

int i; float f =3.14; i=(int)f;

The previous code converts the float number 3.14 to an integer value (3), the remainder is lost. Here, the typecasting operator was (int).

11

Page 45: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Another way to do the same thing in C++ is using the functional notation: preceding the expression to be converted by the type and enclosing the expression between parentheses: i=int(f); Both ways of type casting are valid in C++. sizeof()

This operator accepts one parameter, which can be either a type or a variable itself and returns(integer) the size in bytes of that type or object: int a; a=sizeof(char);

This will assign the value 1 to a, because char is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution. Precedence of operators

When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression: a = 5 + 7 % 2 We may doubt if it really means: a = 5 + (7 % 2) // with a result of 6, or a = (5 + 7) % 2 // with a result of 0 The correct answer is the first of the two expressions, with a result of 6.

12

Page 46: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Precedence of arithmetic operators – Operators in parentheses evaluated first – Multiplication, division, modulus applied next

• Operators applied from left to right – Addition, subtraction applied last

• Operators applied from left to right

Operator(s) Operation(s) Order of evaluation (precedence)

( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.

*

/

%

Multiplication

Division

Modulus

Evaluated second. If there are several, they are evaluated left to right.

+ -

Addition Subtraction

Evaluated last. If there are several, they are evaluated left to right.

All these precedence levels for operators can be manipulated or become more legible by removing possible ambiguities using parentheses signs ( and ), as in this example: a=5+7%2; might be written either as: a=5+(7%2); or a=(5+7)%2; depending on the operation that we want to perform.

So if you want to write complicated expressions and you are not completely sure of the precedence levels, always include parentheses. It will also become a code easier to read.

13

Page 47: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but for all the operators which can appear in C++. Associativity: In the above table we mentioned that if there are several operators in the same precedence then it is evaluated from left to right. It is called as Associativity of operator. In c++ the binary operators *,/,%,+,- are all left associative. That is, it is evaluated from left to right when the expression having the same operator. Example: 9-5-1 means (9-5)-1=4-1=3 Good Programming Practice Using redundant parentheses in complex arithmetic expressions can make the expressions clearer. Example

14

Page 48: Introduction to Algorithms and Programming...2 1 Introduction to Algorithms What is an algorithm? Our text defines an algorithm to be any well-defined computational procedure that

Exercises 1. The expression 19 % 4 evaluates to ______ - 1 Mark 2. The increment operator increases the value of a

variable by how much? - 1 Mark 3. Assuming var1 starts with the value 20, what will the

following code fragment print out? - 2 Marks cout<<var1--; cout<<++var1;

4. Write a program to generate the following output - 2 Marks 10 20 19 Use an integer variable to set the value 10, an arithmetic assignment operator to generate the 20, and a decrement operator to generate the 19.

5. Write a program to find a given year is leap year or not through conditional operator. - 2 Marks

6. Evaluate the following expressions: - 4 Marks a).z=7*10-5%3*4+9 b).y=(7*(10-5)%3)*4+9 c).t=12-4+15/3%5*2+6*2 d).x=5+3+8*9+6*4

7. Show the order of evaluation and find the final result for each of the following expression. - 3 Marks Assume x=6 y=3 z=2 w=1

1. R= x*(y+z*w-1)%(y+1) 2. R=(x+1)*(y-1)/(w+z%2)

15