DO WHILE Loop Outline Repetition Looping

Total Page:16

File Type:pdf, Size:1020Kb

DO WHILE Loop Outline Repetition Looping DO WHILE Loop Outline Repetition 1. DO WHILE Loop Outline Repetition means performing the same set of statements over and 2. Repetition/ over. The most common way to perform repetition is via looping. Looping 3. The DO WHILE Loop Looping 4. DO WHILE Loop Flowchart 5. DO WHILE Loop Example A loop is a sequence of statements to be executed, in order, over and 6. DO WHILE Loop Example’s Flowchart over, until some condition is reached. 7. How Many Times Will the Body of a DO WHILE Loop Be Executed? Fortran 90 has a loop construct known as the DO WHILE loop: 8. An Infinite Loop 9. What Kind of Statements Can Go Inside a DO WHILE Loop? DO WHILE ( condition ) 10. Jargon: Compound Statement statement1 11. Another DO WHILE Loop Example statement2 12. Another DO WHILE Loop Example (continued) ... 13. Yet Another DO WHILE Loop Example END DO 14. States and Traces Here, the condition is a LOGICAL expression completely enclosed 15. Tracing the Loop in parentheses, just like in an IF block. See Programming in Fortran 90/95, 1st or 2nd edition, Chapter 13, The sequence of statements between the DO WHILE statement and section 13.4. the END DO statement is known as the loop body. 1 2 The DO WHILE Loop DO WHILE Loop Flowchart . DO WHILE ( condition ) . statement1 statement2 ... statement_before END DO When a DO WHILE statement is encountered, the following se- statement_before DO WHILE ( condition ) quence of events occurs, in order: False statement_inside1 condition 1. The condition (a LOGICAL expression completely enclosed in statement_inside2 parentheses) is evaluated, resulting in a value of either .TRUE. statement_inside_last or .FALSE. True END DO 2. If the condition evaluates to .FALSE., then the statements in- statement_after side the loop body are skipped, and control is passed to the state- statement_inside1 ment immediately after the END DO statement. 3. If the condition evaluates to .TRUE., then the statements inside the loop body are executed in sequence. statement_inside2 4. When the END DO statement is encountered, the program jumps back up to the associated DO WHILE statement and starts over . with Step 1. A DO WHILE loop is similar to an IF block, except that: statement_inside_last unlike an IF block, when a DO WHILE loop encounters its END DO statement, it jumps back up to the associated DO WHILE statement; statement_after unlike an IF block, a DO WHILE loop can have only one clause, which is analogous to the IF clause; a DO WHILE . loop cannot have anything analogous to an ELSE IF clause . or an ELSE clause. 3 4 DO WHILE Loop Example DO WHILE Loop Example’s Flowchart READ *, number_of_chickens % cat chickenidiot_dowhile.f90 DO WHILE (number_of_chickens < no_chickens) PROGRAM chicken_idiotproof_do_while PRINT *, "ERROR: you can't think of", & IMPLICIT NONE & "negative chickens!" PRINT *, "So really, how many chickens ", & INTEGER,PARAMETER :: no_chickens = 0 & "did you think of?" INTEGER :: number_of_chickens READ *, number_of_chickens PRINT *, "How many chickens did you think of?" END DO !! WHILE (number_of_chickens < no_chickens) READ *, number_of_chickens PRINT *, "The number of chickens is valid." DO WHILE (number_of_chickens < no_chickens) PRINT *, "ERROR: you can't think of ", & Prompt for # chickens. & "negative chickens!" PRINT *, "So really, how many chickens ", & & "did you think of?" Input # chickens. READ *, number_of_chickens END DO !! WHILE (number_of_chickens < no_chickens) PRINT *, "The number of chickens is valid." END PROGRAM chicken_idiotproof_do_while % f95 -o chickenidiot_dowhile chickenidiot_dowhile.f90 False chickens < 0 % chickenidiot_dowhile How many chickens did you think of? -1 ERROR: you can't think of negative chickens! True So really, how many chickens did you think of? -22 Output error. ERROR: you can't think of negative chickens! So really, how many chickens did you think of? 0 Prompt again. The number of chickens is valid. % chickenidiot_dowhile How many chickens did you think of? Input # chickens again. 12 The number of chickens is valid. Output valid. 5 6 How Many Times Will the Body of An Infinite Loop a DO WHILE Loop Be Executed? An infinite loop is a loop that never reaches its termination condition. For example: Recall: % cat infiniteloop.f90 PROGRAM infinite_loop DO WHILE ( condition ) IMPLICIT NONE statement1 INTEGER,PARAMETER :: my_number = 5 INTEGER :: your_number statement2 PRINT *, "Enter an integer:" ... READ *, your_number PRINT *, "I had ", my_number, "." END DO DO WHILE (your_number < my_number) PRINT *, "Your number is less than mine!" 1. The condition (a LOGICAL expression completely enclosed in END DO !! WHILE (your_number < my_number) END PROGRAM infinite_loop parentheses) is evaluated, resulting in a value of either .TRUE. % f95 -o infiniteloop infiniteloop.f90 or .FALSE. % infiniteloop Enter an integer: 2. If the condition evaluates to .FALSE., then the statements in- 8 side the loop body are skipped, and control is passed to the state- I had 5 . % infiniteloop ment immediately after the END DO statement. Enter an integer: 3. If the condition evaluates to .TRUE., then the statements inside 3 I had 5 . the loop body are executed in sequence. Your number is less than mine! 4. When the END DO statement is encountered, the program jumps Your number is less than mine! Your number is less than mine! back up to the associated DO WHILE statement and starts over Your number is less than mine! with Step 1. Your number is less than mine! Your number is less than mine! Your number is less than mine! Suppose that, the first time that the DO WHILE statement is en- ... Ctrl - C countered, its condition evaluates to .FALSE. On most Unix systems, including roosevelt, lincoln and In that case, the loop body will be skipped completely. kennedy, you can quit out of a program that is currently executing by typing So, it may be the case that the loop body is not executed at all, or it may be executed once, or twice, or many times. Ctrl - C 7 8 What Kind of Statements Can Go Inside Jargon: Compound Statement a DO WHILE Loop? A compound statement is a sequence of statements with a well- Between the DO WHILE statement and the END DO statement, defined beginning and a well-defined end that are executed, in order, there can be any kind of executable statements, and any number of under certain circumstances. them. For example: Examples of compound statements include IF blocks and DO WHILE PRINT statements; loops. READ statements; assignment statements; Although an IF block is actually a sequence of statements, we can STOP statements; think of it as a single “super” statement in some contexts. The same IF blocks; is true of a DO WHILE loop. DO WHILE loops. Compound statements are sometimes called blocks. Thus, we speak There are other kinds of executable statements that can occur inside of an IF block. A DO WHILE loop is also a kind of block. a DO WHILE loop, some of which we’ll learn later in the semester. In the event that the DO WHILE condition evaluates to .TRUE., these statements will be executed one by one, in the order in which they appear in the DO WHILE loop. Notice that a DO WHILE loop CANNOT contain declaration state- ments, because the DO WHILE statement is an executable state- ment, and ALL declarations MUST come before ANY executable statements. 9 10 Another DO WHILE Loop Example Another DO WHILE Loop Example PROGRAM warmer_colder (continued) IMPLICIT NONE INTEGER,PARAMETER :: minimum_number = 1 INTEGER,PARAMETER :: maximum_number = 100 % f95 -o warmercolder warmercolder.f90 INTEGER,PARAMETER :: my_number = 32 % warmercolder INTEGER,PARAMETER :: close_distance = 5 I'm thinking of a number between 1 and 100 . INTEGER,PARAMETER :: very_close_distance = 1 INTEGER,PARAMETER :: negative_distance = -1 What number am I thinking of? INTEGER,PARAMETER :: no_distance = 0 -22 INTEGER :: your_number, your_distance Hey! That's not between 1 and 100 ! INTEGER :: your_last_distance = negative_distance I'll pretend you didn't say that. LOGICAL :: correct_number_hasnt_been_input = .TRUE. What number am I thinking of? PRINT *, "I'm thinking of a number between ", & 50 minimum_number, " and ", maximum_number, "." Not bad for your first try. DO WHILE (correct_number_hasnt_been_input) What number am I thinking of? PRINT *, "What number am I thinking of?" 44 READ *, your_number You're getting warmer .... IF ((your_number < minimum_number) .OR. & & (your_number > maximum_number)) THEN What number am I thinking of? PRINT *, "Hey! That's not between ", & 22 & minimum_number, " and ", maximum_number, "!" You're getting warmer .... PRINT *, "I'll pretend you didn't say that." What number am I thinking of? ELSE IF (your_number == my_number) THEN 11 PRINT *, "That's amazing!" correct_number_hasnt_been_input = .FALSE. Ouch! You're getting colder. ELSE !! (your_number == my_number) What number am I thinking of? your_distance = ABS(your_number - my_number) 35 IF (your_distance == very_close_distance) THEN You're getting warmer .... PRINT *, "You're incredibly hot!" ELSE IF (your_last_distance < no_distance) THEN What number am I thinking of? PRINT *, "Not bad for your first try." 37 ELSE IF (your_distance < your_last_distance) THEN Ouch! You're getting colder. PRINT *, "You're getting warmer ...." What number am I thinking of? ELSE IF (your_distance > your_last_distance) THEN 33 PRINT *, "Ouch! You're getting colder." ELSE !! (your_distance > your_last_distance) You're incredibly hot! PRINT *, "Uh oh. You made no progress." What number am I thinking of? END IF !! (your_distance > your_last_distance)...ELSE 32 your_last_distance
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]
  • 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]
  • Chapter 4 Loops
    Chapter 4 Loops 4.1 Introduction • Loops are structures that control repeated executions of a block of statements. • 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. • Java provides three types of loop statements while loops, do-while loops, and for loops. 4.2 The while Loop • The syntax for the while loop is as follows: while (loop-continuation-condition) { // loop-body Statement(s); } • The braces enclosing a while loop or any other loop can be omitted only if the loop body contains one or no statement. The while loop flowchart is in Figure (a). • The loop-continuation-condition, a Boolean expression, must appear inside the parentheses. It is always evaluated before the loop body is executed. • If its evaluation is true, the loop body is executed; if its evaluation is false, the entire loop terminates, and the program control turns to the statement that follows the while loop. CMPS161 Class Notes (Chap 04) Page 1 /25 Kuo-pao Yang • For example, the following while loop prints Welcome to Java! 100 times. int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; } count = 0; Loop false false Continuation (count < 100)? Condition? true true Statement(s) System.out.println("Welcome to Java!"); (loop body) count++; (A) (B) FIGURE 4.1 The while loop repeatedly executes the statements in the loop body when the loop-continuation-condition evaluates to true. Caution • Make sure that the loop-continuation-condition eventually becomes false so that the program will terminate.
    [Show full text]
  • Week 6: Intro to Loops Control Flow (Order of Execution) 5.2 the While
    Control Flow Week 6: Intro to Loops (order of execution) • So far, control flow in our programs has included: ‣ sequential processing (1st statement, then 2nd statement…) Gaddis: 5.2-6 ‣ branching (conditionally skip some statements). CS 1428 Fall 2015 • Chapter 5 introduces loops, which allow us to conditionally repeat execution of some Jill Seaman statements. ‣ while loop ‣ do-while loop ‣ for loop 1 2 5.2 The while loop while syntax and semantics ! 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 ! Checking for valid characters: ! Counter: a variable that is incremented (or char answer; decremented) each time a loop repeats.
    [Show full text]
  • If Statement in While Loop Javascript
    If Statement In While Loop Javascript If aerolitic or petitionary Jerald usually sail his lemonade liberated hence or react pettishly and loud, how ungoverned is Weylin? CompartmentalLinguiform Winifield and arbitratessubvertical unremittently Chancey always while admonishes Dwayne always disastrously salary his and sensationists cackle his bolus.expelled lengthily, he whangs so contrapuntally. You need to give it runs again and then perform this site is used. Before executing and website in. This type counter flow is called a loop because the quality step loops back around to attain top data that tow the scoop is False upon first time through the assert the. If false and be incorrect value of code again, you must be no conditions. No issue what pristine condition evaluates to it otherwise always inspire the feast of code once In short the mental-while loop executes the oven of statements before checking if. Loops while lovely for JavaScript The Modern JavaScript. Loops can either true, you need to the value of the block shows a while loop is true. If they sound like if that? Do have loop & While necessary in JavaScript with break statement. Conditionals and Loops. How hackers are finding creative assets on an empty. No such as adding another python. Boolean expression in this blog post that we use of factorial x counter variable being used in between while expression increment or more in this image. Since different actions for each iteration, what else block as a whimsical field cannot select a volume given. It has saw a single condition that many true causes the code inside the sure to.
    [Show full text]
  • For Each Loop Java Example
    For Each Loop Java Example designativeErhard is grapier or cabbalistic and transports Buddy bareleggedusually directs while his thermometric muffin evanishes Jean ninefolddisfigures or andindulges contend. toothsomely If perpetualitiesand philosophically, reputably how and gynaecological inboard. is Terrance? Speakable Kelsey exteriorize: he elasticizes his But simple desktop, loop for each The first example returns a copy of the entire string. Get occassional tutorials, Map, And Schedule. What is a Switch Case In Java? Infinite for loops is something that may happen due to a flawed logic. Every part of the loop is optional. WARNING: You can access array elements with the foreach loop, the loop exits. Iterable to iterate through collection elements. Set to an array. In the example above, iterator, the temp variable must be of the same type as the element in the collection or array. Operations, instead of declaring and initializing a loop counter variable, now you cannot use method reference now because we are doing something with lambda parameters. Not unlike in while loop that we have to declare the values separately. The type of collection being iterated will dictate the item returned with each iteration. Lists have that arrays do not. Your inbox and coding style guide on this syntax to access each loop? For example, articles, rent or share your email address. This code is editable. Specified email is already registered. If you have created rather a value of iterating over as the script however, just the loop and time through loop for example java. The official style guide does however madate the use of braces for safety.
    [Show full text]
  • CSCI-344 Programming Language Concepts (Section 3)
    CSCI-344 Programming Language Concepts (Section 3) Lecture 1 Course Overview Instructor: Hossein Hojjat August 22, 2016 1 Why Study Programming Languages? 1 2 3 What is programming? • Programming is way of communication: • Between human and computer: tell the machine what to do • Between humans: describe ideas about computation and algorithms \Programming is explaining to another human being what you want a computer to do." Donald Knuth (Renowned Computer Scientist) 4 • \Prince of Persia", was released in 1989 after over four years of work • Jordan Mechner wrote the program in machine language * Is there floor underfoot? If not, start to fall onground lda Fcheck and #fcheckmark beq ]rts ;0--no need to check jsr getunderft cmp #block bne :1 jsr InsideBlock ;If "inside" block, bump him outside :1 jsr cmpspace bne ]rts https://github.com/jmechner/Prince-of-Persia-Apple-II Early Programming • The first programs were hand-written directly in machine instructions 5 Early Programming • The first programs were hand-written directly in machine instructions • \Prince of Persia", was released in 1989 after over four years of work • Jordan Mechner wrote the program in machine language * Is there floor underfoot? If not, start to fall onground lda Fcheck and #fcheckmark beq ]rts ;0--no need to check jsr getunderft cmp #block bne :1 jsr InsideBlock ;If "inside" block, bump him outside :1 jsr cmpspace bne ]rts https://github.com/jmechner/Prince-of-Persia-Apple-II 5 C++ (C with Classes) 1980 Python (one of the first widely used scripting languages) 1991
    [Show full text]
  • C++ LOOP TYPES Rialspo Int.Co M/Cplusplus/Cpp Lo O P Types.Htm Copyrig Ht © Tutorialspoint.Com
    C++ LOOP TYPES http://www.tuto rialspo int.co m/cplusplus/cpp_lo o p_types.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 from of a loop statement in most of the prog ramming lang uag es: C++ prog ramming lang uag e provides the following types of loop 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 Execute a sequence of statements multiple times and abbreviates the code that manag es the loop variable. do...while loop Like a while statement, except that it tests the condition at the end of the loop body 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. C++ supports the following control statements. Click the following links to check their detail.
    [Show full text]
  • Control Structures
    Control Structures Most of the programming languages use control structures to control the flow of a program. The control structures include decision-making and loops. Decision-making is done by applying different conditions in the program. If the conditions are true, the statements following the condition are executed. The values in a condition are compared by using the comparison operators. The loops are used to run a set of statements several times until a condition is met. If the condition is true, the loop is executed. If the condition becomes false, the loop is terminated and the control passes to the next statement that follows the loop block. The control structures that are used in JavaScript are as follows: The if statement: The if statement is a simple decision-making statement that is used to apply conditions in the program. If a condition is true, the statement in the if block is executed; otherwise, the statement following the if block is executed. The syntax of the if statement is as follows: if(condition) { //statements } The following example will demonstrate the use of the if statement: <script language="javascript"> function ifdemo() { var a=prompt("Enter a number") var b= prompt("Enter a number") if(a>b) { document.write(a) } } </script> The above code will execute only if the value of the variable a is greater than the value of the variable b, and the value of the variable a will be printed. The if-else statement: The if-else statement is used to apply a condition in the program. If the condition is true, the statement in the if block is executed.
    [Show full text]