Skip to content

Instantly share code, notes, and snippets.

@PaulMarisOUMary
Created October 12, 2023 20:24
Show Gist options
  • Save PaulMarisOUMary/31e88b4fb01e9c2768f1c06bf9169994 to your computer and use it in GitHub Desktop.
Save PaulMarisOUMary/31e88b4fb01e9c2768f1c06bf9169994 to your computer and use it in GitHub Desktop.
ASCII star of n using only write sys call (my_putchar)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void my_putchar(char c)
{
write(1, &c, 1);
}
static void top(unsigned int size) {
for (int i = size - 1; i >= 0; i--) {
for (int j = 0; j < size*2; j++) {
my_putchar(' ');
}
for (int j = 0; j < i; j++) {
my_putchar(' ');
}
my_putchar('*');
if (i != size - 1)
{
for (int j = 0; j < 2 * size - 2 * i - 3; j++) {
my_putchar(' ');
}
my_putchar('*');
}
my_putchar('\n');
}
}
static void plateau(unsigned int size) {
for (int i = 0; i < size * 2 + 1; i++) {
my_putchar('*');
}
for (int i = 0; i < 2 * size - 3; i++) {
my_putchar(' ');
}
for (int i = 0; i < size * 2 + 1; i++) {
my_putchar('*');
}
my_putchar('\n');
}
static void middle(unsigned int size) {
int space_count = 0;
int max_lenght = 6 * size - 1;
for (int i = 0; i < size * 2 - 1; i++)
{
if (i <= size - 1)
{
space_count++;
}
else
{
space_count--;
}
for (int j = 0; j < space_count; j++)
{
my_putchar(' ');
}
my_putchar('*');
for (int j = 0; j < max_lenght - space_count * 2 - 2; j++)
{
my_putchar(' ');
}
my_putchar('*');
my_putchar('\n');
}
}
static void bottom(unsigned int size) {
for (int i = 0 ; i < size; i++) {
for (int j = 0; j < size*2; j++) {
my_putchar(' ');
}
for (int j = 0; j < i; j++) {
my_putchar(' ');
}
my_putchar('*');
if (i != size - 1)
{
for (int j = 0; j < 2 * size - 2 * i - 3; j++) {
my_putchar(' ');
}
my_putchar('*');
}
my_putchar('\n');
}
}
static void star_one() {
// TOP
for (int i = 0; i < 3; i++) {
my_putchar(' ');
}
my_putchar('*');
my_putchar('\n');
// PLATEAU
for (int i = 0; i < 3; i++) {
my_putchar('*');
}
my_putchar(' ');
for (int i = 0; i < 3; i++) {
my_putchar('*');
}
my_putchar('\n');
// MIDDLE
my_putchar(' ');
my_putchar('*');
for (int i = 0; i < 3; i++) {
my_putchar(' ');
}
my_putchar('*');
my_putchar('\n');
// PLATEAU
for (int i = 0; i < 3; i++) {
my_putchar('*');
}
my_putchar(' ');
for (int i = 0; i < 3; i++) {
my_putchar('*');
}
my_putchar('\n');
// BOTTOM
for (int i = 0; i < 3; i++) {
my_putchar(' ');
}
my_putchar('*');
my_putchar('\n');
}
void star(unsigned int size) {
if (size == 0) {
return;
}
else if (size == 1)
{
star_one();
return;
}
top(size);
plateau(size);
middle(size);
plateau(size);
bottom(size);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <size>\n", argv[0]);
return 1;
}
int size = atoi(argv[1]);
star(size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment