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 all odd number between 1 to %d = %d", n, sum);

    return 0;
} 

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

Output
Enter any number: 10

Sum of all odd number between 1 to 10 = 25

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