Calculate the sum of the digits of a 5 digit number using recursion
#include<iostream>
#include<conio.h>
using namespace std;
int check_five(int number);
int add(int number);
int main()
{
int number = 0, sum = 0, remainder = 0, temp = 0,
check = 0;
while(check != 1)
{
system("cls");
cout
<< "\n
__ Program to calculate the sum of the digits of 5 digit number
___";
cout
<< "\n\n\n Enter the Number - ";
cin
>> number;
check
= check_five(number);
if (check == 0)
{
//__ Error Message____
cout
<< "\n\n\t\t____ 5 digit number is
required ____";
cout
<< "\n\n\n Press Enter to Continue....";
while(getch() != 13)
{
}
}
}
sum =
add(number);
cout
<< "\n\n
The sum of the digits of number " << number << " is " << sum;
getch();
return 0;
}
int check_five(int number)
{
int remainder = 0, counter = 0;
while(number != 0)
{
remainder
= number % 10;
number
= number / 10;
counter++;
}
if (counter == 5)
/*___ Change 5 to make this program for any digit number,
but do check the value of integer
before
doing that */
{
return 1;
}
else
{
return 0;
}
}
int add(int number)
{
if(number == 0)
{
return 0;
}
else
{
return (number % 10) + add(number/10);
}
}
No comments:
Post a Comment