Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Similar documents
Introduction. C provides two styles of flow control:

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Module 4: Decision-making and forming loops

C++ Programming: From Problem Analysis to Program Design, Third Edition

REPETITION CONTROL STRUCTURE LOGO

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Decision Making -Branching. Class Incharge: S. Sasirekha

LECTURE 5 Control Structures Part 2

8. Control statements

Flow Control: Branches and loops

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Programming for Electrical and Computer Engineers. Loops

Chapter 2: Functions and Control Structures

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Fundamentals of Computer Programming Using C

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

OER on Loops in C Programming

Flow Control. CSC215 Lecture

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Information Science 1

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Chapter 4 C Program Control

LESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script.

Chapter 5: Control Structures

C++ Programming: From Problem Analysis to Program Design, Third Edition

Programming for Engineers Iteration

Unit 3 Decision making, Looping and Arrays

Why Is Repetition Needed?

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Information Science 1

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

CHAPTER 9 FLOW OF CONTROL

LOOPS. Repetition using the while statement

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CT 229 Java Syntax Continued

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

SELECTION STATEMENTS:

Theory of control structures

3 The L oop Control Structure

Chapter 3 Structured Program Development

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Branching is deciding what actions to take and Looping is deciding how many times to take a certain action.

Chapter 8 Statement-Level Control Structures

Accelerating Information Technology Innovation

Chapter 4 - Notes Control Structures I (Selection)

Short Version of Matlab Manual

Control Structures. Control Structures 3-1

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Computers Programming Course 7. Iulian Năstac

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Introduction to C/C++ Lecture 3 - Program Flow Control

Lecture 6. Statements

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

(Refer Slide Time: 00:26)

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

CHAPTER : 9 FLOW OF CONTROL

Computer Programming: C++

CS112 Lecture: Repetition Statements

DECISION CONTROL AND LOOPING STATEMENTS

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Chapter 4 C Program Control

C++ PROGRAMMING SKILLS Part 2 Programming Structures

CS 199 Computer Programming. Spring 2018 Lecture 5 Control Statements

Repetition, Looping CS101

CIS 3260 Intro to Programming in C#

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Chapter 4: Control Structures I (Selection)

LESSON 6 FLOW OF CONTROL

ENGR 1181 MATLAB 09: For Loops 2

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 8. Statement-Level Control Structures

Introduction to C Programming

Software Design & Programming I

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

MODULE 2: Branching and Looping

CHAPTER 5 FLOW OF CONTROL

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Control Structures in Java if-else and switch

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

5. Selection: If and Switch Controls

5. Control Statements

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Transcription:

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Decision Making and Branching C language possesses such decision-making capabilities by supporting the following statements : 1. if statement 2. switch statement 3. Conditional operator statement? 4. goto statement We shall discuss their features, capabilities and applications in more detail.

Decision Making with IF Statement The if statement is a powerful decision-making statement and is used to control the flow of execution of statements. It allows the computer to evaluate the expression first and then, depending on whether the value of the expression is true of false, it transfers the control to a particular statement.

Decision Making with IF Statement Some examples : 1. if (bank balance is zero) borrow money 2. if (room is dark) put on lights 3. if (code is 1) person is male 4. if (age is more than 55) person is retired

Decision Making with IF Statement The if statement may be implemented in different forms depending on the complexity of conditions to be tested. 1. Simple if statement 2. if.else statement 3. Nested if.else statement 4. else if ladder

Simple if Statement

Simple if Statement The general form of a simple if statement is If ( test expression ) { statement-block; } statement - x; If the test expression is true, the statement-block will be executed. Otherwise the statement-block will be skipped and the execution will jump to the statement-x.

Simple if Statement Fig. 5.3 Illustration of simple if statement

Simple if Statement Use of if for counting

Simple if Statement

The if.else Statement

The if.else Statement If the test expression is true, then the true-block statement(s), immediately following the if statements are executed. Otherwise, the false-block statement(s) are executed.

The if.else Statement Illustration of if...else statement

Nesting of if.else Statements

Nesting of if.else Statements When a series of decisions are involved, we may have to use more than one if else statement in nested form as shown below : If the condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 is true, the statement-1 will be evaluated; otherwise the statement-2 will be evaluated and then the control is transferred to the statement-x

Nesting of if.else Statements Selecting the largest of three numbers

Nesting of if.else Statements

The else if Ladder

The else if Ladder A multipath decision is a chain of ifs in which the statement associated with each else is an if. This construct is known as the else if ladder. As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statementx. When all the n conditions become false, then the final else containing the default-statement will be executed.

The else if Ladder Illustration of else..if ladder

The else if Ladder

The Switch Statement We have seen that when one of the many alternatives is to be selected, we can use an if statement to control the selection. C has a built-in multiway decision statement as a switch. The switch statement tests the value of a given variable against a list of case values and when a match is found, a block of statements associated with that case is executed. Note that case labels end with a colon (:).

The Switch Statement When the switch is executed, the value of the expression is successfully compared against the values value-1, value-2, If a case is found whose value matches with the value of the expression, then the block of statements that follows the case are executed. The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement. The default will be executed if the value of the expression does not match with any of the case values.

The Switch Statement

The Switch Statement

The?: Operator The conditional expression is evaluated first. If the result is nonzero, expression1 is evaluated and is returned as the value of the conditional expression. Otherwise, expression2 is evaluated and its values is returned. if (x < 0) flag = 0; else flag = 1; = flag = (x < 0)? 0 : 1;

The?: Operator Illustration of the conditional operator

The?: Operator

The Goto Statement C supports the goto statement to branch unconditionally from one point to another in the program. The goto requires a label in order to identify the place where the branch is to be made. A label is any valid variable name, and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred.

The Goto Statement The label: can be anywhere in the program either before or after the goto label; statement. During running of a program when a statement like goto ABbCd; is met, the flow of control will jump to the statement immediately following the label ABbCd:. This happens unconditionally.

The Goto Statement Use of the goto statement

The Goto Statement Another use of the goto statement is to transfer the control out of a loop (or nested loops) when certain peculiar conditions are encountered. We should try to avoid using goto as far as possible. But there is nothing wrong, if we use it to enhance the readability of the program or to improve the execution speed.

Just Remember

Decision Making and Looping We need to initialize and increment a counter and test its value at an appropriate place in the program for the completion of the loop. On such occasions where the exact number of repetitions are known, there are more convenient methods of looping in C. A program loop therefore consists of two segments, one known as the body of the loop and the other known as the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.

Decision Making and Looping Depending on the position of the control statement in the loop, a control structure may be classified either as the entrycontrolled loop or as the exit-controlled loop.

Decision Making and Looping A looping process, in general, would include the following four steps : 1. Setting and initialization of a condition variable. 2. Execution of the statements in the loop. 3. Test for a specified value of the condition variable for execution of the loop. 4. Incrementing or updating the condition variable. The C language provides for three constructs for performing loop operations. 1. The while statement. 2. The do statement. 3. The for statement.

Decision Making and Looping

The While Statement The simplest of all the looping structures in C is the while statement. The while is an entry-controlled loop statement. The test-condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body, the test-condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test-condition finally becomes false and the control is transferred out of the loop

The While Statement The body of the loop is executed 10 times for n = 1, 2,,10, each time adding the square of the value of n, which is incremented inside the loop. The test condition may also be written as n < 11; the result would be the same. The variable n is called counter or control variable.

The While Statement Program to compute x to the power n using while loop

The Do Statement On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the test-condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement.

The Do Statement Printing of a multiplication table using do...while loop

The For Statement Simple for Loops The execution of the for statement is as follows : 1. Initialization of the control variables is done first, using assignment statements such as i = 1 and count = 0. 2. The value of the control variable is tested using the test-condition. The test-condition is a relational expression, such as i < 10 that determines when the loop will exit. If the condition is true, the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.

The For Statement 3. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now, the control variable is incremented using an assignment statement such as i = i + 1 and the new value of the control variable is again tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is again executed. This process continues till the value of the control variable fails to satisfy the testcondition.

The For Statement This for loop is executed 10 times and prints the digits 0 to 9 in one line. The three sections enclosed within parentheses must be separated by semicolons Note that there is no semicolon at the end of the increment section, x = x + 1.

The For Statement One of the important points about the for loop is that all the three actions, namely initialization, testing, and incrementing, are placed in the for statement itself, thus making them visible to the programmers and users, in one place. The for statement and its equivalent of while and do statements are shown

The For Statement Additional Features of for Loop The for loop in C has several capabilities that are not found in other loop constructs. For example can be rewritten as p = 1; for (n = 0 ; n < 17 ; ++n) for (p = 1, n = 0 ; n < 17 ; ++n)

The For Statement Like the initialization section, the increment section may also have more than one part. For example is perfectly valid. The multiple arguments in the increment section are separated by commas.

The For Statement The third feature is that the test-condition may have any compound relation and the testing need not be limited only to the loop variable. For example The loop uses a compound test condition with the counter variable i and sentinel variable sum. The loop is executed as long as both the conditions i < 20 and sum < 100 are true. The sum is evaluated inside the loop.

Nesting of for Loop The For Statement The nesting may continue up to any desired level. The loops should be properly indented so as to enable the reader to easily determine which statements are contained within each for statement.

The For Statement Illustration of nested for loops

The For Statement

Jumps in Loops Loops perform a set of operations repeatedly until the control variable fails to satisfy the test-condition Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to leave the loop as soon as a certain condition occurs. For example, consider the case of searching for a particular name in a list containing, say, 100names. A program loop written for reading and testing the names 100 times must be terminated as soon as the desired name is found.

Jumping Out of a Loop Jumps in Loops When a break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop. When the loops are nested, the break would only exit from the loop containing it. That is, the break will exit only a single loop. Since a goto statement can transfer the control to any place in a program, it is useful to provide branching within a loop. Another important use of goto is to exit from deeply nested loops when an error occurs.

Jumps in Loops Exiting a loop with break statement

Jumps in Loops Jumping within and exiting from the loops with goto statement

Jumps in Loops Use of break in a program

Jumps in Loops Use of goto to exit from a loop

Jumps in Loops Skipping a Part of a Loop During the loop operations, it may be necessary to skip a part of the body of the loop under certain condition. Like the break statement, C supports another similar statement called the continue statement. However, unlike the break which causes the loop to be terminated, the continue, as the name implies, causes the loop to be continued with the next iteration after skipping any statements in between. The continue statement tells the compiler, SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH THE NET ITERATION.

Jumps in Loops In while and do loops, continue causes the control to go directly to the test-condition and then to continue the iteration process. In the case of for loop, the increment section of the loop is executed before the test-condition is evaluated. Bypassing and continuing in loops

Jumps in Loops Use of continue statement

Avoiding goto Jumps in Loops When goto is used, many compilers generate a less efficient code. In addition, using many of them makes a program logic complicated and renders the program unreadable. It is possible to avoid using goto by careful program design. In case any goto is absolutely necessary, it should be documented. The goto jumps shown

Jumps in Loops Jumping out of the Program We can jump out of a program by using the library function exit(). In case, due to some reason, we wish to break out of a program and return to the operating system, we can use the exit() function. if (test-condition) exit (0) ; The exit() function take an integer value as its argument. Normally zero is used to indicate normal termination and a nonzero value to indicate termination due to some error or abnormal condition. The use of exit() function requires the inclusion of the header file <stdlib.h>.

Concise Test Expressions We often use test expressions in the if, for, while and do statements that are evaluated and compared with zero for making branching decisions. Since every integer expression has a true/false value, we need not make explicit comparisons with zero. Applying! operator, we can write concise test expressions without using any relational operators. if (expression == 0) is equivalent to if (!expression) Similarly, if (expression! = 0) is equivalent to if (expression)

Just Remember

Just Remember

Assignment Program to print Power of 2 table LOOPS (while, do, for)

Try to implement programs by yourself CASE STUDIES FOR MORE PRACTICE

Case Studies Calculation of range of values

Case Studies Pay-bill calculations

Pay-bill calculations

Pay-bill calculations

Case Studies Program to print binomial coefficient table

Case Studies Program to draw a histogram

Case Studies Program of minimum cost problem

Case Studies Plotting of two functions

Case Studies Plotting of two functions

Case Studies Plotting of two functions