C Program to Find Sum of All Odd Numbers Between 1 to N using For Loop

  • Write a C program to find sum of all odd numbers between 1 to N using for loop.
  • Wap in C to print sum of all odd numbers between 1 to 100 using for loop.

Required Knowledge

C program to find sum of all odd numbers between 1 to N using for loop

#include <stdio.h>  
   
int main() {  
    int counter, N, sum = 0;  
    /* 
     * Take a positive number as input form user 
     */
    printf("Enter a Positive Number\n");
    scanf("%d", &N);
   
    for(counter = 1; counter <= N; counter++) {  
        /* Odd numbers are not divisible by 2 */ 
        if(counter%2 == 1) { 
            /* counter is odd, add it to sum */
            sum = sum + counter;  
        }  
    }
    printf("Sum of all Odd numbers between 1 to %d is %d", N, sum);
 
    return 0;  
}

Output:

Enter a Positive Number
9
Sum of all Odd numbers between 1 to 9 is 25