Coding Practice

Write a C program to find sum of all odd numbers between 1 to n

Find sum of all odd numbers between 1 to n
Sample Output
Enter a number: 10

Odd numbers are...
1
3
5
7
9

Sum: 25

Process returned 0 (0x0)   execution time : 91.045 s
Press any key to continue.
Source Code
#include<stdio.h>

int main()
{
    int n, num, sum = 0;
    
    printf("Enter a number: ");
    scanf("%d", &num);

    printf("\nOdd numbers are...\n");
    
    for(n = 1; n <= num; n++)
    {
        if(n % 2 != 0)
        {
            sum += n; // Or, sum = sum + n;
            
            printf("%d\n", n);
        }
    }
    printf("\nSum: %d\n", sum);
    
    return 0;
}
Sample Output
Enter a number: 7

Odd numbers are...
1
3
5
7

Sum: 16

Process returned 0 (0x0)   execution time : 24.620 s
Press any key to continue.

No comments:

Post a Comment

Change Theme
X