Odd number series using continue in the for loop
Program to print the series of odd numbers using an alternative technique of using the continue within the for loop.
Learning Objectives
- Use of continue in 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) 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 continue the operation of the for loop by going to instruction which increments the number.
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 the continue based results in the while loop may be different.
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-cont.cpp
Created: 1-Jan-2018 18:25 | Updated: 15-Sep-2018 12:33|
