1 king saud university programming in c++ ge 211 dr. ahmed telba

127
1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Upload: owen-russell

Post on 14-Dec-2015

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

1

King Saud university Programming in C++

GE 211

Dr. Ahmed Telba

Page 2: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

2

Introduction to C++ Language

Scalar Variables, Operators

and

Control Structures

Page 3: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

3

Structure of a C++ Program

• A C++ program is a collection of definitions and declarations:– data type definitions– global data declarations– function definitions (subroutines)– class definitions– a special function called main()

(where the action starts).

Page 4: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

4

Procedural vs. Object Oriented

• Procedural languages express programs as a collection of procedures (subroutines).

• Object Oriented languages express programs as a collection of object types (classes).

• C++ is both!

• We will start with procedural and build up to Object Oriented

Page 5: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

5

Hello World++// Hello World program

#include <iostream.h>

int main() {

cout << "Hello World\n";

return 0;

}

comment

Allows access to an I/O library

output (print) a string

Program returns a status code (0 means OK)

Starts definition of special function main()

Page 6: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

6

Comments

• Comments contain text that is not converted to machine language (it's just there for humans).

• Everything after "//" is ignored by the compiler.

• Everything between "/*" and "*/" is ignored.

Page 7: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

7

Comment Example// omar's Homework #1

// This program is awesome!

#include <iostream.h>

/* This program computes the

coefficient of expansion of the

universe to 27 decimal places.

*/

int main() {

cout << 1.0000000000000000000001;

}

Page 8: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

8

Includes

• The statement: #include <foo.h> inserts the contents of the file foo.h inside your file before the compiler starts.

• Definitions that allow your program to use the functions and classes that make up the standard C++ library are in these files.

• You can include your own file(s):#include "myfile.h"

Page 9: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

9

C++ Preprocessor

• C++ Compilers automatically invoke a preprocessor that takes care of #include statements and some other special directives.

• You don't need to do anything special to run the preprocessor - it happens automatically.

Page 10: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

10

Preprocessing

C++ ProgramC++ Program ExecutableProgram

ExecutableProgram

C++Compiler

C++Compiler

C++Preprocessor

C++Preprocessor

Temporary file(C++ program)

Temporary file(C++ program)

Page 11: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

11

The Preprocessor

• Lines that start with the character '#' are special to instructions to a preprocessor.

• The preprocessor can replace the line with something else:– include: replaced with contents of a file

• Other directives tell the preprocessor to look for patterns in the program and do some fancy processing.

Page 12: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

12

#define (macro) Example

#define square(a) (a * a)

y = square(x);

z = square(y*x);

becomes y = (x * x);

becomes z = (y*x * y*x);

Page 13: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

13

Some common includes

• Basic I/O: iostream.h

• I/O manipulation: iomanip.h

• Standard Library: stdlib.h

• Time and Date support: time.h

Page 14: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

14

Another C++ Program// C++ Addition of integers

#include <iostream.h>

int main() {

int integer1, integer2, sum;

cout << "Enter first integer\n";

cin >> integer1;

cout << "Enter second integer\n";

cin >> integer2;

sum = integer1 + integer2;

cout << "Sum is " << sum << endl;

return 0;

}

// C++ Addition of integers

#include <iostream.h>

int main() {

int integer1, integer2, sum;

cout << "Enter first integer\n";

cin >> integer1;

cout << "Enter second integer\n";

cin >> integer2;

sum = integer1 + integer2;

cout << "Sum is " << sum << endl;

return 0;

}

Page 15: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

15

Variables

• The program now uses variables:int integer1, integer2, sum;

• Variables are just names for locations in memory.

• In C++ all variables must have a type (not all languages require this).

• In C++ all variables must be declared before they can be used.

Page 16: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

16

Variables (cont.)

• C++ variables are declared like this:

type var_name;

• type indicates what kind of variable.

• C++ built in types include:

int char float double bool• You can also create new types!

Page 17: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

17

Variable Names

• C++ variable names:– made up of letters, digits and underscore.– Must start with a non-digit.– Case sensitive

•foo is not the same name as Foo

• Can be any length

• Good variable names tell the reader what the variable is used for!

Page 18: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

18

Literals (Constants)• Literals are fixed values used by a program.

• Some examples of literals:22 3.14159 0x2A

false "Hi Dave" 'c'

• You can initialize a variable in the declaration by assigning it a value:

int foo = 17;

double PI = 3.14159;

char newline = '\n';

Page 19: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

19

Expressions

• C++ expressions are used to express computation.

• Expressions include operations and the operands on which the operations are applied.

• Operands can be variables, literals or function calls.

Page 20: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

20

Math Expressions

• Mathematical expressions have numeric values when evaluated.

• Some examples:1+2

(fahr - 32)*(5/9)

1*(2*(3*(4*5)))

Page 21: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

21

Mathematical Operators

+ - * / %• Operators have rules of precedence and

associativity that control how expressions are evaluated.

• What is the value of this C++ expression ?:2 / 3 / 4 + 5

• Answer: You can't tell unless you know the rules.

Page 22: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

22

Associatively

• The associatively of an operator control the order of evaluation of expressions involving the same operator, for example:

3 / 4 / 5

• Associatively can be:– left-to-right: the leftmost operator is applied first.– Right-to-left: the rightmost operator is applied first.

Page 23: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

23

Precedence

• Precedence controls the order of evaluation of operators. – A high precedence means an operator is

evaluated (applied) before any lower precedence operators.

• Operators that have the same precedence can happen in either order, but in C++ the one on the left is evaluated first.

Page 24: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

24

C++ Math Operator Rules

Operator Associativity Precedence

() left to right high

* / % left to right middle

+ - left to right low

• Now - what is the value of this?:2 / 3 / 4 + 5

• How about this: (7*3/4-2)*5

Page 25: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

25

Relational and Equality Operators• Relational and Equality operators are used to

compare values:

• Relational Operators:> Greater than

>= Greater than or equal

< Less than

<= Less than or equal

• Equality Operators:== Equal to

!= Not Equal to

Page 26: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

26

Relational and Equality Operators (cont.)

• The relational operators have very low precedence and associate left-to-right.

• The equality operators have very-very low precedence and associate left-to-right.

• Some examples:

17 < x foo == 3.14

age != 21 x+1 >= 4*y-z

Page 27: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

27

Another Operator

• The assignment operator "=" is used to assign a value to a variable.

x = 13 - y;

• Assignment has very low precedence and associates from right to left.

• You can do this:x = y = z + 15;

Page 28: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

28

Precedence

Operators Precedence

() highest (applied first)

* / %

+ -

< <= > >=

== !=

= lowest (applied last)

Page 29: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

29

Another Program#include <iostream.h>

int main(){double fahr,celcius;

cout << "Enter Temperature in Fahrenheit\n";cin >> fahr;

celcius = (fahr - 32.0)*5/9;cout << fahr << " fahrenheit is " << celcius

<< " Celcius" << endl;

return 0;}

Page 30: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Structure of a program

Page 31: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Starting C++

• // my first program in C++ • Comment line• #include <iostream>• using namespace std;• All the elements of the standard C++ library are declared within

what is called a namespace.• Int main ()• This line corresponds to the beginning of the definition of the

main function.• cout << "Hello World!"; • “apper in the screen” • return 0; • The return statement causes the main function to finish.

Page 32: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Structure of a program

• // my first program in C++• #include <iostream>• using namespace std;• int main ()• { • cout << "Hello World!";• return 0;• }

Page 33: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba
Page 34: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba
Page 35: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Additional instruction to our first program

• // my second program in C++ • #include <iostream> • using namespace std;• int main ()• {• cout << "Hello World! "; cout << "I'm a C++

program"; return 0; • }• Hello World! I'm a C++ program

Page 36: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Writing program in one line

• int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; }

• We were also free to divide the code into more lines if we considered it more convenient:

Page 37: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Writing program in one line

Page 38: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Comments

Page 39: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

The standard reserved keywords in C++

• asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while

Page 40: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Operators reserved

• and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

• The C++ language is a "case sensitive" language

Page 41: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

basic fundamental data types in C++

Page 42: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Declaration of variables

• int a; • float mynumber;• declare more than one variable of the same type• int a, b, c; OR declared

int a;

int b;

int c;• Same meaning

Page 43: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba
Page 44: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Initialization of variables

• Int a = 0; OR

• int a (0);

Page 45: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Print

Page 46: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Calculate circumference

Page 47: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Assignment Operation

Page 48: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Arithmetic operators• The five arithmetical operations supported by the C++

language are: • + addition - subtraction * multiplication / division % modulo• a = 11 % 3;• the variable a will contain the value 2, since 2 is the

remainder from dividing 11 between 3.

Page 49: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Compound assignment

• Compound assignment are

• (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

Page 50: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Example

Page 51: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Relational and equality operators

Page 52: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

52

const

• You can add the const modifier to the declaration of a variable to tell the compiler that the value cannot be changed:

const double factor = 5.0/9.0;

const double offset = 32.0;

celcius = (fahr - offset)*factor;

Page 53: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

53

What if you try to change a const?

• The compiler will complain if your code tries to modify a const variable:

const foo = 100;

foo = 21;

Error: l-value specifies const object

Page 54: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

54

Why use const?

• Const tells the compiler that a variable should never be changed.

• You already know the variable should never be changed!

• But - let the compiler save you from yourself (you might forget that it shouldn't be changed).

Page 55: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

55

Integer vs. floating point math

• How does C++ know whether to use floating point or integer math operators?

• If either operand is floating point, a floating point operation is done (the result is a floating point value).

• If both operand are integer the result is an integer (even division).

Page 56: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

56

Math Operator Quiz

What are the values printed?

const int five = 5;

int i = 7;

float x = 7.0;

cout << five + i/2 << endl;

cout << five + x/2 << endl;

Page 57: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

57

Control Structures

• Unless something special happens a program is executed sequentially.

• When we want something special to happen we need to use a control structure.

• Control Structures provide two basic functions: selection and repetition

Page 58: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

58

Selection

• A Selection control structure is used to choose among alternative courses of action.

• There must be some condition that determines whether or not an action occurs.

• C++ has a number of selection control structures:

if if/else switch

Page 59: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

59

Repetition Control Structures

• Repetition control structures allow us to repeat a sequence of actions (statements).

• C++ supports a number of repetition control structures:

while for do/while

Page 60: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

60

if

• The if control structure allows us to state that an action (sequence of statements) should happen only when some condition is true:

if (condition)

action;

Page 61: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

61

Conditions

• The condition used in an if (and other control structures) is a Boolean value - either true or false.

• In C++:– the value 0 is false– anything else is true

Page 62: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

62

if examples

if (1)

cout << "I am true!\n";

if (1-1)

cout << "I am false!\n";

Page 63: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

63

Relational and Equality Operators and Conditions

• Typically a condition is built using the C++ relational and equality operators.

• These operators have the values true (1) and false (0).

• So the expression x==x has the value true.

• and 7 <= 3 has the value false.

Page 64: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

64

More ifsif (foo)

cout << "foo is not zero\n";

if (grade>=90)

lettergrade = 'A';

if (lettergrade == 'F')

cout << "The system has failed you\n"

Page 65: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

65

Common Mistake

• It is easy to mix up the assignment operator "=" with the equality operator "==".

• What's wrong with this:

if (grade=100)

cout << "your grade is perfect - RPI has decided to give you your degree today!\n";

Page 66: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

66

Compound Statements• Inside an if you can put a single statement or

a compound statement.

• A compound statement starts with "{", ends with "}" and can contain a sequence of statements (or control structures)

if (grade>=90) {

cout << "Nice job - you get an A\n";

acnt = acnt+1;

}

Page 67: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

67

A word about style

• C++ doesn't care about whitespace (including newlines), so you can arrange your code in many ways.

• There are a couple of often-used styles.

• All that is important is that the code is easy to understand and change!

Page 68: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

68

Some common styles

if (foo>10) {

x=y+100;

cout << x;

}

if (foo>10) {

x=y+100;

cout << x;

}

if (foo>10)

{

x=y+100;

cout << x;

}

if (foo>10)

{

x=y+100;

cout << x;

}

if(foo>10){x=y+100;cout<<x;}if(foo>10){x=y+100;cout<<x;}

Page 69: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

69

if else Control Structure

• The if else control structure allows you to specify an alternative action:

if ( condition )

action if true

else

action if false

Page 70: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

70

if else example

if (grade >= 90)

lettergrade = 'A';

else

lettergrade = 'F';

Page 71: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

71

Another exampleif (grade >= 90)

lettergrade = 'A';

else if (grade >= 80)

lettergrade = 'B';

else if (grade >= 70)

lettergrade = 'C';

else if (grade >= 60)

lettergrade = 'D';

else

lettergrade = 'F';

Page 72: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

72

while Control Structure

• The while control structure supports repetition - the same statement (or compound statement) is repeated until the condition is false.

while (condition)

do something;

the inside is called

the "body of the loop"

Page 73: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

73

while dangers

• The body of the loop must change something that effects the condition!

• if not - the loop could never end– or the loop would never end

• or the loop would never end– or the loop would never end

» or the loop would never end

…….

Page 74: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

74

while example

lettergrade = 'A';

cutoff = 90;

while (grade < cutoff) {

lettergrade = lettergrade + 1;

cutoff = cutoff - 10;

}

if (lettergrade > 'F')

lettergrade = 'F';

Page 75: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

75

Off topic - increment and decrement operators

• You can increment an integer variable like this:

// same as lettergrade = lettergrade + 1;

lettergrade++;

• You can also decrement:

// same as lettergrade = lettergrade - 1;

lettergrade--;

Page 76: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

76

More off topic - special assignment operators

• This C++ statement:foo += 17;– is shorthand for this:

foo = foo + 17;

• You can also use:

-= *= /=

Page 77: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

77

while example modified

lettergrade = 'A';

cutoff = 90;

while (grade < cutoff) {

lettergrade++;

cutoff -= 10;

}

if (lettergrade > 'F')

lettergrade = 'F';

Page 78: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

78

do while

• The do while control structure also provides repetition, this time the condition is at the bottom of the loop.– the body is always executed at least once

do

somestuff;

while ( condition );

Page 79: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

79

do example

i=1;

do

cout << "i is " << i++ << endl;

while (i <= 10);

Page 80: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

80

for loops

• The for control structure is often used for loops that involve counting.

• You can write any for loop as a while (and any while as a for).

for (initialization; condition; update)

dosomething;

Page 81: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

81

for (initialization; condition; update)

• initialization is a statement that is executed at the beginning of the loop (and never again).

• the body of the loop is executed as long as the condition is true.

• the update statement is executed each time the body of the loop has been executed (and before the condition is checked)

Page 82: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

82

for example

for (i=1; i<10; i++)

cout << "i is " << i << endl;

for (i=10; i>=0; i--)

cout << "i is " << i << endl;

Page 83: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

83

for (lettergrade = 'A', cutoff = 90;

grade < cutoff; lettergrade++;)

cutoff -= 10;

if (lettergrade > 'F')

lettergrade = 'F';

con

dit

ion

another forinitialization

update

Page 84: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

84

Yet another odd example

for (i=1; i<100;i++) {

cout << "Checking " << i << endl;

if ( i%2 )

cout << i << " is odd" << endl;

else

cout << i << " is even" << endl;

}

Page 85: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

85

More about for

• You can leave the initialization, condition or update statements blank.

• If the condition is blank the loop never ends!

for (i=0; ;i++)

cout << i << endl;

Page 86: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

86

Complex Conditions

• You can build complex conditions that involve more than one relational or equality operator.

• The && (means "and") and ||(means "or") operators are used to create complex conditions.

• More operators means another precedence table...

Page 87: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

87

Updated Precedence TableOperators Precedence

() highest (applied first)

++ --

* / %

+ -

< <= > >=

== !=

&&

||

= lowest (applied last)

Page 88: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

88

&& Operator

• && is a boolean operator, so the value of an expression is true or false.

( cond1 && cond2 )

is true only if both cond1 and cond2 are true.

Page 89: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

89

&& Example

lettergrade = 'A';

cutoff = 90;

while ((grade<cutoff) && (lettergrade!='F')) {

lettergrade++;

cutoff -= 10;

}

Page 90: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

90

|| Operator

• || is a boolean operator, so the value of an expression is true or false.

( cond1 || cond2 )

is true if either of cond1 or cond2 is true.

Page 91: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

91

|| Example

if ((test1==0) || (test2==0))

cout << "You missed a test!\n";

if ((hw1==0) || (hw2==0))

cout << "You missed a homework!\n";

Page 92: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

92

The ! operator

• The ! operator is a unary boolean operator– unary means it has only 1 operand.

• ! negates it's operand.• ! means "not".

(! condition)

is true only when condition is false

Page 93: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

93

! example

bool done = false;

int i=1;

while (! done) {

cout << "i is " << i << endl;

i++;

if (i==100) done=true;

}

Page 94: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

94

Exercises(informal - not to hand in)

• Try exercises 2.12 a,d and e.

• Don't just do on paper - create programs!

• Make sure you can create, compile and run a C++ program.

• Send Dave email if you have problems:

[email protected]

Page 95: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

95

Computers and Programs

• A simplified model of a computer consists of a processing unit (CPU) and a memory.

• CPU can understand simple instructions:– read/write a memory location– add two numbers– compare numbers– etc.

Page 96: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

96

Machine Code

• An executable program is a sequence of these simple instructions.

• The sequence is stored in memory.

• The CPU processes the simple instructions sequentially.– Some instructions can tell the CPU to jump to a

new place in memory to get the next instruction.

Page 97: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

97

Instructions

• Each instruction is stored in memory as a bunch of bits.

• The CPU decodes the bits to determine what should happen.

• For example, the instruction to add 2 numbers might look like this:

10100110

Page 98: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

98

Memory

• The Memory can hold programs and data.

• Each piece of data is also just a bunch of bits.

• Typically the memory is organized in chunks of 8 bits (called a byte).

• Each chunk (byte) has an address.

Page 99: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

99

A Picture

CPUCPU...

...

MEMORY

012345

813458134681347

Address

...

...

Page 100: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

100

Sample Program

# Instruction

1 Set memory[801] to hold 00000001

2 Set memory[802] to hold 00000000

3 If memory[802] = 10 jump to instruction #8

4 increment memory[802]

5 set memory[803] to 2 times memory[801]

6 put memory[803] in to memory[801]

7 jump to instruction #3

8 print memory[801]

Page 101: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

101

Another Picture

CPUCPU

Instruction #1

Instruction #2

Instruction #3

Instruction #4

Instruction #5

Instruction #6

...

...

MEMORY

012345

801802803

Address

Page 102: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

102

Human vs Machine Programs

• The computer can only understand the bits (the encoded program)

• Humans don't like to deal with bits, so they developed english-like abbreviations for programs. Assembly Language

Machine Language

Page 103: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

103

Assembly & Machine Language

ST 1,[801]

ST 0,[802]

TOP: BEQ [802],10,BOT

INCR [802]

MUL [801],2,[803]

ST [803],[801]

JMP TOP

BOT: LD A,[801]

CALL PRINT

Assembly Language00100101 11010011

00100100 11010100

10001010 01001001 11110000

01000100 01010100

01001000 10100111 10100011

11100101 10101011 00000010

00101001

11010101

11010100 10101000

10010001 01000100

Machine Language

Page 104: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

104

An Assembler

AssemblyLanguageProgram

ST 1,[801]. . .

AssemblyLanguageProgram

ST 1,[801]. . .

MachineLanguageProgram

0100100110010100

MachineLanguageProgram

0100100110010100

AssemblerAssembler

Page 105: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

105

Higher-Level Languages

• Assembly Language is much easier to deal with than Machine Language, but you need to know about all the instructions.

• People developed languages that were independent of the specific machine language.– More abstract representation of instructions.

Page 106: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

106

High-Level Languages

• Many high-level languages have been developed.– Different ways of representing computations.– Different languages for different needs:

• symbolic vs. numeric computation

• human efficiency vs. program efficiency

• portability

• extensibility

Page 107: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

107

C++

• C++ is an extension of C.

• C++ was first developed in the early 1980s (back in the last century!).

• Focus was on Object Oriented Programming– view computer programs as collection of

objects.– Objects have attributes and actions.

Page 108: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

108

As a C/C++ program

set memory[801] to hold 00000001

set memory[802] to hold 00000000

if memory[802] = 10 jump to instruction #8

increment memory[802]

set memory[803] to 2 times memory[801]

put memory[803] in to memory[801]

jump to instruction #3

print memory[801]

x=1;

i=0;

while (i!=10) {

i++;

x=x*2;

}

printf("%d",x);

}

Page 109: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

109

Compiler

C++ Program

int main() {int i=1;. . .

C++ Program

int main() {int i=1;. . .

MachineLanguageProgram

0100100110010100

MachineLanguageProgram

0100100110010100

C++ CompilerC++ Compiler

Created with text editor or development environment

Page 110: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

110

Many Different Compilers

• There are many different C++ Compilers:– Microsoft Visual C++– Borland C++– GNU g++– IBM xlc– Sun CC

Page 111: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

C++

• what is C++?

• Why are so many programs written in C++?

Page 112: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

C++

• C++ is a third generation programming language

• machine language.

• These codes would be fed into a computer with switches, punch-cards, or primitive keypads. These programs were cumbersome to write, and very hard to debug.

• Assembly languages

Page 113: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Assembly language

• Assembly languages are considered the second generation of programming languages

Page 114: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

C++

Page 115: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

C++

• C++ is a very useful language, because it gives the programmer a lot of control, but also is abstract enough so development can be done fairly quickly.

• C++ is a very portable language as well, because it is a third-generation language, and because it has a well defined set of standards written for it.

Page 116: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

• C++ is widely used for program development under a variety of operating systems.

• Good C++ programmers are in high demand today.

Page 117: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Operator precedence in C++

• * multiplication / division % mod • + addition - subtraction • < is less than <= is less than or equal to• > is greater than >= is greater than or equal

to • == is equal to != is not equal to • && boolean and • || boolean or

Page 118: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

• using namespace std;#include <iostream> // This is a key C++ library#include <cmath> // The standard C library math.h

int main (){ double a;

a = 1.2; a = sin (a);

cout << a << endl;

return 0;}

Page 119: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

• using namespace std; // Using the standard library namespace.#include <iostream> // The iostream library is often used.

int main () // The program's main routine.{ double a; // Declaration of variable a.

a = 456.47; a = a + a * 21.5 / 100; // A calculation.

cout << a << endl; // Display the content of a.

return 0; // Program end.}

Page 120: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

• Output This is a sample program.

Type your age : 12Type your name: Emad       

Hello Emad you're 12 old.

Bye!

Page 121: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

A global variable can be accessed even if another variable

with the same name has been declared inside the function: • using namespace std;

#include <iostream>

double a = 128;

int main (){ double a = 256;

cout << "Local a: " << a << endl; cout << "Global a: " << ::a << endl;

return 0;}

Local a:  256Global a: 128

Page 122: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

Mathematical functions #include <stdio.h>#include <math.h>voied main(voied){double x=3.0 ,y=4.0,a,b,c,d,e,f;float g;a=sin(x);b=exp(x);c=log(x);d=sqrt(x);f=pow(x,y); // x^ye=sin(x) - log10(y);G=log(x)

printf(“x=%4.1f%s",s); // return 0;}

Page 123: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

if statement

• The first type of branching statement we will look at is the if statement. An if statement has the form:

• if (condition) { // code to execute if condition is true } else { // code to execute if condition is false } In an if statement, condition is a value or an expression that is used to determine which code block is executed, and the curly braces act as "begin" and "end" markers.

Page 124: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba
Page 125: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

If statement

• account type interest earned

• personal financial 2.3%

• personal homeowner 2.6%

• personal gold 2.9%

• small business 3.3%

• big business 3.5%

• gold business 3.8%

Page 126: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba

switch statement

Page 127: 1 King Saud university Programming in C++ GE 211 Dr. Ahmed Telba