Skip to content

Instantly share code, notes, and snippets.

@sumeet
Created June 15, 2022 02:05
Show Gist options
  • Save sumeet/05c81cc54200f6760863b1dad81ecbe5 to your computer and use it in GitHub Desktop.
Save sumeet/05c81cc54200f6760863b1dad81ecbe5 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <algorithm>
// print regular triangle
// for n = 5
// X
// XX
// XXX
// XXXX
// XXXXX
// ----
void print_reg_triangle(int n) {
for (int fill = 1; fill <= n; fill++) {
for (int i = 0; i < fill; i++) printf("X");
printf("\n");
}
}
// print upside down (usd) triangle
// for n = 5
// XXXXX
// XXXX
// XXX
// XX
// X
// ----
void print_usd_triangle(int n) {
for (int i = 0; i < n; i++) {
// add leading spaces
for (int j = 0; j < i; j++) printf(" ");
// fill in triangle for this line
for (int j = 0; j < n - i; j++) printf("X");
printf("\n");
}
}
int main() {
int n = 5;
void (*current_print) (int) = &print_reg_triangle;
void (*next_print) (int) = &print_usd_triangle;
for (int i = 0; i < n; i++) {
current_print(n);
printf("----\n");
// flip flop between regular and upside down printing
std::swap(current_print, next_print);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment