Home » Posts tagged 'loop'

Tag Archives: loop

Do While Statement in C Programming

like a while statement,  “ do while statement” repeats a set of statements if condition is true.

If condition is false the flow of control do not enter inside the do-while loop.

“do-while” first execute the body of loop than tests the condition.

Means even if the condition if false do-while executes at least ones.

The syntax of a do…while loop in C programming language is −

Example: Write a program to print 1 to 10 using while loop.

#include int main() { int a = 1; do { printf(” %d \n”, a); a++; } while (a <= 10); // loop executes 10 times return 0; }

OUTPUT

Even if the condition if false do-while executes at least ones.

#include int main() { int a = 100; do { printf(” %d \n”, a); a++; } while (a <= 10); // condition is false even do-while executes ones return 0; }

OUTPUT

Loop (Iteration) Statements in JavaScript

Loop(Iteration) Statement

A loop describes the process in a software program/script that repeats the same set of instructions over and over until it receives the order to stop.

Loops offer a quick and easy way to execute something repeatedly. There are 4 types of loop in JavaScript:

  • for statment
  • for/in statement
  • while statment
  • do/while statement

for Statement

The for is a loop statement that is executed as long as the given condition is true. It will not stop until and unless the condition becomes false.

Example of for statement

For/in Statement

  • This statement loops through the properties of an object.
  • The block of code snippet inside the loop will be executed once for each of the properties.

While Statement

  • while is a loop statement that is executed as long as the given condition is true. It will not stop until and unless the condition becomes false.
  • Initialization of loop variable is mandatory before writing while loop.

Example of while statment

do-while Loop

  • It loops through a block of code once at first and then repeats the loop while the specified condition is true.
  • The main difference between do-while and while loop is that in do-while loop, the set of statements are executed at least once even if the condition isn’t satisfied whereas in while loop nothing is executed if the condition is false.

Example: of do while statement

Nested Loops

An important fact is that both break and continue affect the current loop.

So while working with the nested loops, things can get confusing very quickly.

Consider the following example below:

Note:

  • We have got 2 loops here. Each loop runs for 5 times i.e., 0–4.
  • The first loop will continue if i is even i.e., the only values of i that can ever be logged are 1 & 3 as 0, 2, and 4 will not pass the even criteria: if (i % 2 == 0).
  • Now, the inner lop breaks when j is 2. So, the values of j can only be 0 & 1.

So finally the printed output is:

Managed by MochaHost - Fast & Easy WordPress Hosting