I wonder if it is possible to print an opposite triangle (by "*") recursively using 1 function only.
for example
for the given base n=4
it should print
*****
***
**
*
*
**
***
****
I am a beginner, but I know how to program 1 recursive function for
*****
***
**
*
and one for
*
**
***
****
but is it possible to program 2 opposite triangles in 1 function?
Might be a stupid question that the answer of it is no- but I've been trying for an hour now and I could'nt make it.
I will be very thankful if you can let me know if it's even possible or not.
EDIT: My code for 2 different functions:
#include <iostream>
using namespace std;
void printOppositeriangle(int n);
void printOppositeriangle2(int n);
void main()
{
int n = 5;
printOppositeriangle(n);
printOppositeriangle2(n);
}
void printOppositeriangle(int n)
{
if (n == 0)
return;
else
{
for (int i = 0; i < n; i++)
cout << "*";
cout << endl;
printOppositeriangle(n - 1);
}
}
void printOppositeriangle2(int n)
{
if (n == 0)
return;
else
printOppositeriangle2(n - 1);
for (int i = 0; i < n; i++)
cout << "*";
cout << endl;
}
Simple enough, make your recursive call in the middle, before and after print out a row of asterisks.
void print(int n)
{
for (int i = 0; i < n; ++i)
cout << '*';
cout << '\n';
if (n > 1)
print(n - 1);
for (int i = 0; i < n; ++i)
cout << '*';
cout << '\n';
}
Untested code.
Related
ive got the below code to print a pattern (attached below). However i'd like to just use one loop
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
cout<<"*";
}
for(int j=1;j<=n-i;j++){
if(j%2!=0){
cout<<"_";
}else{
cout<<".";
}
}
cout<<endl;
}
for(int i=1;i<n;i++){
for(int j=1;j<=n-i;j++){
cout<<"*";
}
for(int j=1;j<=i;j++){
if(j%2==0){
cout<<".";
}else{
cout<<"_";
}
}
cout<<endl;
}
}
when n = 5, heres the output.
*_._.
**_._
***_.
****_
*****
****_
***_.
**_._
*_._.
how do i just make this into one single loop
Try this and see how it does what you want to understand the step you did not find on your own:
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n*2-1; i++) {
if (i <= n)
{
for (int j = 1; j <= i; j++) {
cout << "*";
}
for (int j = 1; j <= n - i; j++) {
if (j % 2 != 0) {
cout << "_";
}
else {
cout << ".";
}
}
cout << endl;
}
else
{
for (int j = 1; j <= n*2 - i; j++) {
cout << "*";
}
for (int j = 1; j <= i-n; j++) {
if (j % 2 == 0) {
cout << ".";
}
else {
cout << "_";
}
}
cout << endl;
}
}
}
I'd like to just use one loop.
I'll take it literally and show a starting point for a possible solution.
// Let's start by figuring out some dimensions.
int n;
std::cin >> n;
int height = 2 * n - 1;
int area = n * height;
// Now we'll print the "rectangle", one piece at a time.
for (int i = 0; i < area; ++i)
{ // ^^^^^^^^
// Extract the coordinates of the char to be printed.
int x = i % n;
int y = i / n;
// Assign a symbol, based on such coordinates.
if ( x <= y and x <= height - y - 1 )
{ // ^^^^^^ ^^^^^^^^^^^^^^^^^^^ Those are the diagonals.
std::cout << '*'; // This prints correctly the triangle on the left...
}
else
{
std::cout << '_'; // <--- But of course, something else should done here.
}
// End of row.
if ( x == n - 1 )
std::cout << '\n';
}
If you look at the pattern, then you can see a sort of "triangles". And this already gives a hint for the solution. Use a triangle function.
Please read about it here.
Then you will notice that always the "aboslute"-function, in C++ std::abs, is involved.
But first of all, it is easily visible that the number rows to print is always the width of a triangle * 2.
And the number of charcters in the pattern, can be calculated by applying the triangle function. Example for width 5:
Number of stars number of dashdot
Row width-abs(row-width) abs(row-width)
1 1 4
2 2 3
3 3 2
4 4 1
5 5 0
6 4 1
7 3 2
8 2 3
9 1 4
And this can be implemented easily now.
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std::string_literals;
int main() {
// Get the max width of the pattern and perform a short input validation
int maxWidth{};
if ((std::cin >> maxWidth) and (maxWidth > 0)) {
// The number of rows for the pattern is dependent on the width. It is a simple relation
const int numberOfRows = 2 * maxWidth;
// Show all rows
for (int row = 1; row < numberOfRows; ++row) {
// Use triangle formular to create star pattern
std::string starPattern(maxWidth - std::abs(row - maxWidth), '*');
// Create dashDot pattern
std::string ddp(std::abs(row - maxWidth), '\0');
std::generate(ddp.begin(), ddp.end(), [i = 0]() mutable { return i++ % 2 ? '.' : '_'; });
// Show output
std::cout << (starPattern+ddp) << '\n';
}
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
Of course you can also create the whole pattern wit std::generate.
Maybe it is too complex for now.
And less understandable.
See:
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
int main() {
// Get the max width of the pattern and perform a short input validation
if (int width{}; (std::cin >> width) and (width > 0)) {
std::vector<std::string> row(2 * width - 1);
std::for_each(row.begin(), row.end(), [&, r = 1](std::string& s) mutable {
s = std::string(width - std::abs(r - width), '*');
std::string ddp(std::abs(r++ - width),'\0');
std::generate(ddp.begin(), ddp.end(), [&, i = 0]() mutable{ return i++ % 2 ? '.' : '_'; });
s += ddp; std::cout << s << '\n'; });
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
I need to print a star pattern like this:
*****
** *
*** *
*****
The code that I have tried is:
#include <iostream>
using namespace std;
int main()
{
int i,j,k;
for(i=1;i<5;i++){
for(j=1;j<5;j++){
if(i==1 || j==4 || i==4 )
// if(j==4 || i==4)
cout<<"*";
if(i>1 && i<4){
for(k=1;k<3;k++){
cout<<"";
}
}
else {
cout<<"";
}
}
cout<<endl;
}
return 0;
}
This is the output I get:
****
*
*
****
So, you see I'm having trouble printing the star at the end of each line. and as you can see in the desired output I provided above, in the 2nd and 3rd line, I need to print them with gaps. Now, as I've given the code, I tried to do that but not sure why isn't it working. So, I need your help in achieving this output.
Many other questions have similar title but this is about a completely different star pattern.
P.S: On a side note, I want to mention that I've been learning C++ for over a year now, and I am still having trouble with loops. I have understood other things such as functions, if-else, structures, arrays, basic oop etc, but for some reason, loops trouble me so I thought I should do these star pattern exercises. If you guys have any suggestions how I can improve my logic in loops (especially the nested ones), then it would be very helpful for me. Thanks.
Corrected code with my comments:
#include <iostream>
using namespace std;
int main()
{
int n = 5; // columns count
for(int i = 1; i < n; i++) // i is row index
{
for(int j = 1; j <= n; j++) // j is current symbol index in line i
{ // note, you print 5 symbols per line, so j <= 5, not j < 5
if (i > 1 && i < n && j != n && j > i) // for lines 2 and 3 indexes [3-4] and [4] print space, print * for symbol #5 (last symbol in a line is always *)
{
cout << " ";
}
else
{
cout << "*";
}
}
cout << endl;
}
return 0;
}
i=1;i<5;
This runs 4 times. i=1,i=2,i=3,i=4.
You either need i<6 or i<=5
In an effort to make the "shortest, cleanest C++ code," you could do it all in a single loop:
int n = 10; //input
std::cout << std::string(n, '*') << std::endl; //First line
for (int i = 2; i < n; i++)
std::cout << std::string(i, '*');
<< std::string(n - i - 1, ' ')
<< '*' << std::endl;
The Issue is that "" does not register a space, " " will though.
int main()
{
int i, j, k;
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++) {
if (i == 0 || i == 3)
{
cout << "*";
}
else if (i == 1) {
if (j == 2 || j == 3) {
cout << " ";
}
else {
cout << "*";
}
}
else if (i == 2) {
if (j == 3) {
cout << " ";
}
else {
cout << "*";
}
}
}
cout << endl;
}
return 0;
}
here's a solution in python. you should be able to extrapolate from that into C++
N = 10
print('*' * N)
for row in range(2, N+1):
print('*' * row, end='')
print(' ' * (N-row -1), end='')
print('*')
here's a solution in C++, which does the exact same thing but is longer than the python solution. I gave the python solution first because I believed it shows the thought process more cleanly than the C++ counterpart.
int N = 10;
for(int i=0 ; i<N ; ++i)
cout << '*';
cout << endl;
for (int row = 2; row < N; ++row) {
for(int i=0 ; i<row ; ++i)
cout << "*";
for(int i=row ; i<N-1; ++i)
cout << ' ';
cout << '*' << endl;
}
this is the output for N=10
**********
** *
*** *
**** *
***** *
****** *
******* *
******** *
**********
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
I am trying to do this exercise.
Write a recursive function to generate a pattern of stars such as the following:
*
**
***
****
****
***
**
*
It seems simple but is giving me a lot of problems. I can only output this
*
**
***
****
using the following code
#include <iostream>
using namespace std;
void outputStars(int);
int main()
{
outputStars(5);
return 0;
}
void outputStars(int num)
{
if (num == 1)
{
return;
}
outputStars(--num);
for (int i = 0; i < num ; i++)
{
cout << "*";
}
cout << endl;
}
You are only printing the stars when you return from the call. Also print it before you call.
I've modified it to take 2 arguments. i specifies number of times * is to be printed in a call
void outputStars(int num,int i)
{
if (i == num)
{
return;
}
for (int j = 0 ;j < i; j++)
{
cout << "*";
}
cout << endl;
outputStars(num,i+1);
for (int j = 0; j < i; j++)
{
cout << "*";
}
cout << endl;
Call it as
outputStars(5,1);
#include <stdio.h>
void rec_fun(int x);
void print_stars(int times, int x);
int main(int argc, char *argv[])
{
rec_fun(5);
return 0;
}
void rec_fun(int x)
{
static int times = x;
if (x <= 0)
return;
print_stars(times, x);
rec_fun(x - 1);
if (x != 1)
print_stars(times, x);
}
void print_stars(int times, int x)
{
int i;
for (i = 0; i < times - x + 1; i++)
printf("*");
printf("\n");
}
i want to write a program to draw the shape of X letter using asterisk(*)
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[]){
int i, j;
for(i = 1; i <= 9; i++){
for(j = 1; j <= 12; j++){
if(i == j){
cout << "***";
}else{
cout << " ";
}
}
cout<< endl;
}
return 0;
}
i am very new to programming
i only made (\) how can I make the whole X
***------***
-***----***-
--***--***--
---******---
--***--***--
-***----***-
***------***
that's what i did uptill now
include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int i, d, a=1,b=12,c;
for(i = 1; i <= 6; i++)
{
for (d=1; d<i;d++) {cout <<" ";}
cout<<"***";
for (c=a+1; c<b;c++) {cout <<" ";}
{cout<<"***";}
for(b=12-i;b<i;b++)
{cout<<"***";}
cout<<endl;
a++;
}
return 0;
}
i divided the top of the (\//) to three parts
[space][][space][]
I have written the following function/method in java. You can convert it to c++;
public static void printX(int x) {
char[] chars = new char[x];
for (int i = 0; i < x; i++) {
chars[i] = '*';
chars[x - 1 - i] = '*';
for (int j = 0; j < x; j++) {
if (j == i || j == (x - 1 - i)) {
continue;
}
chars[j] = ' ';
}
System.out.println(new String(chars));
}
}
If you call the above function/method as printX(5); The output will by 5x5 sized and containing X character.
* *
* *
*
* *
* *
**** ****
*** ***
** **
* *
** **
*** ***
**** ****
Firstly, pardon my very uneven X. For you as a beginner I would give out an algo for you to ponder upon rather than spoon feeding a code.
The interpreter does not know how to come back to a line which has already been printer.
Therefore, you would have to draw both sides of the X in one iteration of the loop.
After that you decrease you star count (star--) and draw line # 2.
Repeat till the mid way mark when your stars are 0.
When your code sees that the stars are 0, then start with the same loop but this time star++ in each iteration.
This is repeated till the starting count of the star i.e 4 in my case.
If any problems you can post your code on the site :)
You shall dynamically evaluate the spacing areas in each row. Draw manually desired shape on piece of paper and try to create function, which takes as an argument the row number and returns amount of spaces required in the specific row. For example:
* *
* *
*
* *
* *
The amount of spaces in each row equals:
0 [*] 3 [*]
1 [*] 1 [*]
2 [*]
1 [*] 1 [*]
0 [*] 3 [*]
Note, that inside each row you'll need two loops: first for the initial and middle spaces.
The solution I wrote 2 decades ago (when I was still learning):
Make an line-column array, e.g. char screen[80][25];
Clear it by setting all entries to ' '
"Draw a point" at x,y by setting screen[x][y]='*';
When done, render the whole screen[80][25] by calling cout 2080 times. (2000 times for the characters and and 80 times for endl)
In your case, you know how to draw a \. You can easily adapt this. But with my method, you can then draw a / in the same screen array. And when you're done, you have an overlapping / and \ at the last step: X
I used this method since we had to draw a circle and that's really a lot harder. And yes, nowadays I'd probably use std::vector<std::string> screen but back then screens were really 80x25 :)
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int i, d, a=1,b=12,c ,e=1;
for(i = 1; i <= 6; i++)
{
for (d=1; d<i;d++) {cout <<" ";}
cout<<"***";
for (c=a+1; c<b;c++) {cout <<" ";}
{cout<<"***";}
for(b=12-i;b<i;b++)
{cout<<"***";}
cout<<endl;
a++;
}
for( i = 1; i <= 3; i++)
{
for ( d=6; d>i;d--) {cout <<" ";}
cout<<"***";
for (c=0; c<e-1;c++) {cout <<" ";}
{cout<<"***";}
cout<<endl;
e++;
}
return 0;
}
int n=11,i=0,k=0,j=0;
for(i=0;i<n;i++)
{
if(i<(n/2))
{
cout<<endl;
for(j=0;j<i;j++)
{
cout<<" ";
}
cout<<"*";
for(k=n/2;k>i;k--)
{
cout<<" ";
}
cout<<"*";
}
else
{
cout<<endl;
for(k=n-1;k>i;k--)
{
cout<<" ";
}
cout<<"*";
for(j=n/2;j<i;j++)
{
cout<<" ";
}
cout<<"*";
}
}
#include<iostream>
using namespace std;
int main()
{
int i, j;
for(i = 1;i<= 5;i++)
{
for(j = 1;j<= 5;j++)
{
if((i == j)||(j==(5+1)-i))
{
cout << "*";
}
else{
cout << " ";
}
}
cout<< endl;
}
system("pause");
}
#include "stdafx.h"
#include <iostream>
using namespace std;;
int _tmain(int argc, _TCHAR* argv[])
{
int i,k,j;
for (i=1;i<8;i++)
{
for (int k=0;k<i;k++)
{
cout<<" ";
}
cout<<"*";
for (int k=8;k>i;k--)
{
cout<<" ";
}
cout<<"*";
cout<<endl;
}
for (i=1;i<8;i++)
{
for (int k=8;k>i;k--)
{
cout<<" ";
}
cout<<"*";
for (int k=0;k<i;k++)
{
cout<<" ";
}
cout<<" *";
cout<<endl;
}
system("Pause");
return 0;
}