C program to print all odd numbers from 1 to n

Write a C program to print all odd numbers from 1 to 100 using for loop. How to display odd numbers from 1 to n using loop in C programming. C program to print odd numbers in a given range.

Example:
Input upper limit to display odd numbers: 10
Output all odd numbers between 1 to 10: 1, 3, 5, 7, 9

Required knowledge

Basic C programming, If else, For loop

Odd numbers

Numbers that are not exactly divisible by 2 is called as Odd numbers. For example 1, 3, 5, 7, 9 are the first five odd numbers.

We have already seen in our previous programs how to check even/odd conditions using various techniques such as using if else, switch case, conditional operator and by bitwise operator. Hence to print odd numbers from 1 to n we need to iterate from 1 to n using any loop construct and print the current number inside loop if it is odd.

Program to print odd numbers using if

/**
 * C program to print all Odd numbers from 1 to n
 */

#include <stdio.h>

int main()
{
    int i, n;
    
    //Read the upper limit to print odd from user
    printf("Print odd numbers till: ");
    scanf("%d", &n);

    printf("All odd numbers from 1 to %d are: \n", n);

    /*
     * Starts a loop from 1 and increments its by 1
     */
    for(i=1; i<=n; i++)
    {
        /* Check if the number is odd then print */
        if(i%2!=0)
        {
            printf("%d\n", i);
        }
    }

    return 0;
}

Note: As I have said many time the above mentioned method for generating odd numbers is not optimal and you should use the below approach to generate odd numbers.

Program to display odd numbers without using if

/**
 * C program to display all odd numbers between 1 to n
 */

#include <stdio.h>

int main()
{
    int i, n;
    
    //Read the upper limit to print odd from user
    printf("Print odd numbers till: ");
    scanf("%d", &n);

    printf("All odd numbers from 1 to %d are: \n", n);

    /*
     * Starts a loop from 1 and increments it by 2 
     * And in each repetition prints the number
     */
    for(i=1; i<=n; i+=2)
    {
        printf("%d\n", i);
    }

    return 0;
} 


Output
X
_
Print odd numbers till: 100
All odd numbers from 1 to 100 are:
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

2 comments:

  1. Just a quick question since I am new in C does i+=2 mean i=i+2

    ReplyDelete
    Replies
    1. @Gaurav yes both are same. You can use any of them. But since i+=2 is short and trendy its a good programming practice to use i+=2 in short expressions such as in loops.

      Delete