C program to find sum of all odd numbers from 1 to n using loop

Write a C program to print the sum of all odd numbers from 1 to n using for loop. How to find sum of all odd numbers in a given number in C programming. Calculating sum of odd numbers in a given interval.

Example:
Input range: 10
Output sum of odd numbers from 1-10: 25

Also learn this program using another recursive approach - C program to find sum of all odd number with range using recursion.

Required knowledge

Basic C programming, For loop

Logic to find sum of odd numbers

I already have talked many times about even and odd numbers, and explained many methods of checking even or odd numbers such as using bitwise operator, conditional operator, if else, switch case. Also we have learnt to generate odd numbers in a given range. Here in this program we will be using the same logic which we have used for generating odd numbers.

Program to find sum of odd numbers

/**
 * C program to print the sum of all odd numbers from 1 to n
 */

#include <stdio.h>

int main()
{
    int i, n, sum=0;

    /* Reads range to find sum of odd numbers */
    printf("Enter any number: ");
    scanf("%d", &n);

    /* Finds the sum of all odd number */
    for(i=1; i<=n; i+=2)
    {
        sum += i;
    }

    printf("\nSum of odd numbers = %d", sum);

    return 0;
} 

Note: sum += i and sum = sum + i both are same. You can use any of them to find sum.


That was easy, now using this you can also find the sum of odd numbers in a given range. For finding sum of odd numbers in a range M - N. You need two input from user specifying the lower and upper limit. Let us write now a program that sums all odd number in a given range M-N.

Program to find sum of odd numbers in given range M-N

/**
 * C program to print the sum of all odd numbers from m to n
 */

#include <stdio.h>

int main()
{
    int m, n, sum=0;

    /* Reads range to find sum of odd numbers */
    printf("Enter lower limit: ");
    scanf("%d", &m);
    printf("Enter upper limit: ");
    scanf("%d", &n);

    /* If lower limit is even then make it odd */
    if(m % 2 == 0)
    {
        m++;
    }
    
    /* Iterate from m to n and find sum */
    while(m <= n)
    {
        sum += m;
        m += 2;
    }

    printf("\nSum of odd numbers = %d", sum);

    return 0;
}


Output
Enter lower limit: 4
Enter upper limit: 11

Sum of odd numbers = 32

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).

No comments:

Post a Comment