116k views
0 votes
(b) Write a C program to find the sum of all even numbers between 1 and n. User has to input the n number and the program has to verify this is a number before calculating the sum. Example: User's input and program output Input a number larger than 1: 100 Sum of even numbers between 1 and 100: 2550

User Akiba
by
7.6k points

1 Answer

2 votes

Answer:

#include <stdio.h>

int main() {

int n, i, sum = 0;

printf("Input a number larger than 1: ");

if (scanf("%d", &n) != 1 || n <= 1) {

printf("Invalid input!\\");

return 0;

}

for (i = 2; i <= n; i += 2) {

sum += i;

}

printf("Sum of even numbers between 1 and %d: %d\\", n, sum);

return 0;

}

User Luiz Viola
by
7.7k points