1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-10-29 22:17:23 +01:00

feat(solutions): add print-pyramid/c/function

This commit is contained in:
Divlo 2021-09-29 23:10:38 +02:00
parent 7d140cb8a9
commit 264da68a20
No known key found for this signature in database
GPG Key ID: 6F24DA54DA3967CF
6 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,3 @@
# print-pyramid/c/function
Created by [@Divlo](https://github.com/Divlo) on 29 September 2021.

View File

@ -0,0 +1,17 @@
#include "character.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void character_append(char* string, char character) {
size_t length = strlen(string);
string[length] = character;
string[length + 1] = '\0';
}
void character_print(char* character, int number_of_times) {
for (size_t iteration = 0; iteration < number_of_times; iteration++) {
printf("%s", character);
}
}

View File

@ -0,0 +1,15 @@
#ifndef CHARACTER_H
#define CHARACTER_H
/**
* @brief Append a character to a string, assuming string points to an array
* with enough space.
*
* @param string
* @param character
*/
void character_append(char* string, char character);
void character_print(char* character, int number_of_times);
#endif

View File

@ -0,0 +1,19 @@
#include "input.h"
#include <stdio.h>
#include <stdlib.h>
#include "character.h"
char* input() {
char character;
size_t length = 1;
char* string = malloc(length * sizeof(char));
*string = '\0';
while ((character = getchar()) != '\n' && character != EOF) {
length++;
string = realloc(string, length * sizeof(char));
character_append(string, character);
}
return string;
}

View File

@ -0,0 +1,11 @@
#ifndef INPUT_H
#define INPUT_H
/**
* @brief Read a line from stdin.
*
* @return char*
*/
char* input();
#endif

View File

@ -0,0 +1,27 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "character.h"
#include "input.h"
int main() {
char* type = input();
int height;
scanf("%d", &height);
int step = strcmp(type, "normal") == 0 ? 1 : height;
while ((strcmp(type, "normal") == 0 && step <= height) || (strcmp(type, "reverse") == 0 && step != 0)) {
int numberOfStars = (step * 2) - 1;
int totalNumberOfLocations = (height * 2) - 1;
int totalNumberOfSpaces = totalNumberOfLocations - numberOfStars;
int numberOfSpacesOnEachSide = totalNumberOfSpaces / 2;
character_print(" ", numberOfSpacesOnEachSide);
character_print("*", numberOfStars);
character_print(" ", numberOfSpacesOnEachSide);
printf("\n");
step = strcmp(type, "normal") == 0 ? step + 1 : step - 1;
}
return EXIT_SUCCESS;
}