In: Computer Science
Write a program in C++ that prints out the even numbers between 1 and 21 using WHILE loop.
Also, find the sum AND product of these numbers and display the resulting sum and product.
#include <iostream>
using namespace std;
int main()
{int sum=0; //variable to store sum of even numbers
long product=1;//variable to store product of even numbers
int i=1; //loop variable starts from 1
while(i<21) //run the loop till i=21
{if(i%2==0){ //if number is divisible by 2 i.e even number
cout <<i<< endl; //print even number
sum=sum+i; //calculate the sum
product=product*i; //calculate the product
i++; //increement the loop variable
}
else //if number is odd,increement the loop variable
i++;
}
cout <<"Sum of even numbers between 1 and 21 :
"<<sum<< endl;
cout <<"Product of even numbers between 1 and 21 :
"<<product<< endl;
return 0;
}
/********OUTPUT*********
2
4
6
8
10
12
14
16
18
20
Sum of even numbers between 1 and 21 : 110
Product of even numbers between 1 and 21 : 3715891200
********OUTPUT************/
/* Note:Please get back in case of any doubt,Thanks */