首页 > 其他分享 >02 - functions

02 - functions

时间:2022-10-21 12:37:14浏览次数:65  
标签:02 10 functions return cout int factorial result

functions

Summing Up Digits

img

using function to solve it

// every time get the last digit and add.

int sumOfDigitsOf(int n){
    int result = 0
    while (n > 0){
        result += (n % 10);
        n /= 10;
    }
    return result;
}

int main() {
    int n = getInteger("Enter an integer: ");
    int digitSum = sumOfDigitsOf(n);
    cout << n << " sums to " << digitSum << endl;
    return 0;
}

recursion

int sumOfDigitsOfByRecursion(int n){
    if (n < 10){
        return n;
    } else {
        return sumOfDigitsOfByRecursion(n / 10) + (n % 10);
    }
}

int main() {
    cout << "Summing up digits by recursion" << endl;
    int n = getInteger("Enter an integer: ");
    int digitSum = sumOfDigitsOfByRecursion(n);
    cout << n << " sums to " << digitSum << endl;
    return 0;
}

Factorials

  • The number n factorial, denoted n!, is n × (n – 1) × ... × 3 × 2 × 1
int factorial(int n){
    if (n == 0) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

int main(){
    int num = getInteger("Enter a integer: ");
    int factorialOfIt = factorial(num);
    cout << "Factorail of " << n << " is: " << factorail << endl;
    return 0;
}

标签:02,10,functions,return,cout,int,factorial,result
From: https://www.cnblogs.com/louis614/p/cs106b_02.html

相关文章