C++ Program to find the sum of digits of a number using call by Reference


In this program, You will learn how to find the sum of digits of a number using call by Reference in C++.


Call by Reference

void sumOfDigit(int n, int *sum){ }


Example: How to find the sum of digits of a number using call by Reference in C++

Run it Now
#include<iostream>
using namespace std;

void sumOfDigit(int n, int *sum) {
    int r;
    while (n > 0) {
        r = n % 10;
        *sum = *sum + r;
        n = n / 10;
    }
}

int main() {

    int n, sum = 0;

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

    sumOfDigit(n, &sum);
    cout << "\nSum of digits is : " << sum;

    return 0;
}

Output:

Enter a number : 1203
Sum of digits is : 6