Hi, I have been doing this exercise from a book - stated below
a.Prompt the user to input two integers: firstNum and secondNum (Hint: Ensure that firstNum is less than secondNum).
b. Output all odd numbers between firstNum and secondNum
c. Output the sum of all even numbers between firstNum and secondNum.
d. Output the numbers and their square between firstNum and secondNum.
e. Output the sum of the squares of the odd numbers between firstNum and secondNum
I have written some codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
#include<iostream>
using namespace std;
int main()
{
int firstNum,secondNum,j,sum,sum_square_odd,i,k;
cout<<"Enter two integers"<<"\n";
cin>>firstNum>>secondNum;
j=firstNum;
i=firstNum;
k=firstNum;
sum=0;
sum_square_odd=0;
while(j<secondNum-1)
{
j++;
if(j % 2 != 0)
{
cout<<j<<" ";
sum_square_odd = sum_square_odd + (j * j);
}
if(j % 2 == 0)
{
sum = sum + j;
}
if(j>1 && j<10)
{
cout<<j<<" "<<j*j<<" ";
}
}
cout<<"The sum of squares of odd numbers are"<<" "<<sum_square_odd<<"\n";
cout<<"The sum of all even numbers are"<<" "<<sum<<"\n";
return 0;
}
|
However, when I run the program, the following answers are deployed.
Enter two integers
3 15
4 16 5 5 25 6 36 7 7 49 8 64 9 9 81 11 13 The sum of squares of odd numbers are 445
The sum of all even numbers are 54
Press any key to continue . . .
I entered 3 as my firstNum and 15 as my secondNum. The programming is correct, but i want the answers to be displayed such :
The odd numbers should be displayed first then the numbers and their square. Right now..it is mixed up..is there any way to work around this