Python – program to print odd natural number upto n

Python – program to print odd natural number upto n

In this post, we will see programs for how to print odd natural numbers up to n in python, provided n is positive.

Odd Number : Any integer either positive or negative, which can not be divided exactly by 2 is an odd number. The numbers having the last digit is 1, 3, 5, 7 or 9 are considered as an odd number.

Note : Natural number is positive integers. It’s range from 1 to infinity.

Examples:

Input: n : 10

Output: 1 3 5 7 9

Input: n : 15

Output: 1 3 5 7 9 11 13 15

Let’s see the different version of codes for this program :

Code version 1: Using a concept of range() function with for loop.

As we know, we can pass 3 parameters in range() function, the third parameter is stepped i.e jump after each iteration.


# main code
if __name__ == "__main__" :

    # input value of n
    n = 10

    # for loop starts from 1
    # and ends on n.
    # each time value of variable  
    # i is incremented by 2
    for i in range(1, n + 1, 2) :
        
        # print value of variable i
        # and end parameter is space
        # so print all outputs
        # in a single line
        print(i,end=" ")
Output: 1 3 5 7 9

Code version 2: Using if statement along with for loop.

 

# main code
if __name__ == "__main__" :

    # input value of n
    n = 15

    # for loop starts from 1
    # and ends on n.
    # each time value of variable  
    # i is incremented by 1
    for i in range(1, n + 1) :

        # if condition is True 
        # that means i % 2 gives 
        # non-zero value then
        # i is odd number so, 
        # print value of variable i
        # and end parameter is space
        # so print all outputs
        # in a single line
        if i % 2 :
            print(i,end=" ")
            
Output: 1 3 5 7 9 11 13 15

Code version 3: Using a concept of increment operator with while loop .


# main code
if __name__ == "__main__" :

    # input value of n
    n = 20

    # initialize value of i by 1
    i = 1
    
    # while loop starts from 1
    # run untill value of i
    # is less than n  
    while i < n :
        
        # print value of variable i
        # and end parameter is space
        # so print all outputs
        # in a single line
        print(i,end=" ")

        # each time value of variable  
        # i is incremented by 2
        i += 2
Output: 1 3 5 7 9 11 13 15 17 19

Leave a Reply

Your email address will not be published.

📢 Need further clarification or have any questions? Let's connect!

Connect 1:1 With Me: Schedule Call


If you have any doubts or would like to discuss anything related to this blog, feel free to reach out to me. I'm here to help! You can schedule a call by clicking on the above given link.
I'm looking forward to hearing from you and assisting you with any inquiries you may have. Your understanding and engagement are important to me!

This will close in 20 seconds