Print a numerical hollow square pattern using recursive functions in c++ - c++

I've been trying to print a square numerical pattern like this one:
12345
2 4
3 3
4 2
54321
But I can't seem to find the correct way to code a recursive function to do it.
I've only managed to print a numerical triangle, but the square has been killing me.
#include <iostream>
using namespace std;
void print_row(int no, int val)
{
if (no == 0)
return;
cout << val << " ";
print_row(no - 1, val);
}
void pattern(int n, int num)
{
if (n == 0)
return;
print_row(num - n + 1, num - n + 1);
cout << endl;
pattern(n - 1, num);
}
int main()
{
int n = 5;
pattern(n, n);
}
output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Code to output a square shape pattern using recursion.This is as far as I've gotten to try and print a numerical square, I don't know how to print it out with ascending and descending numbers.
#include <iostream>
#include <string>
using namespace std;
void line( int row, int num )
{
if ( row < 0 ) return;
char c = row * ( num - row - 1 ) ? ' ' : '*';
cout << '*' << string( num - 2, c ) << "*\n";
line( row - 1, num );
}
int main()
{
int n;
cout << "Input side (n > 2): "; cin >> n;
line( n - 1, n );
return 0;
}
output:
*****
* *
* *
* *
*****

I took the time to built this two functions. Try to understand them though, you probably are on a test and this topic might be helpful in the future.
You just call square(n), with n being the number you want to use for the square.
void print_sides(int n, int col) {
if (col == 0) return;
print_sides(n, col - 1);
if(col != 1) cout << col << string(2*(n - 1)-1, ' ') << (n - col) + 1 << "\n" ;
}
void square(int n, int col = 0, bool sides = true) {
if (col >= n) {
return;
}
else {
if (sides) {
cout << col + 1 << " ";
square(n, col + 1, true);
}
else {
square(n, col + 1, false);
cout << col + 1 << " ";
}
if (col == n - 1 && sides == true) {
cout << "\n";
print_sides(n, col);
square(n, 0, false);
}
}
}

This is one of the ways to solve this question.
The pattern function prints the hollow square pattern while the printSubRows is responsible for generating the middle portion.
void printSubRows(int n,int i,int c) {
if (c==n-2) return;
//adjust the space according to your requirements
cout << i << " " << n-i+1 << endl;
printSubRows(n,i+1,c+1);
}
void pattern(int n) {
//prints the first row
for (int i=1;i<=n;i++) cout << i;
cout << endl;
//recursive function to print the middle part
printSubRows(n,2,0);
//prints the last row
for (int i=n;i>0;i--) cout << i;
cout << endl;
}

Related

Function: smallest positive integer

#include <iostream>
using namespace std;
int enough(int goal)
{
int C { };
int i { };
if (goal > 1)
{
while (((C += i) <= goal) && ((goal - i) <= (i + 1)))
{
i += 1;
}
}
else
{
i = 1;
}
return i;
}
int main()
{
cout << enough(21);
return 0;
}
So the purpose of this function is for it to return the smallest positive integer that can be summed consecutively from 1 before the cumulative sum becomes greater than the parameter "goal".
So, for example:
cout << enough(9) << endl;
will print 4 because 1+2+3+4 > 9 but 1+2+3<9
cout << enough(21) << endl;
will print 6 'cause 1+2+ . . .+6 > 21 but 1+2+ . . . 5<21
cout << enough(-7) << endl;
will print 1 because 1 > -7 and 1 is the smallest positive integer
cout << enough(1) << endl;
will print 1 because 1 = 1 and 1 is the smallest positive integer
My logic at first was using just while ((C += i) <= goal), but that went wrong, for example, for the parameter 21, where you get C = 20, which passes the test and ends up in i being augmented by 1 (resulting in the return value i = 7, which is clearly wrong).
Therefore I decided to create a test which tested both C and i, but that went wrong because the code isn't considering goal - i and i + 1 as separate tests for the while circuit, but I believe it is actually altering the value of ints goal and i, which screws everything up.
Any ideas where I went wrong?
Your approach is unnecessarily verbose. There is a closed-form (i.e. O(1)) solution for this.
The sum S of the arithmetic progression 1, 2, ..., n is
S = n * (n + 1) / 2
Rearranging this (completing the square), rejecting the spurious root, and rounding appropriately to fit the requirements of the question yields the result
n = std::ceil((-1 + std::sqrt(1 + 8 * S)) / 2)
This will not work for negative n, and possibly 0 too depending on the specific (and unspecified) requirements.
Or if you must use an O(N) approach, then
int enough(int goal){
int i = 0;
for (int total = 0; (total += ++i, total) < goal; );
return i;
}
will do it, which returns 1 for goal <= 1.
You could perhaps try to simplify your original O(N) approach by only having one condition in your while-loop, i.e., no &&:
#include <iostream>
using namespace std;
int enough(int goal)
{
if (goal <= 0)
{
return 1;
}
int total{};
int i{};
while (total < goal)
{
total += ++i;
}
return i;
}
int main()
{
cout << "enough(9): " << enough(9) << endl;
cout << "enough(21): " << enough(21) << endl;
cout << "enough(-7): " << enough(-7) << endl;
cout << "enough(1): " << enough(1) << endl;
cout << "enough(0): " << enough(0) << endl;
return 0;
}
Output:
enough(9): 4
enough(21): 6
enough(-7): 1
enough(1): 1
enough(0): 1

C++ - Is this conditional statement written correctly? Or is there a more effective way to write it?

I have a program that attempts to find a magic square. A square matrix of numbers where all the rows,columns,diagonals add up to the same number.
So far I have a 3x3 array that successfully populates with truly random numbers. It appears to work properly in doing so, but when I include the program in a while(true) loop, the program runs on forever without finding the magic square, and I think it's because my conditional statement is written incorrectly. Here's it is:
if (row0 == row1 == row2 == col0 == col1 == col2 == dia1 == dia2) {
cout << "We have a magic square!" << endl;
cout << troysArray[i][j];
cout << "";
break;
}
The whole program is here:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//Defining the sum function, which takes 3 integers as arguments.
int addnums(int x,int y,int z){
int result = x + y + z;
return result;}
int main() {
srand(time(0));
//Initial array contents before random numbers are substituted
int troysArray[3][3] = {
{1,3,2},
{4,6,5},
{7,9,8},
};
int i;
int j;
int row0;
int zero_zero;
int zero_one;
int zero_two;
int row1;
int one_zero;
int one_one;
int one_two;
int row2;
int two_zero;
int two_one;
int two_two;
int col0;
int col1;
int col2;
int dia1;
int dia2;
int sum = row0;
while(true) {
for (i = 0;i < 3;i++){
for (j = 0;j < 3;j++){
//Generating random numbers between 1-9, with which to populate troysArray.
troysArray[i][j] = 1 + (rand() % 9);
cout << troysArray[i][j];
cout << "";
//If all the rows,columns, and diagonals are equal,we have a magic square!
if (row1 == sum && row2 == sum && col0 == sum && col1 == sum && col2 == sum &&
dia1 == sum && dia2 == sum) {
cout << "We have a magic square!" << endl;
cout << troysArray[i][j];
cout << "";
break;}
}
cout << endl;
}
}
//Adding up row 0 (top row):
zero_zero = troysArray[0][0];
zero_one = troysArray[0][1];
zero_two = troysArray[0][2];
row0 = addnums(zero_zero,zero_one,zero_two);
cout << "The sum of row 0 equals: " << zero_zero + zero_one + zero_two << endl;
//Adding up row 1 (middle row):
one_zero = troysArray[1][0];
one_one = troysArray[1][1];
one_two = troysArray[1][2];
row1 = addnums(one_zero,one_one,one_two);
cout << "The sum of row 1 equals: " << one_zero + one_one + one_two << endl;
//Adding up row 2 (bottom row):
two_zero = troysArray[2][0];
two_one = troysArray[2][1];
two_two = troysArray[2][2];
row2 = addnums(two_zero,two_one,two_two);
cout << "The sum of row 2 equals: " << two_zero + two_one + two_two << endl;
cout << "\n";
//Adding up col 0 (Left):
col0 = addnums(zero_zero,one_zero,two_zero);
cout << "The sum of col 0 equals: " << zero_zero + one_zero + two_zero << endl;
//Adding up col 1 (Middle):
col1 = addnums(zero_one,one_one,two_one);
cout << "The sum of col 1 equals: " << zero_one + one_one + two_one << endl;
//Adding up col 2 (Right):
col2 = addnums(zero_two,one_two,two_two);
cout << "The sum of col 2 equals: " << zero_two + one_two + two_two << endl;
cout << "\n";
//Adding up tL-bR diagonal (dia 1):
dia1 = addnums(zero_zero,one_one,two_two);
cout << "The sum of dia 1 equals: " << zero_zero + one_one + two_two << endl;
//Adding up bL-tR diagonal (dia 2):
dia2 = addnums(two_zero,one_one,zero_two);
cout << "The sum of dia 2 equals: " << zero_two + one_one + two_zero << endl;
return 0;
}
The Equality operator doesn't work in C and C++ the way you think it does.
It is evaluated from left to right, therefore a == b == c becomes (a == b) == c, or (true/false) == c.
The correct way to solve this is to compare each value individually:
int sum = row0;
if (row1 == sum && row2 == sum && ...) { ... }
Update:
You can create your own multiple value comparator like this:
template <class Arg, class... Args>
bool all_equal(Arg&& arg, Args&&... args) {
static_assert(sizeof...(args), "At least 2 arguments expected");
return (arg == args && ...);
}
// Example
if (all_equal(row0, row1, ...)) {}

Sum 1 to N, printing every sum along the way in a new row (recursion)

I have a basic program down that sums 1 to N.
However, I need to print every line of sums leading up to 'N'.
ex: input -> 3
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
I need to do this through recursion without using any loops in the code.
Any help appreciated. I can't seem to wrap my head around how to do this.
#include <iostream>
using namespace std;
int sumToN(int n, int row);
int input;
int main()
{
cout << "Sum to: ";
cin >> input;
cout << sumToN(input, 1);
}
int sumToN(int n, int row)
{
if (row==n) // BASE CASE
{
cout << row << " = ";
return row;
}
else // RECURSIVE CASE
{
cout << row << " + ";
return (row + sumToN(n, row+1));
cout << endl;
}
}
See this :
int sumToN(int n, int row);
void out(int n);
int input;
int main()
{
cout << "Sum to: \n";
cin >> input;
out(1);
}
void out(int n)
{
if( n > input) return;
cout << sumToN(n, 1)<<"\n";
out(n+1);
}
int sumToN(int n, int row)
{
if (row==n) // BASE CASE
{
cout << row << " = ";
return row;
}
else // RECURSIVE CASE
{
cout << row << " + ";
return (row + sumToN(n, row+1));
cout << endl;
}
}
Output:
You can try something like storing the sum like 1+2.. In a string and keep appending the new number on each call and also output the new sum in each call after the string
Use a internal value prefix_val and prefix_str to store the prefix recursive result. Then we can output the whole recursive workflow.
int sumToN(int n, int row, int prefix_val, const std::string& prefix_str);
int main()
{
// Meanwhile you should void using global variables.
int input;
cout << "Sum to: ";
cin >> input;
sumToN(input, 1, 0, "");
}
int sumToN(int n, int row, int prefix_val, const std::string& prefix_str)
{
string gap;
if (prefix_val == 0) {
gap = "";
} else {
gap = " + ";
}
cout << prefix_str << gap << row << " = " << prefix_val + row << std::endl;
if (row == n) // recursive end
{
return 0;
}
return sumToN(n, row + 1, row + prefix_val, prefix_str + gap + std::to_string(row));
}
DEMO OUTPUT
Sum to: 10
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
With loops you can do something like that:
#include <iostream>
using namespace std;
void displayToN(const int last) {
int sum = 0;
for (int i=1; i<last; sum += i, i++)
cout << i << " + ";
cout << last << " = " << (sum + last) << endl;
}
void sumToN(const int curr, const int last) {
for (int i=curr; i<=last; i++)
displayToN(i);
}
int main() {
int input;
cout << "Sum to: ";
cin >> input;
sumToN(1, input);
}
But with your limits, you have to emulate for loops with recursion like that:
#include <iostream>
using namespace std;
void displayToN(const int curr, const int last, const int sum = 0) {
if (curr < last) {
cout << curr << " + ";
displayToN(curr + 1, last, sum + curr);
} else {
cout << curr << " = " << (sum + curr) << endl;
}
}
void sumToN(const int curr, const int last) {
if (curr <= last) {
displayToN(1, curr);
sumToN(curr + 1, last);
}
}
int main() {
int input;
cout << "Sum to: ";
cin >> input;
sumToN(1, input);
}
This works
#include<iostream>
using namespace std;
int input;
int sumToN(int n, int row)
{
if (row==n) // BASE CASE
{
cout << row << " = ";
//cout<< row<<endl;
return row;
}
else // RECURSIVE CASE
{
cout << row << " + ";
return (row + sumToN(n, row+1));
cout << endl;
}
}
void caller(int n,int current){
if(current==n){
cout<<sumToN(n,1)<<endl;
}
else{
cout<<sumToN(current,1)<<endl;
caller(n,current+1);
}
}
int main()
{
cout << "Sum to: "<<endl;
cin >> input;
caller(input, 1);
}
Output
Sum to:3
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6

Recursively printing a star pattern

For my c++ data structures class our assignment is to print a pattern of stars like this
*
* *
* * *
* * * *
* * * *
* * *
* *
*
with the number of lines in the pattern determined by the user input. So the pattern above would print if the user enters a 4.
We had a previous assignment where we had to print the opposite pattern, one like this
* * * * *
* * * *
* * *
* *
*
*
* *
* * *
* * * *
* * * * *
and the above pattern would print if the user enters a 5. This pattern, the one above, I had no problem with. I used a for loop to print the top half, then recursively called the function again, and then the same for loop to print the bottom half in the opposite direction. For reference, here's the code I used for the above pattern:
int main()
{
int number;
cout << "Enter the number of lines in the grid: ";
cin >> number;
printStars(number);
cout << endl << "Grid Pattern Complete - End of Program.";
return 0;
} // end of main
void printStars(int num)
{
if (num < 0) cout << endl << "Please enter a non negative number." << endl;
else{
if (num == 0) return;
else{
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
printStars(num - 1);
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
}
}
} // end printStars
This function works like how I want it, so I figured I would use it as a reference to complete the second assignment. The problem I'm having is that, while it was easy enough to complete the first assignment (printing a line of 4 stars, then a line of 3, then a line of 2 , then a line of 1, then all that again in reverse order), I can't seem to figure out how to format the for loops to print the pattern starting with a line of 1 star, then a line of 2, then a line of 3, and so on, until its called recursively and printed again in reverse order.
For reference, this is the code I have (so far) for the second assignment:
int main()
{
int number;
cout << "Enter the number of lines in the grid: ";
cin >> number;
printStars(number, 0);
cout << endl << "Grid Pattern Complete - End of Program.";
return 0;
}
void printStars(int num, int num2)
{
if (num2 <= num)
{
for (int e = num; e > num2; e--)
{
cout << "*";
}
cout << endl;
printStars(num - 1, num2);
}
}
The only thing this prints is the second half of the pattern;
(If the user enters a 5)
* * * * *
* * * *
* * *
* *
*
And even to make this work, I have to recursively call the function at the end, which is out of order.
I guess I'm just confused on how this recursion is supposed to work but I've been playing with it for hours and I can't seem to reformat it or rearrange it or restructure it so that it prints like I need it to. Can someone give me some guidance? Just maybe write some pseudo code to help me out. This is for school so I need to be able to understand it but I'm really lost right now.
Try this. It is minimally modified version of your code. The upper limit is passed to all recursions and the recursive function calls are performed with the values starting with 1 (only 1 start in the first line):
void printStars(int num, int limit)
{
if (num >limit) return;
else{
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
printStars(num +1, limit);
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
}
}
int main()
{
int number=5;
cin>>number;
printStars(1, number);
return 0;
} // end of main
I tested it and the result is correct. The link is:
http://ideone.com/ez6pZ5
ideone result:
Success time: 0 memory: 3144 signal:0
*
**
***
****
*****
*****
****
***
**
*
For the sake of the exercise - how about a recursive function to print the stars and another to determine the number of stars:
string ReturnStars(int number)
{
if (number > 1)
return "*" + ReturnStars(number -1);
return "*";
}
void PrintStars(int start, int lines)
{
cout << ReturnStars(start) << endl;
if (start < lines)
PrintStars(start + 1, lines);
cout << ReturnStars(start) << endl;
}
int main()
{
int numberLines = 1;
cout << "Please enter a positive number to print a star pattern for: ";
cin >> numberLines;
PrintStars(1, numberLines);
return 0;
}
Example of output:
I suggest using two recursive functions, one to print in increasing order and the other to print in decreasing order.
After you get the two functions working, save a copy of the program.
You can then try to create one function the performs both increasing and decreasing orders of stars.
You aren't printing out the stars after your recursion call:
void printStars(int num, int num2)
{
if (num2 < num)
{
for (int e = num; e > num2; e--)
{
cout << "*";
}
cout << endl;
printStars(num - 1, num2);
for (int e = num; e > num2; e--)
{
cout << "*";
}
cout << endl;
}
}
note the if condition had to change slightly too. I also agree with Thomas, it might make more sense to structure your recursion differently:
void printStars(int num)
{
for (int i = 1; i <= num; i++)
{
cout << "*";
}
cout << endl;
}
void printStarsRecursive(int stars)
{
if (stars == 0)
return;
printStars(stars);
printStarsRecursive(stars-1);
printStars(stars);
}
int main()
{
int number;
cout << "Enter the number of lines in the grid: ";
cin >> number;
printStarsRecursive(number);
cout << endl << "Grid Pattern Complete - End of Program.";
return 0;
}
If you want to do it recursively, you have to keep in mind that there are multiple states: the state where you're counting up to N, and the state where you're counting back to 1. So if you have to go it recursively, you need to keep track of those extra things:
void printStarsImpl(int count, int initial, int sign)
↑ ↑ ↑
current termination next step
And this function just has to know which next printStarsImpl() function to call - whether we just call with count + sign, whether we flip sign to -1, or whether we do nothing... all after printing count *'s of course.
The initial call is then:
void printStars(int n) {
printStarsImpl(1, n, +1);
}
The straightforward approach if to use the function declared as having only one parameter is the following with using a static local variable in the function
#include <iostream>
void print_stars( size_t n )
{
static size_t m;
if ( m++ != n )
{
for ( size_t i = 0; i < m; i++ ) std::cout << '*';
std::cout << std::endl;
print_stars( n );
}
--m;
for ( size_t i = 0; i < m; i++ ) std::cout << '*';
std::cout << std::endl;
}
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
size_t n = 0;
std::cin >> n;
if ( !n ) break;
std::cout << std::endl;
print_stars( n );
std::cout << std::endl;
}
return 0;
}
The program output can look like
Enter a non-negative number (0-exit): 4
*
**
***
****
****
***
**
*
Enter a non-negative number (0-exit): 3
*
**
***
***
**
*
Enter a non-negative number (0-exit): 2
*
**
**
*
Enter a non-negative number (0-exit): 1
*
*
Enter a non-negative number (0-exit): 0
If you do not want to use a static variable within the recursive function then instead of it you can apply a trick with standard stream member function width. In this case the recursive function will look the following way
#include <iostream>
#include <iomanip>
void print_stars( size_t n )
{
std::streamsize m = std::cout.width();
if ( m++ != n )
{
std::cout.width( m );
std::cout << std::setfill( '*' );
std::cout << '*' << std::endl;
std::cout.width( m );
print_stars( n );
}
std::cout.width( m-- );
std::cout << std::setfill( '*' );
std::cout << '\n';
}
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
size_t n = 0;
std::cin >> n;
if ( !n ) break;
std::cout << std::endl;
print_stars( n );
std::cout << std::endl;
}
return 0;
}
The output will be the same as above.
P.S. It seems that the only programmer who is able to write the function is me unemployed.:) All others are unable to do this assignment for beginners.:)
I think the best answer should be if only one recursive function is used -
#include <iostream>
using namespace std;
void recursive(int current, int lastEnter, int limit, bool isLimitReached) {
cout << "*";
if(current == lastEnter ) {
cout << endl;
current = 0;
if(isLimitReached == false)
lastEnter++;
else lastEnter--;
}
if(current + 1 == limit) {
isLimitReached = true;
}
current++;
if(!(isLimitReached == true && lastEnter == 0))
recursive(current, lastEnter, limit, isLimitReached);
}
int main()
{
int num = 0;
cout << "Enter max number of stars to be generated : ";
cin >> num;
recursive(1, 1, num, false);
return 0;
}
The code above uses only one recursive function without for/while loops.
output -
Enter max number of stars to be generated : 6
*
**
***
****
*****
******
*****
****
***
**
*

Convert integers to characters [duplicate]

This question already has answers here:
How to convert a number to string and vice versa in C++
(5 answers)
Closed 9 years ago.
I am trying to get my program to print letters instead of numbers. I used char c = static_cast<char>(N); to attempt to do this but it wont work, instead it prints character images that are not (a-z) How can I get the numbers to be printed as letters?
#include <cstdlib>
#include <iostream>
using namespace std;
// Function getUserInput obtains an integer input value from the user.
// This function performs no error checking of user input.
int getUserInput()
{
int N(0);
cout << endl << "Please enter a positive, odd integer value, between (1-51): ";
cin >> N;
if (N < 1 || N > 51 || N % 2 == 0)
{
cout << "Error value is invalid!" << "\n";
cout << endl << "Please enter a positive, odd integer value, between (1-51): ";
cin >> N;
system("cls");
}
cout << endl;
return N;
} // end getUserInput function
// Function printDiamond prints a diamond comprised of N rows of asterisks.
// This function assumes that N is a positive, odd integer.
void printHourglass(int N)
{
char c = static_cast<char>(N);
for (int row = (N / 2); row >= 1; row--)
{
for (int spaceCount = 1; spaceCount <= (N / 2 + 1 - row); spaceCount++)
cout << ' ';
for (int column = 1; column <= (2 * row - 1); column++)
cout << c;
cout << endl;
} // end for loop
// print top ~half of the diamond ...
for (int row = 1; row <= (N / 2 + 1); row++)
{
for (int spaceCount = 1; spaceCount <= (N / 2 + 1 - row); spaceCount++)
cout << ' ';
for (int column = 1; column <= (2 * row - 1); column++)
cout << c;
cout << endl;
} // end for loop
// print bottom ~half of the diamond ...
return;
} // end printDiamond function
int main()
{
int N = 1;
while (N == 1)
{
printHourglass(getUserInput());
cout << endl;
cout << "Would you like to print another hourglass? ( 1 = Yes, 0 = No ):";
cin >> N;
}
} // end main function
The letters are not numbered with A starting at 1 or anything like that. You're likely on an ASCII/UTF-8 system. So, in printHourglass, replace cout << N with
cout << static_cast<char>('A' + count - 1);
C functions, itoa
C++, using stringstream
boost::lexical_cast
Actually for your case, you can directly print it out. cout << N