Understanding a code - c

I'm trying to understand a code here. I have been trying to understand it for quite a while now and since i can't completely understand it i'm turning to you for help.
#include<stdio.h>
int sumdig(int);
int main()
{
int a, b;
a = sumdig(123);
b = sumdig(123);
printf("%d, %d\n", a, b);
return 0;
}
int sumdig(int n)
{
int s, d;
if(n!=0)
{
d = n%10;
n = n/10;
s = d+sumdig(n);
}
else
return 0;
return s;
}
I can understand that the number will continue to pass the function until it reaches to 0 and then it returns 1 because 0==0 but after it returns 3 and finishes with a 6. That I don't understand. Remember i'm new to C

The first time round, with 123, n % 10 will evaluate to 3, and n / 10 will evaluate to 12, so it will return 3 + sumdig(12). sumdig(12) will, in the same way, return 2 + sumdig(1), sumdig(1) will return 1 + sumdig(0), and sumdig(0) will return 0, at which point it will stop. So overall, it will return 3 + 2 + 1, which is the sum of the digits in 123.

it is quite a basic recursive call...
the function sumdig is called in the following order:
1.sumdig(123):
d=3
n=12
s=3+sumdig(12)
2.sumdig(12):
d=2
n=1
s=2+sumdig(1)
3.sumdig(1):
d=1
n=0
s=1+sumdig(0)
4.sumdig(0): returns 0
3. return 1+0
2. return 2+1
1.returns 3+3
and that's how you get 6.

Related

How to multiply and print the digits of 2 numbers recursively

I'm looking for a way to multiply the digits of two numbers (not necessarily of the same digits length) recursively without using loops in the following way:
let's say the numbers are 123 and 567. I'm trying to figure out a way to print:
5
6
7
10
12
14
15
18
21
it's the left most digit of the first number times every digit of the second number starting from the left and moving in both the right most.
the function must fit the prototype:
void multi(int a, int b);
I've managed to dive recursively to 1 and 5 from there to 1 56 and then 1 567 and in every call I print the result of a%10 * b%10.
but when backtracking to 12 567 the function dives to 1 567 again.
here's my best attempt:
int main()
{
int a, b;
scanf("%d %d", &a, &b);
multi(a, b);
return 0;
}
void multi(int a, int b)
{
if (a == 0)
return;
multi(a / 10, b);
if(b /10 != 0)
multi(a, b / 10);
printf("%d\n", a % 10 * b % 10);
}
list of restricions:
no loops
single function
mandatory prototype
This is a possible solution:
void multi(int a, int b)
{
// First "consume" the first parameter
if ( a > 9)
multi(a / 10, b);
// Then the second, passing only one digit of the first
if ( b > 9 )
multi(a % 10, b / 10);
// Multiply the last digits before backtracking
printf("%d\n", (a % 10) * (b % 10));
}
Testable HERE.
Here the catch is that you need to run a routine for each sub a value of a with all of sub b values.
I think you need a bit more of divide a concur approach here. you send your reduced values but you fail to treat all the cases properly.
I would suggest a simpler approach which takes the values a and b, then for each a sub value run a routine to show all of the different cases by passing the entire b each time.
so that for each sub a value you get all of the multiplications with the sub b values.
#include <stdio.h>
static void AuxMul(int a, int b)
{
int bs;
if(0 == b)
{
return;
}
bs = b%10; /*save res for multipication */
AuxMul(a, (b/10)); /*now sent it back with the same a value and reduced b value */
printf("|%d| \n", (a*bs));
}
void MultPrintRec( int a, int b)
{
int as = 0;
if (0 == a )
{
return;
}
as = a%10; /*get the value to mult. with all the b values */
MultPrintRec(a/10, b); /*do this until there is nothing to send */
AuxMul(as, b); /*send to a rec aux function that will take care of sub a value sent with all of the sub b values*/
}
int main() {
MultPrintRec(123, 567);
return 0;
}
Hope this is clear and helpful, Good luck

increment digits of natural number recursively

I wanna make a funcion that will take a natural number and make a new number so every digit in the old number will be incremented and if the digit is 9 it will become zero, but not to check specificly if the digit is 9.
example:
930 will return 41
9999 will return 0
879021 will return 980132.
This is what i got so far:
int newNumber(int n)
{
int dig;
if (n < 9)
return n + 1;
dig = n % 10;
dig++;
n = n / 10;
n = n * 10 + dig;
return newNumber(n/10);
}
There are a couple of issues with your code:
It doesn't handle a single digit of 9 (which cause a stack overflow).
Adding 1 to 9 makes 10 not 0.
I've run it through the sample data you supplied and it seems to work (in C#) and it has a hard core recursive line at the end.
int newNumber(int n)
{
if (n == 9)
return 0;
if (n < 9)
return n + 1;
return (newNumber(n / 10) * 10) + newNumber(n % 10);
}
Here's to avoid the check for n == 9:
int newNumber(int n)
{
static int table[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
return (n <= 9) ? table[n] : (newNumber(n / 10) * 10) + newNumber(n % 10);
}
A lookup table seems the most appropriate and does exactly what the requirements describe. Trying to use the non-compatible arithmetic operators results in side effects (as we see in Bathsheba's answer for example), that then need to be corrected.
unsigned newNumber(unsigned n, unsigned c = 0)
{
return n ? (n + 1) % 10 + 10 * newNumber(n / 10, 1 + c) : !c;
}
is one way, and it will treat 0 as 1, via the !c branch where c counts the number of recursions. Note the tail recursion in the ternary conditional branch - some compilers will optimise a tail recursion out to a simple loop, see What is tail recursion?
Bathsheba's solution posted above is very elegant by using the ternary operator, but it will give you a wrong result if the input is zero. To avoid that you may use a stub function:
#include <stdio.h>
int incDigits(int n)
{
return n ? (n + 1) % 10 + incDigits(n / 10) * 10 : 0;
}
int newNumber(int n)
{
return n ? incDigits(n) : 1;
}
int main()
{
for(int i = 0; i <= 100; ++i)
{
int n = newNumber(i);
printf("%d -> %d\n", i, n);
}
}
EDIT: user meaning-matters also posted a way to fix the input value problem using a lookup table, but he still has to check if n equals 9, which is something you don't want. So I believe using a stub function still is the best way.
Two ternary operator has been used to take care of the two cases:
i) number equal to 9
ii) number not equal to 9 => Another ternary operator is used to take care of further two possible cases:
a) number greater than 9( return sum of num(n/10)*10 and num(n%10) ); this can be further elaborated based on the argument fed to the num function.
b)number smaller than 9(return number plus one(n+1))
Once this function is called from the main function with argument equal to the number to be transformed in the manner asked in the question, each call in line4 will undergo recursion until they pass the argument to the subsequent iteration less than or equal to 9(which leads to termination of the recursion). With basic understanding of recursion, the above para can easily be understood in context to the subroutine below.
Blockquote
int num(int n)//line1
{//line2
int t;//line3
t=(n==9?0:(n>9?num(n/10)*10+num(n%10):n+1));//line4
return t;/line5
}//line6
Blockquote

Use recursion to solve the position index in a sequence in a C Program? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So there is a sequence of integers, {𝑎1, 𝑎2, 𝑎3, … } , the pattern of this sequence is that 𝑎𝑛 = 𝑎𝑛−1 + (𝑛 − 1) and 𝑎1 = 1. So if the first five elements in the sequence are: {𝑎1 = 1, 𝑎2 = 1 + 1 = 2, 𝑎3 = 2 + 2 = 4, 𝑎4 = 4 + 3 = 7, 𝑎5 = 7 + 4 = 11 … } . I am trying to write a program in C to ask the user to input an integer (an) to be the position index for this sequence and calculate the value of that position in the sequence. Like the user inputs 7 and it prints that the answer is 22? I have to use recursion and honestly don't even know where to go from that...
I think I am figuring it out, but I am pretty sure this is how it should work and yet it is off by exactly 1!
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int num)
{
if (num!=0)
return num-1 + sum(num-1); // sum() function calls itself
else
return num;
}
If I give you a function that magically calculates a(n-1), you can easily calculate a(n) right?
int a(int n)
{
int previousA /*a(n-1)*/ = magic(); // magic() knows by itself which n to use
return previousA + n - 1;
}
What if I tell you that magic() is exactly the same as a(n-1)?
int a(int n)
{
int previousA /*a(n-1)*/ = a(n-1);
return previousA + n - 1;
}
Now, the only problem is that this kind of calling we would get an endless loop of calling - for a(3), a(2) is going to be called, then a(1), a(0), a(-1)... It'll never end.
What do we do?
Happily, we have an ending condition - a(1) is constant and equal to 1.
How do we insert it into the code? We insert a condition to check if n is 1, and if it is we simply return, with no further calls.
int a(int n)
{
if (n == 1)
{
return 1;
}
else
{
int previousA /*a(n-1)*/ = a(n-1);
return previousA + n - 1;
}
}
Or in short:
int a(int n)
{
return n == 1 ? a(n - 1) + n - 1 : 1;
}
(The ? and : are the syntax for a ternary operator. Read about it if you didn't understand them.)
For starters the name sum is not suitable because nothing is summarized. Maybe the function could be named like for example recursive_sequence.
The sequence is calculated for non-negative numbers. You have the base condition a[1] == 1 and the recursive condition a[n] = a[n-1] + ( n - 1 ). You should determine the value for the index equal to 0.
You have according to the conditions
a[1] == a[0] + ( 1 - 1 )
that is
a[1] == a[0] + 0
so a[0] is equal to 1.
Having this base condition for the index 0 you can write the function
unsigned int recursive_sequence(unsigned int n)
{
return n == 0 ? 1 : n - 1 + recursive_sequence(n - 1);
}
Pay attention to that the return type and the type of the parameter should be unsigned integer type.
Here is a demonstrative program
#include <stdio.h>
unsigned int recursive_sequence(unsigned int n)
{
return n == 0 ? 1 : n - 1 + recursive_sequence(n - 1);
}
int main( void )
{
const unsigned int N = 6;
for (unsigned int i = 0; i < N; i++)
{
printf("%u: %u\n", i, recursive_sequence(i));
}
return 0;
}
Its output is
0: 1
1: 1
2: 2
3: 4
4: 7
5: 11

Don't understand how Codility CountDiv solution is correct

Codility CountDiv Exercise:
Given a range A..B and value K, return the number of values in the range that are divisible by K.
The example given is A = 6, B = 11 and K = 2. In the range 6 to 11, the numbers divisible by 2 are 6, 8 and 10, so the answer is 3. The solution required must be O(1) - so a simple calculation is needed.
You can assume that A and B are in the range 0..2,000,000,000, K is 1..2,000,000,000 and that 0 <= A <= B.
The accepted solution, that scores 100% is as follows:
int solution(int A, int B, int K)
{
int inclusive = ((A%K)==0) ? 1 : 0;
return (B/K) - (A/K) + inclusive;
}
Where I get confused is that when I test this solution with inputs A=0, B=0 and K=1, the result is 1? I would have thought that in the range 0 to 0, the number of values divisible by 1 is... 0!
I thought this was an error and that the +1 for inclusive values of A should only be set if A is non-zero.
So I submitted the following solution (test that A is non-zero):
int solution(int A, int B, int K)
{
int inclusive = (A && (A%K)==0) ? 1 : 0;
return (B/K) - (A/K) + inclusive;
}
But this only scored 62% (50% correctness and 75% performance). Some of the test cases it failed were:
A = 0, B = 1, K = 11 - Got 0, expected 1
A = 0, B = MAXINT, K in {1,MAXINT}, got 2000000000, expected 2000000001
Can someone explain?
The value 0 is divisible by K for all K that are allowed (non zero). There is nothing special about zero. The definition of divisible means there is no remainder after dividing.
The range is inclusive: there is 1 value in the range 0 to 0: the value 0 itself. All values are divisible by 1, so the result is indeed 1 value.
Note that the proposed code is redundant:
int inclusive = ((A%K)==0) ? 1 : 0; is equivalent to int inclusive = (A%K)==0;. It can be further simplified as int inclusive = !(A%K); and the complete solution becomes a one-liner:
int solution(int A, int B, int K) { return B/K - A/K + !(A%K); }
And here is a variant with only 2 divisions:
int solution(int A, int B, int K) { return B/K - (A ? (A-1)/K : -1); }
Here is a C++ solution with 100/100 score
int solution(int A, int B, int K) {
return B / K - A / K + (A % K == 0 ? 1 : 0);
}
it returns the number of multiples in the interval [0, B] minus the number of multiples in the interval [0, A] - getting the number of multiples in the interval (A, B] - and adds the multiple in A if A is a multiple.
In my case, I just made the following math:
(B - A)/K + (A/K)
in same cases as explained before, this + (A/K) is very tricky because of some stupid inputs like A=0,B=0 etc. Then, for those cases, I made a treatment, and I'm calling it of adjustment.
There's the code:
class Solution {
public int solution(int startingFrom, int endingAt, int divisibleBy) {
double adjustment = startingFrom % divisibleBy == 0 || endingAt % divisibleBy == 0 ? 1 : ((double) startingFrom < divisibleBy) ? (double) startingFrom / divisibleBy : 0;
return (int) ( ((double) endingAt - startingFrom) / (divisibleBy) + adjustment);
}
}
Java code 100/100.
https://app.codility.com/demo/results/trainingS96J5R-NTC/

Adding Numbers Using Recursion In C

#include<stdio.h>
#include<conio.h>
int add(int n);
void main()
{
int n, ans;
clrscr();
printf("Enter Number:");
scanf("%d", &n);
ans = add(n);
printf("%d", ans);
getch();
}
int add(int n)
{
if (n==0)
{
return 0;
} else {
return n + add(n-1);
}
}
I have some doubts related recursion programs which have this type of return statements. Can anyone explain me it in a proper way.
I am not able to understand that thing if I am writing return 0 when n==0 then why it returns value from else.Why answer is not 0.I am confused in return statement.
Plz help me.
Thank You In Advance.
Lets take a simple example: add(2).
In that initial call we go to the else branch (because n is not zero) and do return 2 + add(2 - 1) (i.e. return 2 + add(1)).
That leads to the second calls, which also goes to the else branch and does return 1 + add(1 - 1) (i.e. return 1 + add(0)).
That leads to a call in which n is equal to zero and so we return zero.
That returns to the return 1 + add(1 - 1) part, which is equal to return 1 + 0 so return that.
That returns to the return 2 + add(2 - 1) part, which now is equal to return 2 + 1.
And that takes us back to the initial call, giving the result 3.
It can be laid out in a tree something like
add(2) -> return 2 + add(2 - 1)
add(1) -> return 1 + add(1 - 1)
add(0) -> return 0
add(1) -> return 1 + 0
add(2) -> return 2 + 1

Resources