Loops Control Flow (Order of Execution) 5.2 the While Loop While

Total Page:16

File Type:pdf, Size:1020Kb

Loops Control Flow (Order of Execution) 5.2 the While Loop While Control Flow Loops (order of execution) • So far, control flow in our programs has included: Unit 4 ‣ sequential processing (1st statement, then 2nd statement…) Sections 5.2-12 ‣ branching (conditionally skip some statements). CS 1428 • Chapter 5 introduces loops, which allow us to Fall 2017 conditionally repeat execution of some statements. Jill Seaman ‣ while loop ‣ do-while loop ‣ for loop 1 2 5.2 The while loop while syntax and semantics l As long as the relational expression is true, repeat • The while statement is used to repeat the statement statements: while (expression) statement • How it works: ‣ expression is evaluated: ‣ If it is true, then statement is executed, then it starts over (and expression is evaluated again). ‣ If it is false, then statement is skipped (and the loop is done). 3 4 while example 5.3 Using while for input validation • Example: • Inspect user input values to make sure they are Hand trace! valid. int number = 1; • If not valid, ask user to re-enter value: while (number <= 3) { int number; This expression is true when cout << “Student” << number << endl; number is OUT of range. number = number + 1; cout << “Enter a number between 1 and 10: “; } cin >> number; Explain the valid values in the prompt cout << “Done” << endl; while (number < 1 || number > 10) { cout << “Please enter a number between 1 and 10: “; cin >> number; } Don’t forget to input • Output Student1 the next value Student2 // Do something with number here Student3 Done 5 6 Input Validation 5.4 Counters l Checking for valid characters: l Counter: a variable that is incremented (or char answer; decremented) each time a loop repeats. cout << “Enter the answer to question 1 (a,b,c or d): “; cin >> answer; l Used to keep track of the number of iterations while (answer != ‘a’ && answer != ‘b’ && (how many times the loop has repeated). answer != ‘c’ && answer != ‘d’) { cout << “Please enter a letter a, b, c or d: “; cin >> answer; } l Must be initialized before entering loop!!!! // Do something with answer here 7 8 Counters Counters l Example (how many times does the user enter l Example, using the counter to control how an invalid number?): many times the loop iterates: cout << “Number Number Squared” << endl; int number; cout << “------ --------------” << endl; int count = 0; cout << “Enter a number between 1 and 10: “; int num = 1; // counter variable cin >> number; while (num <= 8) { cout << num << “ “ << (num * num) << endl; while (number < 1 || number > 10) { num = num + 1; // increment the counter count = count + 1; cout << “Please enter a number between 1 and 10: “; } cin >> number; } Number Number Squared ------ -------------- cout << count << “ invalid numbers were entered.“ << endl; l Output: 1 1 // Do something with number here 2 4 3 9 4 16 5 25 6 36 9 7 49 10 8 64 5.5 The do-while loop do-while syntax and semantics l Execute the statement(s), then repeat as long as • The do-while loop has the test expression at the relational expression is true. the end: Don’t forget the do semicolon at the end statement while (expression); • How it works: ‣ statement is executed. ‣ expression is evaluated: ‣ If it is true, then it starts over (and statement is executed again). ‣ If (when) it is false, the loop is done. 11 • statement always executes at least once. 12 do-while example do-while with menu char choice; • Example: do { cout << “A: Make a reservation.” << endl; int number = 1; cout << “B: View flight status.” << endl; do cout << “C: Check-in for a flight.” << endl; { cout << “D: Quit the program.” << endl; cout << “Student” << number << endl; cout << “Enter your choice: “; number = number + 1; } while (number <= 3); cin >> choice; cout << “Done” << endl; switch (choice) { case ‘A’: // code to make a reservation break; case ‘B’: // code to view flight status • Output Student1 break; Student2 case ‘C’: // code to process check-in Student3 break; Done } 13 } while(choice != ‘D’); 14 Different ways to control the loop 5.6 The for loop • The for statement is used to easily implement a l Conditional loop: body executes as long as a count-controlled loop. certain condition is true ‣ input validation: loops as long as input is invalid for (expr1; expr2; expr3) statement l Count-controlled loop: body executes a specific number of times using a counter • How it works: 1. expr1 is executed (initialization) ‣ actual count may be a literal, or stored in a variable. 2. expr2 is evaluated (test) l Count-controlled loop follows a pattern: 3. If it is true, then statement is executed, ‣ initialize counter to zero (or other start value). then expr3 is executed (update), then go to step 2. ‣ test counter to make sure it is less than count. 4. If (when) it is false, then statement is skipped ‣ update counter during each iteration. 15 (and the loop is done). 16 The for loop flow chart The for loop and the while loop for (expr1; expr2; expr3) • The for statement statement for (expr1; expr2; expr3) statement • expr1 is equivalent to the following code using a while statement: expr1; // initialize while (expr2) { // test expr2 statement expr3 statement expr3; // update } 17 18 for loop example Counters: redo l Example, using the counter to control how • Example: Equivalent to number = number + 1 many times the loop iterates: cout << “Number Number Squared” << endl; int number; cout << “------ --------------” << endl; for (number = 1; number <= 3; number++) { int num = 1; // counter variable cout << “Student” << number << endl; while (num <= 8) { Note: no semicolon cout << num << “ “ << (num * num) << endl; } num = num + 1; // increment the counter } cout << “Done” << endl; l Rewritten using a for loop: cout << “Number Number Squared” << endl; • Output Student1 cout << “------ --------------” << endl; Student2 Student3 int num; Done for (num = 1; num <= 8; num++) cout << num << “ “ << (num * num) << endl; 19 20 Define variable in init-expr User-controlled count • You may define the loop counter variable inside • You may use a value input by the user to the for loop’s initialization expression: control the number of iterations: int maxCount; for (int x = 10; x > 0; x=x-2) Hand trace! cout << “How many squares do you want?” << endl; cout << x << endl; cin >> maxCount; cout << x << endl; //ERROR, can’t use x here cout << “Number Number Squared” << endl; cout << “------ --------------” << endl; for (int num = 1; num <= maxCount; num++) • Do NOT try to access x outside the loop cout << num << “ “ << (num * num) << endl; (the scope of x is the for loop statement ONLY) • What is the output of the for loop? • How many times does the loop iterate? 21 22 The exprs in the for are optional Loops in C++ (review) statement may be a • You may omit any of the three exprs in the for • while while (expression) compound statement loop header statement (a block: {statements}) int value, incr; ‣ if expression is true, statement is executed, repeat cout << “Enter the starting value: “; cin >> value; • for for (expr1; expr2; expr3) statement for ( ; value <= 100; ) { ‣ equivalent to: expr1; cout << “Please enter the next increment amount: “; while (expr2) { cin >> incr; statement value = value + incr; expr3; cout << value << endl; } } • do while • Style: use a while loop for something like this. do statement is executed. statement if expression is true, then repeat while (expression); • When expr2 is missing, it is true by default.23 24 Common tasks solved Counting using loops (review) l set a counter variable to 0 l Counting l increment it inside the loop (each iteration) l Summing l after each iteration of the loop, it stores the # of l Calculating an average (the mean value) loop iterations so far l int number; Read input until “sentinel value” is encountered int count = 0; cout << “Enter a number between 1 and 10: “; l Read input from a file until the end of the file is cin >> number; encountered while (number < 1 || number > 10) { count = count + 1; cout << “Please enter a number between 1 and 10: “; cin >> number; } cout << count << “ invalid numbers entered “ << endl; // Do something with number here 25 26 5.7 Keeping a running total Keeping a running total (summing) l After each iteration of the loop, it stores the sum • Output: of the numbers added so far (running total) How many days did you ride you bike? 3 l set an accumulator variable to 0 Enter the miles for day 1: 14.2 Enter the miles for day 2: 25.4 l Enter the miles for day 3: 12.2 add the next number to it inside the loop Total miles ridden: 51.8 int days; //Count for count-controlled loop float total = 0.0; //Accumulator float miles; //daily miles ridden cout << “How many days did you ride your bike? “; cin >> days; • How would you calculate the average mileage? for (int i = 1; i <= days; i++) { cout << “Enter the miles for day “ << i << “: ”; cin >> miles; total = total + miles; } total is 0 first time through cout << “Total miles ridden: “ << total << endl; 27 28 5.8 Sentinel controlled loop Sentinel example l sentinel: special value in a list of values that • Example: indicates the end of the data float total = 0.0; //Accumulator float miles; //daily miles ridden l sentinel value must not be a valid value! cout << “Enter the miles you rode on your bike each day, “; -99 for a test score, -1 for miles ridden cout << “then enter -1 when finished. “ << endl; cin >> miles; //priming read l User does not need to count how many values while (miles != -1) { total = total + miles; //skipped when miles==-1 will be entered cin >> miles; //get the next one } l Requires a “priming read” before the loop starts cout << “Total miles ridden: “ << total << endl; ‣ so the sentinel is NOT included in the sum Enter the miles you rode on your bike each day, • Output: then enter -1 when finished.
Recommended publications
  • C++ Programming: Program Design Including Data Structures, Fifth Edition
    C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: • Learn about repetition (looping) control structures • Explore how to construct and use count- controlled, sentinel-controlled, flag- controlled, and EOF-controlled repetition structures • Examine break and continue statements • Discover how to form and use nested control structures C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2 Objectives (cont'd.) • Learn how to avoid bugs by avoiding patches • Learn how to debug loops C++ Programming: From Problem Analysis to Program Design, Fifth Edition 3 Why Is Repetition Needed? • Repetition allows you to efficiently use variables • Can input, add, and average multiple numbers using a limited number of variables • For example, to add five numbers: – Declare a variable for each number, input the numbers and add the variables together – Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers C++ Programming: From Problem Analysis to Program Design, Fifth Edition 4 while Looping (Repetition) Structure • The general form of the while statement is: while is a reserved word • Statement can be simple or compound • Expression acts as a decision maker and is usually a logical expression • Statement is called the body of the loop • The parentheses are part of the syntax C++ Programming: From Problem Analysis to Program Design, Fifth Edition 5 while Looping (Repetition)
    [Show full text]
  • 7. Control Flow First?
    Copyright (C) R.A. van Engelen, FSU Department of Computer Science, 2000-2004 Ordering Program Execution: What is Done 7. Control Flow First? Overview Categories for specifying ordering in programming languages: Expressions 1. Sequencing: the execution of statements and evaluation of Evaluation order expressions is usually in the order in which they appear in a Assignments program text Structured and unstructured flow constructs 2. Selection (or alternation): a run-time condition determines the Goto's choice among two or more statements or expressions Sequencing 3. Iteration: a statement is repeated a number of times or until a Selection run-time condition is met Iteration and iterators 4. Procedural abstraction: subroutines encapsulate collections of Recursion statements and subroutine calls can be treated as single Nondeterminacy statements 5. Recursion: subroutines which call themselves directly or indirectly to solve a problem, where the problem is typically defined in terms of simpler versions of itself 6. Concurrency: two or more program fragments executed in parallel, either on separate processors or interleaved on a single processor Note: Study Chapter 6 of the textbook except Section 7. Nondeterminacy: the execution order among alternative 6.6.2. constructs is deliberately left unspecified, indicating that any alternative will lead to a correct result Expression Syntax Expression Evaluation Ordering: Precedence An expression consists of and Associativity An atomic object, e.g. number or variable The use of infix, prefix, and postfix notation leads to ambiguity An operator applied to a collection of operands (or as to what is an operand of what arguments) which are expressions Fortran example: a+b*c**d**e/f Common syntactic forms for operators: The choice among alternative evaluation orders depends on Function call notation, e.g.
    [Show full text]
  • While Statement in C
    While Statement In C EnricoIs Reg alwaysdisheartening deplete or his novel aspects when chagrined luminesced disputatiously, some crayfishes he orbits clump so temporizingly? grindingly. Solid Ring-necked and comose Bennet Brendan tarnishes never tensehalf-and-half his Stuttgart! while Thank you use a counter is a while loop obscures the condition which is evaluated to embed videos in while c program C while loops statement allows to repeatedly run at same recipient of code until a wrap is met while loop is empty most basic loop in C programming while loop. We then hand this variable c in the statement block and represent your value for each. While adultery in C Set of instructions given coil the compiler to night set of statements until condition becomes false is called loops. If it is negative number added to the condition in c language including but in looping structures, but is executed infinite loop! While Loop Definition Example & Results Video & Lesson. While talking in C Know Program. What is the while eternal in C? A while loop around loop continuously and infinitely until the policy inside the parenthesis becomes false money must guard the. C while and dowhile Loop Programiz. Programming While Loop. The widow while redeem in the C language is basically a post tested loop upon the execution of several parts of the statements can be repeated by reckless use children do-while. 43 Loops Applications in C for Engineering Technology. Do it Loop in C Programming with Examples Phptpoint. Statements and display control C Tutorials Cpluspluscom. Do while just in c example program.
    [Show full text]
  • Chapter 6 Flow of Control
    Chapter 6 Flow of Control 6.1 INTRODUCTION “Don't you hate code that's In Figure 6.1, we see a bus carrying the children to not properly indented? school. There is only one way to reach the school. The Making it [indenting] part of driver has no choice, but to follow the road one milestone the syntax guarantees that all after another to reach the school. We learnt in Chapter code is properly indented.” 5 that this is the concept of sequence, where Python executes one statement after another from beginning to – G. van Rossum the end of the program. These are the kind of programs we have been writing till now. In this chapter Figure 6.1: Bus carrying students to school » Introduction to Flow of Control Let us consider a program 6-1 that executes in » Selection sequence, that is, statements are executed in an order in which they are written. » Indentation The order of execution of the statements in a program » Repetition is known as flow of control. The flow of control can be » Break and Continue implemented using control structures. Python supports Statements two types of control structures—selection and repetition. » Nested Loops 2021-22 Ch 6.indd 121 08-Apr-19 12:37:51 PM 122 COMPUTER SCIENCE – CLASS XI Program 6-1 Program to print the difference of two numbers. #Program 6-1 #Program to print the difference of two input numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) diff = num1 - num2 print("The difference of",num1,"and",num2,"is",diff) Output: Enter first number 5 Enter second number 7 The difference of 5 and 7 is -2 6.2 SELECTION Now suppose we have `10 to buy a pen.
    [Show full text]
  • While and Do-While Loops
    While and Do-While Loops 15-110 Summer 2010 Margaret Reid-Miller Loops • Within a method, we can alter the flow of control using either conditionals or loops. • The loop statements while, do-while, and for allow us execute a statement(s) over and over. • Like a conditional, a loop is controlled by a boolean expression that determines how many times the statement is executed. E.g., You may want to calculate the interest paid on a mortgage for each year of the loan term. Summer 2010 15-110 (Reid-Miller) The while statement • The form of the while statement is while (<boolean_expression>) <statement> • If boolean_expression evaluates to true, then statement is executed. • Then, the boolean_expression is evaluated again. If it evaluates to true, statement is executed again. • This repetition continues until the boolean_expression evaluates to false. How is the while loop different from the if statement? Summer 2010 15-110 (Reid-Miller) The if Flowchart false boolean_expression true statement (body of loop) Summer 2010 15-110 (Reid-Miller) The while Flowchart false boolean_expression true statement (body of loop) Summer 2010 15-110 (Reid-Miller) A Example n = 5 while i output 0 Print n asterisks! i < n ? *! 1 int i = 0; ! i < n ? while (i < n) { ! ! **! System.out.print(“*”);! 2 i < n ? !i++;! ***! }! 3 i < n ? System.out.println();! ****! 4 i < n ? *****! 5 i < n ? ***** Summer 2010 15-110 (Reid-Miller) The Loop Control Variable • The variable i (known as the loop control variable) is used in three ways: it is initialized, tested, and updated.!
    [Show full text]
  • Chapter 5: Conditionals and Loops Lab Exercises
    Chapter 5: Conditionals and Loops Lab Exercises Topics Lab Exercises Boolean expressions PreLab Exercises The if statement Computing a Raise The switch statement A Charge Account Statement Activities at Lake LazyDays Rock, Paper, Scissors Date Validation Conditional Operator Processing Grades The while statement PreLab Exercises Counting and Looping Powers of 2 Factorials A Guessing Game Iterators & Reading Text Files Baseball Statistics The do statement More Guessing Election Day The for statement Finding Maximum and Minimum Values Counting Characters Using the Coin Class Drawing with loops and conditionals A Rainbow Program Determining Event Sources Vote Counter, Revisited Dialog Boxes Modifying EvenOdd.java A Pay Check Program Checkboxes & Radio Buttons Adding Buttons to StyleOptions.java Chapter 5: Conditionals and Loops 65 Prelab Exercises Sections 5.1-5.3 1. Rewrite each condition below in valid Java syntax (give a boolean expression): a. x > y > z b. x and y are both less than 0 c. neither x nor y is less than 0 d. x is equal to y but not equal to z 2. Suppose gpa is a variable containing the grade point average of a student. Suppose the goal of a program is to let a student know if he/she made the Dean's list (the gpa must be 3.5 or above). Write an if... else... statement that prints out the appropriate message (either "Congratulations—you made the Dean's List" or "Sorry you didn't make the Dean's List"). 3. Complete the following program to determine the raise and new salary for an employee by adding if ..
    [Show full text]
  • PYTHON LOOPS Rialspo Int.Co M/Pytho N/Pytho N Lo O Ps.Htm Copyrig Ht © Tutorialspoint.Com
    PYTHON LOOPS http://www.tuto rialspo int.co m/pytho n/pytho n_lo o ps.htm Copyrig ht © tutorialspoint.com There may be a situation when you need to execute a block of code several number of times. In g eneral, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Prog ramming lang uag es provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or g roup of statements multiple times and following is the g eneral form of a loop statement in most of the prog ramming lang uag es: Python prog ramming lang uag e provides following types of loops to handle looping requirements. Click the following links to check their detail. Loop Type Description while loop Repeats a statement or g roup of statements while a g iven condition is true. It tests the condition before executing the loop body. for loop Executes a sequence of statements multiple times and abbreviates the code that manag es the loop variable. nested loops You can use one or more loop inside any another while, for or do..while loop. Loop Control Statements: Loop control statements chang e execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements. Click the following links to check their detail. Control Statement Description break statement Terminates the loop statement and transfers execution to the statement immediately following the loop.
    [Show full text]
  • Smalltalk Tutorial for Java Programmers!
    SmallTalk Tutorial for Java Programmers! SmallTalk Tutorial for Java Programmers! Giovanni Giorgi <[email protected]> Jan 2002 A small paper to teach yourself the incredible Smalltalk language! It's so easy, it's so fun! 1. Introduction ● 1.1 Revision history ● 1.2 Conventions used in this paper ● 1.3 Distribution Policy ● 1.4 Why Smalltalk? ● 1.5 Background Required 2. Why Smalltalk is so strange? (or a brief history of Smalltalk) ● 2.1 Download Right Now! ● 2.2 Hello world in Smalltalk ● 2.3 Big Numbers ● 2.4 Code Blocks ● 2.5 The while loop 3. Main Differences between Java and Smalltalk http://daitanmarks.sourceforge.net/or/squeak/squeak_tutorial.html (1 of 2) [1/7/2002 20:44:13] SmallTalk Tutorial for Java Programmers! ● 3.1 Java Versus Smalltalk ● 3.2 Types? No thank you!! ● 3.3 The Squeak base library compared with Java ● 3.4 The Smalltalk Code database ● 3.5 Multiple-Inheritance 4. Ending Words ● 4.1 Going on ● 4.2 Commercial and free products list ● 4.3 References http://daitanmarks.sourceforge.net/or/squeak/squeak_tutorial.html (2 of 2) [1/7/2002 20:44:13] SmallTalk Tutorial for Java Programmers!: Introduction 1. Introduction This paper will teach you the basics of Smalltalk80 language. This tutorial suites the needs of C and Java programmers. But the tutorial can be understanded by everyone knowing a bit of C and/or OOP concepts, as we'll see. Because I will refer a lot to other books and use a lot of technical terms, I'll try to enjoy you while reading.
    [Show full text]
  • Control Flow Statements
    Control Flow Statements http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html http://math.hws.edu/javanotes/c3/index.html 1 Control Flow The basic building blocks of programs - variables, expressions, statements, etc. - can be put together to build complex programs with more interesting behavior. CONTROL FLOW STATEMENTS break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. Decision-making statements include the if statements and switch statements. There are also looping statements, as well as branching statements supported by Java. 2 Decision-Making Statements A. if statement if (x > 0) y++; // execute this statement if the expression (x > 0) evaluates to “true” // if it doesn’t evaluate to “true”, this part is just skipped // and the code continues on with the subsequent lines B. if-else statement - - gives another option if the expression by the if part evaluates to “false” if (x > 0) y++; // execute this statement if the expression (x > 0) evaluates to “true” else z++; // if expression doesn’t evaluate to “true”, then this part is executed instead if (testScore >= 90) grade = ‘A’; else if (testScore >= 80) grade = ‘B’; else if (testScore >= 70) grade = ‘C’; else if (testScore >= 60) grade = ‘D’; else grade = ‘F’; C. switch statement - - can be used in place of a big if-then-else statement; works with primitive types byte, short, char, and int; also with Strings, with Java SE7, (enclose the String with double quotes);
    [Show full text]
  • Chapter 3: Control Statements
    Chapter 3: Control Statements 3.1 Introduction In this chapter, you will learn various selection and loop control statements. Java provides selection statements that let you choose actions with two or more alternative courses. Java provides a powerful control structure called a loop, which controls how many times an operation or a sequence of operation is performed in succession. 3.2 Selection Statements Java has several types of selection statements: if Statements, if … else statements, nested if statements switch Statements Conditional Expressions 3.2.1 Simple if Statements if (booleanExpression) { statement(s); } // execution flow chart is shown in Figure (A) Example if (radius >= 0) { area = radius*radius*PI; System.out.println("The area for the circle of radius " + radius + " is " + area); } // if the Boolean expression evaluates to T, the statements in the block are executed as shown in figure (B) false false Boolean (radius >= 0) Expression true true Statement(s) area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area); (A) (B) FIGURE 3.1 An if statement executes statements if the Boolean Expression evaluates as true Note: The Boolean expression is enclosed in parentheses for all forms of the if statement. Thus, the outer parentheses in the previous if statements are required. Outer parentheses required Braces can be omitted if the block contains a single statement if ((i > 0) && (i < 10)) { Equivalent if ((i > 0) && (i < 10)) System.out.println("i is an " + System.out.println("i is an " + + "integer between 0 and 10"); + "integer between 0 and 10"); } (a) (b) Caution: o Adding a semicolon at the end of an if clause is a common mistake.
    [Show full text]
  • C Programming Tutorial
    C Programming Tutorial C PROGRAMMING TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i COPYRIGHT & DISCLAIMER NOTICE All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at [email protected] ii Table of Contents C Language Overview .............................................................. 1 Facts about C ............................................................................................... 1 Why to use C ? ............................................................................................. 2 C Programs .................................................................................................. 2 C Environment Setup ............................................................... 3 Text Editor ................................................................................................... 3 The C Compiler ............................................................................................ 3 Installation on Unix/Linux ............................................................................
    [Show full text]
  • Iterating in Perl: Loops
    Iterating in Perl: Loops - Computers are great for doing repetitive tasks. - All programming languages come with some way of iterating over some interval. - These methods of iteration are called ‘loops’. - Perl comes with a variety of loops, we will cover 4 of them: 1. if statement and if-else statement 2. while loop and do-while loop 3. for loop 4. foreach loop if statement Syntax: - if the conditional is ‘true’ then the if(conditional) body of the statement (what’s in { between the curly braces) is …some code… executed. } #!/usr/bin/perl -w $var1 = 1333; Output? if($var1 > 10) 1333 is greater than 10 { print “$var1 is greater than 10\n”; } exit; if-else statement Syntax: -if the conditional is ‘true’ then execute if(conditional) the code within the first pair of curly { braces. …some code… } - otherwise (else) execute the code in else the next set of curly braces { …some different code… } Output? #!/usr/bin/perl -w 13 is less than 100 $var1 = 13; if($var1 > 100) { print “$var1 is greater than 100\n”; } else { print “$var1 is less than 100\n”; } exit; Comparisons that are Allowed - In perl you can compare numbers and strings within conditionals - The comparison operators are slightly different for each one - The most common comparison operators for strings: syntax meaning example lt Less than “dog” lt “cat” False! d > c gt Greater than “dog” gt “cat” True! d > c le Less than or equal to “dog” le “cat” False! d > c ge Greater than or equal to “dog” ge “cat” True! d > c eq Equal to “cat” eq “cat” True! c = c ne Not equal to “cat” eq “Cat”
    [Show full text]