1 Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Flow Control if, while, do-while Juan Marquez (03_flow_control.ppt)
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
1 Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps.
CS1061: C Programming Lecture 8: Repetition A. O’Riordan, 2004.
CSC 200 Lecture 4 Matt Kayala 1/30/06. Learning Objectives Boolean Expressions –Building, Evaluating & Precedence Rules Branching Mechanisms –if-else.
C++ for Engineers and Scientists Third Edition
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
UNIT II Decision Making And Branching Decision Making And Looping
L EC. 03: C ONTROL STATEMENTS Fall Java Programming.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 C++ Control Statements ~ Selection and Iteration.
Chapter 4 Program Control Statements
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Introduction to Computer Algorithmics and Programming Ceng 113 Program Control Statements.
CPS120: Introduction to Computer Science Decision Making in Programs.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Chapter 5: Structured Programming
Conditional Statement Chapter 8. Conditional Statements Are statements that check an expression then may or may not execute a statement or group of statement.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
IT CS 200: C ONDITION Lect. Napat Amphaiphan. T HE ABILITY TO CONTROL THE FLOW OF YOUR PROGRAM, LETTING IT MAKE DECISIONS ON WHAT CODE TO EXECUTE 2.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Dr. Sajib Datta Jan 23,  A precedence for each operator ◦ Multiplication and division have a higher precedence than addition and subtraction.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Dr. Sajib Datta Sep 3,  A new operator used in C is modulus operator: %  % only used for integers, not floating-point  Gives the integer.
Decision Making in C.
REPETITION CONTROL STRUCTURE
Flow of Control True and False in C Conditional Execution Iteration
C Program Controls + Flow Structure
CS1010 Programming Methodology
Condition Statements.
Control Structures Lecture 7.
Looping.
Arrays, For loop While loop Do while loop
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Control Structures Lecture 6.
ECE 103 Engineering Programming Chapter 18 Iteration
Flow of Control.
CSC215 Lecture Control Flow.
Presentation transcript:

1 Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps

2 True and False in C False is represented by any zero value. –The int expression having the value 0. –The floating expression having the value 0.0. –The null character ‘\0’. –The NULL pointer (for pointer see chap. 8). True is represented by any nonzero value. An logical expression, such as a<b, is either true or false. –This expression yields the int value 1 if it is true or the int value 0 if it is false.

3 Examples int i=1, j=2, k=3; double x=5.5, y=7.7, z=0.0; i<j-ki<(j-k)0 -i+5*j>=k+1((-i)+(5*j))>=(k+1)1 x-y<=j-k-1 (x-y)<=((j-k)-1)1 x+k+7<y/k ((x+k)+7)<(y/k)0 i!=j1 !!5 !(!5)1 !i-j+4 ((!i)-j)+4 2 x||i&&j-2 x||(i&&(j-2))1

4 Selection if switch

5 if statement Conditional execution: if (Boolean expression) statement; else statement; Where a statement may consist of a single statement, a code block, or empty statement. The else clause is optional.

6 if – logic:if (Boolean Expression) statement_1; If-else-logic: if (Boolean Expression){ compound_1 } else{ compound_2 }; Conditional execution allows you write code that reacts to tested conditions. No Semi-colon Yes- For a Semi-colon

7 Example #include int main ( ) { double salary, payrate; int hours, union; printf (“Please enter hours worked, payrate,\ and union status”);

8 printf (“Enter 1 if a union member, 0 if not”); scanf (“%d%lf%d”, &hours, &payrate, &union); if (hours > 40 && union = = 1) salary = (40 * payrate) + ((1.5 * payrate) * (hours - 40)); else salary = payrate * hours; printf (“Salary is: $ % 6.2 f”, salary); }

9 Nested ifs Nested:One statement coded within another statement. Nested ifs:An nested if is an if that is the target of another if or else. Why Nested ifs?A simple - if and if - else statement are used to handle 2-choice tasks. Nested ifs:Needed to handle tasks where we have 3 or More options that are mutually exclusive. ANSI C specifies that at least 15 levels of nesting must be supported by the compiler.

10 The if-else-if ladder General form: if (expression) statement; else if (expression) statement; else if (expression) statement;... else statement;

11 The conditions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed and the rest of the ladder is bypassed. If none of the conditions are true, the final else is executed. That is, if all other conditional tests fail, the last else statement is performed. If the final else is not present, no action takes place if all other conditions are false.

12 E.g. You are a salesperson for the Widget Manufacturing Co. You will earn a salary bonus according to the following rules: Sales > = $50,000earn $5,000 Sales > = $100,000 earn $15,000 Sales > = $150,000earn $30,000 Example

13 double sales, bonus; printf (“please enter total sales”); scanf (“%lf”, &sales); if (sales < 50000) bonus = 0; else if (sales < ) bonus = 5000; else if (sales < ) bonus = 15000; else bonus = 30000;

14 In a nested if, an else always refers to the nearest if that is within the same block as the else and that is not already associated with an else. if(i) { if(j) dosomething1(); if(k) dosomething2(); /* this if */ else dosomething3(); /* is associated with this else */ } else dosomething4(); /* associated with if(i) */

15 Conditional Expression The expressions must simply evaluate to either a true or false (zero or nonzero) value. The expressions are not restricted to involving the relational and logical operators.

16 x = 10; y = x>9 ? 100 : 200; x = 10; if(x>9) y = 100; else y = 200; The ?: Alternative Exp1 ? Exp2: Exp3

17 #include int f1(int n); int f2(void); int main(void) { int t; printf("Enter a number: "); scanf("%d", &t); t ? f1(t) + f2() : printf("zero entered."); printf("\n"); return 0; }

18 /* Divide the first number by the second. */ #include int main(void) { int a, b; printf("Enter two numbers: "); scanf(''%d%d", &a, &b); if(b) printf("%d\n", a/b); else printf("Cannot divide by zero.\n"); return 0; } if(b != 0) printf("%d\n", a/b);

19 switch statement switch is a multiple-branch selection statement, which successively tests the value of an expression against a list of integer or character constants (floating point expression, for example, are not allowed). When a match is found, the statements associated with that constant are executed.

20 General Form switch (expression) { case constant1: statement sequence break; case constant2: statement sequence break;.. default statement sequence } //ANSI C allowed at least 257 case statements.

21 Execution The value of the expression is tested against the constants specified in the case statements in a top-down order.. When a match is found, the statement sequence associated with that case is executed until the break statement or the end of the switch statement is reached. When break is encountered in a switch, program execution "jumps" to the line of code following the switch statement. The default statement is executed if no matches are found. The default is optional.

22 The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of relational or logical expression. No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch may have case constants that are in common. If character constants are used in the switch statement, they are automatically converted to integers (as is specified by C's type conversion rules).

23 The switch statement is often used to process keyboard commands, such as menu selection. The following function will when called: display the options, allow the user to make a selection, and then evoke the appropriate function to perform the task selected. void menu(void) { char ch; printf("1. Check Spelling\n"); printf(''2. Correct Spelling Errors\n"); printf("3. Display Spelling Errors\n"); printf("Strike Any Other Key to Skip\n"); printf(" Enter your choice: "); ch = getchar(); /* read the selection from the keyboard */

24 switch(ch) { case '1': check_spelling (); break; case '2': correct_errors (); break; case '3': display_errors (); break; default : printf("No option selected"); } }

25 int flag, k; /* Assume k is initialized */ flag = -1; switch(k) { case 1: /* These cases have common */ case 2: /* statement sequences. */ case 3: flag = 0; break; case 4: flag = 1; case 5: error(flag); break; default: process(k); } The break inside the switch is optional. If the break is omitted, execution will continue on into the next case until either a break or the end of the switch is reached.

26 Nested Switch You can have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and the outer switch contain common values, no conflict arise.

27 switch(x) { case 1: switch(y) { case 0: printf(''Divide by zero error.\n"); break; case 1: process(x, y); break; } break; case 2: ….

28 Iteration Iteration statements (also called loops) allow a set of instructions to be repeatedly executed until a certain condition is reached. This condition may be predetermined (as in the for and while loop) or open ended (as do-while loops).

29 for loop General form for (initialization; testing; increment) Loop Body; The initialization is an assignment statement that is used to set the loop control variable. The testing is a relational expression that determines when the loop exits. The increment defines how the loop control variable changes each time the loop is repeated.

30 Execution The for loop continues to execute as long as the condition is true. Once the condition becomes false, program execution resumes on the statement following the body of the for loop.

31 #include int main(void) { int x; for(x=1; x <= 100; x++) printf("%d ", x); return 0; } for(x=100; x != 65; x -= 5) { z = x*x; printf(''The square of %d, %d", x, z); }

32 The Elements of the For-loop The initialization, testing and incrementation can be any valid C expression. for (x=0; Ajax>Manchester; Ajax=Q*7/i) Common use as a counting loop. for (count=0; count <n; count=count+1)

33 Pieces of the loop definition need not be there. The incrementation of the loop control variable can occur outside the for statement. for(x=0; x != 123; ) scanf("%d", &x); for( x=1 ; x < 10; ) { printf("%d", x); ++x; }

34 The Infinite Loop Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. for( ; ; ) printf("This loop will run forever.\n"); for( ; ; ) { ch = getchar(); /* get a character */ if(ch == 'A') break; /* exit the loop */ } printf("you typed an A"); Terminate the infinite loop

35 For Loops With No Bodies A loop body may be empty. This fact is used to simplify the coding of certain algorithms and to create time delay loops. Does what? for(t=0; t < SOME_VALUE; t++) ;

36 Declaring Variables within a For Loop A variable so declared has its scope limited to the block of code controlled by that statement. /* i is local to for loop; j is known outside loop.*/ int j; for(int i = 0; i<10; i++) j = i * i; i = 10; /*** Error ***-- i not known here! */

37 While Loop General form: while(condition) statement; Execution: –Check the test condition at the top of the loop. –The loop iterates while the condition is true. –When the condition becomes false, program control passes to the line of code immediately following the loop.

38 Example char wait_for_char(void) { char ch; ch = '\0'; /* initialize ch */ while(ch != 'A') ch = getchar(); return ch; } while((ch=getchar()) != 'A') ;

39 Example 2: void func1() { int working; working = 1; /* i.e., true */ while (working) { working = process1(); if (working) working = process2(); if (working) working = process3(); } }

40 For loop Vs While Loop A-(Assignment), T-(testing), I-(Increment) for (A; T; I) { Body; } A; While (T) { Body; I; }