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;
}
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);
}
My function has to be able to print the sum of the numbers 1+1+1.... to get to N. I can only enter N. For example: sumaRecursiva(6): 1+1+1+1+1+1=6.
This is what I have:
int sumaRecursiva(int y) {
int x=0;
if (x == y){
return y;
}
else {
x += 1;
cout << x << "+" <<endl;
sumaRecursiva(y-1);
}
}
You may want another function to handle the fact that you need fewer + characters in your print than you need 1s
void printSum(int y) {
if (y == 0) return;
cout << 1;
printPlusRecursive(y - 1);
}
void printPlusRecursive(int y) {
if (y == 0) return;
cout << '+' << 1;
printPlusRecursive(y - 1);
}
or shorter, but more complex version:
void printSum(int y, bool firstCall = true) {
if (y == 0) return;
if (firstCall) cout << 1;
else cout << '+' << 1;
printSum(y - 1, false);
}
If you want the output to be exactly 1+1+1+1+1+1=6 then you will need a helper function sumaRecursivaHelper to print the 1+'s and the outer function to print the =n which I believe none of the other answers include.
#include <iostream>
using namespace std;
void sumaRecursivaHelper(int x) {
if (x == 0) {
cout << 1;
}
else {
cout << "1+";
sumaRecursivaHelper(x - 1);
}
}
void sumaRecursiva(int x) {
if (x == 0) {
cout << 0;
}
else {
sumaRecursivaHelper(x);
}
cout << "=" << x;
}
int main()
{
sumaRecursiva(6);
return 0;
}
Your recursive function should return a value.
The value passed to a recursive is usually used to test for the escape condition (not usually used as part of the result).
int sum(int N)
{
if (N == 0) {
return 0; // I like zero as the escape value.
// Though this will give you
// sum(6) = 1 + 1 + 1 + 1 + 1 + 1 + 0 = 6
// If you only want to add ones change
// the escape condition to 1 and return 1
// Though this will prevent you doing sum(0)
}
return 1 + sum(N-1);
}
I have some lines of a book shuffled and their words are shuffled too. I want to sort them using quicksort algorithm. I sorted the lines and it worked well. then I tried to sort each line like this;
for each (Line l in lines) {
srand(255);
l.quicksort(0, l.words.size() - 1);
for each (Word w in l.words)
cout << w.content << " ";
cout << endl;
}
srand part is because I am using randomized quick sort. This loop gives me the correct results. However, when I tried to write it again like this;
for each (Line l in lines) {
for each (Word w in l.words)
cout << w.content << " ";
cout << endl;
}
It gives an output like I didn't call the quicksort function. It is the same code with one line missing. Why is it happening?
Line class:
#include<iostream>
#include<vector>
#include "word.h"
using namespace std;
class Line {
public:
vector<Word> words;
Line(string&, string&);
void quicksort(int, int);
private:
int partition(int, int);
void swap(int, int);
};
Line::Line(string& _words, string& orders) {
// Reading words and orders, it works well.
}
void Line::quicksort(int p, int r) {
if (p < r) {
int q = partition(p, r);
quicksort(p, q - 1);
quicksort(q + 1, r);
}
}
int Line::partition(int p, int r) {
int random = rand() % (r - p + 1) + p;
swap(r, random);
int x = words[r].order;
int i = p - 1;
for (int j = p; j < r; j++)
if (words[j].order <= x) {
i++;
swap(i, j);
}
swap(i + 1, r);
return i + 1;
}
void Line::swap(int i, int j) {
if (i != j) {
Word temp = words[j];
words[j] = words[i];
words[i] = temp;
}
}
You sort a local copy, iterate by reference instead:
srand(255); // Call it only once (probably in main)
for (Line& l : lines) {
l.quicksort(0, l.words.size() - 1);
for (const Word& w : l.words)
std::cout << w.content << " ";
std::cout << std::endl;
}
// Second loop
for (const Line& l : lines) {
for (const Word& w : l.words)
std::cout << w.content << " ";
std::cout << std::endl;
}
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; }
I am trying to print the values of all indices of a given sorted array using postorder traversal. I don't understand what the problem is! Please help me with that. As you know a sorted array is a minheap that here is going to be printed by postorder traversal.
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <cmath>
using namespace std;
int a, b, temp;
char c;
int B[10] = { NULL };
int L(int i) //returning the index of left child
{
i = ((2 * i) + 1);
return i;
}
int R(int i) //returning the index of right child
{
i = ((2 * i) + 2);
return i;
}
int P(int i) //returning the index of parent
{
if (i % 2 == 0) { i = ((i - 2) / 2); }
else { i = ((i - 1) / 2); }
return i;
}
//printing function
void f(int A[], int i) //printing using post order format
{
while (A[L(i)] != NULL && B[L(i)] != 1)
{
i = L(i);
}
cout << A[i] << " A ";
B[i] = 1; // B[i] is a kind of flag that checks whether A[i] has already been printed or not
if (i == 2) //I noticed that when it approaches the index 2, it only needs to print A[0] and gets out of the function
{
cout << A[0] << endl<< endl;
return;
}
if (A[L(i+1)] == NULL)
{
cout << A[i + 1] << " "; B[i + 1] = 1;
} //checks if the right node hasn't a child, prints it
else
{
f(A, i + 1);
}
cout << A[P(i)] << " "; B[P(i)] = 1;
// When looking at the parent, if its index is odd, it means that you have already printed a left child so you should go the right index
if (P(i) % 2 == 1)
{
f(A, P(i) + 1);
}
// When looking at the parent, if its index is even, it means that you have already printed a right child so you should go up to its parent : (P(P(i))
else
{
f(A, P(P(i)));
}
}
int main()
{
int A[10]={0,1,2,3,4,5,6,7,8,9};
f(A,0);
return 0;
}
First, I don't think int B[10] = { NULL }; is good method for whatever you wanted.
If you just want do the postorder traversal, the easier way to implement is:
void postTraversal(int a[], int n)
{
if (n <=9 && n >= 0)
{
postTraversal(a, L(n));
postTraversal(a, R(n));
cout << a[n] << " ";
}
}
int main()
{
int A[10]={0,1,2,3,4,5,6,7,8,9};
//f(A,0);
postTraversal(A, 0);
cout << endl;
return 0;
}