Control structures in C. Going beyond sequential

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

Loops. Repeat after me

Loops. Repeat after me

Module 4: Decision-making and forming loops

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

Flow Control. CSC215 Lecture

Structured Programming. Dr. Mohamed Khedr Lecture 9

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

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

Logic & program control part 3: Compound selection structures

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

Chapter 5: Control Structures

Lecture 7 Tao Wang 1

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

REPETITION CONTROL STRUCTURE LOGO

Repetition and Loop Statements Chapter 5

3 The L oop Control Structure

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

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

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

Repetition Structures

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

Programming for Electrical and Computer Engineers. Loops

Dept. of CSE, IIT KGP

LECTURE 5 Control Structures Part 2

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

Why Is Repetition Needed?

Theory of control structures

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

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

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

Programming for Engineers Iteration

OER on Loops in C Programming

Lecture 6. Statements

204111: Computer and Programming

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

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

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

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

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

Unit 7. 'while' Loops

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

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

COMP 208 Computers in Engineering

MODULE 2: Branching and Looping

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

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

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

Chapter 4: Control structures. Repetition

Operators And Expressions

Information Science 1

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

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

Chapter 2: Functions and Control Structures

Chapter 13 Control Structures

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

Chapter 4: Control structures

Crude Video Game Simulator Algorithm

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

Chapter 5: Control Structures II (Repetition)

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

Chapter 4. Flow of Control

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

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

Structured Program Development

C: How to Program. Week /Apr/23

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

Unit 3 Decision making, Looping and Arrays

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

5. Control Statements

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Information Science 1

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

DECISION CONTROL AND LOOPING STATEMENTS

Chapter Goals. Contents LOOPS

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Introduction to the Java Basics: Control Flow Statements

Decision Making and Loops

Writing to and reading from files

Flow Control. Key Notion. Statement Categories. 28-Oct-10

A Look Back at Arithmetic Operators: the Increment and Decrement

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

Advanced Computer Programming

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

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

Introduction to C Programming

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

Review of the C Programming Language for Principles of Operating Systems

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

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

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

General Information About Iteration (Loops)

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

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

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

Transcription:

Control structures in C Going beyond sequential

Flow of control in a program Start (main) Program starts with the first statement in main Instructions proceed sequentially: One at a time Top to bottom Each executes exactly once If a function call occurs, the sequence is interrupted; when the function returns, the sequence resumes Step 1 Step 2 Call F Step 3 End (main) Start (F) F step 1 F step 2 End (F)

Altering flow of control Programming constructs can be employed to alter the flow of logic Two basic categories: Selection (aka branching) Iteration (aka looping) Both constructs rely on the evaluation of logical or relational expressions to determine which instruction(s) to execute

Quick review of logical expressions Logical, or boolean expressions, are expressions that evaluate to true or false In C, there is no boolean data type Int values used instead 0 means false Any other int value means true

Relational & Logical Operators in C Relational operators: >, <, >=, <= ==,!= Logical operators: &&!

Selection structures in C Simplest structure is plain if: if(expression evaluates true) { } Example: /* perform instruction(s) */ if ((x % 10) == 0) { } printf( %d is a multiple of 10\n, x);

Selection structures in C Important syntax notes: Always put parentheses around the expression to be tested in an if clause (it's a syntax error if you don't) Never put a semicolon at the end of the if clause Semicolon, all by itself, is a null (non-operational) statement if (expression); says if expression is true, do nothing Begin/end brackets ({}) are required if more than one statement is to be executed because of an if clause; if there is only one statement, they are optional

Something to watch out for what is output from this program? #include <stdio.h> int main() { int x = 0; if (x = 0) { printf("x is zero"); } return 0; }

Selection structures in C Perhaps the most versatile selection structure is the if/else structure In this structure, the if clause is followed by statement(s) to perform if the expression is true, and an else clause is followed by statement(s) to perform if the expression is false

The if/else structure: syntax if (expression) { } else { } /* statement(s) to perform if expression is true */ /* statement(s) to perform if expression is false */

#include <stdio.h> #include <stdlib.h> #include <time.h> Example int main() { srand(time(null)); int r = rand() % 20-10; if(r >= 0) printf("%d is positive\n", r); else printf("%d is negative\n", r); }

Compound selection (multiple branching) Each if and else clause is followed by one or more statements to execute We can place another if or if/else combination within the set of statements followed by either clause The result is a nested if or nested if/else structure

#include <stdio.h> #include <stdlib.h> Example int main() { srand(time(null)); int r = rand() % 3-1; if(r > 0) printf("%d is positive\n", r); else if (r < 0) printf("%d is negative\n", r); else printf("%d is zero\n", r); }

Notes on nested if/else An else clause never has its own condition; it is always the alternative to the nearest previous if clause If you want to test another condition, therefore, you need another if clause this was the case with the previous program: if(r > 0) printf("%d is positive\n", r); else if (r < 0) /* new condition, new if clause */

Matching ifs and elses An else clause always pairs with the closest if clause that doesn't already have a paired else Example if (A)... if (B)... if (C)... else /* pairs with condition C */... else /* pairs with condition B */... else /* pairs with condition A */...

Alternate branching structures: switch/case & the ternary operator Nested if/else structures are sufficient to cover any program you might want to write that involves logical selection There are a couple of alternative structures you should at least be aware of These are briefly discussed on the next 2 slides

The switch/case structure May be used instead of if/else when the condition being tested is in the form if x == y Instead of using the relational expression, we use the variable (x) as the switch, and the various possible values (y) as cases Instead of a final else, we can use a default case

The ternary operator Is so named because it takes 3 operands Syntax: Logic: expression? statement1 : statement2 If the expression is true, perform statement1 Otherwise, perform statement 2

Loops in C Selection structures, as the name implies, select certain statements to execute while skipping other statements Loops are structures that repeat a set of statements as long as a condition remains true

Loop control We can generally divide all loops into two categories: Count controlled loops are those that execute a set number of iterations Event controlled loops execute an indeterminate number of times; something external to the program (e.g. the user) decides how many times the loop will execute

Loop constructs in C The basic, most general type of loop is the while loop A loop specifically designed for count control is the for loop A loop that is guaranteed to give us at least one iteration regardless of the condition is a do/while loop We will spend most of our time with the first two

While loops Syntax: while (expression) { } /* statements to perform if expression is true */ /* statement or statements that update the condition */

While Statement while ( Expression ) { statement(s); } Expression is test for terminating condition Loop exit occurs when test succeeds (tests false) Loop entry is moment flow of control reaches 1st statement in loop body One iteration means one pass through the loop Even though actual value being tested changes inside loop body, exit does not occur until next time value is tested

Example int x = 0; // control variable initialization while (x < 100) // control variable test { printf ( x=%d\n, x); x ++; // control variable updated }

Another example int main() { int x = 10; while (x > 0) { printf( %2d\n, x); x--; } printf( Lift off!\n ); return 0; } Loop trace: Value of x Output 10 10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 (loop ends) Lift off!

int sum = 0, number = 1; while ( sum <= 1000000 ) { } sum = sum + number; number = number + 1; Example When will the loop end? A.When number reaches 100 B.When sum equals 1000000 C.When number exceeds 100 D.When sum exceeds 1000000

Example int product = 1, number = 1, count = 20, lastnumber; lastnumber = 2 * count - 1; When the loop concludes, what is the value of number? while (number <= lastnumber) { product = product * number; number = number + 2; }

Example: finding sum and average 100 numeric values need to be added together and averaged Using a while loop: read the 100 values find their total find their average

int main() { int thisnum; int total = 0; // initialize sum int count = 0; // initialize loop control while ( count < 100 ) // test expression { printf ( Enter value: ); scanf( %d, &thisnum); // read 1 value total = total + thisnum ; // add value to sum count++ ; // update loop control } } printf ( The sum of the values is: %d\n, total); printf ( The average is: %lf\n, (double)total/count); return 0;

Event controlled loop In the previous example, a loop was used to find the sum and average of 100 numbers Although it should work, it's pretty rigid User has to hang in there and type 100 values Only works for data sets of size 100 Using an event-controlled loop we can modify the program to be both more user-friendly and more versatile

Infinite loop Loop that never stops iterating Happens when terminating condition can t be reached Need to ensure that the control variable changes during body of loop 31

Examples of infinite loops /* loop body is null statement: */ int x=0; while (x < 10); /* loop body is single statement that doesn t update control variable */ int x=0; while (x < 10) printf( %d\n, x); x++; /* control variable update is incorrectly written */ int x=0; while (x < 10) { printf( %d\n, x); x--; } 32

For loops Count-controlled loops are so common in programming that most languages have a special set of syntax designed specifically for this construct In C, the special syntax for a countcontrolled loop is called a for loop 33

Count-controlled loops Count-controlled while loop: initialize counter before loop starts test counter in loop control expression update counter inside loop body A for loop is a stylized version of a countcontrolled while loop; all of the elements above appear at the top of the loop 34

For Loop Syntax for ( initialization ; test expression ; update ) { 0 or more statements to repeat } 35

The for loop contains an initialization an expression to test for continuing an update to execute after each iteration of the body 36

Count-controlled while loop example int x=0; /* step 1: initialize counter */ while (x < 100) /* step 2: test counter value */ { printf( I will be a good student\n ); x++; /* step 3: increment counter */ } 37

Same logic using for loop for (int x=0; x<100; x++) printf( I will be a good student\n ); Step 1: initialize loop counter (performed once) Step 2: test counter value (performed once for each iteration) Step 3: increment loop counter (performed once per iteration) Body of loop is performed between steps 2 and 3, just as in the while loop version 38

Example using decrement for (int count = 4 ; count > 0 ; count-- ) { printf( %d\n, count); } printf( Done\n ); OUTPUT: 4 3 2 1 Done 39

Notes on for loop Just stylized version of while loop; condition test occurs before each iteration Can contain single statement (making brackets unnecessary) because increment occurs in loop heading Each section of loop heading can contain multiple parts, separated by commas; each section can also be omitted 40

What is output? int count=0; for (; count < 10 ; count++ ) { printf( ) ; } 41

What is output? int count=0; for (; count < 10 ; count++ ); { printf( ) ; } 42

1Potato 2Potato 3Potato 4 5Potato 6Potato 7Potato More Write a loop to produce the following output: 43

Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop body is performed first, then condition is tested A do-while loop is guaranteed to perform one iteration, because the validity of the condition is not known until after the iteration is complete 44

Syntax for do-while loop do { /* loop body statements */ }while (expression); Notes: do-while loops are almost always event-controlled Often not necessary to initialize loop control Good idea to keep end bracket and while(expression) on same line 45

Applications for do-while loops Often used to display an initial menu of choices, one of which is quit program you want user to see this at least once, even if the option they pick is to quit Can work well for file input Useful for checking validity of input value eliminates having to prompt twice for same data (see examples, next two slides) 46

Do-While Loop vs. While Loop POST-TEST loop (exitcondition) The looping condition is tested after executing the loop body. Loop body is always executed at least once. PRE-TEST loop (entrycondition) The looping condition is tested before executing the loop body. Loop body may not be executed at all. 47

Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested When one loop is nested within another, each iteration of the outer loop contains several iterations of the inner loop 48