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

Similar documents
Flow Control. CSC215 Lecture

n Group of statements that are executed repeatedly while some condition remains true

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Introduction. C provides two styles of flow control:

REPETITION CONTROL STRUCTURE LOGO

Chapter 5: Control Structures

Lecture 6. Statements

Dept. of CSE, IIT KGP

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

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

Module 4: Decision-making and forming loops

Structured Program Development

Chapter 4. Flow of Control

Structured Programming. Dr. Mohamed Khedr Lecture 9

Programming for Electrical and Computer Engineers. Loops

Unit 3 Decision making, Looping and Arrays

Introduction to C Programming

MODULE 2: Branching and Looping

COMP 208 Computers in Engineering

3 The L oop Control Structure

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

Computers Programming Course 7. Iulian Năstac

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

Chapter 3 Structured Program Development

Lecture 7 Tao Wang 1

Decision Making -Branching. Class Incharge: S. Sasirekha

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur

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

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

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

Information Science 1

Problem Solving and 'C' Programming

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 10. Daily Puzzle

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

15 FUNCTIONS IN C 15.1 INTRODUCTION

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

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

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

Programming for Engineers Iteration

DECISION CONTROL AND LOOPING STATEMENTS

Control structures in C. Going beyond sequential

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE

Chapter 4 C Program Control

Information Science 1

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

Theory of control structures

C++ PROGRAMMING SKILLS Part 2 Programming Structures

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

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

Control Statements. If Statement if statement tests a particular condition

Chapter 13 Control Structures

Fundamentals of Computer Programming Using C

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

SELECTION STATEMENTS:

Fundamental of Programming (C)

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

Repetition Structures II

C: How to Program. Week /Mar/05

بسم اهلل الرمحن الرحيم

Fundamentals of Programming. Lecture 6: Structured Development (part one)

Repetition Structures

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

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

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

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

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Structured Program Development in C

LECTURE 5 Control Structures Part 2

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

Other Loop Options EXAMPLE

Chapter 2 - Introduction to C Programming

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

Loops / Repetition Statements

STUDENT LESSON A12 Iterations

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

Chapter 13. Control Structures

Day06 A. Young W. Lim Wed. Young W. Lim Day06 A Wed 1 / 26

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

The following expression causes a divide by zero error:

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

Decision making with if Statement : - Control Statements. Introduction: -

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Informatics Ingeniería en Electrónica y Automática Industrial. Control flow

5. Selection: If and Switch Controls

ECE 2400 Computer Systems Programming Fall 2018 Topic 1: Introduction to C

5. Control Statements

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Fundamental of Programming (C)

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

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

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Comments. Comments: /* This is a comment */

Fundamentals of Programming Session 9

Transcription:

Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate for very simple programs. There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions. For example, we might want to execute a group of statements only if a particular condition is true, and skip them otherwise. Or, we might want to execute a group of statements again and again. The C language provides statements, which we call control-flow statements, that specify the order of execution of statements in the program.

Objectives: at the end of this module, the student should be able to: 1. explain the purposes of the sequence, selection and iteration control-flow structures; 2. use the if and switch statements; 3. use the while, do-while, and for statements; 4. differentiate the various selection and iteration statements from each other.

- the order in which statements are executed in a program. 3 Types of Control Flow Structures: 1. Sequence 2. Selection 3. Iteration

Sequence control refers mainly to the sequential execution of statements. This type of control corresponds to the following flowchart: Statement 1 Statement 2 Statement 3 Figure 4.1 Sequence Control Flow

Translated into a C program, the statements are ordered successively, statement1; statement2; statement3; As you can see, we have used this type of control flow in all the sample programs that we discussed in the previous module.

Selection control allows the program to choose which statement to execute next based on some condition. C provides two such statements to achieve this: 1. the if-else statement and 2. the switch statement.

The if-else statement functions the same way as the diamond symbol does in flowcharts. It evaluates an expression (or condition) and chooses the next statement to perform based on the truth value of the expression. The format of the if-else statement is if (expression) statement1; else statement2; where the else part is optional.

The if-else statement is equivalent to the following flowchart: true expression false Statement 1 Statement 2 Fig 4.2 Flowchart for If-else statement

The if-else statement first evaluates expression. If it is true, statement1 is executed. Otherwise, statement2 is executed. Notice that statement2 is not executed when expression is true, and statement1 is not executed when expression is false.

#include <stdio.h> int x; main() { printf( Input an integer : ); /*prompt*/ scanf( %d, &x); /*read input, store in x*/ if (x < 0) { /*evaluate expression*/ printf( negative number\n ); } else { printf( nonnegative number\n ); } } we used the if-else statement to control which printf statement to execute.

Recall: we said the else part of the If-else statement is optional. So, we can write the statement as: if (expression) statement1; In this case, expression is evaluated and if it s true, statement1 is executed. Otherwise, nothing is executed and the program merely proceeds to the next statement in the program.

The If statement is equivalent to the following flowchart: true expression false Statement 1 Fig 4.3 Flowchart of If statement So, if we omit the else part in our previous example, no message is outputted when the input value is greater than or equal to zero (that is, x >= 0).

if (expression) { statement1a; statement2a; statementna; } else { statement1b; statement2b;. statementmb; }

true expression false Statement 1a Statement 1b Statement 2a Statement 2b Statement Na Statement Mb Fig. 4.4 If-else with compound statements

The group of statements enclosed in braces is called a compound statement. In C, a compound statement can always take the place of a single statement. So in the if-else statement if (expression) statement1; else statement2; we can put a compound statement in place of statement1. The same is true for statement2.

This results to if-else statements that have the following structures: if (expression) statement1; else { statement; statement; statement; } if (expression) { statement; statement; statement; } else statement2;

below is a program code which has a compound statement: if (b == 0) printf( c is undefined\n ); else { c = a/b; printf( c = %d\n, c); }

The braces and the statements may be placed differently as long as their sequence is not altered. It can be equally written as if (b == 0) printf( c is undefined\n ); else { c = a/b; printf( c = %d\n, c); }

In the program, a compound statement is placed in the else part. If expression (b==0) is true, the statement printf( c is undefined\n ); is executed. Otherwise, statements c = a/b; and printf( c = %d\n, c); are executed instead.

Let s take a look again at the format of the ifelse statement: if (expression) statement1; else statement2; Actually, it s possible for statement1 (or statement2) to be another if-else statement. In such a case, an if-else statement is specified within another if-else statement.

if (x!= 0) if (y!= 0) { a = x/y; z = a + b; } else z = LONG_MAX; else z = b;

In the program above, the statements a = x/y; and z = a + b; are executed only if expressions (x!= 0) and (y!= 0) are both true. If (x!= 0) is true but (y!= 0) is false, the statement z = LONG_MAX; is executed instead. As we mentioned earlier, the else part is optional. Omitting the else part of the inner if-else statement, however, can result to ambiguity because there will be more if s than else s, and the else part can possibly be meant to belong to any one of the if s. The C compiler resolves this ambiguity by associating the else with the closest previous else-less if.

The nesting of the if-else statements can be extended to several levels. For example, if (expression1) if (expression2) { if (expression3) if (expression4) statement1; else statement2; } else statement3; else statement4; has the if-else statements nested up to four levels. Note how the braces are placed. In this program, statement1 is executed only if all four expressions are true.

The if-else statement provides a two-way decision the next statement is chosen between two alternatives. The switch statement, on the other hand, provides a multi-way decision. The next statement is chosen among several alternatives.

format of the switch statement is switch (expr) { case const1: statement1a; statement1b; case const2: statement2a; case const3: statement3a; default: statement4a; }

expr is an expression of type integer, and const1, const2 and const3 are constant integer values (that is, not variables). The expression is evaluated and compared to several constant integer values. When a match is found, the program starts execution at the corresponding statement. By the way, the default part is optional and may be omitted. The switch statement is best understood by looking at its equivalent flowchart shown in Figure 4.5.

expr=const 1? T F Statement 1a; Fig. 4.5 Flowchart for Switch Statement expr=const 2? T Statement 1b; F Statement 2a; expr=const 3? T F Statement 3a; Statement 4a;

char ch; float grade; switch (ch) { case A : grade = 4.0; break; case B : grade = 3.0; break; case C : grade = 2.0; break; case D : grade = 1.0; break; default: grade = 0.0; } grade is assigned the value 4.0 when ch is A, 3.0 when ch is B, 2.0 when ch is C, 1.0 when ch is D, and 0.0 otherwise. Now, what do you think would happen if we remove all the break statements? grade will be 0.0 no matter what ch is, because the last statement always gets executed.

Iteration - refers to the repeated execution of program statement. - often referred to as loops. C provides three statements to perform iteration: 1) the while statement, 2) the do-while statement, and 3) the for statement.

The while statement has the format: while (expression) statement; It repeatedly executes statement while expression is true. It is equivalent to the flowchart in Figure 4.6.

expression F T Statement 1a; Fig. 4.6 Flowchart for While Statement

The expression is first evaluated. If true, statement is executed and expression is reevaluated. statement is repeatedly executed until expression becomes false, which causes the loop to exit. In the while loop, statement can be a compound statement. Thus we have while (expression) { statement; statement; } which executes several statements repeatedly.

int n; n = 0; while (n < 5) { printf( %d\n, n); n++; } gives the output 0 1 2 3 4 A loop that does not terminate is called an infinite loop.

Another example: char ch; printf( continue? (y/n) ); scanf( %c, &ch); while (ch!= n ) { printf( continue? (y/n) ); scanf( %c, &ch); } Can you tell what it does? It keeps on prompting for a character input and it terminates when character y is inputted. When run, the output might look like continue? (y/n) y continue? (y/n) y continue? (y/n) n

The do-while statement is quite similar to the while statement. Both continue to iterate as long as an expression is true. The format of do-while is do statement; while (expression); where statement is repeatedly executed while expression is true.

The difference between the do-while statement and the while statement is that in do-while, expression is evaluated after executing statement. In while, expression is evaluated first before executing statement. This means that in do-while, statement is executed at least once, while in while, statement may not be executed at all.

n = 0; do { printf( %d\n, n); n++; } while (N < 5); The do-while version of the prompting program previously given is char ch; do { printf( continue? (y/n) ); scanf( %c, &ch); } while (ch!= n )

Another loop C provides is the for loop. But it has a much different structure than the while and do-while statements. Its format is: for (init; cond; incr) statement; init, cond and incr stands for initialization, condition, and increment, respectively.

The for statement above is equivalent to init; while (cond) { statement; incr; } init is first executed and then cond is evaluated. If it is true, statement is executed, followed by incr. Then, cond is again evaluated. The loop exits when cond becomes false.

Thus, given a while statement, the equivalent for statement can be easily obtained by identifying which is init, cond, statement and incr. While statement: n = 0; /* init */ while (n < 5) { /* cond */ printf( %d\n, n); /* statement */ n++; /* incr */ }

This can be directly transformed into a for loop that does the same thing output numbers 0 to 4. The for loop is obtained by simply plugging in the components that we identified above. The equivalent for loop: for (n = 0; n < 5; n++) printf( %d\n, n); Init and incr may consist of several statements separated by commas. For example, for (n = 0, m = 1; n < 5; n++, m++) printf( %d\n, m+n); has two statements (n = 0; and m = 1;) in the initialization part and two statements (n++; and m++;) in the increment part.

The initialization, condition and increment parts may be omitted, although the semicolons separating these parts must remain. If init and incr are omitted, no initialization and increment is done. If cond is omitted, it is taken as permanently true. Thus, for (n = 0; ;n++ ) printf( %d\n, n); outputs the numbers 0, 1, 2, 3, 4, until infinity

C provides two statements that are sometimes used to control the execution of loops. These are: 1) break statements. 2) continue statements. The break statement causes an immediate exit from the loop.

For example, consider again the while loop that outputs integers 0 to 4: int n; n = 0; while (n < 5) { printf( %d\n, n); n++; } For illustration purposes, let s insert an if statement that executes break, such that:

int n; n = 0; while (n < 5) { if (n == 3) break; printf( %d\n, n); n++; } This causes the loop to exit (or terminate) when n is 3. As a result, the loop only outputs integers 0 to 2.

The continue statement, is used to skip an iteration (that is, to ignore executing the rest of the loop). For example, suppose that we replace the break statement above with a compound statement that executes continue: int n; n = 0; while (n < 5) { if (n == 3) { n++; continue; } printf( %d\n, n); n++; }

When n is 3, it is incremented and then the continue statement causes the program control to ignore the rest of the loop (the printf and n++) and jump back to test the loop condition (n < 5). This means that 3 is not outputted since the printf statement is ignored when n is 3. The output of the program is thus: 0 1 2 4

Let s have a more useful example. Suppose that we would like to prompt the user to enter a sequence of positive integers. We can design the program such that it ignores negative values and it stops reading input when a zero is entered.

int x, sum = 0; printf( input a sequence of positive integers: ); while (sum == sum) { scanf( %d, &x); if (x == 0) break; if (x < 0) continue; sum = sum + x; } printf( sum of positive integers = %d\n, sum);

The loop condition (sum == sum) is always true since sum is always equal to itself. Inside the loop, scanf reads an integer and stores it in x. If x is 0, the loop immediately exits. If it s a negative integer, the rest of the loop is ignored (the negative value is not added to sum) and the next number is read. The loop continues until a zero value causes it to exit. Note that even though the loop condition is always true, it s not an infinite loop because of the break statement inside.

Control-flow structures are statements that determine the order of execution of statements in a program. In C, control-flow structures are of three types: sequence, selection, and iteration. Sequence control is what is normally followed when statements are written sequentially. Selection control provides a way to select the next statement among a number of alternatives. The if-else and switch statements are used for this type of control-flow. Iteration control refers to the repetitive execution of statements. There are three C statements that provide iteration: the while statement, the do-while statement, and the for statement.