Looping refers to performing a set of operations repeatedly.
Loops can be of 2 types:
-Fixed Loop:The number of times a loop gets executed is fixed.
-Variable Loop:The number of times a loop gets executed is not known.
Fixed Loop
Eg.
Problem
To calculate the total expenditure (sum of monthly expenditure) incurred during a year the algorithm and Flowchart are as follows :
Algorithm
1.Set a counter variable called no_of_months to 1.This variable will keep track of the number of months for which total expenditure is calculated.
You need to understand that the total expenditure must be calculated for month 1 through 12.
2.Accept monthly expenditure starting from month January from the user.
3.Add the monthly expenditure to a variable called total expenditure. This variable will contain the sum of the expenditure incurred every month. (January through December)
4.Increase 5 value of the counter variable no_of_months by 1.
5.Check if the value of the counter variable no_of_months is less than 13.
If the value of the variable no_of_months is less than 13,then repeat steps 2 through 5.
7.Else(that is the expenditure has been calculated for 12 months) display the value of the variable total_expenditure.
Loops can be of 2 types:
-Fixed Loop:The number of times a loop gets executed is fixed.
-Variable Loop:The number of times a loop gets executed is not known.
Fixed Loop
Eg.
Problem
To calculate the total expenditure (sum of monthly expenditure) incurred during a year the algorithm and Flowchart are as follows :
Algorithm
1.Set a counter variable called no_of_months to 1.This variable will keep track of the number of months for which total expenditure is calculated.
You need to understand that the total expenditure must be calculated for month 1 through 12.
2.Accept monthly expenditure starting from month January from the user.
3.Add the monthly expenditure to a variable called total expenditure. This variable will contain the sum of the expenditure incurred every month. (January through December)
4.Increase 5 value of the counter variable no_of_months by 1.
5.Check if the value of the counter variable no_of_months is less than 13.
If the value of the variable no_of_months is less than 13,then repeat steps 2 through 5.
7.Else(that is the expenditure has been calculated for 12 months) display the value of the variable total_expenditure.
Explanation:
This is a fixed loop because the total number of months in a year are 12.This process will be terminated when the number of months is more than 12.
In the above example, the expenditure for each month is added to the total expenditure.Then the loop examines whether the number of months is less than 13.If'No',then the loop is terminated and the total expenditure is displayed. If'Yes', the expenditure of the next month is added to the total expenditure and the loop continues.
Since the number of months in a year is fixed, this loop cannot be executed more than 12 times. Hence, this is an example of fixed loop.