Detailed Print – CSKC
Sign In

Search

siteicon
Code Learning#CPP#1997 Back

Odd number series with double step counter – for loop

Printing odd number series by incrementing counter in double step using for loop

Learning Objectives

  • Learning to use multiple step increment expression in the for loop.

Source Code

		 
Click to open popup
Alternate (?) : 1999   Related ( ? ) : 1999

Run Output

1 3 5 7 9 11 13 15 17 19

Code Understanding

for(int i=1;i<=20;i+=2) cout<<i<<” “;
Here i+=2; allow increment by two steps with every loop traversing. Thus after 1, 3 is printed and so on the numbers are printed which are below the condition of <=20.

Notes

  • Double step counting is an efficient approach as compared to checking odd number by comparison operator such as (i%2!=0).
  • People who confuse with the shortcut syntax of i+=2 can also write i=i+2 .


Suggested Filename(s): odd-series-ds.cpp