You are on page 1of 37

COMPUTER

PROGRAMMING

Lecture 04
Switch Multiple Selection Structure
While Repetition Structure

Dr. Muniba Ashfaq


TODAY’S AGENDA
 Switch Multiple Selection Structure
 Syntax
 Flowchart
 Examples
 While Repetition Structure
 Syntax
 Flowchart
 Examples
 Nested Control Structure
 Example

Dr. Muniba Ashfaq


THE SWITCH MULTIPLE-SELECTION
STRUCTURE
 Switch is typically a selection structure and an alternative to the long string
of ifs
 Tests variables for multiple values
 Consists of a series of case labels and an optional default case
 General format

 switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch

case value2:
case value3: // taken if variable == value2 or == value3
statements
break;

default: // taken if variable matches no other cases


statements
break;
}

Dr. Muniba Ashfaq


THE SWITCH MULTIPLE-SELECTION
STRUCTURE
 Expression (variable in braces after switch)
must be of type integer or character. It is the
controlling expression of switch statement

 The keyword case must be followed by a


constant

 break statement is required unless you want all


subsequent statements to be executed.

Dr. Muniba Ashfaq


RULES
The following rules apply to a switch
statement:
 You can have any number of case statements
within a switch. Each case is followed by the
value to be compared to and a colon.

 The constant-expression for a case must be


the same data type as the variable in the
switch.

Dr. Muniba Ashfaq


RULES CONTD..
 When the variable being switched on is
equal to a case, the statements following
that case will execute until a break
statement is reached
 When a break statement is reached, the
switch terminates, and the flow of control
jumps to the next line following the switch
statement

Dr. Muniba Ashfaq


RULES CONTD..
 Not every case needs to contain a break. If
no break appears, the flow of control
will fall through to subsequent cases until
a break is reached
 A switch statement can have an
optional default case, which must appear
at the end of the switch. The default case
can be used for performing a task when
none of the cases is true. No break is
needed in the default case

Dr. Muniba Ashfaq


EXAMPLE
#include <iostream>
using namespace std;
int main ()
{
char grade = 'D'; // local variable declaration:
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl; break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl; }
cout << "Your grade is " << grade << endl;
return 0; } Dr. Muniba Ashfaq
OUTPUT
This would produce the following
result:

You passed
Your grade is D

Dr. Muniba Ashfaq


REVIEWING CHARACTER
DATA TYPE
 As we know a computers can process character data too
 char
 Short for character
 Can be any single character from the keyboard
 To declare a variable of type char:

char letter;

 Character constants are enclosed in single quotes

char letter = 'a';

 Strings of characters, even if only one character


is enclosed in double quotes
 "a" is a string of characters containing one character
 'a' is a value of type character

Dr. Muniba Ashfaq


CHAR   INT
 It is possible to store char values in integer variables (an important feature of c++)
 Characters are represented as 1-byte integer in computers so we can treat a
character as either char or int depending on its use
int value = ‘A'; //65 is ASCII for A

 value will contain an integer representing 'A‘ i.e. value = 65


 Similarly
 It is possible to store int values in char variables

char letter = 97; //97 is numerical representation of lower case a (ASCII)


 Result of the above statement is letter = a

 Use single quotes to get numerical representation of a character

cout << "The character (" << 'a' << ") has the value "
<< ( int ) ( 'a' ) << endl;
Prints
The character (a) has the value 97

ASCII (American Standard Code For Information Interchange)

Dr. Muniba Ashfaq


COMPARING IF/ELSE WITH SWITCH WITH THE HELP OF
AN EXAMPLE

•When you want to create different outcomes depending on specific


values, you can use a series of ifs.

Dr. Muniba Ashfaq


COMPARING IF/ELSE WITH SWITCH WITH THE HELP OF
AN EXAMPLE
 However, as an alternative to the long string of ifs, you can use the switch statement
 Department is the control variable and is integer
 Compare the department to cases and prints the department it matches.

Removing break changes behavior of


statement.
It causes switch statement to end.

Dr. Muniba Ashfaq


REPETITION STRUCTURES
 Many application require certain operations to be carried out more than once. Such
situations require repetition in control flow.
 C++ has three types while, do/while, for
 while Repetition Structure
 Action repeated while some condition remains true.
 When an action must be repeated a loop is used.

 While loop syntax


 while (boolean expression is true)
{
statements to repeat ; //braces are required for compound statement.
}
 While (boolean expression is true)
statement to repeat; // no braces are required for single statement

Dr. Muniba Ashfaq


WHILE STATEMENT
SYNTAX

Dr. Muniba Ashfaq


WHILE REPETITION
STRUCTURE
 Flow chart

no
condition

yes

Statements in
Loop body

Dr. Muniba Ashfaq


WHILE LOOP OPERATION
 First, the condition is evaluated

 If true, the body of the loop is executed and the control is transferred back
to the condition for re-evaluation
 During execution, some item from the boolean expression

is changed

 If false, the while loop is exited and control is transferred to the statement
after the while loop body.

 A while loop might not execute at all if the


boolean expression is false on the first check

Dr. Muniba Ashfaq


EXAMPLE:
#include <iostream>
using namespace std;
int main ()
{ // Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++; }
return 0;
}

Dr. Muniba Ashfaq


OUTPUT
When the above code is compiled and executed, it
produces the following result:
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
Dr. Muniba Ashfaq
WHILE REPETITION STRUCTURE
 Psuedocode example
while there are more items on my shopping list
Purchase next item and cross it off my list
 while loop repeated until condition becomes false

 Condition there are more items on my shopping list is either true or false.
 If true, the action “Purchase next item and cross it off my list” is performed.
 The action will be performed repeatedly while the condition remains true.
 The condition will become false when the last item on the list is purchased and
crossed of the list. The repetition will terminate.
 Then the first statement after the repetition structure is executed.

Dr. Muniba Ashfaq


WHILE REPETITION
STRUCTURE

 Example statement
 Consider a program segment designed to find the first power of 2 larger
than 1000.
 Suppose the integer variable product has been initialized to 2.
 When wile repetition structure finishes executing.
 Product will contain the desired answer.

 Lets observe the flow chart and the c++ code.

Dr. Muniba Ashfaq


WHILE REPETITION
STRUCTURE
 Flow chart

true
product <= 1000 product = 2 * product

false

 C++ Code
int product = 2;
while ( product <= 1000 )
product = 2 * product;

Dr. Muniba Ashfaq


EXPLANATION
 In the previous example the value of product is 2 when the while
structure is entered.

 The variable product is repeatedly multiplied by 2, taking values


4, 8, 16, 32, 64, 128, 256, 512, 1024.

 At product = 1024 the while structure condition product<=1000,


becomes false.

 This terminates the repetition.

 Observe that the final value of product is 1024.

Dr. Muniba Ashfaq


EXAMPLE TO PRINT GREETINGS USING WHILE
REPETITION STRUCTURE
1. //a while loop example
2. //program to print the hello greetings
3. //user give the number of times hello greeting to be printed.

4. #include <iostream.h>

5. int main()
6. {
7. int count_down; //declaring count_down as an integer variable
8. cout<<"How many greetings do u want\n"; //prompt user to enter the number for greetings
9. cin>>count_down; //reading value this value gives number of times greeting will appears

10. while(count_down > 0) //while loop condition, if countdown is greater than zero
11. {
12. cout<<"HELLO!\t"; //printing hello
13. count_down = count_down - 1; //decrementing the value in count_down (counter) by 1
14. } //while body ends here
15. cout<<endl;
16. cout<<"thats all \n"<<"have a great day";
17. return 0;
18. }

Dr. Muniba Ashfaq


OUT PUT FOR TWO DIFFERENT INPUTS

Input = 5

Printing hello 5 times

Input = 7
Printing hello 7 times

Dr. Muniba Ashfaq


COUNTER CONTROL
REPETITION
 Loop is repeated until counter reaches certain value.
 Number of repetitions known before the loop begins executing
(Definite repetition).
 Counter variables should be initialized before the loop begins.
 An uninitialized counter may contain a garbage (undefined)
value and the result of the program could be incorrect (LOGIC
ERROR).
 Counter variables are normally initialized to zero or one,
depending on their use.

Dr. Muniba Ashfaq


ESSENTIALS OF COUNTER-CONTROLLED
REPETITION

 Counter-controlled repetition requires

 Name of control variable/loop counter


 Initial value of control variable
 Condition to test for final value
 Increment/decrement to modify control variable when looping

Dr. Muniba Ashfaq


COUNTER CONTROL
REPETITION
 //Consider a simple example to understand counter
controlled //repetition structure.
1. //print 1 to 100 using a while loop
2. #include <iostream.h>

3. int main()
4. {
5. int count; //declaration of control variable count
6. count=1; //initialization of control variable
7. while (count<=100) //while count is less than 100 program will print the count
8. {
9. cout<<count<<“\t”;
10. count=count+1 //add one to the count every time the loop repeats.
11. } /*when count is greater than 100 then the loop will
12. terminate and the statement next to the while loop will execute*/
13. Return 0; //indicated successful termination
14. } //end of function main

Dr. Muniba Ashfaq


OUTPUT

Dr. Muniba Ashfaq


C++ CODE
1. // example
2. // Class average program with counter-controlled repetition.
3. #include <iostream.h>

4. // function main begins program execution


5. int main()
6. {
7. int total; // sum of grades input by user
8. int gradeCounter; // number of grade to be entered next
9. int grade; // grade value
10. int average; // average of grades
11.

12. // initialization phase


13. total = 0; // initialize total
14. gradeCounter = 1; // initialize loop counter
15.

Dr. Muniba Ashfaq


C++ CODE
21 // processing phase
22 while ( gradeCounter <= 10 ) { // loop 10 times
23 cout << "Enter grade: "; // prompt for input
24 cin >> grade; // read grade from user
25 total = total + grade; // add grade to total
26 gradeCounter = gradeCounter + 1; // increment counter
27 }
28
29 // termination phase
30 average = total / 10; // integer division
31
The counter gets incremented each
32 // display result
time the loop executes.
33 cout << "Class average is " << average << endl;
Eventually, the counter causes the
34 loop to end.
35 return 0; // indicate program ended successfully
36
37 } // end function main
38 //observe the output on next slide

Dr. Muniba Ashfaq


OUTPUT

•Note that total is 723


•Average = 723 / 10 = 72.3(floatin point number)
•Program produce an integer result 72,
•because average is identified as integer type
•To deal with such situation we use the explicit
conversion which we will discuss latter.

Dr. Muniba Ashfaq


SENTINEL-CONTROLLED
REPETITION
 Also called indefinite repetition.
 The number of repetitions is not known before the loop begins executing.
 unknown number of inputs to the loop.
 Requires a sentinel value (to indicate end of data entry) to quit the loop.

 Sentinel value
 Also called dummy value, signal value or a flag value.
 Indicates “end of data entry”
 Loop ends with sentinel input
 Sentinel value should be chosen so that it cannot be confused with an
acceptable data value.
 For example (-1) in case of grade example.
 As -1 is not going to be any grade (grade is only + value) so
this can be used to quit the loop.

Dr. Muniba Ashfaq


C++ CODE
1 // grade example for sentinel controlled repitition
2 // Class average program with sentinel-controlled repetition.
3 #include <iostream.h>
4
10 #include <iomanip.h> // parameterized stream manipulators
11
12
13
14 // function main begins program execution
15 int main()
16 {
17 int total; // sum of grades Data type double used to represent
18 int gradeCounter; // number of gradesdecimal
enterednumbers.
19 int grade; // grade value
20
21 double average; // number with decimal point for average
22
23 // initialization phase
24 total = 0; // initialize total
25 gradeCounter = 0; // initialize loop counter

Dr. Muniba Ashfaq


C++ CODE
26
27 // processing phase
28 // get first grade from user
29 cout << "Enter grade, -1 to end: "; // prompt for input
30 cin >> grade; // read grade from user
31
32 // loop until sentinel value read from user
33 while ( grade != -1 ) {
34 total = total + grade; // add grade to total
35 gradeCounter = gradeCounter + 1; // increment counter
36
37 cout << "Enter grade, -1 to end: "; // prompt for input
38 cin >> grade; // read next grade •As dividing two integers truncates the remainder, to deal
39 with it unary cast operator is used. Its general form is
40 } // end while <type>(operand)
41 •<float>(total)is used in this program. It creates a temporary
42 // termination phase floating point copy of operand in the parenthesis.
•Here it treats total as a float temporarily (casting).
43 // if user entered at least one grade ... producing a floating point calculation with integer values.
44 if ( gradeCounter != 0 ) { •. Using cast operator in this manner is called explicit
45 conversion.
46 // calculate average of all grades entered •gradeCounter is an int, but it gets promoted to float by the
47 average = <float >( total ) / gradeCounter;
compiler implicitly for the calculation purpose.

Dr. Muniba Ashfaq


setprecision(2)prints two digits past
C++ CODE decimal point (rounded to fit precision).
49 // display average with two digits of precision
Programs that use this must include
50 cout << "Class average is " << setprecision( 2 )
<iomanip.h>
51 << fixed << average << endl;
52
53 } // end if part of if/else
54
55 else // if no grades were entered, output appropriate message
56 cout << "No grades were entered" << endl; fixed forces output to print
57 in fixed point format (not
58 return 0; // indicate program ended successfully scientific notation). Also,
59 forces trailing zeros and
60 } // end function main decimal point to print.

Include <iostream>

Dr. Muniba Ashfaq


OUTPUT

Notice -1 (sentinel value) indicating


the end of the data entry.

Dr. Muniba Ashfaq

You might also like