introduction to c++ and language building blocks

67
INTRODUCTION TO C++ AND ITS LANGUAGE BUILDING BLOCKS Engineer Jokhio Sultan Salahuddin Kohistani Lecturer, Computer Systems Engineering, MUET Jamshoro E-mail: [email protected] Facebook: http://www.facebook.com/salahuddinjokhio http://www.twitter.com/engrsalahuddinj

Upload: sultan-salahuddin-jokhio

Post on 21-Apr-2015

192 views

Category:

Documents


0 download

DESCRIPTION

A basics lecture notes on C++

TRANSCRIPT

Page 1: Introduction to C++ and Language Building Blocks

INTRODUCTION TO C++ AND ITS

LANGUAGE BUILDING BLOCKS

Engineer Jokhio Sultan Salahuddin Kohistani

Lecturer, Computer Systems Engineering, MUET Jamshoro E-mail: [email protected]

Facebook: http://www.facebook.com/salahuddinjokhio

http://www.twitter.com/engrsalahuddinj

Page 2: Introduction to C++ and Language Building Blocks

Reference Books

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

2

Object Oriented Programming in C++

By Robert Lafore.

4th Edition or latest

This book will be used as text book.

For Further Studies, you may buy;

C++, How to Program

By Dietel and Dietel.

C++, The Complete Reference

By Herbert Scheldt.

Page 3: Introduction to C++ and Language Building Blocks

Programming

Programming is all about making the computer to do your own desired work.

“Computer is like a husband”, will do any thing that is said in well format and language according to appropriate language rules.

Programming is the art and science of instructing the computer (in an specific language) to do and carry out the said work according to the programmer‟s desires and intents.

Requires lot of interest and hard work.

Also requires analytical ability (as we are about to solve problems).

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

3

Page 4: Introduction to C++ and Language Building Blocks

Mastering the programming

You must have Brain.

You must know tactics, such as how to use your Brain?

Draw rough sketch (or flow or solution) in your mind.

Program on a rough page (graphical using flow chart).

Don‟t directly use interactive, intelligent compilers to

write programs. Better to do with editors like notepad.

Make Mistakes and try to correct them.

Think out of Box.

Practice, Practice and Practice.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

4

Page 5: Introduction to C++ and Language Building Blocks

Practice

Common English proverb, “Practice Makes the Man

perfect”.

Chinese Proverb,

“I hear, I forget;

I see, I remember;

I do, I understand.”

So, Practice as much as you can to master the

programming.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

5

Page 6: Introduction to C++ and Language Building Blocks

Learning Approaches

Top Down.

Start from advance and cover the basics as you move further.

Used in west.

First build the roof then basic blocks.

Bottom Up.

Vice versa of Top Down Approach.

Our Approach.

Both approaches parallel.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

6

Page 7: Introduction to C++ and Language Building Blocks

Computer Languages

High level Computer Languages

Syntax and Semantics(Rules of Language) very much similar to

daily life English sentences and phrases.

Easier to learn and easier to implement (to write code) very

difficult and complex logics.

C++, Java, PHP, ASP.NET, C#.NET all are high level languages.

Require either Compiler or Interpreter (or both) to translate

into respective Machine code (so that computer can

understand).

Mostly used to write Consumer and Enterprise Software

Applications.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

7

Page 8: Introduction to C++ and Language Building Blocks

Computer Languages

Medium level Computer Languages

Syntax and Semantics are short hand or stenographic representations of commands and phrases.

For MOVE, we have mov keyword, for INSERT, we have ins keyword and so on.

Assembly Languages for programming Microprocessors, Microcontrollers all are Medium level languages.

Bit harder to difficult.

Requires knowledge of hardware.

Requires Assembler to translate into respective machine code.

Harder to learn.

Implementing complex logic may be difficult, but still applicable.

Used to write control programs for industry control systems, air control systems and other automation projects.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

8

Page 9: Introduction to C++ and Language Building Blocks

Computer Languages

Low Level Language

Ones and Zeroes.

Extremely hard to understand for humans.

Understood by Computers only.

1 0 1 1 0 1 1

What

the hell

this

string

mean?

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

9

Page 10: Introduction to C++ and Language Building Blocks

Towards C++ Language

Machine Language

“A” Language,

an Assembly Language

BCPL Language

B Language

C Language

C++ Language

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

10

Page 11: Introduction to C++ and Language Building Blocks

C & C++ Language.

C is structured or Functional programming language.

Working on procedural methodology.

Also offers Assembly Language to be embedded inside C code.

C++, in addition to classic C Features, also offers

programming capability in Object Oriented Paradigm.

Object Oriented Paradigm offers depiction of real world in

programming and is including following key features.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

11

Page 12: Introduction to C++ and Language Building Blocks

Object Oriented Programming

OOP

Polymorphism

Abstraction

Encapsulation

Inheritance

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

12

Page 13: Introduction to C++ and Language Building Blocks

Object Oriented Programming

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

13

Abstraction

Ideas about problem solving. Rough Sketches.

Polymorphism

One thing having poly (many) morphs (shapes).

Inheritance

Allow child programs to inherit different properties from the

parent programs.

Encapsulation

Provides means of security, by encapsulating (closing and

hiding) the data inside its object with certain attributes. Like

capsules encapsulates medication.

Page 14: Introduction to C++ and Language Building Blocks

Compilation of a C++ Program

Editing Preprocessing Compiling Linking Executing

A .cpp

File

This

requires

an editor

in which

programs

are

written

mostly in

notepad

Headers files and

namespaces

Since header

files are

imported

into the

source code,

to assure the

compatibility

this is done.

Its automatic

A single .obj File

or multiple

Here

translation

is done

from c++

to

respective

code

An exe

Executable File

Here

translated

obj files

and library

files are

combined

and one

exe file is

created

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

14

Page 15: Introduction to C++ and Language Building Blocks

Steps to execute a C++ Program

1. Editing: Requires an editor program to write the source

code and must be saved as one of the extension

formats as .cpp, .C.

2. Compilation

1. Preprocessing: A C Preprocessor actually looks for the

imported files and classes and collect them for compiling, it

works on seeing the preprocessor directives.

2. Compilation: Program is compiled and Machine language

code for the respective platform is generated.

3. Linking: Compiled Libraries and others are linked.

4. Executing: .exe file is executed then to run the program.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

15

Page 16: Introduction to C++ and Language Building Blocks

Basic C++ Program Structure

Preprocessor Directives

Using Directive

Start of Main Function

Program Statements

End of Main Function

Mostly some constants are

declared.

Namespaces are used to

identify different names.

This is where the execution

starts.

These all Program statements

are executed.

Execution Stops here.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

16

Page 17: Introduction to C++ and Language Building Blocks

Basic Program outline

#include <some header file>

using namespace namespace-name

int main( ){

Statement(s) come here.

return 0;

}

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

17

Page 18: Introduction to C++ and Language Building Blocks

Basic C++ Program

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

18

Page 19: Introduction to C++ and Language Building Blocks

An Alternative Version

#include <iostream>

int main()

{

std::cout << “Every age has a

language of its own\n”;

return 0;

}

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

19

Page 20: Introduction to C++ and Language Building Blocks

#include <iostream>

The # sign, indicates the use of any preprocessor directive. In this case include is the preprocessor directive.

Preprocessor directives are not part of the program, but they are instructions to the compiler, and preprocessor, a part of compiler program, deals with them.

It tells the compiler to include the header files in the program.

In older versions of C++, extension for header file (.H) was required.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

20

Page 21: Introduction to C++ and Language Building Blocks

#include <iostream>

This iostream header file actually contains the definition

of cout, << operator and other basic input/output

operations.

Other header files could be found in the include folder of

your compiler.

Some common header files are math, ctype, dos, io etc.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

21

Page 22: Introduction to C++ and Language Building Blocks

using namepace std;

The using is another directive, which is used to import

namespaces inside the program.

Each using command must end with a semicolon (;).

Namespace is the part of program, which identifies

different names and items inside c++ program statements.

The using directive tells the program that statements

inside main will be recognized using the std (standard)

namespace.

cout is also identified inside std namespace.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

22

Page 23: Introduction to C++ and Language Building Blocks

int main( )

main is the perhaps the most essential part of any C++

program, which acts as the entry point for statement

execution.

The Parenthesis followed by main keyword tell the

compiler that it‟s the the function, and main shows that it

is the main function.

Statement inside main are actually executed.

Braces limit the function‟s boundary. { tells the starting of

the function, while } tells the ending of the function.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

23

Page 24: Introduction to C++ and Language Building Blocks

cout << “Hello”;

An statement must end with semicolon ( ; ).

cout (console-out) is an standard output object which is

sending out to the standard connected output device.

Mostly Monitor is the standard output object.

The thing enclosed in “ “ will appear as it would be inside

it.

The “\n” will insert a new line after the output, and will

force the cursor to blink on the next line.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

24

Page 25: Introduction to C++ and Language Building Blocks

return 0;

0 is going to be returned to operating system by main

function, which indicates the ending of program and

operating systems frees the memory (RAM) space, which

was occupied by the program

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

25

Page 26: Introduction to C++ and Language Building Blocks

White Spaces and Blanks

White Spaces and Blanks are ignored by the compiler.

They are mostly for human readability. #include<iostream>

using namespace std;

int main(){

cout<<“Hello World!”;

return 0;

}

Each Header File must be written on

separate line, and space between #include

and <iostream> is not necessary. While the

space between using and namespace and

namespace‟s name is important. Space

between int and main is also necessary. So

there should be space between C++

reserved keywords. They also must not be

used for some other purpose. The Ending

bracket can also be put anywhere after the

return 0‟s semicolon.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

26

Page 27: Introduction to C++ and Language Building Blocks

C++ Keywords

These are part of the C++ Language.

They can not be used for any other purpose than their

defined operation.

In previous program, include, using, namespace, int, main,

cout, return, they were all c++ reserved keywords.

They even can not be used to define **variables.

**Variables will be studied soon in future classes.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

27

Page 28: Introduction to C++ and Language Building Blocks

cout

console out displays different data on the screen.

For string (a sequence of characters), enclose it into the

double quotes. E.g. cout<<“This is a Program”;

For a single character, single quotes E.g. cout<<„A‟;

For any number, without quotes or with quotes works

same. e.g. cout<<123; e.g. cout<<“123”;

Without quotes, it also performs the arithmetic

operation.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

28

Page 29: Introduction to C++ and Language Building Blocks

cout

cout << “12a34”;

cout << “af4”;

cout<<“ ”;

cout<<„ ‟;

cout<<1+3;

cout<<1243;

cout<<“123+654”;

cout>>asd;

cout>>as23asc;

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

29

Page 30: Introduction to C++ and Language Building Blocks

Cascading cout with <<

We can display multiple outputs in single cout statement

by cascading the << several times. So,

cout<<“Hello\n”<<123<<234+56; is equal to three

cout statements.

cout<<“Hello\n”;

cout<<123;

cout<<234+56;

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

30

Page 31: Introduction to C++ and Language Building Blocks

Comments

They are not executed but are ignored by the compiler.

They are just for writing some message for future

reference purpose.

Two Types:

Single Line Comments & Multi- Line Comments

Single Line Comments

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

31

Page 32: Introduction to C++ and Language Building Blocks

Multi-Line comments

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

32

Page 33: Introduction to C++ and Language Building Blocks

Escape Sequences

They are some special characters

Do not appear on the screen, rather their effect can be seen,

sensed and felt.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

33

Page 34: Introduction to C++ and Language Building Blocks

Manipulators

They are some keywords, which are used to manipulate

(modify/change) the output from its original appearance.

endl Manipulator

Inserts a new line, and is used with cout statement.

cout<< “Hello”<<endl<<“Bye”;

setw Manipulator

Inserts a some spaces in the output, and is used with cout

statement.

Also requires header file named iomanip

cout<< “Hello”<<setw(12)<<“Bye”;

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

34

Page 35: Introduction to C++ and Language Building Blocks

// width2.cpp

// demonstrates setw manipulator

#include <iostream>

#include <iomanip> // for setw

using namespace std;

int main()

{

long pop1=2425785, pop2=47, pop3=9761;

cout << setw(8) << “LOCATION” << setw(12)

<< “POPULATION” << endl

<< setw(8) << “Portcity” << setw(12) << pop1 << endl

<< setw(8) << “Hightown” << setw(12) << pop2 << endl

<< setw(8) << “Lowville” << setw(12) << pop3 <<

endl;

return 0;

}

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

35

Page 36: Introduction to C++ and Language Building Blocks

Output

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

36

Page 37: Introduction to C++ and Language Building Blocks

Data Types

Data Have Different Types

Numeric

Integers (Whole numbers)

short, int and long

Floating point Numbers

float and double

Characters

char

True/False

bool (for boolean true/false values)

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

37

Page 38: Introduction to C++ and Language Building Blocks

Data Types Summary

Note: You don‟t need to remember this entire table, what you have to

remember, is the exact name of the data-type.

Now you have every reason to smile. Smile please but

not to laugh, this is not that much easy. Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

38

Page 39: Introduction to C++ and Language Building Blocks

Variables

Place Holders for Data.

Named Memory Location inside RAM.

They are allowed to change their values.

For declaring variable we must:

Name it

declare its type (type of data, which will be

held) as well.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

39

Page 40: Introduction to C++ and Language Building Blocks

Variable Naming Rules

C++ Keyword can not be assigned.

Must begin with a English letter or an underscore (_).

Can not begin with a number.

Names must be meaningful.

Names can not be repeated.

Different cases can be used.

Name can-not contain spaces, but underscores (_) and

Hyphens (-) are allowed.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

40

Page 41: Introduction to C++ and Language Building Blocks

variable Declaration & Assignment.

Declaration

data-type name;

int number1;

Assignment

name = value;

number1 = 50;

Declaration+Assignment

data-type name = value;

int number1 = 50;

50

number1

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

41

Page 42: Introduction to C++ and Language Building Blocks

Variables short var0 = 51;

int var1 = 5000;

long var2 = 100000000L;

float var3 = 0.52354F;

double var4 = 45.236644478;

bool isPrime = true; or bool isPrime = 1;

char English1 = „A‟;

The single statement is equivalent to two statements like,

int num1 = 35678;

its equivalent to:

int num1;

num1 = 35678;

Adopt the way you love to do!

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

42

Page 43: Introduction to C++ and Language Building Blocks

Program // charvars.cpp

// demonstrates character variables

#include <iostream> //for cout, etc.

using namespace std;

int main()

{

char charvar1 = „A‟; //define char variable as character

char charvar2 = „\t‟; //define char variable as tab

cout << charvar1; //display character

cout << charvar2; //display character

charvar1 = „B‟; //set char variable to char constant

cout << charvar1; //display character

cout << „\n‟; //display newline character

return 0;

}

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

43

Page 44: Introduction to C++ and Language Building Blocks

Constants

Constants are not allowed to change their values.

In ANSI C++, constants are defined with const keyword.

While in older version constants were implemented by

using #define directive.

#define being pre-processor directive must be defined at

the top of program, while const keyword can be used

anywhere inside the function (main in this case).

Constant‟s name must contain all capital letters to

distinguish it from conventional variables.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

44

Page 45: Introduction to C++ and Language Building Blocks

Constants

Let‟s suppose we want to define one constant, like PI in

the following example.

Using #define directive

#define PI 3.1415

Using const keyword

const float PI = 3.1415;

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

45

Page 46: Introduction to C++ and Language Building Blocks

Operators

Arithmetic

+ (Addition)

- (Subtraction)

* (Multiplication)

/ (Division)

% (Remainder Operator)

To be covered.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

46

Page 47: Introduction to C++ and Language Building Blocks

// circarea.cpp

// demonstrates floating point variables

#include <iostream> //for cout, etc.

using namespace std;

int main()

{

float rad; //variable of type float

const float PI = 3.14159F; //type const float

cout << “Enter radius of circle: “; //prompt

cin >> rad;

float area = PI * rad * rad; //find area

cout << “Area is “ << area << endl; //display answer

return 0;

}

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

47

Page 48: Introduction to C++ and Language Building Blocks

The Remainder Operator (%) Calculates the remainder

// remaind.cpp

// demonstrates remainder operator

#include <iostream>

using namespace std;

int main()

{

cout << 6 % 8 << endl // 6

<< 7 % 8 << endl // 7

<< 8 % 8 << endl // 0

<< 9 % 8 << endl // 1

<< 10 % 8 << endl; // 2

return 0;

}

3)10(3

-9

= 1

(remainder)

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

48

Page 49: Introduction to C++ and Language Building Blocks

Expressions in C++

First parenthesis are solved, they multiplication, division and

remainder (%) operator are solved and then finally addition

and subtraction is carried out and result is assigned to the

L.H.S. So, Assignment (=) Operator has the lowest priority.

(ftemp-32) * 5 / 9 //ftemp is pre-defined variable.

There should be a single variable name at Left hand side of the

equation (unlike conventional Math's equation having multiple

variables on both sides) and all other things on the Right hand

side.

So, x+3 = 2y -5 in Maths.

But in C++, x= 2y-5-3 or y = (x+3+5) /2.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

49

Page 50: Introduction to C++ and Language Building Blocks

Expressions in C++

X+3 = Y-2

L.H.S

R.H.S

X = Y-2-3;

L.H.S

R.H.S

Y= X+3+2;

L.H.S

R.H.S

But in C++, we must only keep a

variable name on L.H.S and all others

(Numbers, variables etc) on the either

side (R.H.S).

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

50

Page 51: Introduction to C++ and Language Building Blocks

Integer Division Rule

Two Axioms/Principles.

If Both the operators are integers, result must also be

integer.

If one of the operator is floating-point number or both

are floating-point numbers, then result must also be a

floating point number.

So, cout<<9/5; will display 1.

To see actual result, either keep one number as Floating

point or both as floating point. cout<<9.0/5; cout<<9/5.0;

cout<<9.0/5.0;

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

51

Page 52: Introduction to C++ and Language Building Blocks

Input with cin

Used to input some data inside variable.

cin>>variable-name;

The variable-name is the name of the variable where the

data (which will be inputted by the user) will be stored.

So, After cin, unlike cout, there must be any variable name.

Which should either be pre-declared or pre-initialized.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

52

Page 53: Introduction to C++ and Language Building Blocks

Temperature conversion program

// fahren.cpp

// demonstrates cin, newline

#include <iostream>

using namespace std;

int main()

{

int ftemp; //for temperature in fahrenheit

cout << “Enter temperature in fahrenheit: “;

cin >> ftemp;

int ctemp = (ftemp-32) * 5 / 9;

cout << “Equivalent in Celsius is: “ << ctemp <<

„\n‟;

return 0;

}

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

53

Page 54: Introduction to C++ and Language Building Blocks

Arithmetic Assignment Operator

Binary Operators (requires two operands)

Some time called as the op-operator.

+=

-=

*=

/=

A+=3; //equivalent to a=a+3

A*=3; //equivalent to a=a*3

A/=3; //equivalent to a=a/3

A-=3; //equivalent to a=a-3

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

54

Page 55: Introduction to C++ and Language Building Blocks

Program // assign.cpp

// demonstrates arithmetic assignment operators

#include <iostream>

using namespace std;

int main(){

int ans = 27;

ans += 10; //same as: ans = ans + 10;

cout << ans << “, “;

ans -= 7; //same as: ans = ans - 7;

cout << ans << “, “;

ans *= 2; //same as: ans = ans * 2;

cout << ans << “, “;

ans /= 3; //same as: ans = ans / 3;

cout << ans << “, “;

ans %= 3; //same as: ans = ans % 3;

cout << ans << endl;

return 0;

}

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

55

Page 56: Introduction to C++ and Language Building Blocks

The Unary Arithmetic Operators

Requires single operators

Also knows as increment and decrement operators

The ++ and – operators, may be post-fix (after the

operand name) or even may be pre-fix (before the

operand name.

So, ++x is pre-fix, and x++ is post-fix.

x++ is same as x = x+1or x+=1

and ++x is also equal to x = x+1. (Same is true for --)

THEN WHAT IS THE DIFFERENCE???????????

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

56

Page 57: Introduction to C++ and Language Building Blocks

The Unary Arithmetic Operators

#include <iostream>

using namespace std;

int main(){

int x = 3;

cout << ++x <<endl; //will display 4

cout << x++ <<endl; //will also display 4

cout<< x; // will display 5

}

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

57

Page 58: Introduction to C++ and Language Building Blocks

Program // increm.cpp

// demonstrates the increment operator

#include <iostream>

using namespace std;

int main(){

int count = 10;

cout << “count=” << count << endl; //displays 10

cout << “count=” << ++count << endl; //displays 11 (prefix)

cout << “count=” << count << endl; //displays 11

cout << “count=” << count++ << endl; //displays 11 (postfix)

cout << “count=” << count << endl; //displays 12

return 0;

}

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

58

Page 59: Introduction to C++ and Language Building Blocks

Library Function

We already have used two functions, main is the function, which is most mandatory. we have also used other function named as setw(value), which was a manipulator.

Similarly, C++ offers a large variety of library function, which when called, perform some really useful operation. Like sqrt(double number), inside cmath header file calculates the square root of the argument** double type number and it is depicted in the next slide with program.

sqrt accepts type double and also returns double type result.

**argument is the input of the function.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

59

Page 60: Introduction to C++ and Language Building Blocks

Program // sqrt.cpp

// demonstrates sqrt() library function

#include <iostream> //for cout, etc.

#include <cmath> //for sqrt()

using namespace std;

int main()

{

double number, answer; //sqrt() requires type double

cout << “Enter a number: “;

cin >> number; //get the number

answer = sqrt(number); //find square root

cout << “Square root is “

<< answer << endl; //display it

return 0;

}

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

60

Page 61: Introduction to C++ and Language Building Blocks

Casts

Casting Processing is done in order to convert from one

data type to the other.

Two types of casting.

Implicit casting (Also done Automatically by the compiler).

Explicit casting (By the Programmer with brute force).

Conversion can be implicit when converting from lower

to higher data types, because lower data types can be

accommodated in the larger ones, but vice versa may not

be true, some of the digits/precision numbers will be lost

in the alternative case (Converting from higher to lower)

Higher Data Type?? Lower Data Type?? Next Slide

61 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

Page 62: Introduction to C++ and Language Building Blocks

Automatic Conversions or Implicit Casting

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

62

Types are roughly designated “Higher” or “Lower” in the

below order.

Program on the next slide for demonstration.

Page 63: Introduction to C++ and Language Building Blocks

Program

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

63

#include <iostream>

using namespace std;

int main()

{

int count = 7;

float avgWeight = 155.5F;

double totalWeight = count * avgWeight;

cout << “totalWeight=” << totalWeight << endl;

return 0;

} The Result inside totalWeight variable can still be accommodated in a

float variable, but double is used just to depict the automatic conversion.

Page 64: Introduction to C++ and Language Building Blocks

Explicit Casting

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

64

Using static_cast keyword.

Will be covered in the future lectures.

Page 65: Introduction to C++ and Language Building Blocks

Assignment # 02

Solve Exercise Questions from 1 to 10 of Chapter 2,

Robert Lafore‟s Object oriented Programming in C++.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

65

Page 66: Introduction to C++ and Language Building Blocks

So Now….

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

66

What‟s Next?

Tired!

A tight sleep!

Page 67: Introduction to C++ and Language Building Blocks

End of Session 1

What we have learned in this session?

Did you practice?

If yes, do you often?

how much you were able to digest, and what was

exhausted?

How is C++?

These were basics, next chapter deals with more

complexities. Get ready, and boost yourself!

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE

MUET Jamshoro

67