μ°λ¦¬λ for λ°λ³΅λ¬Έμ΄λ while λ°λ³΅λ¬Έκ³Ό κ°μ λ°λ³΅λ¬Έμ μμ±ν΄μ λ°λ³΅μ ꡬνν μ μμμ 보μλ€. λ°λ³΅μ μ»λ λ λ€λ₯Έ λ°©λ²μ ν¨μκ° μμ μ μ μ λ΄μμ μμ μ νΈμΆν λ λ°μνλ μ¬κ·(recursion)λ₯Ό ν΅ν΄μμ΄λ€.
All recursive methods have the following characteristics:
#include <iostream>
using namespace std;
int counting(int n, int val);
int main()
{
int n, val = 0, res;
cout << "Enter a positive integer : ";
cin >> n;
res = counting(n, val);
cout << "The " << n << "th integer is " << res << endl;
}
int counting(int n, int val)
{
if (n == 0)
{
cout << "Base case" << endl;
return 0;
}
else
{
cout << n << endl;
val = val + 1;
}
return counting(n - 1, val) + 1;
}
#include <iostream>
using namespace std;
int factorial(int n);
int main()
{
int n = 5, res;
res = factorial(n);
cout << "Factorial of " << n << " is " << res << endl;
return 0;
}
int factorial(int n)
{
int fact = 1;
for (int i = 1; i <= n; i++)
{
fact = fact * i;
}
return fact;
}
// iteration & recursive factorial
#include <iostream>
using namespace std;
long long int iteration_factorial(unsigned long long int n)
{
unsigned long long int value = 1;
for (unsigned long long int i = 1; i <= n; i++)
{ // nλ² λ°λ³΅
value = value * i;
}
return value;
}
unsigned long long int factorial(unsigned long long int n)
{ // recursive
if (n <= 1)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
int main()
{
unsigned long long int n = 5, result;
result = iteration_factorial(n);
// result = factorial(n);
cout << result;
return 0;
}
#include <iostream>
using namespace std;
int fibonacci(int n); // recursive fibonacci implementation
int main()
{
int n;
cout << "Enter an integer n for fibonacci(n): ";
cin >> n;
cout << "Fibonacci(" << n << ") = " << fibonacci(n) << endl;
}
int fibonacci(int n)
{
if ((n == 0) || (n == 1))
{
return n;
}
else
{
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
#include <iostream>
using namespace std;
int fibonacci(int n); // iterative fibonacci implementation
int main()
{
int n;
cout << "Enter an integer n for fibonacci(n): ";
cin >> n;
cout << "Fibonacci(" << n << ") = " << fibonacci(n) << endl;
}
int fibonacci(int n)
{
if (n == 0)
{
return 0;
}
int fib0 = 0;
int fib1 = 1;
for (int i = 2; i <= n; ++i)
{
int temp = fib1;
fib1 = fib0 + fib1;
fib0 = temp;
}
return fib1;
}
Seven functions that often appear in algorithm analysis:
#include <iostream>
using namespace std;
int main()
{
try
{
int age;
cout << "Enter your age: ";
cin >> age;
if (age >= 18)
{
cout << "Access granted - you are old enough.";
}
else
{
throw(age);
}
}
catch (int myNum)
{
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum << endl;
}
}