coding for printing diamond pattern using recursion
as following
*
* *
* * *
* * * *
* * *
* *
*

Dani AI

Generated

The goal is a centered diamond of stars (rows 1..N..1) produced by recursion rather than loops. provided an iterative triangle-style example that’s a useful starting point, but it does not produce the centered diamond or demonstrate a recursive approach. The recursive trick is to print a line, recurse toward the middle, then print the same line again on the unwind so the top and bottom mirror each other.

Algorithm in short:

  • Represent the diamond by its maximum star count in the middle (call it max, so total rows = 2*max-1).
  • A helper printLine(stars, max) emits the correct leading spaces and single spaces between stars.
  • A recursive function diamond(cur, max) prints printLine(cur,max), calls diamond(cur+1,max), then prints printLine(cur,max) again unless cur==max (to avoid duplicating the middle row).

A compact C++ recursive implementation:

#include <iostream>
using namespace std;

void printLine(int stars, int maxStars) {
    int lead = maxStars - stars;
    for (int i = 0; i < lead; ++i) cout << ' ';
    for (int i = 0; i < stars; ++i) {
        if (i) cout << ' ';
        cout << '*';
    }
    cout << '\n';
}

void diamond(int cur, int max) {
    if (cur > max) return;
    printLine(cur, max);
    diamond(cur + 1, max);
    if (cur != max) printLine(cur, max);
}

int main() {
    int max = 4; // middle row has 4 stars
    diamond(1, max);
    return 0;
}

Notes and caveats: handle max<=0 as a no-op. For very large max recursion depth may be an issue; an iterative two-pass solution (build top then mirror) avoids stack growth. If the desired total row count is given (odd number T), compute max = (T+1)/2.

Recommended Answers

All 3 Replies

Please show us some work, ask questions.

Then you'll get some help.

#include <iostream>
using namespace std;
int main(){

int i, j, N=7;

for(i=1; i<=(0.5*N+1); i++){
    for(j=1;j<=i; j++){
        cout<<"*";}
cout<<"\n";}

for(i=(0.5*N); i<=N; i++){
for(j=(N-1); j>i; j--){
    cout<<"*";}
cout<<"\n";}



return 0;}

hope this gives you an idea that you can manipulate to your taste

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.