DEV Community

Keerthana M
Keerthana M

Posted on

Looping

LOOPING:

=> Looping means forming a loop or repeating something in a circular or continuous way.

Flow Chart:

Coding:

Ref: W3 school.

Types of looping :

  1. while loop
  2. For loop

While Loop:

What is while?

=> A while loop is best to use when you don't know how many times the code should run.

=>The while loop is the most intuitive loop type because it resembles many things we do in our every day life:

  • Keep walking (taking new steps) until you reach your destination.
  • As long as the pot is dirty, continue washing it.
  • Keep filling the tank of the car until it is full.

syntax:

what we should we find before coding?

  1. Initialization.
  2. condition.
  3. Increment or decrement.

Example: to print the values: 1 3 5 7 9.

  1. initialization: i=1;
  2. Condition: c = i<=10;
  3. dec/Inc: increment by 2.

program:

For Loop:

=> For loop is used to reduce the number of code lines than while loop.
=> A for loop is best to use when you know how many times the code should run, and the most basic thing we can do with a for loop is counting.

=>To count, a for loop uses a counting variable to keep track of how many times the code has run.

The counting variable in a for loop is set up like this:

  1. Starting value.
  2. Condition using the counting variable, the for loop runs as long as the condition is true.
  3. Description of how the counting variable should change each time the loop runs.

It counts down from 10 to 1,and then writes "Liftoff!", using a for loop with a counting variable i.

Ref: W3 School.

Top comments (0)