Menu

Wednesday, 13 May 2015

Chapter 5,Problem a: Let Us C by Yashawant Kanetkar solution manual

Problem Statement:

A 5-digit positive integer is entered through the keyboard,
write a function to calculate sum of digits of the 5-digit
number:
(1) Without using recursion
(2) Using recursion

Solution:


//Ahmad Furqan
//P5.a
#include <iostream>
#include <conio.h>
using namespace std;
int dig_sum(int num)
{
int sum = 0;
for (int i = 0; i < 5; i++) //5 iterations for each digit
{
sum += num % 10; //remainder of number divided with 10 is the rightmost digit
num = num / 10; //dividing number with 10 eliminates reightmost digit.
}
return sum;
}
int dig_sum_rec(int num)
{
if (num <10)
return num;
//return sum of rightmost digit and sum of digits of number without rightmost digit
return dig_sum_rec(num / 10) + (num % 10);
}
void main(void)
{
int num;
cout << "Enter 5 digit number:";
cin >> num;
cout << "Sum of digits without recursion: " << dig_sum(num);
cout << "\nSum of digits with recursion: " << dig_sum_rec(num);
_getch();
}

No comments:

Post a Comment