Coding Practice

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

Find sum of all even numbers between 1 to n
Sample Output
Enter a number: 6

Even numbers are...

2
4
6
Sum: 12

Process returned 0 (0x0)   execution time : 217.563 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("\nEven numbers are...\n");

    for(n = 1; n <= num; n++)
    {
        if(n % 2 == 0)
        {
            sum += n; // Or, sum = sum + n;

            printf("\n%d", n);
        }
    }
    printf("\nSum: %d\n", sum);

    return 0;
}
Sample Output
Enter a number: 11

Even numbers are...

2
4
6
8
10
Sum: 30

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

No comments:

Post a Comment

Change Theme
X