An example you might understand is the Fibonacci sequence {1, 1, 2, 3, 5, 8, 13, 21, ...}
Each term in the sequence (after the first two) is the sum of the previous two. That is, each term in the sequence is defined by the other terms in the sequence, who are also defined by the other terms in the sequence, etc... until you reach some base case, some starting point. In the case of the Fibonacci sequence we define the first two numbers as 1 and 1, after that we use recursion to define the rest of the sequence. Formally: Let an be the nth term in the sequence.
a0 = 1
a1 = 1
an = an-1 + an-2
In C++ this might look something like the following:
#include <iostream>
usingnamespace std;
// Calculate the nth term in the Fibonacci sequence
int fib(int n) {
if( n <= 1 )
return 1; // The first two terms (term 0 and term 1) are defined equal to 1.
// This is our starting point. Without this clause the recursion
// would never stop!
elsereturn fib(n - 1) + fib(n - 2); // Recursion! We are invoking the function 'fib'
// within itself to calculate the nth term of
// the sequence
}
int main() {
cout << "The 10th term in the Fibonacci sequence is " << fib(10) << '\n';
return 0;
}
A tutor helped me with my assignment, but the diamond outputs wrong and
I want to include an if then else statement like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
if (number != 7)
{
cout <<"Incorrect number of lines. The pattern will not be shown.";
cout <<"\n";
system ("pause");
return 0;
else
{
//call recursion here
}
/*Write a recursive function to generate the following pattern of stars:
*
* *
* * *
* * * *
* * *
* *
*
Also, write a program that prompts the user to enter the number of lines in
the pattern and uses the recursive function to generate the pattern. For
example, specifying 4 as the number of lines generates the above pattern. */
#include <iostream>
#include <stdio.h>
usingnamespace std;
int main()
{
int n, c, k, space = 1;
printf("Enter number of rows\n");
scanf("%d", &n);
space = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space--;
for (c = 1; c <= 2*k-1; c++)
printf("*");
printf("\n");
}
space = 1;
for (k = 1; k <= n - 1; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space++;
for (c = 1 ; c <= 2*(n-k)-1; c++)
printf("*");
printf("\n");
}
system("pause");
return 0;
}