C++ program to find odd numbers within a range then calculate sum of evens and sum of square of odds. (logic explained)
Here is the C++ code to find odd numbers within a range then calculate sum of evens and sum of square of odds. You all should have in mind how it works exactly. Here is the algorithm.
Steps
User side
1: User asked to enter first number of range
2: User asked to enter second number of range that should be greater than first
3: User displayed odd numbers within range
4: User displayed sum of even numbers within range
5: User displayed sum of squares of odd numbers within range
Developer side
1: Declare variables that are going to be used in program.
2: Input first number of range
3: Input second number of range that should be greater than first
4: If second number is less than first stop program here it must be greater
5: If second number is greater than first start a loop from first number of the range to the second
6: In the loop check if the number is modulus of 2 if(firstNum%2==0)
7: If above condition fails show the numbers its odd
8: If the above condition true add it to a variable that is initially zero (This is the sum of evens )
9: If the above condition false ,first multiply number by itself and then add it to a variable that is initially zero (This is the sum of squares of odds )
10: Program ends here
Here is the C++ code.
Code:
#include<iostream>
using namespace std;
int
main(){
//declaraton of
varables
int
firstNum,secondNum,sume=0,sumo=0;
//heading
cout<<"\n\t\t\t ***Start of program***"<<endl;
//input
of integers
cout<<"Enter first number ";
cin>>firstNum;
cout<<"Enter second number (It must be greater than first
number) ";
cin>>secondNum;
//the
conditon on first & second number
if(firstNum<secondNum)
{ cout<<"\t\t\t***First phase Odd numbers***"<<endl;
//loop
to repeat from first to second number
while(firstNum<=secondNum)
{ //to sum all
evens
if(firstNum%2==0)
{
sume=sume+firstNum;
}
else
{ //to print odd
cout<<firstNum<<endl;
//to sum square of odds
sumo=sumo+(firstNum*firstNum);
}
firstNum=firstNum+1;
}
cout<<"\t\t\t***First phase End***"<<endl;
cout<<"\t\t\t***Second phase sum of evens***"<<endl;
cout<<"Sum of Even numbers = "<<sume<<endl;
cout<<"\t\t\t***Second phase sum of evens***"<<endl;
cout<<"\t\t\***Third phase sum of square of odds***"<<endl;
cout<<"Sum of square ODD numbers = "<<sumo<<endl;
cout<<"\t\t\Third phase End"<<endl;
}
else
{ cout<<"First number is not less than second number"<<endl;}
cout<<"\n\t\t\t ***End of program***"<<endl;
system("pause");
return 0;
}
Is Zero an Even or an Odd Number
ReplyDelete