Examples of tasks solving on recursion in C# programming language
Contents
- 1. Calculating the area of a triangle
- 2. Calculate the value of the square of the number based on the dependence
- 3. Combinatorial problem
- 4. The parser for the concept of “identifier”
- 5. Ackermann function value
- 6. The parser for the notion of “simple expression”
- 7. Parser for the concept of “sum”
- 8. Conversion from one number system to another
- 9. Recursive function Min(). Calculating the minimum value in the array of type double[]
- 10. Recursive function ConvertAnyR(). Converting a number from one number system to another
- 11. Recursive function isPrime(). Determine if a number is prime
- Related topics
Search other websites:
1. Calculating the area of a triangle
Task. A triangle of size m×n is given, where m, n are integers and m>0, n>0. Develop a recursive function that calculates the area of a triangle based on the dependency:
Decision. If the dependency is known, then the implementation of the function presents no particular problems. The recursive process will be stopped when the condition n = m = 1 is fulfilled.
The program code of the S() function is as follows:
static int S(int n, int m) { if ((n == 1) && (m == 1)) return 1; else if (n > 1) return S(n - 1, m) + m; else return S(n, m - 1) + 1; }
Using S() method in another program code
int k; k = S(5,3); // k = 15 k = S(9,2); // k = 18
2. Calculate the value of the square of the number based on the dependence
Task. Calculate the value of the square of a positive integer n, if the dependence is known
n² = (n-1)² + 2·(n-1) + 1
From this dependence we get the recursion formula:
Decision.
// calculating the square of a number static int f(int n) { if (n == 1) return 1; else return f(n - 1) + 2 * n - 1; }
Using the function in another program code
int k; k = f(9); // k = 81
3. Combinatorial problem
Task. Calculate the number of combinations of n different elements for m. The number of combinations is determined by the dependence
Decision.
// number of combinations of n by m static int C(int n, int m) { if ((m == 0) && (n > 0) || (m == n) && (n > 0)) return 1; else if ((m > n) && (n >= 0)) return 0; else return C(n - 1, m - 1) + C(n - 1, m); }
Using the C() function in other program code
int nn; nn = C(6, 4); // nn = 15 nn = C(4, 3); // nn = 4
4. The parser for the concept of “identifier”
Task. Develop a recursive function that implements the parser for the concept ‘identifier’. As is known, in the C# programming language, the identifier obeys the following rules:
- the first character of the identifier is necessarily the letter of the Latin alphabet;
- second, third, etc. the symbol identifier can be a letter or a number.
The general identifier formula is as follows:
here
- identifier – an identifier;
- letter – some letter of the Latin alphabet (from ‘a’ to ‘z’ or from ‘A’ to ‘Z’);
- digit – digit from ‘0’ to ‘9’.
Decision. In this case, a recursive function is implemented with the name IsIdentifier().Since the function analyzes the concept of “identifier”, the result of returning from a function is a value of type bool. If the function returns true, then the identifier name is correct in accordance with the condition of the task. If the function returns false, then there is an error in the identifier name.
The input parameter of the recursive function IsIdentifier() is a string of type string. This line contains the identifier name. The condition for the end of the recursive process is the achievement of the first character of the identifier.
The text of the IsIdentifier () method is as follows
// method that determines if the identifier name is correct static bool IsIdentifier(string s, int pos) { if (pos == 0) { char c; c = s[pos]; // check whether the first symbol is a letter if ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z')) return IsIdentifier(s, pos + 1); // go to check next symbol else return false; } else if (pos < s.Length) // if not the last symbol { char c; c = s[pos]; // check if a symbol is a letter or a number if ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z') || (c >= '0') && (c <= '9')) return IsIdentifier(s, pos + 1); else return false; } else return true; // if there are no characters to check, then the identifier is correct }
Using the IsIdentifier() function in other program code
bool f; f = IsIdentifier("A13yuu", 0); // f = true
5. Ackermann function value
Task. Calculate the value of the Ackermann function for two non-negative integers n and m, where
Decision. If dependencies are known, the implementation of the function is not a difficult task. In accordance with the condition of the task, the function gets two parameters. These are non-negative integers n and m. The function also returns a non-negative integer.
For large values of n and m, a stack overflow may occur, since the Ackermann function is twice recursive: one of the arguments to the function is the same recursive function.
The implementation of the function is as follows:
// Ackermann function static uint A(uint n, uint m) { if (n == 0) return m + 1; else if ((n != 0) && (m == 0)) return A(n - 1, 1); else return A(n - 1, A(n, m - 1)); }
Using the function for small values of n and m:
uint res; res = A(1, 2); // res = 4 res = A(0, 1); // res = 2 res = A(0, 0); // res = 1 res = A(2, 2); // res = 7
6. The parser for the notion of “simple expression”
Task. Create a program that implements the parser for the concept of “expression”
here
- Expression – a simple expression;
- simple_identifier – a simple identifier;
- letter – Latin letter from ‘a’ to ‘z’ or from ‘A’ to ‘Z’;
- operation – operation sign ‘+’, ‘–’ or ‘*’.
Decision. To solve this problem, you need to implement three functions:
- the IsIdentifier() function, which determines whether a simple identifier is a letter;
- the function IsOperation(), which determines whether there is an operation syntactically correct in accordance with the task;
- the recursive function IsExpression(), which determines whether a simple expression is syntactically correct in accordance with the task.
The recursive function IsExpression() receives 3 parameters:
- string s, which is analyzed;
- the position pos of the current symbol in the string s;
- an IsOp flag that indicates whether the previous symbol was an operation sign.
The implementations of the functions IsIdentifier(), IsOperation() and IsExpression() are as follows:
// determines if a symbol c is identifier static bool IsIdentifier(char c) { if ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z')) return true; else return false; } // Determines if a symbol c is operation sign static bool IsOperation(char c) { if ((c == '-') || (c == '+') || (c == '*')) return true; else return false; } // Recursive function-analyzer of expression static bool IsExpression(string s, uint pos, bool IsOp) { char c; c = s[(int)pos]; if (pos == 0) // if s [pos] is a first symbol in the expression { if (IsIdentifier(c)) // check if a first symbol is a letter return IsExpression(s, pos + 1, false); else return false; } else if (pos < s.Length - 1) // not the first character (second, third, etc.) and not the last { if (IsIdentifier(c)) // if a symbol, then go to the next symbol return IsExpression(s, pos + 1, false); else { if (IsOperation(c) && !IsOp) // if the operation is the first time return IsExpression(s, pos + 1, true); // true - indicate at the next level that there was an operation else return false; } } else // process the last character in the string s return IsIdentifier(c); // check if there is last character an identifier }
Demonstration of using IsExpression() in another method:
bool b; b = IsExpression("a+b", 0, false); // b = true b = IsExpression("+a+b", 0, false); // b = false b = IsExpression("Adsdl-Bdslf-FDF", 0, false); // b = true b = IsExpression("a+-b-c", 0, false); // b = false b = IsExpression("a+b;", 0, false); // b = false b = IsExpression("alsd+bsldk-", 0, false); // b = false b = IsExpression("AbcDEf", 0, false); // b = true
Using a similar pattern, you can create several recursive functions that will analyze complex expressions or their fragments. It is important for each function to determine the correct dependencies (algorithm).
7. Parser for the concept of “sum”
Task. Create a program that implements the parser for the concept of “sum”
here
- Sum – a function that analyzes the total amount;
- Integer – a function that analyzes an integer;
- Digit – a function that analyzes a digit;
- Operation – a function that implements the sign of the operation. The sign of the operation can be ‘+’ or ‘–’.
The expression in braces { } can be repeated except for the operation.
Decision. Using this example as a sample, you can develop your own analyzers of complex expressions. The representation of each complex expression can be broken apart. For each part, its own recursive function can be developed.
To solve this problem, 4 functions have been developed:
- the IsSignOp() function, which determines whether is a character c with an operation sign. The character c is passed to the function as an input parameter. The function returns true or false;
- the function IsDigit(), which determines whether is an input symbol c with an integer. The symbol c is a function parameter;
- the recursive function IsInteger(), which analyzes the entire expression. Function receives 3 parameters. The first parameter is the analyzed string. The second parameter pos is the position of the current symbol in the analyzed string s. The third, auxiliary parameter IsOp indicates whether the previous character was an operation sign. The third parameter IsOp is necessary to avoid repeating two characters of operations, for example, “++”;
- the IsSum() function, which calls the recursive IsInteger() function. The IsSum() function performs a simple redirection to the execution of the IsInteger() function.
The implementation of the functions is as follows:
// operation sign static bool IsSignOp(char c) { if ((c == '+') || (c == '-')) return true; else return false; } // an integer static bool IsDigit(char c) { if ((c >= '0') && (c <= '9')) return true; else return false; } // the recursive function IsInteger (), implements the check of the whole expression, // pos - current character position from string s, which is analyzed // IsOp=true, if the previous character at the top level was a sign of the operation static bool IsInteger(string s, int pos, bool IsOp) { char c; c = s[pos]; if (pos == 0) // first character { if (IsDigit(c)) return IsInteger(s, pos + 1, false); else return false; } else if (pos < s.Length - 1) { if (IsDigit(c)) // if a number (digit) return IsInteger(s, pos + 1, false); // then process the next symbol else { // if not number if (IsSignOp(c)) // if an operation sign { // view previous operation sign if (!IsOp) return IsInteger(s, pos + 1, true); else return false; // error: two signs of the operation follow in a row } else return false; // error: invalid character in the expression } } else return IsDigit(c); // the last character of the expression must be a number (digit) } // the IsSum() function that calls the recursive IsInteger() function static bool IsSum(string s) { // invoke the recursive function IsInteger() return IsInteger(s, 0, false); }
Using the IsSum() function in another method
bool b; b = IsSum("253+23"); // b = true b = IsSum("2345w-18"); // b = false b = IsSum("750-450+200"); // b = true b = IsSum("-200"); // b = false b = IsSum("2019"); // b = true b = IsSum("210+-6"); // b = false b = IsSum("300+"); // b = false
8. Conversion from one number system to another
Task. Develop a recursive conversion function from decimal to binary.
Decision. The conversion algorithm is classic. It is necessary to divide the input parameter num by 2 as long as num>2. For each division, you need to select the remainder using the expression num%2. The % operation is intended to highlight the remainder of the division of two numbers.
The function Convert10to2() receives two arguments:
- an argument of an unsigned integer type with a parameter named num. This is the given number in decimal notation.
- temporary argument that serves to memorize the current result in binary calculus.
The result of the function is an inverse (reversible) string to the string res. Because, when dividing, the resulting value is formed in the reverse order.
The function has the following implementation:
// conversion of a natural number from the 10th number system to the binary static string Convert10to2(uint num, string res) { if (num < 2) { uint t = num % 2; res = res + t.ToString(); // reversing of the res string and returning the result string res2 = ""; for (int i = res.Length-1; i>=0; i--) res2 = res2 + res[i]; return res2; } else { uint t = num % 2; res = res + t.ToString(); return Convert10to2(num / 2, res); } }
Using a function in another method
string res; res = Convert10to2(18, ""); // res = 10010 res = Convert10to2(39, ""); // res = 100111 res = Convert10to2(0, ""); // res = 0 res = Convert10to2(250, ""); // res = 11111010
9. Recursive function Min(). Calculating the minimum value in an array of type double[]
Task. Develop a recursive Min() function to calculate the minimum value in array A, which contains n double numbers (n>0).
Solution. In order to ensure a cyclic process, additional parameters must be passed to the Min() function:
- A – an array of numbers of type double[];
- item – the index of the current element in the loop, which is compared with the minimum value;
- min – current minimum value.
using System; namespace ConsoleApp12 { class Program { // Recursive function Min() - calculating the minimum in the array. // Parameters: // - A - original array of numbers; // - item - the index of the element that is compared with the minimum; // - min - current minimum (result). public static double Min(double[] A, int item, double min) { // Calculate minimum if (min > A[item]) min = A[item]; // Checking if the last item if (item == A.Length - 1) return min; else return Min(A, item + 1, min); } static void Main(string[] args) { // The array under test double[] A = { 2.3, 2.5, 1.8, 8.3, 11.2 }; // Calling a static function double min = Program.Min(A, 1, A[0]); Console.WriteLine("min = {0:f}", min); // min = 1.80 } } }
10. Recursive function ConvertAnyR(). Converting a number from one number system to another
Task. Develop a recursive function ConvertAny() for converting a number from a calculus system with basis m to a calculus system with basis n. The function should receive the following parameters:
- the number num, which needs to be converted from the calculus system m to the calculus system n;
- unsigned integer number m specifying the denomination of the calculus system with the base m (2<m≤9);
- unsigned integer number n specifying the denomination of the calculus system with the base n (2<n≤9);
The function must return a string of type string, which is the result.
Solution. To convert a number from base m to base n, you need to do the following:
- convert a number from the m number system to the decimal number system;
- convert a number from decimal to base n.
With this in mind, the solution to the problem is represented by two functions:
- the recursive function ConvertTo10R(), which converts the number to the decimal system;
- recursive function ConvertAnyR(), which converts a number from one system to another. This function calls another recursive function, ConvertTo10R().
using System; namespace ConsoleApp12 { class Program { // Recursive function that converts a number to decimal public static long ConvertTo10R(long num, int m, int i) { long t; if (num > 0) { t = num % 10 * (long)Math.Pow(m, i); return t + ConvertTo10R(num / 10, m, i + 1); } else return 0; } // Recursive function that converts a number from one number system to another public static string ConvertAnyR(long num, int m, int n) { long t; long num10; // 1. Checking data for correctness if ((m < 2) || (m > 10) || (n < 2) || (n > 10)) return "Incorrect data"; if (m==10) { // Convert to the number system with base n if (num > 0) { t = num % n; // get the last number return ConvertAnyR(num / n, 10, n) + Convert.ToString(t); } else return ""; } else { // First, translate to the 10th number system num10 = ConvertTo10R(num, m, 0); // Then call the recursive function return ConvertAnyR(num10, 10, n); } } static void Main(string[] args) { // Convert 58 from base 4 to base 6 string numberR = ConvertAnyR(23, 4, 6); Console.WriteLine("number = {0}", numberR); } } }
11. Recursive function isPrime(). Determine if a number is prime
Task. Develop a recursive function that determines whether a given positive integer N is prime number. A prime number is the number N> 1 which has no other divisors except 1 and itself.
Solution. An integer is considered prime if it is divisible by 1 and itself. For example, prime numbers are 2, 3, 5, 17, etc.
using System; namespace ConsoleApp12 { class Program { // Recursive function that determines if a number is prime public static bool isPrime(int num, int tnum, int k) { if (tnum > 1) { // If the number num is evenly divisible by tnum, then increase k by 1 if ((num % tnum) == 0) k++; // Move to next iteration decreasing tnum by 1 return isPrime(num, tnum - 1, k); } else { k++; if (k > 2) return false; else return true; } } static void Main(string[] args) { // Determine if the number 25 is prime bool f = isPrime(25, 25, 0); Console.WriteLine("f = {0}", f); } } }
The result of the program
f = False