I am getting unexpected output - c

I assumed the output to be '0' for the following code but, I am getting the output as '3'.
#include<stdio.h>
int num_digit(int n);
int num_digit(int n)
{
if (n == 0)
return 0;
else
return 1 + num_digit(n/10);
}
int main() {
int k = num_digit(123);
printf("%d\n",k);
return 0;
}

The following link provides an excellent source for learning C Recursion and as #MFisherKDX pointed out help solve my confusion.
https://www.programiz.com/c-programming/c-recursion
After each time the recursion happens it returns a value.
adding up all the values :
0+1 = 1
1+1 = 2
2+1 = 3
gives the answer as 3.

This is basic recursion. Just try to create a recursion tree for the program that you have written and you should be able to figure out why is the output that you see coming as 3.
You are expecting 0 as answer, only based on the last recursive call (terminating condition), but when a recursive call happens, there is a concept of activation records which are maintained in the form of Stack data structure.
The recursion tree will look something like what is shown in Recursion Tree for shared code
num_digits(123) = 1 + num_digits(12)
num_digits(12) = 1 + num_digits(1)
num_digits(1) = 1 + num_digits(0)
num_digits(0) = 0
Using substitution:
num_digits(123) = 1 + (1 + (1 + (0)))
Please follow the parenthesis above clearly and you should be able to absolutely understand the output that you were getting out of the code that you wrote.

Recursion stack for your code is like below
1 + num_digit(123/10);
1 + num_digit(12/10);
1 + num_digit(1/10); //at this point your code will return 0 for num_digit(1/10)
and backtracking is like below
1+0=1
1+1=2
1+2=3
Hence the final answer is 3

Related

What is the cause for 'Segmentation fault (core dumped) '

I wrote a program to find the prime factors of a number using recursion. I am getting an run time error. What is the cause?
#include<stdio.h>
int main () {
int num , i = 2 ;
printf ( " Enter the number to find the prime factors\n ") ;
scanf ( "%d", &num ) ;
printf ( " The factors are :\n") ;
pf ( num , i ) ;
}
int pf ( int num , int i){
if ( num % i == 0 ){
if ( checkprime(i) == 1){
printf ( " %d " , i ) ;
num = num / i ;
}
}
if ( num > 1 ){
i++ ;
pf ( num , i ) ;
}
}
int checkprime ( int i){
int j ;
if (i==2)
return 1 ;
for ( j = 2 ; j < i ; j++ ){
if ( (i % j) == 0 )
return 0 ;
else
return 1 ;
}
if ( i==j )
return 1 ;
}
Sample run:
Enter the number to find the prime factors
12
The factors are :
Segmentation fault (core dumped)enter code here
This looks like a learning exercise you want to solve on your own, so I won’t be writing code for you. (If you try to plug the sample code here into your program without refactoring, it won’t work.)
In the spirit of teaching you to fish, the first thing you should do is compile without optimization, with debugging symbols, and with all warnings turned on. On gcc/clang/icc, the flags for that will be something like:
-std=c11 -Wall -Wextra -Wpedantic -Wconversion -g
This code should not even compile. You’re repeatedly falling through to the end of a function that does not return the void type, yet falls through with no return statement. Not only that, you define pf() and checkprime() after they are called with no prototype! That’s not the only bug, but let’s start there.
You’re technically supposed to have a return from main(), too, but so many programs don’t that the C committee just gave in and said it’s optional.
A good next step to catch a bug is to load the program in a debugger, put a breakpoint on the function you want to debug, and single-step through it.
When you do this, you see that the program goes into an infinite loop if you give it, let’s say, 4, and if you do give it an answer that terminates, such as pf(1, 2), it will fall through all the if blocks and never reach a return statement.
So you need to debug your algorithm, but first, you need to make sure that every path through your function reaches a return statement. (You might also, if you don’t actually need a return value, declare void pf(int, int).
One way I like to do this (but doesn’t seem to be common in C) is to write if-else-return with the ? operator, such as:
return (num <= 1) ? 1 : // No more factors.
(num % i == 0) ? pf( num/i, i ) : // Prime factor, with possible multiplicity.
pf( num, i+1 ); // Not a factor. Keep looking.
This of course doesn’t work here because it never prints the factors. (It’s based on functional-style code that isn’t supposed to have side-effects like doing I/O.) One way to fix it would be to rewrite with if/then/else. Another is to store the factors in a data structure such as a dynamic array or linked list, and return that. Another is to print before the complex return. Another is to have the branch that should print a factor call a mutually-recursive function that prints and then calls pf(). A really ugly hack that you shouldn’t do is to use the comma operator. Pick the one you like the best.
This has the advantage of being tail-recursive, so it might go into an infinite loop but will not cause a stack overflow.
If you don’t like this style, another approach that some shops use to prevent this bug from happening is to write the function with nested if blocks that set a variable like int to_return = UNSET;. Then, every branch sets to_return to the proper value and you can finish with something like
if (foo)
to_return = 1;
else
to_return = f(i);
asseert(to_return != UNSET);
return to_return;
That way, the compiler ensures that you’re returning from a valid branch, or if you do forget to set a return value along some path, crashes and tells you where and why, not “Segmentation fault (core dumped).”

Number of recursive calls in gcd() function

Recently I have been given a gcd() function, written in C programming language which takes two arguments n and m and compute the GCD of these two numbers using recursion.I have been asked that "How many recursive calls are made by the function if n>=m?" Can any one provide the solution with explanation to my problem as I am unable to figure it out.
Here is the source code of the function :
int gcd(int n, int m)
{
if (n%m==0)
return m;
else
n=n%m;
return gcd(m, n);
}
Euclidean algorithm gives #steps =
T(a, b) = 1 + T(b, r0) = 2 + T(r0, r1) = … = N + T(rN - 2, rN - 1) = N + 1
where a and b are the inputs, and r_i the remainder. We used that T(x, 0) = 0
Running an example in paper would help you get a better grasp of the aforementioned equation:
gcd(1071, 462) is calculated from the equivalent gcd(462, 1071 mod 462) = gcd(462, 147). The latter GCD is calculated from the gcd(147, 462 mod 147) = gcd(147, 21), which in turn is calculated from the gcd(21, 147 mod 21) = gcd(21, 0) = 21
So a = 1071 and b = 462, and we have:
T(a, b) =
1 + T(b, a % b) = 1 + T(b, r_0) = (1)
2 + T(r_0, b % r_0) = 2 + T(r_0, r_1) =
3 + T(r_1, r_0 % r_1) = 3 + T(r_1, r_2) = (2)
3 + T(r_1, 0) =
3 + 0 =
3
which says that we needed to take 3 steps to compute gcd(1071, 462).
(1): notice that the 1 is the step already done before, i.e. T(a, b)
(2): r_2 is equal to 0 in this example
You could run a plethora of examples in paper, and see how this unfolds, and eventually you will be able to see the pattern, if you don't see it already.
Note: While #Ian'Abott's comments are also correct, I decided to present this approach, since it's more generic, and can be applied to any similar recursive method.

Count number of digits recursively

In order to learn recursion, I want to count the number of decimal digits that compose an integer. For didactic purposes, hence, I would like to not use the functions from math.h, as presented in:
Finding the length of an integer in C
How do I determine the number of digits of an integer in C? .
I tried two ways, based on the assumption that the division of an integer by 10 will, at a certain point, result in 0.
The first works correctly. count2(1514, 1) returns 4:
int count2(int n, int i){
if(n == 0)
return 0;
else
return i + count2(n / 10, i);
}
But I would like to comprehend the behavior of this one:
int count3(int n, int i){
if(n / 10 != 0)
return i + count3(n / 10, i);
}
For example, from count3(1514, 1); I expect this:
1514 / 10 = 151; # i = 1 + 1
151 / 10 = 15; # i = 2 + 1
15 / 10 = 1; # i = 3 + 1
1 / 10 = 0; # Stop!
Unexpectedly, the function returns 13 instead of 4. Should not the function recurse only 3 times? What is the actual necessity of a base case of the same kind of count2()?
If you do not provide a return statement the result is indeterminate.
On most architectures that mean your function returns random data that happens to be present on the stack or service registers.
So, your count3() function is returning random data when n / 10 == 0 because there is no corresponding return statement.
Edit: it must be stressed that most modern compilers are able to warn when a typed function does not cover all exit points with a return statement.
For example, GCC 4.9.2 will silently accept the missing return. But if you provide it the -Wreturn-type compiler switch you will get a 'warning: control reaches end of non-void function [-Wreturn-type]' warning message. Clang 3.5.0, by comparison, will by default give you a similar warning message: 'warning: control may reach end of non-void function [-Wreturn-type]'. Personally I try to work using -Wall -pedantic unless some required 3rd party forces me to disable some specific switch.
In recursion there should be base conditions which is the building block of recursive solution. Your recursion base doesn't return any value when n==0 — so the returned value is indeterminate. So your recursion count3 fails.
Not returning value in a value-returning function is Undefined behavior. You should be warned on this behavior
Your logic is also wrong. You must return 1 when `(n >= 0 && n / 10 == 0) and
if(n / 10 != 0)
return i + count3(n / 10, i);
else if (n >= 0) return 1;
else return 0;
I don't think you need that i+count() in the recursion. Just 1+count() can work fine...
#include <stdio.h>
#include <stdlib.h>
static int count(), BASE=(10);
int main ( int argc, char *argv[] ) {
int num = (argc>1?atoi(argv[1]):9999);
BASE= (argc>2?atoi(argv[2]):BASE);
printf(" #digits in %d(base%d) is %d\n", num,BASE,count(num)); }
int count ( int num ) { return ( num>0? 1+count(num/BASE) : 0 ); }
...seems to work fine for me. For example,
bash-4.3$ ./count 987654
#digits in 987654(base10) is 6
bash-4.3$ ./count 123454321
#digits in 123454321(base10) is 9
bash-4.3$ ./count 1024 2
#digits in 1024(base2) is 11
bash-4.3$ ./count 512 2
#digits in 512(base2) is 10

How do I create a "twirly" in a C program task?

Hey guys I have created a program in C that tests all numbers between 1 and 10000 to check if they are perfect using a function that determines whether a number is perfect. Once it finds these it prints them to the user, they are 6, 28, 496 and 8128. After this the program then prints out all the factors of each perfect number to the user. This is all fine. Here is my problem.
The final part of my task asks me to:
"Use a "twirly" to indicate that your program is happily working away. A "twirly" is the following characters printed over the top of each other in the following order: '|' '/' '-' '\'. This has the effect of producing a spinning wheel - ie a "twirly". Hint: to do this you can use \r (instead of \n) in printf to give a carriage return only (instead of a carriage return linefeed). (Note: this may not work on some systems - you do not have to do it this way.)"
I have no idea what a twirly is or how to implement one. My tutor said it has something to do with the sleep and delay functions which I also don't know how to use. Can anyone help me with this last stage, it sucks that all my coding is complete but I can't get this "twirly" thing to work.
if you want to simultaneously perform the task of
Testing the numbers and
Display the twirly on screen
while the process goes on then you better look into using threads. using POSIX threads you can initiate the task on a thread and the other thread will display the twirly to the user on terminal.
#include<stdlib.h>
#include<pthread.h>
int Test();
void Display();
int main(){
// create threads each for both tasks test and Display
//call threads
//wait for Test thread to finish
//terminate display thread after Test thread completes
//exit code
}
Refer chapter 12 for threads
beginning linux programming ebook
Given the program upon which the user is "waiting", I believe the problem as stated and the solutions using sleep() or threads are misguided.
To produce all the perfect numbers below 10,000 using C on a modern personal computer takes about 1/10 of a second. So any device to show the computer is "happily working away" would either never be seen or would significanly intefere with the time it takes to get the job done.
But let's make a working twirly for perfect number search anyway. I've left off printing the factors to keep this simple. Since 10,000 is too low to see the twirly in action, I've upped the limit to 100,000:
#include <stdio.h>
#include <string.h>
int main()
{
const char *twirly = "|/-\\";
for (unsigned x = 1; x <= 100000; x++)
{
unsigned sum = 0;
for (unsigned i = 1; i <= x / 2; i++)
{
if (x % i == 0)
{
sum += i;
}
}
if (sum == x)
{
printf("%d\n", x);
}
printf("%c\r", twirly[x / 2500 % strlen(twirly)]);
}
return 0;
}
No need for sleep() or threads, just key it into the complexity of the problem itself and have it update at reasonable intervals.
Now here's the catch, although the above works, the user will never see a fifth perfect number pop out with a 100,000 limit and even with a 100,000,000 limit, which should produce one more, they'll likely give up as this is a bad (slow) algorithm for finding them. But they'll have a twirly to watch.
i as integer
loop i: 1 to 10000
loop j: 1 to i/2
sum as integer
set sum = 0
if i%j == 0
sum+=j
return sum==i
if i%100 == 0
str as character pointer
set *str = "|/-\\"
set length = 4
print str[p] using "%c\r" as format specifier
Increment p and assign its modulo by len to p

Finding lengths between the elements of an event

I have a matrix which has 1's,-1's and zeros.. say
state=[1; 1; -1; 1; -1; 0; 0; 0; 0; 0; 0; 0; 0; 1; 0; -1; 1; 0; -1.........];
Say -1 is the start of an event and 0 contributes to the length of it when its between (-1 and 1) as -1 remains the start and 1 is the end of event. But when 0 comes after a 1 that means it doesn't have any value to it as the event ended recently; can't take that into consideration.
So I need to get the number of such events that happened and also lengths of those events in the entire matrix for such events so my output would be
result=[2 10 2........]
and need the no of such events.
And in the above case I would exclude my first two indices which are 1's that doesn't contribute to anything.
It sounds simple but its been a while I got back to matlab. This is what I tried but it fails as it takes the zeros in between 1 and -1 as it should be excluded:
result=[find(state==-1)-find(state==1)];
which is wrong.
Your help is appreciated.
Follow these steps:
Find all starts and all ends.
For each start, find the end immediately after it.
Subtract each end found in step 2 minus each corresponding start, and don't forget to add 1.
The number of events is immediate from that.
The interesting part is step 2. bsxfun tests, for each combination of start and end, if the start is less than the end. Then the second output of max gives the index of the first true value for each start, if any; and its first output tells you if there really was some true value, (that is, if the found index is valid).
starts = find(state(:)==-1); % // step 1
ends = find(state(:)==1); % // step 1
[valid, next_end] = max(bsxfun(#lt, starts.', ends)); %'// step 2
result = ends(next_end(valid)) - starts(valid) + 1; % // step 3
number = numel(result); % // step 4

Resources