Dremendo Tag Line

Input number and find sum of all odd and even digits in it using for loop in C++

for Loop - Question 12

In this question, we will see how to input a number and find the sum of all odd digits and even digits present in the number separately in C++ programming using for loop. To know more about for loop click on the for loop lesson.

Q12) Write a program in C++ to input a number and find the sum of all odd digits and even digits present in the number separately using for loop.

Program

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    int i,n,d,even=0,odd=0;

    cout<<"Enter a number ";
    cin>>n;

    for(i=n; i>0; i=i/10)
    {
        d=i%10;
        if(d%2==0)
        {
            even=even+d;
        }
        else
        {
            odd=odd+d;
        }
    }

    cout<<"Sum of even digits = "<<even<<endl;
    cout<<"Sum of odd digits = "<<odd;
    return 0;
}

Output

Enter a number 45612
Sum of even digits = 12
Sum of odd digits = 6
video-poster