Pages

Friday, April 4, 2025

Calculate Sum of Digits of a Number in Function in C++

 #include<iostream>

using namespace std;


void sum(int n) {
    int totalSum = 0;
   
    while(n > 0) { // calculates until loop reaches n
    totalSum = totalSum + n; // adds the no. to totalSum
    n--; // decrements n to break the loop at the end
    }
    cout << totalSum << " " << endl;
}

int main(){
    sum(5);

    return 0;
}

OUTPUT-
15

No comments:

Post a Comment

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...