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

Similar documents
Maltepe University Computer Engineering Department. Algorithms and Programming. Chapter 4: Conditionals - If statement - Switch statement

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Computer Science & Engineering 150A Problem Solving Using Computers

Introduction. C provides two styles of flow control:

REPETITION CONTROL STRUCTURE LOGO

Looping. Arizona State University 1

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

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

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

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

LECTURE 5 Control Structures Part 2

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

Repetition Structures

Flow Control. CSC215 Lecture

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

Information Science 1

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

Module 4: Decision-making and forming loops

Repetition and Loop Statements Chapter 5

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

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

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.

Information Science 1

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

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

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

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

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

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

Programming for Electrical and Computer Engineers. Loops

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

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

Chapter 3. Selections

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

Lecture 7 Tao Wang 1

3 The L oop Control Structure

STUDENT LESSON A12 Iterations

DECISION MAKING STATEMENTS

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

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

(Refer Slide Time: 00:26)

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Lecture 3. More About C

Control Statements. Musa M. Ameen Computer Engineering Dept.

Fundamentals of Programming Session 7

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Chapter 13 Control Structures

8. Control statements

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

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

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

A Look Back at Arithmetic Operators: the Increment and Decrement

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CS112 Lecture: Loops

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

CpSc 1111 Lab 5 Formatting and Flow Control

Chapter 5: Control Structures

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

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Computer Programming I - Unit 5 Lecture page 1 of 14

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

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

Introduction to C Programming

CHAPTER 2 PROBLEM SOLVING TECHNIQUES. Mr Mohd Hatta Bin Hj Mohamed Ali Computer Programming BFC2042

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

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

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

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

Why Is Repetition Needed?

Add Subtract Multiply Divide

Repetition CSC 121 Fall 2014 Howard Rosenthal

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

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

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

Control structures in C. Going beyond sequential

CS 106 Introduction to Computer Science I

Course Outline Introduction to C-Programming

Loops and Files. of do-while loop

Theory of control structures

CS110D: PROGRAMMING LANGUAGE I

Chapter 2. C++ Basics

CS112 Lecture: Repetition Statements

Unit 3. Operators. School of Science and Technology INTRODUCTION

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

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

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

Laboratory 5: Implementing Loops and Loop Control Strategies

5. Control Statements

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

Chapter 5: Loops and Files

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

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Transcription:

CS 201 Selection Structures (2) and Repetition Debzani Deb Multiple-Alternative Decision Form of Nested if Nested if statements can become quite complex. If there are more than three alternatives and indentation is not consistent, it may be difficult for you to determine the logical structure of the if statement. You can code the nested if as the multiple-alternative decision described below: if ( condition_1 ) statement_1 else if ( condition_2 ) statement_2... else if ( condition_n ) statement_n else statement_e 1 2 Example Given a person s salary, we want to calculate the tax due by adding the base tax to the product of the percentage times the excess salary over the minimum salary for that range. Salary Range 0.00 14,999.99 15,000.00 29,999.99 30,000.00 49,999.99 50,000.00 79,999.99 80,000.00 150,000.00 Base tax 0.00 2,250.00 5,400.00 11,000,00 21,600.00 Percentage of Excess 15 18 22 27 33 if ( salary < 0.0 ) tax = -1.0; else if ( salary < 15000.00 ) tax = 0.15 * salary; else if ( salary < 30000.00 ) tax = (salary 15000.00)*0.18 + 2250.00; else if ( salary < 50000.00) tax = (salary 30000.00)*0.22 + 5400.00; else if ( salary < 80000.00) tax = (salary 50000.00)*0.27 + 11000.00; else if ( salary <= 150000.00) tax = (salary 80000.00)*0.33 + 21600.00; else tax = -1.0; 3 4 Order of Conditions in a Multiple- Alternative Decision When more than one condition in a multiplealternative decision is true, only the task following the first true condition executes. Therefore, the order of the conditions can affect the outcome. The order of conditions can also have an effect on program efficiency. If we know that salary range 30,000-49,999 are much more likely than the others, it would be more efficient to test first for that salary range. For example, if ((salary>30,000.00) && (salary<=49,999.00)) Nested if Statements with More Than One Variable In most of our examples, we have used nested if statements to test the value of a single variable. Consequently, we have been able to write each nested if statement as a multiple-alternative decision. If several variables are involved in the decision, we cannot always use a multiple-alternative decision. The next example contains a situation in which we can use a nested if statement as a filter to select data that satisfies several different criteria. 5 6 1

Example The Department of Defense would like a program that identifies single males between the ages of 18 and 26, inclusive. One way to do this is to use a nested if statement whose conditions test the next criterion only if all previous criteria tested were satisfied. Another way would be to combine all of the tests into a single logical expression In the next nested if statement, the call to printf executes only when all conditions are true. Example /* Print a message if all criteria are met.*/ if ( marital_status == S ) if ( gender == M ) if ( age >= 18 && age <= 26 ) printf("all criteria are met.\n"); or we could use an equivalent statement that uses a single if with a compound condition: /* Print a message if all criteria are met.*/ if ((maritial_status == S ) && (gender == M ) && (age >= 18 && age <= 26)) printf("all criteria are met.\n"); 7 8 Common if statement errors if crsr_or_frgt == C printf("cruiser\n"); This error is that there are no ( ) around the condition, and this is a syntax error. if (crsr_or_frgt == C ); printf("cruiser\n"); This error is that there is a semicolon after the condition. C will interpret this as there is nothing to do if the condition is true. If Statement Style All if statement examples in this lecture have the true statements and false statements indented. Indentation helps the reader but conveys no meaning to the compiler. The word else is typed without indentation on a separate line. This formatting of the if statement makes its meaning more apparent and is used solely to improve program readability. 9 10 Tracing an if Statement A critical step in program design is to verify that an algorithm or C statement is correct before you spend extensive time coding or debugging it. Often a few extra minutes spent in verifying the correctness of an algorithm saves hours of coding and testing time. A hand trace or desk check is a careful, step-by-step simulation on paper of how the computer executes the algorithm or statement. The results of this simulation should show the effect of each step s execution using data that is relatively easy to process by hand. Sections 4.4 and 4.5 in the text have great step-by-step examples of using if statements to solve problems. Switch statements The switch statement is a better way of writing a program when a series of if-elseif occurs. The switch statement selects one of several alternatives. The switch statement is especially useful when the selection is based on the value of a single variable or of a simple expression This is called the controlling expression In C, the value of this expression may be of type int or char, but not of type double. 11 12 2

Figure 4.12 Example of a switch Statement with Type char Case Labels Explanation of Example This takes the value of the variable class and compares it to each of the cases in a top down approach. It stops after it finds the first case that is equal to the value of the variable class. It then starts to execute each line of the code following the matching case till it finds a break statement or the end of the switch statement. If no case is equal to the value of class, then the default case is executed. default case is optional. So if no other case is equal to the value of the controlling expression and there is a default case, then default case is executed. If there is no default case, then the entire switch body is skipped. 13 14 Remember!!! The statements following a case label may be one or more C statements, so you do not need to make multiple statements into a single compound statement using braces. You cannot use a string such as Cruiser or Frigate as a case label. It is important to remember that type int and char values may be used as case labels, but strings and type double values cannot be used. Another very common error is the omission of the break statement at the end of one alternative. In such a situation, execution falls through into the next alternative. Forgetting the closing brace of the switch statement body is also easy to do. In the book it says that forgetting the last closing brace will make all following statements occur in the default case, but actually the code will not compile on most compilers. 15 Nested if versus switch Advantages of if: It is more general than a switch It can be a range of values such as x < 100 A switch can not compare Strings or doubles Advantages of switch: A switch is more readable Use the switch whenever there are ten or fewer case labels 16 Common Programming Errors Consider the statement: if (0 <= x <= 4) This is always true! First it does 0 <= x, which is true or false so it evaluates to 1 for true and 0 for false Then it takes that value, 0 or 1, and does 1 <= 4 or 0 <= 4 Both are always true In order to check a range use (0 <= x && x <= 4). Consider the statement: if (x = 10) This is always true! The = symbol assigns x the value of 10, so the conditional statement evaluates to 10 Since 10 is nonzero this is true. You must use == for comparison More Common Errors Don t forget to parenthesize the condition. Don t forget the and if they are needed C matches each else with the closest unmatched if, so be careful so that you get the correct pairings of if and else statements. In switch statements, make sure the controlling expression and case labels are of the same permitted type. Remember to include the default case for switch statements. Don t for get your and for the switch statement. Don t forget your break statements!!! 17 18 3

Repetition in Programs Repetition and Loop We have learned how to write code that chooses between multiple alternatives. It is also useful to be able to write code that repeats an action. Writing out a solution to a specific case of problem can be helpful in preparing you to define an algorithm to solve the same problem in general. After you solve the specific case, you need to determine whether loops will be required in the general algorithm and if so which loop structure to choose from. 19 20 Figure 5.1 Flow Diagram of Loop Choice Process Counting Loops The loop shown below in pseudo code is called a countercontrolled loop (or counting loop) because its repetition is managed by a loop control variable whose value represents a count. Set loop control variable to an initial value of 0 While loop control variable < final value... //Do something multiple times Increase loop control variable by 1. We use a counter-controlled loop when we can determine prior to loop execution exactly how many loop repetitions will be needed to solve the problem. 21 22 The While Statement This slide shows a program fragment that computes and displays the gross pay for seven employees. The loop body is the compound statements (those between and ). The loop repetition condition controls the while loop. count_emp = 0; while (count_emp < 7) loop repetition condition printf("hours> "); scanf("%d",&hours); printf("rate> "); scanf("%lf",&rate); pay = hours * rate; printf("pay is $%6.2f\n", pay); count_emp = count_emp + 1; printf("\nall employees processed\n"); While Statement General form: While (loop repetition condition) //Steps to perform. These should eventually //result in condition being false Syntax of the while Statement: Initialization. i.e. count_emp = 0; Testing. i.e. count_emp < 7 Updating i.e. count_emp = count_emp + 1; The above steps must be followed for every while loop. If any of these are skipped it may produce an infinite loop 23 24 4

General While Loops In the above example we had count_emp < 7, but we may have more or less than 7 employees. To make our program fragment more general we should use a printf/scanf to get the number of employees and store it is num_emp. Now we can have count_emp < num_emp and our code is more general. Computing Sum If we want to compute i, we need to go i= 1 1+2+3+...+100 We can use a while loop. sum = 0; currentval = 1; while (currentval <= 100) sum = sum + currentval; currentval = currentval + 1; printf("sum is %d", sum); 100 25 26 Compound Assignment Operators Several times we have seen: variable = variable <operator> expression; Example: sum = sum + currentval; where <operator> is a C operator This occurs so often, C gives us short cuts. Instead of writing x = x +1 we can write: x += 1. W can use -=, *=, /=, and %= in the same way. The For Statement A better way to construct a counting loop is to use the for statement. C provides the for statement as another form for implementing loops. As before we need to Initialize the loop control variable Test the loop repetition condition Update the loop control variable. An important feature of the for statement in C is that it supplies a designated place for each of these three components. An example of the for statement is shown in the next slide. 27 28 For Example To compute the sum of 1 to 100: int sum = 0; int curval; for (curval = 1; curval <= 100; curval++) sum = sum + curval; Note: curval++ is the same as curval = curval + 1 and as curval += 1. General Form of For statement for (initialize; test; update) //Steps to perform each iteration First, the initialization expression is executed. Then, the loop repetition condition is tested. If the condition is true, the statement enclosed in are executed. After that the update expression is evaluated. Then the loop repetition condition is retested. The statement is repeated as long as the condition is true. For loop can be used to count up or down by any interval. 29 30 5

Program Style For clarity, it can be useful to place each expression of the for heading on a separate line. If all three expressions are very short, we will place them together on one line, like we did in the example. The body of the for loop is indented just as the if statement. Increment and Decrement Operators The counting loops that we have seen have all included assignment expressions of the form counter = counter + 1 or counter++ or counter += 1 This will add 1 to the variable counter. If we use a - instead of a +, it will subtract 1 from the variable counter. Be careful about using the ++ or -- options. 31 32 Increment and Decrement Other Than 1 Instead of adding just 1, we can use sum = sum + x or sum += x Both of these will take the value of sum and add x to it and then assign the new value to sum. We can also use temp = temp -x or temp -= x Both of these will take the value of temp and subtract x from it and then assign the new value to temp. Prefix and Postfix Increment/Decrement The values of the expression in which the ++ operator is used depends on the position of the operator. When the ++ operator is placed immediately in front of its operand (prefix increment, Ex: ++x), the value of the expression is the variable s value after incrementing. When the ++ operator is placed immediately after the operand (postfix increment, Ex: x++), the value of the expression is the value of the variable before it is incremented. 33 34 Figure 5.6 Comparison of Prefix and Postfix Increments More on prefix and postfix operator If n = 4, what will be the output of the following? printf( %3d, --n); printf( %3d, n); printf( %3d, n--); printf( %3d, n); 3 3 4 3 35 36 6

Conditional Loops In many programming situations, we will not be able to determine the exact number of loop repetitions before loop execution begins. Below is an example where we do not know how many times our program will repeat. Example We need a program that prompts the user for a value and multiplies it by the value of the variable temp. It then stores the result in temp. It keeps doing this until the user enters a 0. The outline of the program would be as follows: assign temp the value of 1 prompt the user for a value while value does not equal 0 assign temp the value of temp times value prompt the user for a value output the value of temp 37 38 Program Fragment temp = 1; printf("enter a value, 0 will stop the program> "); scanf("%d",&value); Initialization while(value!= 0) Testing temp = temp * value; printf("enter a value, 0 will stop the program>"); scanf("%d",&value); Update printf("the product is %d", temp); It is very common for loops to have identical initialization and update steps while performing input operations where the number of input values is not known in advance. Sentinel Controlled Loops Many programs with loops input one or more additional data items each time the loop body is repeated. Often we don t know how many data items the loop should process when it begins execution. We must find some way to signal the program to stop reading and processing new data. One way to do this is to instruct the user to enter a unique data value, called a sentinel value, after the last data item. The loop repetition condition tests each data item and causes loop exit when the sentinel value is read. This is what we did in the previous example: use the value 0 to stop the loop. 39 40 Figure 5.10 Sentinel-Controlled while Loop Sentinel Controlled for loop Because the for statement combines the initialization, test, and update in once place, some programmers prefer to use it to implement sentinel-controlled loops. printf("enter first score (or %d to quit)> ", sentinel); for( scanf("%d",&score); score!= sentinel; scanf("%d",&score)) sum += score; printf("enter next score (%d to quit)> ", sentinel); 41 42 7