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 range in C programming. Logic to find sum of odd numbers in a given range in C program.

**Example**

**Input**

Input upper limit: 10

**Output**

Sum of odd numbers from 1-10: 25

## Required knowledge

Must read - Program to print odd numbers in range

## Logic to find sum of odd numbers from 1 to n

Below is the step by step descriptive logic to find sum of first n odd numbers.

- Input upper limit to find sum of odd numbers from user. Store it in some variable say N.
- Initialize some other variable to store sum say sum = 0.
- Run a loop from
`1`

to N, increment`1`

in each iteration. The loop structure must look similar to for(i=1; i<=N; i++). - Inside the loop add the sum with the current value of i i.e. sum = sum + i.
- Print the final value of sum.

## Program to find sum of odd numbers from 1 to n

```
/**
* C program to print the sum of all odd numbers from 1 to n
*/
#include <stdio.h>
int main()
{
int i, n, sum=0;
/* Input range to find sum of odd numbers */
printf("Enter upper limit: ");
scanf("%d", &n);
/* Find the sum of all odd number */
for(i=1; i<=n; i+=2)
{
sum += i;
}
printf("Sum of odd numbers = %d", sum);
return 0;
}
```

**Note:** sum += i and sum = sum + i both are same.

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.

## Program to find sum of odd numbers in given range

```
/**
* C program to print the sum of all odd numbers in given range
*/
#include <stdio.h>
int main()
{
int i, start, end, sum=0;
/* Input range to find sum of odd numbers */
printf("Enter lower limit: ");
scanf("%d", &start);
printf("Enter upper limit: ");
scanf("%d", &end);
/* If lower limit is even then make it odd */
if(start % 2 == 0)
{
start++;
}
/* Iterate from start to end and find sum */
for(i=start; i<=end; i++)
{
sum += i;
}
printf("Sum of odd numbers between %d to %d = %d", start, end, sum);
return 0;
}
```

Output

Enter lower limit: 4 Enter upper limit: 11 Sum of odd numbers between 4 to 11 = 32

Happy coding 😉

### Recommended posts

- Loop programming exercises index.
- C program to check even odd using if else.
- C program to check even odd using bitwise operator.
- C program to check even odd using conditional operator.
- C program to check even odd using switch case.
- C program to print sum of all even numbers between 1 to n.
- C program to print all even numbers between 1 to 100.

<pre><code> ----Your Source Code---- </code></pre>