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

Similar documents
Flow Control. CSC215 Lecture

Introduction. C provides two styles of flow control:

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

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

Programming for Electrical and Computer Engineers. Loops

MODULE 2: Branching and Looping

COMP 208 Computers in Engineering

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

Subject: PIC Chapter 2.

Module 4: Decision-making and forming loops

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

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

REPETITION CONTROL STRUCTURE LOGO

DECISION CONTROL AND LOOPING STATEMENTS

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

Lecture 6. Statements

Decision Making -Branching. Class Incharge: S. Sasirekha

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

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

Computer Programming. Decision Making (2) Loops

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

Dept. of CSE, IIT KGP

8. Control statements

The following expression causes a divide by zero error:

Introduction to Computing Lecture 07: Repetition and Loop Statements (Part II)

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

Chapter 4. Flow of Control

Problem Solving and 'C' Programming

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

3 The L oop Control Structure

Chapter 13 Control Structures

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Control Statements. If Statement if statement tests a particular condition

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

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

A control structure refers to the way in which the Programmer specifies the order of executing the statements

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

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

Computers Programming Course 7. Iulian Năstac

Crude Video Game Simulator Algorithm

Week 2 / Lecture 2 15 March 2017 NWEN 241 Control constructs, Functions. Alvin Valera

Conditional Expressions

Chapter 3 Structured Program Development

M1-R4: Programing and Problem Solving using C (JAN 2019)

Learning to Program with Haiku

C: How to Program. Week /Mar/05

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

Engineering 12 - Spring, 1998

CS1100 Introduction to Programming

Chapter 13. Control Structures

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

Control structures in C. Going beyond sequential

Repetition Structures II

Chapter 13 Control Structures

C Programming Lecture V

CHAPTER 9 FLOW OF CONTROL

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

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

Introduction. Pretest and Posttest Loops. Basic Loop Structures ว ทยาการคอมพ วเตอร เบ องต น Fundamentals of Computer Science

Control Structures. Chapter 13 Control Structures. Example If Statements. ! Conditional. if (condition) action;

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Chapter 5: Control Structures

Lecture 7: General Loops (Chapter 7)

Unit 3 Decision making, Looping and Arrays

Control Structures in Java if-else and switch

Theory of control structures

SELECTION STATEMENTS:

Example: Monte Carlo Simulation 1

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

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

Tail recursion. Decision. Assignment. Iteration

Loops / Repetition Statements

Name Roll No. Section

Control Structures in Java if-else and switch

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

Copy: IF THE PROGRAM or OUTPUT is Copied, then both will have grade zero.

Chapter 9: Functions. Chapter 9. Functions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

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

switch-case Statements

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Other operators. Some times a simple comparison is not enough to determine if our criteria has been met.

Fundamentals of Computer Programming Using C

CS50 Supersection (for those less comfortable)

Programming Language A

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

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

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Coding Tutorial. Derrick Hasterok. February 1, 2005

Part I Part 1 Expressions

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements

UIC. C Programming Primer. Bharathidasan University

Iosif Ignat, Marius Joldoș Laboratory Guide 4. Statements. STATEMENTS in C

The four laws of programs

Lecture 5: C programming

Slides adopted from T. Ferguson Spring 2016

Principles of Computer Science

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Transcription:

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

Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement The switch-case Conditional Statement The (exp)? x:y Conditional Expression Iteration or Loop Statements The while Loop Statement The do-while Loop Statement The for Loop Statement Jump Statements: break, continue, and goto Example: Primality Testing Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 2

Examples of Statements Every program in C is a sequence of compiler directives, declarations, and statements. There are six kinds of statements in C: expression statement, compound statement, conditional statement, iteration (loop) statement, labeled statement, and jump statement. So far, we have seen just one of these --- the expression statement. An expression statement is just an expression followed by ; for example: x = a+b; x++; a+b; ; Here is one more kind of statements --- the compound statement also called a block. A compound statement is any sequence of statements and declarations enclosed in... for example: t = x; x = y; y = t; int main() bool drunk = True; if(!drunk) printf("can drive!\n"); a = x++; if (a == x) printf("wow?"); return 1; Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 3

Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement The switch-case Conditional Statement The (exp)? x:y Conditional Expression Iteration or Loop Statements hyperlink The while Loop Statement The do-while Loop Statement The for Loop Statement Jump Statements: break, continue, and goto Example: Primality Testing Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 4

The if Conditional Statement expression 0 statement 0 The syntax of the if conditional statement is as follows: if (expression) statement If the logical value of the expression is True the statement is executed. If the logical value of the expression is False the statement is skipped, and the program flow continues with the next statement. In most cases, but not always, the statement is a compound statement. Example: if (b*b < 4*a*c) printf("quadratic equation has no real roots!"); return 1; Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 5

The if-else Conditional Statement 0 expression 0 The syntax of the if-else conditional statement is as follows: if (expression) statement1 else statement2 st1 st2 If the logical value of the expression is True statement1 is executed, then statement2 is skipped and the program flow continues. If the logical value of the expression is False statement2 is executed, then statement1 is skipped and the program flow continues. Example: if (tomorrow_is_rainy == y ) printf("take your umbrella.\n"); else printf("leave the umbrella at home.\n"); Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 6

Nested if-else Statements What does the following statement do? if (a==1) if (b==2) if (b==2) a printf("***"); printf("***"); =1 1 b else else printf("###"); printf("###"); 2 *** ### The rule is this: the else always belongs to the last else-less if. 2 ### ### if (a==1) if (b==2) printf("***"); else printf("###"); Nevertheless, the rule can be modified by explicitly creating a single compound statement enclosed in... for example like this: Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 7

Multi-way if-else-if Chains The best way to explain this is by using an example: if (a < 0) return -1; else if (a == 0) return 0; else if (a < 11) return 1; else return a; False False a < 11 False a == 0 True a < 0 True 0 True -1-1 1 a 1 0 a 10 a Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 8

Indentation for if-else-if Chain Proper indentation is extremely useful in elucidating the structure of an if-else-if chain, like this: if (a < 0) return -1; else if (a == 0) return 0; else if (a < 11) return 1; else return a; if (a < 0) return -1; else if (a == 0) return 0; else if (a < 11) return 1; else return a; Both indentation methods are well-established. The second one results in a more compact code, with shorter lines. Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 9

The switch-case Statement The syntax of the switch-case-default conditional statement is as follows: switch (expression) case value1: statements Integer type Integer constant break; case value2: statements break;... // optional // optional default: statements // optional The value of the expression is compared to value1, value2, and so on sequentially until there is a match. If there is no match, default is executed. If there is also no default case, nothing is executed. If there is a match, execution starts at this case and goes on until either a break or the closing brace is encountered. Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 10

Calculator Program Using switch int x, y; char op;... // read x, y, op switch (op) case '+': printf("result is: %d", x + y); break; //what if we remove it? case '-': printf("result is: %d", x - y); break;... // code for '*' and '/' and '%' default: printf("invalid operation!"); Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 11

Conditional Expression (exp)? x:y Expressions in C can involve the ternary conditional operator. The syntax of this operator?: is as follows: expression1? expression2 : expression3 If the logical value of expression1 is True, expression2 is evaluated. If the logical value of expression1 is False, expression3 is evaluated. The conditional expression?: is not a statement; thus it can appear as part of another expression. For example: if (n > 1) c = 2*a; else c = 2*b; c = 2*((n > 1)? a:b); What is the value of x here? float x; x = 1/((n > 1)? 2.0:2); More Examples: float x; x = 1/(n > 1)? 2.0:2; min = (x < y)? x:y; distance = (a > b)? (a b):(b a); printf("you have %d item%s.\n", n, (n == 1)? "":"s"); Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 12

Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement The switch-case Conditional Statement The (exp)? x:y Conditional Expression Iteration or Loop Statements The while Loop Statement The do-while Loop Statement The for Loop Statement Jump Statements: break, continue, and goto Example: Primality Testing Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 13

What Is a Loop? In general, a loop is a piece of code that is executed repeatedly several times, where several could range from zero to infinity. Here are some examples of loops: for (i = 1; i <= n; i++) factorial *= i; Each time the piece of code is executed is called a loop iteration, or simply an iteration. These iterations continue until either: The loop condition ceases to be satisfied, or The program exits from the loop via a jump tstatement, such as break or return. The C language provides three different types of loops: The while statement The do-while statement The for statement while (1) factorial *= i++; if (i > n) break; Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 14

The while Loop Statement expression 0 statement =0 The syntax of the while loop statement is as follows: while (expression) statement The expression is evaluated. If its logical value is True (the expression is nonzero) then statement is executed. After that the expression is evaluated again, and the process repeats until the logical value of the expression becomes False. When the logical value of the expression is False, program continues to next statement. Example: int n, factorial = 1, i = 1; scanf("%d", &n); while(i <= n) factorial *= i++; printf("n!= %d", factorial); Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 15

Example: Odd and Even Averages Problem: Prompt the user to enter a positive integer, and keep doing this while the user complies. When the user inputs an integer that is not positive, output: t The average of all the even positive integers the user entered The average of all the odd positive integers the user entered Assumptions: The user input is valid. The user enters only integers, including at least one odd integer and at least one even integer.t Algorithm: Read user input in a while loop, and keep the current even_sum and odd_sum. At each iteration, the integer entered by the user will be added to even_sum iftit is even and to odd_sum if it is odd. Also count the total number of odd and even integers entered. Then:t even_average = even_sum / even_count odd_average = odd_sum / odd_count Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 16

Example: Odd and Even Averages #include <stdio.h> int main() int odd_sum = 0, even_sum = 0, odd_count = 0, even_count = 0, next; printf("enter a positive integer: "); scanf("%d", &next); while (next > 0) if (next % 2) odd_sum += next; odd_count++; else even_sum += next; even_count++; printf("enter a positive integer: "); scanf("%d", &next); printf("\naverage of even integers is: %6.2f\n" " Average of odd integers is: %6.2f\n\n", (double)even_sum/even_count, (double)odd_sum/odd_count); return 0; Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 17

The do-while Loop Statement statement The syntax of the do-while loop statement is as follows: do statement while(expression); 0 expression =0 First, the statement is executed, and then expression is evaluated. If its logical value is True (the expression is nonzero), the statement is executed again, and the process repeats until the logical value of the expression becomes False. Example: When expression evaluates to False, program flow continues to the next statement. do printf("enter a positive integer: "); scanf("%d", &x); while (x <= 0); The statement of a do-while loop is executed at least once! Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 18

The for Loop Statement expression1 expression2 0 statement expression3 =0 The syntax of the for loop statement is as follows: for (expression1; expression2; expression3) statement First, expression1 is executed. This serves as the initialization of the loop. Next, expression2 is evaluated. If its logical value is True (expression2 is nonzero), the statement and then expression3 are executed.lthey keep being executed, in this order repeatedly, as longlas expression2 evaluates to True.l When expression2 evaluates to False, program flow continues to next statement. Each of the three expressions can be empty; empty expression2 is True! Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 19

The for Loop: Examples Here is an example of a for loop that computes the sum of the first n squares: sum = 0; for (i = 1; i <= n; i++) sum += i*i; Another example: factorial = 1; for (i = 2; i <= n; i++) factorial *= i; Note: The for and the while loops are equivalent! for (expression1; expression2; expression3) statement expression1; while (expression2) statement expression3; for (i = 2; i <= n; i++) factorial *= i; i = 2; while(i <= n) factorial *= i; i++; Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 20

The for Loop: Comma Operator What is the comma operator? An expression like this exp1, exp2 is evaluated by first evaluating exp1 then evaluating exp2. Similarly for exp1, exp2, exp3, etc. The type of a comma expression is the type of the last exp evaluated. Such expressions can be used in the initialization/increment of for-loop. Example. We have seen this before: This can be also written as: Or even as: sum = 0; for (i = 1; i <= n; i++) sum += i*i; for (sum = 0, i = 1; i <= n; i++) sum += i*i; for (sum = 0, i = 1; i <= n; sum += i*i, i++); Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 21

Example: Primality Testing Problem: Given a positive integer n, decide whether it s prime. Definition: A positive integer n is prime if and only if n > 1 and it has no divisors in the set 2,3,...,n-1. Equivalently, n is not prime if either n = 1 or n has a divisor in the set 2,3,...,n-1. Solution: unsigned int is_prime = 1, n, i;... \\ read n if(n == 1) is_prime = 0; else for (i = 2; i < n; i++) if (n % i == 0) is_prime = 0; if (is_prime) printf("%d is a prime\n", n); else printf("%d is not a prime\n", n); Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 22

Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement The switch-case Conditional Statement The (exp)? x:y Conditional Expression Iteration or Loop Statements The while Loop Statement The do-while Loop Statement The for Loop Statement Jump Statements: break, continue, and goto Example: Primality Testing Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 23

The break and continue Statements These are special jump statements that change the default behavior of the while, do-while, and for loops: break Causes immediate exit from the loop. The rest of the code in the loop is skipped, and the program flow proceeds to the next statement after the end of the loop. Recall that break works in exactly the same way also for the switchcase-default statement. The following, though, works only for loops: continue Causes the rest of the loop to be skipped. The program flow proceeds to the next iteration of the same loop. Example: What will get printed? for (k = i = 0; i < 8; i++) for (j = 0; j < 8; j++) if (j == 4) break; k++; printf("%d,%d,%d", i,j,k); for (k = i = 0; i < 8; i++) for (j = 0; j < 8; j++) if (j == 4) continue; 8, 4, 32 8, 8, 56 k++; printf("%d,%d,%d", i,j,k); Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 24

Examples of continue Usage The following code reads 100 integers and computes the sum of those that are nonnegative: for (i = 0; i < 100; i++) i = 0; while (i < 100) scanf("%d",&num); if(num < 0) continue; sum += num; i++; scanf("%d",&num); if(num < 0) continue; sum += num; What is the difference between the code above and the code to the left? Are they equivalent? The for loop will always read exactly 100 integers. The while loop will read as many integers as it needs (perhaps 1,000,000) to get exactly 100 nonnegative integers. What could we change to make the two loops equivalent? Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 25

Infinite Loops and break Usage Infinite loops could arise in a C program either by design or by mistake. If a program goes into an infinite loop by mistake, it will usually hang producing no output. In most cases, you can terminate such a program by pressing CTRL-C and then debug. However, infinite loops are often introduced into a C program by design. For example: while(1)... for( ;1; )... for( ; ; )... The program can be designed to exit such infinite loops via one of the following statements: break, return, or goto. Example: The following loop is designed to read from the input nonnegative integers and compute their sum, exiting as soon as the user inputs the first negative integer. What s wrong with this do-while loop? sum = 0; do sum = 0; scanf("%d",&num); while(1) sum += num; scanf("%d",&num); while (num >= 0) if (num < 0) break; sum += num; Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 26

break Usage: Another Example Problem: Compute the logical OR of n input values. Solution: Two different approaches, both using break. enum boolean FALSE,TRUE; int i, value; boolean or; or = FALSE; for (i = 0; i < n; i++) scanf("%d",&value); if (value) or = TRUE; break; What happens if we delete the break? for (i = 0; i < n; i++) scanf("%d",&value); if (value) break; or = (i < n); What happens if we delete the break? Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 27

The goto Jump Statement To use the goto statement, you first need to create a labeled statement, which is any statement prefixed by a label:, like this: sum: x = a+b; myloop: while(1) x++; error: return 1; Any identifier can serve as the label in a labeled statement. Thereafter, you can use goto sum, goto myloop, etc. at any point in the program. Example of Usage: for (i = 0; i < n; i++)... // do something for (j = 0; j < m; j++)... // do something else if (disaster) goto error;... // no disaster here... error: printf("please wait while I clean-up the mess!");... // clean-up the mess Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 28

Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement The switch-case Conditional Statement The (exp)? x:y Conditional Expression Iteration or Loop Statements The while Loop Statement The do-while Loop Statement The for Loop Statement Jump Statements: break, continue, and goto Example: Primality Testing Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 29

Recall: Primality Testing Problem: Given a positive integer n, decide whether it s prime. Definition: A positive integer n is prime if and only if n > 1 and it has no divisors in the set 2,3,...,n-1. Equivalently, n is not prime if either n = 1 or n has a divisor in the set 2,3,...,n-1. Solution: unsigned int is_prime = 1, n, i;... \\ read n if(n == 1) is_prime = 0; else for (i = 2; i < n; i++) if (n % i == 0) is_prime = 0; if (is_prime) printf("%d is a prime\n", n); else printf("%d is not a prime\n", n); Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 30

Primality Testing Improved If n is not 2, but is divisible by 2, then n is not prime. If n is not divisible by anything up to the square root of itself, then it must be prime. n It is enough to check divisibility up to square root of n. Since n is odd under else, we can skip testing divisibility by all even integers i. When a divisor i is found, n is not prime, and there is no need to keep testing. n #include <math.h>... int is_prime = 1, n, i, sqrt_n;... if (n == 1 (n!= 2 && n%2 == 0)) is_prime = 0; else sqrt_n = (int) sqrt(n); for (i = 3; i <= sqrt_n; i += 2) if (n%i == 0) is_prime = 0; break; if (is_prime) printf("%d is a prime\n", n); else printf("%d is not a prime\n", n);... Lecture Unit 4 ECE15: Introduction to Computer Programming Using the C Language 31