Loop Exercises
C program to find sum of odd numbers from 1 to n
Write a C program to find 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 using loop in C programming.
Example
Input
Input upper limit: 10
Output
Sum of odd numbers from 1-10: 25
Required knowledge
Basic C programming, Relational operators, For loop
Logic to find sum of odd numbers from 1 to n
Step by step descriptive logic to find sum of odd numbers between 1 to n.
1.Input upper limit to find sum of odd numbers from user. Store it in some variable say N.
2.Initialize other variable to store sum say sum = 0.
3.To find sum of odd numbers we must iterate through all odd numbers between 1 to n. 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++).
4.Inside the loop add sum to the current value of i i.e. sum = sum + i.
5.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: Do not confuse with the shorthand assignment operator sum += i. It is equivalent to sum = sum + i.
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+=2) { 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