MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

324
Lecture 3 (Conditional Statement) Dr. Nelidya Md Yusoff Department of Electrical Engineering UTM Razak School MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Transcript of MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Page 1: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Lecture 3 (Conditional Statement)

Dr. Nelidya Md Yusoff

Department of Electrical Engineering UTM Razak School

MRSL 1163

SCIENTIFIC COMPUTING FOR

SYSTEM ENGINEER

Page 2: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Topics (Decision Making)

The if Statement

The if/else Statement

The if/else if Statement

4-2

condition

1 or more

statements

true false

Page 3: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Relational Operators

• Allow to compare numeric and char

values and determine relative order

• Operators:

4-3

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

== Equal to

!= Not equal to

Page 4: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Relational Expressions

• Relational expressions are Boolean (i.e., the value can be true or false)

• Examples:12 > 5 is true

7 <= 5 is false

if x is 10, then

x == 10 is true,

x != 8 is true, and

x == 8 is false4-4

Page 5: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Relational Expressions

• Can be assigned to a variable

bool result = (x <= y);

• Assigns 0 for false, 1 for true

• Do not confuse = (assignment) and

== (equal to)

4-5

Page 6: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The if Statement

• Allows statements to be conditionally

executed or skipped over

• Models the way we mentally evaluate

situations

1. if (it is cold outside)wear a coat and wear a hat;

2. if (it is cold outside)wear a coat; wear a hat;

4-6

Page 7: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Format of the if Statement

if (condition){

statement1;

statement2;

statementn;

}

The block inside the braces is called the body of the if statement.

If there is only 1 statement in the body, the { }may be omitted.

4-7

No ;goes here

; goes here

Page 8: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

How the if Statement Works

• If (condition) is true, then the statement(s) in the body are executed.

• If (condition) is false, then the statement(s) are skipped.

4-8

Page 9: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

if Statement in Program 4-2

Continued…

Page 10: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

if Statement in Program 4-2

{}

Page 11: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example if Statements

int score;

char grade;

if (score >= 60){

cout << "You passed.\n";

}

if (score >= 90){

grade = 'A';

cout << "Wonderful job!\n";

}

4-11

Page 12: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

if Statement Notes

• Do not place ; after (condition)

• Don't forget the { } around a multi-

statement body

• Place each statement; on a separate line after (condition), indented

• 0 is false; any other value is true

4-12

Page 13: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

• Relational expressions are not only the

conditions that may be tested.

• Ex. – if (value){ bool value = true;

Cout << “It is true!”;

}

– if (x + y){ int x = 10, y = 0;

Cout << “It is true!”;

}

– if (pow(a, b)){ double a; int b;

Cout << “It is true!”;

}4-13

Page 14: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise

• if it is cold outside is true

– Display “Please wear a coat”;

– Display “Please wear a hat”;

– Display “Please wear gloves”;

Page 15: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The if/else Statement

• Allows a choice between statements depending on whether (condition)is true or false

• Format: if (condition){ statement set 1;

}

else{

statement set 2;

}

4-15

Page 16: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

if/else Flow of Control

4-16

condition

statement

set 1

true false

statement

set 2

Page 17: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

How the if/else Works

• If (condition) is true, statementset 1 is executed and statement set

2 is skipped.

• If (condition) is false, statementset 1 is skipped and statement set 2

is executed.

4-17

Page 18: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The if/else statement and Modulus Operator in Program 4-8

Page 19: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example if/else Statements

if (score >= 60){

cout << "You passed.\n";

}

else{

cout << "You did not pass.\n";}

if (intRate > 0){

interest = loanAmt * intRate;

cout << interest;

}

else{

cout << "You owe no interest.\n";

}

4-19

Page 20: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise

• if it is cold outside is true

– Display “Please wear a coat”;

– Display “Please wear a hat”;

– Display “Please wear gloves”;

• else

– Display “It’s hot today”;

Page 21: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The if/else if Statement

• Chain of if statements that test in order until one is found to be true

• Also models thought processes

“If it is raining, take an umbrella,

else, if it is windy, take a hat,

else, if it is sunny, take sunglasses.”

4-21

Page 22: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

if/else if Format

if (condition 1){

statement set 1;

}

else if (condition 2){

statement set 2;

}

else if (condition n){

statement set n;

}

4-22

Page 23: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Using a Trailing else

• Chain of if statements. They perform their tests one after the other until one of them is found to be true.

• Used with if/else if statement when all of the conditions are false

• Provides a default statement or action

• Can be used to catch invalid values or handle

other exceptional situations

4-23

Page 24: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example if/else if with Trailing else

if (age >= 21){

cout << "Adult";

}

else if (age >= 13){

cout << "Teen";

}

else if (age >= 2){

cout << "Child";

}

else{

cout << "Baby";

}

4-24

Page 25: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Nested if Statements

• An if statement that is part of the if or else part of

another if statement

• Can be used to evaluate > 1 data item or condition

if (score < 100){

if (score > 90){

grade = “A+”;

}

else if (score > 80){

grade = “A”;

}

}

4-25

Page 26: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Notes on Coding Nested ifs

• An else matches the nearest if that does not have an else

if (score < 100){

if (score > 90){

grade = 'A';

}

else ... // goes with second if,

// not first one

}

• Proper indentation aids comprehension

4-26

Page 27: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise

• if it is cold outside is true

– Display “Please wear a coat”;

– Display “Please wear a hat”;

– Display “Please wear gloves”;

• Else if it is raining today

– Display “Please wear rain coat”;

• Else

– Display “It’s hot today”;

Page 28: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Logical Operators

Connect two or more relational expressions into one or reverse the logic of an expression.

Operators, Meaning, and Explanation

4-28

&& AND New relational expression is true if both expressions are true

|| OR New relational expression is true if either expression is true

! NOTReverses the value of an expression; true expression becomes false, false expression becomes true

Page 29: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

29

Logical Operator Examples

int x = 12, y = 5, z = -4;

(x > y) && (y > z) true

(x > y) && (z > y) false

(x <= z) || (y == z) false

(x <= z) || (y != z) true

!(x >= z) false

Page 30: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Logical Precedence

Highest ! (!(x + y), (!x + y)

&&

Lowest ||

Example:(2 < 3) || (5 > 6) && (7 > 8)

is true because AND is evaluated before OR 4-30

Page 31: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

31

More on Precedence

Example:

8 < 2 + 7 || 5 == 6 is true

logical operatorsLowest

relational operators

arithmetic operatorsHighest

Page 32: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Checking Numeric Ranges with Logical Operators

• Used to test if a value is within a rangeif (grade >= 0 && grade <= 100)

cout << "Valid grade";

• Can also test if a value lies outside a range

if (grade <= 0 || grade >= 100)

cout << "Invalid grade";

• Cannot use mathematical notationif (0 <= grade <= 100) //Doesn’t

//work!4-32

Page 33: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

ExamplePlease input grade.

if (grade >= 0 && grade <= 100) {

cout << "Valid grade";

if (grade > 90){

cout << “You have obtained A+”;

}

else if (grade > 80){

cout << “You have obtained A”;

}

else {

cout << “You have to work hard”;

}

}

else if (grade <= 0 || grade >= 100)

cout << "Invalid grade";

Page 34: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise.1

• Write a C++ program that calculates the

gross pay of hari kurban month:

– If the salary is over RM5000 then the bonus to

be paid is RM500

– Otherwise, if the salary is over RM2000 then

the bonus to be paid is RM300

– Otherwise, the salary is over RM1000 then the

bonus to be paid is RM200

– Else, the bonus to be paid is RM100

Page 35: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise.2

• Write a C++ program that asks the user to

enter two numbers. The program should

use the conditional operator to determine

which number is smaller and which is the

larger.

Page 36: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise.3

• Write a C++ program that asks the user to

enter a number within the range of 1

through 10.

– Display the Roman numeral version of that

number.

Page 37: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The Conditional Operator

• Can use to create short if/elsestatements

• Format: expr ? expr : expr;

4-37

Page 38: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The switch Statement

• Used to select among statements from several alternatives

• May sometimes be used instead of if/else if statements

4-38

Page 39: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

switch Statement Format

switch (IntExpression)

{

case exp1:

statement set 1;

case exp2:

statement set 2;

...

case expn:

statement set n;

default:

statement set

n+1;

}4-39

Page 40: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

switch Statement Requirements

1) IntExpression must be a char or

an integer variable or an expression that evaluates to an integer value

2) exp1 through expn must be constant

integer type expressions and must be unique in the switch statement

3) default is optional but recommended

4-40

Page 41: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

How the switch Statement Works

1) IntExpression is evaluated

2) The value of intExpression is compared against exp1 through expn.

3) If IntExpression matches value expi, the program branches to the statement(s) following expi and continues to the end of the switch

4) If no matching value is found, the program branches to the statement after default:

4-41

Page 42: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The break Statement

• Used to stop execution in the current block

• Also used to exit a switch statement

• Useful to execute a single casestatement without executing statements following it

4-42

Page 43: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example switch Statement

switch (gender){

case 'f':

cout << "female";

break;

case 'm':

cout << "male";

break;

default :

cout << "invalid

gender";

}4-43

Page 44: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The switch Statement in Program 4-23

Page 45: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

break and default

Continued…

Page 46: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER
Page 47: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Ladder

47

#include <iostream> using namespace std; int main() { int x; for(x=0; x<6; x++) { if(x==1) cout << "x is one\n"; else if(x==2) cout << "x is two\n"; else if(x==3) cout << "x is three\n"; else if(x==4) cout << "x is four\n"; else cout << "x is not between 1 and 4\n"; } return 0; }

Page 48: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise

48

Write a program that asks the user to enter anumber within the range of 1 through 100 (onlymultiple of 10). Use a switch statement todisplay the Roman numeral version of thatnumber.

Page 49: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Lecture 4 (Loop)

Dr Nelidya Md Yusoff

Department of Electrical Engineering UTM Razak School

MRSL 1163

SCIENTIFIC COMPUTING FOR

SYSTEM ENGINEER

Page 50: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Topics

The Increment and Decrement Operators

Introduction to Loops: The while Loop

Using the while loop for Input Validation

Counters

The do-while loop

The for loop

5-2

Page 51: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The Increment and Decrement Operators

• ++ is the increment operator.

It adds one to a variable.

val++; is the same as val = val + 1;

• ++ can be used before (prefix) or after (postfix) a variable:++val; val++;

Page 52: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The Increment and Decrement Operators

• -- is the decrement operator.

It subtracts one from a variable.

val--; is the same as val = val - 1;

• -- can be also used before (prefix) or after (postfix) a variable:--val; val--;

Page 53: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Increment and DecrementOperators in Program 5-1

Continued…

Page 54: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Increment and DecrementOperators in Program 5-1

Page 55: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Prefix vs. Postfix

• ++ and -- operators can be used in complex statements and expressions

• In prefix mode (++val, --val) the operator increments or decrements, then returns the value of the variable

• In postfix mode (val++, val--) the operator returns the value of the variable, then increments or decrements

Page 56: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Prefix vs. Postfix - Examples

int num, val = 12;

cout << val++; // displays 12,

// val is now 13;

cout << ++val; // sets val to 14,

// then displays it

num = --val; // sets val to 13,

// stores 13 in num

num = val--; // stores 13 in num,

// sets val to 12

Page 57: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Notes on Increment and Decrement

• Can be used in expressions:result = num1++ + --num2;

• Must be applied to something that has a

location in memory. Cannot have:result = (num1 + num2)++;

• Can be used in relational expressions:if (++num > limit)

pre- and post-operations will cause different

comparisons

Page 58: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Loops

• A loop is a part of programs that repeats

• A loop is a control structure that causes a

statement or group of statements to

repeat.

• C++ has three looping control structures:

– foor loop

– while loop

– do-while loop

Page 59: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The for Loop• The foor loop is a pretest loop that combines the

initialization, testing, and updating of a loop control

variable in a single loop header

• Foor loop is a count-controlled loop. A loop that repeats a

specific number of times is known as count-controlled

loop.

• General Format:for(initialization; test; update){

statement;

}

• No semicolon after the update expression or after the )

Page 60: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop - Mechanics

for(initialization; test; update)

statement; // or block in { }

1) Perform initialization

2) Evaluate test expression– If true, execute statement

– If false, terminate loop execution

3) Execute update, then re-evaluate test

expression

Page 61: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop - Example

int count;

for (count = 0; count <= 10; count++){

cout << "Hello MJIIT" << endl;

}

Page 62: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

A Closer Look at the Previous Example

Page 63: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Flowchart for the Previous Example

Page 64: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

A for Loop in Program 5-9

Continued…

Page 65: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

A for Loop in Program 5-9

Page 66: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

A Closer Look at Lines 15 through 16 in Program 5-9

Page 67: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Flowchart for Lines 15 through 16 in Program 5-9

Page 68: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

When to Use the for Loop

• In any situation that clearly requires

– an initialization

– a false condition to stop the loop

– an update to occur at the end of each iteration

Page 69: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The for Loop is a Pretest Loop

• The for loop tests its test expression

before each iteration, so it is a pretest

loop.

• Check the following loop (?):

for (count = 11; count <= 10; count++){

cout << "Hello" << endl;

}

Page 70: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop - Modifications

• You can have multiple statements in the initialization expression. Separate the statements

with a comma:

int x, y;

for (x=1, y=1; x <= 5; x++){

cout << x << " plus " << y

<< " equals " << (x+y)

<< endl;

}

Initialization Expression

Page 71: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop - Modifications

• You can also have multiple statements in the test expression. Separate the statements with a comma:

int x, y, result;for (x=1, y=5; x <= 5 || y <8; x++, y++){

result = x + y;cout << x << " plus " << y

<< " equals " << (x+y)<< endl;

}

cout << result;

Test Expression

Page 72: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop - Modifications

• You can omit the initialization

expression if it has already been done:

int sum = 0, num = 1;

for (; num <= 10; num++){

sum += num;

// sum = sum + num;

}

Page 73: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop - Modifications

• You can declare variables in the initialization expression:

int sum = 0;

for (int num = 0; num <= 10; num++){

sum += num;

}

The scope of the variable num is the for loop.

Page 74: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise-1, 2, 3

• Write a program that displays odd and

even numbers between 1 and 10

(for/while/do-while Loop)

• Write a loop that displays the following set

of numbers (for/while/do-while Loop) :

0, 5, 15, 20, 25, 35, 40, …, 100

Page 75: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise-4

• Write a program that displays prime

numbers between 1 and 100.

Page 76: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Nested Loops (Prime Number)for (num=1; num<=10; num++){ //outer

for (x=2; x < num; x++){//inner

if ( num % x ==0){

cout << num << “: is not a prime

number”<<endl;

break;

}

}

if ( num == x){

cout << num << “: IS a PRIME

number”<<endl;

}

}

Page 77: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Ex.

• Write a program that displays odd number

numbers between 0 and 20.

Page 78: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop Flow of Control

5-30

true

statement(s)

falsetest

initialization

code

update

code

Page 79: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The for Loop

• Pretest loop that executes zero or more times

• Useful for counter-controlled loop

• Format:

for( initialization; test; update )

{ 1 or more statements;

}

5-31

No ; goes

here

Required ;

Page 80: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop Mechanics

5-32

Page 81: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop Example

int sum = 0, num;

for (num = 1; num <= 10; num++){

sum += num;

}

cout << "Sum of numbers 1 – 10 is

"

<< sum << endl;

5-33

Page 82: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop Notes

• If test is false the first time it is evaluated, the body of the loop will not be executed

• The update expression can increment or decrement by any amount

• Variables used in the initialization section should not be modified in the body of the loop

5-34

Page 83: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

for Loop Modifications

• Can define variables in initialization code– Their scope is the for loop

• Initialization and update code can contain more than one statement

– Separate statements with commas

• Example:for (int sum = 0, num = 1; num <= 10; num++)

sum += num;

5-35

Page 84: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

More for Loop Modifications(These are NOT Recommended)

• Can omit initialization if already done

int sum = 0, num = 1;for (; num <= 10; num++)

sum += num;

• Can omit update if done in loop

for (sum = 0, num = 1; num <= 10;)sum += num++;

• Can omit test – may cause an infinite loop

for (sum = 0, num = 1; ; num++)sum += num;

• Can omit loop body if all work is done in header

5-36

Page 85: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

while Loop is a Pretest Loop

• while is a pretest loop (condition is evaluated before the loop executes)

• If the condition is initially false, the statement(s) in the body of the loop are never executed

• If the condition is initially true, the statement(s) in the body continue to be executed until the condition becomes false

5-37

Page 86: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The while Loop

• Loop: part of program that may execute >

1 time (i.e., it repeats)

• while loop format:while (condition)

{ statement(s);

}

• The {} can be omitted if there is only one

statement in the body of the loop

5-38

No ; here

Page 87: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

How the while Loop Works

while (condition)

{ statement(s);

}

condition is evaluated

– if it is true, the statement(s) are executed,

and then condition is evaluated again

– if it is false, the loop is exited

5-39

Page 88: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

while Loop Flow of Control

5-40

true

statement(s)

false

condition

Page 89: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

while Loop Example

int val = 5;

while (val >= 0)

{ cout << val << " ";

val--;

}

• produces output:

5 4 3 2 1 0

5-41

Page 90: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exiting the Loop

• The loop must contain code to allow condition to eventually become falseso the loop can be exited

• Otherwise, you have an infinite loop (i.e., a loop that does not stop)

• Example infinite loop:x = 5;

while (x > 0) // infinite loop because

cout << x; // x is always > 0

5-42

Page 91: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Common Loop Errors

• Don’t forget the { } :int numEntries = 1;

while (numEntries <=3)

cout << "Still working … ";

numEntries++; // not in the loop body

• Don’t use = when you mean to use ==while (numEntries = 3) // always true

{

cout << "Still working … ";

numEntries++;

}

5-43

Page 92: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Using the while Loop for Input Validation

Loops are an appropriate structure forvalidating user input data

1. Prompt for and read in the data.

2. Use a while loop to test if data is valid.

3. Enter the loop only if data is not valid.

4. Inside the loop, display error message and prompt the user to re-enter the data.

5. The loop will not be exited until the user enters valid data.

5-44

Page 93: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Input Validation Loop Example

cout << "Enter a number (1-100) and"

<< " I will guess it. ";

cin >> number;

while (number < 1 || number > 100){

cout << "Number must be between 1 and 100."

<< " Re-enter your number. ";

cin >> number;

}

// Code to use the valid number goes here.

5-45

Page 94: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Letting the User Control the Loop

• Program can be written so that user input determines loop repetition

• Can be used when program processes a list of items, and user knows the number of items

• User is prompted before loop. Their input is used to control number of repetitions

5-46

Page 95: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

User Controls the Loop Example

int num, limit;

cout << "Table of squares\n";

cout << "How high to go? ";

cin >> limit;

cout << "\n\nnumber square\n";

num = 1;

while (num <= limit)

{ cout << setw(5) << num << setw(6)

<< num*num << endl;

num++;

}

5-47

Page 96: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The do-while Loop

• do-while: a post test loop (conditionis evaluated after the loop executes)

• Format:do {

1 or more statements;

} while (condition);

5-48

Notice the

required ;

Page 97: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

do-while Flow of Control

5-49

statement(s)

condition

false

true

Page 98: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

do-while Loop Notes• Loop always executes at least once

• Execution continues as long as condition is true; the loop is exited when condition becomes false

• Useful in menu-driven programs to bring user back to menu to make another choice

5-50

int sum = 0, num = 1; // sum is the

char again;

do {

sum += num;

num++;

cin >> again;

} while (again == ‘Y’ || again == ‘y’);

Example.

Page 99: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise-1, 2, 3

• Write a program that displays odd and

even numbers between 1 and 10

(for/while/do-while Loop)

• Write a loop that displays the following set

of numbers (for/while/do-while Loop) :

0, 5, 15, 20, 25, 35, 40, …, 100

Page 100: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Deciding Which Loop to Use

• while: pretest loop (loop body may not be executed at all)

• do-while: post test loop (loop body will always be executed at least once)

• for: pretest loop (loop body may not be executed at all); has initialization and update code; is useful with counters or if precise number of repetitions is known

52

Page 101: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Nested Loops

• A nested loop is a loop inside the body of another loop

• Example:for (row = 1; row <= 3; row++)

{

for (col = 1; col <= 3; col++)

{

cout << row * col << endl;

}

}

outer loop

inner loop

53

Page 102: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Notes on Nested Loops

• Inner loop goes through all its repetitions

for each repetition of outer loop

• Inner loop repetitions complete sooner

than outer loop

• Total number of repetitions for inner loop

is product of number of repetitions of the

two loops. In previous example, inner loop

repeats 9 times

54

Page 103: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Nested Loops (Prime Number)for (num=1; num<=10; num++){ //outer

for (x=2; x < num; x++){//inner

if ( num % x ==0){

cout << num << “: is not a prime

number”<<endl;

break;

}

}

if ( num == x){

cout << num << “: IS a PRIME

number”<<endl;

}

}

Page 104: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

• Write a program by using a nested loops

that displays prime numbers between 1

and 100.

Exercise 4

56

Page 105: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

using namespace std;

int main()

{

int x;

for (int num=1; num<=100; num++){ //outer loop

for (x=2; x < num; x++){ //inner loop

if ( num % x ==0){

cout << num <<": is not a prime number"<<endl;

break;

}

}

if ( num == x){

cout << num <<": IS a PRIME number"<<endl;

}

}

return 0;

}

Exercise 4 - answer

57

Page 106: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Breaking Out of a Loop

• Can use break to terminate execution of

a loop

• Use sparingly if at all – makes code

harder to understand

• When used in an inner loop, terminates

that loop only and returns to the outer

loop

58

Page 107: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The continueStatement

• Can use continue to go to end of loop and prepare for next repetition

– while and do-while loops go to test and

repeat the loop if test condition is true

– for loop goes to update step, then tests, and

repeats loop if test condition is true

• Use sparingly – like break, can makeprogram logic hard to follow

59

Page 108: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

• A statement break and continue are important in loop usage.

• break will stop the loop i.e. the program goes straight to the following statement.

• continue stop the current iteration and continue to the next iteration.

60

The break andcontinue Statements

Page 109: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

61

The break andcontinue Statements

Page 110: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

{

int count,total,totalS,num;

count=1;

total=0;

while (count <=10)

{

cout<<“Please enter number "<<count<<” :”;

cin>> num;

if (num<=0)

{

cout<<“You enter a wrong number"<<endl;

continue;

}

62

The break and continue Statements - Example

Page 111: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

count=count+1;

totalT=total //totalT=Temperory total

total=total+num;

if (total>20)

{

cout<<"\nNumber is enough.“ <<endl;

cout<<"Thank you.\n"<<endl;

total=totalT

break;

}

}

cout<<“Total number is "<< total <<"\n"<<”.”<<endl;

return 0;

}

63

The break and continue Statements - Example

Page 112: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

64

The break and continue Statements - Example

Output:

Please enter number 1: -12

You enter a wrong number

Please enter number 1: 2

Please enter number 2: 12

Please enter number 3: 10

Number is enough.

Thank you.

Total number is 14.

Page 113: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Counters

• Counter: variable that is incremented or

decremented each time a loop repeats

• Can be used to control execution of the

loop (loop control variable)

• Must be initialized before entering loop

• May be incremented/decremented either

inside the loop or in the loop test

5-65

Page 114: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

DR. NELIDYA MD. YUSOFFUTM RAZAK SCHOOL OF ENGINEERING AND ADVANCED TECHNOLOGY

MRSL 1163

SCIENTIFIC COMPUTING FOR

SYSTEM ENGINEER

Page 115: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Defining and Calling Functions

• Function definition: A collection of statements that perform a specific task

• Function call: statement causes a function to execute

Page 116: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

int main (){

//Odd number

-------

-------

//Even Number

-------

-------

//MaxMin number

-------

-------

//Even Number

-------

-------

//odd Number

-------

return 0;

}

Writing codes inside main function

int primeNumberFunction(){

-------

retun val;

}

int oddEvenFunction(){

-------

retun val;

}

string romanNumberFunction(){

-------

retun “X”;

}

int maxMinFunction(){

-------

retun val;

}

Page 117: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

int main(){

primeNumberFunction();

oddEvenFunction();

romanNumberFunction();

fibanocciNumberFunction();

----------------------

primeNumberFunction();

maxMinFuction();

retrun 0;

}

Page 118: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Function Definition

• Definition includes:

• return type: data type of the value that function returns to the part of the program that called it

• int

• name: name of the function. Function names follow same rules as variables

• main

• parameter list: variables containing values passed to the function

• ( ) - EMPTY

• body: statements that perform the function’s task, enclosed in {}

Page 119: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Function Definition

Note: The line that reads int main()is the function header.

Page 120: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Function Return Type

• If a function returns a value, the type of the value must be indicated:

void main()

• If a function does not return a value, its return type is void:

void printHeading(int num){

cout << “My Monthly Sales is :“ << num;

}

int printHeading(){

cout << “My Monthly Sales not sure :“;

return 1;

}

Page 121: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Calling a Function

• A function is executed when it is called

• Need to define a function before it is called.

• To call a function, use the function name followed by () and ;

printHeading();

myFunction(5, 6);

int myFunction(int x, int y){

---

return 1;

}

• When called, program executes the body of the called function

• After the function terminates, execution resumes in the calling function at point of call.

Page 122: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Functions in Program 6-1

Page 123: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Flow of Control in Program 6-1

Page 124: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Calling Functions

• main can call any number of functions

• Functions can call other functions

• Compiler must know the following about a function before it is called:

• name

• return type

• number of parameters

• data type of each parameter

Page 125: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Function Prototypes

• Eliminates the need to place a function definition before it is called

void first ();

• Ways to notify the compiler about a function before a call to the function:

1.Place function definition before calling function’s definition

2.Use a function prototype (function declaration) – like the function definition without the body

• Header: void printHeading()

• Prototype: void printHeading();

Page 126: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

(Program Continues)

Page 127: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Program 6-5 (Continued)

Page 128: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Prototype Notes

• Place prototypes near top of program

• Program must include either prototype or full function definition before any call to the function – compiler error otherwise

• When using prototypes, can place function definitions in any order in source file

Page 129: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Sending Data into a Function

• Can pass values into a function at time of call:

• int a, b, c;• cin >> a >> b;

c = pow(a, b);

• Values passed to function are arguments

• Variables in a function that hold the values passed as arguments are parameters

Page 130: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

A Function with a Parameter Variable

void displayValue(int num){

cout << "The value is " << num << endl;

}

void displayValue(){

cout << "The value is " << num << endl;

}

displayValue(num);

The integer variable num is a parameter. It accepts any integer value

passed to the function.

Page 131: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

(Program Continues)

Page 132: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER
Page 133: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The function call in line 11 passes the value 5 as an argument to the

function.

Page 134: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Parameters, Prototypes, and Function Headers

• For each function argument,• the prototype must include the data type of each parameter inside its

parentheses

• the header must include a declaration for each parameter in its ()

void evenOrOdd(int); //prototype

void evenOrOdd(int num) //header

evenOrOdd(val); //call

Page 135: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Passing Multiple Arguments

When calling a function and passing multiple arguments:

• the number of arguments in the call must match the prototype and definition

• the first argument will be used to initialize the first parameter, the second argument to initialize the second parameter, etc.

Page 136: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

(Program Continues)

Page 137: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Program 6-8 (Continued)

Page 138: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The function call in line 18 passes value1, value2, and value3 as a

arguments to the function.

Page 139: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Passing Data by Value

• Pass by value: when an argument is passed to a function, its value is copied into the parameter.

• Changes to the parameter in the function do not affect the value of the argument

Page 140: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Passing Information to Parameters by Value

• Example: int val=5;

evenOrOdd(val);

• evenOrOdd can change variable num, but it will have no effect on variable val

5

val

argument in

calling function

5

num

parameter inevenOrOdd function

Page 141: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The return Statement

• Used to end execution of a function

• Can be placed anywhere in a function• Statements that follow the return statement will not be executed

• Can be used to prevent abnormal termination of program

• In a void function without a return statement, the function ends at its last }

Page 142: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

(Program Continues)

Page 143: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Program 6-11(Continued)

Page 144: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Returning a Value From a Function

• A function can return a value back to the statement that called the function.

• You've already seen the pow function, which returns a value:

double x;

x = pow(2.0, 10.0);

Page 145: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Returning a Value From a Function

• In a value-returning function, the return statement can be used to return a value from function to the point of call. Example:

int sum(int num1, int num2)

{

double result;

result = num1 + num2;

return result;

}

Page 146: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

A Value-Returning Function

int sum(int num1, int num2)

{

double result;

result = num1 + num2;

return result;

}

Return Type

Value Being Returned

Page 147: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

A Value-Returning Function

int sum(int num1, int num2)

{

return num1 + num2;

}

Functions can return the values of expressions, such as num1 + num2

Page 148: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

(Program Continues)

Page 149: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Program 6-12 (Continued)

Page 150: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The statement in line 17 calls the sum function, passing value1 and value2 as arguments. The return value is

assigned to the total variable.

Page 151: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Another Example, from Program 6-13

Page 152: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Returning a Value From a Function

• The prototype and the definition must indicate the data type of return value (not void)

• Calling function should use return value:• assign it to a variable

• send it to cout

• use it in an expression

Page 153: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Returning a Boolean Value

• Function can return true or false

• Declare return type in function prototype and heading as bool

• Function body must contain return statement(s) that return true or false

• Calling function can use return value in a relational expression

Page 154: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

(Program Continues)

Page 155: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER
Page 156: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Local and Global Variables

• Variables defined inside a function are local to that function. They are hidden from the statements in other functions, which normally cannot access them.

• Because the variables defined in a function are hidden, other functions may have separate, distinct variables with the same name.

Page 157: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER
Page 158: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

When the program is executing in main, the num variable

defined in main is visible. When anotherFunction is called,

however, only variables defined inside it are visible, so the num

variable in main is hidden.

Page 159: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Local Variable Lifetime

• A function’s local variables exist only while the function is executing. This is known as the lifetime of a local variable.

• When the function begins, its local variables and its parameter variables are created in memory, and when the function ends, the local variables and parameter variables are destroyed.

• This means that any value stored in a local variable is lost between calls to the function in which the variable is declared.

Page 160: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Global Variables and Global Constants

• A global variable is any variable defined outside all the functions in a program.

• The scope of a global variable is the portion of the program from the variable definition to the end.

• This means that a global variable can be accessed by allfunctions that are defined after the global variable is defined.

• You should avoid using global variables because they make programs difficult to debug.

• Any global that you create should be global constants.

Page 161: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Global constants defined for

values that do not change throughout

the program’s execution.

Page 162: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The constants are then used for those values

throughout the program.

Page 163: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Initializing Local and Global Variables

• Local variables are not automatically initialized. They must be initialized by programmer.

• Global variables (not constants) are automatically initialized to 0(numeric) or NULL (character) when the variable is defined.

Page 164: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Static Local Variables

• Local variables only exist while the function is executing. When the function terminates, the contents of local variables are lost.

• static local variables retain their contents between function calls.

• static local variables are defined and initialized only the first time the function is executed. 0 is the default initialization value.

Page 165: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

(Program Continues)

Page 166: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

In this program, each time showLocal is called, the localNum variable

is re-created and initialized with the value 5.

Page 167: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

A Different Approach, Using a Static Variable

(Program Continues)

Page 168: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

statNum is automatically initialized to

0. Notice that it retains its value between

function calls.

Page 169: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

If you do initialize a local static variable, the initialization

only happens once. See Program 6-23.

Page 170: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Default Arguments

A Default argument is an argument that is passed automatically to a parameter if the argument is missing on the function call.

• Must be a constant declared in prototype:

void evenOrOdd(int = 0);

• Can be declared in header if no prototype

• Multi-parameter functions may have default arguments for some or all of them:

int getSum(int, int=0, int=0);

6-57

Page 171: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Default arguments specified in the prototype

(Program Continues)

Page 172: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Program 6-23 (Continued)

Page 173: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Using Reference Variables as Parameters

• A mechanism that allows a function to work with the original argument from the function call, not a copy of the argument

• Allows the function to modify values stored in the calling environment

• Provides a way for the function to ‘return’ more than one value

Page 174: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Passing by Reference

• A reference variable is an alias for another variable

• Defined with an ampersand (&)void getDimensions(int&, int&);

• Changes to a reference variable are made to the variable it refers to

• Use reference variables to implement passing parameters by reference

Page 175: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The & here in the prototype indicates that the

parameter is a reference variable.

Here we are passing value by

reference.

(Program Continues)

Page 176: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The & also appears here in the

function header.

Program 6-25 (Continued)

Page 177: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Reference Variable Notes

• Each reference parameter must contain &

• Space between type and & is unimportant

• Must use & in both prototype and header

• Argument passed to reference parameter must be a variable – cannot be an expression or constant

• Use when appropriate – don’t use when argument should not be changed by function, or if function needs to return only 1 value

Page 178: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Overloading Functions

• Overloaded functions have the same name but different parameter lists

• Can be used to create functions that perform the same task but take different parameter types or different number of parameters

• Compiler will determine which version of function to call by argument and parameter lists

Page 179: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Function Overloading Examples

Using these overloaded functions,void getDimensions(int); // 1

void getDimensions(int, int); // 2

void getDimensions(int, double); // 3

void getDimensions(double, double);// 4

the compiler will use them as follows:int length, width;

double base, height;

getDimensions(length); // 1

getDimensions(length, width); // 2

getDimensions(length, height); // 3

getDimensions(height, base); // 4

Page 180: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The overloaded

functions have different

parameter lists

Passing an int

Passing a double

(Program Continues)

Page 181: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Program 6-27 (Continued)

Page 182: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The exit() Function

• Terminates the execution of a program

• Can be called from any function

• Can pass an int value to operating system to indicate status of program termination

• Usually used for abnormal termination of program

• Requires cstdlib header file

Page 183: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

The exit() Function

• Example:

exit(0);

• The cstdlib header defines two constants that are commonly passed, to indicate success or failure:

exit(EXIT_SUCCESS);

exit(EXIT_FAILURE);

Page 184: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Lecture 6 (Arrays)

Dr Nelidya Md Yusoff

Department of Electrical Engineering UTM Razak School

MRSL 1163

SCIENTIFIC COMPUTING FOR

SYSTEM ENGINEER

Page 185: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

ARRAY

• A form of variable from usual data type such as int, double and char

• Able to store a group of data of the same data

type under one name.

• Example (in 1D-ARRAY) :

for variable mark[100]:

- 100 memory cell are provided

• Array allows to store and work with multiple

values of the same data type

• Values are stored in adjacent memory locations

2

Page 186: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

3

• Array

– Consecutive group of memory locations

– Same name and type (int, char, etc.)

• To refer to an element

– Specify array name and position number (index)

– Format: arrayname [ position number ]

– First element at position 0

• N-element array cc[ 0 ], c[ 1 ] … c[ n - 1 ]

– Nth element as position N-1

Page 187: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Introduction to Arrays

• Array: variable that can store multiple values or a group of the same data type under one name.

• Usual data type such as int,double and char.

• Values are stored in adjacent memory locations.

• Declared using [ ] operator:

int tests[5];

4

Page 188: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

• Variable declaration so far can hold only one

value at a time

int val = 5; // enough memory for 1

int (4 Bytes)

char letter = ‘A’; // enough memory

for 1 char (1 Byte)

Double price = 56.981; // enough

memory for 1 double (8 Bytes)

Introduction to Arrays

5

Page 189: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Array Terminology

In the definition int tests[5];

• int is the data type of the array elements

• tests is the name of the array

• 5, in [5], is the size declarator. It shows the number of elements in the array.

• The size of an array is (number of elements) * (size of each element)

6

Page 190: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Array Terminology

• The size of an array is:– the total number of bytes allocated for it

– (number of elements) * (number of bytes for each element)

• Examples:int tests[5] is an array of 20 bytes, assuming 4 bytes for an int

long double measures[10]is an array of 80 bytes, assuming 8 bytes for a long double

7

Page 191: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

• The definition:

int tests[5]; // size is 5

allocates the following memory:

• tests - name of the array, read as tests sub 5

• 5 - the number of elements or values that

tests can hold

first element

second element

third element

fourth element

fifth element

Array Definition

8

Page 192: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Size Declarators

• Named constants are commonly used as size declarators.const int SIZE = 5;

int tests[SIZE];

• This eases program maintenance when the size of the array needs to be changed.

9

Page 193: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Array Declaration

• Syntax:

DataType variable1 [n1],

variable2 [n2];

• n1 and n2 are called size declaration for array.

• Example:

int mark[100];

long stress[15];

float quiz[60];

10

Page 194: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

• With this declaration, in RAM

• In C++,

– element starts with 0 subscript

– Ends with n-i subscript where n is the size declaration.

• In n=100 in mark[100], then we have

• mark[0],mark[1],...,mark[99]

Array Declaration

11

Page 195: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Accessing Array Elements

• An array has only one name, the elements may be accessed and used as individual variables.

• Each array element has a unique subscript, used to access the element.

• Subscripts start at 0

• The last element’s subscript is n-1 where n is the number of elements in the array.

subscripts 0 1 2 3 4

12

Page 196: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

• Array elements can be used as regular variables:

tests[0] = 79;

cout << tests[0];

cin >> tests[1];

tests[4] = tests[0] + tests[1];

• Arrays must be accessed by array name andsubscript:

cout << tests; // illegal due to

missing subscript

Accessing Array Elements

13

Page 197: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Array Subscripts

• Array subscript can be

– integer constant,

– integer variable, or

– integer expression

• Examples: Subscript is

cin >> tests[3]; int constant

cout << tests[i]; int variable

cout << tests[i+j]; int expression

14

Page 198: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Inputting and Displaying Array Contents

• cout and cin can be used to display values from and store values into an array

const int ISIZE = 5;

int tests[ISIZE]; // Define array with 5

cout << "Enter first test score ";

cin >> tests[0];// NOT cin >> tests

cout << tests[0];// NOT cout << tests

15

Page 199: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

(Program Continues)

16

Page 200: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Here are the contents of the hours array, with the

values entered by the user in the example output:

17

Page 201: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

• To access each element of an array

– Use a loop

– Let the loop control variable be the array

subscript

– A different array element will be referenced each time through the loop

for (i = 0; i < 5; i++){

cout << tests[i] << endl;

}

Inputting and Displaying Array Contents using Loops

18

Page 202: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

(Program Continues)

Exercise 1 - Display the inputs using for loop

19

Page 203: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

20

Page 204: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise 1 - Answer

21

Page 205: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

No Bounds Checking

• There are no checks in C++ that an array subscript is in range

• An invalid array subscript can cause program to overwrite other memory

• Example:const int ISIZE = 3;

int i = 4;

int num[ISIZE];

num[i] = 25;num

[0] [1] [2]

25

22

Page 206: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

23

Page 207: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

24

Page 208: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Off-By-One Errors

• An off-by-one error happens when you use array subscripts that are off by one.

• This can happen when you start the initialization at 1 rather than 0.

// This code has an off-by-one error.

const int SIZE = 100;

int numbers[SIZE];

for (int count = 1; count <= SIZE;

count++){

numbers[count] = 0;

}

25

Page 209: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Off-By-One Errors

• As a result the first element which is at subscript 0 is skipped.

• Loop attempts to use 100 as a subscript during the last iteration

• 100 is invalid subscript, the program will write data beyond the array’s boundaries.

26

Page 210: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Array Initialization

• Can be initialized during program execution with assignment statements

tests[0] = 79;

tests[1] = 82; // etc.

• Can be initialized at array definition with an initialization list

const int ISIZE = 5;

int tests[ISIZE]={79,82,91,77,84};

27

Page 211: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Program 7-6

28

Page 212: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Partial Array Initialization

• If array is initialized at definition with fewer

values than the size declarator of the array, remaining elements will be set to 0 or NULL

int tests[ISIZE] = {79, 82};

79 82 0 0 0

29

Page 213: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Implicit Array Sizing

• Can determine array size by the size of the

initialization list

short quizzes[]={12,17,15,11};

• Must use either array size declarator or

initialization list when array is defined

12 17 15 11

30

Page 214: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise 2

• Write a program that defines array of 5

elements.

– Display max of the elements.

– Display min of the elements.

31

Page 215: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise 2 - Answer

32

Output:

Page 216: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Processing Array Contents

• Array elements can be – treated as ordinary variables of the same type

as the array

– used in arithmetic operations, in relational expressions, etc.

• Example:if (principalAmt[3] >= 10000){

interest = principalAmt[3] * intRate1;

}

else{

interest = principalAmt[3] * intRate2;

}

33

Page 217: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Processing Array Contents

• Comparison with working with variables :

// principalAmt is a integer type variable

if (principalAmt >= 10000){

interest = principalAmt * intRate1;

}else{

interest = principalAmt * intRate2;

}

// principalAmt is an integer type ARRAY

if (principalAmt[3] >= 10000){

interest = principalAmt[3] * intRate1;

}else{

interest = principalAmt[3] * intRate2;

}

34

Page 218: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Using Increment and Decrement Operators with Array Elements

• When using ++ and -- operators, don’t confuse the element with the subscript

tests[i]++; // adds 1 to tests[i]

tests[i++]; // increments i, but has

// no effect on tests

Example:int tests [5]={2,4,6,8,10}; i=0;tests [i]++; //adds 1 to data of test [0] 2+1tests [i++]; // from tests[0] to tests[1]

35

Page 219: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Copying One Array to Another

• Arrays: tests and tests2

• Cannot copy with an assignment statement:

tests2 = tests; //won’t work

• Must instead use a loop to copy element-by-

element:

for (int indx=0; indx < ISIZE;

indx++){

tests2[indx] = tests[indx];

}

36

Page 220: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Comparing Arrays

• Like copying, cannot compare in a single

expression:

if (tests2 == tests)

• Use a while loop with a boolean variable:bool areEqual=true;

int indx=0;

while (areEqual && indx < ISIZE){

if(tests[indx] != tests2[indx]{

areEqual = false;

break;

}

indx++;

}

37

Page 221: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Comparing Arrays

• Cannot use the == operator with the names of two arrays to determine they are equal.

• The operator compares the beginning memory addresses of the arrays not the contents of the arrays.

• The code reports that arrays are not the same.

38

Page 222: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Comparing Arrays

• To compare the contents of two arrays, must compare the elements of the arrays.

39

Page 223: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example: Finding size of array

#include<iostream>

using namespace std;

int main() {

int a[]={1,2,3,4,5,6};

int size;

//total size of array/size of array

data type

size=sizeof (a)/sizeof(int);

cout<<size;

return 0;

}

40

Page 224: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Largest Array Element

• Use a loop to examine each element and find the largest element (i.e., one with the largest value)

int largest = tests[0];

for (int tnum = 1; tnum < ISIZE; tnum++){

if (tests[tnum] > largest){

largest = tests[tnum];

}

}

cout << "Highest score is " << largest;

• A similar algorithm exists to find the smallest

element

41

Page 225: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

a) Write a program that sums all the elements of

arrays with size 10. Once summed, compute

their average.

b) Write a program that implements linear search

algorithm

»x= 15

12 17 15 11

Exercise 3

42

Page 226: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise 3a - Answer

43

Output:

Page 227: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise 3b - Answer

44

Page 228: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Exercise 3b - Answer

45

Output:

Page 229: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

SMJE 1013 and SMJP

1043 Programming (C++) for Engineers

Shared Memory

Yusnaidi MD Yusof

Department of Electronic Systems Engineering (ESE)

Page 230: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Computer Memory

• Three main location a computer store data:

– Physical memory: through memory cell and is

accessed using an address, the memory does not

have to be consecutive

– Cache: stored either directly in the CPU (level 1

cache), or on the motherboard (level 2 cache).

It stores a copy of recently used parts of the

main memory, in a location that can be accessed

much faster.

– Registers: storage units inside the CPU with very

fast access

Page 231: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Shared Memory

• Shared memory = Multithreaded

• What being shared?

– The memory

– Code (instructions)

– Global variable (the value that its variables

reference at any given moment)

Page 232: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Shared Memory

• Variables represent storage space in the

computer's memory. Each variable presents a

convenient names like number or result in the

source code. Behind the scenes at runtime,

each variable uses an area of the computer's

memory to store its value.

• However, not every variable in a program has a

permanently assigned area of memory, instead,

modern languages are smart about giving

memory to a variable only when necessary

Page 233: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Shared Memory

• Allocate = the variable is given an area of

memory to store its value

• Deallocate = the system reclaims the memory

from the variable, so it no longer has an area

to store its value

• Lifetime = the period of time from variable’s

allocation until its deallocation

• The most common memory related error is

using a deallocated variable

Page 234: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Automatic Memory

Management

• Automatic memory management is closely

related to local variables.

• A local variable occupies memory that the

system allocates when it sees the variable's

definition during execution.

• The system also deallocates that memory

automatically at the end of the block that

contains the definition.

Page 235: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Manual Memory

Management

• Manual memory management is all about

deallocation of memory section

• As a comparison, to allocate a new object from

the free store, C uses the malloc function and

C++ uses the new operator.

Page 236: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Manual Memory

Management

• The determination of when an object ought to

be created is not problematic. The critical

issue, however, is the determination of when

an object is no longer needed and arranging for

its underlying storage to be returned to the

free store (heap) so that it may be re-used to

satisfy future memory requests.

• In manual memory allocation, this is also

specified manually by the programmer; via

functions such as free() in C, or the delete

operator in C++.

Page 237: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Thread

• Smallest unit of processing

• Scheduled by an OS

• It is contained in a process, so, multiple threads

can exist within the same process

• Shares the resources with the process: the memory,

code (instructions), and global variable (the values

that its variables reference at any given moment)

• On a single processor, each thread has its turn by

multiplexing based on time. On a multiple

processor, each thread is running at the same time

with each processor/core running a particular

thread

Page 238: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Why Multithreaded?

• Application that has more than one thread of

execution within the application itself is called

multithreaded application

– Ex 1: A server that can serve as many

concurrent connections as the server can

cope with, therefore devote a new thread to

each connection

Page 239: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Why Multithreaded?

– Ex 2: GUI application-have one thread of

execution (Main Thread) and do one

operation at a time. This thread is either

waiting for an event or processing an event.

If multithreaded, the GUI runs in its own

thread and additional processing takes place

in other threads, and the application will

have responsive GUIs even during intensive

processing.

Page 240: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Threads vs Processes

• Processes and threads are related to each other

but are fundamentally different

• Process - an instance of a running program

• A process is the unit of resource allocation &

protection

• Each process is an independent entity to which

system resources such as CPU time, memory,

etc. are allocated and each process is executed

in a separate address space.

Page 241: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Threads vs Processes

• Threads - the unit of computation that runs in

the context of a process

• A thread uses the same address space of a

process

• A thread is a particular execution path of a

process

• When one thread modifies a process resource,

the change is immediately visible to sibling

threads

Page 242: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Threads vs Processes

• Multiple threads share parts of their state:

multiple threads can read from and write to the

same memory (no process can directly access

the memory of another process)

• Processes are independent while thread is

within a process

• Processes have separate address spaces while

threads share their address spaces

• Processes communicate each other through

inter-process communication

Page 243: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Threads vs Processes

• Processes carry considerable state (e.g., ready,

running, waiting, or stopped) information,

whereas multiple threads within a process share

state as well as memory and other resources

• Threads require less overhead to manage than

processes, and intraprocess thread

communication is less expensive than

interprocess communication

Page 244: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Threads vs Processes

• A process manages certain resources, e.g.,

virtual memory, I/O handlers, and signal

handlers

• A thread manages certain resources, e.g., stack,

registers, signal masks, priorities, and thread-

specific data

• Process is protected from other processes

• Threads can interfere with each other

Page 245: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Threads vs Processes

• When a process executes a fork() call, a new

copy of the process is created with its own

variables and its own process id (PID), and this

new process is scheduled independently, and

executed almost independently of the parent

process.

• When we create a new thread within a process,

on the other hand, the new thread gets its own

stack but shares global variables, file descriptors,

signal handlers, and its current directory state

with the process which created it.

Page 246: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Race Condition

• A condition where the outcome depends on the

relative ordering of execution of operations on

two or more threads where the threads race to

perform their respective operations

• All possible outcomes are acceptable, even

though they may change with different relative

orderings

• For example, if two threads are adding items to a

queue for processing, it generally doesn't matter

which item gets added first, provided that the

invariants of the system are maintained.

Page 247: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Race Condition

• It's when the race condition leads to broken

invariants that there's a problem, therefore, race

condition means the problem of concurrent

modification to a single object such that data races

cause the undefined behaviour

• This happens when a critical section (a code

segment that accesses shared variable (or other

shared resources) and that has to be executed as

an atomic action) is not executed atomically. For

example, two threads share variable i and trying to

increment it by 1. It is highly dependent on when

they get it and when they save it

Page 248: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Mutex (Mutual Exclusion)

• The most basic mechanism for protecting shared

data, and protecting from race conditions

• Mark all the pieces of code that access the data

structure as mutually exclusive, so that if any

thread was running one of them, any other

thread that tried to access that data structure

had to wait until the first thread was finished

• Mutex ensures that a group of atomic actions

(critical section) cannot be executed by more

than one thread at a time

Page 249: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Mutex (Mutual Exclusion)

• Once one thread has locked a specific mutex, all

other threads that try to lock the same mutex

have to wait until the thread that successfully

locked the mutex unlocks it

• However, if multiple threads are waiting for the

lock, the order in which the waiting threads will

acquire the mutex is not guaranteed

Page 250: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Deadlock

• Two or more competing actions are waiting for

other to finish. No threads are changing their

states

• i.e., deadlock occurs when some threads are

blocked to acquire resources held by other

blocked threads

• A deadlock may arise due to dependence

between two or more threads that request

resources and two or more threads that hold

those resources

Page 251: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Deadlock: Example 1

Alphonse and Gaston are friends, and great

believers in courtesy. A strict rule of courtesy is

that when you bow to a friend, you must remain

bowed until your friend has a chance to return the

bow. Unfortunately, this rule does not account for

the possibility that two friends might bow to each

other at the same time

Page 252: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Deadlock: Example 2

Two threads want to acquire mutex locks A and B

to finish their task. Suppose thread 1 has already

acquired lock A and thread 2 has already acquired

B. Then, thread 1 cannot make progress because it

is waiting for lock B, and thread 2 cannot make

progress because it is waiting for lock A. So, the

two thread are in deadlock

Page 253: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Deadlock

• How to avoid deadlock?

– Don't request another resource while holding

one resource

– If ever need to acquire two locks at once

acquire locks in a fixed order

– Don't wait for another thread if there's a

chance it's waiting for you

– Try to avoid holding locks for longer than we

need to

Page 254: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Livelock

• A situation that process is not progressing

• A situation of constantly acquiring and releasing

mutexes

• As with deadlock, livelocked threads are unable

to make further progress. However, the threads

are not blocked - they are simply too busy

responding to each other to resume work

• Two threads executed at the same time and

constantly acquiring and releasing mutexes. It is

very unlikely that either will make progress

Page 255: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Livelock: Example

Each thread acquires a lock and

then attempts to acquire the

other lock. If it fails to acquire

the other lock, it releases the

lock it is holding before another

try to get both locks again. The

thread exits the loop when it

manages to acquire both locks,

and it may happen, but until

then, the application will make

no progress

Page 256: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Starvation

• Starvation – a condition when a process having

been denied necessary resources

• Without the resources the program can not finish

• Example: An object provides a synchronized

method that often takes a long time to return. If

one thread invokes this method frequently, other

threads that also need frequent synchronized

access to the same object will often be blocked

Page 257: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Semaphores

• Semaphores – a guard to a certain number of

identical resources. They are counters that can

be either incremented or decremented

• Semaphore can be signalled by any of the thread.

In contrast, mutex can be unlocked only by the

thread which owns it

• Used to provide mutual exclusion and condition

synchronization (coordinate and schedule

processing)

Page 258: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Semaphores

• Provide signaling between threads: signal or

wake up threads that are waiting on them to use

available resources

• We pass 1 to the semaphore constructor, and tell

the semaphore that it controls a single resource

• Semaphores provide a means of restricting

access to a finite set of resources or of signaling

that a resource is available

• As in the case with mutex locks, semaphores can

be shared across processes

Page 259: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Join

• A thread can execute a thread join to wait until

the other thread terminates

• thread join is for a parent (P) to join with one of

its child threads (C)

• A parent thread may join with many child

threads created by the parent. Or, a parent only

join with some of its child threads, and ignore

other child threads. In this case, those child

threads that are ignored by the parent will be

terminated when the parent terminates

Page 260: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Join

• Assuming that a parent thread P wants to join

with one of its child threads C:

– When P executes a thread join in order to join

with C, which is still running, P is suspended

until C terminates. Once C terminates, P

resumes

– When P executes a thread join and C has

already terminated, P continues as if no such

thread join has ever executed (i.e., join has

no effect)

Page 261: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Reader/Writer Locks

• reader/writer locks provide support for the

situation where there are multiple threads that

read shared data, and the shared data needs to

be written

• Only a single thread can have access to update

the data at any one time, and other threads

cannot access that data during the write

operation

• To prevent threads from reading incomplete or

corrupted data that is in the process of being

written

Page 262: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Dining Philosophers

Problem

Five philosophers sitting at a table doing one

of two things: eating or thinking. While eating,

they are not thinking, and while thinking, they

are not eating. The five philosophers sit at a

circular table with a large bowl of spaghetti in

the center. A fork is placed in between each

pair of adjacent philosophers, and as such,

each philosopher has one fork to his left and

one fork to his right. As spaghetti is difficult to

serve and eat with a single fork, it is assumed

that a philosopher must eat with two forks.

Each philosopher can only use the forks on his

immediate left and immediate right

Page 263: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Dining Philosophers

Problem

• Deadlock - philosopher P1 waits for the fork

grabbed by philosopher P2 who is waiting for the

fork of philosopher P3 and so forth, making a

circular chain

• Starvation - philosopher is unable to acquire both

forks because of a timing problem. For example

there might be a rule that the philosophers put

down a fork after waiting five minutes for the

other fork to become available and wait a further

five minutes before making their next attempt

Page 264: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Dining Philosophers

Problem

• Livelock - all five philosophers appear in the

dining room at exactly the same time and each

picks up the left fork at the same time the

philosophers will wait five minutes until they all

put their forks down and then wait a further five

minutes before they all pick them up again

Page 265: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Conditional Statements and Loops

29 October 2015

Dr. Mohd Nabil Bin Muhtazaruddin

Dr. Nelidya Binti Md. Yusoff

Razak School of Engineering & Advanced Technology

Page 266: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Conditional Statements

• Decision making structures require that theprogrammer should specify one or more conditionsto be evaluated or tested by the program.

• if the condition is determined to be true, andoptionally, other statements to be executed if thecondition is determined to be false.

• Following is the general form of a typical decisionmaking structure found of the programminglanguages.

Page 267: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Conditional Statements cont.

Page 268: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Conditional Statements cont.• MATLAB provides several type of decision making

statements.Statement Description

If...end An if ... end statement consists of a boolean expression followed by one or more statements

If…else…end

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

If…elseif…elseif….else…end

An if statement can be followed by one (or more) optional elseif... and an else statement, which is very useful to test various conditions.

Nested if You can use one if or elseif statement inside another if or elseif statement(s).

switch A switch statement allows a variable to be tested for equality against a list of values.

nested switch

You can use one switch statement inside another switch statement(s).

Page 269: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

If….end Statement

• The syntax of an if statement in MATLAB is

if <expression>

% statement(s) will execute if the boolean expression is true <statements>

end

Page 270: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 1a = 10;% check the condition using if statementif a < 20% if condition is true then print the following

fprintf('a is less than 20\n' );end

fprintf('value of a is : %d\n', a);

a is less than 20

value of a is : 10

Page 271: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

If….else….end Statement• The syntax of an if...else statement in MATLAB

is −if <expression>% statement(s) will execute if the boolean expression is true<statement(s)>else<statement(s)>% statement(s) will execute if the boolean expression is falseend

Page 272: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 2

a = 100;% check the boolean condition

if a < 20% if condition is true then print the followingfprintf('a is less than 20\n' );

else% if condition is false then print the followingfprintf('a is not less than 20\n' );

endfprintf('value of a is : %d\n', a);

a is not less than 20

value of a is : 100

Page 273: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

If…elseif…elseif…else…end

• An if statement can be followed by one (or more) optional elseif... and an else statement, which is very useful to test various conditions.

• When using if... elseif...else statements, there are few points to keep in mind:

a) An if can have zero or one else's and it must come after any elseif's.

b) An if can have zero to many elseif's and they must come before the else.

c) Once an else if succeeds, none of the remaining elseif's or else's will be tested.

Page 274: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

If…elseif…elseif…else…end cont.

• The syntax in MATLAB is as follow:-if <expression 1>% Executes when the expression 1 is true <statement(s)>

elseif <expression 2>% Executes when the boolean expression 2 is true<statement(s)>

elseif <expression 3>% Executes when the boolean expression 3 is true <statement(s)>

else % executes when the none of the above condition is true <statement(s)>end

Page 275: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 3

a = 100;

%check the boolean condition

if a == 10

% if condition is true then print the following

fprintf('Value of a is 10\n' );

elseif( a == 20 )

% if else if condition is true

fprintf('Value of a is 20\n' );

elseif a == 30

% if else if condition is true

fprintf('Value of a is 30\n' );

else

% if none of the conditions is true '

fprintf('None of the values are matching\n');

fprintf('Exact value of a is: %d\n', a );

end

None of the values are matching

Exact value of a is : 100

Page 276: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Nested if Statement

• The syntax for a nested if statement is asfollows −

if <expression 1>% Executes when the boolean expression 1 is true

if <expression 2>% Executes when the boolean expression 2 is true

endend

• You can nest elseif...else in the similar way as youhave nested if statement.

Page 277: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 4

a = 100;

b = 200;

% check the boolean condition

if( a == 100 )

% if condition is true then check the following

if( b == 200 )

% if condition is true then print the following

fprintf('Value of a is 100 and b is 200\n' );

end

end

fprintf('Exact value of a is : %d\n', a );

fprintf('Exact value of b is : %d\n', b );

Value of a is 100 and b is 200

Exact value of a is : 100

Exact value of b is : 200

Page 278: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

switch statement

• A switch block conditionally executes one set of statements from several choices. Each choice is covered by a case statement.

• An evaluated switch_expression is a scalar or string.

• When a case is true, MATLAB executes the corresponding statements and then exits the switch block.

Page 279: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

switch statement cont.

• The syntax for switch statementswitch <switch_expression>

case <case_expression>

<statements>

case <case_expression>

<statements>

...

...

otherwise

<statements>

end

Page 280: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 5

grade = 'B';

switch(grade)

case 'A'

fprintf('Excellent!\n' );

case 'B'

fprintf('Well done\n' );

case 'C'

fprintf('Well done\n' );

case 'D'

fprintf('You passed\n' );

case 'F'

fprintf('Better try again\n' );

otherwise

fprintf('Invalid grade\n' );

end

Well done

Page 281: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Nested switch statements

• It is possible to have a switch as part of thestatement sequence of an outer switch. Evenif the case constants of the inner and outerswitch contain common values, no conflictswill arise.

Page 282: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Nested switch statements cont.

• The syntax for a nested switch statement is as follows −

switch(ch1)

case 'A'

fprintf('This A is part of outer switch');

switch(ch2)

case 'A'

fprintf('This A is part of inner switch' );

case 'B'

fprintf('This B is part of inner switch' );

end

case 'B'

fprintf('This B is part of outer switch' );

end

Page 283: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 6

a = 100;

b = 200;

switch(a)

case 100

fprintf('This is part of outer switch %d\n', a );

switch(b)

case 200

fprintf('This is part of inner switch %d\n', a );

end

end

fprintf('Exact value of a is : %d\n', a );

fprintf('Exact value of b is : %d\n', b );

This is part of outer switch 100

This is part of inner switch 100

Exact value of a is : 100

Exact value of b is : 200

Page 284: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Loops• There may be a situation when you need to

execute a block of code several number oftimes (sequentially).

• The first statement in a function is executedfirst, followed by the second, and so on.

• A loop statement allows us to execute astatement or group of statements multipletimes and following is the general form of aloop statement in most of the programminglanguages −

Page 285: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Loop Cont.

• MATLAB provides following types of loops to handle looping requirements.

Loop Type Description

while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

nested loop You can use one or more loops inside any another loop.

Page 286: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

While loop

• The syntax of a while loop in MATLAB is -

while <expression>

<statements>

end

• The while loop repeatedly executes program statement(s) as long as the expression remains true.

Page 287: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 7

a = 10;

% while loop execution

while( a < 20 )

fprintf('value of a: %d\n', a);

a = a + 1;

end

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

Page 288: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

For loop

• The syntax of a for loop in MATLAB is −

for index = values

<program statements>

...

end

Page 289: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 8

for a = 10:20

fprintf('value of a: %d\n', a);

end

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

value of a: 20

Page 290: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 9

for a = [24,18,17,23,28]

disp(a)

end24

18

17

23

28

Page 291: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Nested loops

• The syntax for a nested for loop statement in MATLAB is as follows −

for m = 1:j

for n = 1:k

<statements>;

end

end

Page 292: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Nested loops cont.

• The syntax for a nested while loop statement in MATLAB is as follows −

while <expression1>

while <expression2>

<statements>

end

end

Page 293: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 10

• Let us use a nested for loop to display all theprime numbers from 1 to 100. Create a scriptfile and type the following code −

for i=2:100

for j=2:100

if(~mod(i,j))

break; % if factor found, not prime

end

end

if(j > (i/j))

fprintf('%d is prime\n', i);

end

end

2 is prime

3 is prime

5 is prime

7 is prime

11 is prime

13 is prime

17 is prime

19 is prime

23 is prime

29 is prime

31 is prime

37 is prime

41 is prime

43 is prime

47 is prime

53 is prime

59 is prime

61 is prime

67 is prime

71 is prime

73 is prime

79 is prime

83 is prime

89 is prime

97 is prime

Page 294: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Loop Control Statement

• Loop control statements change executionfrom its normal sequence.

• When execution leaves a scope, all automaticobjects that were created in that scope aredestroyed.

Page 295: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Loop Control Statement cont.

• MATLAB supports the following controlstatements.

Control Statement Description

Break Statement Terminates the loop statementand transfers execution to thestatement immediatelyfollowing the loop.

Continue Statement Causes the loop to skip theremainder of its body andimmediately retest itscondition prior to reiterating.

Page 296: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Break statement

• The break statement terminates executionof for or while loop. Statements in the loopthat appear after the break statement are notexecuted.

• In nested loops, break exits only from the loopin which it occurs. Control passes to thestatement following the end of that loop.

Page 297: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 11

a = 10;

% while loop execution

while (a < 20 )

fprintf('value of a: %d\n', a);

a = a+1;

if( a > 15)

% terminate the loop using break statement

break;

end

end

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

Page 298: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Continue Statement

• The continue statement is used for passingcontrol to next iteration of for or while loop.

• The continue statement in MATLAB workssomewhat like the break statement. Instead offorcing termination, however, 'continue' forcesthe next iteration of the loop to take place,skipping any code in between.

Page 299: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 12

a = 10;

%while loop execution

while a < 20

if a == 15

% skip the iteration

a = a + 1;

continue;

end

fprintf('value of a: %d\n', a);

a = a + 1;

end

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 16

value of a: 17

value of a: 18

value of a: 19

Page 300: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Relational and Logical Operators

29 October 2015

Dr. Mohd Nabil Bin Muhtazaruddin

Dr. Nelidya Binti Md. Yusoff

Razak School of Engineering & Advanced Technology

Page 301: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Relational Operators

• The relational operators are <, >, <=, >=, ==and ~=.

• Relational operators perform element-by-element comparisons between two arrays.

• They return a logical array of the same size,with elements set to logical 1 (True), andelements set to logical 0 (False) where it isnot.

Page 302: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Relational Operators cont.

• The operators <, >, <= and >= use only the realpart of their operands for the comparison,whereas, the operators == and ~= test realand imaginary parts.

• To test if the two strings are equivalent, usestrcmp , which allows vectors of dissimilar tobe compared.

Page 303: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Relational Operators cont. • Be careful about round off errors during

numeric comparisons (== and ~= operators)

a=0;b=sin(pi);a==b

ans=0 (since sin(pi) calculation yields 1.2246e-16)

• You may use “abs(a-b) < small number”instead of “a==b”

abs(a-b)<1.0e-14

Ans=1

Page 304: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Table of Relational Operators

Operator

Description

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

== Equal to

~= Not Equal to

Page 305: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Syntax for Operational

Syntax in MATLAB

A>B

A<B

A>=B

A<=B

A==B

A~=B

Page 306: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 1• If one of the operands is a scalar and the other

a matrix, the scalar expands to the size of thematrix. For example, the two pairs ofstatements.

X=5;

X>=[1 2 3;4 5 6;7 8 10]

X=5*ones(3,3);

X>=[1 2 3;4 5 6;7 8 10]

Both Produce the same result:

ans=

1 1 1

1 1 0

0 0 0

Page 307: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 2

a = 100;

b = 200;

if (a>=b)

max=a

else

max=b

end

ans=

max=200

Page 308: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 3

• Compare two different strings.

S1=‘Yes’;

S2=‘No’;

tf=strcmp(S1,S2)

tf=

0

Strcmp return 0 because the

strings are not equal.

Page 309: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 4

• Compare two different strings.

S1=‘Yes’;

S2=‘Yes’;

tf=strcmp(S1,S2)

tf=

1

Strcmp return 1 because the

strings are equal.

Page 310: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 5

• Compare String and cell array of strings.

S1=‘Upon’;

S2={‘Once’, ‘Upon’; ‘a’, ‘time’};

tf=strcmp(S1,S2)

tf=

0 1

0 0

Page 311: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 6

• Compare two cell array of strings.

S1={‘Once’, ‘is’; ‘test’, ‘time’}

S2={‘Once’, ‘Upon’; ‘a’, ‘time’}

tf=strcmp(S1,S2)

tf=

1 0

0 1

Page 312: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Alternative syntax• Apart from above-mentioned relational

operators, MATLAB provides alternativecommands/Functions used for the samepurpose-

Function Description

eq(A,B) Tests whether A is equal to B

ge(A,B) Tests whether A is greater than or equal to B

gt(A,B) Tests whether A is greater than B

le(A,B) Tests whether A is less than or equal to B

lt(A,B) Tests whether A is less than B

ne(A,B) Tests whether A is not equal to B

isequal Tests arrays for equality

isequaln Tests arrays for equality, treating NaN values as equal

Page 313: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 7

% Comparing two values

a = 100;

b = 200;

if (ge(a,b))

max=a

else

max=b

end

ans=

max=200

Page 314: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Logical Operators

• More complex conditions can be represented

• By combining relational operations usinglogical operators

a) “Temperature ≠ 25” AND “Humidity < 60%”

b) “Exam grade < 45” OR “attendance ≤ 75”

• They take one or two logical operands

• They yield a logical result (true or false)

Page 315: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Logical Operators cont.• MATLAB offers two types of logical operators

and functions:

a) Element wise- These operators operate oncorresponding elements of logical arrays.

b) Short-circuit-These operators operate onscalar and, logical expressions.

• Element-wise= operate elements by elementson logical array. (& (AND), |(OR), xor(XOR) and~(NOT)).

• Short-circuit= allow short-circuiting on logicaloperations. (&& (AND) and ||(OR)) .

Page 316: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

AND, &

• Performs a logical AND of all input arrays A, B etc and returns an array containing elements set to either logical 1 (true) or logical 0 (false).

• An element of the output array is set to 1 if all input arrays contain nonzero element at that same array location.

• Otherwise, that element is set to 0.

Page 317: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 8

If matrix A= and matrix B=

A&B=

ans=

0 0

1 1

1.06.0

7.04.0

11

00

Page 318: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Or, |

• Perform a logical OR of all input arrays A,B andetc., and return an array containing elementsset to either logical 1 (true) or logical 0 (false).

• An element of the output array is set to anyinput arrays contain a nonzero element at thatsame array location. Otherwise, that elementis set to 0.

Page 319: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 9

If matrix A= and matrix B=

A&B=

ans=

1 1

0 1

1.00

7.04.0

10

00

Page 320: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

xor

• Performs an exclusive OR operation on the corresponding elements of array A and B.

• The resulting element c(I,j,…) is logical true if A(i,j,….) or B(i,j,…) but not both, is nonzero.

Page 321: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 10

If matrix A= and matrix B=

C=xor (A,B)

ans=

1 1

0 0

1.00

7.04.0

10

00

Page 322: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

NOT, ~

• Performs a logical NOT of input array A, and return an array containing elements set to either logical 1 or 0.

• An element of the output array is set to 1 if the input array contains a zero value element at that same array location.

• Otherwise, that element is set to 0.

Page 323: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Example 11

If matrix A=

~A

ans=

0 0

1 0

1.00

7.04.0

Page 324: MRSL 1163 SCIENTIFIC COMPUTING FOR SYSTEM ENGINEER

Truth Table for Logical Operations

Input A and B andA&B

orA|B

xorxor(A,B)

not~A

0 0 0 0 0 1

0 1 0 1 1 1

1 0 0 1 1 0

1 1 1 1 0 0