CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ......

72
CHAPTER – 4 CONTROL STRUCTURES 1

Transcript of CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ......

Page 1: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

CHAPTER – 4

CONTROL STRUCTURES

1

Page 2: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Control Structures A program is usually not limited to a linear sequence of

instructions. During its process it may deviate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

With the introduction of control structures we are going

to have to introduce a new concept: the compound statement or block. A block is a group of statements which are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces: { }: {statement1; statement2; statement3;}

Most of the control structures that we will see in this

section require a generic statement as part of its syntax. A statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block), like the one just described. In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ({}).But in the case that we want the statement to be a compound statement it must be enclosed between braces ({}), forming a block. Only three control structures needed Three control structures

• Sequence structure – Programs executed sequentially by

default • Selection structures

– if, if…else, switch • Repetition structures

– while, do…while, for

2

Page 3: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Selection Structures (or) Conditional Structures (or) Branching Structures 1. if structure If keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if(condition) statement; where condition is the expression that is being evaluated.

If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure.

Statement

Condition YES

NO

Continue

For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100: if(x == 100) cout << "x is 100";

3

Page 4: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }: if(x == 100) { cout<<"x is "; cout<<x; } 2. if …else statement

We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is: if(condition) statement1; else statement2;

Statement1

Condition YES NO

Continue

Statement2

4

Page 5: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

For example:

100";

<"x is not 100";

rints on the screen x is 100 if indeed x has a value of 100,

ay if …else statements (or) if…else…if ladder

if(x==100) cout<<"x iselse cout< pbut if it has not -and only if not- it prints out x is not 100. 3. Multi-w

we m

(condition-1)

(condition-2)

(condition-3)

(condition-n)

efault statement; statement-x;

When a series of many conditions have to be checkeday use the ladder else if statement which takes the

following general form ifstatement-1;

else ifstatement-2;

else ifstatement-3;

else ifstatement-n;

else d

This construct is known as if else construct or ladder. The conditions are evaluated from the top of the ladder to downwards. As soon on the true condition is found, the statement associated with it is executed and the control is transferred to the statement–x (skipping the rest of the ladder. When all the condition becomes false, the final else containing the default statement will be executed.

5

Page 6: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Condition-1 YES NO

Statement-1

6

Condition-2Statement-2

YES

Default Statement

NO

Condition-3 Statement-3 YES

NO

Statement-n YES Condition-n

NO

Statement-x

Page 7: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

The if + else structures can be concatenated with the intention of verifying a range of values.

The following example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero):

if(x > 0) cout<<"x is positive"; else

if(x<0) cout<<"x is negative";

else cout<<"x is 0";

Example program using if else ladder to grade the student according to the following rules.

Marks Grade

>=90 A

>=80 B

>=70 C

>=60 D

<60 F

7

Page 8: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Example: Algorithm steps If stu

If student’s grade is greater than or equal to 80

int “B”

If student’s grade is greater than or equal to 70 int “C” If student’s grade is greater than or equal to 60 else

“F”

++ Program Steps

dent’s grade is greater than or equal to 90 Print “A” else

Pr else

Pr else

Print “D” Print C if(s rade>= cout<<"A"; else if(studentGrade>= 80) cout<<"B"; el if(studentGrade>=70) cout<<"C"; e if(studentGrade >= 60) cout<<"D"; else cout<<"F";

tudentG 90)

se

lse

8

Page 9: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

4. Nested if Statements tatements can be nested, i.e. used inside

else corresponds to its closest preceding if ion)

if(e {

}

{

lse statement;

if and if-else sanother if or else statement

Everyif(express{ xpression) statement; else statement; } } e Example: to find the givgreater than oif(first { cout<<"These} else { if(firs { cout<<"The firs } else

en two numbers are equal, or ther

== second)

two numbers are equal.";

t > second)

t number is bigger.";

{ cout<<"The second is bigger."; }

}

9

Page 10: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

5. The selective structure: switch…case

made from more than two possibilities by using if-else ladder statements. However a less unwieldy method in some cases

h statement.

: h(selector)

label1 : up of statement1 ;

break;

group of statement2 ; break;

group of statementn ;

optional break;

The selector may be an integer or character variable or expression that evaluates to an integer or a character.

s ted and the value compared with each ase labels. The case labels must have the same type

different. Switch lu s selector and checks if it is equivalent to label1, if it t tes group of statements 1 until it finds the break e ent. When it finds this break statement the program

ve structure If the value h selector cannot be matched with any of the case

bels then the statement associated with default is

In the last Lesson it was shown how a choice could be

is to use a switc The general form of a switch…case statement isswitc{ case

gro

case label2 :

. . . case labeln :

break; default :

statementd; //

}

anThe elector is evaluaof the cas the selector and they must all beeva ateis, i execustat mjumps to the end of the switch selectiof t e la

10

Page 11: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

executed. The default is optional but it should only be left out if it i

losed in curly brackets).

s certain that the selector will always take the value of one of the case labels. Note that the statement associated with a case label can be a single statement or a sequence of statements (without being enc

11

Page 12: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

For example The following switch statement will set the variable grade to the character A, B or C depending on whether the variable i has the value 1, 2, or 3. If i has none of the values 1, 2, or 3 then a warning message is output. switch(i) { case 1:

grade = 'A'; break;

case 2: grade = 'B'; break;

case 3: grade = 'c'; break;

default: cout<<i<<"not in range"; break;

} The following statement writes out the day of the week

depending on the value of an integer variable day. It assumes that day 1 is Sunday. switch(day) { case 1:

cout<<"Sunday"; break;

case 2: cout<<"Monday"; break;

case 3: cout<<"Tuesday"; break;

12

Page 13: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

case 4: cout<<"Wednesday"; break;

case 5: cout<<"Thursday"; break;

cout<<"Friday"; k;

caseSaturday";

k; defau

Not an allowable day number"; ak;

}

has already been ensured that day takes a value between 1 and 7 then the default case may be missed out.

It is allowable to associate several case labels with one statement. For example, if we did not include a break

end of the switch selective would continue executing the rest of statements

til it reaches either a break instruction or the end of the lective block. This makes unnecessary to include

braces { } surrounding the statements for each of the cases, and it can also be useful to execute the same block of

ns for different possible values for the expression being

ple

case 6:

brea 7: cout<<"brealt: cout<<"bre

If it

statement after the first group for case one, the program will not automatically jump to the block and it unswitch se

instructio evaluated.

For exam if the above example is amended to write out whether day is a weekday or is part of the weekend:

13

Page 14: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

switch(day) { case

ekend day";

casecase

caseThis is a weekday";

k; defau

Not a legal day"; break;

Switc

oth of the following code fragments have the same behavior:

switc

lue of x nknown";

{ cout<<"value of x unknown";

1: case 7:

cout<<"This is a webreak;

case 2: 3: 4:

case 5: 6: cout<<"brealt: cout<<"

} h statement something similar to what we did at the

beginning of this section with if else ladder. B

h example switch (x) { case 1: cout<<"x is 1"; break; case 2: cout<<"x is 2"; break; default: cout<<"va

if-else equivalent if(x == 1) { cout<<"x is 1"; } else if(x == 2) { cout<<"x is 2"; } else

u

}

}

14

Page 15: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

For example the weekday/weekend example above could written:

&&day<=7)

if(daycout<<"This is a weekend day";

his is a weekday";

ot a legal day"; However the first example becomes very tedious- there are

rnatives! Consider the following:

day==1)

sday";

y";

";

ice that switch can on used to compare an ants. Therefore we cannot put

labels (for example c ranges (case (1..3):) becau they are not valid C++

onstants. If you need to check ranges or values that are not ncatenation of if and else if statements.

beif(day>=1{

==1||day==7)

else cout<<"T} else cout<<”N

eight alte

if(cout<<"Sunday"; else if(day==2) cout<<"Monday"; else if(day==3) cout<<"Tue. . else if(day==7) cout<<"Saturdaelse cout<<"Not a legal day

Not ly be expression against constvariables s ase n: where n is a variable) or secconstants, use a co

15

Page 16: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Common Programming Error • Forgetting a break statement when one is needed in a

is a logic error. • Omitting the space between the word case and the

being tested in a switch statement can mple, writing case3: instead

of writing case 3: simply creates an unused label. n including variables(e.g.,a + b)

in a switch statement’s case label is a syntax error.

ctice

switch statement

integral value cause a logic error. For exa

• Specifying an expressio

Good Programming Pra

In a switch statement that lists the default clause last,

and for symmetry ith other cases.

structures (or) Iteration Structures (or)

the default clause does not require a break statement. Someprogrammers include this break for clarityw RepetitionLooping Structures

as purpose to repeat a statement a certain r while a condition is fulfilled.

types of loops in C++

2. do-while loops 3. for loops

p

Loops havenumber of times o

There are 31. while loops

1. The while loo

(condition)

tatement; }

Its format is: while{ s

• This while loop executes as long as the given logical expression between parentheses is true. When condition is false, execution continues with the statement following the loop block.

16

Page 17: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

• The condition is tested at the beginning of the loop, so if

peat statement while

it is initially false, the loop will not be executed at all, and its functionality is simply to rethe condition set in expression is true. Two or more number of statements to be repeated then encloses braces { }. Otherwise no need to enclose brace for single statement repetition.

17

Page 18: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

FousingExam

r example, we are going to make a program to countdown a while-loop: ple Program

tom countdown using while // cus#inusingint m{ int n; cout<<"Enter the starting number"; cin>>n; while(n>0) { cout<<n<<","; --n; } cout<<"FIRE!\n"; return(0); } Output

clude<iostream> namespace std; ain()

Enter the starting number 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true.

The whole process of the previous program can be interpreted according to the following script (beginning in main): 1. User assigns a value to n 2. The while condition is checked (n>0). At this point there are two possibilities: * condition is true: statement is executed (to step 3)

18

Page 19: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

* condition is false: ignore statement and continue after it (to step 5) 3. Execute statement:

the screen and decreases n by 1) lock. Return automatically to step 2

Continue the program right after the block: print FIRE! and ogram.

e must always consider s to end at some point, therefore we must provide

lock some method to force the condition to come false at some point, otherwise the loop will continue

r. In this case we have included --n; that eases the value of the variable that is being evaluated in

e condition (n) by one - this will eventually make the become false after a certain number of

ons: to be more specific, when n becomes 0, that where our while-loop and our countdown end.

course this is such a simple action for our computer performed instantly without any

mbers. Note

cout<<n<<","; --n; (prints the value of n on4. End of b5.end pr

When creating a while-loop, wthat it hawithin the bbelooping forevedecrthcondition (n>0) toloop iteratiis

Of that the whole countdown ispractical delay between nu

: placing semicolon after the while statement, i.e while(); will produce a logical error. 2. The do-while loop Its format is: do {

s, t least one execution of the body

statement; } while(condition);

• Its functionality is exactly the same as the while loopbut guarantees a

19

Page 20: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

• Two or more number of statements to be repeated thenenc

loses braces { }. Otherwise no need to enclose

atement repetition. brace for single st

For example, the following example program echoes any number you enter until you enter 0. Example Program // number echoer #include<iostream> using namespace std; int main() { unsigned long n; do { cout<<"Enter number (0 to end):";

ut<<"You entered:"<<n<<"\n";

whretur}

cin>>n; co}

ile(n!=0); n(0);

20

Page 21: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Output number (0 to end): 12345 ntered: 12345

EnterYou eEnter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0

The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever. Note: Forget to place semicolon after the while statement, i.e while() will produce a syntax error. 3. The for loop Its format is: for(initialization;condition;increment)

d its main function is to repeat statement while condition the while loop.

in addition, for loop provides specific locations to contain initialization statement and an increase statement. So this

rm a repetitive action with r which is initialized and increased on each iteration.

orks in the following way: n is executed. Generally it is an initial value

a counter variable. This is executed ly once.

{ statement; } anremains true, like But anloop is specially designed to perfoa counte It w1. Initializatiosetting for on

21

Page 22: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

2. Condition is checked. If it is true the loop continues, ement is skipped

al, it can be either a single nclosed in braces { }.

ecified in the increase field is e loop gets back to step 2.

otherwise the loop ends and stat(not executed). 3. Statement is executed. As usustatement or a block e4. Finally, whatever is spexecuted and th

Comparison of for and while loops

22

Page 23: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Here is an example of countdown using for loop: Example Program // countdown using a for loop #include<iostream> using namespace std; int main() { for(int n=10;n>0;n--) { cout<<n<<","; }

return(0); } Output

cout<<"FIRE!\n";

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. For example we could write:

23

Page 24: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

for(;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe because the variable was already initialized before).

Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop: for(n=0,i=100;n!=i;n++,i-- ) { // whatever here...

e for 50 times if either n or i are modified } This loop will executwithin the loop:

n starts with a value of 0, and i with 100, the condition is n!=i

at n is not equal to i). Because n is increased by one and i one, the loop's condition will become false

ter the 50th loop, when both n and i will be equal to 50.

(thdecreased by af

24

Page 25: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Nested Loops You can nest loops of any kind inside another to any depth. Example Program //Printing a Triangle #inclu

cout<<"*";

ut<<"\n";

} Output

de<iostream> using namespace std; int main() { for(int i=1;i<=5;i++) {

for(int j=1;j<=i;j++) {

} co} return(0);

* ** *** **** ***** Jumping statements . The break statement1

Using break we can leave a loop even if the condition r its end is not fulfilled. It can be used to end an infinite op, or to force it to end before its natural end. or example, we are going to stop the count down before its atural end (maybe because of an engine check failure?): xample Program

foloFnE break loop example include<iostream> sing namespace std;

//#u

25

Page 26: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

int main() { int n; for(n=10; n>0; n--) { cout<<n<< ", ";

if(n==3) {

wn aborted!"; break;

} retur}

cout<<"countdo

}

n(0);

Output 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

tinue statement2. The con The continue statement causes the program to skip the

he loop in the current iteration as if the end of the atement block had been reached, causing it to jump to the rt of the following iteration. example, we are going to skip the number 5 in our tdown: ple Program

rest of tststaFor counExam

using

//continue loop example#include<iostream>

namespace std; int main() { for(int n=10; n>0; n--) { if(n==5) continue; cout<<n<< ", "; } cout<<"FIRE!\n";

26

Page 27: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

return(0); } Output

, 1, FIRE!

tement

10, 9, 8, 7, 6, 4, 3, 2 3. The goto sta

ws to make an absolute jump to another point in the program. You should use this feature with caution since conditional jump ignoring any type of nesting limitations.

The destination point is identified by a label, which is as an argument for the goto statement. A label is

ade of a valid identifier followed by a colon (:) erally speaking, this instruction has no concrete

mming aside from ing fans may find for it.

For e

Goto allo

its execution causes an un

then used m

Genuse in structured or object oriented prograthose that low-level programm

xample, here is our countdown loop using goto: Example Program //goto loop example #include<iostream> using namespace std; int main() { int n=10; loop: cout<<n<<","; n--; if(n>0)

ut<<"FIRE!\n";

utput

goto loop; coreturn(0); } O

3, 2, 1, FIRE! 10, 9, 8, 7, 6, 5, 4,

27

Page 28: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Exercises 1. Write an if statement that prints YES if a variable age is

ater than 21. - 2 Marks t that displays YES if a

variable age is greater than 21, and displays NO - 2 Marks

3.

- 2 Marks 5. t least how many times the loop body is executed in a

OWN

r even - 2 Marks

to find the factorial of a given number - 2 Marks that displays the following set of

- 2 Marks 60 70 80 90 100

11. Write a program to find sum, difference, multiply and on of given two numbers using switch case

elective structure - 3 Marks icity board charges the following rates to

domestic users to discourage large consumption of ergy: For the first 100 units – 10 Paisa per unit

For next 200 units – 20 Paisa per unit nd 300 units – 30 Paisa per unit

total cost is more than 10 OMR then an additional surcharge of 15% is added.

te a program to print the consumed unit and total it. - 3 Marks

gre2. Write an if…else statemen

otherwise Write a for loop that displays the number from 100 to 110. Thank You - 2 Marks

4. Write a while loop that displays the number from 500 to 520. Ado…while loop? - 1 Mark

6. Write a switch statement that prints YES if a variable ch is ‘y’, prints NO if ch is ‘n’, and prints UNKNotherwise - 2 Marks

7. Write a program to find the biggest among three given numbers - 2 Marks

8. Write a program to find the given number is odd o9. Write a program

by using for loop10. Write a for loop

numbers 0 10 20 30 40 50

divisis

12. An electr

en BeyoIf the

Wriamount for the consumed un

28

Page 29: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

13. Write a Program to find the GCD of two numbers by

14 g

using while loop structure - 2 Marks . Write a program to calculate and Print the Followintable by using for loop structure - 3 Marks1*2=2 2*2=4 3*2=6 4*2=8 5*2=10 6*2=12 7*2=14 8*2=16 9*2=18 10*2=20

29

Page 30: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

CHAPTER – 6

ARRAYS

1

Page 31: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

An array is a group of elements of the same type that are placed in contiguous memory locations. In general, only the array itself has a symbolic name, not its elements. Each element is identified by an index which denotes the position of the element in the array. Arrays are suitable for representing composite data which consist of many similar, individual items. Examples: a list of names, a table of world cities and their current temperatures, or the monthly transactions for a bank account. The number of elements in an array is called its dimension. The dimension of an array is fixed and predetermined. It cannot be changed during program execution. In this array we will discuss

1. One dimensional Array 2. Two dimensional Array

One Dimensional Array Array DeclarationC++ Arrays can be declared for all c++ data types (int, float, double, char etc…). All the elements are stored in consecutive memory locations. The elements can be accessed by using the position (or) index. Declaring C++ Arrays of int type: The c++ arrays are declared with the data type name and the number of elements inside the square brackets. int varname[50]; // C++ Array of type int with maximum size=50. The above declaration means, the varname is an array of integer type. The values inside this varname array can be accessed by referring to the position of their elements like varname[0], varname[1] etc.,

2

Page 32: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

All the C++ arrays are based on Zero index values. That means the position reference starts at 0(Zero) and counts till the n-1th position. So in the above array, 50 elements can be stored starting from 0 to 49. The maximum number of elements that can be stored or the maximum size of the c++ array is 50. Accessing Elements Like normal variables, we can use these elements in program statements such as assignment statements, input and output statements. Example Program The values can be stored and accessed as given in the following code fragment. #include<iostream> using namespace std; int main() { int a[5]; a[0]=10; a[1]=20; cout<<"Enter the value for third element"<<endl; cin>>a[2]; a[0]=a[0]*5; cout<<a[0]<<"\t"<<a[1]<<"\t"<<a[2]<<endl; return(0); } Output Enter the value for third element 30 50 20 30 Note: Care should be taken while using or referring to the position of the element. The position reference should not exceed the maximum size specified in the declaration. If it exceeds, the program will not generate any compiler errors. But it will raise run time errors and exceptions.

3

Page 33: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Declaring C++ arrays of type float: The declaration and use of c++ arrays in float type are the same as int. The declaration is written as follows. float varname[100]; //A c++ array of float type The above declaration means, the c++ float array contains 100 elements starting from position 0 till 99. The elements can be accessed as varname[0], varname[1], varname[2] … varname[99]. Accessing Elements Like normal variables, we can use these elements in program statements such as assignment statements, input and output statements. The values can be stored and accessed as given in the following code fragment. varname[0]=10.05; varname[1]=11.04; varname[2]=13.34; cout<<"Enter the value for fourth element"<<endl; cin>>varname[3]; cout<<varname[0]<<endl; Declaring C++ arrays of type char: This is one of the most widely used and problematic type of c++ array. When an array of char is declared, this char array can be used as a string with the maximum size as specified in the array declaration. char varname[50]; //Memory reserved for 50 characters. The above declaration means, the c++ char array contains 50 elements starting from position 0 till 49. The elements can be accessed as varname[0], varname[1], varname[2] … varname[49].

4

Page 34: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Accessing Elements Like normal variables, we can use these elements in program statements such as assignment statements, input and output statements. The values can be stored and accessed as given in the following code fragment. varname[0]='a'; cout<<"Enter the character for second element"<<endl; cin>>varname[1]; cout<<varname[0]<<endl; cout<<varname[1]<<endl; C++ Array Advantages:

Easier to declare and use. Can be used with all data types.

C++ Array Disadvantages: Fixed size data. If the number of elements stored are

less than the maximum size, then the rest of the memory space goes waste.

If the number of elements to be stored are more than the maximum size, the array cannot accommodate those new values.

Initialization of Integer, Float and Char types of Array If a programmer wants to initialize an array elements it can be done by specifying the values enclosed within braces { }. For example, using the array age, if a programmer wants to initialize integer values 55, 35, 30, 40 respectively to each of the array positions it can be written. int age[4]={55,35,30,40}; So the above arrays would take values as below

5

Page 35: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

age [0] [1] [2] [3]

values 55 35 30 40

If a programmer wants to initialize float values 34.5, 23.4, and 45.6 in the array temperature then the initialization can be written as float temperature[3]={34.5,23.4,45.6}; So the above arrays would take values as below

temperature [0] [1] [2]

values 34.5 23.4 45.6

If a programmer wants to initialize char values ‘e’, ‘f’, ‘g’, ‘y’ in the array name then the initialization can be written as char name[5]={‘e’,’f’,’g’,’y’,’\0’}; When initializing the array of characters, a special character (the null character) is used to signal the end of the string. The null character can be written as '\0' (backslash, zero). So the above arrays would take values as below

Note: One interesting fact is that the size of the array element can also be left blank, in which case the array takes the size of the array as the number of elements initialized within { }.

name [0] [1] [2] [3] [4]

values ‘e’ ‘f’ ‘g’ ‘y’ ‘\0’

For example if the array takes the form as int age[ ]={55,35,30,40,50};

6

Page 36: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Then the size of the array age is 5 which is the number of elements initialized within { }. float temperature[ ]={34.5,23.4,45.6,28.9}; Then the size of the array temperature is 4 which is the number of elements initialized within{ }. char name[ ]={‘s’,’a’,’y’,’\0’}; Then the size of the array name is 4 which is the number of elements initialized within{ }. In C++ array of characters is called as string. A string or array of characters can be initialized without specifying the single quote inside{ }. But like a string literals it should be given within double quote. Example: char sen[ ]="c++ char array string example"; In this second case, when using double quotes (") for initialization, the null character ‘\0’ is appended automatically. Note: When declaring array without initialization, the size should be mentioned in [ ]. Example: int age[ ]; is not the proper declaration. The compiler will generate the error as size should be mentioned. Like the above examples, the c++ arrays can be declared with or without initializing values.

7

Page 37: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Accessing Array Elements through For loop In an array, the index values are starts from 0 and it is increasing one by one up to the maximum size of the array. So to get the input values in an array or to display the content of the array, we can use for loop. Without for loop, manipulating the array is difficult. Almost always need to use a for loop to step through the array elements. Example Program /*Program to read the input for an array through for loop and to display the content of the array through for loop*/ #include<iostream> using namespace std; int main() { int a[10],i; //To read the input for array for(i=0;i<10;i++) { cout<<"Enter the Value for a["<<i<<"]"<<endl; cin>>a[i]; } //To display the content of the array for(i=0;i<10;i++) { cout<<"Value of a["<<i<<"] is"<<a[i]<<endl; } return(0); } Output Enter the Value for a[0] 11 Enter the Value for a[1] 345 Enter the Value for a[2] 15

8

Page 38: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Enter the Value for a[3] 3 Enter the Value for a[4] 56 Enter the Value for a[5] 27 Enter the Value for a[6] 90 Enter the Value for a[7] 41 Enter the Value for a[8] 12 Enter the Value for a[9] 77 Value of a[0] is11 Value of a[1] is345 Value of a[2] is15 Value of a[3] is3 Value of a[4] is56 Value of a[5] is27 Value of a[6] is90 Value of a[7] is41 Value of a[8] is12 Value of a[9] is77 Note Without using for loop, array of characters (or) string can be manipulated. This is allowed in c++. But, int and float arrays are always manipulated through for loop. Example Program #include <iostream> using namespace std; int main () { char question[ ] = "Please, enter your first name:"; char greeting[ ] = "Hello ";

9

Page 39: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

char fname[80]; cout<<question; cin>>fname; cout<<greeting<<"Your First name is..."<<fname; return(0); } Output Please, enter your first name:Salim Hello Your First name is...Salim In the above example to read the values in fname char array, for loop is not used. Simply the array name, fname is given with cin. Also, to display the content of the fname char array, for loop is not used. Simply the array name, fname is given with cout. Note: When giving input to the char array without for loop, only the characters other than blank space are allowed. If the blank space is given as input from keybord, which means it’s the end of array. So after blank space whatever given as the input, it is not stored in the char array. So in this case, only a single word is allowed as the input to the char array. Passing arrays to Functions At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address. In practice this has almost the same effect and it is a much faster and more efficient operation. In order to pass arrays as parameters to a function, the function declaration is specified as in the following example. void display(int[ ]);

10

Page 40: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

That is the above function display takes the int type of array as a parameter. In function declaration the array data type is followed by empty [ ]. This is enough to specify in the declaration. No need to specify the array name. Example Program #include<iostream> using namespace std; void print(int[ ],int); int main() { int a[20],n,i; cout<<"Enter the number of elements in the array"<<endl; cin>>n;

for(i=0;i<n;i++) { cout<<"Enter Value for a["<<i<<"]"<<endl; cin>>a[i]; }

print(a,n);

for(i=0;i<n;i++) { cout<<"Value of a["<<i<<"] is"<<a[i]<<endl; }

return(0); } void print(int b[ ],int m) { int i;

for(i=0;i<m;i++) { cout<<"Value of b["<<i<<"] is"<<b[i]+1<<endl; }

}

11

Page 41: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Output Enter the number of elements in the array 3 Enter Value for a[0] 11 Enter Value for a[1] 22 Enter Value for a[2] 33 Value of b[0] is12 Value of b[1] is23 Value of b[2] is34 Value of a[0] is11 Value of a[1] is22 Value of a[2] is33 The print() function is declared before the main(), with the first parameter is an int type of array, and the second parameter is an int type of variable. A int type of array a[20] is declared inside the main() and the input for the array is read out through the for loop. Then this array a is passed as the first parameter to print(). In print() call only the array name a is specified. No need to specify the size. The second parameter is used to get the number of elements in the array, and it is passed to the print() call. In c++ the set of values are passed as a parameter through array concept When receiving the array values in the print() body, another int type of array b[ ] is specified with empty [ ]. The first value a[0] is copied to b[0] and so on up to the last element of the array. So whatever changes in the array b[ ], inside the body of print() will not affect the values of array a[ ] in the main(). So after the print() call, the values in array a[ ] is not changed in main().

12

Page 42: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Exercises 1. Write a C++ program to read 10 integer numbers in

an array and find the sum of these numbers. 2. Write a C++ program to read and print your first

name, middle name and Family name. 3. Write a C++ program to read 10 floating point

numbers in an array and pass this array to a function named sum(), which calculates the sum of these numbers and print the sum.

13

Page 43: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Chapter 5 Two-Dimensional Arrays

COMP151 Lecture

5 Two-Dimensional Arrays

Two-Dimensional Array

A two-dimensional array is used to represent items in a table with rows and

columns, provided that each item in the table is of the same data type.

In the following figure , we have an array with 9 rows which are accessed by an

integer ranging from 0 through 8 and 7 columns which are accessed by an integer

ranging from 0 through 6.

Row 7 , Column 5

Declaring two-dimensional Array Types

Here is a syntax template describing the simplest form of one-dimensional array

declaration:

DataType ArrayName [ ConstIntExpression1] [ ConstIntExpression2];

This declaration is explained in the following table:

[0] [1] [2] [3] [4] [5] [6]

[0]

[1]

[2]

[3]

[4]

[5]

[6]

[7]

[8]

Page 44: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Chapter 5 Two-Dimensional Arrays

COMP151 Lecture

ConstIntExpression1 and ConstIntExpression2 must have a value greater than zero.

Example of declaring Two-dimensional Array

Here an example of declaring two dimensional array :

int matrix[6][5];

In this example, we have an array called matrix having 6 rows and 5 columns. This

means that the array contains 30 elements (6x5) all of type integer.

Accessing Individual Components

To access an individual array component, we write the array name, followed by an

expression enclosed in square brackets specifying which component to access.

Arrayname [ IndexExpression1] [ IndexExpression2]

Example

Let's consider the following two-dimensional array:

8579

1265

3014

)4,3(AA

ConstIntExpression2 ConstIntExpression1 ArrayName DataType

An integer expression

composed only of literal

or named constants. It

specifies the second

array dimension (the

number of colums in the

array).

An integer expression

composed only of literal

or named constants. It

specifies the first array

dimension (the number

of rows in the array).

The name of the

array

Describes the

type of each

stored

component of

the array

Page 45: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Chapter 5 Two-Dimensional Arrays

COMP151 Lecture

A is an array with 3 rows and 4 columns. It contains 12 components (3x4). In the

following table, we show how to access to any component of the array A.

Component How To

access

Component How To

access

Component How To

access

4 a(0,0) 5 a(1,0) 9 a(2,0)

-1 a(0,1) -6 a(1,1) 7 a(2,1)

0 a(0,2) 2 a(1,2) 5 A(2,2)

3 a(0,3) 1 a(1,3) 8 a(2,3)

Initializing Two-Dimensional Array in Declaration

To initialize the above array

8579

1265

3014

)4,3(AA , we can use the following

declaration:

int A[3][4] = {4, -1, 0, 3, 5, -6, 2, 1, 9, 7, 5, 8};

or:

int A[3][4] = {

{4, -1, 0, 3},

{5, -6, 2, 1},

{ 9, 7, 5, 8}

};

Page 46: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Chapter 5 Two-Dimensional Arrays

COMP151 Lecture

Example 1

Let's shows how to declare an array of five integers.

1

2

3

4

5

6

7

8

9

10

11

12

//Declaring two-Dimensional array

#include <iostream>

using namespace std;

int main()

{

int matrix[2][3]={-1, 2, 9, -3, 10, 11} ;

int i,j;

for (i = 0; i<2; i++)

for (j = 0; j<3; j++)

cout <<"matrix["<< i<<"," <<j<< "] = " << matrix[i][j] << "\n";

return(0);

}

Output: matrix[0,0] = -1

matrix[0,1] = 2

matrix[0,2] = 9

matrix[1,0] = -3

matrix[1,1] = 10

matrix[1,2] = 11

Page 47: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Chapter 5 Two-Dimensional Arrays

COMP151 Lecture

5 Two-Dimensional Arrays

Two-Dimensional Array

A two-dimensional array is used to represent items in a table with rows and

columns, provided that each item in the table is of the same data type.

In the following figure , we have an array with 9 rows which are accessed by an

integer ranging from 0 through 8 and 7 columns which are accessed by an integer

ranging from 0 through 6.

Row 7 , Column 5

Declaring two-dimensional Array Types

Here is a syntax template describing the simplest form of one-dimensional array

declaration:

DataType ArrayName [ ConstIntExpression1] [ ConstIntExpression2];

This declaration is explained in the following table:

[0] [1] [2] [3] [4] [5] [6]

[0]

[1]

[2]

[3]

[4]

[5]

[6]

[7]

[8]

Page 48: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Chapter 5 Two-Dimensional Arrays

COMP151 Lecture

ConstIntExpression1 and ConstIntExpression2 must have a value greater than zero.

Example of declaring Two-dimensional Array

Here an example of declaring two dimensional array :

int matrix[6][5];

In this example, we have an array called matrix having 6 rows and 5 columns. This

means that the array contains 30 elements (6x5) all of type integer.

Accessing Individual Components

To access an individual array component, we write the array name, followed by an

expression enclosed in square brackets specifying which component to access.

Arrayname [ IndexExpression1] [ IndexExpression2]

Example

Let's consider the following two-dimensional array:

8579

1265

3014

)4,3(AA

ConstIntExpression2 ConstIntExpression1 ArrayName DataType

An integer expression

composed only of literal

or named constants. It

specifies the second

array dimension (the

number of colums in the

array).

An integer expression

composed only of literal

or named constants. It

specifies the first array

dimension (the number

of rows in the array).

The name of the

array

Describes the

type of each

stored

component of

the array

Page 49: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Chapter 5 Two-Dimensional Arrays

COMP151 Lecture

A is an array with 3 rows and 4 columns. It contains 12 components (3x4). In the

following table, we show how to access to any component of the array A.

Component How To

access

Component How To

access

Component How To

access

4 a(0,0) 5 a(1,0) 9 a(2,0)

-1 a(0,1) -6 a(1,1) 7 a(2,1)

0 a(0,2) 2 a(1,2) 5 A(2,2)

3 a(0,3) 1 a(1,3) 8 a(2,3)

Initializing Two-Dimensional Array in Declaration

To initialize the above array

8579

1265

3014

)4,3(AA , we can use the following

declaration:

int A[3][4] = {4, -1, 0, 3, 5, -6, 2, 1, 9, 7, 5, 8};

or:

int A[3][4] = {

{4, -1, 0, 3},

{5, -6, 2, 1},

{ 9, 7, 5, 8}

};

Page 50: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Chapter 5 Two-Dimensional Arrays

COMP151 Lecture

Example 1

Let's shows how to declare an array of five integers.

1

2

3

4

5

6

7

8

9

10

11

12

//Declaring two-Dimensional array

#include <iostream>

using namespace std;

int main()

{

int matrix[2][3]={-1, 2, 9, -3, 10, 11} ;

int i,j;

for (i = 0; i<2; i++)

for (j = 0; j<3; j++)

cout <<"matrix["<< i<<"," <<j<< "] = " << matrix[i][j] << "\n";

return(0);

}

Output: matrix[0,0] = -1

matrix[0,1] = 2

matrix[0,2] = 9

matrix[1,0] = -3

matrix[1,1] = 10

matrix[1,2] = 11

Page 51: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

CHAPTER – 5

FUNCTIONS

Page 52: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Functions are used to modularize code or sort it into different blocks or sub-tasks. Functions perform a particular job that the programmer assigns it to do. They make code look neater and more elegant and can be "called" or used as many times as you like. Statements in function bodies are written only once and reused from several locations of a program. It enables the divide and conquer technique. It is called as methods or procedure in other language.

We are going to discuss two types of Functions 1. User Defined Functions 2. Library Functions (or) Predefined Functions

1. User Defined Functions Example program for Simple Function #include<iostream> using namespace std; void starline(); //Function Declaration (or) Prototype int main() { cout<<"Program for Function \n"; starline(); //Call to Function starline cout<<"This is the simple Program\n "; starline(); //Call to Function starline cout<<"Printing Star line to decorate the output\n"; starline(); //Call to Function starline return(0); } void starline() //Function definition { int j; for(j=0;j<45;j++) { cout<<"*"; } cout<<endl; }

2

Page 53: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Output Program for Function ********************************************* This is the simple Program ********************************************* Printing Star line to decorate the output ********************************************* In C++, Function has 3 parts

1. Function declaration (or) Prototype 2. Function Call 3. Function definition

1. Function Declaration (or) Prototype

Just as you can’t use a variable without first telling the compiler what it is, you also can’t use a function without telling the compiler about it. The most common approach is to declare the function at the beginning of the program. In the above program the function starline() is declared in the line void starline();

The declaration tells the compiler that at some later point we plan to present a function called starline. The keyword void specifies that the function has no return value, and the empty parenthesis indicate that it takes no arguments (or) parameters. Function declarations are also called prototypes, since they provide a model (or) blueprint for the function. They tell the compiler, “a function that looks like this is coming up later in the program. Note: The function declaration is terminated with a semicolon.

3

Page 54: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

2. Function Call The function is called (or) invoked (or) executed three times from main(). Each of the three calls looks like this: starline(); The syntax of the function call is: The function name followed by the parenthesis. This is very similar to that of the declaration, except that the return type is not used. The call is terminated by a semicolon. Executing the call statement causes the function to execute; that is, control is transferred to the statement in the function definition are executed, and then control returns to the statement following the function call. 3. Function Definition Finally we come to the function itself, which is referred to as the function definition. The definition contains the actual code for the function. Here’s the definition for starline(); void starline() //declarator (or) header { for(int j=0;j<45;j++) // function body { cout<<’*’; } cout<<endl; } The definition consists of a line called the declarator (or) header, followed by the function body. The function body is composed of the statements that make up the function, delimited by braces. The declarator must agree with the declaration: It must use the same function name, have the same argument types in the same order (if there are arguments), and have the same return type.

4

Page 55: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Notice that the declarator is not terminated by a semicolon. When the function is called, the control transferred to the first statement in the function body. The other statements in the function body are then executed, and when the closing brace is encountered, the control returns to the calling program.

Function Components S.NO Components Purpose Example 1 Declaration

(Prototype) Specifies function name, argument types, and return value. Alerts compiler(and programmer) that function definition is coming up later

void func();

2 Call Causes the function to be executed

func();

3 Definition Body of the function. Contains the lines of code that constitute the function

void func() { -------;//lines of code -------; }

4 Declarator (or) Header

First line of definition

void func()

Common Programming Error A function is invoked (or) called before it is defined (body), and that function does not have a function prototype, a compilation error occurs.

5

Page 56: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Note: If a function is defined before it is invoked, then the function’s definition also serves as the function’s prototype, so a separate prototype is unnecessary. Example Program #include<iostream> using namespace std; /*Function definition before it is called (or) invoked So no need of prototype (or) declaration*/ void starline() { int j; for(j=0;j<45;j++) { cout<<"*"; } cout<<endl; } int main() { cout<<"Program for Function \n"; starline(); //Call to Function starline cout<<"This is the simple Program\n "; starline(); //Call to Function starline cout<<"Printing Star line to decorate the output\n"; starline(); //Call to Function starline return(0); } Good Program Practice In general for the good program practice do the declaration (or) prototype of the function, then main() function followed by definition of function.

6

Page 57: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Passing Parameters (or) Arguments to Functions When a function is called, the program may send values into the function. Values that are passed into a function are called actual arguments (or) actual parameter. The variables that receive these values in function definition are called formal arguments (or) formal parameters. Functions with Empty Parameter List

– Specified by writing either void or nothing at all in parentheses

– For example, void print(); (or) void print(void); Specifies that function print does not take arguments and does not return a value Example Program #include<iostream> using namespace std; void function1(); void function2(void);

Specify an empty parameter list by putting nothing in the parentheses

Specify an empty parameter list by putting void in the parentheses int main()

{ function1(); function2(); return(0); } void function1() { cout<<”function 1 takes no arguments”<<endl; } void function2(void) { cout<<”function 2 also takes no arguments”<<endl; }

7

Page 58: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Output function 1 takes no arguments function 2 also takes no arguments Two ways to pass arguments to functions

1. Pass-by-Value 2. Pass-by-Reference 1. Pass-by-Value When an actual argument is passed into a formal argument, only a copy of the actual argument’s value is passed. Changes to the formal arguments do not affect the actual arguments. Value given in actual argument is straight value (or) value passed through variable Example 1: actual arguments are straight values #include<iostream> using namespace std; in function prototype void repchar(char,int); only arguments int main() data type is enough { repchar(‘-‘,45); Actual arguments repchar(‘*’,25); return(0); } Formal arguments void repchar(char ch,int n) { for(int j=0;j<n;j++) { cout<<ch; } cout<<endl; } Output --------------------------------------------- *************************

8

Page 59: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Example 2: Actual arguments are given through variable #include<iostream> using namespace std; in function prototype void repchar(char,int); only arguments int main() data type is enough { char chin; int nin; cout<<”Enter a character”<<endl cin>>chin; cout<<”Enter number of times to repeat it”<<endl; cin>>nin; repchar(chin,nin); Actual arguments return(0); } void repchar(char ch,int n) Formal arguments { for(int j=0;j<n;j++) { cout<<ch; } cout<<endl; }

Output Enter a character * Enter number of times to repeat it 5 *****

2. Pass-by-Reference When the actual arguments passed to the formal

arguments, the reference variables (used in function declarator (or) header) allow the function to access the actual argument’s original values (not copy). Changes in

9

Page 60: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

the formal arguments in function body will affect the actual arguments.

C++ provides a special type of variable called a reference variable that used as a formal argument allows access to the original values of actual arguments. A reference variable is an alias for another variable. Any changes made to the reference variable are actually performed on the variable for which it is an alias.

Reference variables are declared like regular variables, except you have to place an ampersand (&) symbol in front of the name.

Example Program #include<iostream> int squarebyvalue(int); void squarebyref(int&); using namespace std; int main() { int x=2; int z=3; int y; cout<<"Before square by value call x value is"<<x<<endl; y=squarebyvalue(x); cout<<"After square by value call x value is"<<x<<endl; cout<<"After square by value call y value is"<<y<<endl; cout<<"Before square by reference call z value is"<<z<<endl; squarebyref(z); cout<<"After square by reference call z value is"<<z<<endl; return(0); } int squarebyvalue(int a) { a=a*a; return(a); }

10

Page 61: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

void squarebyref(int &b) { b=b*b; } Output Before square by value call x value is2 After square by value call x value is2 After square by value call y value is4 Before square by reference call z value is3 After square by reference call z value is9 Returning Values From Functions:

When function completes its execution it can return a single value to the calling program. Usually this return value consists of an answer to the problem the function has solved. When a function returns a value, the data type of this return value must be specified.

In the above example squarebyvalue() function returns an integer value to the calling program. So the return type integer is specified before the function name in declaration and in definition. Example Program #include<iostream> using namespace std; float convert(float); int main() { float pound,kg; cout<<”Enter your weight in pounds”<<endl; cin>>pound; kg=convert(pound); cout<<”Your weight in Kilograms is”<<kg; return(0); }

11

Page 62: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

float convert(float p) { float k; k=0.453592*p; return(k); } Output Enter your weight in pounds 45.7 Your weight in Kilograms is20.7292

2. Library Functions (or) Predefined Functions Example: Math Library Functions (or) Math pre-defined Functions

Function Description Example

ceil( x ) rounds x to the smallest integer not less than x

ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x ( x in radians)

cos( 0.0 ) is 1.0

xponential function ex exp( 1.0 ) is 2.71828 ex

e exp( x )

p( 2.0 ) is 7.38906 olute value of x fabs( 5.1 ) is 5.1

fa

abs fabs( x )

bs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76

oor( x ) fl rounds x to the largest integer not greater than x

floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0

od( x, y ) fm remainder of x/y as a floating-point num ber

fmod( 2.6, 1.2 ) is 0.2

log( x ) natural logarithm of x (base e)

log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0

g10( x ) lo logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0

pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128 pow( 9, .5 ) is 3

sin( x ) trigonometric sine of x (x in radians)

sin( 0.0 ) is 0

sqrt( x ) square root of x (where x is a sqrt( 9.0 ) is 3.0 nonnegative value)

tan( x ) trigonometric tangent of x (x in radians) 12

tan( 0.0 ) is 0

Page 63: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

In the above figure, the variables x and y are of type double. These are the predefined functions for mathematical calculations. These functions are global functions and are placed in header file <cmath> or <math>, so that the global functions can be reused in any program that includes the header file <cmath> or <math>. Example Program #include<iostream> #include<cmath> using namespace std; int main() { double x,y; x=12.45; y=1.9; cout<<”Output of ceil function”<<ceil(x)<<endl; cout<<”Output of floor function”<<floor(x)<<endl; cout<<”Output of exp function”<<exp(x)<<endl; cout<<”Output of pow function”<<pow(x,y)<<endl; cout<<”Output of sqrt function”<<sqrt(x)<<endl; cout<<”Output of fabs function”<<fabs(x)<<endl; cout<<”Output of fmod function”<<fmod(x,y)<<endl; cout<<”Output of log function”<<log(x)<<endl; cout<<”Output of log10 function”<<log10(x)<<endl; cout<<”Output of sin function”<<sin(x)<<endl; cout<<”Output of cos function”<<cos(x)<<endl; cout<<”Output of tan function”<<tan(x)<<endl; return(0); } Output Output of ceil function13 Output of floor function12 Output of exp function255250 Output of pow function120.454

13

Page 64: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Output of sqrt function3.52846 Output of fabs function12.45 Output of fmod function1.05 Output of log function2.52172 Output of log10 function1.09517 Output of sin function-0.116108 Output of cos function0.993237 Output of tan function-0.116899 Scope of Variables: All the variables that we intend to use in a program must have been declared with its type specifier. A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block. #include<iostream> using namespace std; int a; char name[50]; Global variables unsigned int numberofsons; int main() { unsigned int age; Local Variables float average,percentage; cout<<”Enter your age:”; cin>>age; Instructions … } Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration.

14

Page 65: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa. Example Program #include<iostream> using namespace std; void fun(); int temp=0; //global variable int main() { int x=15;//local variable to main cout<<"The value of x is"<<x<<endl; temp=temp+x; cout<<"Value of temp in main"<<temp<<endl; fun(); return(0); } void fun() { int a=25;//local variable to fun cout<<"Value of a is"<<a<<endl; temp=temp+a; cout<<"Value of temp in fun"<<temp<<endl; } Output The value of x is15 Value of temp in main15 Value of a is25 Value of temp in fun40

15

Page 66: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

Unary scope resolution operator (::) • Used to access a global variable when a local variable

of the same name is in scope • Cannot be used to access a local variable of the same

name in an outer block Example Program #include<iostream> using namespace std; int number=100; int main() { int number=45; int a=10; cout<<"Value of local variable number in main"<<number<<endl; if(a>0) { int number=10; cout<<"The value of number in if statement is"<<number<<endl; cout<<"Value of global variable number is"<<::number<<endl; } number=number*2; cout<<"Value of local variable number in main"<<number<<endl; ::number=::number+100; cout<<"Value of global variable number is"<<::number<<endl; return(0); } Output Value of local variable number in main45 The value of number in if statement is10 Value of global variable number is100 Value of local variable number in main90 Value of global variable number is200

In the above program main function uses two variable named number. The scope of the first variable number is start from the beginning of main function, and the scope of

16

Page 67: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

second variable number is starting inside if block. The second variable number scope is only within if block. So inside if block number is 10. At that time the global variable number and the first variable number in main function are hided. After if block, number means, it is the first variable number in main. At that time the global variable number is hided. So with the help of unary scope resolution operator we can access the global variable number inside main function. But we can’t use unary scope resolution operator to access the variable number from if block. This will produce an error message. Good Programming Practice

• Always using the unary scope resolution operator (::) to refer to global variables makes programs easier to modify by reducing the risk of name collisions with non-global variables.

• Avoid using variables of the same name for different purposes in a program. Although this is allowed in various circumstances but, it can lead to errors.

Exercises 1. Write a program with a print function to display your

favorite colors. Choose a name for the function that tells what it does. - 2 Marks

2. Write a program with two print functions and call them each from the main function. Write one function to list your favorite foods and another to list your hobbies. - 2 Marks

3. Write a program using a print function to print a right triangle made out of stars (*) which is five stars high and five stars wide at the base of the triangle. - 2 Marks

17

Page 68: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

4. What would the following function do? - 2 Marks void example(int n) { int i; for (i=0; i<n; i++) cout<<'*'; cout<<endl; } How would you call this function in a program? How would you use this function in producing the following output on the screen? * ** *** ****

5. Check the following two programs are correct or not. If it is correct what would be the output of these two programs?

- 2 Marks a)

#include<iostream> using namespace std; void change(void) { int x; x=1; } int main() { int x; x=0; change(); cout<<x<<endl; return(0); }

18

Page 69: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

b) #include<iostream> using namespace std; void change(int x) { x=1; cout<<x<<endl; }

int main() { int x; x=0; change(x); cout<<x<<endl; return(0); }

6. Write a function prototype for a function that takes two parameters of type float and returns true (1) if the first parameter is greater than the second and otherwise returns false (0). - 1 Mark

7. How is information supplied as input to a function? How

can information be conveyed back to the calling program? - 1 Mark

8. Check the following program is correct or not. If it is correct what would be the output of the program? - 2 Marks #include<iostream> using namespace std; void change(int &y) { y=1; }

19

Page 70: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

int main() { int x; x=0; change(x); cout<<x<<endl; return(0); }

9. If a function doesn't return a value, what type should it be

declared? - 1 Mark 10. What must be the first line of a function definition, and

what information does it contain? - 1 Mark 11. How many values can be returned from a function?

- 1 Mark 12. What is the significance of empty parenthesis in a

function declaration? - 1 Mark 13. True or False: When a function returns a value, the

entire function call can appear on the right side of the assignment statement and be assigned to another variable on the left side. - 1 Mark

14. True or False: When actual arguments are passed by

value, only the copy of the actual arguments are sent to the formal arguments and later changes on the formal arguments will affect the actual arguments. - 1 Mark

15. Where is a function’s return type specified? - 1 Mark

20

Page 71: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

16. Regarding Overloaded functions which of the following statement(s) is(are) true. - 1 Mark

a). are group of functions with the same name and all have the same number and types of arguments b). make life simpler for programmers c). are group of functions doing the same work with different names. d). all have the same number and types of arguments with different return types. e). are group of functions with the same name and all have the different number, different sequence and different types of arguments.

17. Write declarations for two overloaded functions named bar(). They both return type int. The first takes one argument of type char, and the second takes two arguments of type char. If this is impossible, say why?

- 1 Mark 18. Write a declaration for a function called blyth() takes

two arguments and return type char. The first argument is type int, and the second is type float with a default value of 3.14159 - 1 Mark

19. Write a function called zerosmaller() that is passed two

int arguments by reference and then sets the smaller of the two numbers to 0(zero). Write a main() program to execute this function. - 2 Marks

20. Write a function called circarea() that finds the area of a

circle. It should take an argument of type float and return an argument of the same type. Write a main() function that gets a radius value from the user, calls circarea(), and displays the result. - 2 Marks

21

Page 72: CHAPTER – 4 CONTROL STRUCTURES - جامعة نزوى · CHAPTER – 4 CONTROL STRUCTURES 1. ... Three control structures • Sequence structure ... • Repetition structures –

21. Check the following program is correct or not. If it is correct what would be the output of the program? - 2 Marks #include<iostream> using namespace std; void square(int); int c=3; int main() { int a=1; int c=12; c=c/2; cout<<"The value of c is"<<c<<endl; square(c); square(::c); if(a<10) { int c=44; cout<<"The value of c is"<<c<<endl; } c++; cout<<"The value of c is"<<c<<endl; ::c=::c+5; cout<<"The value of c is"<<::c<<endl; return(0); }

void square(int x) { int c; c=x*x; cout<<"The value of c is"<<c<<endl; ::c++; cout<<"The value of c is"<<::c<<endl; }

22