Advertisement

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) {
     //statement
}

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

#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 << "Sum of digits:" << sum;

    return 0;
}

Output:

Enter a number:1234
Sum of digits:10