In: Computer Science
Write a C++ code to perform the following steps:
1. Ask the user to enter two whole numbers number1 and number2 ( Number 1 should be less than Number 2)
2. calculate and print the sum of all even numbers between Number1 and Number2
3. Find and print all even numbers between Number1 and Number2
4. Find and print all odd numbers between Number1 and Number2
5. Calculate and print the numbers and their squares between 2 and 20 (inclusive)
6. Calculate and print the sum of the square of the odd numbers between Number1 and Number2
CPP Program :
//header files
#include <iostream>
using namespace std;
//main() method
int main()
{
//declaring variable to store number1
int number1=0;
//declaring variable to store number2
int number2=0;
//declaring variable to store sumOfEvens
int sumOfEvens=0;
//declaring variable to store sum of the square of the odd
numbers
int sumOfOddNumbers=0;
//asking user to enter number1
cout<<"Enter number1 : ";
//reading number1
cin>>number1;
//asking user to enter number2
cout<<"Enter number2 : ";
//reading number2
cin>>number2;
while(number2<number1)
{
//if number2 is less than number1 then
//asking user to enter number
cout<<"Enter number2 greter than "<<number1<<" :
";
//reading number2
cin>>number2;
}
cout<<"Even numbers between "<<number1<<" and
"<<number2<<" : "<<endl;
//using for loop
for(int i=number1;i<=number2;i++)
{
//checking numbers for odd and event
if(i%2==0)
{
//if even number then print it
cout<<i<<" ";//print even numbers
//add i to the sumOfEvens
sumOfEvens+=i;
}
}
cout<<"\nOdd numbers between "<<number1<<" and
"<<number2<<endl;
//using for loop
for(int i=number1;i<=number2;i++)
{
//checking numbers for odd and event
if(i%2!=0)
{
//if odd number then print it
cout<<i<<" ";//print even numbers
sumOfOddNumbers+=i*i;//square number and store in the
sumOfOddNumbers
}
}
//print sum of even numbers
cout<<"\nSum of even numbers
:"<<sumOfEvens<<endl;
//print sum of the square of the odd numbers
cout<<"Sum of the square of the odd numbers between
"<<number1<<" and "<<number2<<" :
"<<sumOfOddNumbers<<endl;
// print the numbers and their squares between 2 and 20
cout<<"Numbers and their squares between 2 and
20"<<endl;
cout<<"Number Square"<<endl;
cout<<"----------------------"<<endl;
//using for loop
for(int i=2;i<=20;i++)
{
cout<<i<<" "<<(i*i)<<endl;//print number
and square
}
return 0;
}
============================================================
Output :