Recursion - Understanding return [closed] - c#

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 1 year ago.
Improve this question
using System;
using System.Collections.Generic;
using System.Linq;
namespace Return
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Factorial(10));
Console.WriteLine(test());
}
private static int Factorial(int factorialNum)
{
if (factorialNum <= 1)
{
return 1;
}
return factorialNum * Factorial(factorialNum - 1);
}
public static int test()
{
return 1;
}
}
}
Okay so here is my thought proccess. If i make a method, that returns 1. I.e: public static int test() { return 1; } And Console.WriteLine that method, then it will say 1. If I change it to 3 it will write 3, and so on. So with the other method, I'm saying that I want to * it with the factorialNum -1. And return that. But if it is 1 it should return 1. And no matter which int I put inside it, it will always eventually = 1. Because we are saying factorialNum -1 But why is it that, when it is eventually 1. And it returns 1 Then why isn't the output in the Console.WriteLine 1 Since we're returning 1

Let's try to execute the code of calling:
Factorial(4)
When this method is called for 4 the return statement would be
4 * Factorial(3)
So we have to call Factorial(3) now and we would get
3 * Factorial(2)
Last
2 * Factorial(1)
At the last point Factorial(1) would return 1 and the result:
2 * 1
Would be passed to 3 * Factorial(2) and would be become
3 * 2 * 1
And that would be passed at the end to 4 * Factorial(3):
4 * 3 * 2 * 1
and now the method returns 24, which is the factorial of 4.
You have to keep an eye on the call stack. The fact that it would stop the recursive calls of the method at the base case factorialNum <= 1, it doesn't mean that the result of calling that method with any argument would be 1.
On the other hand, when you call test you don't have recursive calls, you return immediately 1.

return factorialNum * Factorial(factorialNum - 1);
In the above factorialNum will always be 10 since that was the input value, and will return 10*Factorial(9).
Then in the next loop it will be 9*Factorial(8) and so on. So the final return value will be 10*9*8*7*6*5*4*3*2*1

You get the number 3628800 when you run the Factorial(10) because 10! equals 3628800. If you run through the code, Factorial() returns the current number * the current number - 1. So it returns 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 3628800.
You are in fact returning 1 at the end of Factorial(10), but this 1 is simply multiplied by the numbers that come prior.
To get the console to return a 1, you would have to run Factorial(1) because 1! = 1.

Related

C# Program to Get a Number and Display the Sum of the Digits [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm just beginning to learn C# and I can't figure out why this example problem is laid out this way. Maybe I'm not understanding the basics of how the order of operations works. Can someone explain how the "while" portion of this program works? I don't understand what "num = num / 10" does when num is not referenced after this line. Does it affect the previous line? Thanks for any insight.
/*
* C# Program to Get a Number and Display the Sum of the Digits
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program
{
class Program
{
static void Main(string[] args)
{
int num, sum = 0, r;
Console.WriteLine("Enter a Number : ");
num = int.Parse(Console.ReadLine());
while (num != 0)
{
r = num % 10;
num = num / 10;
sum = sum + r;
}
Console.WriteLine("Sum of Digits of the Number : "+sum);
Console.ReadLine();
}
}
}
Does it affect the previous line?
If by previous you mean the while condition, then yes, and just affect the check by next check in the loop.
the code just do a summary of all the digital numbers
like if your input is
1235
then the output will be
1+2+3+5 = 11
The while loop will forever be executed if the condition is true by
num != 0
And in the loop, you just modify the num so that it will be compared to 0 again in the next condition check.
If it's always true ie always
num != 0
Then you will get an infinite loop, which is possible in some condition.
And welcome to the coding world :D
Example We Input a Number "123"
When it goes to the condition While Number(123) != (is not equal to) 0 Then it will perform the code.
First get the remainder by using modulus %.
Second get the Whole number by using division.
Third Get the sum.
1.) r = num % 10 | The value of r now is 3
2.) num = num / 10 | The value of num now is 12.
3.) sum = sum + r | The value of sum here is 0 + the remainder 3.
It will go the the while statement again. Is the number(12) != (is not equal to) 0 then it will perform the code.
Take note the value now of Num is 12 ok.
Perform again the code.
1.) r = num % 10 | The value of r now is 2
2.) num = num / 10 | The value of num now is 1.
3.) sum = sum + r | The value of sum here now is 3 + the remainder now is 2.
So the sum now is 5. Then it will loop again because Num now is equal to 1. Then
Perform the code again.
I think this explains the best for you.
class Program
{
static void Main(string[] args)
{
int num, sum = 0, r;
Console.WriteLine("Enter a Number : ");
num = int.Parse(Console.ReadLine());
while (num != 0)
{
/* Important: The logic behind is to add the numbers from the last one
* to the first one.
*
* For example, 123 will be added in this way: 3 + 2 + 1
* We will use number 123 as example.*/
/* Comment:
*
* 1st run: 123 % 10, remainder will be 3. Anything modulus 10 will
* always get the final digit. Now, we have r = 3, which will be used
* in the final sum below.
*
* 2nd run: 12 % 10, remainder will be 2. Now, we have r = 2, which
* will be used in the final sum below.
*
* 3rd run: 1 % 10, remainder will be 1. Now, we have r = 1, which will
* be used in the final sum below.
*/
r = num % 10;
/* Comment:
*
* 1st run: 123 / 10, answer will be 12. If you are wondering why it
* isn't 12.3, then it is because the datatype in used is "int", so the
* answer will always be a round number, so 12.3 in round number will
* be 12, which is the 2 numbers that have not been added, so now,
* num = 12, and we have managed to discard 3 because we no longer need
* it because it will be added in the final sum below.
*
* 2nd run: 12 / 10, again answer is not 1.2, but num = 1.
* We have managed to discard 2 because we no longer need it because it
* will be added in the final sum below.
*
* 3rd run: 1 / 10, again answer is not 0.1, but num = 0.
* We have managed to discard 1 because we no longer need it because it
* will be added in the final sum below. This will be the final run.
*/
num = num / 10;
/* Comment:
* 1st run: 0 + 3 (1st run remainder)
* 2nd run: 3 + 2 (2nd run remainder)
* 3rd run: 5 + 1 (3rd run remainder)
*/
sum = sum + r;
}
Console.WriteLine("Sum of Digits of the Number : " + sum);
Console.ReadLine();
}
}
And yes, the "num" variable is used by the "while" loop to check on the current condition. If the "num" is not "0", then the logic will continue to run. Hope this helps.
I think you will end up in an endless loop in that Code. Using while loop it always execute the code inside the while loop as long as your num variable has a value.
And inside your while loop code your sum value has no connection with the formula.
r = num % 10;
num = num / 10;
sum = sum + r;
Instead change it to this where sum is set to value of num / 10
r = num % 10;
sum = num / 10;
sum = sum + r;
And use if statement instead. Because every time the user input number it is guaranteed that it is only executed once. so no need for while loop.

I just do not understand how this code is able to calculate factorial of the given numbers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
//calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}
so i know it has to do with the function being a recursion but how is the code able to know when to keep multiplying the integers less than 6 in order to find the factorial. Also how does the code know when to stop multiplying when it reaches 6. If this was in a loop i could fully understand how this would be possible but with no loop i just do not understand.
I'm still in the tutorial of learning c#, if you can please try to keep it as simple as possible.
Any help would be greatly appreciated.
Let's step through factorial(6).
What's factorial(6)? factorial(5) * 6.
What's factorial(5)? factorial(4) * 5.
What's factorial(4)? factorial(3) * 4.
What's factorial(3)? factorial(2) * 3.
What's factorial(2)? factorial(1) * 2.
What's factorial(1)? 1.
You then just go backward from there and you'll arrive at your answer:
factorial(6) = 1 * 2 * 3 * 4 * 5 * 6.

Factorial Calculations using Recursive Method call

This code is from the book: "C# 5.0 in a Nutshell" and is a sample on LinqPad. On page 39 it says:
"This method is recursive, meaning that it calls itself. Each time the method is entered,
a new int is allocated on the stack, and each time the method exits, the int is
deallocated."
Using the literal 5 yields and answer of 120 (3 yields 6)
Can someone explain how this works? I'm a VB programmer trying to learn C# and would like to understand constructs like this. I've single stepped through it many times and can't understand what happens after x == 0 and 1 is returned. Until x equals zero, the flow of execution is easy to understand. After that, the last return statement seems to be repeatedly executed (magically) until x increments back to it's original value and then returns to the point where it was originally called and produces the aforementioned (magical) numeric result.
static void Main()
{
Console.WriteLine (Factorial(5));
}
static int Factorial (int x)
{
if (x == 0) return 1;
return x * Factorial (x-1);
}
Call Factorial(3) (which returns 3 * 2)
x doesn't == 0
return 3 * Factorial(2)
Calls Factorial(2) (which returns 2 * 1)
x doesn't == 0
return 2 * Factorial(1)
Calls Factorial(1) (which returns 1 * 1)
x doesn't == 0
return 1 * Factorial(0)
Calls Factorial(0) (which returns 1)
x == 0 so return 1
An important point is that the recursive function must have a termination condition, otherwise it would call itself infinitely (until it runs out of stack space). In your example, the if (x == 0) return 1; is the termination condition. Since the function calls itself with a parameter value of one less than it was called with, eventually it will end up calling itself with 0, and that is when the recursion ends.
This brings out a problem with this code though. If you call with a negative number, it will call itself recursively with increasingly negative numbers, will never reach 0, and you'll eventually run out of stack space. How best to handle that is probably outside the scope of your question though.
The concept of recursion is not really limited to any specific language. The idea behind it that the function calls itself.
Let's consider your example: factorial function. But for now let's put implementation aside and think of it in more abstract terms. The function consists of two elements:
i) Instruction how to calculate an element 'n'.
ii) Instruction how to calculate an initial element
So how do we calculate element n for factorial? We take n and multiply it by factorial of a previous element: n-1:
n * Factorial(n-1)
And there is only one initial item: 0. That is when n == 0 the result is 1 or in other words Factorial(0) gives 1.
The algorithm you provided contains really of these two steps
if (x == 0)
return 1; // Do this when calculating Factorial of 0
else
return x * Factorial (x-1); // Do this when calculating an element n
Ok. Now what happens when we want to calculate factorial of 4? Let's break it down to specific steps.
Factorial(4) -> 4 * Factorial(4-1) -> 4 * Factorial(3)
We invoked factorial of 4. So we multiply 4 by factorial of 4-1. To get the factorial of 4-1 we again invoke factorial function:
Factorial(3) -> 3 * Factorial(3-1) -> 3 * Factorial(2)
Now we need to calculate factorial of 2.
Factorial(2) -> 2 * Factorial(2-1) -> 2 * Factorial(1)
And of 1
Factorial(1) -> 1 * Factorial(1-1) -> 1 * Factorial(0)
Note that now we have to calculate factorial of 0. But here we have a special instruction: if the argument is 0 the result has to be 1. Let's wind back our calculations:
Factorial(0) is 1. Replace the result in the calculation for factorial of 1.
Factorial(1) -> 1 * Factorial(1-1) -> 1 * 1 which is also 1
Factorial(2) -> 2 * Factorial(1) -> 2 * 1 -> 2
Factorial(3) -> 3 * Factorial(2) -> 3 * 2 -> 6
Factorial(4) -> 4 * Factorial(3) -> 4 * 3 -> 12
You mentioned following explanation:
Each time the method is entered, a new int is allocated on the stack,
and each time the method exits, the int is deallocated.
These steps when we go inside Factorial function to calculate factorial for a previous number is when a new int has to be allocated on the stack: for factorial of 4 the number 4 goes on the stack and the algorithm calculates factorial of 3, and so on.
And when we get to the very end that is to factorial of 0 we can finally start deallocating numbers. We have factorial of 0, multiply the result by 1. Factorial of 1 is returned and 1 is deallocated. Same happens for 2, 3 and finally 4.
Hope that clarified whole concept a bit. I'm aware the explanation is extensive, but, on the other hand, it's tricky to grasp it at the beginning so I preferred to be too thorough.
It's recursive because this statement here:
return x * Factorial (x-1);
returns the result of x * the result of the call to Factorial (X-1)... It's calling itself to get the answer. It breaks out of the loop when x==0 simply by returning the value of 1.
But one thing to note, to whom does x==0 return the value? The answer is most likely the loop which is accumulating the values.
The method Factorial calls itself again, starting with 5, and decrements the argument (x-1), until the passed argument x is 0.
So the first call to Factorial passes 5, the second call 4, 3, 2, 1, 0.
And the math done is: 5*4*3*2*1 = 120.
What it is doing is calling itself repeatedly.
What's effectively happening is the following.
We enter Factorial with x equal to 5 and since we're greater than 0 we multiply our 5 with the result of calling our self (Factorial) again with 5 - 1 which is 4. Inside this recursive call we find our selves doing another recursive call with 4 - 1 which is 3. We do this repeatedly until we call Factorial with 0, where it returns 1. Then that 1 returns to the recursion which multiplies it by 2, which returns to the recursion which multiplies it by 3, and then the next by 4, and then the next by 5.
In the end you return the result of 1 * 2 * 3 * 4 * 5 which is 120.
There is one call to return for each call to Factorial. These are the recursive calls unwinding after x == 0.
I think this might be easier to see if you slightly modify your code, if only temporarily:
static int Factorial (int x)
{
if (x == 0) return 1;
else
{
int y = x * Factorial (x-1);
return y;
}
}
Thanks for all the great replies to my question. I have a both a better understanding now of this piece of code works and a realization that I need to put a more in-depth study of recursion on my TO-DO list.

How can I determine how many of an array of ints need to be a non-default value for the total value of the count of items to equal a given value? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Given the value I want a number of items to total, how can I programmatically determine how many need to be of an alternate/adjusted value to equal (as close as possible, anyway) the given value?
More specifically, say I had 290 items that needed to total 2700. The default value is 10, but if the given value is less than (item count * 10) - which would be 2900 in this case, a certain number of those items will have to have a value of 9 instead of 10; OTOH, if the given value is greater than (item count * 10), a certain number of those items will have to have a value of 11 instead of 10 (for example, if the given value was still 2700, but the item count was 250). Eight and twelve would never be used - only 9, 10, and 11.
In these cases, there would be 200 nines and 90 tens in the first case:
200 * 9 == 1800
90 * 10 == 900
2700
...and 200 elevens and 50 tens in the second case:
200 * 11 == 2200
50 * 10 == 500
2700
I need a function that will take the given value, and the item count, and return the number of "outliers" (9s or 11s). IOW, the function would look like this:
function int GetOutlierCount(int ValToEqual, int ItemCount) {
// TODO: How?
}
...and be called like this:
GetOutlierCount(2700, 290)
-or:
GetOutlierCount(2700, 250)
...etc. In both cases shown above, it would return 200, as 200 9s are needed in the first case, and 200 11s in the second case (the caller would know which to expect, based on whether ValToEqual was 10* greater than (ItemCount * 10) or not.
OK, you have n integers each of value v.
You have a total t that you want to achieve, where n * (v-1) <= t <= n * (v+1).
If t < n * v, you have to decrease (n*v) - t of your integers by 1 to total t.
If t > n * v, you have to increase t - (n*v) of your integers by 1 to total t.
Your first example has n = 290, v = 10, t = 2700. 2700 < 290 * 10 holds so you need to adjust (290*10) - 2700 = 200 of your items downwards.
Your second example has n = 250, v = 10, t = 2700. 2700 > 250 * 10 holds so you need to adhust 2700 - (250*10) = 200 of your items upwards.
(In case I've not made it obvious enough: the number of items you need to change is simply the difference between your desired total and your actual total.)
Brute force implementation. Linear time, so still pretty good. Left here for posterity, since I first mistakenly thought this was a hard problem. :)
def outlier_count(target_val, count):
default_val = 10
other_val = default_val - 1
x_max = target_val / default_val
for x in range(x_max, -1, -1): # x_max, x_max-1, ..., 0
y = count - x
if x*default_val + y*other_val == target_val:
return (x, y)
raise ValueError("No solution")
function int GetOutliers(int totalVal, int itemsCount) {
const int DEFAULT_MULTIPLIER = 10;
int icMultiplied = itemsCount * DEFAULT_MULTIPLIER;
return Math.Abs(totalVal - icMultiplied);
}

Recursive loop (C#)

Can someone please explain it to me? I wrote a function to calculate the factorial of a number like this in C#:
public int factorial(int input)
{
if (input == 0 || input == 1)
return 1;
else
{
int temp = 1;
for (int i = 1; i <= input; i++)
temp = temp * i;
return temp;
}
}
But I found some C++ code (I don't really know any C++ btw) which finds a factorial using a recursive loop:
int factorial(int number) {
int temp;
if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;
}
Can someone explain to me how it works? Thanks.
Well, it uses the fact that factorial(n) is n * factorial(n - 1) with a base case of n = 1.
So for example:
factorial(5) = 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
The implementation just uses this recursive definition.
Syntactically, the C++ code is identical to the same code written in C#. Don't let the language discrepancy catch you off guard! It actually looks like C to me, given that the variable is declared at the top of the function; that's not strictly necessary in either C++ or C#. I prefer to declare variables the first time I use them, combining the declaration and initialization in one single statement, but that's merely a stylistic preference that doesn't change the function of the code.
I'll try to explain this by adding comments to each line of the code snippet:
// Declare a function named "Factorial" that accepts a single integer parameter,
// and returns an integer value.
int Factorial(int number)
{
// Declare a temporary variable of type integer
int temp;
// This is a guard clause that returns from the function immediately
// if the value of the argument is less than or equal to 1.
// In that case, it simply returns a value of 1.
// (This is important to prevent the function from recursively calling itself
// forever, producing an infinite loop!)
if(number <= 1) return 1;
// Set the value of the temp variable equal to the value of the argument
// multiplied by a recursive call to the Factorial function
temp = number * Factorial(number - 1);
// Return the value of the temporary variable
return temp;
}
Recursive calls simply mean that the function calls itself from within the same function. This works because the factorial of n is equivalent to the following statement:
n! = n * (n-1)!
One great way to understand how code works is to add it to a test project, then single-step through the code using the debugger. Visual Studio has very rich support for this in C# applications. You can watch how the function recursively calls itself, watching each line execute in sequence, and even seeing the values of the variables change as operations are performed on them.
Lets analyze this line by line:
if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;
Line 1: If the number is less than or equal to zero, we return 1. This is saying that 0! = 1 and 1! = 1
Lines 2 + 3: Otherwise we return number * factorial(number - 1). Lets look at this for 5! (here i use n! as a synonym for factorial(n) for brevity)
5!
5 * 4!
5 * 4 * 3!
5 * 4 * 3 * 2!
5 * 4 * 3 * 2 * 1!
5 * 4 * 3 * 3 * 1 // Here we don't have to expand 1! in the same way because of the condition
So the whole thing expands out. Its just using the property that
n! = n * (n - 1) * ... * 2 * 1 = n * (n - 1)!
Warning: The recursive code, as always, will suffer from a stack overflow and increased memory usage as compared to an iterative (or tail-recursive-optimized) version, so use at your own risk.
A recursive function is a function that calls itself in its body. For it be bounded, and eventually return a value, two things must happen:
It has to have a base case where it doesn't call itself again, returning a known value. This base case stops the recursion. For the factorial function, this value is 1 when the input is 0.
Its recursive applications must converge to the base case. For factorial, the recursive application calls the function with the input subtracted by 1, which will eventually converge to the base case.
A simpler way to look at this function is this (only valid for positive input):
int factorial(int input) {
return input == 0 ? 1 : input * factorial(input - 1);
}
Recursive function are function calling from the same function
eg:
Test()
{
i++;
Test();
cout<<i;
}
look at the code it will call the function again and again
Problem with recursion it will work infinitely so want to stop it by a particular condition
some change in above code now look
int i=0;
Test()
{
if(i==10) return;
i++;
Test();
cout<<i;
}
output will be 10 printed 10 times, here this line cout<<i; will execute after return

Categories