Detailed Print – CSKC
Sign In

Search

siteicon
Code Learning#CPP#1999 Back

Odd number series with divisibility test – for loop

Printing odd number series by testing divisibility test on each number in the for loop

Learning Objectives

  • Learning to use divisibility test on each number in a for loop.

Source Code

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

Run Output

1 3 5 7 9 11 13 15 17 19

Code Understanding

for(int i=1;i<=20;i++)
if(i%2!=0) cout<<i<<” “;
Here the for loop allows to go to each number and then with if selection the divisibility test with 2 is performed on each number using i%2!=0. This means that if remainder of number divided by 2 is not zero. The % operator helps to find the remainder. For example 3%2 would not be zero while 4%2 would be zero.

Notes

  • Double step counting is an efficient approach as compared to checking odd number by comparison operator such as (i%2!=0).


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