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

Similar documents
Flow Control. CSC215 Lecture

Computers Programming Course 7. Iulian Năstac

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

Introduction. C provides two styles of flow control:

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

SELECTION STATEMENTS:

DECISION CONTROL AND LOOPING STATEMENTS

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

Subject: PIC Chapter 2.

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

Programming for Electrical and Computer Engineers. Loops

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

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

Module3. Program Control Statements CRITICAL SKILLS. 3.1 Know the complete form of the if statement. 3.2 Use the switch statement

Unit 3 Decision making, Looping and Arrays

Decision Making and Loops

Decision Making -Branching. Class Incharge: S. Sasirekha

More examples for Control statements

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

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

Lecture 6. Statements

Prepared by: Shraddha Modi

Decision Making in C

Module 4: Decision-making and forming loops

Problem Solving and 'C' Programming

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science)

CHAPTER 9 FLOW OF CONTROL

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

COMP 208 Computers in Engineering

CSE 130 Introduction to Programming in C Control Flow Revisited

BRANCHING if-else statements

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

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

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

LESSON 6 FLOW OF CONTROL

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Object Oriented Programming with C++ SYLLABUS OBJECT ORIENTED PROGRAMMING WITH C++ (Common to CSE & ISE)

Midterm Exam. CSCI 2132: Software Development. March 4, Marks. Question 1 (10) Question 2 (10) Question 3 (10) Question 4 (10) Question 5 (5)

Chapter 13 Control Structures

CHAPTER 5 FLOW OF CONTROL

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

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

MODULE 2: Branching and Looping

Fundamentals of Computer Programming Using C

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

Structured Programming. Functions and Structured Programming. Functions. Variables

1/31/2018. Overview. The C Programming Language Part 2. Basic I/O. Basic I/O. Basic I/O. Conversion Characters. Input/Output Structures and Arrays

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

Dept. of CSE, IIT KGP

Unit 7. Functions. Need of User Defined Functions

Operators And Expressions

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

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

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

Simple if Simple if-else Nested if - else Notes for if-else statement Logical operators

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

3 The L oop Control Structure

C-LANGUAGE CURRICULAM

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

ECET 264 C Programming Language with Applications. C Program Control

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Topic 6: A Quick Intro To C

DELHI PUBLIC SCHOOL TAPI

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

Chapter 3: Arrays and More C Functionality

Lecture 3. More About C

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

CHAPTER : 9 FLOW OF CONTROL

Chapter 5: Control Structures

Scope. Scope. Region of a program in which a defined object is visible. Defined Objects. Two types of regions. Variables Functions

REPETITION CONTROL STRUCTURE LOGO

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

Dr. R. Z. Khan, Associate Professor, Department of Computer Science

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

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

Programming and Data Structures

Control structures in C. Going beyond sequential

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

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

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

CS50 Supersection (for those less comfortable)

Fundamentals of Programming. Lecture 14 Hamed Rasifard

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

CpSc 1111 Lab 5 Formatting and Flow Control

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

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

Introduction to C Programming

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

Overview. CS 201 Repetition. Endfile-controlled loops. What is the Output? Nested Loops. Loops. Debzani Deb

Government Polytechnic Muzaffarpur.

Decision Making and Branching

Loops / Repetition Statements

5. Selection: If and Switch Controls

The C language. Introductory course #1

{C} Programming. Part 1/2 Basics Variables, Conditions, Loops, Arrays, Pointer basics

Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. One More Type of Control Flow. What s Wrong with HW1?

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Transcription:

Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps 1 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 00 The null character \0 The NULL pointer (for pointer see chap 8) True is represented by any nonzero value A 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 2 Examples int i=1, j=2, k=3; double x=55, y=77, z=00; i<j-k i<(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!=j 1!!5!(!5) 1!i-j+4 ((!i)-j)+4 2 if switch Selection x i&&j-2 x (i&&(j-2)) 1 3 4 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 if logic: If-else-logic: if (Boolean Expression) statement_1; if (Boolean Expression) compound_1 No Semi-colon else compound_2 Yes- For a Semi-colon The else clause is optional 5 Conditional execution allows you write code that reacts to tested conditions 6 1

Example #include <stdioh> WHY? int main ( ) double salary, payrate; int hours, union; printf ( Please enter hours worked, payrate, and union status ); 7 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) + ((15 * payrate) * (hours - 40)); else salary = payrate * hours; printf ( Salary is: $ % 62 f, salary); 8 Nested: Nested ifs: Why Nested ifs? Nested ifs One statement coded within another statement An nested if is an if that is the target of another if or else 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 9 The if-else-if ladder Linear nested If General form: OLD STYLE if (expression) statement; else if (expression) statement; else if (expression) statement; else statement; 10 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 11 Example Eg You are a salesperson for the Widget Manufacturing Co You will earn a salary bonus according to the following rules: Sales > = $50,000 earn $5,000 Sales > = $100,000 earn $15,000 Sales > = $150,000 earn $30,000 12 2

double sales, bonus; printf ( please enter total sales ); scanf ( %lf, &sales); 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 (sales < 50000) bonus = 0; else if (sales < 100000) bonus = 5000; else if (sales < 150000) bonus = 15000; else bonus = 30000; 13 if(i) if(j) dosomething1(); if(k) dosomething2(); /* this if */ else dosomething3(); /* goes with this else */ else dosomething4(); /* associated with if(i) */ 14 Conditional Expression The?: Alternative 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 15 Exp1? Exp2: Exp3 x = 10; y = x>9? 100 : 200; x = 10; if(x>9) y = 100; else y = 200; 16 #include <stdioh> 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; 17 /* Divide the first number by the second */ #include <stdioh> int main(void) int a, b; printf("enter two numbers: "); scanf(''%d%d", &a, &b); if(b) printf("%d\n", a/b); VALID? else printf("cannot divide by zero\n"); return 0; 18 3

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 19 General Form switch (expression) case constant1: statement sequence case constant2: statement sequence default statement sequence //ANSI C - at least 257 case constants 20 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 21 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) 22 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; switch(ch) case '1': check_spelling (); case '2': correct_errors (); 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: "); case '3': display_errors (); default : printf("no option selected"); ch = getchar(); /* read the selection from the keyboard */ 23 24 4

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 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; case 4: flag = 1; case 5: error(flag); default: process(k); 25 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 26 switch(x) case 1: switch(y) case 0: printf(''divide by zero error\n"); case 1: process(x, y); case 2: 27 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) 28 for loop 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 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 The increment defines how the loop control variable changes each time the loop is repeated 29 30 5

#include <stdioh> 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); 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) 31 32 Pieces of the loop definition need not be there for(x=0; x!= 123; ) scanf("%d", &x); The incrementation of the loop control variable can occur outside the for statement 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( x=1 ; x < 10; ) printf("%d", x); ++x; 33 Terminate the infinite loop for( ; ; ) ch = getchar(); /* get a character */ if(ch == 'A') /* exit the loop */ printf("you typed an A"); 34 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++ ) ; 35 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! */ 36 6

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 37 Example char wait_for_char(void) char ch; ch = '\0'; /* initialize ch */ while(ch!= 'A') ch = getchar(); return ch; while((ch=getchar())!= 'A') ; 38 Example 2 void func1() int process1(void); int process2(void); int process3(void); int working; working = 1; while (working) working = process1(); if (working) working = process2(); if (working) working = process3(); For loop Vs While Loop A-(Assignment), T-(testing), I-(Increment) for (A; T; I) Body; 39 40 A; While (T) Body; I; Nested Loop NESTED LOOPS 1 loop syntax coded inside another syntax General Format: while (boolean expression) Why?- Single -Loop? Have a statement or statements that you want to repeat A repetitive task that you must solve while (boolean expression) Why? - Nested-Loops? You have a single - repetitive task - THAT YOU MUST REPEAT ie, a repetition of an 41 already repetitive task You may have any combination of the 3 loop syntax inside each other The problem dictates what combination should be used 42 7

/* Find triples of integers that add up to n */ #include <stdioh> #define N 7 main() int cnt = 0, j, k, m; for(j = 0; j <= N; ++j) for( k = 0; k <= N; ++k) for( m = 0: m <= N; ++m) if ( j + k + m == N) ++cnt; printf( %d%d%d, j, k, m); printf( \n Count: %d\n, cnt); 43 How many times will if be executed? 512 times j range 0 7 k range 0 7 m range 0 7 8 * 8 * 8 = 512 44 What will the values of j, k, and m be in sequence J K M 0 0 0 0 0 1 0 0 2 0 0 7 0 1 0 0 1 1 0 1 2 0 1 7 45 Cont 0 2 0 0 2 1 0 2 7 46 do-while Loop General form: do statement; while(condition); Execution: Always executes at least once Iterates until condition becomes false do scanf(''%d", &num); The most common use of the do-while loop is in a menu selection function void menu(void) char ch; printf("1 Check Spelling\n"); printf("2 Correct Spelling Errors\n"); printf("3 Display Spelling Errors\n"); printf(" Enter your choice: "); while(num > 100); 47 48 8

do ch = getchar(); /* read the selection from the keyboard */ switch(ch) case '1': check_spelling(); case '2': correct_errors(); case '3': display_errors(); Jump break continue return (will be introduced in Ch 4, Functions) while(ch=='1' ch=='2' ch=='3'); 49 50 break Statement Two uses: You can use it to terminate a case in the switch statement You can also use it to force immediate termination of a loop, bypassing the normal loop conditional test #include <stdioh> int main (void) int t; for(t=0; t < 100; t++) printf(''%d ", t); if(t == 10) return 0; A break causes an exit from only the innermost loop for(t=0; t < 100; ++t) count = 1; for(;;) printf(''%d ", count); count++; if(count == 10) 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 1051 52 100 times Breaking out of loops Sometimes loops need to be cut short: You can break out of any loop with break ; statement A break will cause the loop to be aborted immediately The next statement executed is the statement following the loop Compare this with return: A return will cause a function to be aborted immediately General form continue; Continue Statement break forces termination of the loop continue forces the next iteration of the loop to take place, skipping any code in between Control returns to the calling function 53 54 9

continue can expedite the exit from a loop by forcing the conditional test to be performed sooner For the for loop, continue causes the increment and then the conditional test portions of the loop to execute For the while and do-while loops, program control passes to the conditional tests 55 void code(void) char done, ch; done = 0; while(!done) ch = getchar(); if(ch == S') done = 1; continue; /* test the condition now */ putchar(ch+1); This function codes a message by shifting all characters you type one letter higher For example, an A becomes a B The function will terminate when you type a S 56 10