A while loop in C programming repeatedly executes a target statement as long as a given condition is true. Show SyntaxThe syntax of a while loop in C programming language is − while(condition) { statement(s); }Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop. Flow DiagramHere, the key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Example#include <stdio.h> int main () { /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) { printf("value of a: %d\n", a); a++; } return 0; }When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19c_loops.htm A loop is used for executing a block of statements repeatedly until a given condition returns false. In the previous tutorial we learned for loop. In this guide we will learn while loop in C. C – while loopSyntax of while loop: while (condition test) { //Statements to be executed repeatedly // Increment (++) or Decrement (--) Operation }Flow Diagram of while loopExample of while loop#include <stdio.h> int main() { int count=1; while (count <= 4) { printf("%d ", count); count++; } return 0; }Output: 1 2 3 4step1: The variable count is initialized with value 1 and then it has been tested for the condition. Guess the output of this while loop #include <stdio.h> int main() { int var=1; while (var <=2) { printf("%d ", var); } }The program is an example of infinite while loop. Since the value of the variable var is same (there is no ++ or – operator used on this variable, inside the body of loop) the condition var<=2 will be true forever and the loop would never terminate. Examples of infinite while loopExample 1: #include <stdio.h> int main() { int var = 6; while (var >=5) { printf("%d", var); var++; } return 0; }Infinite loop: var will always have value >=5 so the loop would never end. Example 2: #include <stdio.h> int main() { int var =5; while (var <=10) { printf("%d", var); var--; } return 0; }Infinite loop: var value will keep decreasing because of –- operator, hence it will always be <= 10. Use of Logical operators in while loopJust like relational operators (<, >, >=, <=, ! =, ==), we can also use logical operators in while loop. The following scenarios are valid : while(num1<=10 && num2<=10)-using AND(&&) operator, which means both the conditions should be true. while(num1<=10||num2<=10)– OR(||) operator, this loop will run until both conditions return false. while(num1!=num2 &&num1 <=num2)– Here we are using two logical operators NOT (!) and AND(&&). while(num1!=10 ||num2>=num1)Example of while loop using logical operatorIn this example we are testing multiple conditions using logical operator inside while loop. #include <stdio.h> int main() { int i=1, j=1; while (i <= 4 || j <= 3) { printf("%d %d\n",i, j); i++; j++; } return 0; }Output: 1 1 2 2 3 3 4 4This article's factual accuracy is disputed.(November 2020) In most computer programming languages, a do while loop is a control flow statement that executes a block of code at least once, and then either repeatedly executes the block, or stops executing it, depending on a given boolean condition at the end of the block.
The do while construct consists of a process symbol and a condition. First, the code within the block is executed, and then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. Contrast with the while loop, which tests the condition before the code within the block is executed, the do-while loop is an exit-condition loop. This means that the code must always be executed first and then the expression or test condition is evaluated. If it is true, the code executes the body of the loop again. This process is repeated as long as the expression evaluates to true. If the expression is false, the loop terminates and control transfers to the statement following the do-while loop. In other words, whereas a while loop sets the truth of a statement as a condition precedent for the code's execution, a do-while loop provides for the action's ongoing execution subject to defeasance by the condition's falsity, which falsity (i.e., the truth of the condition's negation) is set as a condition subsequent. It is possible, and in some cases desirable, for the condition to always evaluate to true, creating an infinite loop. When such a loop is created intentionally, there is usually another control structure (such as a break statement) that allows termination of the loop. Some languages may use a different naming convention for this type of loop. For example, the Pascal and Lua languages have a "repeat until" loop, which continues to run until the control expression is true (and then terminates) — whereas a "while" loop runs while the control expression is true (and terminates once the expression becomes false). do { do_work(); } while (condition); is equivalent to do_work(); while (condition) { do_work(); } In this manner, the do ... while loop saves the initial "loop priming" with do_work(); on the line before the while loop. As long as the continue statement is not used, the above is technically equivalent to the following (though these examples are not typical or modern style used in everyday computers): while (true) { do_work(); if (!condition) break; } or LOOPSTART: do_work(); if (condition) goto LOOPSTART;
These example programs calculate the factorial of 5 using their respective languages' syntax for a do-while loop. ActionScript 3var counter: int = 5; var factorial: int = 1; do { factorial *= counter--; /* Multiply, then decrement. */ } while (counter > 0); trace(factorial); Ada
The Wikibook Ada_Programming has a page on the topic of: Control with Ada.Integer_Text_IO; procedure Factorial is Counter : Integer := 5; Factorial : Integer := 1; begin loop Factorial := Factorial * Counter; Counter := Counter - 1; exit when Counter = 0; end loop; Ada.Integer_Text_IO.Put (Factorial); end Factorial; BASICEarly BASICs (such as GW-BASIC) used the syntax WHILE/WEND. Modern BASICs such as PowerBASIC provide both WHILE/WEND and DO/LOOP structures, with syntax such as DO WHILE/LOOP, DO UNTIL/LOOP, DO/LOOP WHILE, DO/LOOP UNTIL, and DO/LOOP (without outer testing, but with a conditional EXIT LOOP somewhere inside the loop). Typical BASIC source code: Dim factorial As Integer Dim counter As Integer factorial = 1 counter = 5 Do factorial = factorial * counter counter = counter - 1 Loop While counter > 0 Print factorial C#int counter = 5; int factorial = 1; do { factorial *= counter--; /* Multiply, then decrement. */ } while (counter > 0); System.Console.WriteLine(factorial); Cint counter = 5; int factorial = 1; do { factorial *= counter--; /* Multiply, then decrement. */ } while (counter > 0); printf("factorial of 5 is %d\n", factorial); Do-while(0) statements are also commonly used in C macros as a way to wrap multiple statements into a regular (as opposed to compound) statement. It makes a semicolon needed after the macro, providing a more function-like appearance for simple parsers and programmers as well as avoiding the scoping problem with if. It is recommended in CERT C Coding Standard rule PRE10-C.[1] C++int counter = 5; int factorial = 1; do { factorial *= counter--; } while (counter > 0); std::cout << "factorial of 5 is "<< factorial << std::endl; CFScriptfactorial = 1; count = 10; do { factorial *= count--; } while (count > 1); writeOutput(factorial); Dint counter = 5; int factorial = 1; do { factorial *= counter--; // Multiply, then decrement. } while (counter > 0); writeln("factorial of 5 is ", factorial); FortranWith legacy FORTRAN 77 there is no DO-WHILE construct but the same effect can be achieved with GOTO: INTEGER CNT,FACT CNT=5 FACT=1 1 CONTINUE FACT=FACT*CNT CNT=CNT-1 IF (CNT.GT.0) GOTO 1 PRINT*,FACT END Fortran 90 and later does not have a do-while construct either, but it does have a while loop construct which uses the keywords "do while" and is thus actually the same as the for loop.[2] program FactorialProg integer :: counter = 5 integer :: factorial = 1 factorial = factorial * counter counter = counter - 1 do while (counter > 0) ! Truth value is tested before the loop factorial = factorial * counter counter = counter - 1 end do print *, factorial end program FactorialProg Javaint counter = 5; int factorial = 1; do { factorial *= counter--; /* Multiply, then decrement. */ } while (counter > 0); System.out.println("The factorial of 5 is " + factorial); //============================================// // The below function does the same as above. // //============================================// int counter = 5; int factorial = 1; while (counter > 0){ factorial *= counter--; /* Multiply, then decrement. */ } System.out.println("The factorial of 5 is " + factorial); JavaScriptlet counter = 5; // Declaring two variables, counter and factorial let factorial = 1; do { factorial *= counter--; //What will be looped } while (counter > 0); //The looping conditions console.log(factorial); //Showing the result [3] Kotlinvar counter = 5 var factorial = 1 //These line of code is almost the same as the above JavaScript codes, the only difference is the keyword that shows the results do { factorial *= counter-- } while (counter > 0) println("Factorial of 5 is $factorial") [4] PascalPascal does not have a do/while; instead, it has a repeat/until. As mentioned in the introduction, one can consider a repeat/until to be equivalent to a 'do code while not expression' construct. factorial := 1; counter := 5; repeat factorial := factorial * counter; counter := counter - 1; // In Object Pascal one may use dec (counter); until counter = 0; PHP$counter = 5; $factorial = 1; do { $factorial *= $counter--; } while ($counter > 0); echo $factorial; PL/IThe PL/I DO statement subsumes the functions of the post-test loop (do until), the pre-test loop (do while), and the for loop. All functions can be included in a single statement. The example shows only the "do until" syntax. declare counter fixed initial(5); declare factorial fixed initial(1); do until(counter <= 0); factorial = factorial * counter; counter = counter - 1; end; put(factorial);PythonPython lacks a specific do while flow control construct. However, the equivalent may be constructed out of a while loop with a break. counter = 5 factorial = 1 while True: factorial *= counter counter -= 1 if counter == 0: break print(factorial) RacketIn Racket, as in other Scheme implementations, a "named-let" is a popular way to implement loops: #lang racket (define counter 5) (define factorial 1) (let loop () (set! factorial (* factorial counter)) (set! counter (sub1 counter)) (when (> counter 0) (loop))) (displayln factorial) Compare this with the first example of the while loop example for Racket. Be aware that a named let can also take arguments. Racket and Scheme also provide a proper do loop. (define (factorial n) (do ((counter n (- counter 1)) (result 1 (* result counter))) ((= counter 0) result) ; Stop condition and return value. ; The body of the do-loop is empty. )) Rubycounter = 10 factorial = 2 begin factorial *= counter counter -= 2 end while counter > 1 puts factorial Smalltalk| counter factorial | counter := 5. factorial := 1. [counter > 0] whileTrue: [factorial := factorial * counter. counter := counter - 1]. Transcript show: factorial printString SwiftSwift 2.x and later:[5] var counter = 5 var factorial = 1 repeat { factorial *= counter counter -= 1 } while counter > 0 print(factorial) Swift 1.x: var counter = 5 var factorial = 1 do { factorial *= counter counter -= 1 } while counter > 0 println(factorial) Visual Basic .NETDim counter As Integer = 5 Dim factorial As Integer = 1 Do factorial *= counter counter -= 1 Loop While counter > 0 Console.WriteLine(factorial)
|