C Program to find sum of all odd numbers

Category: C Program
Tags: #cprogram#loops

Write a C Program to find the sum of all odd numbers from 1 to n using for loop and if statement. How to find the sum of all odd numbers from 1 to n using for loop and if statement. Logic to find the sum of all odd numbers from 1 to n.

C Program to find the sum of all odd numbers from 1 to n

#include <stdio.h>

void main()
{
    int i, n, sum = 0;
    printf("Enter value of n: ");
    scanf("%d", &n);

    for (i = 1; i <= n; i++)
    {
        if (i % 2 != 0)
        {
            sum = sum + i;
        }
    }

    printf("Sum of even numbers from 1-%d: %d", n, sum);
}

Output

Enter value of n: 20
Sum of even numbers from 1-20: 100