Selection Statements

Save this PDF as:

Size: px
Start display at page:

Transcription

1 Chapter 5 Selection Statements 1 Statements So far, we ve used return statements and expression ess statements. e ts. Most of C s remaining statements fall into three categories: Selection statements: if and switch Iteration statements: while, do, and for Jump statements: break, continue, and goto. (return also belongs in this category.) Other C statements: Compound statement Null statement 2 1

2 Logical Expressions Several of C s statements must test the value of an expression to see if it is true or false false. For example, an if statement might need to test the expression i<j; a true value would indicate that i is less than j. In many programming languages, an expression such as i < j would have a special Boolean or logical type. In C, a comparison such as i<jyields an integer: either 0 (false) or 1 (true). 3 Relational Operators C s relational operators: < less than > greater than <= less than or equal to >= greater than or equal to These operators produce 0 (false) or 1 (true) when used in expressions. The relational operators can be used to compare integers and floating-point numbers, with operands of mixed types allowed. 4 2

3 Relational Operators The precedence of the relational operators is lower than that of the arithmetic operators. For example, i + j<k-1means (i+j)<(k-1). The relational operators are left associative. 5 The expression Relational Operators i < j < k is legal, but does not test whether j lies between i and k. Since the < operator is left associative, this expression is equivalent to (i < j) < k The 1 or 0 produced by i<jis then compared to k. The correct expression is i<j&&j<k. 6 3

4 Equality Operators C provides two equality operators: == equal to!= not equal to The equality operators are left associative and produce either 0 (false) or 1 (true) as their result. The equality operators have lower precedence than the relational operators, so the expression i < j == j < k is equivalent to (i < j) == (j < k) 7 Logical Operators More complicated logical expressions can be built from simpler ones by using the logical operators:! logical negation && logical and logical or The! operator is unary, while && and are binary. The logical operators produce 0 or 1 as their result. The logical operators treat any nonzero operand as a true value and any zero operand as a false value. 8 4

5 Logical Operators Behavior of the logical operators:!expr has the value 1 if expr has the value 0. expr1 && expr2 has the value 1 if the values of expr1 and expr2 are both nonzero. expr1 expr2 has the value 1 if either expr1 or expr2 (or both) has a nonzero value. In all other cases, these operators produce the value 0. 9 Logical Operators Both && and perform short-circuit evaluation: they first evaluate the left operand, then the right one. If the value of the expression can be deduced from the left operand alone, the right operand isn t evaluated. Example: (i!= 0) && (j / i > 0) (i!= 0) is evaluated first. If i isn t equal to 0, then (j/i>0)is evaluated. If i is 0, the entire expression must be false, so there s no need to evaluate (j/i>0). Without short-circuit evaluation, division by zero would have occurred. 10 5

6 Logical Operators Thanks to the short-circuit nature of the && and operators, side effects in logical expressions may not always occur. Example: i > 0 && ++j > 0 If i>0is false, then ++j > 0 is not evaluated, so jisn t incremented. The problem can be fixed by changing the condition to ++j>0&&i>0or, even better, by incrementing j separately. 11 Logical Operators The! operator has the same precedence as the unary plus and minus operators. The precedence of && and is lower than that of the relational and equality operators. For example, i<j&&k==mmeans (i<j)&& (k == m). The! operator is right associative; && and are left associative. 12 6

7 The if Statement The if statement allows a program to choose between two alternatives by testing an expression. In its simplest form, the if statement has the form if ( expression ) statement When an if statement is executed, expression is evaluated; if its value is nonzero, statement is executed. Example: if (line_num == MAX_LINES) line_num = 0; 13 The if Statement Confusing == (equality) with = (assignment) is perhaps the most common C programming error. The statement if (i == 0) tests whether i is equal to 0. The statement if (i = 0) assigns 0 to i, then tests whether the result is nonzero. 14 7

8 The if Statement Often the expression in an if statement will test whether a variable falls within a range of values. To test whether 0 i < n: if (0 <= i && i < n) To test the opposite condition (i is outside the range): if (i < 0 i >= n) 15 Compound Statements In the if statement template, notice that statement is singular, not plural: if ( expression ) statement To make an if statement control two or more statements, use a compound statement. A compound statement has the form { statements Putting braces around a group of statements forces the compiler to treat it as a single statement. 16 8

9 Example: Compound Statements { line_num num = 0; page_num++; A compound statement is usually put on multiple lines, with one statement per line: { line_num = 0; page_num++; Each inner statement still ends with a semicolon, but the compound statement itself does not. 17 Compound Statements Example of a compound statement used inside an if statement: if (line_num == MAX_LINES) { line_num = 0; page_num++; Compound statements are also common in loops and other places where the syntax of C requires a single statement. 18 9

10 The else Clause An if statement may have an else clause: if ( expression ) statement else statement The statement that follows the word else is executed if the expression has the value 0. Example: if (i > j) max = i; else max = j; 19 The else Clause When an if statement contains an else clause, where should the else be placed? Many C programmers align it with the if at the beginning of the statement. Inner statements are usually indented, but if they re short they can be put on the same line as the if and else: if (i > j) max = i; else max = j; 20 10

11 The else Clause It s not unusual for if statements to be nested inside other if statements: if (i > j) if (i > k) max = i; else max = k; else if (j > k) max = j; else max = k; Aligning each else with the matching if makes the nesting easier to see. 21 The else Clause To avoid confusion, don t hesitate to add braces: if (i > j) { if (i > k) max = i; else max = k; else { if (j > k) max = j; else max = k; 22 11

12 The else Clause Some programmers use as many braces as possible inside if statements: if (i > j) { if (i > k) { max = i; else { max = k; else { if (j > k) { max = j; else { max = k; 23 The else Clause Advantages of using braces even when they re not required: Makes programs easier to modify, because more statements can easily be added to any if or else clause. Helps avoid errors that can result from forgetting to use braces when adding statements to an if or else clause

13 Cascaded if Statements A cascaded if statement is often the best way to test a series of conditions, stopping as soon as one of them is true. Example: if (n < 0) printf("n is less than 0\n"); else if (n == 0) printf("n is equal to 0\n"); else printf("n is greater than 0\n"); 25 Cascaded if Statements Although the second if statement is nested inside the first, C programmers don t usually indent it. Instead, they align each else with the original if: if (n < 0) printf("n is less than 0\n"); else if (n == 0) printf("n is equal to 0\n"); else printf("n is greater than 0\n"); 26 13

14 Cascaded if Statements This layout avoids the problem of excessive indentation when the number of tests is large: if ( expression ) statement else if ( expression ) statement else if ( expression ) statement else statement 27 Program: Calculating a Broker s Commission When stocks are sold or purchased through a broker, the broker s commission often depends upon the value of the stocks traded. Suppose that a broker charges the amounts shown in the following table: Transaction size Commission rate Under \$2,500 \$ % \$2,500 \$6,250 \$ % \$6,250 \$20,000 \$ % \$20,000 \$50,000 \$ % \$50,000 \$500,000 \$ % Over \$500,000 \$ % The minimum charge is \$

15 Program: Calculating a Broker s Commission The broker.c program asks the user to enter the amount of the trade, then displays the amount of the commission: Enter value of trade: Commission: \$ The heart of the program is a cascaded if statement that determines which range the trade falls into. 29 broker.c /* Calculates a broker's commission */ #include <stdio.h> int main(void) { float commission, value; printf("enter value of trade: "); scanf("%f", &value); if (value < f) commission = 30.00f +.017f * value; else if (value < f) commission = 56.00f f * value; else if (value < f) 00f) commission = 76.00f f * value; else if (value < f) commission = f f * value; else if (value < f) commission = f f * value; else commission = f f * value; 30 15

16 if (commission < 39.00f) commission = 39.00f; printf("commission: \$%.2f\n", commission); return 0; 31 The Dangling else Problem When if statements are nested, the dangling else problem pobe may ayoccu: occur: if (y!= 0) if (x!= 0) result = x / y; else printf("error: y is equal to 0\n"); The indentation suggests that the else clause belongs to the outer if statement. However, C follows the rule that an else clause belongs to the nearest if statement that hasn t already been paired with an else

17 The Dangling else Problem A correctly indented version would look like this: if (y!= 0) if (x!= 0) result = x / y; else printf("error: y is equal to 0\n"); 33 The Dangling else Problem To make the else clause part of the outer if statement, we can enclose the inner if statement in braces: if (y!= 0) { if (x!= 0) result = x / y; else printf("error: y is equal to 0\n"); Using braces in the original if statement would have avoided the problem in the first place

18 Conditional Expressions C s conditional operator allows an expression to produce one of two values depending on the value of a condition. The conditional operator consists of two symbols (? and :), which must be used together: expr1? expr2 : expr3 The operands can be of any type. The resulting expression is said to be a conditional expression. 35 Conditional Expressions The conditional operator requires three operands, so it is often referred to as a ternary operator. The conditional expression expr1? expr2 : expr3 should be read if expr1 then expr2 else expr3. The expression is evaluated in stages: expr1 is evaluated first; if its value isn t zero, then expr2 is evaluated, and its value is the value of the entire conditional expression. If the value of expr1 is zero, then the value of expr3 is the value of the conditional

19 Example: int i, j, k; Conditional Expressions i = 1; j = 2; k = i > j? i : j; /* k is now 2 */ k = (i >= 0? i : 0) + j; /* k is now 3 */ The parentheses are necessary, because the precedence of the conditional operator is less than that of the other operators discussed so far, with the exception of the assignment operators. 37 Conditional Expressions Conditional expressions tend to make programs shorter but harder to understand, so it s probably best to use them sparingly. Conditional expressions are often used in return statements: return i > j? i : j; 38 19

20 Conditional Expressions Calls of printf can sometimes benefit from condition expressions. Instead of if (i > j) printf("%d\n", i); else printf("%d\n", j); we could simply write printf("%d\n", i > j? i : j); Conditional expressions are also common in certain kinds of macro definitions. 39 Boolean Values in C89 For many years, the C language lacked a proper Boolean type, and there e is none defined ed in the C89 standard. One way to work around this limitation is to declare an int variable and then assign it either 0 or 1: int flag; flag = 0; flag = 1; Although this scheme works, it doesn t contribute much to program readability

21 Boolean Values in C89 To make programs more understandable, C89 programmers often define macros with names such as TRUE and FALSE: #define TRUE 1 #define FALSE 0 Assignments to flag now have a more natural appearance: flag = FALSE; flag = TRUE; 41 Boolean Values in C89 To test whether flag is true, we can write if (flag == TRUE) or just if (flag) The latter form is more concise. It also works correctly if flag has a value other than 0 or 1. To test twhether flag is false, we can write if (flag == FALSE) or if (!flag) 42 21

22 Boolean Values in C89 Carrying this idea one step further, we might even define a macro that can be used as a type: #define BOOL int BOOL can take the place of int when declaring Boolean variables: BOOL flag; It s now clear that flag isn t an ordinary integer variable, but instead represents a Boolean condition. 43 Boolean Values in C99 C99 provides the _Bool type. A Boolean variable can be declared by writing _Bool flag; _Bool is an integer type, so a _Bool variable is really just an integer variable in disguise. Unlike an ordinary integer variable, however, a _Bool variable can only be assigned 0 or 1. Attempting to store a nonzero value into a _Bool variable will cause the variable to be assigned 1: flag = 5; /* flag is assigned 1 */ 44 22

23 Boolean Values in C99 It s legal (although not advisable) to perform arithmetic on _Bool variables. It s also legal to print a _Bool variable (either 0 or 1 will be displayed). And, of course, a _Bool variable can be tested in an if statement: if (flag) /* tests whether flag is 1 */ 45 Boolean Values in C99 C99 s <stdbool.h> header makes it easier to work with Boolean values. It defines a macro, bool, that stands for _Bool. If <stdbool.h> is included, we can write bool flag; /* same as _Bool flag; */ <stdbool.h> also supplies macros named true and false, which stand for 1 and 0, respectively, making it possible to write flag = false; flag = true; 46 23

24 The switch Statement A cascaded if statement can be used to compare an expression ess against a series es of values: if (grade == 4) printf("excellent"); else if (grade == 3) printf("good"); else if (grade == 2) printf("average"); else if (grade == 1) printf("poor"); else if (grade == 0) printf("failing"); else printf("illegal grade"); 47 The switch Statement The switch statement is an alternative: switch (grade) { case 4: printf("excellent"); break; case 3: printf("good"); break; case 2: printf("average"); break; case 1: printf("poor"); break; case 0: printf("failing"); break; default: printf("illegal grade"); break; 48 24

25 The switch Statement A switch statement may be easier to read than a cascaded if statement. switch statements are often faster than if statements. Most common form of the switch statement: switch ( expression ) { case constant-expression : statements case constant-expression : statements default : statements 49 The switch Statement The word switch must be followed by an integer expression the controlling expression inin parentheses. Characters are treated as integers in C and thus can be tested in switch statements. Floating-point numbers and strings don t qualify, however

26 The switch Statement Each case begins with a label of the form case constant-expression : A constant expression is much like an ordinary expression except that it can t contain variables or function calls. 5is a constant expression, and 5+10is a constant expression, but n + 10 isn t a constant expression (unless n is a macro that represents a constant). The constant expression in a case label must evaluate to an integer (characters are acceptable). 51 The switch Statement After each case label comes any number of statements. No braces are required around the statements. The last statement in each group is normally break

27 The switch Statement Duplicate case labels aren t allowed. The order of the cases doesn t matter, and the default case doesn t need to come last. Several case labels may precede a group of statements: switch (grade) { case 4: case 3: case 2: case 1: printf("passing"); break; case 0: printf("failing"); break; default: printf("illegal grade"); break; 53 The switch Statement To save space, several case labels can be put on the same line: switch (grade) { case 4: case 3: case 2: case 1: printf("passing"); break; case 0: printf("failing"); break; default: printf("illegal grade"); break; If the default case is missing and the controlling expression s value doesn t match any case label, control passes to the next statement after the switch

28 The Role of the break Statement Executing a break statement causes the program to break out of the switch statement; execution continues at the next statement after the switch. The switch statement is really a form of computed jump. When the controlling expression is evaluated, control jumps to the case label matching the value of the switch expression. A case label is nothing more than a marker indicating a position within the switch. 55 The Role of the break Statement Without break (or some other jump statement) at the end of a case, control o will flow into the next case. Example: switch (grade) { case 4: printf("excellent"); case 3: printf("good"); case 2: printf("average"); case 1: printf("poor"); case 0: printf("failing"); default: printf("illegal grade"); If the value of grade is 3, the message printed is GoodAveragePoorFailingIllegal grade 56 28

29 The Role of the break Statement Omitting break is sometimes done intentionally, but it s usually yjust an oversight. It s a good idea to point out deliberate omissions of break: switch (grade) { case 4: case 3: case 2: case 1: num_passing++; /* FALL THROUGH */ case 0: total_grades++; break; Although the last case never needs a break statement, including one makes it easy to add cases in the future. 57 Program: Printing a Date in Legal Form Contracts and other legal documents are often dated in the following ow gway: Dated this day of, 20. The date.c program will display a date in this form after the user enters the date in month/day/year form: Enter date (mm/dd/yy): 7/19/14 Dated this 19th day of July, The program uses switch statements to add th (or st or nd or rd ) to the day, and to print the month as a word instead of a number

30 date.c /* Prints a date in legal form */ #include <stdio.h> int main(void) { int month, day, year; printf("enter date (mm/dd/yy): "); scanf("%d /%d /%d", &month, &day, &year); printf("dated this %d", day); switch (day) { case 1: case 21: case 31: printf("st"); break; case 2: case 22: printf("nd"); break; case 3: case 23: printf("rd"); break; default: printf("th"); break; printf(" day of "); 59 switch (month) { case 1: printf("january"); break; case 2: printf("february"); break; case 3: printf("march"); break; case 4: printf("april"); break; case 5: printf("may"); break; case 6: printf("june"); break; case 7: printf("july"); break; case 8: printf("august"); break; case 9: printf("september"); break; case 10: printf("october"); break; case 11: printf("november"); break; case 12: printf("december"); break; printf(", 20%.2d.\n", year); return 0; 60 30

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions

Chapter 2: Problem Solving Using C++

Chapter 2: Problem Solving Using C++ 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common

Going from Python to C

Going from Python to C Darin Brezeale December 8, 2011 Python is a high-level, interpreted language. C has many of the same types of programming constructs as in Python: arrays, loops, conditionals, functions,

switch Multiple-Selection Statement

switch Multiple-Selection Statement (This feature is rarely useful, although it s perfect for programming the iterative song The Twelve Days of Christmas!) If no match occurs, the default case is executed,

Chapter 4 Operators & Arithmetic

Chapter 4 Operators & Arithmetic 4-1 Arithmetic in C++ Arithmetic expressions can be made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition)

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

Control Structure. Pseudocode: Input number If number is even Then Print even Else print odd. Flowchart: Begin. End. Print Odd. number even?

Control Structure Normally, a program is executed in a sequential manner.however, in many cases, a program has to choose among alternative statements C++ provides constructs that enable the programmer

Boolean Variables and Expressions

Boolean Variables and Expressions 1 Recall Standard C++ supports a simple data type specialized for representing logical values. bool type variables can have either of two values: or The identifiers and

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors

14 MAKING DECISIONS IN C

14 MAKING DECISIONS IN C 14.1 INTRODUCTION So far we have seen that in C programs the instructions are executed in the same order in which they appear in the program. Each instruction is executed once

Boolean Data Outline

1. Boolean Data Outline 2. Data Types 3. C Boolean Data Type: char or int 4. C Built-In Boolean Data Type: bool 5. bool Data Type: Not Used in CS1313 6. Boolean Declaration 7. Boolean or Character? 8.

Chapter 5. Selection 5-1

Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

Object Oriented Software Design

Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

Selection: if Statement

: if Statement The simplest selection structure in C++ is the if statement. Syntactically: 1 if The Boolean expression must be enclosed in parentheses, and

NRI Institute of Technology Principles of Programming Languages III B.Tech I Sem (R09)-CSE

Unit-4 Expressions and Assignment Statements Introduction Expressions are the fundamental means of specifying computations in a programming language. To understand expression evaluation, need to be familiar

Indicates the end of data when the number of data is not known in advance Must be distinct from the data but be of the same type

Program Control Essentials of repetition Loop control variable Counts the number of repetitions in the counter-controlled loop Controls the execution of loop Sentinel value Indicates the end of data when

Lecture 2 Notes: Flow of Control

6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The

CMSC 106 Introduction to C Programming

CMSC 106 Introduction to C Programming Math Library, Escape Sequences, Conditionals CMSC 106 - Slides developed by Jan Plane with some modifications by Nelson Padua-Perez Additional Operators Increment

Dept. of CSE, IIT KGP

Programming in C: Basics CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of variable We must declare the

JavaScript: Control Statements I

1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

6.087 Lecture 3 January 13, 2010

6.087 Lecture 3 January 13, 2010 Review Blocks and Compound Statements Control Flow Conditional Statements Loops Functions Modular Programming Variable Scope Static Variables Register Variables 1 Review:

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University (revised October 8, 2004) 1 Introduction The PCAT language (Pascal Clone

Two-way selection. Branching and Looping

Control Structures: are those statements that decide the order in which individual statements or instructions of a program are executed or evaluated. Control Structures are broadly classified into: 1.

Conditions & Boolean Expressions

Conditions & Boolean Expressions 1 In C++, in order to ask a question, a program makes an assertion which is evaluated to either true (nonzero) or false (zero) by the computer at run time. Example: In

Statements and Control Flow

Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

C / C++ and Unix Programming Materials adapted from Dan Hood and Dianna Xu 1 C and Unix Programming Today s goals ú History of C ú Basic types ú printf ú Arithmetic operations, types and casting ú Intro

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 2: Basic Elements of C++

C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with the basic components of a C++ program,

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

Boolean Expressions & the if Statement

Midterm Results Boolean Expressions & the if Statement September 24, 2007 Average: 91.6 Median: 94 Standard Deviation: 18.80 Maximum: 129 (out of 130) ComS 207: Programming I (in Java) Iowa State University,

Chapter 3 Operators and Control Flow

Chapter 3 Operators and Control Flow I n this chapter, you will learn about operators, control flow statements, and the C# preprocessor. Operators provide syntax for performing different calculations or

A relational operator is used to make comparison between two expressions. All these operators are binary and require two operands.

Control Structures in C++ Index Control Structures in C++ 3.1 Relational Operators A relational operator is used to make comparison between two expressions. All these operators are binary and require two

CSI 333 Lecture 2 Introduction to C: Part I 2 1 / 16

CSI 333 Lecture 2 Introduction to C: Part I 2 1 / 16 Basics of C Remark: Skim Chapters 1 through 6 of Deitel & Deitel. You will notice the following: C is (more or less) a subset of Java. (So, you are

C Control Statements : Branching and jumps

C Control Statements : Branching and jumps Using Bloodshed Dev-C++ Heejin Park Hanyang University 2 Introduction The if Statement Adding else to the if Statement Let's Get Logical A Word-Count Program

E91 Embedded System. Intro

E91 Embedded System Intro Why embedded systems? Big bang-for-the-buck buck by adding some intelligence to systems. Embedded Systems are ubiquitous. Embedded Systems more common as prices drop, and power

Chapter 8 Statement-Level Control Structures Chapter 8 Topics

Chapter 8 Statement-Level Control Structures Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Chapter 8 Statement-Level Control Structures Introduction A

COMPSCI 210 Part II Decisions & Iterations

Agenda COMPSCI 210 Part II Decisions & Iterations Based on slides @ McGraw-Hill Agenda: Decision-making statements: he if statement he switch statement Iterations he for statement he while statement he

Example of a Java program

Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

Object Oriented Software Design

Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

C Programming Dr. Hasan Demirel

C How to Program, H. M. Deitel and P. J. Deitel, Prentice Hall, 5 th edition (3 rd edition or above is also OK). Introduction to C Programming Dr. Hasan Demirel Programming Languages There are three types

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

Selection Structures: If and Switch Statements

Selection Structures: If and Switch Statements Chuan-Ming Liu Computer Science & Information Engineering National Taipei University of Technology Taiwan 1 Outline Control Structures Conditions The If Statement

UNIT-1. C Programming & Data Structures. Introduction to Computers: Computing Environment: Types of Computing Environments:

Introduction to Computers: C Programming & Data Structures UNIT-1 A computer system consists of hardware and software. Computer hardware is the collection of physical elements that comprise a computer

1. A(n) structure is a logical design that controls the order in which a set of statements execute. a. function b. control c. sequence d.

Chapter Four MULTIPLE CHOICE 1. A(n) structure is a logical design that controls the order in which a set of statements execute. a. function b. control c. sequence d. iteration 2. The decision structure

Introduction to Programming

Introduction to Programming SS 2012 Adrian Kacso, Univ. Siegen adriana.dkacsoa@duni-siegena.de Tel.: 0271/740-3966, Office: H-B 8406 Stand: April 25, 2012 Betriebssysteme / verteilte Systeme Introduction

3/13/2012. Writing Simple C Programs. ESc101: Decision making using if-else and switch statements. Writing Simple C Programs

Writing Simple C Programs ESc101: Decision making using if- and switch statements Instructor: Krithika Venkataramani Semester 2, 2011-2012 Use standard files having predefined instructions stdio.h: has

1. Constants. 2. Variables. 3. Reserved words or key words. 4. Constants. Character set in C

Character set in C We should use only the following characters in writing a C program. These characters can be combined to create C words. Alphabet: A, B, C, D.. Z, a, b, c, d..z Numeric digits: 0, 1,

Command Scripts. 13.1 Running scripts: include and commands

13 Command Scripts You will probably find that your most intensive use of AMPL s command environment occurs during the initial development of a model, when the results are unfamiliar and changes are frequent.

Programming Fundamental. Instructor Name: Lecture-2

Programming Fundamental Instructor Name: Lecture-2 Today s Lecture What is Programming? First C++ Program Programming Errors Variables in C++ Primitive Data Types in C++ Operators in C++ Operators Precedence

Fundamentals of Programming

Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language

Programming for MSc Part I

Herbert Martin Dietze University of Buckingham herbert@the-little-red-haired-girl.org July 24, 2001 Abstract The course introduces the C programming language and fundamental software development techniques.

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

C Control Structures. Chapter 13

C Control Structures Chapter 13 Cyrus Bazeghi Conditional Control Structures making a decision about which code to execute, based on evaluated expression if Iterative if-else switch executing code multiple

arrays C Programming Language - Arrays

arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

1. Boolean Data Type & Expressions Outline. Basic Data Types. Numeric int float Non-numeric char

Boolean Data Type & Expressions Outline. Boolean Data Type & Expressions Outline 2. Basic Data Types 3. C Boolean Data Types: char or int/ Boolean Declaration 4. Boolean or Character? 5. Boolean Literal

Chapter 2: Elements of Java

Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

GETTING STARTED WITH C++ C++ BASICS - 1 -

- 1 - GETTING STARTED WITH C++ Programming is a core activity in the process of performing tasks or solving problems with the aid of a computer. An idealised picture is: PROBLEM COMPUTER SOLUTION Unfortunately

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

Chapter 8 Selection 8-1

Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

CMPSCI 119 Python Review Sheet Professor William T. Verts. line break (can contain " or '). N = [1, 2.3, "Hello"]

Variables, Data Types, Computations, and Assignment variable = expression Variable is assigned the value on right, data type of variable becomes data type of value (variables may change type). N = 5 Variable

Writing Control Structures

Writing Control Structures Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 5-1 Objectives After completing this lesson, you should be able to do the following: Identify

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

Fundamentals of Python: First Programs. Chapter 3: Control Statements modifications by Mr. Dave Clausen

Fundamentals of Python: First Programs Chapter 3: Control Statements modifications by Mr. Dave Clausen Objectives After completing this chapter, you will be able to: Write a loop to repeat a sequence of

C AND C++ PROGRAMMING

C AND C++ PROGRAMMING Bharathidasan University A Courseware prepared by University Informatics Centre Part I - Programming in C Getting Started This courseware is intended to be an introduction to C programming

School of Informatics, University of Edinburgh

CS1Ah Lecture Note 5 Java Expressions Many Java statements can contain expressions, which are program phrases that tell how to compute a data value. Expressions can involve arithmetic calculation and method

The design recipe. Programs as communication. Some goals for software design. Readings: HtDP, sections 1-5

The design recipe Readings: HtDP, sections 1-5 (ordering of topics is different in lectures, different examples will be used) Survival and Style Guides CS 135 Winter 2016 02: The design recipe 1 Programs

Decision Logic: if, if else, switch, Boolean conditions and variables

CS 1044 roject 3 Fall 2009 Decision Logic: if, if else, switch, Boolean conditions and variables This programming assignment uses many of the ideas presented in sections 3 through 5 of the Dale/Weems text

Adjusted/Modified by Nicole Tobias. Chapter 2: Basic Elements of C++

Adjusted/Modified by Nicole Tobias Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types

The Basics of C Programming. Marshall Brain

The Basics of C Programming Marshall Brain Last updated: October 30, 2013 Contents 1 C programming 1 What is C?................................. 2 The simplest C program, I........................ 2 Spacing

Introduction to Python

Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment

1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

Boolean Expressions Boolean Expressions Sometimes a programmer would like one statement, or group of statements to execute only if certain conditions are true. There may be a different statement, or group

Branching. We ll continue to look at the basics of writing C++ programs including. Overview

Branching Overview We ll continue to look at the basics of writing C++ programs including Boolean Expressions (need to know this before we can using branching and looping!) Branching J.S. Bradbury CSCI

EC312 Chapter 4: Arrays and Strings

Objectives: (a) Describe how an array is stored in memory. (b) Define a string, and describe how strings are stored. EC312 Chapter 4: Arrays and Strings (c) Describe the implications of reading or writing

J a v a Quiz (Unit 3, Test 0 Practice)

Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control Reading: Bowman, Chapters 16 CODE BLOCKS A code block consists of several lines of code contained between a BEGIN

Java Review (Essentials of Java for Hadoop)

Java Review (Essentials of Java for Hadoop) Have You Joined Our LinkedIn Group? What is Java? Java JRE - Java is not just a programming language but it is a complete platform for object oriented programming.

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

CompSci 125 Lecture 08 Chapter 5: Conditional Statements Chapter 4: return Statement Homework Update HW3 Due 9/20 HW4 Due 9/27 Exam-1 10/2 Programming Assignment Update p1: Traffic Applet due Sept 21 (Submit

Conditionals (with solutions)

Conditionals (with solutions) For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations: final int MAX = 25, LIMIT = 100; int num1 = 12, num2 = 25, num3 = 87;

Which of the following is the correct operator to compare two variables? A. := B. = C. equal D. ==

Group 1 Question 1. What is the correct value to return to the operating system upon the successful completion of a program? A. -1 B. 1 C. 0 D. Programs do not return a value. Question 2. What is the only

Outline TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA. What is DrJava? Dr Java

1 Outline TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

Borland C++ Compiler: Operators

Introduction Borland C++ Compiler: Operators An operator is a symbol that specifies which operation to perform in a statement or expression. An operand is one of the inputs of an operator. For example,

Conditional and Looping Construct

Chapter 3 Conditional and Looping Construct After studying this lesson, students will be able to: Understand the concept and usage of selection and iteration statements. Know various types of loops available

Chapter 3: Writing C# Expressions

Page 1 of 19 Chapter 3: Writing C# Expressions In This Chapter Unary Operators Binary Operators The Ternary Operator Other Operators Enumeration Expressions Array Expressions Statements Blocks Labels Declarations

PE1 Worksheet. 3) What are the three control structures for writing an algorithm in pseudocode?

PE1 Worksheet Problem solving 1) What are the four stages of problem solving by programming? What shall be done in each stage? Stage 1: Stage 2: Stage 3: Stage 4: 2) What is the top-down design strategy

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 UX Software - 2009 TABLE OF CONTENTS INTRODUCTION... ii What is this book about?... iii How to use this book... iii Time to start...

Tutorial on C Language Programming

Tutorial on C Language Programming Teodor Rus rus@cs.uiowa.edu The University of Iowa, Department of Computer Science Introduction to System Software p.1/64 Tutorial on C programming C program structure:

Chapter 8. Statement-Level Control Structures

Chapter 8 Statement-Level Control Structures Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions 8-2 1 Levels of Control Flow Within

CS 241 Data Organization Coding Standards

CS 241 Data Organization Coding Standards Brooke Chenoweth University of New Mexico Spring 2016 CS-241 Coding Standards All projects and labs must follow the great and hallowed CS-241 coding standards.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

Today s Lecture. SYS-1A4Y Programming - Languages and Software Construction. Conditional Execution. Conditional Execution.

SYS-1A4Y Programming - Languages and Software Construction Dr Gavin Cawley Lecture 9 - Selection Today s Lecture In the previous lectures: Using objects Strings NumberFormat In this lecture: Relational

C-Sheep (v0.2) Reference 2006 Eike Anderson & Leigh McLoughlin

The C-Sheep Programming Language Introduction This text is a reference for the C-Sheep programming language. C-Sheep is a member of the family of mini-languages 1 (toy languages) used for teaching programming

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011

6.096 Lab 1 Due: 7 January 1:30:00 September 0, 011 1 Additional Material 1.1 Constants A constant is an expressions with a fixed value. Kinds of constants: Literals: used to express particular values