From 4b06a1587ee338541c70473750795e7dbef3b734 Mon Sep 17 00:00:00 2001 From: Maalvika Bhat Date: Thu, 6 Feb 2020 12:06:46 -0500 Subject: [PATCH] Submission --- exercises/ex02/adder.c | 57 +++++++++++++++++++++++++++++++++++++++++ exercises/ex02/aspace.c | 23 ++++++++++++----- exercises/ex02/stack.c | 18 ++++++------- 3 files changed, 81 insertions(+), 17 deletions(-) create mode 100644 exercises/ex02/adder.c diff --git a/exercises/ex02/adder.c b/exercises/ex02/adder.c new file mode 100644 index 00000000..63d48c9a --- /dev/null +++ b/exercises/ex02/adder.c @@ -0,0 +1,57 @@ +/* + * Exercise 2 + * Maalvika Bhat + */ + +#include +#include +#include + +int processInput(char input[]) { + int val = atoi(input); + + if (val == 0) { + puts("input not valid"); + } else if (strlen(input) > 10) { + puts("input is too large"); + } else { + printf("input of %i has been added\n", val); + return val; + } + return 0; +} + +void addIntegers(int integers[]) { + int sum = 0; + for (int i = 0; i < 10; ++i) { + sum += integers[i]; + } + printf("final sum of all the integers is %i\n", sum); +} + +void run() { + char input[5]; + int integers[10]; + int count = 0; + + puts("enter up to 10 integers to add"); + while (scanf("%10s", input) != EOF) { + if (count < 10) { + int result = processInput(input); + + if (result != 0) { + integers[count] = result; + count++; + } + } else { + puts("press CTRL+D to add the integers up"); + continue; + } + } + addIntegers(integers); +} + +int main() { + run(); + return 0; +} diff --git a/exercises/ex02/aspace.c b/exercises/ex02/aspace.c index 6403e0ac..28cdb444 100644 --- a/exercises/ex02/aspace.c +++ b/exercises/ex02/aspace.c @@ -1,15 +1,13 @@ -/* Example code for Think OS. - -Copyright 2014 Allen Downey -License: GNU GPLv3 - -*/ - #include #include int var1; +void printLocalVariable() { + int a = 0; + printf("Address of local variable a is %p\n", &a); +} + int main () { int var2 = 5; @@ -22,5 +20,16 @@ int main () printf ("p points to %p\n", p); printf ("s points to %p\n", s); + p = malloc(10); + printf ("Address of p is now %p\n\n", p); + + printLocalVariable(); + + void *b = malloc(10); + void *c = malloc(10); + + printf ("Address of b is %p\n", b); + printf ("Address of c is %p\n\n", c); + return 0; } diff --git a/exercises/ex02/stack.c b/exercises/ex02/stack.c index 61d2568a..442d648a 100644 --- a/exercises/ex02/stack.c +++ b/exercises/ex02/stack.c @@ -1,10 +1,3 @@ -/* Example code for Think OS. - -Copyright 2014 Allen Downey -License: GNU GPLv3 - -*/ - #include #include @@ -12,7 +5,7 @@ License: GNU GPLv3 int *foo() { int i; - int array[SIZE]; + int array[SIZE]; // local array printf("%p\n", array); @@ -24,7 +17,7 @@ int *foo() { void bar() { int i; - int array[SIZE]; + int array[SIZE]; // local array printf("%p\n", array); @@ -36,7 +29,7 @@ void bar() { int main() { int i; - int *array = foo(); + int *array = foo(); // assigning a pointer to a function's local array bar(); for (i=0; i