diff --git a/arithmetic_progressions/.gitignore b/arithmetic_progressions/.gitignore new file mode 100644 index 0000000..1bac95e --- /dev/null +++ b/arithmetic_progressions/.gitignore @@ -0,0 +1 @@ +ap \ No newline at end of file diff --git a/arithmetic_progressions/Makefile b/arithmetic_progressions/Makefile new file mode 100644 index 0000000..0b3b9c3 --- /dev/null +++ b/arithmetic_progressions/Makefile @@ -0,0 +1,9 @@ +# Rudimetary makefile +CC=gcc +CFLAGS= -ggdb + +ap: arithmetic_progressions.c + $(CC) -o $@ $< $(CFLAGS) + +clean: + rm ap diff --git a/arithmetic_progressions/arithmetic_progressions.c b/arithmetic_progressions/arithmetic_progressions.c new file mode 100644 index 0000000..ca0fe2c --- /dev/null +++ b/arithmetic_progressions/arithmetic_progressions.c @@ -0,0 +1,53 @@ +#include +#include +#include + +#define INTS_START_SIZE 8 +#define INTS_DELIM " \t\n" +#define BUF_SIZE 1024 + +size_t read_ints(char *str, int **ints) { + if (str == NULL) { + return 0; + } + size_t size = INTS_START_SIZE; + *ints = malloc(INTS_START_SIZE * sizeof *ints); + if (*ints == NULL) { + return 0; + } + + size_t i = 0; + char *toksave, *end; + long int tmp; + char *tok = strtok_r(str, INTS_DELIM, &toksave); + while (tok != NULL) { + tmp = strtol(tok, &end, 10); + if (*end == '\0' || isspace(*end)) { // valid number found + if (i == size) { + // If we have filled array, double its size + size *= 2; + *ints = realloc(*ints, size * sizeof *ints); + if (*ints == NULL) { + return 0; + } + } + // store in array + (*ints)[i] = tmp; + i++; + } + tok = strtok_r(NULL, INTS_DELIM, &toksave); + } + return i; +} + +int main(int argc, char **argv) { + char buf[BUF_SIZE]; + fgets(buf, BUF_SIZE, stdin); + int *ints; + size_t numints = read_ints(buf, &ints); + int i; + for (i = 0; i < numints; i++) { + printf("%d\n", ints[i]); + } + return 0; +} \ No newline at end of file