Odd number series using continue in the while loop
Program to print the series of odd numbers using an alternative technique of using the continue within the while loop.
Learning Objectives
- Use of continue in the while loop and understanding how it is different from the for loop.
Source Code
|
|
Alternate (?) : Related ( ? ) : |
Run Output
Code Understanding
for(int i=1;i<=20;++i)
For loop to begin with 1 and an arbitrary limit of 20. This limit can be set as per user’s choice also.
if(i%2==0) { ++i; continue;}
If the number is even then it is tested by using the divisibility test by 2 (i%2==0), means no remainder is left when divided by 2. When the number is even we first increment the count as there is no inherent instruction available in the while loop. Then we continue the operation of the while loop by going to entry level comparison instruction of the while.
else cout<<i<<” “;
This will print the odd number only as in the case of even number continue has been used.
Notes
- It is interesting to note that in case of use of continue in the for loop it reaches the third (update instruction) of the for loop. In case of continue in the while loop it reaches the comparison instruction as that is the only instruction available. So before the continue instruction manual increment is required to let the loop move to next number. So in case of while loop 2 manual increment instructions may be required when continue is used.
Common Errors
- Some students write the cout instruction before the continue line. In that case all numbers shall be printed.
Suggested Filename(s): odd-series-while-cont.cpp
Created: 1-Jan-2018 18:41 | Updated: 15-Sep-2018 12:34|
