In: Computer Science
2.c++ if and loop statement Write a program that will count the number of even number and odd numbers between two inputted numbers. Display the numbers and compute the sum and average of all the even numbers and the sum and average all the odd numbers.
Sample outputs:
Enter starting number:3 Enter starting number:4
Enter ending number:10 Enter ending number:10
odd numbers Even number
3 4
5 6
7 8
9 10
number of even numbers=4 number of even numbers=4
sum=24 sum=28
average=6 average=7
Even number odd number
4 5
6 7
8 9
10
Number of even number=4 Number of even number=3
sum=28 sum=21
average=7 average=7
#include <iostream>
using namespace std;
int main() {
int num1,num2,count=0,count_odd=0,count_even=0,even_sum=0,odd_sum=0;
cout<<"Enter starting number : ";
cin>>num1;
cout<<"Enter ending number : ";
cin>>num2;
if(num1%2==0)
cout<<"Even numbers odd numbers\n";
else
cout<<"Odd numbers even numbers\n";
for(int i=num1;i<=num2;i++)
{
if(i%2==0)
{
count_even++;
even_sum+=i;
cout<<i<<" ";
count++;
}
else
{
count_odd++;
odd_sum+=i;
cout<<i<<" ";
count++;
}
if(count==2)
{
count=0;
cout<<endl;
}
}
if(num1%2==0)
{
cout<<"\nNumber of even numbers="<<count_even<<" Number of odd numbers="<<count_odd<<endl;
cout<<"sum="<<even_sum<<" sum="<<odd_sum<<endl;
cout<<"average="<<even_sum/count_even<<" average="<<odd_sum/count_odd;
}
else
{
cout<<"\nNumber of odd numbers="<<count_odd<<" Number of even numbers="<<count_even<<endl;
cout<<"sum="<<odd_sum<<" sum="<<even_sum<<endl;
cout<<"average="<<odd_sum/count_odd<<" average="<<even_sum/count_even;
}
}