Print the sum of all numbers from 1 to n. Print the sum of all even numbers as well as odd numbers from 1 to N


Program to print the sum of all even numbers, odd numbers and total sum of all numbers from 1 to N

        If the number is completely divisible by 2 it is even else the number is odd. Learn more about loops here and operators here!


Code

#include<bits/stdc++.h>

using namespace std;


int main(){


    cout<<"Enter a number"<<endl;

    int n;      //to store number

    cin>>n;     //reading a number


    int sum=0;             //to store total sum

    int evensum=0;    //to store even sum

    int oddsum=0;    //to store odd sum


    for(int i=1;i<=n;i++){     //loop to go through all numbers

        if(i%2==0){

            evensum=evensum+i;    //if even add to evensum

        }

        else{

            oddsum=oddsum+i;    //if odd add to oddsum

        }

    }


    sum=evensum+oddsum;    //final sum

    

    //printing the required data

    cout<<"Sum of all even numbers in a given range is: "<<evensum<<endl;

    cout<<"Sum of all odd numbers in a given range is: "<<oddsum<<endl;

    cout<<"Sum of all numbers in a given range is: "<<sum<<endl;


    return 0;

}


Output

Enter a number
7
Sum of all even numbers in a given range is: 12
Sum of all odd numbers in a given range is: 16
Sum of all numbers in a given range is: 28

Post a Comment

0 Comments