for Loop (Lesson-15)

As you already know that loops are used to execute a set of statements many number of times. for loop is handy if we already know that how many times the loop will execute. Syntax for for loop is:
for (initialization ; condition ; incement/decrement)
    //Body of loop
In initialization, we initialize a variable, in condition, we provide a condition. The loop executes as long as the condition is true. In increment/decrement, we increment or decrement the variable we initialized before.
To understand for loop, let's take a problem. First we will solve it with while loop and then we will use for loop to solve it. We will write a program to display first ten natural numbers on the screen.
Solution using while loop:
Keeping in mind the syntax of for loop, let's solve the same problem using for loop:

Now let's observe how things have changed while going from while loop to for loop:
Did you observe that? The for loop makes our code shorter and much easier to understand.

Now let's consider another problem. A program to display first ten natural numbers in descending order.

Let's consider another example to display the first ten multiples of two.

Practice Corner:

  • Write a program to input a number and display its table upto 10th multiple on the screen in the following format:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
The program should use for loop.
  • Write a program to calculate the sum of first 100 natural numbers. (The program should use for loop and not any formula)
  • Write a program to display first 100 whole numbers (0,1,2,3,....,99)

Post a Comment