Programming in C++

82
Programming in C++ Programming in C++ Lecture Notes 1 – Getting Started Andreas Savva

description

Programming in C++. Lecture Notes 1 – Getting Started. Andreas Savva. What is a Computer?. Is it a machine with a fantastic brain and incredible intelligence? Of course NOT. - PowerPoint PPT Presentation

Transcript of Programming in C++

Page 1: Programming in C++

Programming in C++Programming in C++

Lecture Notes 1 – Getting Started

Andreas Savva

Page 2: Programming in C++

2

What is a Computer?What is a Computer?Is it a machine with a fantastic brain and incredible intelligence?

Of course NOT.

A computer has no reasoning power. It does exactly what we tell it to do - no more and no less. If we tell it to do something stupid, it does it. If we tell it to do sensible/clever things it does it as well.

The important thing is that computers do what we ask them to do very - very quickly and without making mistakes.

Page 3: Programming in C++

3

What is a Computer What is a Computer Program?Program?

A computer program is a sequence of instructions.

The computer does not obey these instructions while we write them.

Instead, it stores them in a file and when we finish, we can ask the computer to execute them.

The process of constructing (or writing) a program is called programming.

#include <iostream>using namespace std;void main(){ int a, b; cout << ”Enter two numbers”; cin >> a >> b; cout << a << ” + ” << b << ” = ” << a+b;}

Page 4: Programming in C++

4

What is a Programming What is a Programming Language?Language?

Why can’t we “speak” to the computer in English or in Greek or even in Chinese?

Because natural languages are prone to ambiguities.

Since computers do exactly what we tell them to, we must be very precise what we tell them, otherwise they will not respond since they have no intelligence.

Programming languages have been developed for the purpose of communicating with computers.

Programming languages are a sort of stylised English with a few special symbols. They are called high level languages, since they are designed at the level at which wewe want to think about things rather than at the level at which the machine operates.

Page 5: Programming in C++

5

A program written in a high level language is called the “source code”, and it does not make sense to a computer. The computer understands only one language – the “machine code”.Thus, the source-code must be translated into machine code. The translation process is called compilation and the program is called compiler .This compiled program can then be run/executed. So, on a computer you can use any programming language for which the computer has a compiler .

What is a Compiler?What is a Compiler?

#include <iostream>

using namespace std;

void main()

{

cout << ”Hello World”;

}

10110110 11010011

10110011 00010001

11001111 11110000

10100100 10010010

11010100 00010001

. . .

C++compiler

runexecute

Page 6: Programming in C++

6

HistoryHistory1950s• Assembly languagesLate 1950s, early 1960s• FORTRAN (FORmula TRANslator)• COBOL (Common Business Oriented Language)Early 1970s• Pascal was developed by Nicklaus Wirth of Switzerland –

Academic language (good programming techniques)• C was developed by Dennis Ritchie at AT&T Bell Labs –

Language of choice by many professionalsEarly 1980s• C++ was developed by Bjarne Stroustrup at AT&T Bell

Labs – Successor of C, supports OOP.

Page 7: Programming in C++

7

What is an AlgorithmWhat is an Algorithm

An Algorithm is a detailed sequence of simple steps that are needed to solve a problem.

It is a step-by-step solution to a problem

Page 8: Programming in C++

8

Mathematical ExampleMathematical Example

Problem: What is the value of x in the following equation?

5x – 10 = 30

Algorithm (Solution):Step 1: 5x = 30 + 10Step 2: 5x = 40Step 3: x = 40/5Step 4: x = 8

Page 9: Programming in C++

9

Making a cakeMaking a cake

Step 1: Preheat oven to 200 degrees.Step 2: Mix the eggs with the sugar.Step 3: Add the butter, flour, and the rest of the ingredients.Step 4: Stir for 5 minutes.Step 5: Put the mixture into a baking pan and cook it in a

175 degrees for 40 minutes.Step 6: Keep it in the pan for 15 minutes to cool down.Step 7: Serve with vanilla ice-cream.

Page 10: Programming in C++

10

AlgorithmAlgorithmStepStep 1: 1: Move 3 squares and turn right.StepStep 2:2: Move 1 square and turn left.StepStep 3:3: Move 2 squares and turn left.StepStep 4:4: Move 2 squares and turn right.etcetc..

The ProblemThe Problem: How will the robot go to the file folder?

In programming the steps are called statements.

Page 11: Programming in C++

11

Start ProgrammingStart ProgrammingThe simplest C++ program has the form:

At least one space or end-of-line must appear between adjacent words (one or more characters) and numbers but none can occur between a symbol and a word, or a symbol and a symbol.Additional spaces and end-of-lines are ignored.

void main()

{

}

Page 12: Programming in C++

12

Two Types of WordsTwo Types of WordsReserved WordsIdentifiers

1 to 255 characters (if more it will be truncated to 255) must start with a letter or an underscoreconsist of letters, digits and underscores

void main(){ int x; x = 5;}

C++ is a case-sensitive languageSemicolons ( ; ) denote the end of statements

Page 13: Programming in C++

13

Which are valid Identifiers?Which are valid Identifiers?

3men_and_a_baby

MyTax

My New Name

Paper.Size

4_Me

_4Me

int

Int

Integer

_ _ _

Tom&Jerry

_Salary!

A123456789

gghdjtjhgjfg

Epsilon

New-life

Page 14: Programming in C++

14

Input and OutputInput and OutputLibrary: iostream

#include <iostream>using namespace std;int main(){ int x,y; cin >> x >> y; cout << x + y; return 0;}

InputInput OutputOutput

Page 15: Programming in C++

15

Output – The command Output – The command ““coutcout””

i.e.

will display on the screen:

cout << ”……………”

My name is George

where “<<” is the output operator.

cout << ”My name is George”;

Page 16: Programming in C++

16

A complete programA complete program

Note:”Hello world” is called a string – a set of characters

#include <iostream>using namespace std;int main(){ cout << ”Hello world”; return 0;}

Output:Output: Hello world

Page 17: Programming in C++

17

Another ExampleAnother Example#include <iostream>using namespace std;int main(){ cout << ”Hello” << ”My name is George”; return 0;}

Note:If you want to leave a space between the words Hello and My you must add it either after Hello or before My, i.e.cout << ”Hello ” << ”My name is George”;

cout << ”Hello” << ” My name is George”;

Output:Output: HelloMy name is George

Page 18: Programming in C++

18

Is this different?Is this different?#include <iostream>using namespace std;int main(){ cout << ”Hello”; cout << ”My name is George”; return 0;}

Note:It does not change the line unless we ask it to.

Output:Output: HelloMy name is George

Page 19: Programming in C++

19

Changing the lineChanging the lineWe can change the line using the special word “endl”.

#include <iostream>using namespace std; int main(){ cout << ”Hello” << endl; cout << ”My name is George”; return 0;}

Output:Output: HelloMy name is George

cout << ”Hello” << endl << ”My name is George”;Same output:Same output:

Page 20: Programming in C++

20

Structure of Structure of coutcout

where p1, p2, … pn are parameters.

What is the output of the following statements?

cout << p1 << p2 << … << pn ;

cout << ”I am” << ”a student”;cout << ” of:” << endl << endl << ”C”;cout << ”++” << endl << ”!+-%45 @”;

I ama student of:

C++!+-%45 @

Page 21: Programming in C++

21

Special charactersSpecial characters’\n’ newline’\b’ backspace’\0’ null’\”’ double quote

’\t’ tab’\r’ return’\’’ single quote’\\’ backslash

How can we display the following output?He said: ”I love you”

cout << ”He said: ”I love you””;Error. Why?

cout << ”He said: \”I love you\””;Correct:

Page 22: Programming in C++

22

Special CharactersSpecial Characters

What is the output of the following statement?

cout << ”Harry Potter\nis very-very\n\nFAMOUS”;

Harry Potteris very-very

FAMOUS

Page 23: Programming in C++

23

Three types of Errors:• Syntax Errors (Compile

errors)• Logical errors• Run-time errors

ErrorsErrors

Page 24: Programming in C++

24

Comments, RemarksComments, Remarks• It is very useful to include comments in a

program for the benefit of the human reader.• Any sequence of characters enclosed between

the symbols /* and */, or after the symbols // in the same line, is interpreted as a comment and has no effect upon the action of the program.

• A comment may appear at any point in your program at which a space would be legal.

/* A program to display “Hello World”Programmer: A.Savva */#include <iostream>using namespace std;void main() { // The main program cout << ”Hello”; // Output return 0;}

Page 25: Programming in C++

25

NumbersNumbersWhat is the output of the following

statements?

cout << ”5”; 5

Statement Output

cout << ”5 + 6”; 5 + 6

cout << 5; 5

cout << 5 + 6; 11

cout << 5 << ” + ” << 6 << ” = ” << 5 + 6;

5 + 6 = 11

Page 26: Programming in C++

26

NumbersNumbers

Integers5123-1298765432

Reals3.6123.678-0.0000019876543.2

34.0

34.0

Page 27: Programming in C++

27

IntegersIntegersIntegers come in 3 sizes:

short – at least 16 bitsintlong – at least 32 bits

There is no requirement that long is strictly longer that short (but cannot be shorter).

The expression sizeof(<DataType>) returns the size of the DataType expressed as a multiple number of the size of char. Thus the statement

cout << sizeof(char);

will always display 1. If the statement

cout << sizeof(long);

displays 4 it means that the size of long is 4 times the size of char.

Page 28: Programming in C++

28

Choose the right data-typeChoose the right data-type

Space Shuttle Challenger, 28 Jan 1986

Page 29: Programming in C++

29

Integers (Decimal, Octant, Integers (Decimal, Octant, Hex)Hex)

Octant (base 8) constants are specified by prefixing the number with a zero digit, and hexadecimal (base 16) constants can be specified by prefixing the number with “0x”.

Code will display Reasoncout << 34; 34

cout << 034; 28 34 octant = 28 decimal

cout << 034 + 10; 38 034 is octant, 10 is decimal

cout << 034 + 010; 36 034 + 010 = 044 = 36

cout << 096; Error Digit 9 is illegal in octant numbers

cout << 0x45; 69 45 hexadecimal = 69 decimal

cout << 0xA8F3; 43251 A8F3 hexadecimal = 43251 decimal

Page 30: Programming in C++

30

RealsReals

There are two ways to represent a real number:

Fixed point formFixed point formFloating point formFloating point form 3.1 1.6e7

0.00001 45E-2 123.56 -123.1e3

Page 31: Programming in C++

31

Floating-point RealsFloating-point Reals

where x is an integer or fixed point real and y is an integer.

The letter "E" is interpreted as "times 10 to the power". So

4.576E2 = 4.576 × 102 = 457.6

i.e.-3.478216E2 = -347.82161E-5 = 0.000017.2E9 = 7200000000.0

xEy OR xey

Page 32: Programming in C++

32

Fixed-point form OutputFixed-point form OutputA real is displayed in a fixed-point form if :

the integer part of the real has at most 7 digits. The number will be displayed in at most 7 character positions.the first non-zero digit is within the first 6 positions (including the decimal point). The output will have the leading zeros followed by 6 more digits starting from the first non-zero digit. Zeros at the end of the number will not appear in the output.

Code will displaycout << 1788669.87878787887; 1788669

cout << 178866.987878787887; 178867

cout << 17886.6987878787887; 17886.7

cout << -17.8866987878787887; -17.8867

cout << 61.4578566e3; 61457.9

cout << 0.000634562713456; 0.000634563

cout << 0.012000000234445; 0.012

cout << 1.2000000234445e-2; 0.012

Page 33: Programming in C++

33

Floating-point form OutputFloating-point form OutputOtherwise a real number will be displayed in a floating-point form as:

. e ± _i.e.

1 . 2 3 4 5 6 e - 0 0 5

Code will displaycout << -1788669878.0; -1.78867e+009

cout << 0.0000000123456789; 1.23457e-008

cout << 0.00000001200003456789; 1.2e-008

cout << 0.00000001200006456789; 1.20001e-008

cout << 12340000005678.4; 1.234e+013

Page 34: Programming in C++

34

Formatted OutputFormatted OutputLibrary: Library: iomanipiomanip

setw(n) Sets minimum field width on NEXT output.

setfill(ch) Only useful with setw. If a value does not entirely fill a field, the character ch will be used to fill in the other characters. Default value is blank. Same effects as cout.fill(ch). Applies to ALL.

setprecition(n) Sets the number of digits printed to the NEXT real number. Equivalent to cout.precision(n).

Page 35: Programming in C++

35

Formatted OutputFormatted Output

Output: 300078000200078ppp212.46

#include <iostream>#include <iomanip>using namespace std;int main(){ cout << setw(5) << 3 << endl; cout << setw(5) << setfill(’0’) << 78 << setw(4) << 2 << endl; cout << setw(5) << setfill(’0’) << 78 << setw(4) << setfill(’p’) << 2 << endl; cout << setprecition(4) << 12.45878 << endl; return 0;}

Page 36: Programming in C++

36

Data TypesData TypesIndicates what type of information will be stored in the allocated memory space.

Data Data typetype

intshortlongfloatdoubleboolchar

ValuesValuesWhole NumberWhole number in the range -32,768 to 32,767Whole number in the range -2,147,483,648 to

2,147,483,647Floating point number with 6 digits accuracyFloating point number with 14 digits accuracytrue or falseA single ASCII character ( 0 - 255 )

Bytes in Bytes in MemoryMemory

2 or 4244811

Page 37: Programming in C++

37

Signed and Unsigned Integers

Default is signed

signed int x;

unsigned long y;

x can take values from -2bits-1 to 2bits-1-1

y can take values from 0 to 2bits-1

Long RealsOnly with double not with floatlong double z;

Page 38: Programming in C++

38

Declarations and MemoryDeclarations and Memoryi.e.

char Name[20];int Counter;const double DISCOUNT_RATE =

0.5;Memory

Name Counter

DISCOUNT_RATE0.5

Page 39: Programming in C++

39

ConstantsConstantsconst <DataType> <Identifier> = <value>;

#include <iostream>using namespace std;int main(){ const int x = 5; const int y = 7, z = 3;

cout << x << ”,” << x + 1 << endl; cout << x + y + z;

return 0;} 5,6

15

Page 40: Programming in C++

40

Why Using Constants?Why Using Constants?

#include <iostream>using namespace std;int main(){ const int a = 5, b = 2; cout << a << ”+” << b << ”=” << a+b << endl; cout << a << ”-” << b << ”=” << a-b << endl; cout << a << ”*” << b << ”=” << a*b << endl; cout << a << ”/” << b << ”=” << a/b << endl; return 0;}

5+2=75-2=35*2=105/2=2

Page 41: Programming in C++

41

User-defined constantsUser-defined constants

Examples:Examples:const int threenines = 999;const int retirementage = 65;const double pi = 3.14159;const float Bloodheat = 37.0;const double tinynumber = 1E-20;const int Emergency = threenines;const long Population = 100000;

Page 42: Programming in C++

42

ConstantsConstants#define <identifier> <value>

#include <iostream>using namespace std;int main(){ #define MAX 10 // no semicolon// no semicolon const int Dozen = 12; cout << MAX + Dozen;

return 0;}

22

Page 43: Programming in C++

43

VariablesVariablesAt Run-time:

Constants cannot change their values.Variables can change their values many times.

<DataType> <Identifier>;

i.e.double Salary;int x, y;char c;

Page 44: Programming in C++

44

Values to VariablesValues to Variables

A variable can be assigned a value bythe assignment statementinitializing valuesinput values

Page 45: Programming in C++

45

The Assignment The Assignment StatementStatement

i.e. Num = 6 – 5 * 3; Total = Number1 + Number2 – MAX_NUMS;

i = 0;Num = Num + (4 – 6 * Num);intint x = 5;

<Variable> == <Expression>;

In C++ you can assign a value at declaration

Page 46: Programming in C++

46

Variables ExampleVariables Example#include <iostream>using namespace std;int main(){ const int MAX = 100; int x, y = MAX - 1;

x = y + 1; cout << x << y;

int total = x + y; cout << total;

x = y = total = 0; cout << x; return 0;}

In C++ you can declare

variables anywhere

= can be used many times in a statement.

Page 47: Programming in C++

47

Initializing ValuesInitializing Values

int num(12);int num(12);

i.e. int x (4);int y (x + 3 * 2);

int total (x + y);cout << total;

<Data Type> <Variable><Data Type> <Variable>(( <Expression> <Expression>));;

14

Page 48: Programming in C++

48

Input – The command Input – The command ““cincin””

i.e.

will read a value for variable x,

and a value for variable y.

cin >> var1 >> var2 >> … >> varn

where “>>” is the input operator.

cin >> x >> y;

Page 49: Programming in C++

49

Input ExampleInput Example

#include <iostream>using namespace std;void main(){ int x,y; cin >> x >> y; cout << x << ” + ” << y << ” = ” << x + y;}

5 125 + 12 = 17Input values in

RED.Program holds.

Page 50: Programming in C++

50

A Better ProgramA Better Program#include <iostream>using namespace std;void main(){ int x,y; cout << ”Enter two Numbers: ”; cin >> x >> y; cout << x << ” + ” << y << ” = ” << x + y;}

Enter two numbers:5 + 12 = 17

5 12

When we want input from the user we should display some outputexplaining what the input should be.

Page 51: Programming in C++

51

Arithmetic OperationsArithmetic Operations

+ Addition– Subtraction* Multiplication/ Division

5 + 3 * 2 =

11

(5 + 3) * 2 =

16

Page 52: Programming in C++

52

Order of OperationsOrder of Operations

1.Brackets2.Multiplication ( * ) and Division ( / )3.Addition ( + ) and Subtraction ( – )4.Assignment Statement ( = )

Page 53: Programming in C++

53

ExpressionsWrite the following mathematical expressions in C++:

P = (n*(n-1)*(n-2)+2)/(3*(n-3));

x = (-b+sqrt(b*b – 4*a*c))/(2*a);

)3(3

2)2)(1(

n

nnnP

a

acbbx

2

42

Page 54: Programming in C++

54

Calculations – Left-to-rightCalculations – Left-to-right

5 + 4 / 2 – 6 * 3 =

( 2 - ( 1 + 3 ) * 2 + 8 ) * 2 =

12 / 2 * 3 =

12 / ( 2 * 3 ) =

( ( 1 + 2 ) * ( ( 5 + 7 ) / ( 7 – 4 ) * 2 ) ) / 6 =

-11

4

18

2

4

Page 55: Programming in C++

55

Post-incrementx++; // Increases x by 1, i.e. x = x + 1;

Post-decrementx--; // Decreases x by 1, i.e. x = x - 1;

Pre-increment++x; // Increases x by 1, i.e. x = x + 1;

Pre-decrement--x; // Decreases x by 1, i.e. x = x - 1;

++ Increase the value of a variable by one. - - Decrease the value of a variable by one.

Increment - Decrement Increment - Decrement OperatorsOperators

Page 56: Programming in C++

56

Increment - Decrement Increment - Decrement OperatorsOperators

The difference is when they are used inside expressions.

Pre-operators: will increase/decrease the variable and then evaluate the expression.Post-operators: will evaluate the expression and then increase/decrease the variable.

int x, a = 5;

x = a++;

int x, a = 5;

x = ++a;

x = 5, a = 6x = 5, a = 6 x = 6, a = 6x = 6, a = 6

int x, a = 5;

x = a--;

int x, a = 5;

x = --a;

x = 5, a = 4x = 5, a = 4 x = 4, a = 4x = 4, a = 4

Page 57: Programming in C++

57

Order of OperationsOrder of Operations

1.Brackets2.Prefix operators ( ++var ++var, - - var- - var,

+exp+exp, -exp -exp )3.Multiplication ( * ) and Division (( // ))4.Addition ( ++ ) and Subtraction ( – – ))5.Assignment Statement ( = = )6.Postfix operators ( var++var++, var- - var- - ))

Page 58: Programming in C++

58

Increment - Decrement Increment - Decrement OperatorsOperators

int x, a = 5, b = 10;

x = a++ + --b;

int x, a = 5, b = 10;

x = a++ + b++;

x = 14, a = 6, b = 9x = 14, a = 6, b = 9

x = 15, a = 6, b = 11x = 15, a = 6, b = 11

int x, a = 5, b = 10;

x = ++a + ++b;

x = 17, a = 6, b = 11x = 17, a = 6, b = 11

Page 59: Programming in C++

59

More Examplesint x, a = 5;x = a++ - --a;

x = 0, a = 5x = 0, a = 5

int x, a = 5;x = a++ + --a + ++a;

x = 15, a = 6x = 15, a = 6

int x, a = 5;x = a++ + (--a + ++a);

x = 15, a = 6x = 15, a = 6

int x, a = 2;x = (++a + ++a) + ++a;

x = 13, a = 5x = 13, a = 5

int x, a = 2;x = ++a + (++a + ++a);

x = 15, a = 5x = 15, a = 5

Page 60: Programming in C++

60

Avoid complex statementsAvoid complex statements

int x, a = 2;x = (++a + ++a) + ++a;

x = 13, a = 5x = 13, a = 5

int x, a = 2;x = ++a + (++a + ++a);

x = 15, a = 5x = 15, a = 5

int x, a = 2;x = (++a + 1) + ++a;

x = 9, a = 4x = 9, a = 4Not as expectedNot as expected

int x, a = 2;x = ++a + (1 + ++a);

x = 9, a = 4x = 9, a = 4

Page 61: Programming in C++

61

More Examples (Be careful)int x, a = 5;

x = a++-++a;

x = 0, a = 7x = 0, a = 7

int x, a = 5;

x = a+++--a;

x = 8, a = 5x = 8, a = 5

int x, a = 5;

x = a+++++a;

ErrorError

int x, a = 5;

x = a+++ ++a;

x = 12, a = 7x = 12, a = 7

int x, a = 5;

x = a++---a;

ErrorError

int x, a = 5;

x = a++- --a;

x = 0, a = 5x = 0, a = 5

Page 62: Programming in C++

62

Mathematical FunctionsMathematical FunctionsLibrary: cmathLibrary: cmath

abs(x) = |x|

sin(x)

cos(x)

tan(x)

asin(x) = sin-1x

acos(x) = cos-1x

atan(x) = tan-1x

exp(x) = ex

log(x) = logex

xsqrt(x) =

Page 63: Programming in C++

63

More FunctionsMore Functions

int(x) – Returns the integer portion x

pow(x,y) – Returns xy

The Round function

int(x + 0.5) – Rounds +ve x to the nearest integer

int(x – 0.5) – Rounds –ve x to the nearest integer

The Power function: ab = eb log a

exp(b * log(a)) – Returns ab

Page 64: Programming in C++

64

Integer Division ( Integer Division ( / / ) & ) & Remainder ( Remainder ( %% ) )

2 + 3 = 52 – 3 = -12 * 3 = 62.0 / 3.0 = 0.6666672 / 3.0 = 0.6666672.0 / 3 = 0.6666672 / 3 = 0

20 / 8 = 220 / 8 = 2

20 % 8 = 420 % 8 = 4

Page 65: Programming in C++

65

ExersisesExersises

16 / 4 =

17 / 4 =

18 / 4 =

19 / 4 =

20 / 4 =

21 / 4 =

22 / 4 =

23 / 4 =

24 / 4 =

4

4

4

4

5

5

5

5

6

16 % 4 =

17 % 4 =

18 % 4 =

19 % 4 =

20 % 4 =

21 % 4 =

22 % 4 =

23 % 4 =

24 % 4 =

0

1

2

3

0

1

2

3

0

23 / 6 =

-23 / 6 =

23 / -6 =

-23 / -6 =

23 % 6 =

-23 % 6 =

23 % -6 =

-23 % -6 =

3

-3

-3

3

5

-5

5

-5

Page 66: Programming in C++

66

More ExercisesMore Exercises

27 / 6 =

27 % 6 =

5 / 21 =

5 % 21 =

4 / 0 =

4 % 0 =

4

3

0

5

Error

Error

63 / 10 =

63 % 10 =

3 / 10 =

3 % 10 =

6

3

0

3

Page 67: Programming in C++

67

Order of OperationsOrder of Operations

1. Brackets2. Prefix operators ( ++var , --var, -exp, +exp )3. Multiplication ( * ) and Division ( / ) and

Remainder ( % )4. Addition ( + ) and Subtraction ( – )5. Assignment Statement ( = )6. Postfix operators ( var++ , var-- )

Page 68: Programming in C++

68

ExercisesExercises35 / 8 % 3 =

35 / (8 % 3) =

12 % (7 / 3) =

12 % 7 / 3 =

(12 % 7) / 3 =

3 + 12 % 7 =

3 + 12 / 7 =

1

17

0

1

1

8

4

4 * 8 % 5 =

4 * ( 8 % 5) =

33 % 5 * 2 =

8 % 5 * 4 =

8 % (5 * 4) =

2

12

6

12

8

3 + 2 * (12 – 4 * 11 % 6 * 4 / 3) = 23

Page 69: Programming in C++

69

Swap Variable ValuesSwap Variable Values

What is the output of the following statements?Will the values of a and b be swapped?

int a = 5, b = 8;a = b;b = a;cout << a << ”, ” << b;

We must use a Temporary Variable: int a = 5, b = 8, temp;temp = a;a = b;b = temp;cout << a << ”, ” << b;

Page 70: Programming in C++

70

The Assignment The Assignment StatementStatement

<var> += <exp>; <var> = <var> + <exp>;

<var> –= <exp>; <var> = <var> – <exp>;

<var> *= <exp>; <var> = <var> * <exp>;

<var> /= <exp>; <var> = <var> / <exp>;

<var> %= <exp>; <var> = <var> % <exp>;

<var> ?= <exp>;where ? is a binary operator (i.e. +, - , *, /, %, etc.)

ExpressionExpression same assame as

Page 71: Programming in C++

71

ExamplesExamples

x = 5;

x = 6 – 4 * 3;

x += 5; // same as x = x + 5;

x –= 5; // same as x = x – 5;

x *= 5; // same as x = x * 5;

x /= 5; // same as x = x / 5;

x += 5 + 3 * 2; // same as x = x + (5 + 3 * 2);

X –= 5 – 3; // same as x = x – (5 – 3);

Page 72: Programming in C++

72

ExamplesExamplesint a = 3, b = 5;

a += b;

a = 8, b = 5a = 8, b = 5

int a = 3, b = 5;

a -= b;

a = -2, b = 5a = -2, b = 5

int a = 3, b = 5;

a *= b – (b / 2);

a = 9, b = 5a = 9, b = 5

int a = 3, b = 5;

a += b++;

a = 8, b = 6a = 8, b = 6

int a, b = 5, c = 3;

a = b -= c;

a = 2, b = 2, c = 3a = 2, b = 2, c = 3

int a=3, b=5, c=4;

a += b -= --c * 2;

a = 2, b = -1, c = 3a = 2, b = -1, c = 3

Page 73: Programming in C++

73

The Data-Type “The Data-Type “charchar””In C++ the type char is described as being an integer.

ExamplesExamples

char ch;ch = 66;cout << ch;

char ch;ch = ’A’;cout << ch;

char ch;ch = ’?’;cout << ch;

int x;x = ’3’;cout << x;

Output: Output: AA

Output: Output: ??

Output: Output: BB

Output: Output: 5151

Page 74: Programming in C++

74

ASCIIASCIIcodecode

32 SP 51 3 70 F 89 Y 108 l

33 ! 52 4 71 G 90 Z 109 m

34 " 53 5 72 H 91 [ 110 n

35 # 54 6 73 I 92 \ 111 o

36 $ 55 7 74 J 93 ] 112 p

37 % 56 8 75 K 94 ^ 113 q

38 & 57 9 76 L 95 _ 114 r

39 ' 58 : 77 M 96 ` 115 s

40 ( 59 ; 78 N 97 a 116 t

41 ) 60 < 79 O 98 b 117 u

42 * 61 = 80 P 99 c 118 v

43 + 62 > 81 Q 100 d 119 w

44 , 63 ? 82 R 101 e 120 x

45 - 64 @ 83 S 102 f 121 y

46 . 65 A 84 T 103 g 122 z

47 / 66 B 85 U 104 h 123 {

48 0 67 C 86 V 105 i 124 |

49 1 68 D 87 W 106 j 125 }

50 2 69 E 88 X 107 k 126 ~

Page 75: Programming in C++

75

ExamplesExamples

int c;c = ’3’ + 1;cout << c;

char c;c = ’d’;cout << c;

char c;c = ’d’;cout << int(c);

char c;c = ’3’ + ’1’;cout << c;

Output: Output: dd

Output: Output: 100100

Output: Output: 5252

Output: Output: dd

int c;c = ’d’;cout << c;

Output: Output: 100100

char c;c = ’+’ - 1;cout << (int)c;

Output: Output: 4242

char c;c = ’3’ + 1;cout << c;

Output: Output: 44

Page 76: Programming in C++

76

Type CastType Castdouble x = 4;x += 2 / 3;cout << x;

Output: Output: 44

double x = 4;x += 2.0 / 3;cout << x;Output: Output: 4.666674.66667

double x = 4;x += (double)2 / (double)3;cout << x;Output: Output: 4.666674.66667

double x = 4;x += 2 / 3.0;cout << x;Output: Output: 4.666674.66667

double x = 4;x += 2.0 / 3.0;cout << x;Output: Output: 4.666674.66667

double x = 4;x += (double)2 / 3;cout << x;

Output: Output: 4.666674.66667

Page 77: Programming in C++

77

Real constants are DoubleReal constants are DoubleWarning but not an error:

truncation from 'const double' to 'float‘

No Warning

Also No Warning

float x = 4.2;x += 2.7;

float x = 4.2;x += 1;

double x = 4.2;x += 2.7;

float x = 4.2;x += (float)2.7;

float x = 4;x += 1;

Page 78: Programming in C++

78

Converting to IntegerConverting to Integer

Error:

int x = 5.2;

Correct:

int x = (int) 5.2;

Page 79: Programming in C++

79

Comparison of Comparison of CC and and C++C++#include <stdio.h>void main(){ int x,y; printf(”Enter two Numbers: ”); scanf(”%d %d”, &x, &y); printf(”%d + %d = %d”, x, y, x + y);}

#include <iostream>using namespace std;void main(){ int x,y; cout << ”Enter two Numbers: ”; cin >> x >> y; cout << x << ” + ” << y << ” = ” << x + y;}

CC

C++C++

Page 80: Programming in C++

80

Anatomy of a C/C++ Anatomy of a C/C++ programprogramA program in C/C++ may consist of one or more

files:Program source code files (myprog.c, myprog.cpp)

Contain blocks of code, data declarations, etc.One of the files has a function called main(), where the program will start executing.

Header files (header.h)Contain definitions that are common to many source files.Source files usually #include header files (equivalent to replacing their content at that location).

Libraries (names may vary)Contain precompiled modules used in many programsThey are essential because C and C++ do not have complex capabilities built-in (e.g. input/output).

Page 81: Programming in C++

81

Compiling a ProgramCompiling a Program

Pre-processinclude header filestranslate constantsetc

Compile into object modulesLink modules

combine object files and librariesproduce executable program

PREPRO-CESSOR

C/C++sourceprogram(s)

Headerfiles

Objectfiles

LINKER

COMPILER

Executable

Libraryfiles

abc

010

abc

abc

010010

Page 82: Programming in C++

82

Include FilesInclude Files

#include ”MaxMin.c”

int main()

{

cout << max(3,8);

return 0;

}

#include <iostream>

using namespace std;

int max(int a, int b)

{

if (a > b) return a;

else return b;

}MaxMin.cMaxMin.cMyprog.cppMyprog.cpp