Printing sum of even and odd numbers using For Loop in C++
This is a C++ program that prompts the user to input a starting value and an ending value, and then calculates the sum of all even numbers between those values (including the starting value if it is even). Here is a brief explanation of the program:
- The program declares four integer variables: i, n, j, and a, and initializes j to 0 and reads the starting value from the standard input using the cin object.
- The program prompts the user to input the ending value, and reads it from the standard input using the cin object.
- The program enters a for loop that iterates over all even numbers between a and n, inclusive. In each iteration, the loop body is executed.
- In the loop body, the program adds the current value of i to the variable j. The i variable is incremented by 2 in each iteration to get the next even number.
- After the loop terminates, the program outputs the final value of j, which is the sum of all even numbers between a and n (including the starting value if it is even). The output is sent to the standard output using the cout object.
- Finally, the program returns 0 to the operating system, indicating successful execution.
Source Code
#include<iostream>
using namespace std;
int main()
{
int i,n,j=0,a;
cout<<"\nEnter the starting value:";
cin>>a;
cout<<"\nEnter the Ending value:";
cin>>n;
for(i=a;i<=n;i=i+2)
{
j+=i;
}
cout<<"\n"<<j;
return 0;
}
To download raw file
Click Here
Output
Enter the starting value:1
Enter the Ending value:10
25