// this is a recursive function for finding the sum of digits in C language
//I'm not getting any output in my IDE.
int dsum(int n)
{
int a, r;
r = n % 10;
a = r + dsum(n / 10);
return a;
}
int main()
{
int a;
a= dsum(12345);
printf("%d",a);
return 0;
}
A recursion function should always have a base case as a final return, in this case it's when n equals 0, which means all digits were summed (when msb digit is divided by 10 the result is 0).
Then you'll have the return which will call the function with the result of the current lsb digit (or right most digit) + the result of the function with the input of n/10
int dsum(int n)
{
if (n == 0) {
return 0;
}
return n % 10 + dsum(n / 10);
}
int main()
{
int a;
a = dsum(12345);
printf("%d",a);
return 0;
}
BTW, I also suggest looking into tail recursion:
https://en.wikipedia.org/wiki/Tail_call
In this scenario, it might look like that:
int dsum_tail_recursion(int n, int sum)
{
if (n == 0) {
return sum;
}
return dsum_tail_recursion(n/10, n%10 + sum)
}
int main()
{
int a;
a = dsum_tail_recursion(12345, 0); // 0 is the sum start value
printf("%d",a);
return 0;
}
Related
As a new learner of C, I managed to go this far in this little exercice, the code works (kind of). It doesn't work for the second time, the output just adds up.
int i = 0;
void inverse(unsigned int n) {
int reste;
if (n != 0) {
reste = n % 10;
i = (i * 10) + reste;
inverse(n / 10);
} else {
printf("%d \n", i);
}
}
void main() {
inverse(1589);
inverse(42);
}
Output:
9851
985124
Your approach fails because i is not cleared before each new case. You could clear i after the printf, but a better approach is to avoid global variables. You can modify inverse for this purpose by removing the recursion:
#include <stdio.h>
void inverse(unsigned int n) {
unsigned int i = 0;
while (n != 0) {
unsigned int reste = n % 10;
i = i * 10 + reste;
n = n / 10;
}
printf("%u\n", i);
}
int main() {
inverse(1589);
inverse(42);
return 0;
}
Note these remarks:
you must include <stdio.h> to use printf()
main return type is int.
for consistency, i should have type unsigned int.
Some numbers will produce incorrect output as their inverse exceeds the range of unsigned int eg: 1000000009. You can remove this shortcoming by printing the digits instead of combining them as a number:
void inverse(unsigned int n) {
while (n > 9) {
putchar('0' + n % 10);
n = n / 10;
}
putchar('0' + n);
putchar('\n');
}
You need to reset i at some point. The most straight forward and horrible way is to simply do it after the printf().
But you should better redesign the recursion to work without global variables. Which is not easily done with any similarity to the shown code.
This is (I realised a little late) more or less what luk2302 recommended in a comment on a deleted answer.
#include <stdio.h>
int i = 0;
void inverse(unsigned int n){
int reste;
if (n != 0) {
reste = n % 10;
i = (i * 10) + reste;
inverse(n / 10);
}
else {
printf("%d \n", i);
i=0;
}
}
void inverse2(int number, int reversed)
{
if (number < 1)
{
printf("%d \n",reversed);
} else
{
inverse2(number/10, reversed*10+number%10);
}
}
void main(){
inverse(1589);
inverse(42);
inverse(123);
inverse2(1589,0);
inverse2(42,0);
inverse2(123,0);
}
Output:
9851
24
321
9851
24
321
I do not understand why the return .... does not work. Somehow, Output is always 0. Here the return call to atoi always outputs 0.
#include <stdio.h> //INCLUDES
#include <stdlib.h>
int reverse (int x); //Func Decls
int
main ()
{
printf ("%d", reverse (123)); //123=321, -123=-321, 120=21, 0=0
return 0;
}
int
reverse (int x)
{
int i, rem = 0;
char arr[15];
while (x % 10 != 0)
{
rem = x % 10;
arr[i] = ((char)rem);
x /= 10;
i++;
}
return atoi(arr); //OUTPUT = 0, does not return actual output
}
You don't need an array nor atoi function for this task, and the logic of while loop is not correct. A correct and simple one could be something like that (provided that no integer overflow occurs):
#include <stdio.h>
int reverse (int x)
{
int r = 0;
while (x != 0) {
r = 10 * r + x % 10;
x /= 10;
}
return r;
}
int main (void)
{
printf("%d\n", reverse(1234));
return 0;
}
The problem is the usage of atoi() function. The atoi() function basically converts a string with numeric characters codified in ASCII to an integer.
If you look the ASCII table, the numbers 1, 2 and 3 codify the characters '^A', '^B' and '^C', respectively. This means that, after the while loop in reverse() function, the string passed as argument to atoi() is not a numeric string, so zero is returned as an error. Also, the characters '1', '2' and '3' are codified as numbers 49, 50 and 51, respectively.
Now, I suggest you to change your entire implementation, because it does not make sense to receive an integer as input to operate with and, during the operation, convert it to string to return an integer again using atoi(). So, forget strings, ASCII, and atoi().
Lets start creating a loop to operate with each digit of the number, using the module operator, as you did.
int reverse (int x) {
int result = 0;
while ( x != 0 ) {
result = x%10;
}
return result;
}
Then, to insert another digit to the result, do the opposite: multiply it by 10.
int reverse (int x) {
int result = 0;
while ( x != 0 ) {
result = result*10 + x%10;
}
return result;
}
Now, cut the target digit out of the x, dividing it by ten.
int reverse (int x) {
int result = 0;
while ( x != 0 ) {
result = result*10 + x%10;
x /= 10;
}
return result;
}
Finally, the entire code.
#include <stdio.h>
#include <stdlib.h>
int reverse (int x);
int main () {
printf ("%d\n", reverse(123));
printf ("%d\n", reverse(-123));
printf ("%d\n", reverse(120));
printf ("%d\n", reverse(0));
return 0;
}
int reverse (int x) {
int result = 0;
while ( x != 0 ) {
result = result*10 + x%10;
x /= 10;
}
return result;
}
And the result, as expected:
$ gcc -Wall -std=c99 -o program program.c
$ ./program
321
-321
21
0
$
Based on your code, you can fix your code a little bit to make it works. Below is my opinion:
#include <stdio.h> //INCLUDES
#include <stdlib.h>
int reverse (int x); //Func Decls
int main () {
printf ("%d", reverse (123)); //123=321, -123=-321, 120=21, 0=0
return 0;
}
int reverse (int x) {
int i, rem = 0;
int arr[15];
while (x != 0)
{
rem = x % 10;
arr[i] = rem;
x /= 10;
i++;
}
int result = 0;
for (int j = 0; j < i; j++) {
result = 10 * result + arr[j];
}
return result;
}
regarding:
int i, rem = 0;
and
arr[i] = ((char)rem);
the local variable i in not initialized!. on my system the result is a seg fault event.
I have a difficulty in implementing the tail recursive solution of the following problem:
There is another recursive relation for the double factorial, which also depends on the factorial, which is the above: (for n<20)
I have to implement a recursive relation of this equation- which I did as the above code that works:
long long factorial(int n) {
if (n < 0)
return 0;
if (n < 1)
return 1;
return n * factorial(n - 1);
}
long long doublefactorial(int n) {
if (n < 0)
return 0;
if (n < 2)
return 1;
return factorial(n) / doublefactorial(n - 1);
}
Now I have to implement the same problem using a tail recursion. can someone show me how to do this because I cant figure it out. (no need to implement the factorial function also in a tail recursive way)
test cases:
5!! = 15
10!! = 3840
18!! = 185,794,560
-10!! = 0
Here is a tail-recursive version of Factorial function:
long factorial(int n, int factor)
{
if (n == 0)
return factor;
return factorial(n-1, factor * n);
}
factorial(5, 1); // 120
Here's a tail-recursive double factorial with a simpler logic:
long doublefactorial(int n, int factor)
{
if (n < 0)
return 0;
if (n < 2)
return factor;
return doublefactorial(n-2, factor * n);
}
printf("%d ", doublefactorial(5,1)); // 15
printf("%d ", doublefactorial(10,1)); // 3840
printf("%d ", doublefactorial(18,1)); // 185794560
If you expand your math a little bit you'll get that the factorial function result is iterating between the numerator and the denominator of the final result.
so this code will do that in Python
def _factorial(n, m):
if n < 0:
return 0
elif n == 0:
return 1.0 * m
return _factorial(n - 1, n * m)
def factorial(n):
return _factorial(n, 1)
def _doublefactorial(n, m, is_even):
if n < 0:
return 0
elif n < 2:
return 1.0 * m
if is_even:
m *= factorial(n)
else:
m /= factorial(n)
return _doublefactorial(n - 1, m, (not is_even))
def doublefactorial(n):
return _doublefactorial(n, 1, True)
And in C:
unsigned int _factorial(const unsigned int n, const unsigned int m) {
if (n < 0) {
return 0;
} else if (n == 0) {
return m;
}
return _factorial(n - 1, n * m);
}
unsigned int factorial(const unsigned int n) {
return _factorial(n, 1);
}
double _doublefactorial(const unsigned int n, const double m, const char is_even) {
double value = m;
if (n < 0) {
return 0;
} else if (n < 2) {
return m;
}
if (is_even) {
value *= factorial(n);
} else {
value /= factorial(n);
}
return _doublefactorial(n - 1, value, !is_even);
}
double doublefactorial(const unsigned int n) {
return _doublefactorial(n, 1, 1);
}
Your definition of this double factorial function is incomplete: you need an initial value such as 0!! = 1. From the recurrence definition, it appears that p!! is the product of all numbers from 1 to p that have the same parity as p:
5!! = 1 * 3 * 5 = 15
6!! = 2 * 4 * 6 = 48
10!! = 2 * 4 * 6 * 8 * 10 = 3840
Computing the double factorial by computing the factorial and dividing by the result of the double factorial of the previous number will fail for numbers larger than 19 because of the limited range of integer types and the exponential growth of the factorial function. The double factorial grows quickly too, but its logarithm grows half as fast as that of the factorial function.
Here is an recursive function:
unsigned long long doublefactorial(int n) {
if (n < 0)
return 0;
if (n < 2)
return 1;
return n * doublefactorial(n - 2);
}
Here is a tail recursive implementation with a helper function:
unsigned long long doublefactorial_helper(int n, unsigned long long res) {
if (n < 2)
return res;
return doublefactorial(n - 2, res * n);
}
unsigned long long doublefactorial(int n) {
return doublefactorial_helper(n, n >= 0);
}
The trick to convert the first function to a tail recursive one is instead of waiting for the result and multiplying then by n, pass an updated intermediary result to the recursive function. The multiplications are performed in the opposite order but will produce the same result (even modulo ULLONG_MAX+1).
I was having some problem when trying to do a recursive in C programming. Here is the expected output:
Enter a number: 1234567
Enter the digit position: 3
rDigitValue1(): 5
rDigitvalue2(): 5
And here is my code:
int rdigitValue1(int num, int k)
{
int count = 0, output;
if (count != k) {
rdigitValue1(num / 10, k);
count++;
}
else {
output = (num % 10);
}
return output;
}
The parameter num is the number whereas the parameter k is the position. With these code, when I try to run the program, it just crashed without prompting any error message. Any idea?
Modified
void rdigitValue2(int num, int k, int *result)
{
if (k != 1) {
rdigitValue2(num / 10, k - 1, result);
*result = num;
}
else {
*result = num % 10;
}
}
You are getting a stack overflow! You are never decrementing digit position and keep looping. Your current code can be simplified to:
int rdigitValue1(int num, int k)
{
if (k != 0) {
rdigitValue1(num / 10, k);
}
}
You should use k - 1 for your recursive call, you keep testing if k == 0 and of course it never is since you keep using the same value for k. You also need to store the value returned from the recursive call so that you can return it:
output = rdigitValue1(num / 10, k - 1);
Expected output :
rDigitvalue2(): 5
Current output :
rDigitvalue2(): 1234567
The function you wrote is :
void rdigitValue2(int num, int k, int *result)
{
if (k != 1) {
rdigitValue2(num / 10, k - 1, result);
*result = num;
}
else {
*result = num % 10;
}
}
The above function works well in my g++ compiler. The value for *result in the end is 1234567 for your function because your recursive call ends in the line *result = num.
You need to remove this line and modify your function to :
void rdigitValue2(int num, int k, int *result)
{
if (k != 1) {
rdigitValue2(num / 10, k - 1, result);
}
else {
*result = num % 10;
}
}
Output : rDigitvalue2(): 5
I am writing a C program which should display me all numbers between 100 and 1000 which sum of digit is 20. I tried this code down here, but it just displays 0 as an ouput when I compile it, can you help me? I also tried moving if(iVsota==20) outside of the while loop. I am using Orwell Dev C++ IDE.
#include <stdio.h>
int main (void)
{
int iVnos=0;
int iOstanek=0;
int iVsota=1;
int iStevec1=100;
for(iStevec1=100; iStevec1<1000; iStevec1++)
{
while(iStevec1>0)
{
iOstanek=iStevec1%100;
iStevec1=iStevec1/10;
iVsota=iOstanek+iVsota;
if(iVsota==20)
{
printf("%i\n", iStevec1);
}
}
}
return(0);
I hope this is better.
Your loop should look like :
for(iStevec1=100; iStevec1<1000; iStevec1++)
{
int c2 = iStevec1/100; // extract third digit
int c1 = (iStevec1%100)/10; // extract second digit
int c0 = (iStevec1%10); // extract first digit
if((c0+c1+c2)==20) // sum and verify
{
printf("%i\n", iStevec1);
}
}
This should work for you:
(Changed the variable names so it's more readable)
#include <stdio.h>
int add_digits(int n) {
static int sum = 0;
if (n == 0)
return 0;
sum = n%10 + add_digits(n/10);
return sum;
}
int main() {
int start, end;
start = 100, end = 1000;
for(start = 100; start <= end; start++) {
if(add_digits(start) == 20)
printf("Number: %d\n", start);
}
return 0;
}
EDIT:
(Your code fixed with comments as explanation)
#include <stdio.h>
int main() {
int iVnos=0;
int iOstanek=0;
int iVsota=0;
int iStevec1=100;
int temp; //temp needed
for(iStevec1=100; iStevec1<=1000; iStevec1++)
{
temp =iStevec1; //assign number to temp
iVsota=0; //set sum every iteration to 0
while(temp>0)
{
iOstanek=temp%10; //You need only % 10 to get the last digit of a number
temp = temp / 10; //'delete' last digit of the number
iVsota+=iOstanek; //add digit to sum
}
if(iVsota==20) //You only need to check the digits after sum is calculated
printf("Number %d\n", iStevec1);
}
return 0;
}
Here's a more generalised method to get the sum of all individual numbers in an integer (assumes positive integers):
int getSumOfDigits(int x)
{
int sum = 0;
while (x > 0)
{
sum += x % 10;
x = x / 10;
}
return sum;
}
int main()
{
for (int i = 100; i <= 1000; i++)
{
if (getSumOfDigits(i) == 20)
{
printf("%d\n", x);
}
}
}
The expression x % 10 is the last digit in the integer. Hence, that's what we add. Then we chop off the last digit in the integer by dividing it by 10. Repeat until we hit zero.
Alternative method, taking advantage of the specifics.
#include <stdio.h>
int main()
{
int c0, c1, c2; /* 3 digits sum to 20 */
for(c0 = 2; c0 < 10; c0++){
c1 = 11 - c0;
c2 = 9;
while(c1 < 10){
printf("%d%d%d\n", c0, c1, c2);
/* or printf("%3d\n", (c0*10+c1)*10+c2); */
c1++;
c2--;
}
}
return(0);
}
Just change 1 thing and you will get what you want
int main (void)
{
int iVnos=0;
int iOstanek=0;
int iVsota=1;
int iStevec1=100;
int temp;
for(iStevec1=100; iStevec1<1000; iStevec1++)
{
temp = iStevec1;
while(temp>0)
{
iOstanek=temp%100;
temp=temp/10;
iVsota=iOstanek+iVsota;
if(iVsota==20)
{
printf("%i\n", iStevec1);
}
}
}
return(0);
}
Enjoy Coding Enjoy Life...