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:
- 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)