I currently have code that displays a number triangle:
#include <iostream>
using namespace std;
void RowNumbers(int n, int max) {
if (n < max) {
cout << n << ' ';
RowNumbers(n + 1, max);
}
cout << n << ' ';
}
void PrintRhombus(int n, int space = 0) {
if (n > 1) {
PrintRhombus(n - 1, space + 2);
}
cout << string(space, ' ');
RowNumbers(1, n);
cout << "\n";
}
int main() {
int a;
cout << "Enter a number [1-9]: " << endl;
cin >> a;
if (a > 0 && a < 10) {
PrintRhombus(a, 0);
}
else
cout << "Wrong input." << endl;
}
The output is displayed here if the input is two.
1
1 2 1
This is only half of what I want. I want to make a full diamond, so I would want a "1" as the third line of this output. The RowNumbers function generates each line, and the PrintRhombus function is responsible for creating the number triangle. I only want to use recursions to create the bottom half of the triangle. So should I create another recursion function that creates the bottom half of the diamond? Or should I build upon the PrintRhombus function, and start something else when the value reaches one.
So once again my goal is to create a number diamond, so if you input 3, then the output is:
1
1 2 1
1 2 3 2 1
1 2 1
1
Here's what I would do:
First, write PrintRhombus in the form of a single loop:
void PrintRhombus(int n) {
for(int i = 1; i < 2 * n; i++){
int numbers_in_line = i < n ? i : 2 * n - i;
int space = (n - numbers_in_line) * 2;
cout << string( space, ' ' );
RowNumbers( 1, numbers_in_line );
cout << endl;
}
}
Test your loop and make sure you got it right. It's usually much easier to reason about a loop than a recursive function.
Now transform the loop into a tail-recursive function. This transformation is trivial to perform:
void PrintRhombus(int n, int i = 1){
// ^ loop variable --> extra parameter
if(i == 2 * n) return; // <- terminating condition --> return
// loop body remains unchanged
int numbers_in_line = i < n ? i : 2 * n - i;
int space = (n - numbers_in_line) * 2;
cout << string( space, ' ' );
RowNumbers( 1, numbers_in_line );
cout << endl;
// Now do recursive call with incremented loop variable
PrintRhombus(n, i+1);
}
Demo.
It is because you only iterate to the top of the rhombus, then print out the top half. I could not find a solution that used only one function, but here are two functions, one for the top and one for the bottom, that work:
void PrintRhombusTop(int n, int space = 0)
{
if (n > 1)
{
PrintRhombusTop(n - 1, space + 2);
}
cout << string(space, ' ');
RowNumbers(1, n);
cout << "\n";
}
void PrintRhombusBottom(int n, int space)
{
if (n >= 1)
{
cout << string(space, ' ');
RowNumbers(1, n);
cout << "\n";
PrintRhombusBottom(n - 1, space + 2);
}
}
Call them in main like this:
if (a > 0 && a < 10)
{
PrintRhombusTop(a, 0);
PrintRhombusBottom(a - 1, 2);
}
You need to pass (a - 1, 2) to PrintRhombusBottom so you don't print the middle row twice and so the row after the middle row is indented correctly.
to follow the same logic as RowNumber, you probably want something like that:
void PrintRhombus(int min, int max)
{
if (min < max)
{
RowNumber(1, min);
PrintRhombus(min+1, max);
RowNumber(1, min);
}
else
RowNumber(1, max);
}
Just add the necessary spaces
Another one for fun:
#include <iostream>
#include <string>
void row(int n, int m) {
std::cout << n << " ";
if (n < m) {
row(n + 1, m);
std::cout << n << " "; } }
void line(int n, int r, int m) {
std::cout << std::string(2 * (m - n), ' ');
row(1, r);
std::cout << "\n"; }
void diamond(int n, int r, int m) {
line(n, r, m);
if (r < m) {
diamond(n + 1, r + 1, m);
line(n, r, m); } }
int main(int, char* []) {
std::cout << "Number? ";
int n = 0;
std::cin >> n;
diamond(1, 1, n);
return 0; }
Related
I'm trying to print a right angled triangle with ascending and descending numbers using recursion only.
void straightTriangular(int num)
{
if (num == 0)
{
return;
}
straightTriangular(num - 1);
for (int i = 1; i <= num; i++)
{
cout << i;
}
cout << endl;
}
How can I do this with recursion only without "for" loop?
if the user input number is 4 then
I want the output to be this:
1
121
12321
1234321
my output using the code I posted:
1
12
123
1234
Notice that a triangle(n) has a triangle(n-1) on top of it. It has self-similar structure above it.
Also notice that a layer looking like x...n...x is x (x+1)...n...(x+1) x, which has self-similar structure inside it.
void layer(int x, int n) {
std::cout << x;
if (x >= n) return;
layer(x + 1, n);
std::cout << x;
}
void triangle(int n) {
if (n <= 0) return;
triangle(n - 1);
layer(1, n);
std::cout << std::endl;
}
If you want to render a pyramid with each layer centered, instead of a right-angled triangle, then what appears above a layer is not just a simple triangle, but an indented triangle. You must keep track of this indentation.
The layer function remains the same, but you first print out some space according to the indentation level of the current pyramid.
#include <iostream>
void space(int n) {
if (n <= 0) return;
std::cout << ' ';
space(n-1);
}
void layer(int x, int n) {
std::cout << x;
if (x >= n) return;
layer(x + 1, n);
std::cout << x;
}
void pyramid(int n, int indent) {
if (n <= 0) return;
pyramid(n - 1, indent + 1);
space(indent);
layer(1, n);
std::cout << std::endl;
}
int main() {
pyramid(4, 0);
}
You can have:
a printTriangleRec function that goes on printing every line recursively,
two printAscendingRec and printDescendingRec functions that print the two halves of each line recursively.
[Demo]
#include <iostream> // cout
void printAscendingRec(int cur, int top)
{
std::cout << cur;
if (cur != top)
{
printAscendingRec(cur + 1, top);
}
}
void printDescendingRec(int cur)
{
if (cur)
{
std::cout << cur;
printDescendingRec(cur - 1);
}
}
void printTriangleRec(int cur, int top)
{
printAscendingRec(1, cur);
printDescendingRec(cur - 1);
std::cout << "\n";
if (cur != top)
{
printTriangleRec(cur + 1, top);
}
}
void printTriangle(int num)
{
if (num < 1)
{
std::cout << "Error: num < 1\n";
return;
}
printTriangleRec(1, num);
}
int main()
{
printTriangle(4);
}
I want to print an X shape using n number of rows but without any loop. I have to use a recursive function to print the X.
I have called the functions along with space function but it didn't print the X. It printed:
* *
* *
* *
I have to solve this problem using recursion. No for loop or while loop is allowed to solve this one.
// C++ implementation to print the given
// pattern recursively
#include <bits/stdc++.h>
using namespace std;
// function to print the 'n-th' row of the
// pattern recursively
int g;
void printPatternRowRecur(int n) {
if (n < 1)
return;
if (n = 1) {
cout << "*";
}
// print the remnaining stars of the n-th row
// recursively
else {
return;
}
printPatternRowRecur(n - 1);
}
void print_space(int space) {
// base case
if (space == 0)
return;
cout << " ";
// recursively calling print_space()
print_space(space - 1);
}
int s;
void Rhombus(int n) {
// base condition
if (s >= n)
return;
else {
print_space(s);
printPatternRowRecur(n);
print_space(n - s);
printPatternRowRecur(n);
}
// print the stars of the n-th row
s++;
// move to next line
cout << endl;
// print stars of the remaining rows recursively
Rhombus(n);
}
// Driver program to test above
int main() {
int n = 3;
//cout << "Enter the number of lines you want to print" << endl;
//cin >> n;
//cout << endl << "Rhombus" << endl;
Rhombus(n);
return 0;
}
if (n = 1) should be if (n == 1). As coded, the if expression is always true.
Here is a simplified version:
// C++ implementation to print the given pattern recursively
#include <iostream>
using namespace std;
void print_spaces(int n) {
if (n > 0) {
cout << ' ';
print_spaces(n - 1);
}
}
void rhombus(int s, int n) {
if (s < n) {
int left = min(s, n - s - 1);
int middle = n - 2 * left - 2;
print_spaces(left);
cout << '*';
if (middle >= 0) {
print_spaces(middle);
cout << '*';
}
cout << endl;
// print stars of the remaining rows recursively
rhombus(s + 1, n);
}
}
void rhombi(int s, int n) {
if (s <= n) {
cout << endl << "Rhombus " << s << endl;
rhombus(0, s);
rhombi(s + 1, n);
}
}
int main() {
//int n = 3;
//cout << "Enter the number of lines you want to print" << endl;
//cin >> n;
//cout << endl << "Rhombus" << endl;
//rhombus(0, n);
rhombi(0, 7);
return 0;
}
#include <iostream>
using namespace std;
// * *
// * *
// *
// * *
// * *
//printStarHorizontally will recursively print '*' on a line using x coordinates
void printStarHorizontally(int xCoordinate1, int xCoordinate2, int currentXCoordinate, int maxCoordinate){
if(currentXCoordinate >= maxCoordinate) {
cout<<endl;
return;
}
if(currentXCoordinate == xCoordinate1 || currentXCoordinate == xCoordinate2) {
cout<<"*";
} else {
cout<<" ";
}
printStarHorizontally(xCoordinate1, xCoordinate2, currentXCoordinate + 1, maxCoordinate);
}
//PrintCross will go to each height and then use printStarHorizontally func. to print star on that particular height
void PrintCross(int heightOfCross, int currentHeight) {
if(currentHeight >= heightOfCross) return;
printStarHorizontally(currentHeight, heightOfCross-currentHeight-1, 0, heightOfCross);
PrintCross(heightOfCross,currentHeight+1);
}
int main() {
// heightOfCross should be odd integer
int heightOfCross = 13;
PrintCross(heightOfCross, 0);
return 0;
}
Here's a recursion with one function, one given parameter, and two default parameters:
#include <iostream>
using namespace std;
void f(int y, int x=1, int w=0){
if (y < 1)
return;
if (x > 0){
f(y, -(y + 2 * w), w);
f(y - 2, x, w + 1);
if (y > 1)
f(y, -(y + 2 * w), w);
return;
}
if (x == -w){
cout << endl;
return;
}
if (x == -(w + y) || x == -(w + 1))
cout << '*';
else
cout << ' ';
f(y, x + 1, w);
}
int main(){
f(5);
cout << endl;
f(6);
return 0;
}
I would use two recursive functions: first to write a character after a number of spaces, second to write the lines.
#include <iostream>
/*************************************
* display on character (c) on out after x spaces recursively
* **********************************/
void display_char(int x, std::ostream& out = std::cout, char c='*') {
if (x == 0) out << c;
else {
out << ' ';
display_char(x-1, out, c);
}
}
/*********************************
* displays lines to draw an X pattern
* The pattern is composed of c characters on out
* x decreases to 0 while y increases and a c
* is printed at positions x and y
* ******************************/
void display_line(int x, int y=0, std::ostream& out=std::cout, char c='*') {
int oldx=x, oldy=y;
if (x < y) {
int t = x;
x = y;
y = t;
}
display_char(y, out, c);
if (x != y) display_char(x - y, out, c);
out << '\n';
if (oldx > 0) display_line(oldx-1, oldy+1, out, c);
}
int main() {
int x;
std::cout << "X size (int): ";
std::cin >> x;
display_line(x-1);
return 0;
}
Write a function int fact(int n) which displays the factors of the integer n, and returns the number of factors. Call this function in main() with user input
#include<iostream>
using namespace std;
int fact(int n);
int main() {
int n,factor;
cout << "Enter an integer : ";
cin >> n;
factor = fact(n);
cout << factor;
return 0;
}
int fact(int n)
{
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
cout << i << endl;
}
return 0;
}
If I enter 7, I get 1,7,0 . How do i remove this 0 and how do i find the number of factors?
You should count in your int fact() function. Set a variable to 0 and increment each time you currently display i. Then at the end of the function instead of returning 0 return the count variable.
int fact(int n)
{
int count=0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
count++;
}
}
return count;
}
The key part is "and returns the number of factors". You don't do that. Keep a count of the factors:
int fact(int n)
{
int count = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
{
// found a factor, add to the count
count++;
cout << i << endl;
}
}
// return the count instead
return count;
}
Then, your main function can use that count:
factor = fact(n); // fact(n) will already print the factors
// now just print the number
cout << "Number of factors: " << factor << '\n';
#include <iostream>
#include <vector>
std::vector<int> fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
std::vector<int> factors = fact(n);
for (auto i : factors) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "Number of factors: " << factors.size() << '\n';
return 0;
}
std::vector<int> fact(int n) {
std::vector<int> vec{1};
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
vec.push_back(i);
}
}
vec.push_back(n);
return vec;
}
If you're going to return anything from fact(), it should be the factors. To do so, I am using a std::vector. It is an array that can grow on demand. The numbers 1 and n are always factors, so I don't bother doing the math for them. The vector is initialized already holding the value 1, and I only calculate numbers up to and including half of n (Anything greater than n/2 won't divide evenly, so my loop is finished about half as fast by recognizing the actual range). I then just add n to the vector, which I return.
My main prints the vector, and the vector knows its own size, which is the number of factors.
Alternatively, you can just keep a count in your fact() function.
#include <iostream>
#include <vector>
// Prints factors of n and returns the number of factors
int fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
int numFactors = fact(n);
std::cout << "Number of factors: " << numFactors << '\n';
return 0;
}
int fact(int n) {
int factorCount = 2; // Already counting 1 and n
std::cout << "1 ";
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
std::cout << i << ' ';
++factorCount;
}
}
std::cout << n << '\n';
return factorCount;
}
The main problem with your code is that your function always returns zero. You need to keep a count of factors and return it.
Besides that your code performance badly as the loop goes on much longer than needed. You can use the square root of n as the limit in the for loop. Like:
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int limit = sqrt(n);
for (int i = 1; i <= limit; ++i)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
}
if (limit * limit == n)
{
--res;
}
return res;
}
For n = 36 the output is:
1 - 36
2 - 18
3 - 12
4 - 9
6 - 6
and the returned value is 9
Below is another approach. It doesn't use square root. Instead it keeps the number of loops low by using the square of i as loop limit.
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int i = 1;
int i_square = i * i;
while (i_square < n)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
++i;
i_square = i * i;
}
if (i_square == n)
{
++res;
cout << i << " - " << n/i << endl;
}
return res;
}
Fact() always returns 0 so this line print 0
cout << factor;
for the number of factors you can change the return value of fact() :
int fact(int n)
{
int nb = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
nb++;
}
}
return nb;
}
I know how to write a recursive function to print from N to 0: N, N-1, ... 1, 0
But somehow I get stuck on doing the same thing but in increasing order from 0, 1, ... , N.
This is my code for the N to 0:
int main() {
int n = 4;
backward(n);
return 0;
}
void backward(int n) {
if (n == 0) {
std::cout << n << std::endl;
}
else if (n > 0) {
std::cout << n << " ";
backward(n - 1);
}
}
You should make your recursive call before cout.
You'll recurse all the way to n without printing anything.
Then, on the way back out, it will print out n in ascending order.
int main() {
int n = 4;
forward(n);
return 0;
}
void forward(int n) {
if (n == 0) {
std::cout << n << std::endl;
}
else if (n > 0) {
forward(n - 1);
std::cout << n << " ";
}
}
You just need to swap std::cout << n << " "; and backward(n - 1); around. With the print statement first, your print the value of n and then go on to the next "iteration". If you instead call the function recursively first, and then print the value of n you will get all the way to the zero case, print zero, return to the one case, print one, and keep going until you return to the n case where you then print n. So forward is just
void forward(int n) {
if (n == 0) {
std::cout << n << std::endl;
}
else if (n > 0) {
forward(n - 1);
std::cout << n << " "; // print n only after everything else has printed
}
}
int main() {
int n = 4;
forward(n);
std::cout<<"\n";
return 0;
}
void forward(int n) {
if ( n == -1)
return;
forward(n - 1);
std::cout<<n<<" ";
}
Now this is the combinatorial function if you don't know it:
C(n,k)= { 1 if k=0 or k = n
C(n−1,k−1)+C(n−1,k) otherwise
Now, What I really need is to use recursion to print a Pascal's triangle.
Ok,so what I've done so far is this simple recursion function:
#include <iostream>
using namespace std;
int Pas(int r, int c) {
if (c == 0 || c == r) {
return 1;
} else {
return Pas(r - 1, c - 1) + Pas(r - 1, c);
}
}
int main(){
cout << Pas(4,2) << endl;
return 0;
}
Now this function computes perfectly for example:
Pas(4,2) = 6
But I'm having problem using it to print the whole Pascal's triangle, because I'm new into C++ and especially recursion ..
I'd appreciate any feedback, and I hope that someone would help figure out this problem. But I'd appreciate it more if you guys don't just give me the whole answer (code) just like that; I want to learn.
Thanks!
Something similar to this might to the job
void printTriangle(int printRows, int a = 1, int b = 0)
{
if (a > printRows) return;
int val = Pas(a, b);
cout << val << " ";
if (a == b) {
cout << endl;
printTriangle(printRows, a + 1, 0);
} else {
printTriangle(printRows, a, b + 1);
}
}
Running printTriangle(7) should print the first 7 rows.
Tail recursion is the recursive equivalent to iterative loops. The following function when called with sum(0, 5)
int sum(int start, int end, int resultSoFar = 0) {
if (start == end) return resultSoFar;
return sum(start + 1, end, resultSoFar + start);
}
is equivalent to the iterative function called with sum(0, 5).
int sum(int start, int end) {
int resultSoFar = 0;
for (int i = start; i < end; i++) {
resultSoFar += i;
}
return resultSoFar;
}
If you are allowed to use your recursive function in a loop, the easiest way would be something like:
int n=4;
for (int i=0; i<=n; i++) {
for (int j=0; j<=i; j++) {
cout << Pas(i,j)<<" ";
}
cout <<endl;
}
If you want to reinforce the layout, you coud also #include <iomanip> and <limits> to use a fixed size number output, using the number of digits required to display an integer: just replace the output statement with:
cout << setw(numeric_limits<int>::digits10+1)<<Pas(i,j);
Edit:
You could easily build a recursive function to print lines of the triangle:
void PrintPas(int r) {
if (r==1)
cout << Pas(1,0);
else {
PrintPas(r-1);
for (int c=0; c<=r; c++)
cout << Pas(r,c)<< " ";
}
cout <<endl;
}
Edit 2
If you want a fully recursive version:
void PrintPas(int r, int c) {
if (r==1)
cout << Pas(1,0)<<" ";
else if (c==-1) {
PrintPas(r-1,r-1);
}
else {
PrintPas(r,c-1);
cout << Pas(r,c)<< " ";
}
if (r==c)
cout <<endl;
}
Online demo