Last active
February 20, 2024 11:29
-
-
Save GReturn/acbd91f93f7c0e2219b5af17c6edaaa1 to your computer and use it in GitHub Desktop.
Given Width, print Diamond - Recursive Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// given width, print diamond | |
#include <stdio.h> | |
void printSpaces(int sp) | |
{ | |
if(sp <= 0) return; | |
printf(" "); | |
return printSpaces(sp-1); | |
} | |
void printStars(int st) | |
{ | |
if(st <= 0) return; | |
printf("* "); | |
return printStars(st-1); | |
} | |
void drawLine(int spaces, int stars) | |
{ | |
printSpaces(spaces); | |
printStars(stars); | |
printf("\n"); | |
return; | |
} | |
void drawUpperHalf(int row, int starsCount) | |
{ | |
if(row<=0) return; | |
drawLine(row-1, starsCount); | |
drawUpperHalf(row-1, starsCount+2); | |
return; | |
} | |
void drawLowerHalf(int row, int starsCount) | |
{ | |
if(row<=0) return; | |
drawLowerHalf(row-1, starsCount+2); | |
drawLine(row, starsCount-2); | |
return; | |
} | |
void drawDiamond(int width) | |
{ | |
int height = (width%2==0) ? width/2 : width/2 + 1; | |
drawUpperHalf(height, 1); | |
drawLowerHalf(height-1, width-2); | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
drawDiamond(5); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment