6 Control Structures-1.pptxAAAAAAAAAAAAAAAAAAAAA

EG20910848921ISAACDU 19 views 53 slides Oct 09, 2024
Slide 1
Slide 1 of 53
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53

About This Presentation

Revision


Slide Content

Control Structure

Introduction A control structure is simply a pattern for controlling the flow of a program module. These statements are commonly referred to as control statements because they “control” the flow of program execution. The three fundamental control structures of a structured programming language are: Sequence Selection Iteration

Introduction cont’d… One of the most important aspects of programming is controlling which statement will execute next. Control structures / Control statements enable a programmer to determine the order in which program statements are executed. These control structures allow you to do two things: Skip some statements while executing others, and Repeat one or more statements while some condition is true.

Sequential Program Control By sequential we mean "in sequence," one-after-the-other. Sequential logic is the easiest to construct and follow. Essentially you place each statement in the order that you want them to be executed and the program executes them in sequence from the Start statement to the End statement. For instance, If your program included 20 basic commands, then it would execute those 20 statements in order and then quit.

Control Statements Control statements change the flow of a program based on specified conditions. There are two types of control statements that is: Branching control - if - switch Looping/Iteration control - for - while - do.. while

Selection/Branching Control It is common that you will need to make a decision about some condition of your program's data to determine whether certain statements should be executed. A selection-control statement allows you to make "decisions" in your code about the current state of your program's data and then to take one of two alternative paths to a "next" statement. All decisions are stated as "yes/no" questions. When a program is executed, if the answer to a decision is "yes" (or true), then the left branch of control is taken. If the answer is "no" (or false), then the right branch of control is taken.

Branching Statements if statement The if statement is a powerful decision-making statement and is used to control the flow of execution of statements. It is a two-way decision statement and is used in conjunction with an expression, and takes the following form; if (test expression) statement;

if statement The if statement may be implemented in different forms depending on the complexity of conditions to be tested as follows: Simple if statement If …. else statement Nested if ….. else statement  

Simple if statement The general form of a simple if statement is: if (test expression) statement; The statement block may be a single statement or a group of statements. If the test expression is true the statement block is executed; otherwise it will be skipped and the program control jumps to statement . E.g. If( avg >50 ) printf (“pass”);

Example Write a program to input voter’s name and age then display “you are allowed to vote” if age is equal or greater than 18. Write a program to input student name, maths , english and kiswahili then calculate total and average marks and display the result. If average marks is greater or equal to 50 it should display “pass” else it should display “fail”.

Algorithm Input voter name Input voter age If (age>=18) display “You are allowed to vote”

If age>=18 Vote Not allowed to vote STOP YES NO START Input voters’ name and age

Program code # include < stdio.h > int main() { char vname [10]; int age; printf (“Enter voters’ name”); scanf (“%s”,& vname ); printf (“Enter age”); scanf (“%d”,& age); if (age>=18) printf (“Vote”); else printf (“Not allowed to vote”); } r eturn 0; }

The if …… else Statement It is used to decide between two courses of action. The if … else statement is an extension of the simple if statement. Its general form is ; if (test expression) true-statement(s); else false-statement(s); Example If( avg >50) printf (“pass”);else printf (“fail”); If the expression is TRUE, statement1 is executed; statement2 is skipped. If the expression is FALSE, statement2 is executed; statement1 is skipped.

Example Write a program to enter product name, quantity and price then calculate total price. If total price is greater than 10000 a discount of 10% is offered. Otherwise no discount is offered. Let the program display the discount and net price. If ( tprice >10000) disc=0.1* tprice ; Else disc=0; Netprice = tprice -disc;

Design a flow chart and hence implement a program to input employee name, hours worked and rate per hour then calculate gross pay. Let the program calculate tax o f 15% when gross pay is greater than or equal to 50000 and 10% when gross pay is less than 50000.

Operators Arithmetic operators + , - , *, / ++ increment operator – increase a value by one. -- decrement operator – Decrease a value by one. % modulus – Give the reminder after a division

Conditional/Relational operators They are used to compare values < - less than == - Equality <= Less or equal to > Greater than >= Greater than or equal to != Not equal to

Logical operators AND operator (&&) – Applies when both operands/conditions are true. OR operator (||) – Applies when both or either condition is true. NOT operator (!) – Negates OR or AND operators. E.g. !&& If (rain==“yes” && temp<20) prinf (“Wear a Jacket”);

The if… elseif statement When a series of decisions are involved, we may have to use more than one if .. else statements. The general form for nested if…. elseif statement is; if(expression 1) { statement 1; /* Executes when the expression 1 is true */ } else if( expression 2) { statement 2; /* Executes when the expression 2 is true */ } else if( expression 3) { statement 3; /* Executes when the expression 3 is true */ } else { statement 4; /* executes when the none of the above condition is true */ }

Example Write a program to input employee name, hours worked and rate per hour then calculate gross pay = hours worked * rate per hour. Tax is charged based on gross pay as follows: Gross pay tax Over 100000 20% Between 50000 and 100000 10% Below 50000

Program code Design a flowchart and hence write a program prompts the user to enter the student’s marks and then it displays the grade corresponding to the marks as shown in the table Marks Grade 80 - 100 A 60 - 79 B 50 - 59 C 40 - 49 D - 39 Fail

Nesting if …. else Statements The general form for nested if…. else statement is; if (test-conditions-1) { if (test-conditions-2); statement-1 ; else statement - 2; } statement-x ; }

If the condition-1 is true, condition-2 is tested and if condition-2 is true then and statement-1 will be evaluated otherwise statement-2 will be executed if condition-2 is false. If condition-1 is false control is transferred to the statement-x.

Example If (gender==“female) {if (mean>=60) printf (“Admit student”); else printf (“don’t admit”);} Else printf (“Not admissible”);

Example A bank‟s policy is to a 2% bonus on the ending balance at the end of the year (31st December) irrespective of the balance, and a 5% bonus is also given to female account holders if the balance is more than 50,000.

main() if (sex is female) { if (balance > 50000) { bonus = 0.05 * balance; else bonus = 0.02 * balance; } else { bonus = 0.02 * balance; } balance = balance + bonus;

The Switch statement The switch statement selects from a number of alternatives. The switch statement has the following components.   The switch statement- It includes the variable to be tested in brackets. Braces { }- Used to indicate the start and end of the switch statement block. Case statement- Each case statement specifies a value to compare with the value specifies in the switch statement. Default – It is an optional statement included to indicate the message or statement to be executed if none of the case statements were matched.

Syntax switch (value) { case 1: first alternative statement; break; case 2: second alternative statement; break; case 3: last alternative statement; break; default: default statement; }

NB: Switch statement can only be used for ordinal data types such as character and integer data types. Float data types are not allowed as switch values.

Example Write a Program to input a number then display the number in words. (1 to 5 ). Write a program to input grade. If grade is A, it should display Excellent, grade B - Good, Grade C – Average and D- Below average.

# include < stdio.h > int main() { int num ; Printf (“Enter number”); Scanf (“%d”,& num ); Switch ( num ) { case 1: printf (“One”); break; case 2: printf (“Two”); break; case 3: printf (“Three”); break; case 4: printf (“Four”); break; case 5: printf (“Five”); break; default: printf (“Error”); } return 0; }

# include < stdio.h > int main() { int num ; Printf (“Enter number”); Scanf (“%d”,& num ); If ( num ==1) { printf (“One”);} If ( num ==2) { printf (“Two”);} If ( num ==3) { printf (“Three”);} If ( num ==4)} { printf (“Four”);} If ( num ==5) { printf (“Five”);} return 0; }

Write a program to input two numbers and a sign. Then perform calculations according to the sign entered as shown below. Sign Calculation + Add the two number - Subtract the two numbers * Multiply the two numbers / Divide the two numbers

# include < stdio.h > int main() { int x,y ; float ans ; char sign; Printf (“Enter number”); Scanf (“% d”,& x ); Printf (“Enter 2nd number ”); Scanf (“% d ”,& y ); Printf (“Enter sign”); Scanf (“% c”,&sign ); Switch (sign) { case ‘+’: ans = x+y ; break; case ‘-’: ans =x-y ; break; case ‘*’: ans =x*y ; break; case ‘/’: ans =x/y ; break; default: printf (“Error”); Printf ( “answer %f”, ans ); } return 0; }

Iteration/Loop control structure The purpose of loop statements is to repeat one or more statements a given number of times until certain conditions occur. A programming loop is one that forces the program to go back up again and thus you can execute lines of code repeatedly . This type of control statement is what makes computers so valuable. A computer can repeatedly execute the same instructions over-and-over again without getting bored with the repetition.

There are three kinds of loop statements in C. That is: while do…while for

for Loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated. Syntax : The syntax of a for loop is: for(initialization ; test-condition; increment) { Statements; } Note: the three sections in the for () statement must be separated by semicolons (;). There is no (;) after the increment section (x++)

Example Write a program to display numbers 10,11,12,13,14……..19. int main() { int x; for(x = 10; x < 20; x++) { printf (" value of x : %d " , x ); printf ("\ n"); } return 0; }

Use for control structure to: Write a program to display numbers 10,9,8,7…1. Write a program to enter employee name, hours worked and rate per hour then calculate gross salary of 4 employees.

while loop The while statement continually executes a block of statements while a particular expression/condition is true. Its syntax can be expressed as: while (expression) { statement(s) } NB: In while loop, the test is done at the start. i.e. test then execute .

The while statement evaluates expression , which must return a boolean value. If the expression evaluates to true, the while statement executes the statement (s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.

while flow chart While expression Statement(s) No Yes

counter A counter is an integer variable that counts the number of loops. It is initialized before the loop and incremented or decremented within the loop. It is used when dealing with predefined number of loops.

Examples Write a program to display the word “hallo” 10 times. Write a program to display the numbers 1,2,3,4,5,6,7,8. Write a program to display the numbers 2,4,6,8………12. Write a program to input student name, maths , english and kiswahili and calculate total and average marks of five students.

# include < stdio.h > i nt main() { int counter; counter = ; while(counter<=10) { printf (“ \ nHallo ”); counter++; } }

While (count<10) Display Hallo No Yes start Count=0 stop Count++

# include < stdio.h > Int main() { int counter; counter = 1 ; while(counter<=8) { printf (“%d”, counter); counter++; } }

# include < stdio.h > Int main() { int counter; counter = ; while(counter<=12) { printf (“%d”, counter); counter=counter +2; } }

# include < stdio.h > i nt main() { int counter; counter = 10; while(counter>=1) { printf (“% d”,counter ); printf (“\n”); counter--; } r eturn 0; }

#include < stdio.h > int main() { int count; int mat,eng,kis,tot ; float avg ; char sname [10]; count=0; while (count<5) { printf (“Enter student name”); scanf (“%s”,& sname ); printf (“Enter mathematics”); scanf (“% d”,&mat ); printf (“Enter English”); scanf (“%d ”,& eng ); printf (“Enter Kiswahili”); scanf (“%d ”,& kis ); tot= mat+eng+kis ; avg =tot/3; Printf (“Total is %d \ n”,tot ); Printf (“Average is %f \n”, avg ); Count ++; } return 0; }

do while Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming language checks its condition at the bottom of the loop. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Do…while is used when the body of the loop needs to be executed first before evaluating the test-condition . do { statement(s ) } while (expression );

# include < stdio.h > Int main() { int counter; counter = 10; do { printf (“% d”,counter ); printf (“\n”); counter=counter-1; } while(counter>=1 ); return 0; }
Tags