You are on page 1of 22

CHAPTER 5 CONTROL STRUCTURE

Objectives

Making decision using if, if-else and switch statement Making decision using nested if statement Using looping control structures in the program; while, do-while

and for statement. Using nested loop Using break statements, continue statements and infinite loops

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

5.1 Selection structure - If statements


Called a decision statement It tests relationship using relational operators. Used to make decision based on condition.

Syntax:

if (condition) { Block of 1 or more C statement }

The block of statements following the if statement will execute if the decision (the result of the relation) is True. If statement may or may not execute a section of a code if it does, it executes that section only once. Flowchart:

condition

TRUE

FALSE

True statement

Example:

/*this program using if statement*/ #include <iostream.h> void main() { int num = 10, square; if (num <= 180) { square = num * num; cout << The square is <<square; } }

Lecturer: Wannoraini Abdul Latif

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

5.2 if-else statement Used to make decision based on condition. Syntax: if (condition) { /*any statement if condition } else { } /* any statement if condition = FALSE*/

= TRUE*/

else statement never appears in a program without if statement If tested condition is TRUE, the entire block of statements following the if is performed. If the tested condition is FALSE, the entire block of statements following the else is performed. Flowchart:

TRUE

condition

FALSE

True statement

False statement

Lecturer: Wannoraini Abdul Latif

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Example:
/*this program using if-else statement*/ /*this program using if-else statement*/ #include <iostream.h> #include <iostream.h> #include <string.h> #include <string.h> void main() void main() { { int A = 2, B = 5, min; int A = 2, B = 5, min; /*find minimum value between 2 integers*/ /*find minimum value between 2 integers*/ if (A < B) if (A < B) { { min = A; min = A; } } else else { { min = B; min = B; } } cout << Minimum is << min; cout << Minimum is << min;

} }

5.3

String Comparison You cannot compare the string value using the relational operators. The string comparison starts with the first character in each string and continues with subsequent characters until the corresponding characters differ to until the end of the strings is reached.

string.h.

For string comparison, you must using strcmp function from header file

Besides string comparison, you also can use header file string.h for copying data (strcpy), string connection (strcat) and know string length (strlen).

Lecturer: Wannoraini Abdul Latif

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Example of string comparison:


/*string #include #include #include comparison the wrong way*/ <iostream.h> <string.h> <stdio.h>

void main() { char password [10]; cout << Please enter your password; gets(password); if (password == kembara2000) { cout << Access Granted !; } else { } }

There s a syntax error here!! You cant compare like this.

cout << Access Denied !; /*the write way for string comparison*/ #include <iostream.h> #include <string.h> #include <stdio.h> void main() { char password [10];

Solution

cout << Please enter your password; gets(password); if (strcmp (password, kembara2000) == 0) { cout << Access Granted !; } else { cout << Access Denied !; } }

Example for string copy char *s; /*or char s[5];*/ strcpy (s, Blue); * After this code, the value of variable s is Blue Example of string connection char *s; strcpy (s, light); strcat (s, Blue); Lecturer: Wannoraini Abdul Latif 5

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

* After this code, the value of variable s is Light Blue

Example of string length int n; char s[5]; strcpy (s, air); n = strlen (s); * After this code, the value of variable n is 3. It is because strlen functions not calculate a NULL (\0) character that ending the string. 5.4 Nested if

When if...else is included within an if...else, it is known as a nested if statement. There is no limit to how many levels can be nested, but if there are more than three, they become difficult to read. There are 3 types of nested if.

Type 1 Syntax:
if (condition 1) { if (condition2) { if (condition3) { Execute if condition1, condition 2 and condition 3 = TRUE } } }

Flowchart:

Condition

TRUE

FALSE

Condition

TRUE

FALSE

condition

TRUE

FALSE

True statement 6

Lecturer: Wannoraini Abdul Latif

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Example:
/*this program using nested if type 1*/ . int a, b; cout << Please enter two integers : ; cin >> a; cin >> b; if (a <=0) { if (a <= b) { if(a < b) { cout << a is less than b; } } }

Type 2 Syntax :
if (condition1) { if (condition2) { if (condition3) { execute if condition1, condition2 and condition3 = TRUE } else { execute if condition1 and condition2 = TRUE and condition3 = FALSE } } else { execute if condition1 = TRUE and condition2 = FALSE } } else { execute if condition1= FALSE }

Lecturer: Wannoraini Abdul Latif

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Flowchart : condition
TRUE

condition

TRUE

FALSE FALSE

condition

TRUE

False statement

True statement
FALSE

False statement

False statement

Example :
/*This program show nested if type 2*/ char name[20], password[6]; int num; cout << Please Enter Your Name : ; cin >> name; cout << Please Enter Your Password : ; cin >> password; cout << Please Enter a Number : ; cin >> num; if (strcmp (name, user) == 0) { if (strcmp (password, cbt) == 0) { if (num == 5) { cout << WELCOME; } else { cout << Wrong Number; } } else { cout << Invalid Password; } } else { Lecturer: Wannoraini Abdul Latif cout << Invalid User; exit(0); }

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Type 3 Syntax:
if (condition1) { execute if condition1 = TRUE } else { if (condition2) { execute if condition2 = TRUE and condition1= FALSE } else { if (condition3) { execute if condition3 = TRUE, and condition1 and condition2 = FALSE } else { execute if condition1,condition2 and condition3 = FALSE } } }

Flowchart:

condition

TRUE

True statement

FALSE

condition

TRUE

True statement

FALSE

condition

TRUE

True statement

FALSE

False statement

Lecturer: Wannoraini Abdul Latif

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Example:
/*this program show using nested if type 3*/ . int num; cout << Please enter a number : ; cin >> num; mod = num % 2; if (mod == 0) { cout << No remainder; } else { if (mod == 1) { cout << Remainder = << mod; } else { if (mod == 2) { cout << Remainder = << mod; } else { cout << Remainder is more than 2; } } }

5.5 Switch statement

The switch statement is a better way of writing a program when a series of if-else occurs. This switch structure consists of a series of case label and optional default case. Switch followed by variable name in parentheses called controlling expression.

Syntax:
switch (expression) { case value1: /*any statements if expression= value1*/ break; . . . case valueN: /* any statements if expression = valueN*/ break; default: /*any statements if none of the expression is Lecturer: Wannoraini Abdul Latif matched*/ break; }

10

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Flowchart:

TRUE

case 1
FALSE

Statement for value= 1

break

case N

TRUE

Statement for value= N

break

FALSE

Statement for value= DEFAULT

Example:
cout << Please enter colour code :; cin >> code); switch (code) { case 1 : cout << RED; break ; case 2 : cout << GREEN; break ; case 3 : cout << YELLOW; break ; case 4 : cout << BLUE; break ; default : cout << Invalid colour code !; }

The keyword break must be included at the end of each case statement. The break statement causes program control to proceed with the first statement after the switch structure. Without break statement, all command for that case and next case label will be executed. 11

Lecturer: Wannoraini Abdul Latif

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Example: Without break statement


cout << Enter a number : ; cin >> num; switch (num) { case 1 : cout << WELCOME; case 2 : cout << BYE; default : cout << Wrong Number; }

If input = 1 Output

With break statement


cout << Enter a number : ; cin >> num; switch (num) { case 1 : cout << WELCOME; break; case 2 : cout << BYE; break; default : exit(0); }

If input = 1 Output

Default is an option that will only be executed if suitable case cannot be found.

Rules for Switch statement: The value of case statement must be integer or character constant. Case statement arrangement is not important Default can exist earlier (but assembler will place it at the end) You cant use condition or limit.

Lecturer: Wannoraini Abdul Latif

12

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Comparison between switch statement and nested if statement. if....else statement


cout << Enter a number :; cin >> num; a = num % 2 if (a = 0) { cout << No Remainder!!; } else { cout << Remainder = << a; }

switch statement
cout << Enter a number :; cin >> num; a = num % 2 switch (a) { case 0 : cout << No Remainder!!; break; default : cout << Remainder = << a; }

Why switch is the best way to write a program? More readability More specific statement to implement multiple alternative decision Used to make a decision between many alternatives Different conditions can be expressed as integral values

5.6 Looping control structure

A programming control structure that allows a series of instructions to be executed more than once. Repeating same statement several; times while conditions are still met Three types of loop structure control:

1.

while loop 13

Lecturer: Wannoraini Abdul Latif

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

2. 3.

dowhile loop for loop Loop structure is usually used when we want to repeat the same task. An example is

an input of 20 students name. While statement The test occurs at the begin of the loop.

Syntax:
while (test expression) { Block of one or more C statement; }

Flowchart:

condition

TRUE

FALSE

C statement

Example: this program uses while statement


#include <iostream.h> void main () { int count count = 1; while (count <= 3) { cout << Welcome !; count ++; } }

Output

do-while loop Similar to the while loop except that the test occurs at the bottom (rather than at the top) of the loop. This ensures that the body of the loop executes at least once.

Lecturer: Wannoraini Abdul Latif

14

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Syntax:
do { block of one or more C statement; }while(test expression);

Flowchart:

C statement

condition

TRUE

FALSE

Example of program using do-while statement


#include <iostream.h> void main() { char status; do { cout << Enter your marital status :; status = getchar(); }while ((status != M) && (status !=B)); cout << Your status code accepted !; }

Output:

Comparison between while and do-while Example:


/*while* #define SENTINEL 5 value = 5; while (value < SENTINEL) { cout << Inside Loop \n; value++; } cout >> Outside Loop;

Check the condition before running

Lecturer: Wannoraini Abdul Latif

15

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

/*do-while*/ #define SENTINEL 5 value = 5; do { cout >> Inside Loop \n; value++; }while (value < SENTINEL); cout >> Outside Loop;

Do at least once without check the condition, and then check the condition

Example: Program-based menu


/*Menu-based application*/ #include <iostream.h> void main() { int choice; do { cout << cout << cout << cout << cout << cout << cout << cout << }while (choice } LIST OF OPERATION\n; 1. Addition\n; 2. Subtraction\n; 3. Division\n; 4. Multiplication\n; 0. Exit\n; Your choice ?; choice; != 0);

Output

for statement Repeat the section of your program based on a specified number of times. Unlike the while and do-while loops, the for loop is a determinate loop For statement is helpful in making looping through a section of code when you want to count or total specified amount. Syntax: Lecturer: Wannoraini Abdul Latif 16

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

for (StartExpression;TestExpression;CountExpression) { /*any statement if test expression is TRUE*/ }

NOTE

StartExpression Evaluate before the loop begins and it is one of assignment statement TestExpression Looping continues as long as the TestExpression is TRUE CountExpression Every time the body of the loop repeats. The CountExpression executes, usually increment /decrement. Flowchart

Start Expression
TRUE

Test statement
FALSE

C statement

Count expression

Example:
/*for*/ #include <iostream.h> void main() { int number; /*View 3 messages*/ for (number = 1; number <= 3; number ++) { cout << WELCOME !; } }

For loop will test the first loop structure. If TestExpression is FALSE for loop is not executed.

The diagram shows a sequence of process of a for loop.

Lecturer: Wannoraini Abdul Latif

17

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

1. 2. 3. 4.

The first part of the for statement initialises the value. The for loop continues whilst the condition evaluates as TRUE As the variable has just been initialised, and this condition is TRUE, so the program statement is executed. Next, the remaining statement of the for is executed which adds or subtracts the current value. Control now passes back to the conditional test, if TRUE, the program statement is executed, if not.. (Proceed to number 5)

5.

The conditional test evaluates as FALSE, and the for loop terminates, and program control passes to the next statement outside the for statements.

Comparison between for loop and while loop for loop


/*for*/ #include <iostream.h> void main() { int number; for (number = 1; number <= 3; number ++) { cout << WELCOME !; } }

while loop
/*while*/ #include <iostream.h> void main() { int number = 1; while (number <= 3) { cout << WELCOME !; number++; } }

5.7 Nested Loop

Any statement can go inside the body of a for / while / do...while, even another for / while / do...while. We called this situation as a nested loop (you put a loop within a loop). In nested loop, the inside loop(or loops) execute completely before the outside loops next iteration.

Lecturer: Wannoraini Abdul Latif

18

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Syntax :
Outer loop statement { Inner loop statement { } }

Flowchart:

condition

TRUE

TRUE condition FALSE FALSE

C statement

Example of nested for loop: Use a nested loop to reproduce the following output: 1 1 2 22 3 123 4 1234 /*nested loop*/ /*nested loop*/ 5 #include <iostream.h> 12345
#include <iostream.h> void main() void main() { { int outer, inner; int outer, inner; for (outer = 1; outer <= 5; outer ++) for (outer = 1; outer <= 5; outer ++) { { cout << outer; cout << outer; for (inner = 1; inner <=outer; inner ++) for (inner = 1; inner <=outer; inner ++) { { cout << inner; cout << inner; } } Lecturer: Wannoraini Abdul Latif << \n; cout << \n; cout } } } }

19

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Count total mark for 5 students where each student has 3 marks
#include <iostream.h> void main() { int student, sum, marks, yourMarks; char studentName [25]; for (student = 1; student <= 5; student++) { cout << Please enter student name :; cin >> studentName; sum = 0 ; for (marks = 1; marks <= 3; marks++) { cout << Please enter marks of assignment %d, marks; cin >> yourMarks; sum += yourMarks; } } cout << Total Marks : << sum; }

Example of nested while loop: Use a nested loop to reproduce the following output: 1 22 333 4444 55555 #include <iostream.h> #include <iostream.h>
void main() void main() { { int loop; int loop; int count; int count; loop = 1; loop = 1; while( loop <= 5 ) while( loop <= 5 ) { { count = 1; count = 1; while( count <= loop ) while( count <= loop ) { { cout << "loop; cout << "loop; count++; count++; } } cout << \n; cout << Lecturer: Wannoraini Abdul Latif loop++; \n; loop++; } } } }

20

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

Example of nested for and while loop Count total mark for 5 students where each student has 3 marks of quizzes
#include <iostream.h> #include <iostream.h> void main() void main() { { int student, sum, marks, yourMarks; int student, sum, marks, yourMarks; char studentName [25]; char studentName [25]; for (student = 1; student <= 5; student++) for (student = 1; student <= 5; student++) { { cout << Please enter student name :; cout << Please enter student name :; cin >> studentName; cin >> studentName; sum = 0; sum = 0; marks = 1; marks = 1; while (marks < 4) while (marks < 4) { { cout << Please enter marks of cout << Please enter marks of assignment %d, marks; assignment %d, marks; cout << yourMarks; cout << yourMarks; sum += yourMarks; sum += yourMarks; mark++; mark++; } }

} }

} } cout << Total Marks : << sum; cout << Total Marks : << sum;

5.8

Break statement Cause the loop to immediately exit the structure Quit the loop before the counting variable has reached its final value. Program execution continues with the first statement after the structure. Common use of break statement is to escape early from a loop or to skip the remainder of the switch structure. Example
for (count = 1; count <= 5; count ++) { cout << A\n; break; cout << B\n; } cout << Outside Loop;

Lecturer: Wannoraini Abdul Latif Quit the loop

21

TCS1013: INTRODUCTION TO PROGRAMMING

CHAPTER 5

5.9

Continue statement Skip the remaining statements in the body of structure and proceed with the next iteration of the loop(force the computer to perform another iteration of the loop). Example Perform another iteration

for (count = 1; count <= 5; count ++) { cout << A; continue; cout << B; } cout << Outside Loop;

The continue statement is used when data in the body of the loop is bad out of bound or unexpected.

5.10

Infinite loops

Infinite loop is the situation where the iteration of looping never ends. This is because of the condition (testExpression) always TRUE. Press Ctrl + break or Ctrl + C to interrupt.

Example:
for (count = 1; count >= 1; count ++) for (count = 1; count >= 1; count ++) { { cout << WELCOME !; cout << WELCOME !; } }

Lecturer: Wannoraini Abdul Latif

22