Write a program to find the sum of all even numbers from 1 to n where the value of n is taken as input. [for example when n is 10 then the sum is 2+4+6+8+10 = 30] using only two variables
Answers
Program:
n = int(input("Enter a number"))
sum = 0
for i in range (1,(n+1),1):
if int(i % 2) == 0:
sum = sum + i
print("The sum is : ")
print(sum)
Output
Enter a number10
The sum is :
30
Language
Python 3
-----Hope this helps :)
Answer: C program is given below.
Concept : For loop and modulo operator
Given : Numbers are from 1 to n, and the program should be written using
only two variables.
To Find : Write a program to find the sum of all even numbers from 1 to n
where the value of n is taken as input.
Explanation:
#include<stdio.h>
#include<conio.h>
int main(){
int n, sum = 0 ;
printf("Enter the value of n : ");
scanf("%d\n", &n);
while(n ! = 1){
if(n % 2 == 0){
sum = sum + n;
}
n = n - 1;
}
printf("\n Sum of all even numbers according to the condition is %d", sum);
getch();
}
Output :
Enter the value of n : 5
Sum of all even numbers is 6
#SPJ3