commit 2960058ed918c5a7c759dbb6c092790c9df7dfbe Author: Peter Babič Date: Sun May 3 18:07:52 2020 +0200 initial commit diff --git a/02_C_Fundamentals/Debug/02_C_Fundamentals b/02_C_Fundamentals/Debug/02_C_Fundamentals new file mode 100644 index 0000000..07a89ad Binary files /dev/null and b/02_C_Fundamentals/Debug/02_C_Fundamentals differ diff --git a/02_C_Fundamentals/Debug/main.o b/02_C_Fundamentals/Debug/main.o new file mode 100644 index 0000000..0f04644 Binary files /dev/null and b/02_C_Fundamentals/Debug/main.o differ diff --git a/02_C_Fundamentals/Debug/makefile b/02_C_Fundamentals/Debug/makefile new file mode 100644 index 0000000..b131d89 --- /dev/null +++ b/02_C_Fundamentals/Debug/makefile @@ -0,0 +1,43 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 02_C_Fundamentals + +# Tool invocations +02_C_Fundamentals: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "02_C_Fundamentals" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 02_C_Fundamentals + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/02_C_Fundamentals/Debug/sources.mk b/02_C_Fundamentals/Debug/sources.mk new file mode 100644 index 0000000..df1db10 --- /dev/null +++ b/02_C_Fundamentals/Debug/sources.mk @@ -0,0 +1,17 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +O_SRCS := +C_SRCS := +S_UPPER_SRCS := +OBJ_SRCS := +ASM_SRCS := +OBJS := +C_DEPS := +EXECUTABLES := + +# Every subdirectory with source files must be described here +SUBDIRS := \ +. \ + diff --git a/02_C_Fundamentals/Debug/subdir.mk b/02_C_Fundamentals/Debug/subdir.mk new file mode 100644 index 0000000..726e710 --- /dev/null +++ b/02_C_Fundamentals/Debug/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../main.c + +OBJS += \ +./main.o + +C_DEPS += \ +./main.d + + +# Each subdirectory must supply rules for building sources it contributes +%.o: ../%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/02_C_Fundamentals/main.c b/02_C_Fundamentals/main.c new file mode 100644 index 0000000..cea17dc --- /dev/null +++ b/02_C_Fundamentals/main.c @@ -0,0 +1,227 @@ +#include + +#define INCHES_PER_POUND 166 + +#define FREEZING_PT 32.0f +#define SCALE_FACTOR (5.0f / 9.0f) + +#define PI 3.141592f + +void dweight(void); +void dweight2(void); + +void celsius(void); + +void ex_01(void); +void ex_02(void); +void ex_03(void); +void ex_04(void); +void ex_05(void); +void ex_06(void); +void ex_07(void); +void pr_01(void); +void pr_02(void); +void pr_03(void); +void pr_04(void); +void pr_05(void); +void pr_06(void); +void pr_07(void); +void pr_08(void); + + +int main(void) { +// dweight(); +// dweight2(); + +// celsius(); + +// ex_04(); + + pr_08(); + + return 0; +} + +/* Calculates the dimensional weight of the box, + * constant size */ +void dweight(void) { + int height, lenght, width, volume, weight; + + height = 8; + lenght = 12; + width = 10; + volume = height * lenght * width; + weight = (volume + INCHES_PER_POUND - 1) / INCHES_PER_POUND; + + printf("Dimensions: %dx%dx%d\n", lenght, width, height); + printf("Volume (cubic inches): %d\n", volume); + printf("Dimensional weight (pounds): %d\n", weight); +} + +/* Calculates the dimensional weight of the box, + * user defined size */ +void dweight2(void) { + int height, lenght, width, volume, weight; + + printf("enter height: "); + scanf("%d", &height); + printf("enter lenght: "); + scanf("%d", &lenght); + printf("enter widht: "); + scanf("%d", &width); + volume = height * lenght * width; + weight = (volume + INCHES_PER_POUND - 1) / INCHES_PER_POUND; + + printf("Dimensions: %dx%dx%d\n", lenght, width, height); + printf("Volume (cubic inches): %d\n", volume); + printf("Dimensional weight (pounds): %d\n", weight); +} + +/* Converts tempereture from Fahrenheit to Celsius */ +void celsius(void) { + float fahrenheit, celsius; + + printf("Enter Fahrenheit temperature: "); + scanf("%f", &fahrenheit); + + celsius = (fahrenheit - FREEZING_PT) * SCALE_FACTOR; + + printf("Celsius equivalent: %.1f\n", celsius); +} + +/* EXERCISES */ +void ex_01(void) { + printf("Hello world\n"); +} + +void ex_02(void) { + printf("Parkinson's Law:\nWork expands so as to "); + printf("fill the time\n"); + printf("available for its completion.\n"); +} + +void ex_03(void) { + int height = 8, lenght = 12, width = 10, volume; + + volume = height * lenght * width; + + printf("Dimensions: %dx%dx%d\n", lenght, width, height); + printf("Volume (cubic inches): %d\n", volume); + printf("Dimensional weight (pounds): %d\n", + (volume + INCHES_PER_POUND - 1) / INCHES_PER_POUND); +} + +void ex_04(void) { + int a, b, c; + float d, e, f; + + printf("%d %d %d %f %f %f", a, b, c, d, e, f); +} + +void ex_05(void) { + int _100_bot, bott_by_hun; +} + +void ex_06(void) { + // Reserved +} + +void ex_07(void) { + // for +} + +/* PROJECTS */ +void pr_01(void) { + printf("%8c\n", '*'); + printf("%7c\n", '*'); + printf("%6c\n", '*'); + printf("%1c%4c\n", '*', '*'); + printf("%2c%2c\n", '*', '*'); + printf("%3c\n", '*'); +} + +void pr_02(void) { + int r = 10; + + printf("Volume of sphere of radius %dm is %fm^3.", r, + (4.0f / 3.0f) * PI * (r * r * r)); +} + +void pr_03(void) { + int r = 0; + printf("Please enter radius of the sphere (m): "); + scanf("%d", &r); + printf("Volume of sphere of radius %dm is %fm^3.", r, + (4.0f / 3.0f) * PI * (r * r * r)); +} + +void pr_04(void) { + float amount; + + printf("Enter an amount: "); + scanf("%f", &amount); + printf("With tax added: $%.2f", amount * 1.05f); +} + +void pr_05(void) { + float x; + + printf("Enter x: "); + scanf("%f", &x); + printf("3x^5 + 2x^4 - 5x^3 -x^2 - 6 = %f", + + 3 * (x * x * x * x * x) + + 2 * (x * x * x * x) + - 5 * (x * x * x) + - 1 * (x * x) + + 7 * (x) + - 6 * (1)); +} + +void pr_06(void) { + float x; + + printf("Enter x: "); + scanf("%f", &x); + printf("3x^5 + 2x^4 - 5x^3 -x^2 - 6 = %f", + ((((3 * x + 2) * x - 5) * x - 1) * x + 7) * x - 6); +} + +void pr_07(void) { + int amount, b20, b10, b5; + + printf("Enter a dollar amount: "); + scanf("%d", &amount); + + b20 = amount / 20; + amount -= b20 * 20; + b10 = amount / 10; + amount -= b10 * 10; + b5 = amount / 5; + amount -= b5 * 5; + + printf("\n$20 bills: %d\n$10 bills: %d\n $5 bills: %d\n $1 bills: %d", + b20, b10, b5, amount); +} + +void pr_08(void) { + float balance, interest, payment; + + printf("Enter amount of loan: "); + scanf("%f", &balance); + printf("Enter amount of interest: "); + scanf("%f", &interest); + printf("Enter amount of payment: "); + scanf("%f", &payment); + + float monthly = interest / 100 / 12; + + balance -= payment; + balance += (balance * monthly); + printf("\nBalance remaining after fist payment: $%.2f", balance); + balance -= payment; + balance += (balance * monthly); + printf("\nBalance remaining after second payment: $%.2f", balance); + balance -= payment; + balance += (balance * monthly); + printf("\nBalance remaining after third payment: $%.2f", balance); +} diff --git a/03_Formatted_IO/Debug/03_Formatted_IO b/03_Formatted_IO/Debug/03_Formatted_IO new file mode 100644 index 0000000..fd94acb Binary files /dev/null and b/03_Formatted_IO/Debug/03_Formatted_IO differ diff --git a/03_Formatted_IO/Debug/main.o b/03_Formatted_IO/Debug/main.o new file mode 100644 index 0000000..53288c4 Binary files /dev/null and b/03_Formatted_IO/Debug/main.o differ diff --git a/03_Formatted_IO/Debug/makefile b/03_Formatted_IO/Debug/makefile new file mode 100644 index 0000000..0c07459 --- /dev/null +++ b/03_Formatted_IO/Debug/makefile @@ -0,0 +1,43 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 03_Formatted_IO + +# Tool invocations +03_Formatted_IO: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "03_Formatted_IO" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 03_Formatted_IO + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/03_Formatted_IO/main.c b/03_Formatted_IO/main.c new file mode 100644 index 0000000..d92b245 --- /dev/null +++ b/03_Formatted_IO/main.c @@ -0,0 +1,171 @@ +/* CHAPTER 3 */ + +#include + +void tprintf(void); + +void ex_01(void); +void ex_02(void); +void ex_04(void); +void ex_05(void); + +void pr_01(void); +void pr_02(void); +void pr_03(void); +void pr_04(void); +void pr_05(void); +void pr_06(void); + +int main(void) { +// tprintf(); +// addfrac(); + +// ex_06(); + + pr_06(); + + return 0; +} + +/* Ilustrates the use of printf */ +void tprintf(void) { + int i; + float x; + + i = 40; + x = 839.21f; + + printf("|%d|%5d|%-5d|%5.3d|\n", i, i, i, i); + printf("|%10.3f|%10.3e|%-10g|\n", x, x, x); +} + +/* Adds two fractions */ +void addfrac(void) { + int num1, denom1, num2, denom2, result_num, result_denom; + + printf("Enter first fraction: "); + scanf("%d / %d", &num1, &denom1); + + printf("Enter second fraction: "); + scanf("%d / %d", &num2, &denom2); + + result_num = num1 * denom2 + num2 * denom1; + result_denom = denom1 * denom2; + + printf("The sum is %d/%d\n", result_num, result_denom); + +} + +/* EXERCISES */ +void ex_01(void) { + printf("%6d,%4d\n", 86, 1040); + printf("%12.5e\n", 30.253); + printf("%.4f\n", 83.162); + printf("%-6.2g\n", .0000009979); +} + +void ex_02(void) { + +// a) %-8.1e +// b) %10.6e +// c) %-8.3f +// d) %6.0f +} + +void ex_04(void) { +// Enter 10.3 5 6 + int i, j; + float x; + + scanf("%d%f%d", &i, &x, &j); + printf("i = %d, x = %.1f, j = %d", i, x, j); +} + +void ex_05(void) { + // Enter 12.3 45.6 789 + int i; + float x, y; + + scanf("%f%d%f", &x, &i, &y); + printf("x = %f, i = %d, y = %f", x, i, y); +} + +/* PROJECTS */ +void pr_01(void) { + int dd, mm, yyyy; + + printf("Enter a date (dd/mm/yyyy): "); + scanf("%d/%d/%d", &dd, &mm, &yyyy); + printf("You entered date: %.4d%.2d%.2d", yyyy, mm, dd); +} + +void pr_02(void) { + int number, dd, mm, yyyy; + float price; + + printf("Enter item number: "); + scanf("%d", &number); + printf("Enter item price: "); + scanf("%f", &price); + printf("Enter purchase date (dd, mm, yyyy): "); + scanf("%d/%d/%d", &dd, &mm, &yyyy); + + printf("\nItem\t\tUnit\t\tPurchase\n"); + printf(" \t\tPrice\t\tDate\n"); + printf("%d\t\t$ %.2f\t%.2d/%.2d/%.4d\n", + number, price, dd, mm, yyyy); +} + +void pr_03(void) { + int prefix, groupID, publisher, number, check; + + printf("Enter ISBN: "); + scanf("%d-%d-%d-%d-%d", &prefix, &groupID, + &publisher, &number, &check); + + printf("GS1 prefix: %d\n", prefix); + printf("Group identifier: %d\n", groupID); + printf("Publisher code: %d\n", publisher); + printf("Item number: %d\n", number); + printf("Check digit: %d\n", check); +} + +void pr_04(void) { + int a, b, c; + + printf("Enter phone number [(xxx) xxx-xxxx]: "); + scanf("(%d) %d-%d", &a, &b, &c); + printf("You entered: %d.%d.%d", a, b, c); +} + +void pr_05(void) { + int i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15, i16; + + // Enter 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 for Magic Square + printf("Enter numbers from 1 to 16 in any order:\n"); + scanf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", + &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8, &i9, &i10, &i11, &i12, &i13, &i14, &i15, &i16); + printf("\n"); + printf("%6d %2d %2d %2d |%2d\n", i1, i2, i3, i4, (i1 + i2 + i3 + i4)); + printf("%6d %2d %2d %2d |%2d\n", i5, i6, i7, i8, (i5 + i6 + i7 + i8)); + printf("%6d %2d %2d %2d |%2d\n", i9, i10, i11, i12, (i9 + i10 + i11 + i12)); + printf("%6d %2d %2d %2d |%2d\n", i13, i14, i15, i16, (i13 + i14 + i15 + i16)); + printf("--------------- | --\n"); + printf("%2d |%2d %2d %2d %2d |%2d\n", (i4 + i7 + i10 + i13), (i1 + i5 + i9 + i13), (i2 + i6 + i10 + i14), + (i3 + i7 + i11 + i15), (i4 + i8 + i12 + i16), (i1 + i6 + i11 + i16)); + + printf("\n"); +} + +void pr_06(void) { + int num1, denom1, num2, denom2, result_num, result_denom; + + printf("Enter two fractions separated by a plus sign: "); + scanf("%d / %d + %d / %d", &num1, &denom1, &num2, &denom2); + + + result_num = num1 * denom2 + num2 * denom1; + result_denom = denom1 * denom2; + + printf("The sum is %d/%d\n", result_num, result_denom); +} diff --git a/04_Expressions/Debug/04_Expressions b/04_Expressions/Debug/04_Expressions new file mode 100644 index 0000000..d87a3c7 Binary files /dev/null and b/04_Expressions/Debug/04_Expressions differ diff --git a/04_Expressions/Debug/main.o b/04_Expressions/Debug/main.o new file mode 100644 index 0000000..805d46b Binary files /dev/null and b/04_Expressions/Debug/main.o differ diff --git a/04_Expressions/Debug/makefile b/04_Expressions/Debug/makefile new file mode 100644 index 0000000..3e3eee5 --- /dev/null +++ b/04_Expressions/Debug/makefile @@ -0,0 +1,43 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 04_Expressions + +# Tool invocations +04_Expressions: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "04_Expressions" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 04_Expressions + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/04_Expressions/main.c b/04_Expressions/main.c new file mode 100644 index 0000000..03a892a --- /dev/null +++ b/04_Expressions/main.c @@ -0,0 +1,248 @@ +/* CHAPTER 4 */ + +#include + +void upc(void); + +void ex_01(void); +void ex_02(void); +void ex_09(void); +void ex_10(void); +void ex_11(void); +void ex_12(void); +void ex_13(void); +void ex_14(void); +void ex_15(void); + +void pr_02(void); +void pr_03(void); +void pr_04(void); +void pr_05(void); +void pr_06(void); + +int main(void) { +// upc(); + +// ex_12(); + + pr_06(); + + return 0; +} + +/* Computes a universal product code check digit */ +void upc(void) { + int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, + first_sum, second_sum, total; + + printf("Enter the first (single) digit: "); + scanf("%1d", &d); + printf("Enter first group of five digits: "); + scanf("%1d%1d%1d%1d%1d", &i1, &i2, &i3, &i4, &i5); + printf("Enter second group of five digits: "); + scanf("%1d%1d%1d%1d%1d", &j1, &j2, &j3, &j4, &j5); + + first_sum = d + i2 + i4 + j1 + j3 + j5; + second_sum = i1 + i3 + i5 + j2 + j4; + total = 3 * first_sum + second_sum; + + printf("Check digit: %d\n", 9 - ((total - 1) % 10)); +} + +/* EXERCISES */ +void ex_01(void) { + int i, j, k; + + i = 5; j = 3; + printf("%d %d\n", i / j, i % j); + i = 2; j = 3; + printf("%d\n", (i + 10) % j); + i = 7; j = 8; k = 9; + printf("%d\n", (i + 10) % k / j); + i = 1; j = 2; k = 3; + printf("%d\n", (i + 5) % (j + 2) / k); +} + +void ex_02(void) { + int i = 9, j = 1; + + printf("%d\n", (-i) / j); + printf("%d\n", -(i / j)); +} + +void ex_09(void) { + int i, j, k; + + i = 7; j = 8; + i *= j + 1; + printf("%d %d\n", i, j); + + i = j = k = 1; + i += j += k; + printf("%d %d %d\n", i, j, k); + + i = 1; j = 2; k = 3; + i -= j -= k; + printf("%d %d %d\n", i, j, k); + + i = 2; j = 1; k = 0; + i *= j *= k; + printf("%d %d %d\n", i, j, k); + +} + +void ex_10(void) { + int i, j; + + i = 6; + j = i += i; + printf("%d %d\n", i, j); + + i = 5; + j = (i -= 2) + 1; + printf("%d %d\n", i, j); + + i = 7; + j = 6 + (i = 2.5); + printf("%d %d\n", i, j); + + i = 2; j = 8; + j = (i = 6) + (j = 3); + printf("%d %d\n", i, j); +} + +void ex_11(void) { + int i, j, k; + + i = 1; + printf("%d ", i++ - 1); + printf("%d\n", i); + + i = 10; j = 5; + printf("%d ", i++ - ++j); + printf("%d %d\n", i, j); + + i = 7; j = 8; + printf("%d ", i++ - --j); + printf("%d %d\n", i, j); + + i = 3; j = 4; k = 5; + printf("%d ", i++ - j++ + --k); + printf("%d %d %d\n", i, j, k); + +} + +void ex_12(void) { + int i, j; + + i = 5; + j = ++i * 3 - 2; + printf("%d %d\n", i, j); + + i = 5; + j = 3 - 2 * i++; + printf("%d %d\n", i, j); + + i = 7; + j = 3 * i-- + 2; + printf("%d %d\n", i, j); + + i = 7; + j = 3 + --i * 2; + printf("%d %d\n", i, j); +} + +void ex_13(void) { + // ++i == (i += 1) +} + +void ex_14(void) { +// (a * b) - (c * d) + e +// ((a / b) % c) / d +// (((- a) - b) + c) - (+d) +// ((a * (- b)) / c) - d +} + +void ex_15(void) { +//= 1, 2 +//a 3, 2 +//b 0, 2 +//c 1, 2 +//d 1, 3 +} + +/* PROJECTS */ +void pr_01(void) { + int n; + + printf("Enter two-digit number: "); + scanf("%d", &n); + + printf("The reversal is: %d%d\n", + (n % 10), (n / 10)); +} + +// Reverse +void pr_02(void) { + int n; + + printf("Enter three-digit n: "); + scanf("%d", &n); + + printf("The reversal is: %d%d%d\n", + (n % 10), (n / 10) % 10, n / 100); +} + +// Reverse +void pr_03(void) { + int hundreds, tens, ones; + + printf("Enter three-digit number: "); + scanf("%1d%1d%1d", &hundreds, &tens, &ones); + printf("The reversal is: %d%d%d\n", ones, tens, hundreds); +} + +// Octal +void pr_04(void) { + int n; + + printf("Enter a number between 0 and 32767: "); + scanf("%d", &n); + printf("In octal, your number is: %d%d%d%d%d", + (n / 4096 % 8), (n / 512 % 8), + (n / 64 % 8), (n / 8 % 8), (n % 8)); + +} + +// UPC rewritten +void pr_05(void) { + int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, + first_sum, second_sum, total; + + printf("Enter the first 11 digits of UPC: "); + scanf("%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d", + &d, &i1, &i2, &i3, &i4, &i5, &j1, &j2, &j3, &j4, &j5); + + first_sum = d + i2 + i4 + j1 + j3 + j5; + second_sum = i1 + i3 + i5 + j2 + j4; + total = 3 * first_sum + second_sum; + + printf("Check digit: %d\n", 9 - ((total - 1) % 10)); +} + +// EAN +void pr_06(void) { + int i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, + first_sum, second_sum, total; + + printf("Enter the first 12 digits of EAN: "); + scanf("%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d", + &i1, &i2, &i3, &i4, &i5, &i6, + &i7, &i8, &i9, &i10, &i11, &i12); + + first_sum = i2 + i4 + i6 + i8 + i10 + i12; + second_sum = i1 + i3 + i5 + i7 + i9 + i11; + total = 3 * first_sum + second_sum; + + printf("Check digit: %d\n", 9 - ((total - 1) % 10)); +} diff --git a/05_Selection_Statements/Debug/05_Selection_Statements b/05_Selection_Statements/Debug/05_Selection_Statements new file mode 100644 index 0000000..acc1eb8 Binary files /dev/null and b/05_Selection_Statements/Debug/05_Selection_Statements differ diff --git a/05_Selection_Statements/Debug/main.o b/05_Selection_Statements/Debug/main.o new file mode 100644 index 0000000..58a6b16 Binary files /dev/null and b/05_Selection_Statements/Debug/main.o differ diff --git a/05_Selection_Statements/Debug/makefile b/05_Selection_Statements/Debug/makefile new file mode 100644 index 0000000..3c61224 --- /dev/null +++ b/05_Selection_Statements/Debug/makefile @@ -0,0 +1,43 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 05_Selection_Statements + +# Tool invocations +05_Selection_Statements: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "05_Selection_Statements" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 05_Selection_Statements + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/05_Selection_Statements/main.c b/05_Selection_Statements/main.c new file mode 100644 index 0000000..b6aaad7 --- /dev/null +++ b/05_Selection_Statements/main.c @@ -0,0 +1,619 @@ +/* CHAPTER 5 */ + +#include +#include + +void broker(void); +void date(void); + +void ex_01(void); +void ex_02(void); +void ex_03(void); +void ex_04(void); +void ex_05(void); +void ex_06(void); +void ex_07(void); +void ex_08(void); +void ex_09(void); +void ex_10(void); +void pr_01(void); +void pr_02(void); +void pr_03(void); +void pr_04(void); +void pr_05(void); +void pr_06(void); +void pr_07(void); +void pr_08(void); +void pr_09(void); +void pr_10(void); +void pr_11(void); + +int main(void) { +// broker(); +// date(); + +// ex_08(); + + pr_08(); + + return 0; +} + +// Calculates a broker's commission +void broker(void) { + float commision, value; + printf("Enter value of trade: "); + scanf("%f", &value); + + if (value < 2500.00f) + commision = 30.00f + .017f * value; + else if (value < 6250.00f) + commision = 56.00f + .0066f * value; + else if (value < 20000.00f) + commision = 76.00f + .0034f * value; + else if (value < 50000.00f) + commision = 100.00f + .0022f * value; + else if (value < 500000.00f) + commision = 155.00f + .0011f * value; + else + commision = 255.00f + .0009f * value; + + if (commision < 39.00f) + commision = 39.00f; + + printf("Commission: $%.2f\n", commision); +} + +// Prints date in legal form +void date(void) { + int month, day, year; + + printf("Enter date (dd/mm/yyyy): "); + scanf("%d /%d /%d", &day, &month, &year ); + + printf("Dated this %d", day); + switch (day) { + case 1: case 21: case 31: + printf("st"); break; + case 2: case 22: + printf("nd"); break; + case 3: case 23: + printf("rd"); break; + default: + printf("th"); break; + } + printf(" of "); + + switch (month) { + case 1: printf("January"); break; + case 2: printf("February"); break; + case 3: printf("March"); break; + case 4: printf("April"); break; + case 5: printf("May"); break; + case 6: printf("June"); break; + case 7: printf("July"); break; + case 8: printf("August"); break; + case 9: printf("September"); break; + case 10: printf("October"); break; + case 11: printf("November"); break; + case 12: printf("December"); break; + } + + printf(", %.4d.\n", year); + +} + +/* EXERCISES */ +void ex_01(void) { + int i, j, k; + + i = 2; j = 3; + k = i * j == 6; + printf("%d\n", k); + + i = 5; j = 10; k = 1; + printf("%d\n", k > j < j); + + i = 3; j = 2; k = 1; + printf("%d\n", i < j == j < k); + + i = 3; j = 2; k = 1; + printf("%d\n", i % j + i < k); +} + +void ex_02(void) { + int i, j, k; + + i = 10; j = 5; + printf("%d\n", !i < j); + + i = 2; j = 1; + printf("%d\n", !!i + !j); + + i = 5; j = 0; k = -5; + printf("%d\n", i && j || k); + + i = 1; j = 2; k = 3; + printf("%d\n", i < j || k); +} + +void ex_03(void) { + int i, j, k; + + i = 3; j = 4; k = 5; + printf("%d, ", i < j || ++j < k); + printf("%d %d %d\n", i, j, k); + + i = 7; j = 8; k = 9; + printf("%d, ", i - 7 && j++ < k); + printf("%d %d %d\n", i, j, k); + + i = 7; j = 8; k = 9; + printf("%d, ", (i = j) || (j = k)); + printf("%d %d %d\n", i, j, k); + + i = 1; j = 1; k = 1; + printf("%d, ", ++i || ++j && ++k); + printf("%d %d %d\n", i, j, k); + + +} + +// Short -1, 0, 1 return +void ex_04(void) { + int i = 5, j = 5; + printf("%d", (i > j) - (i < j)); +} + +void ex_05(void) { + int n = -5; + if (n >= 1 <= 10) + printf("n is between 1 and 10\n"); +} + +void ex_06(void) { + int n = -9; + if (n == 1-10) + printf("n is between 1 and 10\n"); +} + +void ex_07(void) { + int i = -17; + printf("%d\n", i >= 0 ? i : -i); +} + +void ex_08(void) { + int age = 22; + bool teenager = (age >= 13 && age <= 19); + printf("Folk of age %d is teenager: %d", age, teenager); +} + +void ex_09(void) { + // they seems both equivalent to me +} + +void ex_10(void) { + int i = 1; + switch (i % 3) { + case 0: printf("zero"); + case 1: printf("one"); + case 2: printf("two"); + } +} + +void ex_11(void) { + int area_code = 404; + + switch (area_code) { + case 229: + printf("Albany"); + break; + case 404: case 470: case 678: case 770: + printf("Atlanta"); + break; + case 478: + printf("Macon"); + break; + case 706: case 762: + printf("Columbus"); + break; + case 912: + printf("Savannah"); + break; + default: + printf("Area code not recognized"); + } +} + +/* PROJECTS */ +void pr_01(void) { + int n, digits = 0; + + printf("Enter a number: "); + scanf("%d", &n); + printf("The number %d has ", n); + + if (n > 0) + digits++; + if (n > 9) + digits++; + if (n > 99) + digits++; + if (n > 999) + digits++; + + printf("%d digits.", digits); +} + +// Convert 24h date to 12h +void pr_02(void) { + int hh, mm; + bool flag; + + printf("Enter a 24-hour time: "); + scanf("%2d:%2d", &hh, &mm); + + flag = hh / 12; + hh %= 12; + + printf("Equivalent 12-hour time: %.2d:%.2d ", hh, mm); + + if (flag) + printf("PM"); + else + printf("AM"); +} + +// Broker modified +void pr_03(void) { + float commision, pricePerShare, value; + int shares; + + printf("Enter number shares: "); + scanf("%d", &shares); + printf("Enter price per share: "); + scanf("%f", &pricePerShare); + + value = (float)shares * pricePerShare; + + if (value < 2500.00f) + commision = 30.00f + .017f * value; + else if (value < 6250.00f) + commision = 56.00f + .0066f * value; + else if (value < 20000.00f) + commision = 76.00f + .0034f * value; + else if (value < 50000.00f) + commision = 100.00f + .0022f * value; + else if (value < 500000.00f) + commision = 155.00f + .0011f * value; + else + commision = 255.00f + .0009f * value; + + if (commision < 39.00f) + commision = 39.00f; + + printf("\nCommission of broker #1: $%.2f\n", commision); + + + if (shares < 2000) + commision = 33.00f + .03f * shares; + else + commision = 33.00f + .02f * shares; + + printf("Commission of broker #2: $%.2f\n", commision); +} + +// Beaufort scale +void pr_04(void) { + int speed; + + printf("Enter wind speed in knots: "); + scanf("%d", &speed); + + if (speed < 1) + printf("Calm\n"); + else if (speed <= 3) + printf("Light air\n"); + else if (speed <= 27) + printf("Breeze\n"); + else if (speed <= 47) + printf("Gale\n"); + else if (speed <= 63) + printf("Storm\n"); + else + printf("Hurricane\n"); +} + +// Tax +void pr_05(void) { + float income, tax; + + printf("Enter income: "); + scanf("%f", &income); + + if (income <= 750.0f) + tax = income * .01f; + else if (income <= 2250.0f) + tax = income * .02f + 7.50f; + else if (income <= 3750.0f) + tax = income * .03f + 37.50f; + else if (income <= 5250.0f) + tax = income * .04f + 82.50f; + else if (income <= 7000.0f) + tax = income * .05f + 142.50f; + else + tax = income * .06f + 230.00f; + + printf("Tax due is: %.2f", tax); +} + +// upc modified +void pr_06(void) { + int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, + first_sum, second_sum, total, check_digit; + + printf("Enter the first (single) digit: "); + scanf("%1d", &d); + printf("Enter first group of five digits: "); + scanf("%1d%1d%1d%1d%1d", &i1, &i2, &i3, &i4, &i5); + printf("Enter second group of five digits: "); + scanf("%1d%1d%1d%1d%1d", &j1, &j2, &j3, &j4, &j5); + printf("Enter the last (single) digit: "); + scanf("%1d", &check_digit); + + first_sum = d + i2 + i4 + j1 + j3 + j5; + second_sum = i1 + i3 + i5 + j2 + j4; + total = 3 * first_sum + second_sum; + + if (check_digit == (9 - ((total - 1) % 10))) + printf("VALID\n"); + else + printf("NOT VALID\n"); +} + +// Smallest and largest out of 4 numbers +void pr_07(void) { + int i1, i2, i3, i4, smal1, smal2, larg1, larg2; + + printf("Enter four integers: "); + scanf("%d %d %d %d", &i1, &i2, &i3, &i4); + + if (i1 < i2) { + smal1 = i1; + larg1 = i2; + } + else { + smal1 = i2; + larg1 = i1; + } + + if (i3 < i4) { + smal2 = i3; + larg2 = i4; + } + else { + smal2 = i4; + larg2 = i3; + } + + printf("Smallest: %d\n", (smal1 < smal2) ? smal1 : smal2); + printf("Largest: %d\n", (larg1 > larg2) ? larg1 : larg2); + +} + +// Flight departures +void pr_08(void) { + int hh, mm, entered, closestToken = 0, + closestDistance, distance; + + printf("Enter a 24-hour time: "); + scanf("%2d:%2d", &hh, &mm); + + entered = hh * 60 + mm; + + distance = 480 - entered; + distance = distance >= 0 ? distance : -distance; + closestDistance = distance; + closestToken = 480; + + distance = 583 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 583; + } + + distance = 679 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 679; + } + + distance = 767- entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 767; + } + + distance = 840 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 840; + } + + distance = 945 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 945; + } + + distance = 1140 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 1140; + } + + distance = 1305 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 1305; + } + + switch (closestToken) { + case 480: + printf("Closest departure time is %2d:%.2d a.m., arriving at %2d:%.2d a.m.", + 8, 0, 10, 16); break; + case 583: + printf("Closest departure time is %2d:%.2d a.m., arriving at %2d:%.2d a.m.", + 9, 43, 11, 52); break; + case 679: + printf("Closest departure time is %2d:%.2d a.m., arriving at %2d:%.2d p.m.", + 11, 19, 1, 31); break; + case 767: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 12, 47, 3, 0); break; + case 840: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 2, 0, 4, 8); break; + case 945: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 3, 45, 5, 55); break; + case 1140: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 7, 0, 9, 20); break; + case 1305: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 9, 45, 11, 58); break; + } + +} + +// Which date is sooner +void pr_09(void) { + int d1, d2, m1, m2, y1, y2, daysFromBeginning1, daysFromBeginning2; + + printf("Enter first date: "); + scanf("%d/%d/%d", &d1, &m1, &y1); + printf("Enter second date: "); + scanf("%d/%d/%d", &d2, &m2, &y2); + + daysFromBeginning1 = d1 + 30 * m1 + 365 * y1; + daysFromBeginning2 = d2 + 30 * m2 + 365 * y2; + + if (daysFromBeginning1 < daysFromBeginning2) + printf("%d/%d/%d is earlier than %d/%d/%d", d1, m1, y1, d2, m2, y2); + else + printf("%d/%d/%d is earlier than %d/%d/%d", d2, m2, y2, d1, m1, y1); +} + +// Grades +void pr_10(void) { + int grade; + + printf("Enter numerical grade: "); + scanf("%d", &grade); + + if (grade < 0 || grade > 100) + printf("Illegal grade!\n"); + + printf("Letter grade: "); + switch (grade / 10) { + case 9: + printf("A"); + break; + case 8: + printf("B"); + break; + case 7: + printf("C"); + break; + case 6: + printf("D"); + break; + case 5: + printf("E"); + break; + default: + printf("FX"); + break; + } +} + +void pr_11(void) { + int tens, ones; + + printf("Enter a two-digit number: "); + scanf("%1d%1d", &tens, &ones); + + printf("You entered the number "); + if (tens == 1) { + switch(ones) { + case 1: + printf("eleven"); break; + case 2: + printf("twelve"); break; + case 3: + printf("thirteen"); break; + case 4: + printf("fourteen"); break; + case 5: + printf("fifteen"); break; + case 6: + printf("sixteen"); break; + case 7: + printf("seventeen"); break; + case 8: + printf("eighteen"); break; + case 9: + printf("nineteen"); break; + } + } + else { + switch(tens) { + case 2: + printf("twenty"); break; + case 3: + printf("thirty"); break; + case 4: + printf("forty"); break; + case 5: + printf("fifty"); break; + case 6: + printf("seventy"); break; + case 7: + printf("seventy"); break; + case 8: + printf("eighty"); break; + case 9: + printf("ninety"); break; + } + printf("-"); + switch(ones) { + case 1: + printf("one"); break; + case 2: + printf("two"); break; + case 3: + printf("three"); break; + case 4: + printf("four"); break; + case 5: + printf("five"); break; + case 6: + printf("six"); break; + case 7: + printf("seven"); break; + case 8: + printf("eight"); break; + case 9: + printf("nine"); break; + } + } + printf("."); +} diff --git a/06_Loops/Debug/06_Loops b/06_Loops/Debug/06_Loops new file mode 100644 index 0000000..5085c4e Binary files /dev/null and b/06_Loops/Debug/06_Loops differ diff --git a/06_Loops/Debug/main.o b/06_Loops/Debug/main.o new file mode 100644 index 0000000..212a807 Binary files /dev/null and b/06_Loops/Debug/main.o differ diff --git a/06_Loops/Debug/makefile b/06_Loops/Debug/makefile new file mode 100644 index 0000000..28f039b --- /dev/null +++ b/06_Loops/Debug/makefile @@ -0,0 +1,43 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 06_Loops + +# Tool invocations +06_Loops: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "06_Loops" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 06_Loops + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/06_Loops/main.c b/06_Loops/main.c new file mode 100644 index 0000000..bec38ce --- /dev/null +++ b/06_Loops/main.c @@ -0,0 +1,523 @@ +/* CHAPTER 6 */ + +#include +#include + +int gcd(int, int); + +void sqaure(void); +void square2(void); +void sqaure3(void); +void sum(void); +void checking(void); +void ex_01(void); +void ex_02(void); +void ex_03(void); +void ex_04(void); +void ex_05(void); +void ex_06(void); +void ex_07(void); +void ex_08(void); +void ex_09(void); +void ex_10(void); +void ex_11(void); +void ex_12(void); +void ex_13(void); +void ex_14(void); +void pr_01(void); +void pr_02(void); +void pr_03(void); +void pr_04(void); +void pr_05(void); +void pr_06(void); +void pr_06(void); +void pr_07(void); +void pr_08(void); +void pr_09(void); +void pr_10(void); +void pr_11(void); +void pr_12(void); + +int main(void) { +// sqaure3(); + +// sum(); + +// checking(); + +// ex_14(); + + pr_11(); + + return 0; +} + +// ################################## // + +// GCD, Euclid algorithm +int gcd(int n, int d) { + int remainder; + + while (d != 0) { + remainder = n % d; + n = d; + d = remainder; + } + + return n; +} + +// ################################## // + + +void sqaure(void) { + int i, n; + + printf("This program prints a table of squares.\n"); + printf("Enter number of entries in table: "); + scanf("%d", &n); + + i = 1; + while (i <= n) { + printf("%10d%10d\n", i, i * i); + i++; + } +} + +void sum(void) { + int n, sum = 0; + + printf("This program prints a series of integers.\n"); + printf("Enter integers (0 to terminate): "); + scanf("%d", &n); + + while (n != 0) { + sum += n; + scanf("%d", &n); + } + + printf("The sum is: %d\n", sum); +} + +// Calculates the numbers of digits in an integer +void numdigits(void) { + int digits = 0, n; + + printf("Enter a nonnegative integer: "); + scanf("%d", &n); + + do { + n /= 10; + digits++; + } while (n > 0); + + +} + +// Squares using for +void square2(void) { + int i, n; + + printf("This program prints a table of squares.\n"); + printf("Enter number of entries in table: "); + scanf("%d", &n); + + for (i = 1; i <= n; i++) { + printf("%10d%10d\n", i, i * i); + } +} + +// Squares using odd method +void sqaure3(void) { + int i, n, odd, square; + + printf("This program prints a table of squares.\n"); + printf("Enter number of entries in table: "); + scanf("%d", &n); + + i = 1; + odd = 3; + for (square = 1; i <= n; odd += 2) { + printf("%10d%10d\n", i, square); + ++i; + square += odd; + } +} + +// Balances a checkbook +void checking(void) { + int cmd; + float balance = 0.0f, credit, debit; + + printf("*** ACME checkbook-balancing program ***\n"); + printf("Commands: 0=clear, 1=credit, 2=debit "); + printf("3=balance, 4=exit\n\n"); + + for(;;) { + printf("Enter command: "); + scanf("%d", &cmd); + switch (cmd) { + case 0: + balance = 0.0f; + break; + case 1: + printf("Enter amount of credit: "); + scanf("%f", &credit); + balance += credit; + break; + case 2: + printf("Enter amount of debit: "); + scanf("%f", &debit); + balance -= debit; + break; + case 3: + printf("Current balance: $%.f\n", balance); + break; + case 4: + return; + default: + printf("Commands: 0=clear, 1=credit, 2=debit "); + printf("3=balance, 4=exit\n\n"); + break; + } + } +} + +// EXERCISES +void ex_01(void) { + int i = 1; + while (i <= 128) { + printf("%d ", i); + i *= 2; + } + printf("\n\n\n"); +} + +void ex_02(void) { + int i = 9384; + do { + printf("%d ", i); + i /= 10; + } while (i > 0); + printf("\n\n\n"); +} + +void ex_03(void) { + int i, j; + for (i = 5, j = i - 1; i > 0, j > 0; --i, j = i - 1) + printf("%d ", i); + printf("\n\n\n"); +} + +void ex_04(void) { + + int i; + + for (i = 0; i < 10; i++) + printf("%d ", i); + printf("\n"); + + for (i = 0; i < 10; ++i) + printf("%d ", i); + printf("\n"); + + for (i = 0; i++ < 10;) // THIS IS DIFFERENT + printf("%d ", i); + printf("\n"); + + printf("\n\n\n"); +} + +void ex_05(void) { + // THIRD is not EQ +} + +void ex_06(void) { + int i; + + for (i = 1; i <= 128; i *= 2) + printf("%d ", i); + + printf("\n\n\n"); +} + +void ex_07(void) { + int i; + + for (i = 9384; i > 0; i /= 10) + printf("%d ", i); + + printf("\n\n\n"); +} + +void ex_08(void) { + int i; + + for (i = 10; i >= 1; i /= 2) + printf("%d ", i++); +} + +void ex_09(void) { + int i = 10; + + while (i >= 1) { + printf("%d ", i++); + i /= 2; + } +} + +void ex_10(void) { + while (1) { +// … + continue; +// … + } + +// The equivalent code using goto would have the following appearance: + + while (1) { +// … + goto loop_end; +// … + loop_end: ; /* null statement */ + } +} + +void ex_11(void) { + int i, sum = 0; + + for (i = 0; i < 10; i++) { + if (i % 2) + continue; + sum += i; + } + printf("%d\n", sum); +} + +void ex_12(void) { + int n, d; + + printf("Enter number: "); + scanf("%d", &n); + +// for (d = 2; d < n; d++) + for (d = 2; d * d <= n; d++) + if (n % d == 0) + break; + + if (d < n) + printf("%d is divisible by %d.", n, d); + else + printf("%d is prime.", n); + +} + +void ex_13(void) { +// for (n = 0; m > 0; m /= 2, n++); +} + +void ex_14(void) { + int n = 24; + if (n % 2 == 0)//; no semicolon here + printf("%d is even\n", n); +} + +// PROJECTS +// Largest number in series +void pr_01(void) { + float n, max = 0; + + do { + printf("Enter a number: "); + scanf("%f", &n); + + if (n > max) + max = n; + } while (n > 0); + + printf("\nThe largest number was: %.2f", max); +} + +// GCD, Euclid algorithm +void pr_02(void) { + int m, n, remainder; + + printf("Enter two integers: "); + scanf("%d%d", &m, &n); + + while (n != 0) { + remainder = m % n; + m = n; + n = remainder; + } + + printf("Greatest common divisor: %d\n", m); +} + +// Reduce a fraction to lowest terms +void pr_03(void) { + int n, d, GCD; + + printf("Enter a fraction: "); + scanf("%d / %d", &n, &d); + + GCD = gcd(n, d); + n /= GCD; + d /= GCD; + + printf("In lowest terms: %d/%d\n", n, d); +} + +// Broker modified +void pr_04(void) { + float commision, value; + + while (1) { + printf("Enter value of trade: "); + scanf("%f", &value); + + if (value <= 0) + break; + + if (value < 2500.00f) + commision = 30.00f + .017f * value; + else if (value < 6250.00f) + commision = 56.00f + .0066f * value; + else if (value < 20000.00f) + commision = 76.00f + .0034f * value; + else if (value < 50000.00f) + commision = 100.00f + .0022f * value; + else if (value < 500000.00f) + commision = 155.00f + .0011f * value; + else + commision = 255.00f + .0009f * value; + + if (commision < 39.00f) + commision = 39.00f; + + printf("Commission: $%.2f\n\n", commision); + } +} + +void pr_05(void) { + int n; + + printf("Enter number: "); + scanf("%d", &n); + printf("The reversal is: "); + + do { + printf("%d", n % 10); + n /= 10; + } while (n > 0); +} + +void pr_06(void) { + int n, i; + + printf("Enter number: "); + scanf("%d", &n); + + for (i = 2; i * i <= n; i += 2) + printf("%d\n", i * i); +} + +void pr_07(void) { + int i, n, odd = 3, square = 1; + + printf("This program prints a table of squares.\n"); + printf("Enter number of entries in table: "); + scanf("%d", &n); + + for (i = 1 ; i <= n ; ++i) { + printf ("%10d%10d\n", i, square) ; + square += odd; + odd += 2; + } +} + +void pr_08(void) { + int i, n, start_day; + + printf("Enter number of days in month: "); + scanf("%d", &n); + printf("Enter starting day of the week (1=Sun, 7=Sat): "); + scanf("%d", &start_day); + +// print any leading "blank dates" + for (i = 1; i < start_day; i++) + printf(" "); + +// now print the calendar + for (i = 1; i <= n; i++) { + printf("%3d", i); + if ((start_day + i - 1) % 7 == 0) + printf("\n"); + } +} + +void pr_09(void) { + float balance, interest, payment; + int n, i; + + printf("Enter amount of loan: "); + scanf("%f", &balance); + printf("Enter interest: "); + scanf("%f", &interest); + printf("Enter payment: "); + scanf("%f", &payment); + printf("Enter number of payments: "); + scanf("%d", &n); + +// monthly = interest / 100 / 12; + float monthly = interest / 1200; + + for (i = 1; i <= n; i++) { + balance -= payment; + balance += (balance * monthly); + printf("\nBalance remaining after %33d. payment: $%.2f", i, balance); + } +} + +void pr_10(void) { + int d1, m1, y1, d, m, y, daysFromBeginning1 = -1, tempDays; + + while (1) { + printf("Enter a date (dd/mm/yy): "); + scanf("%d/%d/%d", &d, &m, &y); + + if (d == 0 && m == 0 && y == 0) + break; + + tempDays = d + 30 * m + 365 * y; + + if (daysFromBeginning1 > tempDays || daysFromBeginning1 == -1) { + daysFromBeginning1 = tempDays; + d1 = d; + m1 = m; + y1 = y; + } + } + + printf("\n%d/%d/%d is earliest date.", d1, m1, y1); +} + +void pr_11(void) { + int n, i, j, fact; + float e = 1.0f; + + printf("Enter n: "); + scanf("%d", &n); + + for (i = 1; i <= n; i++) { + for (j = 1, fact = 1; j <= i; j++) + fact *= j; + e += 1 / (float)fact; + } + + printf("The e after %d aproximations is %f.", n, e); +} + +void pr_12(void) { +// ??? +} diff --git a/07_Basic_Types/Debug/makefile b/07_Basic_Types/Debug/makefile new file mode 100644 index 0000000..9b215aa --- /dev/null +++ b/07_Basic_Types/Debug/makefile @@ -0,0 +1,43 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 07_Basic_Types + +# Tool invocations +07_Basic_Types: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "07_Basic_Types" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 07_Basic_Types + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/07_Basic_Types/main.c b/07_Basic_Types/main.c new file mode 100644 index 0000000..8aa874f --- /dev/null +++ b/07_Basic_Types/main.c @@ -0,0 +1,637 @@ +/* CHAPTER 7 */ + +#include +#include +#include + +void sum2(void); +void lenght(void); +void sum2(void); +void ex_01(void); +void ex_02(void); +void ex_03(void); +void ex_04(void); +void ex_05(void); +void ex_06(void); +void ex_07(void); +void ex_08(void); +void ex_09(void); +void ex_10(void); +void ex_11(void); +void ex_12(void); +void ex_13(void); +void ex_14(void); +void ex_15(void); +void pr_01(void); +void pr_02(void); +void pr_03(void); +void pr_04(void); +void pr_05(void); +void pr_06(void); +void pr_07(void); +void pr_08(void); +void pr_09(void); +void pr_10(void); +void pr_11(void); +void pr_12(void); +void pr_13(void); +void pr_14(void); +void pr_15(void); + + +int main(void) { +// lenght(); + + pr_15(); + + return 0; +} + + +// Sums series of numbers (using long variables) +void sum2(void) { + long n, sum = 0; + + printf("This program prints a series of integers.\n"); + printf("Enter integers (0 to terminate): "); + scanf("%ld", &n); + + while (n != 0) { + sum += n; + scanf("%ld", &n); + } + + printf("The sum is: %ld\n", sum); +} + +// Number of characters +void lenght(void) { + char ch; + int len = 0; + + printf("Enter a message: "); + ch = getchar(); + while (ch != '\n') { + len++; + ch = getchar(); + } + + printf("Your message was %d characters(s) long.\n", len); +} + +// Number of characters easier version +void lenght2(void) { + int len = 0; + + printf("Enter a message: "); + while (getchar() != '\n') + len++; + + printf("Your message was %d characters(s) long.\n", len); +} + +// EXERCISES // +void ex_01(void) { + int i; + + i = 077; + printf("%d\n", i); + + i = 0x77; + printf("%d\n", i); + + i = 0XABC; + printf("%d\n", i); + +} + +void ex_02(void) { + float a = 010E2; + float b = 32.1E+5; +// int c = 0790; +// int d = 100_000; + float e = 3.97e-2; +} + +void ex_03(void) { + short unsigned int sui; +// short float sf; + long double ld; + unsigned long ul; +} + +void ex_04(void) { + char c; + int i; + + i += c; + c = c * 2 - 1; + putchar(c); +// printf(c); +} + +void ex_05(void) { + int i; + + i = 'A': + printf("%d\n", i); + + i = 0b1000001; + printf("%d\n", i); + + i = 0101; + printf("%d\n", i); + + i = 0b1000001; + printf("%d\n", i); +} + +void ex_06(void) { + char a = 31; + short b = 365; + short c = 1440; + int d = 86400; +} + +void ex_07(void) { +// \b = \10 +// \t = \11 +// \n = \12 +// \r = \15 +} + +void ex_08(void) { + +// \b = \x08 +// \t = \x09 +// \n = \x0a +// \r = \x0d +} + +void ex_09(void) { + + +// i / j + 'a': // will be int +} + +void ex_10(void) { + // unsigned int, because the (int) cast applies only to j, not j * k. +} + +void ex_11(void) { + // int * float / double will be double +} + +void ex_12(void) { + // The value of i is converted to float and added to f, + // then the result is converted to double and stored in d. +} + +void ex_13(void) { + char c = '\1': + short s = 2; + int i = -3; + long l = 5; + float f = 6.5f; + double d = 7.5f; + +// c * i = int; +// s + l = long; +// f / c = float; +// d / s = double; +// f - d = float; +// int (f) = int; +} + +void ex_14(void) { +// Converting f to int will fail +// if the value stored in f exceeds the largest value of type int. + float f, frac = f - (int)f; +} + +void ex_15(void) { + // DUNNO how to determine it, use instead +} + + +// PROJECTS // + +// square2 modified +void pr_01(void) { + int i, n, offset = 1; + short s; + long l; + + printf("This program prints a table of squares.\n"); + printf("Enter number of entries in table: "); + scanf("%d", &n); + + printf(" n s i l\n"); + printf("--------------------------------------------------\n"); + for (s = offset, i = offset, l = offset; i <= n + offset; s++, i++, l++) + printf("%11d%7hd%12d%20ld\n", i, s * s, i * i, l * l); + + // short will end at 181, giving 32761 + // int will end at 46340, giving 2147395600 + // long will end at JAVA HEAP ERROR... + +} + +// square2 modified +void pr_02(void) { + int i, n; + short s; + long l; + + printf("This program prints a table of squares.\n"); + printf("Enter number of entries in table: "); + scanf("%d", &n); + + printf(" n s i l\n"); + printf("--------------------------------------------------\n"); + for (s = 0, i = 0, l = 0; + i <= n; + s++, i++, l++) { + printf("%11d%7hd%12d%20ld\n", i, s * s, i * i, l * l); + if ((i % 24) == 0) + getchar(); + } + +} + +// sum2 modified +void pr_03(void) { + double n, sum = 0; + + printf("This program prints a series of fractions (in decimal).\n"); + printf("Enter numbers (0 to terminate): "); + scanf("%lf", &n); + + while (n != 0) { + sum += n; + scanf("%lf", &n); + } + + printf("The sum is: %lf\n", sum); +} + +// Telephone number from letters +void pr_04(void) { + char ch; + + printf("Enter phone number: "); + ch = getchar(); + while (ch != '\n') { + switch (ch) { + case 'A': case 'B': case 'C': + printf("%d", 2); break; + case 'D': case 'E': case 'F': + printf("%d", 3); break; + case 'G': case 'H': case 'I': + printf("%d", 4); break; + case 'J': case 'K': case 'L': + printf("%d", 5); break; + case 'M': case 'N': case 'O': + printf("%d", 6); break; + case 'P': case 'Q': case 'R': case 'S': + printf("%d", 7); break; + case 'T': case 'U': case 'V': + printf("%d", 8); break; + case 'W': case 'X': case 'Y': case 'Z': + printf("%d", 9); break; + default: + printf("%c", ch); break; + } + ch = getchar(); + } +} + +// Scrabble +void pr_05(void) { + int sum = 0; + char ch; + + printf("Enter a word: "); + + while ((ch = getchar()) != '\n') + switch (toupper(ch)) { + case 'D': case 'G': + sum += 2; break; + case 'B': case 'C': case 'M': case 'P': + sum += 3; break; + case 'F': case 'H': case 'V': case 'W': case 'Y': + sum += 4; break; + case 'K': + sum += 5; break; + case 'J': case 'X': + sum += 8; break; + case 'Q': case 'Z': + sum += 10; break; + default: + sum++; break; + } + + printf("Scrabble value: %d\n", sum); +} + +// size of all types +void pr_06(void) { + printf("Size of int: %zu\n", sizeof(int)); + printf("Size of short: %zu\n", sizeof(short)); + printf("Size of long: %zu\n", sizeof(long)); + printf("Size of float: %zu\n", sizeof(float)); + printf("Size of double: %zu\n", sizeof(double)); + printf("Size of long double: %zu\n", sizeof(long double)); +} + +// Fraction computation +void pr_07(void) { + int num1, denom1, num2, denom2, result_num, result_denom; + char operator; + + printf("Enter two fractions separated by a operator: "); + scanf("%d / %d %1c %d / %d", &num1, &denom1, &operator, &num2, &denom2); + + switch (operator) { + case '+': + result_num = num1 * denom2 + num2 * denom1; + result_denom = denom1 * denom2; + break; + case '-': + result_num = num1 * denom2 - num2 * denom1; + result_denom = denom1 * denom2; + break; + case '*': + result_num = num1 * num2; + result_denom = denom1 * denom2; + break; + case '/': + result_num = num1 * denom2; + result_denom = num2 * denom1; + break; + } + + printf("The result is %d/%d\n", result_num, result_denom); +} + +// Flight departments modified +void pr_08(void) { + int hh, mm, entered, closestToken = 0, + closestDistance, distance; + char s1; + + printf("Enter a 12-hour time: "); + scanf("%2d:%2d %1c", &hh, &mm, &s1); + + if (toupper(s1) == 'P') { + hh += 12; + } + + + entered = hh * 60 + mm; + + distance = 480 - entered; + distance = distance >= 0 ? distance : -distance; + closestDistance = distance; + closestToken = 480; + + distance = 583 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 583; + } + + distance = 679 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 679; + } + + distance = 767- entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 767; + } + + distance = 840 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 840; + } + + distance = 945 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 945; + } + + distance = 1140 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 1140; + } + + distance = 1305 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 1305; + } + + switch (closestToken) { + case 480: + printf("Closest departure time is %2d:%.2d a.m., arriving at %2d:%.2d a.m.", + 8, 0, 10, 16); break; + case 583: + printf("Closest departure time is %2d:%.2d a.m., arriving at %2d:%.2d a.m.", + 9, 43, 11, 52); break; + case 679: + printf("Closest departure time is %2d:%.2d a.m., arriving at %2d:%.2d p.m.", + 11, 19, 1, 31); break; + case 767: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 12, 47, 3, 0); break; + case 840: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 2, 0, 4, 8); break; + case 945: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 3, 45, 5, 55); break; + case 1140: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 7, 0, 9, 20); break; + case 1305: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 9, 45, 11, 58); break; + } +} + +void pr_09(void) { + int hh, mm; + char s1; + + printf("Enter a 12-hour time: "); + scanf("%2d:%2d %1c", &hh, &mm, &s1); + + if (toupper(s1) == 'P') { + hh += 12; + } + + printf("Equivalent 24-hour time: %d:%.2d", hh, mm); +} + +void pr_10(void) { + int vowels = 0; + char ch; + + printf("Enter a sentence: "); + ch = getchar(); + while (ch != '\n') { + if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') + vowels++; + ch = getchar(); + } + printf("Your sentence contains 6 vowels."); +} + +void pr_11(void) { + char first, temp; + + printf("Enter a first and last name: "); +// find first nonblank character + while ((first = getchar()) == ' ') + ; +// skip spaces + while (getchar() != ' ') + ; +// find first nonblank character + while ((temp = getchar()) == ' ') + ; + + while (temp != ' ' && temp != '\n') { + putchar(temp); + temp = getchar(); + } + printf(", %c.", first); +} + +void pr_12(void) { + int i = 1; + float result, frac = 1.0f; + char ch, lastOperand = '+'; + + printf("Enter an expression: "); + while ((ch = getchar()) != '\n') { + switch (ch) { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + switch (lastOperand) { + case '+': + result += (ch - '0') * (frac / i); + break; + case '-': + result -= (ch - '0') * (frac / i); + break; + case '*': + result *= (ch - '0') * (frac / i); + break; + case '/': + result /= (ch - '0') * (frac / i); + break; + } + i = 10; + break; + case '+': case '-': case '/': case '*': + lastOperand = ch; + frac = 1.0f; + i = 1; + break; + case '.': + frac = 0.1f; + i = 1; + break; + } + + } + printf("Value of expression: %g", result); +} + +void pr_13(void) { + char ch; + int words = 1; + float len = 0; + + printf("Enter a sentence: "); + ch = getchar(); + while (ch != '\n') { + if (ch == ' ') + words++; + else + len++; + ch = getchar(); + } + + printf("Avrage word lenght: %.1f", len / words); +} + +void pr_14(void) { +// y is initial guess + double root, x, y = 1; + + printf("Enter a positive number: "); + scanf("%lf", &x); + + do { +// also the new value of y + root = (y + (x / y)) / 2; + } while ((fabs(y - root) >= root * 0.00001) && (y = root)); + + printf("Square root: %g", root); +} + + +// Testing what maximum factorial can be storen in what type +void pr_15(void) { + int i = 1, n, c; + short s = 1; + long l = 1L; + long long ll = 1LL; + float f = 1.0f; + double d = 1; + long double ld = 1.0L; + + printf("This program prints a table of factorials.\n"); + printf("Enter number of entries in table: "); + scanf("%d", &n); + + printf(" n s i l ll\n"); + printf("-------------------------------------------------------------------------------------------\n"); + for (c = 1; c <= n; c++) { + printf("%5d", c); + s *= (short)c; + i *= (int)c; + l *= (long)c; + ll *= (long long)c; + f *= (float)c; + d *= (double)c; + ld *= (long double)c; +// printf("%8hd%14d%24ld%24lld%15f\n", s, i, l, ll, f); + printf("%50f%30g\n", f, d); + printf("%30Lg\n", ld); + } + + // short will end at 7, giving 5040 + // int will end at 12, giving 479001600 + // long will end at 20, giving 2432902008176640000 + // long long end at 20, giving 2432902008176640000 + // float will end at 34, giving 295232822996533287161359432338880069632 + // double will end at 170, giving 7.25742e+306 (f*cking long number) + // long double end at 1754, giving 1.97926e+4930 ( !? ) + +} diff --git a/08_Arrays/Debug/makefile b/08_Arrays/Debug/makefile new file mode 100644 index 0000000..cfcc60a --- /dev/null +++ b/08_Arrays/Debug/makefile @@ -0,0 +1,43 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 08_Arrays + +# Tool invocations +08_Arrays: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "08_Arrays" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 08_Arrays + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/08_Arrays/main.c b/08_Arrays/main.c new file mode 100644 index 0000000..519f83b --- /dev/null +++ b/08_Arrays/main.c @@ -0,0 +1,834 @@ +#include +#include +#include +#include +#include + +#define N 10 + +#define NUM_RATES ((int) (sizeof(value) / sizeof(value[0]))) +#define INITIAL_BALANCE 100.00 + +#define NUM_SUITS 4 +#define NUM_RANKS 13 + +#define SIZE ((int) (sizeof(a) / sizeof(a[0]))) + +#define FIBONACCI_LENGHT 40 + +#define MAX_LENGHT 255 + +#define NUM_QUIZZES 5 +#define NUM_STUDENTS 5 + +#define MAP_WIDTH 10 +#define MAP_HEIGHT 10 + +void reverse(void); +void repdigit(void); +void deal(void); +void interest(void); +void reverse2(void); +void ex_01(void); +void ex_02(void); +void ex_03(void); +void ex_04(void); +void ex_05(void); +void ex_06(void); +void ex_07(void); +void ex_08(void); +void ex_09(void); +void ex_10(void); +void ex_11(void); +void pr_01(void); +void pr_02(void); +void pr_03(void); +void pr_04(void); +void pr_05(void); +void pr_06(void); +void pr_07(void); +void pr_08(void); +void pr_09(void); +void pr_10(void); +void pr_11(void); +void pr_12(void); +void pr_13(void); +void pr_14(void); +void pr_15(void); +void pr_16(void); +void pr_17(void); + +int main(void) { +// interest(); + +// ex_11(); + + pr_17(); + + + return (0); +} + + +// Reverses a series of number +void reverse(void) { + int a[N], i; + + printf("Enter %d numbers: ", N); + for (i = 0; i < SIZE; i++) + scanf("%d", &a[i]); + + printf("In reverse order: "); + for (i = SIZE - 1; i >= 0; i--) + printf(" %d", a[i]); + printf("\n"); +} + +void interest(void) { + int i, low_rate, num_years, year; + double value[5]; + + printf("Enter interest rate: "); + scanf("%d", &low_rate); + printf("Enter number of years: "); + scanf("%d", &num_years); + + printf("\nYears: "); + for (i = 0; i < NUM_RATES; i++) { + printf("%6d%%", low_rate + i); + value[i] = INITIAL_BALANCE; + } + printf("\n"); + + for (year = 1; year <= num_years; year++) { + printf("%3d ", year); + for (i = 0; i < NUM_RATES; i++) { + value[i] += (low_rate + i) / 100.0 * value[i]; + printf("%7.2f", value[i]); + } + printf("\n"); + } +} + +void repdigit(void) { + bool digit_seen[10] = {false}; + int digit; + long n; + + printf("Enter number: "); + scanf("%ld", &n); + + while (n > 0) { + digit = n % 10; + if (digit_seen[digit]) + break; + digit_seen[digit] = true; + n /= 10; + } + + if (n > 0) + printf("Repeated digit\n"); + else + printf("No repeated digit\n"); +} + +void deal(void) { + bool in_hand[NUM_SUITS][NUM_RANKS] = {false}; + int num_cards, rank, suit; + const char rank_code[] = {'2', '3', '4', '5', '6', '7', '8', '9', 'n', 'v', 'd', 'k', 'e'}; + const char suit_code[] = {'G', 'P', 'T', 'L'}; + + srand((unsigned) time(NULL)); + + printf("ENter number of cards: "); + scanf("%d", &num_cards); + + printf("In hand: "); + while (num_cards > 0) { + suit = rand() % NUM_SUITS; + rank = rand() % NUM_RANKS; + if (!in_hand[suit][rank]) { + in_hand[suit][rank] = true; + num_cards--; + printf(" %c%c", rank_code[rank], suit_code[suit]); + } + } + printf("\n"); + +} + +void reverse2(void) { + int i, n; + + printf("How many numbers you want to reverse?: "); + scanf("%d", &n); + + int a[n]; + + printf("Enter %d numbers: ", n); + for (i = 0; i < SIZE; i++) { + scanf("%d", &a[i]); + } + + printf("In reverse order: "); + for (i = n - 1; i >= 0; i--) { + printf(" %d", a[i]); + } + printf("\n"); +} + +// EXERCISES // +void ex_01(void) { +// The problem with sizeof(a) / sizeof(t) is that it can't easily be checked +// for correctness by someone reading the program. (The reader would have to +// locate the declaration of a and make sure that its elements have type t.) +} + +void ex_02(void) { + int digit = 5, array[digit - '0']; +} + +void ex_03(void) { + bool wekend[7] = {1, 0, 0, 0, 0, 0, 1}; +} + +void ex_04(void) { + bool wekend[7] = {[0] = 1, [6] = 1}; +} + +// Fibonacci numbers +void ex_05(void) { + int i, fib_numbers[FIBONACCI_LENGHT] = {[1] = 1}; + + printf("First %d Fibonacci numbers are: \n0, 1, ", FIBONACCI_LENGHT); + for (i = 2; i < FIBONACCI_LENGHT; i++) { + fib_numbers[i] = fib_numbers[i - 2] + fib_numbers[i - 1]; + printf("%d, ", fib_numbers[i]); + } +} + +// 7-segment display array initializer +void ex_06(void) { + const int segments[10][7] = { + {1, 1, 1, 1, 1, 1, 0}, + {0, 1, 1, 0, 0, 0, 0}, + {1, 1, 0, 1, 1, 0, 1}, + {1, 1, 1, 1, 0, 0, 1}, + {0, 1, 1, 0, 0, 1, 1}, + {1, 0, 1, 1, 0, 1, 1}, + {1, 0, 1, 1, 1, 1, 1}, + {1, 1, 1, 0, 0, 0, 0}, + {1, 1, 1, 1, 1, 1, 1}, + {1, 1, 1, 1, 0, 1, 1} + }; +} + +// 7-segment display array initializer shrinked +void ex_07(void) { + const int segments[10][7] = { + {1, 1, 1, 1, 1, 1}, + {0, 1, 1, 0, 0, 0, 0}, + {1, 1, 0, 1, 1, 0, 1}, + {1, 1, 1, 1, 0, 0, 1}, + {0, 1, 1, 0, 0, 1, 1}, + {1, 0, 1, 1, 0, 1, 1}, + {1, 0, 1, 1, 1, 1, 1}, + {1, 1, 1}, + {1, 1, 1, 1, 1, 1, 1}, + {1, 1, 1, 1, 0, 1, 1} + }; +} + +void ex_08(void) { + float temperature_readings[30][24]; +} + +// Average temperature +void ex_09(void) { + float avg, sum_hours = 0, sum_days = 0, temperature_readings[30][24]; + int i, j; + + for (i = 0; i < 30; i++) { + for (j = 0; j < 24; j++) { + sum_hours += temperature_readings[i][j]; + } + sum_days += sum_hours / 24; + } + avg = sum_days / 30; +} + +// CHess board +void ex_10(void) { + char chess_board[8][8] = { + {'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'}, + {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'}, + {' ', '.', ' ', '.', ' ', '.', ' ', '.'}, + {'.', ' ', '.', ' ', '.', ' ', '.', ' '}, + {' ', '.', ' ', '.', ' ', '.', ' ', '.'}, + {'.', ' ', '.', ' ', '.', ' ', '.', ' '}, + {'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'}, + {'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'}, + }; +} + +// Checker board +void ex_11(void) { + char checker_board[8][8]; + int i, j; + + for (i = 0; i < 8; i++) { + for (j = 0; j < 8; j++) { + checker_board[i][j] = (i + j) % 2 == 0 ? 'B' : 'R'; + printf("%c ", checker_board[i][j]); + } + printf("\n"); + } +} + +// PROJECTS // +// repdigit modified +void pr_01(void) { + bool digit_seen[10] = {false}; + int digit, i; + long n; + + printf("Enter number: "); + scanf("%ld", &n); + + while (n > 0) { + digit = n % 10; + if (digit_seen[digit]) + break; + digit_seen[digit] = true; + n /= 10; + } + + if (n > 0) { + printf("Repeated digit(s): "); + for (i = 0; i < 10; i++) + if (digit_seen[i]) + printf("%d ", i); + } + else + printf("No repeated digit\n"); +} + +// repdigit modified again +void pr_02(void) { + short digit_seen[10] = {0}; + int digit, i; + long n; + + printf("Enter number: "); + scanf("%ld", &n); + + while (n > 0) { + digit = n % 10; + digit_seen[digit]++; + n /= 10; + } + + printf("Digit:\t\t "); + for (i = 0; i < 10; i++) + printf("%3d", i); + + printf("\nOccurences:\t "); + for (i = 0; i < 10; i++) + printf("%3d", digit_seen[i]); +} + +// repdigit modified again +void pr_03(void) { + short i, digit_seen[10] = {false}; + long n; + + while (1) { + printf("Enter number: "); + scanf("%ld", &n); + +// 0 terminates + if (n == 0) + break; + + while (n > 0) { + digit_seen[n % 10]++; + n /= 10; + } + + printf("Digit:\t\t "); + for (i = 0; i < 10; i++) + printf("%3d", i); + + printf("\nOccurences:\t "); + for (i = 0; i < 10; i++) + printf("%3d", digit_seen[i]); + + printf("\n\n"); + +// Reset the array + for (i = 0; i < 10; i++) + digit_seen[i] = false; + } +} + +// reverse modified +void pr_04(void) { + int a[N], i; + + printf("Enter %d numbers: ", N); + for (i = 0; i < N; i++) + scanf("%d", &a[i]); + + printf("In reverse order: "); + for (i = N - 1; i >= 0; i--) + printf(" %d", a[i]); + printf("\n"); +} + +// Interest modified +void pr_05(void) { + int i, j, low_rate, num_years, year; + double value[5]; + + printf("Enter interest rate: "); + scanf("%d", &low_rate); + printf("Enter number of years: "); + scanf("%d", &num_years); + + printf("\nYears: "); + for (i = 0; i < NUM_RATES; i++) { + printf("%6d%%", low_rate + i); + value[i] = INITIAL_BALANCE; + } + printf("\n"); + + for (year = 1; year <= num_years; year++) { + printf("%3d ", year); + for (i = 0; i < NUM_RATES; i++) { + for (j = 0; j < 12; j++) + value[i] += (low_rate + i) / 100.0 * value[i]; + printf("%7.2f", value[i]); + } + printf("\n"); + } +} + +void pr_06(void) { + char a[MAX_LENGHT], ch; + int i, j = 0, r; + + printf("Enter message: "); + while (1) { + if ((a[j] = getchar()) == '\n') + break; + j++; + } + + printf("In B1FF-speak: "); + for (i = 0; i < j; i++) { + a[i] = toupper(a[i]); + switch (a[i]) { + case 'A': + a[i] = '4'; break; + case 'B': + a[i] = '8'; break; + case 'E': + a[i] = '3'; break; + case 'I': + a[i] = '1'; break; + case 'O': + a[i] = '0'; break; + case 'S': + a[i] = '5'; break; + } + printf("%c", a[i]); + } + +// Get some random number bw 8 and 12 + srand((unsigned) time(NULL)); + r = (rand() % 5) + 8; + for (i = 0; i < r; i++) + printf("!"); +} + + +// 5x5 matrix sum calculator +void pr_07(void) { + int i, j, sum, matrix[5][5]; + + for (i = 0; i < 5; i++) { + printf("Enter row %d: ", i + 1); + scanf("%d %d %d %d %d", &matrix[i][0], &matrix[i][1], + &matrix[i][2], &matrix[i][3], &matrix[i][4]); + } + + printf("\nRow totals: "); + for (i = 0; i < 5; i++) { + sum = 0; + for (j = 0; j < 5; j++) + sum += matrix[i][j]; + printf("%d ", sum); + } + + printf("\nColumn totals: "); + for (i = 0; i < 5; i++) { + sum = 0; + for (j = 0; j < 5; j++) + sum += matrix[j][i]; + printf("%d ", sum); + } + +} + +//5x5 matrix sum calculator student/ quizes +void pr_08(void) { + + int grades[NUM_STUDENTS][NUM_QUIZZES]; + int high, low, quiz, student, total; + + for (student = 0; student < NUM_STUDENTS; student++) { + printf("Enter grades for student %d: ", student + 1); + for (quiz = 0; quiz < NUM_QUIZZES; quiz++) + scanf("%d", &grades[student][quiz]); + } + + printf("\nStudent Total Average\n"); + for (student = 0; student < NUM_STUDENTS; student++) { + printf("%4d ", student + 1); + total = 0; + for (quiz = 0; quiz < NUM_QUIZZES; quiz++) + total += grades[student][quiz]; + printf("%3d %3d\n", total, total / NUM_QUIZZES); + } + + printf("\nQuiz Average High Low\n"); + for (quiz = 0; quiz < NUM_QUIZZES; quiz++) { + printf("%3d ", quiz + 1); + total = 0; + high = 0; + low = 100; + for (student = 0; student < NUM_STUDENTS; student++) { + total += grades[student][quiz]; + if (grades[student][quiz] > high) + high = grades[student][quiz]; + if (grades[student][quiz] < low) + low = grades[student][quiz]; + } + printf("%3d %3d %3d\n", total / NUM_STUDENTS, high, low); + } + +} + +// Map walk +void pr_09(void) { + char ch, map[MAP_WIDTH][MAP_HEIGHT] = {{0}}; + int i, x, y, direction; + bool usedDirection[4] = {false}; + + srand((unsigned) time(NULL)); + + x = 0; + y = 0; + // map[x][y] = ch; + // 65 is 'A', 90 is 'Z' + for (ch = 'A'; ch <= 'Z'; ch++) { + map[x][y] = ch; + +// Reset directions + for (i = 0; i < 4; i++) + usedDirection[i] = false; + + while (1) { + direction = (rand() % 4); + usedDirection[direction] = true; + + if(direction == 0 && (y + 1) < MAP_HEIGHT && !map[x][y + 1]) + break; + if(direction == 1 && (x + 1) < MAP_WIDTH && !map[x + 1][y]) + break; + if(direction == 2 && (y - 1) >= 0 && !map[x][y - 1]) + break; + if(direction == 3 && (x - 1) >= 0 && !map[x - 1][y]) + break; + +// ALl directions are used and we still dont have a path + if (usedDirection[0] && usedDirection[1] && + usedDirection[2] && usedDirection[3]) + goto terminate; + + } + + switch (direction) { + case 0: + y++; + break; + case 1: + x++; + break; + case 2: + y--; + break; + case 3: + x--; + break; + } + + } + + terminate: + for (y = 0; y < MAP_WIDTH; y++) { + for (x = 0; x < MAP_WIDTH; x++) { + if (map[x][y]) + printf("%c ", map[x][y]); + else + printf(". "); + } + printf("\n"); + } +} + +// Departure times modified +void pr_10(void) { + int i, hh, mm, entered, closestToken = 0, + closestDistance, distance; + + int a[] = {480, 583, 679, 767, 840, 945, 1140, 1305}; + int departure[] = {616, 712, 811, 900, 968, 1075, 1280, 1438}; + + printf("Enter a 24-hour time: "); + scanf("%2d:%2d", &hh, &mm); + + entered = hh * 60 + mm; +// 60 min * 24 hour + distance = 1440; + for (i = 0; i < SIZE; i++) { + distance = abs(a[i] - entered); + if (distance < closestDistance) { + closestDistance = distance; + closestToken = i; + } + } + + printf("Closest departure time is %2d:%.2d., arriving at %2d:%.2d.", + a[closestToken] / 60, a[closestToken] % 60, + departure[closestToken] / 60, departure[closestToken] / 60); + +} + +// Phone text number to digits +void pr_11(void) { + char ch, number[15]; + int i; + + printf("Enter phone number: "); + for (i = 0; i < 15 && (ch = getchar()) != '\n'; i++) + number[i] = ch; + + printf("In numeric form: "); + for (i = 0; i < 15; i++) { + switch (number[i]) { + case 'A': case 'B': case 'C': + printf("%d", 2); break; + case 'D': case 'E': case 'F': + printf("%d", 3); break; + case 'G': case 'H': case 'I': + printf("%d", 4); break; + case 'J': case 'K': case 'L': + printf("%d", 5); break; + case 'M': case 'N': case 'O': + printf("%d", 6); break; + case 'P': case 'Q': case 'R': case 'S': + printf("%d", 7); break; + case 'T': case 'U': case 'V': + printf("%d", 8); break; + case 'W': case 'X': case 'Y': case 'Z': + printf("%d", 9); break; + default: + printf("%c", number[i]); break; + } + } +} + +// Scrabble modified +void pr_12(void) { + int sum = 0; + char ch; + const char score[26] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, // L + 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 3, 8, 4, 10}; + + printf("Enter a word: "); + + while ((ch = getchar()) != '\n') { + ch = toupper(ch); + sum += score[ch - 65]; + } + + printf("Scrabble value: %d\n", sum); +} + +// Name input modified +void pr_13(void) { + char first, temp, surname[20]; + int i, j; + + printf("Enter a first and last name: "); +// find first nonblank character + while ((first = getchar()) == ' ') + ; +// skip spaces + while (getchar() != ' ') + ; +// find first nonblank character + while ((surname[0] = getchar()) == ' ') + ; + + for (i = 1; i < 20; i++) { + temp = getchar(); + if (temp == ' ' || temp == '\n') + break; + surname[i] = temp; + } + + printf("You entered the name: "); + for (j = 0; j < i; j++) { + printf("%c", surname[j]); + } + + printf(", %c.", first); +} + +// Reverse words in sentence +void pr_14(void) { + char ch, sentence[50], terminating; + int i, j, k; + + printf("Enter a sentence: "); + i = 0; + +// Insert words into array + ch = getchar(); + while (ch != '.' && ch != '!' && ch != '?') { + sentence[i++] = ch; + ch = getchar(); + } +// Terminating character into separate one + terminating = ch; + + printf("Reversal of sentence:"); +// Some fancy algorithms going back and forth over the words + for (j = i - 1; j >=0; j--) { + if (sentence[j - 1] != ' ' && j > 0) + continue; + putchar(' '); + for (k = j; k < i; k++) { + putchar(sentence[k]); + } + i = j - 1; + } + putchar(terminating); + +} + +// Caesar cipher +void pr_15(void) { + char ch, message[80]; + short i, shift; + + printf("Enter message to be encrypted: "); + i = 0; + while ((ch = getchar()) != '\n') + message[i++] = ch; + + printf("Enter shift amount: "); + while ((ch = getchar()) != '\n') + shift = shift * 10 + ch - '0'; + + printf("Encrypted message: "); + for (i = 0; i < 80; i++) { + if (message[i] >= 'A' && message[i] <= 'Z') + putchar(((message[i] - 'A') + shift) %26 + 'A'); + else if (message[i] >= 'a' && message[i] <= 'z') + putchar(((message[i] - 'a') + shift) %26 + 'a'); + else + putchar(message[i]); + } + +} + +// Anagrams +void pr_16(void) { + char ch, contain[26] = {0}; + short i; + + printf("Enter first word: "); + i = 0; + while ((ch = getchar()) != '\n') { + if (isalpha(ch)) + contain[toupper(ch) - 'A']++; + i++; + } + + printf("Enter second word: "); + i = 0; + while ((ch = getchar()) != '\n') { + if (isalpha(ch)) + contain[toupper(ch) - 'A']--; + i++; + } + + for (i = 0; i < 26; i++) { + if (contain[i] != 0) + break; + } + + if (i == 26) + printf("The words are anagrams."); + else + printf("The words are not anagrams."); +} + +// Magic square generator +void pr_17(void) { + short n = 0, r, c, i, prevr, prevc; + + printf("Magic square of specified size.\n"); + + while (n % 2 != 1) { + printf("Enter odd number between 1 and 99: "); + scanf("%2hd", &n); + } + + short square[n][n]; + for (r = 0; r < n; r++) + for (c = 0; c < n; c++) + square[r][c] = 0; + +// Put 1 into first row, middle column + r = prevr = 0; + c = prevc = n / 2; + i = 1; + do { +// Wrap over row + if (r == -1) + r = n - 1; +// Wrap over column + if (c == n) + c = 0; +// If element already occupied, put new right below previous placed + if (square[r][c] != 0) { + r = prevr + 1; + c = prevc; + } + prevr = r; + prevc = c; +// Move one row up and to to the next column + square[r--][c++] = i++; + } while (i <= (n * n)); + + for (r = 0; r < n; r++) { + for (c = 0; c < n; c++) { + printf("%4hd", square[r][c]); + } + printf("\n"); + } +} diff --git a/09_Functions/Debug/Examples/countdown/subdir.mk b/09_Functions/Debug/Examples/countdown/subdir.mk new file mode 100644 index 0000000..67a138b --- /dev/null +++ b/09_Functions/Debug/Examples/countdown/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Examples/countdown/main.c + +OBJS += \ +./Examples/countdown/main.o + +C_DEPS += \ +./Examples/countdown/main.d + + +# Each subdirectory must supply rules for building sources it contributes +Examples/countdown/%.o: ../Examples/countdown/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/09_Functions/Debug/Examples/subdir.mk b/09_Functions/Debug/Examples/subdir.mk new file mode 100644 index 0000000..5227db7 --- /dev/null +++ b/09_Functions/Debug/Examples/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Examples/prime.c + +OBJS += \ +./Examples/prime.o + +C_DEPS += \ +./Examples/prime.d + + +# Each subdirectory must supply rules for building sources it contributes +Examples/%.o: ../Examples/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/09_Functions/Debug/Exercises/subdir.mk b/09_Functions/Debug/Exercises/subdir.mk new file mode 100644 index 0000000..68a8e81 --- /dev/null +++ b/09_Functions/Debug/Exercises/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Exercises/main.c + +OBJS += \ +./Exercises/main.o + +C_DEPS += \ +./Exercises/main.d + + +# Each subdirectory must supply rules for building sources it contributes +Exercises/%.o: ../Exercises/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/09_Functions/Debug/Program/subdir.mk b/09_Functions/Debug/Program/subdir.mk new file mode 100644 index 0000000..63edae4 --- /dev/null +++ b/09_Functions/Debug/Program/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Program/qsort.c + +OBJS += \ +./Program/qsort.o + +C_DEPS += \ +./Program/qsort.d + + +# Each subdirectory must supply rules for building sources it contributes +Program/%.o: ../Program/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/09_Functions/Debug/Projects/subdir.mk b/09_Functions/Debug/Projects/subdir.mk new file mode 100644 index 0000000..b9b375d --- /dev/null +++ b/09_Functions/Debug/Projects/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_08.c + +OBJS += \ +./Projects/pr_08.o + +C_DEPS += \ +./Projects/pr_08.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/%.o: ../Projects/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/09_Functions/Debug/average/subdir.mk b/09_Functions/Debug/average/subdir.mk new file mode 100644 index 0000000..01b234d --- /dev/null +++ b/09_Functions/Debug/average/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../average/main.c + +OBJS += \ +./average/main.o + +C_DEPS += \ +./average/main.d + + +# Each subdirectory must supply rules for building sources it contributes +average/%.o: ../average/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/09_Functions/Debug/countdown/subdir.mk b/09_Functions/Debug/countdown/subdir.mk new file mode 100644 index 0000000..3f102de --- /dev/null +++ b/09_Functions/Debug/countdown/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../countdown/main.c + +OBJS += \ +./countdown/main.o + +C_DEPS += \ +./countdown/main.d + + +# Each subdirectory must supply rules for building sources it contributes +countdown/%.o: ../countdown/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/09_Functions/Debug/makefile b/09_Functions/Debug/makefile new file mode 100644 index 0000000..55e824b --- /dev/null +++ b/09_Functions/Debug/makefile @@ -0,0 +1,44 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include Projects/subdir.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 09_Functions + +# Tool invocations +09_Functions: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "09_Functions" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 09_Functions + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/09_Functions/Debug/sources.mk b/09_Functions/Debug/sources.mk new file mode 100644 index 0000000..979abc7 --- /dev/null +++ b/09_Functions/Debug/sources.mk @@ -0,0 +1,17 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +O_SRCS := +C_SRCS := +S_UPPER_SRCS := +OBJ_SRCS := +ASM_SRCS := +OBJS := +C_DEPS := +EXECUTABLES := + +# Every subdirectory with source files must be described here +SUBDIRS := \ +Projects \ + diff --git a/09_Functions/Examples/average.c b/09_Functions/Examples/average.c new file mode 100644 index 0000000..0be6952 --- /dev/null +++ b/09_Functions/Examples/average.c @@ -0,0 +1,17 @@ +#include + +double average(double a, double b) { + return (a + b) / 2; +} + +int main(void) { + double x, y, z; + + printf("Enter three numbers: "); + scanf("%lf %lf %lf", &x, &y, &z); + printf("Average of %g and %g: %g\n", x, y, average(x, y)); + printf("Average of %g and %g: %g\n", y, z, average(y, z)); + printf("Average of %g and %g: %g\n", x, z, average(x, z)); + + return 0; +} diff --git a/09_Functions/Examples/countdown.c b/09_Functions/Examples/countdown.c new file mode 100644 index 0000000..582741c --- /dev/null +++ b/09_Functions/Examples/countdown.c @@ -0,0 +1,14 @@ +#include + +void print_count(int n) { + printf("T minus %d and counting\n", n); +} + +int main(void) { + int i; + + for (i = 10; i > 0; --i) + print_count(i); + + return 0; +} diff --git a/09_Functions/Examples/prime.c b/09_Functions/Examples/prime.c new file mode 100644 index 0000000..c959150 --- /dev/null +++ b/09_Functions/Examples/prime.c @@ -0,0 +1,26 @@ +#include +#include + +bool is_prime(int n) { + int divisor; + + if (n <= 1) + return false; + for (divisor = 2; divisor * divisor <= n; divisor++) + if (n % divisor == 0) + return false; + return true; +} + +int main(void) { + int n; + + printf("Enter a number: "); + scanf("%d", &n); + if (is_prime(n)) + printf("Prime\n"); + else + printf("Not prime\n"); + + return 0; +} diff --git a/09_Functions/Examples/pun2.c b/09_Functions/Examples/pun2.c new file mode 100644 index 0000000..6ad6a81 --- /dev/null +++ b/09_Functions/Examples/pun2.c @@ -0,0 +1,11 @@ +#include + +void print_pun(void) { + printf("To C, or not to C: that is the question.\n"); +} + +int main(void) { + print_punt(); + + return 0; +} diff --git a/09_Functions/Examples/qsort.c b/09_Functions/Examples/qsort.c new file mode 100644 index 0000000..dc2097d --- /dev/null +++ b/09_Functions/Examples/qsort.c @@ -0,0 +1,51 @@ +#include + +#define N 10 + +void quicksort(int a[], int low, int high); +int split(int a[], int low, int high); + +int main(void) { + int a[N], i; + + printf("Enter %d numbers to be sorted: ", N); + for (i = 0; i < N; i++) + scanf("%d", &a[i]); + + quicksort(a, 0, N - 1); + + printf("In sorted order: "); + for (i = 0; i < N; i++) + printf("%d ", a[i]); + printf("\n"); + + return 0; +} + +void quicksort(int a[], int low, int high) { + int middle; + + if (low >= high) return; + middle = split(a, low, high); + quicksort(a, low, middle - 1); + quicksort(a, middle + 1, high); +} + +int split(int a[], int low, int high) { + int part_element = a[low]; + + for(;;) { + while (low < high && part_element <= a[high]) + high--; + if (low >= high) break; + a[low++] = a[high]; + + while (low < high && a[low] <= part_element) + low++; + if (low >= high) break; + a[high--] = a[low]; + } + + a[high] = part_element; + return high; +} diff --git a/09_Functions/Exercises/main.c b/09_Functions/Exercises/main.c new file mode 100644 index 0000000..dff0dc2 --- /dev/null +++ b/09_Functions/Exercises/main.c @@ -0,0 +1,241 @@ +#include +#include +#include + + +double triangle_area(double base, double height); +int check(int x, int y, int n); +int gcd(int m, int n); +int day_of_year(int month, int day, int year); +int digit(int n, int k); +int f(int a, int b); +int largest(int a[], int n); +int average(int a[], int n); +int num_positive(int a[], int n); +float compute_GPA(char grades[], int n); +double inner_product(double a[], double b[], int n); +int evaluate_position(char board[8][8]); +bool has_zero(int a[], int n); +double median(double x, double y, double z); +int fact(int n); +int gcd_recursive(int m, int n); +void pb (int n); + + +int main(void) { +// char chess_board[8][8] = { +// {'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'}, +// {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'}, +// {' ', '.', ' ', '.', ' ', '.', ' ', '.'}, +// {'.', ' ', '.', ' ', '.', ' ', '.', ' '}, +// {' ', '.', ' ', '.', ' ', '.', ' ', '.'}, +// {'.', ' ', '.', ' ', '.', ' ', '.', ' '}, +// {'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'}, +// {'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'}, +// }; +// printf("%d", evaluate_position(chess_board)); + + pb(3); + + return 0; +} + +double triangle_area(double base, double height) { + return base * height / 2; +} + +int check(int x, int y, int n) { + return (x >= 0 && x <= n - 1 && y >= 0 && y <= n - 1); +} + +int gcd(int m, int n) { + int remainder; + + while (n != 0) { + remainder = m % n; + m = n; + n = remainder; + } + + return m; +} + +int day_of_year(int month, int day, int year) { + int num_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + int day_count = 0, i; + + for (i = 1; i < month; i++) + day_count += num_days[i-1]; + +// adjust for leap years, assuming they are divisible by 4 + if (year % 4 == 0 && month > 2) + day_count++; + + return day_count + day; +} + +int num_digits(int n) { + int i = 0; + while (n > 0) { + n /= 10; + i++; + } + return i; +} + +int digit(int n, int k) { + int i; + for (i = 1; i < k; i++) + n /= 10; + return n % 10; +} + +int f(int a, int b) { +// a, b, e are legal I think + return 0; +} + +int largest(int a[], int n) { + int i, max = a[0]; + + for (i = 1; i < n; i++) + if (a[i] > max) + max = a[i]; + + return max; +} + +int average(int a[], int n) { + int i, avg = 0; + + for (i = 0; i < n; i++) + avg += a[i]; + + return avg / n; +} + +int num_positive(int a[], int n) { + int i, count = 0; + + for (i = 0; i < n; i++) + if (a[i] > 0) + count++; + + return count; +} + +float compute_GPA(char grades[], int n) { + float avg = 0; + int i; + + for (i = 0; i < n; i++) { + switch (toupper(grades[i])) { + case 'A': + avg += 4; + break; + case 'B': + avg += 3; + break; + case 'C': + avg += 2; + break; + case 'D': + avg += 1; + break; + } + } + return avg; +} + +double inner_product(double a[], double b[], int n) { + double product = 0; + int i; + for (i = 0; i < n; i++) + product += a[i] * b[i]; + return product; +} + +int evaluate_position(char board[8][8]) { + int i, j, black = 0, white = 0; + + for (i = 0; i < 8; i++) { + for (j = 0; j < 8; j++) { + switch (board[i][j]) { + case 'Q': + white += 9; + break; + case 'R': + white += 5; + break; + case 'B': case 'N': + white += 3; + break; + case 'P': + white += 1; + break; + case 'q': + black += 9; + break; + case 'r': + black += 5; + break; + case 'b': case 'n': + black += 3; + break; + case 'p': + black += 1; + break; + } + } + } + return white - black; +} + +bool has_zero(int a[], int n) { + int i; + bool flag = false; + + for (i = 0; i < n; i++) + flag = (a[i] == 0); + return flag; +} + +double median(double x, double y, double z) { + double result; + + if (x <= y) + if (y <= z) result = y; + else if (x <= z) result = z; + else result = x; + else { + if (z <= y) result = y; + else if (x <= z) result = x; + else result = z; + } + + return result; +} + +int fact(int n) { + int i, result = 1; + + for (i = 2; i <= n; i++) + result *= i; + + return result; +} + +int gcd_recursive(int m, int n) { + if (n == 0) + return m; + else + return gcd_recursive(n, m % n); +} + +// DEC to BINARY +void pb(int n) { + if (n != 0) { + pb(n / 2); + putchar('0' + n % 2); + } +} diff --git a/09_Functions/Exercises/swap.c b/09_Functions/Exercises/swap.c new file mode 100644 index 0000000..1efb3f7 --- /dev/null +++ b/09_Functions/Exercises/swap.c @@ -0,0 +1,18 @@ +#include + +void swap(int a, int b); + +int main(void) { + int i = 1, j = 2; + + swap(i, j); + printf("i = %d, j = %d\n", i, j); + return 0; +} + +// Twis will not swap because variables are just local +void swap(int a, int b) { + int temp = a; + a = b; + b = temp; +} diff --git a/09_Functions/Projects/pr_01.c b/09_Functions/Projects/pr_01.c new file mode 100644 index 0000000..80cb2ec --- /dev/null +++ b/09_Functions/Projects/pr_01.c @@ -0,0 +1,46 @@ +/* + * pr_01.c + * + * Created on: Feb 14, 2013 + * Author: delmadord + */ + +// NOT WORKING - DONT UNDERSTAND THE ASSIGMENT + +#include + +#define N 10 + +void selection_sort(int n, int a[n]) { + if (n > 1) { + int i, temp, max = 0; +// Find index of highest element + for (i = 1; i < n; i++) { + if (a[i] > max) + max = i; + } +// Swap it to the end of the array + temp = a[n]; + a[n] = a[max]; + a[max] = temp; + selection_sort(n - 1, a); + } + else printf("%d ", n - 1); +} + +int main(void) { + int i, serie[N] = {0}; + + printf("Enter %d integers: ", N); + for (i = 0; i < N; i++) + scanf("%d", &serie[i]); + + selection_sort(N, serie); + + printf("Sorted: "); + for (i = 0; i < N; i++) + printf("%d ", serie[i]); + + return 0; +} + diff --git a/09_Functions/Projects/pr_02.c b/09_Functions/Projects/pr_02.c new file mode 100644 index 0000000..50109f7 --- /dev/null +++ b/09_Functions/Projects/pr_02.c @@ -0,0 +1,37 @@ +/* + * pr_02.c + * + * Created on: Feb 18, 2013 + * Author: delmadord + */ + +#include + +float tax_due(float income) { + float tax; + if (income <= 750.0f) + tax = income * .01f; + else if (income <= 2250.0f) + tax = income * .02f + 7.50f; + else if (income <= 3750.0f) + tax = income * .03f + 37.50f; + else if (income <= 5250.0f) + tax = income * .04f + 82.50f; + else if (income <= 7000.0f) + tax = income * .05f + 142.50f; + else + tax = income * .06f + 230.00f; + + return tax; +} + +int main(void) { + float income; + + printf("Enter income: "); + scanf("%f", &income); + + printf("Tax due is: %.2f", tax_due(income)); + + return 0; +} diff --git a/09_Functions/Projects/pr_03.c b/09_Functions/Projects/pr_03.c new file mode 100644 index 0000000..02cf05d --- /dev/null +++ b/09_Functions/Projects/pr_03.c @@ -0,0 +1,84 @@ +/* + * pr_03.c + * + * Created on: Feb 18, 2013 + * Author: delmadord + */ + + +// NOT WORKING - I'VE NO IDEA + + +#include +#include +#include + +#define MAP_WIDTH 10 +#define MAP_HEIGHT 10 + +void generate_random_walk(char walk[10][10]); +void print_array(char walk[10][10]); + +// Map walk +void pr_09(void) { + char ch, map[MAP_WIDTH][MAP_HEIGHT] = {{0}}; + int i, x, y, direction; + bool usedDirection[4] = {false}; + + srand((unsigned) time(NULL)); + + x = 0; + y = 0; + // map[x][y] = ch; + // 65 is 'A', 90 is 'Z' + for (ch = 'A'; ch <= 'Z'; ch++) { + map[x][y] = ch; + +// Reset directions + for (i = 0; i < 4; i++) + usedDirection[i] = false; + + while (1) { + direction = (rand() % 4); + usedDirection[direction] = true; + + if(direction == 0 && (y + 1) < MAP_HEIGHT && !map[x][y + 1]) + break; + if(direction == 1 && (x + 1) < MAP_WIDTH && !map[x + 1][y]) + break; + if(direction == 2 && (y - 1) >= 0 && !map[x][y - 1]) + break; + if(direction == 3 && (x - 1) >= 0 && !map[x - 1][y]) + break; + +// ALl directions are used and we still dont have a path + if (usedDirection[0] && usedDirection[1] && + usedDirection[2] && usedDirection[3]) + goto terminate; + + } + + switch (direction) { + case 0: y++; break; + case 1: x++; break; + case 2: y--; break; + case 3: x--; break; + } + + } + + terminate: + for (y = 0; y < MAP_WIDTH; y++) { + for (x = 0; x < MAP_WIDTH; x++) { + if (map[x][y]) + printf("%c ", map[x][y]); + else + printf(". "); + } + printf("\n"); + } +} + +void generate_random_walk(char walk[10][10]) { + +} diff --git a/09_Functions/Projects/pr_04.c b/09_Functions/Projects/pr_04.c new file mode 100644 index 0000000..5868ab6 --- /dev/null +++ b/09_Functions/Projects/pr_04.c @@ -0,0 +1,52 @@ +/* + * pr_04.c + * + * Created on: Feb 18, 2013 + * Author: delmadord + */ + +#include +#include +#include + +void read_word(int counts[26]); +bool equal_array(int counts1[26], int counts2[26]); + +int main(void) { + int counts1[26] = {0}, counts2[26] = {0}; + + read_word(counts1); + read_word(counts2); + + + if (equal_array(counts1, counts2)) + printf("The words are anagrams."); + else + printf("The words are not anagrams."); + + return 0; +} + +void read_word(int counts[26]) { + char ch; + short i; + printf("Enter a word: "); + i = 0; + while ((ch = getchar()) != '\n') { + if (isalpha(ch)) + counts[toupper(ch) - 'A']++; + i++; + } +} + +bool equal_array(int counts1[26], int counts2[26]) { + short i; + bool equals = true; + for (i = 0; i < 26; i++) { + if (counts1[i] != counts2[i]) { + equals = false; + break; + } + } + return equals; +} diff --git a/09_Functions/Projects/pr_05.c b/09_Functions/Projects/pr_05.c new file mode 100644 index 0000000..94f48f0 --- /dev/null +++ b/09_Functions/Projects/pr_05.c @@ -0,0 +1,62 @@ +#include + +void create_magic_square(int n, char magic_square[n][n]); +void print_magic_square(int n, char magic_square[n][n]); + +int main(void) { + int n = 0; + + printf("Magic square of specified size.\n"); + + while (n % 2 != 1) { + printf("Enter odd number between 1 and 99: "); + scanf("%2d", &n); + } + + char magic_square[n][n]; + create_magic_square(n, magic_square); + print_magic_square(n, magic_square); + + return 0; +} + + +void create_magic_square(int n, char magic_square[n][n]) { + short i, r, c, prevr, prevc; + for (r = 0; r < n; r++) + for (c = 0; c < n; c++) + magic_square[r][c] = 0; + +// Put 1 into first row, middle column + r = prevr = 0; + c = prevc = n / 2; + i = 1; + do { +// Wrap over row + if (r == -1) + r = n - 1; +// Wrap over column + if (c == n) + c = 0; +// If element already occupied, put new right below previous placed + if (magic_square[r][c] != 0) { + r = prevr + 1; + c = prevc; + } + prevr = r; + prevc = c; +// Move one row up and to to the next column + magic_square[r--][c++] = i++; + } while (i <= (n * n)); +} + + +void print_magic_square(int n, char magic_square[n][n]) { + short r, c; + for (r = 0; r < n; r++) { + for (c = 0; c < n; c++) { + printf("%4hd", magic_square[r][c]); + } + printf("\n"); + } +} diff --git a/09_Functions/Projects/pr_06.c b/09_Functions/Projects/pr_06.c new file mode 100644 index 0000000..470af72 --- /dev/null +++ b/09_Functions/Projects/pr_06.c @@ -0,0 +1,30 @@ +#include + +int custom_polynomial(int x); +int powi(int number, int exponent); + +int main(void) { + int x; + printf("Please enter x: "); + scanf("%d", &x); + + printf("3x^5 + 2x^4 - 5x^3 - x^2 - 6 = %d", custom_polynomial(x)); + return 0; +} + +int custom_polynomial(int x) { + return + (3 * powi(x, 5)) + + (2 * powi(x, 4)) + - (5 * powi(x, 3)) + - (1 * powi(x, 2)) + - (7 * x) + - 6; +} + +int powi(int number, int exponent) { + int i, product = 1; + for (i = 0; i < exponent; i++) + product *= number; + + return product; +} diff --git a/09_Functions/Projects/pr_07.c b/09_Functions/Projects/pr_07.c new file mode 100644 index 0000000..a88d9aa --- /dev/null +++ b/09_Functions/Projects/pr_07.c @@ -0,0 +1,28 @@ +#include + +int power(int n, int exp); + +int main(void) { + int n, exp; + printf("Please enter a number: "); + scanf("%d", &n); + printf("Please enter an exponent: "); + scanf("%d", &exp); + + printf("%d ^ %d = %d", n, exp, power(n, exp)); + + return 0; +} + +int power(int base, int exp) { + int result = 1; + while (exp) + { + if (exp & 1) + result *= base; + exp >>= 1; + base *= base; + } + + return result; +} diff --git a/09_Functions/Projects/pr_08.c b/09_Functions/Projects/pr_08.c new file mode 100644 index 0000000..35eb9fa --- /dev/null +++ b/09_Functions/Projects/pr_08.c @@ -0,0 +1,79 @@ +/* + * pr_08.c + * Game of craps. + * + * Created on: Jun 4, 2013 + * Author: delmadord + */ + +#include +#include +#include +#include + +int roll_dice(void); +bool play_game(void); + +int main(void) { + srand(time(NULL)); + + int wins = 0, loses = 0; + char ch = 'y'; + while (ch == 'y' || ch == 'Y') { + if (play_game()) { + wins++; + printf("You win!\n"); + } + else { + loses++; + printf("You lose!\n"); + } + + printf("\nPlay again? "); + ch = getchar(); + + while (getchar() != '\n'); + printf("\n"); + } + + printf("Wins: %d Losses: %d", wins, loses); + + return 0; +} + +// Generate a random number (simulation of rolling two dices) +int roll_dice(void) { + return rand() % 6 + rand() % 6 + 2; +} + + +bool play_game(void) { + int status = false, roll = roll_dice(); + printf("You rolled: %d\n", roll); + + if (roll == 7 || roll == 11) + status = true; + else if (roll == 2 || roll == 3) + status = false; + else { + printf("Your point is %d\n", roll); + int point = roll; + while (roll = roll_dice()) { + printf("You rolled: %d\n", roll); + + if (roll == point) { + status = true; + break; + } + else if (roll == 7) { + status = false; + break; + } + } + } + + return status; +} + + + diff --git a/10_Program_Organization/Debug/10_Program_Organization b/10_Program_Organization/Debug/10_Program_Organization new file mode 100644 index 0000000..20805d8 Binary files /dev/null and b/10_Program_Organization/Debug/10_Program_Organization differ diff --git a/10_Program_Organization/Debug/Examples/subdir.mk b/10_Program_Organization/Debug/Examples/subdir.mk new file mode 100644 index 0000000..a7ed4dc --- /dev/null +++ b/10_Program_Organization/Debug/Examples/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Examples/poker.c + +OBJS += \ +./Examples/poker.o + +C_DEPS += \ +./Examples/poker.d + + +# Each subdirectory must supply rules for building sources it contributes +Examples/%.o: ../Examples/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/10_Program_Organization/Debug/Projects/pr_07.d b/10_Program_Organization/Debug/Projects/pr_07.d new file mode 100644 index 0000000..9f4b7b7 --- /dev/null +++ b/10_Program_Organization/Debug/Projects/pr_07.d @@ -0,0 +1 @@ +Projects/pr_07.d: ../Projects/pr_07.c diff --git a/10_Program_Organization/Debug/Projects/pr_07.o b/10_Program_Organization/Debug/Projects/pr_07.o new file mode 100644 index 0000000..4cf4082 Binary files /dev/null and b/10_Program_Organization/Debug/Projects/pr_07.o differ diff --git a/10_Program_Organization/Debug/Projects/subdir.mk b/10_Program_Organization/Debug/Projects/subdir.mk new file mode 100644 index 0000000..6e831f1 --- /dev/null +++ b/10_Program_Organization/Debug/Projects/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_07.c + +OBJS += \ +./Projects/pr_07.o + +C_DEPS += \ +./Projects/pr_07.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/%.o: ../Projects/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/10_Program_Organization/Debug/makefile b/10_Program_Organization/Debug/makefile new file mode 100644 index 0000000..c9bc372 --- /dev/null +++ b/10_Program_Organization/Debug/makefile @@ -0,0 +1,44 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include Projects/subdir.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 10_Program_Organization + +# Tool invocations +10_Program_Organization: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "10_Program_Organization" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 10_Program_Organization + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/10_Program_Organization/Examples/guess.c b/10_Program_Organization/Examples/guess.c new file mode 100644 index 0000000..0aa98a9 --- /dev/null +++ b/10_Program_Organization/Examples/guess.c @@ -0,0 +1,83 @@ +/* Asks user to guess a hidden number */ + +#include +#include +#include + +#define MAX_NUMBER 100 + +// External variable +int secret_number; + +// Prototypes +void initialize_number_generator(void); +void choose_new_secret_number(void); +void read_guesses(void); + +int main(void) { + char command; + printf("Guess the secret number between 1 and %d.\n\n", MAX_NUMBER); + initialize_number_generator(); + + do { + choose_new_secret_number(); + printf("A new number has been choosen.\n"); + + read_guesses(); + printf("Play again? (Y/N) "); + + scanf(" %c", &command); + printf("\n"); + } while (command == 'y' || command == 'Y'); + + return 0; +} + +void initialize_number_generator(void) { + srand ((unsigned) time(NULL)); +} + +void choose_new_secret_number(void) { + secret_number = rand() % MAX_NUMBER + 1; +} + +void read_guesses(void) { + int guess, num_guesses = 0; + + while (1) { + num_guesses++; + printf("Enter guess: "); + scanf("%d", &guess); + + if (guess == secret_number) { + printf("You won in %d guesses!\n", num_guesses); + return; + } + else if (guess < secret_number) + printf("Too low; try again.\n"); + else + printf("Too high; try again.\n"); + + } +} + + + + + + + + + + + + + + + + + + + + + diff --git a/10_Program_Organization/Examples/poker.c b/10_Program_Organization/Examples/poker.c new file mode 100644 index 0000000..dd47146 --- /dev/null +++ b/10_Program_Organization/Examples/poker.c @@ -0,0 +1,163 @@ +/* Classifies a poker hand */ + +#include +#include +#include + +#define NUM_RANKS 13 +#define NUM_SUITS 4 +#define NUM_CARDS 5 + +// External variable +int num_in_rank[NUM_RANKS]; +int num_in_suit[NUM_SUITS]; +bool straight, flush, four, three; +int pairs; // Can be 0, 1 or 2 + +// Prototypes +void read_cards(void); +void analyze_hand(void); +void print_result(void); + +int main (void) { + while (1) { + read_cards(); + analyze_hand(); + print_result(); + } +} + +// Reads the card into external variables +void read_cards(void) { + bool card_exists[NUM_RANKS][NUM_SUITS]; + char ch, rank_ch, suit_ch; + int rank, suit; + bool bad_card; + int cards_read = 0; + + for (rank = 0; rank < NUM_RANKS; rank++) { + num_in_rank[rank] = 0; + for (suit = 0; suit < NUM_SUITS; suit++) + card_exists[rank][suit] = false; + } + + for (suit = 0; suit < NUM_SUITS; suit++) + num_in_suit[suit] = 0; + + while (cards_read < NUM_CARDS) { + bad_card = false; + + printf("Enter a card: "); + + rank_ch = getchar(); + switch (rank_ch) { + case '0': exit(EXIT_SUCCESS); + case '2': rank = 0; break; + case '3': rank = 1; break; + case '4': rank = 2; break; + case '5': rank = 3; break; + case '6': rank = 4; break; + case '7': rank = 5; break; + case '8': rank = 6; break; + case '9': rank = 7; break; + case 't': case 'T': rank = 8; break; + case 'j': case 'J': rank = 9; break; + case 'q': case 'Q': rank = 10; break; + case 'k': case 'K': rank = 11; break; + case 'a': case 'A': rank = 12; break; + default: bad_card = true; + } + + suit_ch = getchar(); + switch (suit_ch) { + case 'c': case 'C': suit = 0; break; + case 'd': case 'D': suit = 1; break; + case 'h': case 'H': suit = 2; break; + case 's': case 'S': suit = 3; break; + default: bad_card = true; + } + + while ((ch = getchar()) != '\n') + if (ch != ' ') + bad_card = true; + + if (bad_card) + printf("Bad card; ignored.\n"); + else if (card_exists[rank][suit]) + printf("Duplicate card; ignored.\n"); + else { + num_in_rank[rank]++; + num_in_suit[suit]++; + card_exists[rank][suit] = true; + cards_read++; + } + } +} + +void analyze_hand(void) { + int num_consec = 0; + int rank, suit; + + straight = false; + flush = false; + four = false; + three = false; + pairs = 0; + + // Check for flush + for (suit = 0; suit < NUM_SUITS; suit++) + if (num_in_suit[suit] == NUM_CARDS) + flush = true; + + // Check for straight + rank = 0; + while (num_in_rank[rank] == 0) + rank++; + for (; rank < NUM_RANKS && num_in_rank[rank] > 0; rank++) + num_consec++; + if (num_consec == NUM_CARDS) { + straight = true; + return; + } + + // Check for 4-of-a-kind, 3-of-a-kind and pairs + for (rank = 0; rank < NUM_RANKS; rank++) { + if (num_in_rank[rank] == 4) + four = true; + if (num_in_rank[rank] == 3) + three = true; + if (num_in_rank[rank] == 2) + pairs++; + + } +} + +void print_result(void) { + if (straight && flush) + printf("Straight flush"); + else if (four) + printf("Four of a kind"); + else if (three && pairs == 1) + printf("Full house"); + else if (flush) + printf("Flush"); + else if (straight) + printf("Straight"); + else if (three) + printf("Three of a kind"); + else if (pairs == 2) + printf("Two pairs"); + else if (pairs == 1) + printf("Pair"); + else + printf("High card"); + + printf("\n\n"); +} + + + + + + + diff --git a/10_Program_Organization/Examples/stack.c b/10_Program_Organization/Examples/stack.c new file mode 100644 index 0000000..c030494 --- /dev/null +++ b/10_Program_Organization/Examples/stack.c @@ -0,0 +1,35 @@ +#include + +#define STACK_SIZE 100 + +//void stack_overflow(void); + +/* external variables */ +int contents[STACK_SIZE]; +int top = 0; + +void make_empty(void) { + top = 0; +} + +bool is_empty(void) { + return top == 0; +} + +bool is_full(void) { + return top == STACK_SIZE; +} + +void push(int i) { +// if (is_full()) +// stack_overflow(); +// else + contents[top++] = i; +} + +int pop(void) { +// if (is_empty()) +// stack_overflow(); +// else + return contents[--top]; +} diff --git a/10_Program_Organization/Projects/pr_01.c b/10_Program_Organization/Projects/pr_01.c new file mode 100644 index 0000000..73c77b6 --- /dev/null +++ b/10_Program_Organization/Projects/pr_01.c @@ -0,0 +1,80 @@ +#include +#include +#include + +#define STACK_SIZE 100 + +/* external variables */ +char contents[STACK_SIZE]; +int top = 0; +bool nested = true; + +void make_empty(void); +bool is_empty(void); +bool is_full(void); +void push(char ch); +char pop(void); +void stack_overflow(void); +void stack_underflow(void); + + +int main(void) { + char ch; + printf("Enter parentheses and/or braces: "); + while ((ch = getchar()) != '\n' && nested == true) { + // Push left + if (ch == '{' || ch == '(' || ch == '[') + push(ch); + // Check if popped left is matched + else if (ch == '}') + nested = (pop() == '{'); + else if (ch == ')') + nested = (pop() == '('); + else if (ch == ']') + nested = (pop() == '['); + } + + // Print the result + if (is_empty() && nested) + printf("Parentheses are nested properly."); + else + printf("Parentheses aren't nested properly."); + + return 0; +} + + +void make_empty(void) { + top = 0; +} + +bool is_empty(void) { + return top == 0; +} + +bool is_full(void) { + return top == STACK_SIZE; +} + +void push(char ch) { + if (is_full()) + stack_overflow(); + + contents[top++] = ch; +} + +char pop(void) { + if (is_empty()) + stack_underflow(); + + return contents[--top]; +} + +void stack_overflow(void) { + printf("Stack overflow!"); + exit(EXIT_FAILURE); +} + +void stack_underflow(void) { + nested = false; +} diff --git a/10_Program_Organization/Projects/pr_02.c b/10_Program_Organization/Projects/pr_02.c new file mode 100644 index 0000000..d2b05c0 --- /dev/null +++ b/10_Program_Organization/Projects/pr_02.c @@ -0,0 +1,164 @@ +/* Classifies a poker hand, poker.c modified */ + +#include +#include +#include + +#define NUM_RANKS 13 +#define NUM_SUITS 4 +#define NUM_CARDS 5 + +// External variable +bool straight, flush, four, three; +int pairs; // Can be 0, 1 or 2 + +// Prototypes +void read_cards(int num_in_rank[NUM_RANKS], int num_in_suit[NUM_SUITS]); +void analyze_hand(int num_in_rank[NUM_RANKS], int num_in_suit[NUM_SUITS]); +void print_result(void); + +int main (void) { + int num_in_rank[NUM_RANKS]; + int num_in_suit[NUM_SUITS]; + + while (1) { + read_cards(num_in_rank, num_in_suit); + analyze_hand(num_in_rank, num_in_suit); + print_result(); + } +} + +// Reads the card into external variables +void read_cards(int num_in_rank[NUM_RANKS], int num_in_suit[NUM_SUITS]) { + bool card_exists[NUM_RANKS][NUM_SUITS]; + char ch, rank_ch, suit_ch; + int rank, suit; + bool bad_card; + int cards_read = 0; + + for (rank = 0; rank < NUM_RANKS; rank++) { + num_in_rank[rank] = 0; + for (suit = 0; suit < NUM_SUITS; suit++) + card_exists[rank][suit] = false; + } + + for (suit = 0; suit < NUM_SUITS; suit++) + num_in_suit[suit] = 0; + + while (cards_read < NUM_CARDS) { + bad_card = false; + + printf("Enter a card: "); + + rank_ch = getchar(); + switch (rank_ch) { + case '0': exit(EXIT_SUCCESS); + case '2': rank = 0; break; + case '3': rank = 1; break; + case '4': rank = 2; break; + case '5': rank = 3; break; + case '6': rank = 4; break; + case '7': rank = 5; break; + case '8': rank = 6; break; + case '9': rank = 7; break; + case 't': case 'T': rank = 8; break; + case 'j': case 'J': rank = 9; break; + case 'q': case 'Q': rank = 10; break; + case 'k': case 'K': rank = 11; break; + case 'a': case 'A': rank = 12; break; + default: bad_card = true; + } + + suit_ch = getchar(); + switch (suit_ch) { + case 'c': case 'C': suit = 0; break; + case 'd': case 'D': suit = 1; break; + case 'h': case 'H': suit = 2; break; + case 's': case 'S': suit = 3; break; + default: bad_card = true; + } + + while ((ch = getchar()) != '\n') + if (ch != ' ') + bad_card = true; + + if (bad_card) + printf("Bad card; ignored.\n"); + else if (card_exists[rank][suit]) + printf("Duplicate card; ignored.\n"); + else { + num_in_rank[rank]++; + num_in_suit[suit]++; + card_exists[rank][suit] = true; + cards_read++; + } + } +} + +void analyze_hand(int num_in_rank[NUM_RANKS], int num_in_suit[NUM_SUITS]) { + int num_consec = 0; + int rank, suit; + + straight = false; + flush = false; + four = false; + three = false; + pairs = 0; + + // Check for flush + for (suit = 0; suit < NUM_SUITS; suit++) + if (num_in_suit[suit] == NUM_CARDS) + flush = true; + + // Check for straight + rank = 0; + while (num_in_rank[rank] == 0) + rank++; + for (; rank < NUM_RANKS && num_in_rank[rank] > 0; rank++) + num_consec++; + if (num_consec == NUM_CARDS) { + straight = true; + return; + } + + // Check for 4-of-a-kind, 3-of-a-kind and pairs + for (rank = 0; rank < NUM_RANKS; rank++) { + if (num_in_rank[rank] == 4) + four = true; + if (num_in_rank[rank] == 3) + three = true; + if (num_in_rank[rank] == 2) + pairs++; + + } +} + +void print_result(void) { + if (straight && flush) + printf("Straight flush"); + else if (four) + printf("Four of a kind"); + else if (three && pairs == 1) + printf("Full house"); + else if (flush) + printf("Flush"); + else if (straight) + printf("Straight"); + else if (three) + printf("Three of a kind"); + else if (pairs == 2) + printf("Two pairs"); + else if (pairs == 1) + printf("Pair"); + else + printf("High card"); + + printf("\n\n"); +} + + + + + + + diff --git a/10_Program_Organization/Projects/pr_03.c b/10_Program_Organization/Projects/pr_03.c new file mode 100644 index 0000000..6b05722 --- /dev/null +++ b/10_Program_Organization/Projects/pr_03.c @@ -0,0 +1,191 @@ +#include /* C99 only */ +#include +#include + +#define NUM_CARDS 5 +#define RANK 0 +#define SUIT 1 + +/* external variables */ +int hand[NUM_CARDS][2]; +/* 0 1 + ____ ____ + 0 |____|____| + 1 |____|____| + 2 |____|____| + 3 |____|____| + 4 |____|____| + rank suit +*/ + +bool straight, flush, four, three; +int pairs; /* can be 0, 1, or 2 */ + +/* prototypes */ +void read_cards(void); +void analyze_hand(void); +void print_result(void); + +/********************************************************** + * main: Calls read_cards, analyze_hand, and print_result * + * repeatedly. * + **********************************************************/ +int main(void) +{ + for (;;) { + read_cards(); + analyze_hand(); + print_result(); + } +} + +/********************************************************** + * read_cards: Reads the cards into the external variable * + * hand; checks for bad cards and duplicate * + * cards. * + **********************************************************/ +void read_cards(void) +{ + char ch, rank_ch, suit_ch; + int i, rank, suit; + bool bad_card, duplicate_card; + int cards_read = 0; + + while (cards_read < NUM_CARDS) { + bad_card = false; + + printf("Enter a card: "); + + rank_ch = getchar(); + switch (rank_ch) { + case '0': exit(EXIT_SUCCESS); + case '2': rank = 0; break; + case '3': rank = 1; break; + case '4': rank = 2; break; + case '5': rank = 3; break; + case '6': rank = 4; break; + case '7': rank = 5; break; + case '8': rank = 6; break; + case '9': rank = 7; break; + case 't': case 'T': rank = 8; break; + case 'j': case 'J': rank = 9; break; + case 'q': case 'Q': rank = 10; break; + case 'k': case 'K': rank = 11; break; + case 'a': case 'A': rank = 12; break; + default: bad_card = true; + } + + suit_ch = getchar(); + switch (suit_ch) { + case 'c': case 'C': suit = 0; break; + case 'd': case 'D': suit = 1; break; + case 'h': case 'H': suit = 2; break; + case 's': case 'S': suit = 3; break; + default: bad_card = true; + } + + while ((ch = getchar()) != '\n') + if (ch != ' ') bad_card = true; + + if (bad_card) { + printf("Bad card; ignored.\n"); + continue; + } + + duplicate_card = false; + for (i = 0; i < cards_read; i++) + if (hand[i][RANK] == rank && hand[i][SUIT] == suit) { + printf("Duplicate card; ignored.\n"); + duplicate_card = true; + break; + } + + if (!duplicate_card) { + hand[cards_read][RANK] = rank; + hand[cards_read][SUIT] = suit; + cards_read++; + } + } +} + +/********************************************************** + * analyze_hand: Determines whether the hand contains a * + * straight, a flush, four-of-a-kind, * + * and/or three-of-a-kind; determines the * + * number of pairs; stores the results into * + * the external variables straight, flush, * + * four, three, and pairs. * + **********************************************************/ +void analyze_hand(void) +{ + int rank, suit, card, pass, run; + + straight = true; + flush = true; + four = false; + three = false; + pairs = 0; + + /* sort cards by rank */ + for (pass = 1; pass < NUM_CARDS; pass++) + for (card = 0; card < NUM_CARDS - pass; card++) { + rank = hand[card][RANK]; + suit = hand[card][SUIT]; + if (hand[card+1][RANK] < rank) { + hand[card][RANK] = hand[card+1][RANK]; + hand[card][SUIT] = hand[card+1][SUIT]; + hand[card+1][RANK] = rank; + hand[card+1][SUIT] = suit; + } + } + + /* check for flush */ + suit = hand[0][SUIT]; + for (card = 1; card < NUM_CARDS; card++) + if (hand[card][SUIT] != suit) + flush = false; + + /* check for straight */ + for (card = 0; card < NUM_CARDS - 1; card++) + if (hand[card][RANK] + 1 != hand[card+1][RANK]) + straight = false; + + /* check for 4-of-a-kind, 3-of-a-kind, and pairs by + looking for "runs" of cards with identical ranks */ + card = 0; + while (card < NUM_CARDS) { + rank = hand[card][RANK]; + run = 0; + do { + run++; + card++; + } while (card < NUM_CARDS && hand[card][RANK] == rank); + switch (run) { + case 2: pairs++; break; + case 3: three = true; break; + case 4: four = true; break; + } + } +} + +/********************************************************** + * print_result: Prints the classification of the hand, * + * based on the values of the external * + * variables straight, flush, four, three, * + * and pairs. * + **********************************************************/ +void print_result(void) +{ + if (straight && flush) printf("Straight flush"); + else if (four) printf("Four of a kind"); + else if (three && + pairs == 1) printf("Full house"); + else if (flush) printf("Flush"); + else if (straight) printf("Straight"); + else if (three) printf("Three of a kind"); + else if (pairs == 2) printf("Two pairs"); + else if (pairs == 1) printf("Pair"); + else printf("High card"); + + printf("\n\n"); +} diff --git a/10_Program_Organization/Projects/pr_04.c b/10_Program_Organization/Projects/pr_04.c new file mode 100644 index 0000000..ba8fe67 --- /dev/null +++ b/10_Program_Organization/Projects/pr_04.c @@ -0,0 +1,169 @@ +/* Classifies a poker hand */ + +#include +#include +#include + +#define NUM_RANKS 13 +#define NUM_SUITS 4 +#define NUM_CARDS 5 + +// External variable +int num_in_rank[NUM_RANKS]; +int num_in_suit[NUM_SUITS]; +bool royal, straight, flush, four, three; +int pairs; // Can be 0, 1 or 2 + +// Prototypes +void read_cards(void); +void analyze_hand(void); +void print_result(void); + +int main (void) { + while (1) { + read_cards(); + analyze_hand(); + print_result(); + } +} + +// Reads the card into external variables +void read_cards(void) { + bool card_exists[NUM_RANKS][NUM_SUITS]; + char ch, rank_ch, suit_ch; + int rank, suit; + bool bad_card; + int cards_read = 0; + + for (rank = 0; rank < NUM_RANKS; rank++) { + num_in_rank[rank] = 0; + for (suit = 0; suit < NUM_SUITS; suit++) + card_exists[rank][suit] = false; + } + + for (suit = 0; suit < NUM_SUITS; suit++) + num_in_suit[suit] = 0; + + while (cards_read < NUM_CARDS) { + bad_card = false; + + printf("Enter a card: "); + + rank_ch = getchar(); + switch (rank_ch) { + case '0': exit(EXIT_SUCCESS); + case '2': rank = 0; break; + case '3': rank = 1; break; + case '4': rank = 2; break; + case '5': rank = 3; break; + case '6': rank = 4; break; + case '7': rank = 5; break; + case '8': rank = 6; break; + case '9': rank = 7; break; + case 't': case 'T': rank = 8; break; + case 'j': case 'J': rank = 9; break; + case 'q': case 'Q': rank = 10; break; + case 'k': case 'K': rank = 11; break; + case 'a': case 'A': rank = 12; break; + default: bad_card = true; + } + + suit_ch = getchar(); + switch (suit_ch) { + case 'c': case 'C': suit = 0; break; + case 'd': case 'D': suit = 1; break; + case 'h': case 'H': suit = 2; break; + case 's': case 'S': suit = 3; break; + default: bad_card = true; + } + + while ((ch = getchar()) != '\n') + if (ch != ' ') + bad_card = true; + + if (bad_card) + printf("Bad card; ignored.\n"); + else if (card_exists[rank][suit]) + printf("Duplicate card; ignored.\n"); + else { + num_in_rank[rank]++; + num_in_suit[suit]++; + card_exists[rank][suit] = true; + cards_read++; + } + } +} + +void analyze_hand(void) { + int num_consec = 0; + int rank, suit; + + royal = false; + straight = false; + flush = false; + four = false; + three = false; + pairs = 0; + + // Check for flush + for (suit = 0; suit < NUM_SUITS; suit++) + if (num_in_suit[suit] == NUM_CARDS) + flush = true; + + // Check for straight + rank = 0; + while (num_in_rank[rank] == 0) + rank++; + for (; rank < NUM_RANKS && num_in_rank[rank] > 0; rank++) + num_consec++; + if (num_consec == NUM_CARDS) { + straight = true; + // Check for royal + if (rank == 13) + royal = true; + return; + } + + // Check for 4-of-a-kind, 3-of-a-kind and pairs + for (rank = 0; rank < NUM_RANKS; rank++) { + if (num_in_rank[rank] == 4) + four = true; + if (num_in_rank[rank] == 3) + three = true; + if (num_in_rank[rank] == 2) + pairs++; + + } +} + +void print_result(void) { + if (royal && flush) + printf("Royal flush"); + else if (straight && flush) + printf("Straight flush"); + else if (four) + printf("Four of a kind"); + else if (three && pairs == 1) + printf("Full house"); + else if (flush) + printf("Flush"); + else if (straight) + printf("Straight"); + else if (three) + printf("Three of a kind"); + else if (pairs == 2) + printf("Two pairs"); + else if (pairs == 1) + printf("Pair"); + else + printf("High card"); + + printf("\n\n"); +} + + + + + + + diff --git a/10_Program_Organization/Projects/pr_05.c b/10_Program_Organization/Projects/pr_05.c new file mode 100644 index 0000000..9b50f20 --- /dev/null +++ b/10_Program_Organization/Projects/pr_05.c @@ -0,0 +1,173 @@ +#include /* C99 only */ +#include +#include + +#define NUM_RANKS 13 +#define NUM_SUITS 4 +#define NUM_CARDS 5 + +/* external variables */ +int num_in_rank[NUM_RANKS]; +int num_in_suit[NUM_SUITS]; +bool straight, flush, four, three; +int pairs; /* can be 0, 1, or 2 */ + +/* prototypes */ +void read_cards(void); +void analyze_hand(void); +void print_result(void); + +/********************************************************** + * main: Calls read_cards, analyze_hand, and print_result * + * repeatedly. * + **********************************************************/ +int main(void) +{ + for (;;) { + read_cards(); + analyze_hand(); + print_result(); + } +} + +/********************************************************** + * read_cards: Reads the cards into the external * + * variables num_in_rank and num_in_suit; * + * checks for bad cards and duplicate cards. * + **********************************************************/ +void read_cards(void) +{ + bool card_exists[NUM_RANKS][NUM_SUITS]; + char ch, rank_ch, suit_ch; + int rank, suit; + bool bad_card; + int cards_read = 0; + + for (rank = 0; rank < NUM_RANKS; rank++) { + num_in_rank[rank] = 0; + for (suit = 0; suit < NUM_SUITS; suit++) + card_exists[rank][suit] = false; + } + + for (suit = 0; suit < NUM_SUITS; suit++) + num_in_suit[suit] = 0; + + while (cards_read < NUM_CARDS) { + bad_card = false; + + printf("Enter a card: "); + + rank_ch = getchar(); + switch (rank_ch) { + case '0': exit(EXIT_SUCCESS); + case '2': rank = 0; break; + case '3': rank = 1; break; + case '4': rank = 2; break; + case '5': rank = 3; break; + case '6': rank = 4; break; + case '7': rank = 5; break; + case '8': rank = 6; break; + case '9': rank = 7; break; + case 't': case 'T': rank = 8; break; + case 'j': case 'J': rank = 9; break; + case 'q': case 'Q': rank = 10; break; + case 'k': case 'K': rank = 11; break; + case 'a': case 'A': rank = 12; break; + default: bad_card = true; + } + + suit_ch = getchar(); + switch (suit_ch) { + case 'c': case 'C': suit = 0; break; + case 'd': case 'D': suit = 1; break; + case 'h': case 'H': suit = 2; break; + case 's': case 'S': suit = 3; break; + default: bad_card = true; + } + + while ((ch = getchar()) != '\n') + if (ch != ' ') bad_card = true; + + if (bad_card) + printf("Bad card; ignored.\n"); + else if (card_exists[rank][suit]) + printf("Duplicate card; ignored.\n"); + else { + num_in_rank[rank]++; + num_in_suit[suit]++; + card_exists[rank][suit] = true; + cards_read++; + } + } +} + +/********************************************************** + * analyze_hand: Determines whether the hand contains a * + * straight, a flush, four-of-a-kind, * + * and/or three-of-a-kind; determines the * + * number of pairs; stores the results into * + * the external variables straight, flush, * + * four, three, and pairs. * + **********************************************************/ +void analyze_hand(void) +{ + int num_consec = 0; + int rank, suit; + + straight = false; + flush = false; + four = false; + three = false; + pairs = 0; + + /* check for flush */ + for (suit = 0; suit < NUM_SUITS; suit++) + if (num_in_suit[suit] == NUM_CARDS) + flush = true; + + /* check for straight */ + rank = 0; + while (num_in_rank[rank] == 0) rank++; + for (; rank < NUM_RANKS && num_in_rank[rank] > 0; rank++) + num_consec++; + if (num_consec == NUM_CARDS) { + straight = true; + return; + } + + /* check for ace-low straight */ + if (num_consec == NUM_CARDS - 1 && + num_in_rank[0] > 0 && num_in_rank[NUM_RANKS-1] > 0) { + straight = true; + return; + } + + /* check for 4-of-a-kind, 3-of-a-kind, and pairs */ + for (rank = 0; rank < NUM_RANKS; rank++) { + if (num_in_rank[rank] == 4) four = true; + if (num_in_rank[rank] == 3) three = true; + if (num_in_rank[rank] == 2) pairs++; + } +} + +/********************************************************** + * print_result: Prints the classification of the hand, * + * based on the values of the external * + * variables straight, flush, four, three, * + * and pairs. * + **********************************************************/ +void print_result(void) +{ + if (straight && flush) printf("Straight flush"); + else if (four) printf("Four of a kind"); + else if (three && + pairs == 1) printf("Full house"); + else if (flush) printf("Flush"); + else if (straight) printf("Straight"); + else if (three) printf("Three of a kind"); + else if (pairs == 2) printf("Two pairs"); + else if (pairs == 1) printf("Pair"); + else printf("High card"); + + printf("\n\n"); +} diff --git a/10_Program_Organization/Projects/pr_06.c b/10_Program_Organization/Projects/pr_06.c new file mode 100644 index 0000000..ba042f8 --- /dev/null +++ b/10_Program_Organization/Projects/pr_06.c @@ -0,0 +1,96 @@ +/* RPN Reverse polish notation with stack */ + +#include +#include +#include +#include + + + +#define STACK_SIZE 100 + +/* external variables */ +int contents[STACK_SIZE]; +int top = 0; + + +void make_empty(void); +bool is_empty(void); +bool is_full(void); +void push(int ch); +int pop(void); +void stack_overflow(void); +void stack_underflow(void); + + +int main(void) { + char ch = 0; + int temp; + + while (ch != 'q') { + printf("Enter an RPN expression: "); + while (1) { + scanf(" %c", &ch); + if (ch == '=' || ch == 'q') + break; + // Operand found (+ and * are comutative) + if (isdigit((int)ch)) + push(ch - '0'); + else if (ch == '+') + push(pop() + pop()); + else if (ch == '-') { + temp = pop(); + push(pop() - temp); + } + else if (ch == '*') + push(pop() * pop()); + else if (ch == '/'){ + temp = pop(); + push(pop() / temp); + } + + } + printf("Value of expression: %d\n", pop()); + make_empty(); + } + + return 0; +} + + + +void make_empty(void) { + top = 0; +} + +bool is_empty(void) { + return top == 0; +} + +bool is_full(void) { + return top == STACK_SIZE; +} + +void push(int ch) { + if (is_full()) + stack_overflow(); + + contents[top++] = ch; +} + +int pop(void) { + if (is_empty()) + stack_underflow(); + + return contents[--top]; +} + +void stack_overflow(void) { + printf("The expression is too complex!"); + exit(EXIT_FAILURE); +} + +void stack_underflow(void) { + printf("Not enough operands in expression!"); + exit(EXIT_FAILURE); +} diff --git a/10_Program_Organization/Projects/pr_07 b/10_Program_Organization/Projects/pr_07 new file mode 100644 index 0000000..c47b1d9 Binary files /dev/null and b/10_Program_Organization/Projects/pr_07 differ diff --git a/10_Program_Organization/Projects/pr_07.c b/10_Program_Organization/Projects/pr_07.c new file mode 100644 index 0000000..e2d92e7 --- /dev/null +++ b/10_Program_Organization/Projects/pr_07.c @@ -0,0 +1,87 @@ +#include +#include + +#define MAX_DIGITS 10 + + +char digits[3][MAX_DIGITS * 4]; + +const int segments[10][7] = { + {1, 1, 1, 1, 1, 1, 0}, // 0 + {0, 1, 1, 0, 0, 0, 0}, // 1 + {1, 1, 0, 1, 1, 0, 1}, // 2 + {1, 1, 1, 1, 0, 0, 1}, // 3 + {0, 1, 1, 0, 0, 1, 1}, // 4 + {1, 0, 1, 1, 0, 1, 1}, // 5 + {1, 0, 1, 1, 1, 1, 1}, // 6 + {1, 1, 1, 0, 0, 0, 0}, // 7 + {1, 1, 1, 1, 1, 1, 1}, // 8 + {1, 1, 1, 1, 0, 1, 1} // 9 +}; + + +void clear_digits_array(void); +void process_digit(int digit, int position); +void print_digits_array(void); + +int main(void) { + clear_digits_array(); + + int i; + char ch; + printf("Enter a number: "); + for (i = 0; i < MAX_DIGITS; ) { + ch = getchar(); + if (isdigit(ch)) { + process_digit(ch - '0', i); + i++; + } + } + + print_digits_array(); + + return 0; +} + +void clear_digits_array(void) { + int r, c; + for (r = 0; r < 3; r++) + for (c = 0; c < MAX_DIGITS * 4; c++) + digits[r][c] = ' '; +} + +void process_digit(int digit, int position) { + int r, c; + for (c = position * 4; c < (position * 4 + 4); c++) { + // In first row, everywhere but top of certain digits is a space + r = 0; + if (c % 4 == 1 && segments[digit][0]) + digits[r][c] = '_'; + + // In second row + r = 1; + if ((c % 4 == 0 && segments[digit][5]) || + (c % 4 == 2 && segments[digit][1])) + digits[r][c] = '|'; + else if (c % 4 == 1 && segments[digit][6]) + digits[r][c] = '_'; + + // In third row + r = 2; + if ((c % 4 == 0 && segments[digit][4]) || + (c % 4 == 2 && segments[digit][2])) + digits[r][c] = '|'; + else if (c % 4 == 1 && segments[digit][3]) + digits[r][c] = '_'; + + } +} + +void print_digits_array(void) { + int r, c; + for (r = 0; r < 3; r++) { + for (c = 0; c < MAX_DIGITS * 4; c++) + putchar(digits[r][c]); + putchar('\n'); + } +} diff --git a/11_Pointers/.settings/org.eclipse.cdt.codan.core.prefs b/11_Pointers/.settings/org.eclipse.cdt.codan.core.prefs new file mode 100644 index 0000000..0710d38 --- /dev/null +++ b/11_Pointers/.settings/org.eclipse.cdt.codan.core.prefs @@ -0,0 +1,65 @@ +eclipse.preferences.version=1 +org.eclipse.cdt.codan.checkers.errnoreturn=Warning +org.eclipse.cdt.codan.checkers.errnoreturn.params={implicit\=>false} +org.eclipse.cdt.codan.checkers.errreturnvalue=Error +org.eclipse.cdt.codan.checkers.errreturnvalue.params={} +org.eclipse.cdt.codan.checkers.noreturn=Error +org.eclipse.cdt.codan.checkers.noreturn.params={implicit\=>false} +org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=Error +org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=Error +org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=Warning +org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={} +org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=Error +org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={} +org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=Warning +org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} +org.eclipse.cdt.codan.internal.checkers.CatchByReference=Warning +org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={unknown\=>false,exceptions\=>()} +org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=Error +org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=Error +org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=Error +org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.InvalidArguments=Error +org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=Error +org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=Error +org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=Error +org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=Error +org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info +org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} +org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=Warning +org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={} +org.eclipse.cdt.codan.internal.checkers.OverloadProblem=Error +org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=Error +org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=Error +org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning +org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={} +org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning +org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={} +org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=Warning +org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={macro\=>true,exceptions\=>()} +org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=Warning +org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={paramNot\=>false} +org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=Warning +org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={else\=>false,afterelse\=>false} +org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=Error +org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} +org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=Warning +org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={macro\=>true} +org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=Warning +org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={macro\=>true} +org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=Warning +org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={macro\=>true,exceptions\=>("@(\#)","$Id")} +org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=Error +org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} diff --git a/11_Pointers/Debug/11_Pointers b/11_Pointers/Debug/11_Pointers new file mode 100644 index 0000000..b7ce0aa Binary files /dev/null and b/11_Pointers/Debug/11_Pointers differ diff --git a/11_Pointers/Debug/Examples/subdir.mk b/11_Pointers/Debug/Examples/subdir.mk new file mode 100644 index 0000000..a0c0d5d --- /dev/null +++ b/11_Pointers/Debug/Examples/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Examples/maxmin.c + +OBJS += \ +./Examples/maxmin.o + +C_DEPS += \ +./Examples/maxmin.d + + +# Each subdirectory must supply rules for building sources it contributes +Examples/%.o: ../Examples/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/11_Pointers/Debug/Projects/pr_01.d b/11_Pointers/Debug/Projects/pr_01.d new file mode 100644 index 0000000..e5c7a50 --- /dev/null +++ b/11_Pointers/Debug/Projects/pr_01.d @@ -0,0 +1 @@ +Projects/pr_01.d: ../Projects/pr_01.c diff --git a/11_Pointers/Debug/Projects/pr_01.o b/11_Pointers/Debug/Projects/pr_01.o new file mode 100644 index 0000000..ab1c51d Binary files /dev/null and b/11_Pointers/Debug/Projects/pr_01.o differ diff --git a/11_Pointers/Debug/Projects/subdir.mk b/11_Pointers/Debug/Projects/subdir.mk new file mode 100644 index 0000000..5537d67 --- /dev/null +++ b/11_Pointers/Debug/Projects/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_01.c + +OBJS += \ +./Projects/pr_01.o + +C_DEPS += \ +./Projects/pr_01.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/%.o: ../Projects/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/11_Pointers/Debug/makefile b/11_Pointers/Debug/makefile new file mode 100644 index 0000000..89e3ffa --- /dev/null +++ b/11_Pointers/Debug/makefile @@ -0,0 +1,44 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include Projects/subdir.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 11_Pointers + +# Tool invocations +11_Pointers: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "11_Pointers" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 11_Pointers + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/11_Pointers/Examples/maxmin.c b/11_Pointers/Examples/maxmin.c new file mode 100644 index 0000000..c52aace --- /dev/null +++ b/11_Pointers/Examples/maxmin.c @@ -0,0 +1,41 @@ +/* Finds the largest and smallest elements in array + * + * maxmin.c + * + * Created on: Jun 9, 2013 + * Author: delmadord + */ + +#include + +#define N 10 + +void max_min(int a[], int n, int *max, int *min); + +int main(void) { + int b[N], i, big, small; + + printf("Enter %d numbers: ", N); + for (i = 0; i < N; i++) + scanf("%d", &b[i]); + + max_min(b, N, &big, &small); + + printf("Largest: %d\n", big); + printf("Smallest: %d\n", small); + + return 0; +} + + +void max_min(int a[], int n, int *max, int *min) { + int i; + + *max = *min = a[0]; + for (i = 1; i < n; i++) { + if (a[i] > *max) + *max = a[i]; + else if (a[i] < *min) + *min = a[i]; + } +} diff --git a/11_Pointers/Exercises/main.c b/11_Pointers/Exercises/main.c new file mode 100644 index 0000000..5e8a88c --- /dev/null +++ b/11_Pointers/Exercises/main.c @@ -0,0 +1,106 @@ +/* + * main.c + * + * Created on: Jun 9, 2013 + * Author: delmadord + */ + +#include + + + +void ex_01(void); +void ex_02(void); +// ex_03 +void avg_sum(double a[], int n, double *avg, double *sum); +// ex_04 +void swap(int *p, int *q); +// ex_05 +void split_time(long total_sec, int *hr, int *min, int *sec); +// ex_06 +void find_two_largest(int a[], int n, int *largest, int *slargest); +// ex_07 +void split_date(int day_of_year, int year, int *month, int *day); +void *find_largest(int a[], int n); + + + +int main(void) { + int a[] = {12, 1, 4, 2, 9}; + + printf("%d is largest", find_largest(a, 5)); + + return 0; +} + + + +void ex_01(void) { + // a, c, d, g, h seems ok to me +} + +void ex_02(void) { + // e, f, i are ok +} + +void avg_sum(double a[], int n, double *avg, double *sum) { + int i; + + *sum = 0.0; + for (i = 0; i < n; i++) + *sum += a[i]; + *avg = *sum / n; +} + +void swap(int *p, int *q) { + int temp = *p; + *p = *q; + *q = temp; +} + +void split_time(long total_sec, int *hr, int *min, int *sec) { + *hr = total_sec / 3600; + total_sec %= 3600; + *min = total_sec / 60; + *sec = total_sec % 60; +} + +void find_two_largest(int a[], int n, int *largest, int *slargest) { + int i; + + if (a[0] > a[1]) { + *largest = a[0]; + *slargest = a[1]; + } else { + *largest = a[1]; + *slargest = a[0]; + } + + for (i = 2; i < n; i++) + if (a[i] > *largest) { + *slargest = *largest; + *largest = a[i]; + } else if (a[i] > *slargest) + *slargest = a[i]; +} + +void split_date(int day_of_year, int year, int *month, int *day) { + int feb = (year % 4 == 0) ? 29 : 28; + int days_in_months[] = {0, + 31, feb, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; + + *day = day_of_year; + for (*month = 1; *day > days_in_months[*month]; (*month)++) { + *day -= days_in_months[*month]; + } +} + +void *find_largest(int a[], int n) { + int i, *largest = &a[0]; + for (i = 0; i < n; i++) + if (a[i] > *largest) + largest = &a[i]; + return *largest; +} + diff --git a/11_Pointers/Exercises/main.c~ b/11_Pointers/Exercises/main.c~ new file mode 100644 index 0000000..615c8c7 --- /dev/null +++ b/11_Pointers/Exercises/main.c~ @@ -0,0 +1,106 @@ +/* + * main.c + * + * Created on: Jun 9, 2013 + * Author: delmadord + */ + +#include + + + +void ex_01(void); +void ex_02(void); +// ex_03 +void avg_sum(double a[], int n, double *avg, double *sum); +// ex_04 +void swap(int *p, int *q); +// ex_05 +void split_time(long total_sec, int *hr, int *min, int *sec); +// ex_06 +void find_two_largest(int a[], int n, int *largest, int *slargest); +// ex_07 +void spit_date(int day_of_year, int year, int *month, int *day); +void *find_largest(int a[], int n); + + + +int main(void) { + int a[] = {12, 1, 4, 2, 9}; + + printf("%d is largest", find_largest(a, 5)); + + return 0; +} + + + +void ex_01(void) { + // a, c, d, g, h seems ok to me +} + +void ex_02(void) { + // e, f, i are ok +} + +void avg_sum(double a[], int n, double *avg, double *sum) { + int i; + + *sum = 0.0; + for (i = 0; i < n; i++) + *sum += a[i]; + *avg = *sum / n; +} + +void swap(int *p, int *q) { + int temp = *p; + *p = *q; + *q = temp; +} + +void split_time(long total_sec, int *hr, int *min, int *sec) { + *hr = total_sec / 3600; + total_sec %= 3600; + *min = total_sec / 60; + *sec = total_sec % 60; +} + +void find_two_largest(int a[], int n, int *largest, int *slargest) { + int i; + + if (a[0] > a[1]) { + *largest = a[0]; + *slargest = a[1]; + } else { + *largest = a[1]; + *slargest = a[0]; + } + + for (i = 2; i < n; i++) + if (a[i] > *largest) { + *slargest = *largest; + *largest = a[i]; + } else if (a[i] > *slargest) + *slargest = a[i]; +} + +void spit_date(int day_of_year, int year, int *month, int *day) { + int feb = (year % 4 == 0) ? 29 : 28; + int days_in_months[] = {0, + 31, feb, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; + + *day = day_of_year; + for (*month = 1; *day > days_in_months[*month]; (*month)++) { + *day -= days_in_months[*month]; + } +} + +void *find_largest(int a[], int n) { + int i, *largest = &a[0]; + for (i = 0; i < n; i++) + if (a[i] > *largest) + largest = &a[i]; + return *largest; +} + diff --git a/11_Pointers/Projects/pr_01.c b/11_Pointers/Projects/pr_01.c new file mode 100644 index 0000000..9876722 --- /dev/null +++ b/11_Pointers/Projects/pr_01.c @@ -0,0 +1,26 @@ +#include + +void pay_amount(int dollars, int *twenties, int *tens, int *fives, int *ones); + +int main(void) { + int dollars, twenties, tens, fives, ones; + printf("Enter a dollar amount: "); + scanf("%d", &dollars); + pay_amount(dollars, &twenties, &tens, &fives, &ones); + printf("\n$20 bills: %d\n$10 bills: %d\n $5 bills: %d\n $1 bills: %d", + twenties, tens, fives, ones); + + return 0; + +} + +void pay_amount(int dollars, int *twenties, int *tens, int *fives, int *ones) { + + *twenties = dollars / 20; + dollars -= *twenties * 20; + *tens = dollars / 10; + dollars -= *tens * 10; + *fives = dollars / 5; + dollars -= *fives * 5; + *ones = dollars; +} diff --git a/11_Pointers/Projects/pr_02.c b/11_Pointers/Projects/pr_02.c new file mode 100644 index 0000000..8f8cedf --- /dev/null +++ b/11_Pointers/Projects/pr_02.c @@ -0,0 +1,101 @@ +// DO NOT KNOW WHAT TO DO + +#include + +void find_closest_flight(int desired_time, int *departure_time, + int *arrival_time); + + +// Flight departures +int main(void) { + int hh, mm, entered, closestToken = 0, + closestDistance, distance; + + printf("Enter a 24-hour time: "); + scanf("%2d:%2d", &hh, &mm); + + entered = hh * 60 + mm; + + distance = 480 - entered; + distance = distance >= 0 ? distance : -distance; + closestDistance = distance; + closestToken = 480; + + distance = 583 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 583; + } + + distance = 679 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 679; + } + + distance = 767- entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 767; + } + + distance = 840 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 840; + } + + distance = 945 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 945; + } + + distance = 1140 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 1140; + } + + distance = 1305 - entered; + distance = distance >= 0 ? distance : -distance; + if (distance < closestDistance) { + closestDistance = distance; + closestToken = 1305; + } + + switch (closestToken) { + case 480: + printf("Closest departure time is %2d:%.2d a.m., arriving at %2d:%.2d a.m.", + 8, 0, 10, 16); break; + case 583: + printf("Closest departure time is %2d:%.2d a.m., arriving at %2d:%.2d a.m.", + 9, 43, 11, 52); break; + case 679: + printf("Closest departure time is %2d:%.2d a.m., arriving at %2d:%.2d p.m.", + 11, 19, 1, 31); break; + case 767: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 12, 47, 3, 0); break; + case 840: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 2, 0, 4, 8); break; + case 945: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 3, 45, 5, 55); break; + case 1140: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 7, 0, 9, 20); break; + case 1305: + printf("Closest departure time is %2d:%.2d p.m., arriving at %2d:%.2d p.m.", + 9, 45, 11, 58); break; + } + + return 0; +} diff --git a/11_Pointers/Projects/pr_03.c b/11_Pointers/Projects/pr_03.c new file mode 100644 index 0000000..fa4f1ba --- /dev/null +++ b/11_Pointers/Projects/pr_03.c @@ -0,0 +1,46 @@ +/* + * pr_03.c + * + * Created on: Jun 9, 2013 + * Author: delmadord + */ + +#include + +int gcd(int n, int d); +void reduce(int numerator, int denominator, + int *reduced_numerator, int *reduced_denomirator); + + +// Reduce a fraction to lowest terms +int main(void) { + int n, d, rn, rd; + + printf("Enter a fraction: "); + scanf("%d / %d", &n, &d); + reduce(n, d, &rn, &rd); + printf("In lowest terms: %d/%d\n", rn, rd); + + return 0; +} + + +void reduce(int numerator, int denominator, + int *reduced_numerator, int *reduced_denomirator) { + int GCD = gcd(numerator, denominator); + *reduced_numerator = numerator / GCD; + *reduced_denomirator = denominator / GCD; +} + +// GCD, Euclid algorithm +int gcd(int n, int d) { + int remainder; + + while (d != 0) { + remainder = n % d; + n = d; + d = remainder; + } + + return n; +} diff --git a/11_Pointers/Projects/pr_04.c b/11_Pointers/Projects/pr_04.c new file mode 100644 index 0000000..bf49576 --- /dev/null +++ b/11_Pointers/Projects/pr_04.c @@ -0,0 +1,169 @@ +/* + * pr_04.c + * + * Created on: Jun 9, 2013 + * Author: delmadord + */ + +/* Classifies a poker hand, poker.c modified */ + +#include +#include +#include + +#define NUM_RANKS 13 +#define NUM_SUITS 4 +#define NUM_CARDS 5 + +// Prototypes +void read_cards(int num_in_rank[NUM_RANKS], int num_in_suit[NUM_SUITS]); +void analyze_hand(int num_in_rank[NUM_RANKS], int num_in_suit[NUM_SUITS], + int hand[5]); +void print_result(int hand[5]); + +int main (void) { + int num_in_rank[NUM_RANKS]; + int num_in_suit[NUM_SUITS]; + // Represents straight, flush, 4-of-a-kind, 3-of-a-kind + // and number of pairs + int hand[5] = {0, 0, 0, 0, 0}; + + while (1) { + read_cards(num_in_rank, num_in_suit); + analyze_hand(num_in_rank, num_in_suit, hand); + print_result(hand); + } +} + +// Reads the card into external variables +void read_cards(int num_in_rank[NUM_RANKS], int num_in_suit[NUM_SUITS]) { + bool card_exists[NUM_RANKS][NUM_SUITS]; + char ch, rank_ch, suit_ch; + int rank, suit; + bool bad_card; + int cards_read = 0; + + for (rank = 0; rank < NUM_RANKS; rank++) { + num_in_rank[rank] = 0; + for (suit = 0; suit < NUM_SUITS; suit++) + card_exists[rank][suit] = false; + } + + for (suit = 0; suit < NUM_SUITS; suit++) + num_in_suit[suit] = 0; + + while (cards_read < NUM_CARDS) { + bad_card = false; + + printf("Enter a card: "); + + rank_ch = getchar(); + switch (rank_ch) { + case '0': exit(EXIT_SUCCESS); + case '2': rank = 0; break; + case '3': rank = 1; break; + case '4': rank = 2; break; + case '5': rank = 3; break; + case '6': rank = 4; break; + case '7': rank = 5; break; + case '8': rank = 6; break; + case '9': rank = 7; break; + case 't': case 'T': rank = 8; break; + case 'j': case 'J': rank = 9; break; + case 'q': case 'Q': rank = 10; break; + case 'k': case 'K': rank = 11; break; + case 'a': case 'A': rank = 12; break; + default: bad_card = true; + } + + suit_ch = getchar(); + switch (suit_ch) { + case 'c': case 'C': suit = 0; break; + case 'd': case 'D': suit = 1; break; + case 'h': case 'H': suit = 2; break; + case 's': case 'S': suit = 3; break; + default: bad_card = true; + } + + while ((ch = getchar()) != '\n') + if (ch != ' ') + bad_card = true; + + if (bad_card) + printf("Bad card; ignored.\n"); + else if (card_exists[rank][suit]) + printf("Duplicate card; ignored.\n"); + else { + num_in_rank[rank]++; + num_in_suit[suit]++; + card_exists[rank][suit] = true; + cards_read++; + } + } +} + +void analyze_hand(int num_in_rank[NUM_RANKS], int num_in_suit[NUM_SUITS], + int hand[5]) { + int rank, suit, i, num_consec = 0; + for (i = 0; i < 5; i++) + hand[i] = 0; + + + // Check for flush + for (suit = 0; suit < NUM_SUITS; suit++) + if (num_in_suit[suit] == NUM_CARDS) + hand[1] = 1; + + // Check for straight + rank = 0; + while (num_in_rank[rank] == 0) + rank++; + for (; rank < NUM_RANKS && num_in_rank[rank] > 0; rank++) + num_consec++; + if (num_consec == NUM_CARDS) { + hand[0] = true; + return; + } + + // Check for 4-of-a-kind, 3-of-a-kind and pairs + for (rank = 0; rank < NUM_RANKS; rank++) { + if (num_in_rank[rank] == 4) + hand[2] = true; + if (num_in_rank[rank] == 3) + hand[3] = true; + if (num_in_rank[rank] == 2) + hand[4]++; + + } +} + +void print_result(int hand[5]) { + if (hand[0] && hand[1]) + printf("Straight flush"); + else if (hand[2]) + printf("Four of a kind"); + else if (hand[3] && hand[4] == 1) + printf("Full house"); + else if (hand[1]) + printf("Flush"); + else if (hand[0]) + printf("Straight"); + else if (hand[3]) + printf("Three of a kind"); + else if (hand[4] == 2) + printf("Two pairs"); + else if (hand[4] == 1) + printf("Pair"); + else + printf("High card"); + + printf("\n\n"); +} + + + + + + + + diff --git a/12_Pointers_And_Arrays/Debug/Examples/subdir.mk b/12_Pointers_And_Arrays/Debug/Examples/subdir.mk new file mode 100644 index 0000000..d3597f7 --- /dev/null +++ b/12_Pointers_And_Arrays/Debug/Examples/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Examples/reverse3.c + +OBJS += \ +./Examples/reverse3.o + +C_DEPS += \ +./Examples/reverse3.d + + +# Each subdirectory must supply rules for building sources it contributes +Examples/%.o: ../Examples/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/12_Pointers_And_Arrays/Debug/makefile b/12_Pointers_And_Arrays/Debug/makefile new file mode 100644 index 0000000..e3959e0 --- /dev/null +++ b/12_Pointers_And_Arrays/Debug/makefile @@ -0,0 +1,44 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include Projects/subdir.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 12_Pointers_And_Arrays + +# Tool invocations +12_Pointers_And_Arrays: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "12_Pointers_And_Arrays" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 12_Pointers_And_Arrays + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/12_Pointers_And_Arrays/Examples/reverse3.c b/12_Pointers_And_Arrays/Examples/reverse3.c new file mode 100644 index 0000000..9fbc76f --- /dev/null +++ b/12_Pointers_And_Arrays/Examples/reverse3.c @@ -0,0 +1,26 @@ +/* Reverses a series of numers (pointer version) + * + * reverse3.c + * + * Created on: Jun 9, 2013 + * Author: delmadord + */ + +#include + +#define N 10 + +int main(void) { + int a[N], *p; + + printf("Enter %d numbers: ", N); + for (p = a; p < a + N; p++) + scanf("%d", p); + + printf("In reverse order: "); + for (p = a + N - 1; p >= a; p--) + printf(" %d", *p); + printf("\n"); + + return 0; +} diff --git a/12_Pointers_And_Arrays/Exercises/main.c b/12_Pointers_And_Arrays/Exercises/main.c new file mode 100644 index 0000000..202009b --- /dev/null +++ b/12_Pointers_And_Arrays/Exercises/main.c @@ -0,0 +1,75 @@ +/* + * main.c + * + * Created on: Jun 9, 2013 + * Author: delmadord + */ + +#include +#include + +#define N 10 + +void ex_02(void); +// ex_04 is in ptr_stack.c +// ex_06 +int sum_array(const int a[], int n); +// ex_07 +bool search(const int a[], int n, int key); +// ex_08 +void store_zeros(int a[], int n); +// identical matrix in pointer arithmetic +void ex_13(void); + + +int main(void) { + + + return 0; +} + +void ex_02(void) { + int high, middle, low; + middle = low + (high - low) / 2; +} + +int sum_array(const int a[], int n) { + int *p, sum; + + sum = 0; + for (p = a; p < a + n; p++) + sum += *p; + return sum; +} + +bool search(const int a[], int n, int key) { + int *p; + bool found = false; + + for (p = a; p < a + n; p++) + if (*p == key) + found = true; + + return found; +} + +void store_zeros(int a[], int n) { + int *p; + for (p = a; p < a + n; p++) + *p = 0; +} + +void ex_13(void) { + double ident[N][N], *p; + int num_zeros = N; + + for (p = &ident[0][0]; p <= &ident[N - 1][N - 1]; p++) + if (num_zeros == N) { + *p = 1.0; + num_zeros = 0; + } + else { + *p = 0.0; + num_zeros++; + } +} diff --git a/12_Pointers_And_Arrays/Exercises/ptr_stack.c b/12_Pointers_And_Arrays/Exercises/ptr_stack.c new file mode 100644 index 0000000..02a6749 --- /dev/null +++ b/12_Pointers_And_Arrays/Exercises/ptr_stack.c @@ -0,0 +1,53 @@ +/* + * ptr_stack.c + * + * Created on: Jun 9, 2013 + * Author: delmadord + */ + +#include + +#define STACK_SIZE 100 + +int *top_ptr; +int contents[STACK_SIZE]; + + + +void push(int i); +int pop(void); +void make_empty(void); +bool is_empty(void); +bool is_full(void); + +int main(void) { + + return 0; +} + + +void push(int i) { + if (is_full()) + stack_overflow(); + else + *top_ptr++ = i; +} + +int pop(void) { + if (is_empty()) + stack_underflow(); + else + return *--top_ptr; +} + +void make_empty(void) { + top_ptr = &contents[0]; +} + +bool is_empty(void) { + return top_ptr = &contents[0]; +} + +bool is_full(void) { + return top_ptr == &contents[STACK_SIZE]; +} diff --git a/12_Pointers_And_Arrays/Projects/pr_01.c b/12_Pointers_And_Arrays/Projects/pr_01.c new file mode 100644 index 0000000..4e51b1a --- /dev/null +++ b/12_Pointers_And_Arrays/Projects/pr_01.c @@ -0,0 +1,26 @@ +/* + * pr_01.c + * + * Created on: Jun 9, 2013 + * Author: delmadord + */ + + +#include + + +#define N 100 + +int main(void) { + char ch, sentence[N], *p = sentence; + printf("Enter a message: "); + while ((ch = getchar()) != '\n' && p < sentence + N) { + *p++ = ch; + } + + printf("Reversal is: "); + for (p--; p >= sentence; p--) + putchar(*p); + + return 0; +} diff --git a/12_Pointers_And_Arrays/Projects/pr_02.c b/12_Pointers_And_Arrays/Projects/pr_02.c new file mode 100644 index 0000000..e67066e --- /dev/null +++ b/12_Pointers_And_Arrays/Projects/pr_02.c @@ -0,0 +1,33 @@ +/* + * pr_02.c + * + * Created on: Jun 9, 2013 + * Author: delmadord + */ + +#include +#include +#include + +#define N 100 + +int main(void) { + char ch, sentence[N], *p = sentence, *q; + printf("Enter a message: "); + while ((ch = getchar()) != '\n' && p < sentence + N) { + if (isalpha(ch)) + *p++ = tolower(ch); + } + + bool palindrome = true; + for (p--, q = sentence; p >= sentence && palindrome; p--, q++) + palindrome = *p == *q; + + if (palindrome) + printf("Palinrome"); + else + printf("Not a palindrome"); + + return 0; +} + diff --git a/12_Pointers_And_Arrays/Projects/pr_05.c b/12_Pointers_And_Arrays/Projects/pr_05.c new file mode 100644 index 0000000..8f5b9cf --- /dev/null +++ b/12_Pointers_And_Arrays/Projects/pr_05.c @@ -0,0 +1,41 @@ +/* + * pr_05.c + * + * Created on: Jun 10, 2013 + * Author: delmadord + */ + +// NOT WORKING - crappy project + + +#include + +// Reverse words in sentence +int main(void) { + char ch, sentence[50], terminating, *p = sentence, *q, *r; + + printf("Enter a sentence: "); +// Insert words into array + ch = getchar(); + while (ch != '.' && ch != '!' && ch != '?') { + *p++ = ch; + ch = getchar(); + } +// Terminating character into separate one + terminating = ch; + + printf("Reversal of sentence:"); +// Some fancy algorithms going back and forth over the words + for (q = p, q--; q >= sentence; q--) { + if (*(p - 1) != ' ' && q > sentence) + continue; + putchar(' '); + for (r = q; r < p; r++) { + putchar(*r); + } + r = q - 1; + } + putchar(terminating); + + return 0; +} diff --git a/12_Pointers_And_Arrays/Projects/pr_06.c b/12_Pointers_And_Arrays/Projects/pr_06.c new file mode 100644 index 0000000..06f4b84 --- /dev/null +++ b/12_Pointers_And_Arrays/Projects/pr_06.c @@ -0,0 +1,59 @@ +/* + * pr_06.c + * + * Created on: Jun 10, 2013 + * Author: delmadord + */ +// NOT WORKING - working with pointers rather than integers +#include + +#define N 10 + +void quicksort(int a[], int *low, int *high); +int *split(int a[], int *low, int *high); + +int main(void) { + int a[N], i, *p; + + printf("Enter %d numbers to be sorted: ", N); + for (p = a; p < a + N; p++) + scanf("%d", p); + + quicksort(a, a, a + N - 1); + + printf("In sorted order: "); + for (i = 0; i < N; i++) + printf("%d ", a[i]); + printf("\n"); + + return 0; +} + +void quicksort(int a[], int *low, int *high) { + int *middle; + + if (*low >= *high) return; + middle = split(a, low, high); + quicksort(a, low, middle - 1); + quicksort(a, middle + 1, high); +} + +int *split(int a[], int *low, int *high) { + int part_element = a[low]; + + while (1) { + while (low < high && part_element <= a[high]) + high--; + if (low >= high) break; + a[low++] = a[high]; + + while (low < high && a[low] <= part_element) + low++; + if (low >= high) break; + a[high--] = a[low]; + } + + a[high] = part_element; + return high; +} + diff --git a/12_Pointers_And_Arrays/Projects/pr_07.c b/12_Pointers_And_Arrays/Projects/pr_07.c new file mode 100644 index 0000000..07e91ce --- /dev/null +++ b/12_Pointers_And_Arrays/Projects/pr_07.c @@ -0,0 +1,43 @@ +/* + * pr_07.c + * + * Created on: Jun 10, 2013 + * Author: delmadord + */ + +// SHOULD WORK WITH POINTER ARITHMETIC BUT I MADE NO CHANGES +// SINCE maxmin.c + +#include + +#define N 10 + +void max_min(int a[], int n, int *max, int *min); + +int main(void) { + int b[N], i, big, small; + + printf("Enter %d numbers: ", N); + for (i = 0; i < N; i++) + scanf("%d", &b[i]); + + max_min(b, N, &big, &small); + + printf("Largest: %d\n", big); + printf("Smallest: %d\n", small); + + return 0; +} + + +void max_min(int a[], int n, int *max, int *min) { + int i; + + *max = *min = a[0]; + for (i = 1; i < n; i++) { + if (a[i] > *max) + *max = a[i]; + else if (a[i] < *min) + *min = a[i]; + } +} diff --git a/13_Strings/Debug/13_Strings b/13_Strings/Debug/13_Strings new file mode 100644 index 0000000..bc64105 Binary files /dev/null and b/13_Strings/Debug/13_Strings differ diff --git a/13_Strings/Debug/Examples/subdir.mk b/13_Strings/Debug/Examples/subdir.mk new file mode 100644 index 0000000..8b2d41f --- /dev/null +++ b/13_Strings/Debug/Examples/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Examples/remind.c + +OBJS += \ +./Examples/remind.o + +C_DEPS += \ +./Examples/remind.d + + +# Each subdirectory must supply rules for building sources it contributes +Examples/%.o: ../Examples/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/13_Strings/Debug/Projects/pr_18.d b/13_Strings/Debug/Projects/pr_18.d new file mode 100644 index 0000000..36db9f1 --- /dev/null +++ b/13_Strings/Debug/Projects/pr_18.d @@ -0,0 +1 @@ +Projects/pr_18.d: ../Projects/pr_18.c diff --git a/13_Strings/Debug/Projects/pr_18.o b/13_Strings/Debug/Projects/pr_18.o new file mode 100644 index 0000000..d53970e Binary files /dev/null and b/13_Strings/Debug/Projects/pr_18.o differ diff --git a/13_Strings/Debug/Projects/subdir.mk b/13_Strings/Debug/Projects/subdir.mk new file mode 100644 index 0000000..1aac204 --- /dev/null +++ b/13_Strings/Debug/Projects/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_18.c + +OBJS += \ +./Projects/pr_18.o + +C_DEPS += \ +./Projects/pr_18.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/%.o: ../Projects/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/13_Strings/Debug/makefile b/13_Strings/Debug/makefile new file mode 100644 index 0000000..3c8e0e6 --- /dev/null +++ b/13_Strings/Debug/makefile @@ -0,0 +1,44 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include Projects/subdir.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 13_Strings + +# Tool invocations +13_Strings: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "13_Strings" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 13_Strings + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/13_Strings/Examples/planet.c b/13_Strings/Examples/planet.c new file mode 100644 index 0000000..022dfbc --- /dev/null +++ b/13_Strings/Examples/planet.c @@ -0,0 +1,32 @@ +/* + * planet.c + * + * Created on: Jun 10, 2013 + * Author: delmadord + */ + + +#include +#include + +#define NUM_PLANETS 9 + +int main(int argc, char *argv[]) { + char *planets[] = {"Mercury", "Venus", "Earth", + "Mars", "Jupiter", "Saturn", + "Uranus", "Neptune", "Pluto"}; + + int i, j; + + for (i = 1; i < argc; i++) { + for (j = 0; j < NUM_PLANETS; j++) + if (strcmp(argv[i], planets[j]) == 0) { + printf("%s is planet %d\n", argv[i], j + 1); + break; + } + if (j == NUM_PLANETS) + printf("%s is not a planet\n", argv[i]); + } + + return 0; +} diff --git a/13_Strings/Examples/remind.c b/13_Strings/Examples/remind.c new file mode 100644 index 0000000..3f0666c --- /dev/null +++ b/13_Strings/Examples/remind.c @@ -0,0 +1,64 @@ +/* + * remind.c + * + * Created on: Jun 10, 2013 + * Author: delmadord + */ + + +// Prints a one-month reminder list + +#include +#include + +#define MAX_REMIND 50 +#define MSG_LEN 60 + +int read_line(char str[], int n); + +int main(void) { + char reminders[MAX_REMIND][MSG_LEN + 3]; + char day_str[3], msg_str[MSG_LEN + 1]; + int day, i, j, num_remind = 0; + + while (1) { + if (num_remind == MAX_REMIND) { + printf("-- No space left --n"); + break; + } + + printf("Enter day reminder: "); + scanf("%2d", &day); + if (day == 0) + break; + sprintf(day_str, "%2d", day); + read_line(msg_str, MSG_LEN); + + for (i = 0; i < num_remind; i++) + if (strcmp(day_str, reminders[i]) < 0) + break; + for (j = num_remind; j > i; j--) + strcpy(reminders[j], reminders[j - 1]); + + strcpy(reminders[i], day_str); + strcat(reminders[i], msg_str); + + num_remind++; + } + + printf("\nDay Reminder\n"); + for (i = 0; i < num_remind; i++) + printf(" %s\n", reminders[i]); + + return 0; +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} diff --git a/13_Strings/Exercises/main.c b/13_Strings/Exercises/main.c new file mode 100644 index 0000000..c812945 --- /dev/null +++ b/13_Strings/Exercises/main.c @@ -0,0 +1,223 @@ +/* + * main.c + * + * Created on: Jun 10, 2013 + * Author: delmadord + */ + +#include +#include +#include +#include + +void ex_01(void); +void ex_02(void); +void ex_03(void); +// ex_04 +int read_line(char str[], int n); +// ex_05 +char *capitalize(char *s1); +// ex_06 +void censor(char s[]); +void ex_07(void); +void ex_08(void); +void ex_09(void); +// ex_11 +int my_strcmp(char *s, char *t); +// ex_12 +void get_extension(const char *file_name, char *extension); +// ex_13 +void build_index_url(const char *domain, char *index_url); +void ex_14(void); +int ex_15(char *s, char *t); +// ex_16 +int count_spaces(const char *s); +// ex_17 +bool test_extension(const char *file_name, const char *extension); + +int main(void) { + + + return 0; +} + +/* +void ex_01(void) { + printf("1|"); + printf("%c", '\n'); + +// printf("2|"); +// printf("%c", "\n"); + +// printf("3|"); +// printf("%s", '\n'); + + printf("4|"); + printf("%s", "\n"); + +// printf("5|"); +// printf('\n'); + + printf("6|"); + printf("\n"); + + printf("7|"); + putchar('\n'); + +// printf("8|"); +// putchar("\n"); + +// printf("9|"); +// puts('\n'); + +// printf("10|"); +// puts("\n"); // actually prints two new lines + + printf("11|"); + puts(""); +} + +void ex_02(void) { + char *p = "abc"; + + putchar(p); // p is adress so char with some random adress is useless + putchar('\n'); + + putchar(*p); // only the first character, but legal + putchar('\n'); + + puts(p); // ok + putchar('\n'); + + puts(*p); + putchar('\n'); // shows nothing, *p is not a pointer +} + +void ex_03(void) { + int i, j; + char s[10]; + + scanf("%d%s%d", &i, s, &j); // 12abc34 56def78 + printf("i = %d, s = %s, j = %d", i, s, j); // i = 12, s = abc34, j = 56 +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n' && ch != EOF) + if (i < n) + str[i++] = ch; + + str[i] = '\0'; + return i; + +} + + +// NOT WORKING +char *capitalize(char *s1) { + char *p = s1; + while (*p) { + *p = toupper(*p); + p++; + } +// *p = '\0'; + + return s1; +} + + +void censor(char s[]) { + int i; + + for (i = 0; s[i] != '\0'; i++) + if (s[i] == 'f' && s[i+1] == 'o' && s[i+2] =='o') + s[i] = s[i+1] = s[i+2] = 'x'; +} + +void ex_07(void) { +// d) +} + +void ex_08(void) { +// tired-or-wired? +} + +void ex_09(void) { + char s1[15], s2[15]; + strcpy(s1, "computer"); + strcpy(s2, "science"); + if (strcmp(s1, s2) < 0) + strcat(s1, s2); + else + strcat(s2, s1); + s1[strlen(s1) - 6] = '\0'; + printf("%s", s1); // computers +} +*/ + + +int my_strcmp(char *s, char *t) { + for (; *s == *t; s++, t++) + if (*s == '\0') + return 0; + return *s - *t; +} + +void get_extension(const char *file_name, char *extension) { + while (*file_name && *file_name != '.') + file_name++; + if (strlen(++file_name)) + strcpy(extension, file_name); + +} + +void build_index_url(const char *domain, char *index_url) { + strcpy(index_url, "http://www."); + strcat(index_url, domain); + strcat(index_url, "/index.html"); +} + +void ex_14(void) { + char s[] = "Hsjodi", *p; + + for (p = s; *p; p++) + --*p; + puts(s); + // Function outputs "Grinch" +} + +// The length of the longest prefix of the string s +// that consists entirely of characters from the string t. +// Or, equivalently, the position of the first character in s +// that is not also in t. +int ex_15(char *s, char *t) { + char *p1, *p2; + + for (p1 = s; *p1; p1++) { + for (p2 = t; *p2; p2++) { + if (*p1 == *p2) + break; + } + if (*p2 == '\0') + break; + } + return p1 - s; +} + +int count_spaces(const char *s) { + int count = 0; + + while (*s) + if (*s++ == ' ') + count++; + return count; +} + +// NOT WORKING +bool test_extension(const char *file_name, const char *extension) { + char ext[10]; + get_extension(file_name, ext); + return strcmp(toupper(ext), toupper(extension)) == 0; +} + diff --git a/13_Strings/Projects/pr_01.c b/13_Strings/Projects/pr_01.c new file mode 100644 index 0000000..39a6b46 --- /dev/null +++ b/13_Strings/Projects/pr_01.c @@ -0,0 +1,32 @@ +/* + * pr_01.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ + +#include +#include + +#define WORD_LEN 20 + +int main(void) { + // + 1 because of null character + char word[WORD_LEN + 1]; + char smallest_word[WORD_LEN + 1] = "", largest_word[WORD_LEN + 1] = ""; + + while (strlen(word) != 4) { + printf("Enter word: "); + scanf("%s", word); + if (strlen(smallest_word) == 0 || strcmp(smallest_word, word) > 0) + strcpy(smallest_word, word); + else if (strlen(largest_word) == 0 || strcmp(largest_word, word) < 0) + strcpy(largest_word, word); + } + + printf("\nSmallest word: %s", smallest_word); + printf("\nLargest word: %s", largest_word); + + return 0; +} + diff --git a/13_Strings/Projects/pr_02.c b/13_Strings/Projects/pr_02.c new file mode 100644 index 0000000..a7cc5be --- /dev/null +++ b/13_Strings/Projects/pr_02.c @@ -0,0 +1,67 @@ +/* + * pr_02.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ + + +// Prints a one-month reminder list, only part (a) is done +#include +#include + +#define MAX_REMIND 50 +#define MSG_LEN 60 + +int read_line(char str[], int n); + +int main(void) { + char reminders[MAX_REMIND][MSG_LEN + 3]; + char day_str[3], msg_str[MSG_LEN + 1]; + int day, i, j, num_remind = 0; + + while (1) { + if (num_remind == MAX_REMIND) { + printf("-- No space left --n"); + break; + } + + printf("Enter day reminder: "); + scanf("%2d", &day); + if (day == 0) + break; + if (day < 0 || day > 31) + continue; + sprintf(day_str, "%2d", day); + read_line(msg_str, MSG_LEN); + + for (i = 0; i < num_remind; i++) + if (strcmp(day_str, reminders[i]) < 0) + break; + for (j = num_remind; j > i; j--) + strcpy(reminders[j], reminders[j - 1]); + + strcpy(reminders[i], day_str); + strcat(reminders[i], msg_str); + + num_remind++; + } + + printf("\nDay Reminder\n"); + for (i = 0; i < num_remind; i++) + printf(" %s\n", reminders[i]); + + return 0; +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} + + diff --git a/13_Strings/Projects/pr_03.c b/13_Strings/Projects/pr_03.c new file mode 100644 index 0000000..e288342 --- /dev/null +++ b/13_Strings/Projects/pr_03.c @@ -0,0 +1,47 @@ +/* + * pr_03.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ +#include +#include +#include +#include +#include + +#define NUM_SUITS 4 +#define NUM_RANKS 13 + + +int main(void) { + bool in_hand[NUM_SUITS][NUM_RANKS] = {{false}}; + int num_cards, rank, suit; + const char *rank_code[] = {"Two", "Three", "Four", "Five", "Six", + "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"}; + const char *suit_code[] = {"spades", "hearts", "diamonds", "clubs"}; + + srand((unsigned) time(NULL)); + + printf("Enter number of cards: "); + scanf("%d", &num_cards); + + printf("Your hand:\N"); + while (num_cards > 0) { + suit = rand() % NUM_SUITS; + rank = rand() % NUM_RANKS; + if (!in_hand[suit][rank]) { + in_hand[suit][rank] = true; + num_cards--; + // Capitalize + printf("%s", rank_code[rank]); + printf(" of "); + printf("%s\n", suit_code[suit]); + + } + } + printf("\n"); + + return 0; + +} diff --git a/13_Strings/Projects/pr_04.c b/13_Strings/Projects/pr_04.c new file mode 100644 index 0000000..7bfcc45 --- /dev/null +++ b/13_Strings/Projects/pr_04.c @@ -0,0 +1,17 @@ +/* + * pr_04.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ + +// reverse command line arguments + +#include + +int main(int argc, char *argv[]) { + while (argc--) + printf("%s ", argv[argc]); + printf("\n"); + return 0; +} diff --git a/13_Strings/Projects/pr_05.c b/13_Strings/Projects/pr_05.c new file mode 100644 index 0000000..9590027 --- /dev/null +++ b/13_Strings/Projects/pr_05.c @@ -0,0 +1,19 @@ +/* + * pr_05.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ + + +// sum command line arguments +#include +#include + +int main(int argc, char *argv[]) { + int sum = 0; + while (argc--) + sum += atoi(argv[argc]); + printf("Total: %d\n", sum); + return 0; +} diff --git a/13_Strings/Projects/pr_06.c b/13_Strings/Projects/pr_06.c new file mode 100644 index 0000000..9420898 --- /dev/null +++ b/13_Strings/Projects/pr_06.c @@ -0,0 +1,46 @@ +/* + * pr_06.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ + + + + +#include +#include +#include +#include + +#define NUM_PLANETS 9 + +bool string_equal(const char *s, const char *t); + +int main(int argc, char *argv[]) { + char *planets[] = {"Mercury", "Venus", "Earth", + "Mars", "Jupiter", "Saturn", + "Uranus", "Neptune", "Pluto"}; + + int i, j; + + for (i = 1; i < argc; i++) { + for (j = 0; j < NUM_PLANETS; j++) + if (string_equal(argv[i], planets[j])) { + printf("%s is planet %d\n", argv[i], j + 1); + break; + } + if (j == NUM_PLANETS) + printf("%s is not a planet\n", argv[i]); + } + + return 0; +} + +bool string_equal(const char *s, const char *t) { + while (toupper(*s++) == toupper(*t++)) + if (*s == '\0') + return 1; + + return 0; +} diff --git a/13_Strings/Projects/pr_07.c b/13_Strings/Projects/pr_07.c new file mode 100644 index 0000000..dfada20 --- /dev/null +++ b/13_Strings/Projects/pr_07.c @@ -0,0 +1,34 @@ +/* + * pr_07.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ + +#include + +int main(void) { + int tens, ones; + char *word_tens[10] = {"", "ten", "twenty", "thirty", "forty", "fifty", + "sixty", "seventy", "eighty", "ninety"}; + char *word_ones[10] = {"", "one", "two", "three", "four", "five", + "six", "seven", "eight", "nine"}; + char *word_special[10] = {"ten", "eleven", "twelve", "thirteen", + "fourteen", "fifteen", "sixteen", "seventeen", + "eighteen", "nineteen"}; + + printf("Enter a two-digit number: "); + scanf("%1d%1d", &tens, &ones); + + printf("You entered the number "); + if (tens != 1) { + printf("%s", word_tens[tens]); + if (ones > 0) + printf("-%s", word_ones[ones]); + } + else + printf("%s", word_special[ones]); + printf("."); + + return 0; +} diff --git a/13_Strings/Projects/pr_08.c b/13_Strings/Projects/pr_08.c new file mode 100644 index 0000000..707ab4d --- /dev/null +++ b/13_Strings/Projects/pr_08.c @@ -0,0 +1,47 @@ +/* + * pr_08.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ + +#include +#include + +#define WORD_LEN 20 + +int compute_scrabble_value(const char *word); + +// Scrabble +int main(void) { + char word[WORD_LEN]; + printf("Enter a word: "); + scanf("%s", word); + printf("Scrabble value: %d\n", compute_scrabble_value(word)); + + return 0; +} + +int compute_scrabble_value(const char *word) { + int sum = 0; + + while (*word) + switch (toupper(*word++)) { + case 'D': case 'G': + sum += 2; break; + case 'B': case 'C': case 'M': case 'P': + sum += 3; break; + case 'F': case 'H': case 'V': case 'W': case 'Y': + sum += 4; break; + case 'K': + sum += 5; break; + case 'J': case 'X': + sum += 8; break; + case 'Q': case 'Z': + sum += 10; break; + default: + sum++; break; + } + + return sum; +} diff --git a/13_Strings/Projects/pr_09.c b/13_Strings/Projects/pr_09.c new file mode 100644 index 0000000..277cd1e --- /dev/null +++ b/13_Strings/Projects/pr_09.c @@ -0,0 +1,47 @@ +/* + * pr_09.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ +#include +#include + +#define SENTENCE_LENGHT 100 + +int compute_vowel_count(const char *sentence); +int read_line(char str[], int n); + +int main(void) { + char sentence[SENTENCE_LENGHT + 1]; + + printf("Enter a sentence: "); + read_line(sentence, SENTENCE_LENGHT); + printf("Your sentence contains %d vowels.", + compute_vowel_count(sentence)); + + return 0; +} + +int compute_vowel_count(const char *sentence) { + int vowels = 0; + char *p = sentence; + while (*p) { + *p = toupper(*p); + if (*p == 'A' || *p == 'E' || *p == 'I' || *p == 'O' || *p == 'U') + vowels++; + p++; + } + + return vowels; +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} diff --git a/13_Strings/Projects/pr_10.c b/13_Strings/Projects/pr_10.c new file mode 100644 index 0000000..139b4c2 --- /dev/null +++ b/13_Strings/Projects/pr_10.c @@ -0,0 +1,66 @@ +/* + * pr_10.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ + +// NOT WORKING - STRANGE BUG + +#include +#include +#include + +#define NAME_LENGHT 40 + +void reverse_name(char *name); +int read_line(char str[], int n); + +int main(void) { + char name[NAME_LENGHT + 1]; + + printf("Enter a first and last name: "); + read_line(name, NAME_LENGHT); + reverse_name(name); + printf("Reversed name: %s", name); + + return 0; +} + +void reverse_name(char *name) { + char first; + // Find where name starts and point there + do + first = *name++; + while (*name == ' '); + // Find where name ends, surname starts + while (isalpha(*name)) + name++; + while (*name == ' ') + name++; + // Copy from start of the last name to the end into temp var + char temp[NAME_LENGHT + 1] = ""; + strcpy(temp, name); + // Find where surname ends and cuts everything after +// while (isalpha(*temp)) +// temp++; +// *temp = '\0'; + // Add the rest + strcat(temp, " , "); + strncat(temp, &first, 1); + strcat(temp, "."); + // Put it to to the original var + // BUG HERE - temp is good, copy to name is good but when + // returned to main function, name cotains first name too + strcpy(name, temp); +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} diff --git a/13_Strings/Projects/pr_11.c b/13_Strings/Projects/pr_11.c new file mode 100644 index 0000000..f3a0d6a --- /dev/null +++ b/13_Strings/Projects/pr_11.c @@ -0,0 +1,50 @@ +/* + * pr_11.c + * + * Created on: Jun 11, 2013 + * Author: delmadord + */ + +#include +#include + +#define SENTENCE_LEN 100 + +double compute_avg_word_lenght(const char *sentence); +int read_line(char str[], int n); +int count_spaces(const char *s); + +int main(void) { + char sentence[SENTENCE_LEN + 1]; + printf("Enter a sentence without punctuation (.,?!): "); + read_line(sentence, SENTENCE_LEN); + printf("Average word length: %.2f", + compute_avg_word_lenght(sentence)); + + return 0; +} + +double compute_avg_word_lenght(const char *sentence) { + double words = count_spaces(sentence); + // Even if there is no space, it is at least one word + return (strlen(sentence) - words) / (words + 1); +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} + +int count_spaces(const char *s) { + int count = 0; + + while (*s) + if (*s++ == ' ') + count++; + return count; +} diff --git a/13_Strings/Projects/pr_12.c b/13_Strings/Projects/pr_12.c new file mode 100644 index 0000000..ff85b5d --- /dev/null +++ b/13_Strings/Projects/pr_12.c @@ -0,0 +1,38 @@ +/* + * pr_12.c + * + * Created on: Jun 12, 2013 + * Author: delmadord + */ +#include +//#include <> + +#define NUM_WORDS 30 +#define WORD_LEN 20 + + +// Reverse words in sentence +int main(void) { + int i = 0, j = 0; + char ch, sentence[NUM_WORDS][WORD_LEN + 1]; + printf("Enter a sentence without pucntation: "); + while ((ch = getchar()) != '\n') { + if (ch == ' ') { + sentence[i++][j] = '\0'; + j = 0; + } + else + sentence[i][j++] = ch; + } + // Add null character in case of just one word. + sentence[i][j] = '\0'; + + printf("Reversal of sentence: "); + while (i >= 0) + printf("%s ", sentence[i--]); + + return 0; + +} + + diff --git a/13_Strings/Projects/pr_13.c b/13_Strings/Projects/pr_13.c new file mode 100644 index 0000000..e7c3693 --- /dev/null +++ b/13_Strings/Projects/pr_13.c @@ -0,0 +1,49 @@ +/* + * pr_13.c + * + * Created on: Jun 12, 2013 + * Author: delmadord + */ + +#include + +#define MESSAGE_LEN 100 + +void caesar_encrypt(char *message, int shift); +int read_line(char str[], int n); + +// Caesar cipher +int main(void) { + char message[MESSAGE_LEN + 1]; + int shift; + + printf("Enter message to be encrypted: "); + read_line(message, MESSAGE_LEN); + printf("Enter shift amount: "); + scanf("%d", &shift); + + caesar_encrypt(message, shift); + printf("Encrypted message: %s", message); + + return 0; +} + +void caesar_encrypt(char *message, int shift) { + while (*message) { + if (*message >= 'A' && *message <= 'Z') + *message = ((*message - 'A') + shift) % 26 + 'A'; + else if (*message >= 'a' && *message <= 'z') + *message = ((*message - 'a') + shift) % 26 + 'a'; + message++; + } +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} diff --git a/13_Strings/Projects/pr_14.c b/13_Strings/Projects/pr_14.c new file mode 100644 index 0000000..3ff107b --- /dev/null +++ b/13_Strings/Projects/pr_14.c @@ -0,0 +1,53 @@ +/* + * pr_14.c + * + * Created on: Jun 12, 2013 + * Author: delmadord + */ +#include +#include +#include + +#define WORD_LENGHT 20 + +bool are_anagrams(const char *word1, const char *word2); + +// Anagrams +int main(void) { + char w1[WORD_LENGHT + 1], w2[WORD_LENGHT + 1]; + printf("Enter first word: "); + scanf("%s", w1); + + printf("Enter second word: "); + scanf("%s", w2); + + if (are_anagrams(w1, w2)) + printf("The words are anagrams."); + else + printf("The words are not anagrams."); + + return 0; +} + +bool are_anagrams(const char *word1, const char *word2) { + int i; + char contain[26] = {0}; + + while (*word1) { + if (isalpha(*word1)) + contain[toupper(*word1) - 'A']++; + word1++; + } + while (*word2) { + if (isalpha(*word2)) + contain[toupper(*word2) - 'A']--; + word2++; + } + + for (i = 0; i < 26; i++) { + if (contain[i] != 0) + break; + } + + return (i == 26); +} diff --git a/13_Strings/Projects/pr_15.c b/13_Strings/Projects/pr_15.c new file mode 100644 index 0000000..a0e77c8 --- /dev/null +++ b/13_Strings/Projects/pr_15.c @@ -0,0 +1,122 @@ +/* + * pr_15.c + * + * Created on: Jun 12, 2013 + * Author: delmadord + */ + +/* RPN Reverse polish notation with stack */ + +#include +#include +#include +#include + +#define STACK_SIZE 100 +#define EXP_LEN 500 + +/* external variables */ +char contents[STACK_SIZE]; +int top = 0; + + +int evaluate_RPN_expression(const char *exp); +int read_line(char str[], int n); +void make_empty(void); +bool is_empty(void); +bool is_full(void); +void push(int ch); +int pop(void); +void stack_overflow(void); +void stack_underflow(void); + + +int main(void) { + char expression[EXP_LEN + 1]; + while (1) { + printf("Enter an RPN expression: "); + read_line(expression, EXP_LEN); + if (expression[0] == 'q') + break; + printf("Value of expression: %d\n", + evaluate_RPN_expression(expression)); + } + + return 0; +} + + +int evaluate_RPN_expression(const char *exp) { + make_empty(); + int temp; + + // Read expression until end or until = + while (*exp && *exp != '=') { + if (isdigit((int)*exp)) + push(*exp - '0'); + // Operand found (+ and * are comutative) + else if (*exp == '+') + push(pop() + pop()); + else if (*exp == '*') + push(pop() * pop()); + // However, operands - and / are not + else if (*exp == '-') { + temp = pop(); + push(pop() - temp); + } + else if (*exp == '/'){ + temp = pop(); + push(pop() / temp); + } + exp++; + } + return pop(); +} + + +void make_empty(void) { + top = 0; +} + +bool is_empty(void) { + return top == 0; +} + +bool is_full(void) { + return top == STACK_SIZE; +} + +void push(int ch) { + if (is_full()) + stack_overflow(); + + contents[top++] = ch; +} + +int pop(void) { + if (is_empty()) + stack_underflow(); + + return contents[--top]; +} + +void stack_overflow(void) { + printf("The expression is too complex!"); + exit(EXIT_FAILURE); +} + +void stack_underflow(void) { + printf("Not enough operands in expression!"); + exit(EXIT_FAILURE); +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} + diff --git a/13_Strings/Projects/pr_16.c b/13_Strings/Projects/pr_16.c new file mode 100644 index 0000000..3f33293 --- /dev/null +++ b/13_Strings/Projects/pr_16.c @@ -0,0 +1,47 @@ +/* + * pr_16.c + * + * Created on: Jun 12, 2013 + * Author: delmadord + */ + +#include + +#define N 100 + +void reverse(char *message); +int read_line(char str[], int n); + +int main(void) { + char sentence[N + 1]; + printf("Enter a message: "); + read_line(sentence, N); + reverse(sentence); + printf("Reversal is: %s", sentence); + + return 0; +} + +void reverse(char *message) { + char temp, *p = message; + // Point to the last character + while (*(p + 1)) + p++; + // Stop when pointers meet + while (message < p) { + // Exchange characters and move them towards + temp = *p; + *p-- = *message; + *message++ = temp; + } +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} diff --git a/13_Strings/Projects/pr_17.c b/13_Strings/Projects/pr_17.c new file mode 100644 index 0000000..6ea2d50 --- /dev/null +++ b/13_Strings/Projects/pr_17.c @@ -0,0 +1,58 @@ +/* + * pr_17.c + * + * Created on: Jun 12, 2013 + * Author: delmadord + */ + + +#include +#include +#include + +#define N 100 + +bool is_palindrome(const char *message); +int read_line(char str[], int n); + +int main(void) { + char sentence[N + 1]; + printf("Enter a message: "); + read_line(sentence, N); + + if (is_palindrome(sentence)) + printf("Palinrome"); + else + printf("Not a palindrome"); + + return 0; +} + +bool is_palindrome(const char *message) { + char *p = message; + bool palindrome = true; + // Point to the last character + while (*(p + 1)) + p++; + // Stop when the pointers meet or there is a mismatch + while (message < p && palindrome) { + // Skip non-aplha characters + while (!isalpha(*message)) + message++; + while (!isalpha(*p)) + p--; + // Move pointers towards, match is recorded + palindrome = (tolower(*message++) == tolower(*p--)); + } + return palindrome; +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} diff --git a/13_Strings/Projects/pr_18.c b/13_Strings/Projects/pr_18.c new file mode 100644 index 0000000..7af2a2e --- /dev/null +++ b/13_Strings/Projects/pr_18.c @@ -0,0 +1,20 @@ +/* + * pr_18.c + * + * Created on: Jun 12, 2013 + * Author: delmadord + */ + +#include + +int main(void) { + char *months[] = {"January", "February", "March", "April", "May", + "June", "July", "August", "September", "October", + "November", "December"}; + int mm, dd, yyyy; + + printf("Enter a date (dd/mm/yyyy): "); + scanf("%2d/%2d/%d", &dd, &mm, &yyyy); + printf("You entered the date %s %d, %d", months[mm - 1], dd, yyyy); + +} diff --git a/14_The_Preprocessor/Debug/14_The_Preprocessor b/14_The_Preprocessor/Debug/14_The_Preprocessor new file mode 100644 index 0000000..752dc95 Binary files /dev/null and b/14_The_Preprocessor/Debug/14_The_Preprocessor differ diff --git a/14_The_Preprocessor/Debug/main.o b/14_The_Preprocessor/Debug/main.o new file mode 100644 index 0000000..b939622 Binary files /dev/null and b/14_The_Preprocessor/Debug/main.o differ diff --git a/14_The_Preprocessor/Debug/makefile b/14_The_Preprocessor/Debug/makefile new file mode 100644 index 0000000..86e75b3 --- /dev/null +++ b/14_The_Preprocessor/Debug/makefile @@ -0,0 +1,43 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 14_The_Preprocessor + +# Tool invocations +14_The_Preprocessor: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "14_The_Preprocessor" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 14_The_Preprocessor + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/14_The_Preprocessor/main.c b/14_The_Preprocessor/main.c new file mode 100644 index 0000000..1b72ef2 --- /dev/null +++ b/14_The_Preprocessor/main.c @@ -0,0 +1,123 @@ +/* + * main.c + * + * Created on: Jun 12, 2013 + * Author: delmadord + */ + +#include +#include +#include + +// ex_01 +#define CUBE(x) ((x)*(x)*(x)) +#define REMAIND_4(n) ((n) % 4) +#define C1(x, y) (((x) * (y)) == 100) + +// ex_02 +#define NELEMS(a) ((int) (sizeof (a) / sizeof (a[0]))) + +// ex_03 +#define DOUBLE(x) (2 * (x)) + +// ex_04 +#define AVG(x,y) (((x) + (y)) / 2) +#define AREA(x,y) ((x) * (y)) + +// ex_05 +#define TOUPPER(c) ('a'<=(c)&&(c)<='z'?(c)-'a'+'A':(c)) + +// ex_06 +#define DISP(f,x) printf(#f "(%g) = %g\n", x, f(x)); + +// ex_07 +#define GENERIC_MAX(type) \ +type type##_max(type x, type y) { \ + return x > y ? x : y; \ +} + +// ex_08 +#define STRINGIZE(x) #x +#define INDIR(x) STRINGIZE(x) +#define LINE_FILE "Line " INDIR(__LINE__) " of file " INDIR(__FILE__) + +// ex_09 +#define CHECK(x,y,n) (((x)>=0&&(x)=0&&(y) MAX_WORD_LEN) + word[MAX_WORD_LEN] = '*'; + if (word_len + 1 > space_remainig()) { + write_line(); + clear_line(); + } + add_word(word); + } +} + diff --git a/15_Writing_Large_Programs/Examples/justify/line.c b/15_Writing_Large_Programs/Examples/justify/line.c new file mode 100644 index 0000000..e7c2f7f --- /dev/null +++ b/15_Writing_Large_Programs/Examples/justify/line.c @@ -0,0 +1,61 @@ +/* + * line.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + + +#include +#include +#include "line.h" + +#define MAX_LINE_LEN 60 + +char line[MAX_LINE_LEN + 1]; +int line_len = 0; +int num_words = 0; + +void clear_line(void) { + line[0] = '\0'; + line_len = 0; + num_words = 0; +} + +void add_word(const char *word) { + if (num_words > 0) { + line[line_len] = ' '; + line[line_len + 1] = '\0'; + line_len++; + } + strcat(line, word); + line_len += strlen(word); + num_words++; +} + +int space_remainig(void) { + return MAX_LINE_LEN - line_len; +} + +void write_line(void) { + int extra_spaces, spaces_to_insert, i, j; + + extra_spaces = MAX_LINE_LEN - line_len; + for (i = 0; i < line_len; i++) { + if (line[i] != ' ') + putchar(line[i]); + else { + spaces_to_insert = extra_spaces / (num_words - 1); + for (j = 1; j <= spaces_to_insert + 1; j++) + putchar(' '); + extra_spaces -= spaces_to_insert; + num_words--; + } + } + putchar('\n'); +} + +void flush_line(void) { + if (line_len > 0) + puts(line); +} diff --git a/15_Writing_Large_Programs/Examples/justify/line.h b/15_Writing_Large_Programs/Examples/justify/line.h new file mode 100644 index 0000000..b970ae0 --- /dev/null +++ b/15_Writing_Large_Programs/Examples/justify/line.h @@ -0,0 +1,29 @@ +/* + * line.h + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#ifndef LINE_H_ +#define LINE_H_ + +// Clears the current line +void clear_line(void); + +// Adds word to the end of the curent line +// If not the first word of the line, puts one space before +void add_word(const char *word); + +// Returns number of characters left in the current line +int space_remainig(void); + +// writes current line with justification +void write_line(void); + +// Writes the current line without justification +// If the line is empty, does nothing +void flush_line(void); + + +#endif /* LINE_H_ */ diff --git a/15_Writing_Large_Programs/Examples/justify/word.c b/15_Writing_Large_Programs/Examples/justify/word.c new file mode 100644 index 0000000..9270a17 --- /dev/null +++ b/15_Writing_Large_Programs/Examples/justify/word.c @@ -0,0 +1,32 @@ +/* + * word.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#include +#include "word.h" + +int read_char(void) { + int ch = getchar(); + + if (ch == '\n' || ch == '\t') + return ' '; + return ch; +} + +int read_word(char *word, int len) { + int ch, pos = 0; + + while ((ch = read_char()) == ' ') + ; + while (ch != ' ' && ch != EOF) { + if (pos < len) + word[pos++] = ch; + ch = read_char(); + } + word[pos] = '\0'; + return pos; +} + diff --git a/15_Writing_Large_Programs/Examples/justify/word.h b/15_Writing_Large_Programs/Examples/justify/word.h new file mode 100644 index 0000000..681c3da --- /dev/null +++ b/15_Writing_Large_Programs/Examples/justify/word.h @@ -0,0 +1,17 @@ +/* + * word.h + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#ifndef WORD_H_ +#define WORD_H_ + +// Reads the next word from the input +// Makes word empty, if exceeds OEF +// Truncates long words +// Returns number of characters stored +int read_word(char *word, int len); + +#endif /* WORD_H_ */ diff --git a/15_Writing_Large_Programs/Projects/pr_01/line.c b/15_Writing_Large_Programs/Projects/pr_01/line.c new file mode 100644 index 0000000..9b1ec68 --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_01/line.c @@ -0,0 +1,66 @@ +/* + * line.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + + +#include +#include +#include "line.h" + +#define MAX_LINE_LEN 60 + +char line[MAX_LINE_LEN + 1]; +int line_len = 0; +int num_words = 0; + +void clear_line(void) { + line[0] = '\0'; + line_len = 0; + num_words = 0; +} + +void add_word(const char *word) { + if (num_words > 0) { + line[line_len] = ' '; + line[line_len + 1] = '\0'; + line_len++; + } + strcat(line, word); + line_len += strlen(word); + num_words++; +} + +int space_remainig(void) { + return MAX_LINE_LEN - line_len; +} + +void write_line(void) { + int extra_spaces, spaces_to_insert, i, j; + + // How many spaces are between the words + extra_spaces = MAX_LINE_LEN - line_len; + // Go over every character of array + for (i = 0; i < line_len; i++) { + // Write arbitrary characters + if (line[i] != ' ') + putchar(line[i]); + else { + // Here should it be IMPROVED by alternating spaces + // But I dont know how + spaces_to_insert = extra_spaces / (num_words - 1); + for (j = 1; j <= spaces_to_insert + 1; j++) + putchar(' '); + extra_spaces -= spaces_to_insert; + num_words--; + } + } + putchar('\n'); +} + +void flush_line(void) { + if (line_len > 0) + puts(line); +} diff --git a/15_Writing_Large_Programs/Projects/pr_02/justify.c b/15_Writing_Large_Programs/Projects/pr_02/justify.c new file mode 100644 index 0000000..333d8b1 --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_02/justify.c @@ -0,0 +1,32 @@ +/* + * justify.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#include "line.h" +#include "word.h" + + + +int main(void) { + // additional spaces for * and \0 + char word[MAX_WORD_LEN + 2]; + int word_len; + + clear_line(); + while (1) { + word_len = read_word(word, MAX_WORD_LEN + 1); + if (word_len == 0) { + flush_line(); + return 0; + } + if (word_len + 1 > space_remainig()) { + write_line(); + clear_line(); + } + add_word(word); + } +} + diff --git a/15_Writing_Large_Programs/Projects/pr_02/line.c b/15_Writing_Large_Programs/Projects/pr_02/line.c new file mode 100644 index 0000000..be139ea --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_02/line.c @@ -0,0 +1,61 @@ +/* + * line.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + + +#include +#include +#include "line.h" + + + +char line[MAX_LINE_LEN + 1]; +int line_len = 0; +int num_words = 0; + +void clear_line(void) { + line[0] = '\0'; + line_len = 0; + num_words = 0; +} + +void add_word(const char *word) { + if (num_words > 0) { + line[line_len] = ' '; + line[line_len + 1] = '\0'; + line_len++; + } + strcat(line, word); + line_len += strlen(word); + num_words++; +} + +int space_remainig(void) { + return MAX_LINE_LEN - line_len; +} + +void write_line(void) { + int extra_spaces, spaces_to_insert, i, j; + + extra_spaces = MAX_LINE_LEN - line_len; + for (i = 0; i < line_len; i++) { + if (line[i] != ' ') + putchar(line[i]); + else { + spaces_to_insert = extra_spaces / (num_words - 1); + for (j = 1; j <= spaces_to_insert + 1; j++) + putchar(' '); + extra_spaces -= spaces_to_insert; + num_words--; + } + } + putchar('\n'); +} + +void flush_line(void) { + if (line_len > 0) + puts(line); +} diff --git a/15_Writing_Large_Programs/Projects/pr_02/line.h b/15_Writing_Large_Programs/Projects/pr_02/line.h new file mode 100644 index 0000000..fd5a389 --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_02/line.h @@ -0,0 +1,31 @@ +/* + * line.h + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#ifndef LINE_H_ +#define LINE_H_ + +#define MAX_LINE_LEN 60 + +// Clears the current line +void clear_line(void); + +// Adds word to the end of the curent line +// If not the first word of the line, puts one space before +void add_word(const char *word); + +// Returns number of characters left in the current line +int space_remainig(void); + +// writes current line with justification +void write_line(void); + +// Writes the current line without justification +// If the line is empty, does nothing +void flush_line(void); + + +#endif /* LINE_H_ */ diff --git a/15_Writing_Large_Programs/Projects/pr_02/word.c b/15_Writing_Large_Programs/Projects/pr_02/word.c new file mode 100644 index 0000000..348cb1a --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_02/word.c @@ -0,0 +1,34 @@ +/* + * word.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#include +#include "word.h" + +int read_char(void) { + int ch = getchar(); + + if (ch == '\n' || ch == '\t') + return ' '; + return ch; +} + +int read_word(char *word, int len) { + int ch, pos = 0; + + while ((ch = read_char()) == ' ') + ; + while (ch != ' ' && ch != EOF) { + if (pos < len) + word[pos++] = ch; + ch = read_char(); + } + if (pos >= len) + word[pos - 1] = '*'; + word[pos] = '\0'; + return pos; +} + diff --git a/15_Writing_Large_Programs/Projects/pr_02/word.h b/15_Writing_Large_Programs/Projects/pr_02/word.h new file mode 100644 index 0000000..c24abea --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_02/word.h @@ -0,0 +1,19 @@ +/* + * word.h + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#ifndef WORD_H_ +#define WORD_H_ + +#define MAX_WORD_LEN 20 + +// Reads the next word from the input +// Makes word empty, if exceeds OEF +// Truncates long words +// Returns number of characters stored +int read_word(char *word, int len); + +#endif /* WORD_H_ */ diff --git a/15_Writing_Large_Programs/Projects/pr_03/qsort.c b/15_Writing_Large_Programs/Projects/pr_03/qsort.c new file mode 100644 index 0000000..b82a549 --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_03/qsort.c @@ -0,0 +1,33 @@ +/* + * qsort.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + + +#include +#include "quicksort.h" + +#define N 10 + + +int main(void) { + int a[N], i; + + printf("Enter %d numbers to be sorted: ", N); + for (i = 0; i < N; i++) + scanf("%d", &a[i]); + + quicksort(a, 0, N - 1); + + printf("In sorted order: "); + for (i = 0; i < N; i++) + printf("%d ", a[i]); + printf("\n"); + + return 0; +} + + + diff --git a/15_Writing_Large_Programs/Projects/pr_03/quicksort.c b/15_Writing_Large_Programs/Projects/pr_03/quicksort.c new file mode 100644 index 0000000..49cc4cc --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_03/quicksort.c @@ -0,0 +1,34 @@ +/* + * quicksort.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +void quicksort(int a[], int low, int high) { + int middle; + + if (low >= high) return; + middle = split(a, low, high); + quicksort(a, low, middle - 1); + quicksort(a, middle + 1, high); +} + +int split(int a[], int low, int high) { + int part_element = a[low]; + + for(;;) { + while (low < high && part_element <= a[high]) + high--; + if (low >= high) break; + a[low++] = a[high]; + + while (low < high && a[low] <= part_element) + low++; + if (low >= high) break; + a[high--] = a[low]; + } + + a[high] = part_element; + return high; +} diff --git a/15_Writing_Large_Programs/Projects/pr_03/quicksort.h b/15_Writing_Large_Programs/Projects/pr_03/quicksort.h new file mode 100644 index 0000000..a9ce708 --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_03/quicksort.h @@ -0,0 +1,15 @@ +/* + * quicksort.h + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#ifndef QUICKSORT_H_ +#define QUICKSORT_H_ + +void quicksort(int a[], int low, int high); +int split(int a[], int low, int high); + + +#endif /* QUICKSORT_H_ */ diff --git a/15_Writing_Large_Programs/Projects/pr_04/readline.c b/15_Writing_Large_Programs/Projects/pr_04/readline.c new file mode 100644 index 0000000..1b13636 --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_04/readline.c @@ -0,0 +1,17 @@ +/* + * readline.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} diff --git a/15_Writing_Large_Programs/Projects/pr_04/readline.h b/15_Writing_Large_Programs/Projects/pr_04/readline.h new file mode 100644 index 0000000..718c67a --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_04/readline.h @@ -0,0 +1,13 @@ +/* + * readline.h + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#ifndef READLINE_H_ +#define READLINE_H_ + +int read_line(char str[], int n); + +#endif /* READLINE_H_ */ diff --git a/15_Writing_Large_Programs/Projects/pr_04/remind.c b/15_Writing_Large_Programs/Projects/pr_04/remind.c new file mode 100644 index 0000000..7b1ff4d --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_04/remind.c @@ -0,0 +1,57 @@ +/* + * remind.c + * + * Created on: Jun 10, 2013 + * Author: delmadord + */ + + +// Prints a one-month reminder list + +#include +#include +#include "readline.h" + +#define MAX_REMIND 50 +#define MSG_LEN 60 + + + +int main(void) { + char reminders[MAX_REMIND][MSG_LEN + 3]; + char day_str[3], msg_str[MSG_LEN + 1]; + int day, i, j, num_remind = 0; + + while (1) { + if (num_remind == MAX_REMIND) { + printf("-- No space left --n"); + break; + } + + printf("Enter day reminder: "); + scanf("%2d", &day); + if (day == 0) + break; + sprintf(day_str, "%2d", day); + read_line(msg_str, MSG_LEN); + + for (i = 0; i < num_remind; i++) + if (strcmp(day_str, reminders[i]) < 0) + break; + for (j = num_remind; j > i; j--) + strcpy(reminders[j], reminders[j - 1]); + + strcpy(reminders[i], day_str); + strcat(reminders[i], msg_str); + + num_remind++; + } + + printf("\nDay Reminder\n"); + for (i = 0; i < num_remind; i++) + printf(" %s\n", reminders[i]); + + return 0; +} + + diff --git a/15_Writing_Large_Programs/Projects/pr_05/rpn.c b/15_Writing_Large_Programs/Projects/pr_05/rpn.c new file mode 100644 index 0000000..40f08d8 --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_05/rpn.c @@ -0,0 +1,54 @@ +/* + * rpn.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + + +/* RPN Reverse polish notation with stack */ + +#include +#include +#include +#include +#include "stack.h" + + + +int main(void) { + char ch = 0; + int temp; + + while (ch != 'q') { + printf("Enter an RPN expression: "); + while (1) { + scanf(" %c", &ch); + if (ch == '=' || ch == 'q') + break; + // Operand found (+ and * are comutative) + if (isdigit((int)ch)) + push(ch - '0'); + else if (ch == '+') + push(pop() + pop()); + else if (ch == '-') { + temp = pop(); + push(pop() - temp); + } + else if (ch == '*') + push(pop() * pop()); + else if (ch == '/'){ + temp = pop(); + push(pop() / temp); + } + + } + printf("Value of expression: %d\n", pop()); + make_empty(); + } + + return 0; +} + + + diff --git a/15_Writing_Large_Programs/Projects/pr_05/stack.c b/15_Writing_Large_Programs/Projects/pr_05/stack.c new file mode 100644 index 0000000..13eb0b0 --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_05/stack.c @@ -0,0 +1,52 @@ +/* + * stack.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#include +#include +#include +#include "stack.h" + +/* external variables */ +int contents[STACK_SIZE]; +int top = 0; + + +void make_empty(void) { + top = 0; +} + +bool is_empty(void) { + return top == 0; +} + +bool is_full(void) { + return top == STACK_SIZE; +} + +void push(int ch) { + if (is_full()) + stack_overflow(); + + contents[top++] = ch; +} + +int pop(void) { + if (is_empty()) + stack_underflow(); + + return contents[--top]; +} + +void stack_overflow(void) { + printf("The expression is too complex!"); + exit(EXIT_FAILURE); +} + +void stack_underflow(void) { + printf("Not enough operands in expression!"); + exit(EXIT_FAILURE); +} diff --git a/15_Writing_Large_Programs/Projects/pr_05/stack.h b/15_Writing_Large_Programs/Projects/pr_05/stack.h new file mode 100644 index 0000000..1bd8602 --- /dev/null +++ b/15_Writing_Large_Programs/Projects/pr_05/stack.h @@ -0,0 +1,24 @@ +/* + * stack.h + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#ifndef STACK_H_ +#define STACK_H_ + +#include + +#define STACK_SIZE 100 + + +void make_empty(void); +bool is_empty(void); +bool is_full(void); +void push(int ch); +int pop(void); +void stack_overflow(void); +void stack_underflow(void); + +#endif /* STACK_H_ */ diff --git a/16_Structures_Unions_Enumerations/Debug/16_Structures_Unions_Enumerations b/16_Structures_Unions_Enumerations/Debug/16_Structures_Unions_Enumerations new file mode 100644 index 0000000..e4d7c72 Binary files /dev/null and b/16_Structures_Unions_Enumerations/Debug/16_Structures_Unions_Enumerations differ diff --git a/16_Structures_Unions_Enumerations/Debug/Examples/subdir.mk b/16_Structures_Unions_Enumerations/Debug/Examples/subdir.mk new file mode 100644 index 0000000..2192f3a --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/Examples/subdir.mk @@ -0,0 +1,27 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Examples/inventory.c \ +../Examples/readline.c + +OBJS += \ +./Examples/inventory.o \ +./Examples/readline.o + +C_DEPS += \ +./Examples/inventory.d \ +./Examples/readline.d + + +# Each subdirectory must supply rules for building sources it contributes +Examples/%.o: ../Examples/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/16_Structures_Unions_Enumerations/Debug/Exercises/subdir.mk b/16_Structures_Unions_Enumerations/Debug/Exercises/subdir.mk new file mode 100644 index 0000000..33db727 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/Exercises/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Exercises/ex_07.c + +OBJS += \ +./Exercises/ex_07.o + +C_DEPS += \ +./Exercises/ex_07.d + + +# Each subdirectory must supply rules for building sources it contributes +Exercises/%.o: ../Exercises/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/16_Structures_Unions_Enumerations/Debug/Projects/pr_01/subdir.mk b/16_Structures_Unions_Enumerations/Debug/Projects/pr_01/subdir.mk new file mode 100644 index 0000000..4ad0b9f --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/Projects/pr_01/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_01/main.c + +OBJS += \ +./Projects/pr_01/main.o + +C_DEPS += \ +./Projects/pr_01/main.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/pr_01/%.o: ../Projects/pr_01/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/16_Structures_Unions_Enumerations/Debug/Projects/pr_02/subdir.mk b/16_Structures_Unions_Enumerations/Debug/Projects/pr_02/subdir.mk new file mode 100644 index 0000000..30a0d20 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/Projects/pr_02/subdir.mk @@ -0,0 +1,30 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_02/inventory.c \ +../Projects/pr_02/quicksort.c \ +../Projects/pr_02/readline.c + +OBJS += \ +./Projects/pr_02/inventory.o \ +./Projects/pr_02/quicksort.o \ +./Projects/pr_02/readline.o + +C_DEPS += \ +./Projects/pr_02/inventory.d \ +./Projects/pr_02/quicksort.d \ +./Projects/pr_02/readline.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/pr_02/%.o: ../Projects/pr_02/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/16_Structures_Unions_Enumerations/Debug/Projects/pr_03/subdir.mk b/16_Structures_Unions_Enumerations/Debug/Projects/pr_03/subdir.mk new file mode 100644 index 0000000..5d6abb4 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/Projects/pr_03/subdir.mk @@ -0,0 +1,27 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_03/inventory.c \ +../Projects/pr_03/readline.c + +OBJS += \ +./Projects/pr_03/inventory.o \ +./Projects/pr_03/readline.o + +C_DEPS += \ +./Projects/pr_03/inventory.d \ +./Projects/pr_03/readline.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/pr_03/%.o: ../Projects/pr_03/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/16_Structures_Unions_Enumerations/Debug/Projects/pr_04/subdir.mk b/16_Structures_Unions_Enumerations/Debug/Projects/pr_04/subdir.mk new file mode 100644 index 0000000..227e97c --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/Projects/pr_04/subdir.mk @@ -0,0 +1,27 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_04/inventory.c \ +../Projects/pr_04/readline.c + +OBJS += \ +./Projects/pr_04/inventory.o \ +./Projects/pr_04/readline.o + +C_DEPS += \ +./Projects/pr_04/inventory.d \ +./Projects/pr_04/readline.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/pr_04/%.o: ../Projects/pr_04/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/16_Structures_Unions_Enumerations/Debug/Projects/pr_05/subdir.mk b/16_Structures_Unions_Enumerations/Debug/Projects/pr_05/subdir.mk new file mode 100644 index 0000000..8c7abbc --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/Projects/pr_05/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_05/departures.c + +OBJS += \ +./Projects/pr_05/departures.o + +C_DEPS += \ +./Projects/pr_05/departures.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/pr_05/%.o: ../Projects/pr_05/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/16_Structures_Unions_Enumerations/Debug/Projects/pr_06/sooner_date.d b/16_Structures_Unions_Enumerations/Debug/Projects/pr_06/sooner_date.d new file mode 100644 index 0000000..efc8b75 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/Projects/pr_06/sooner_date.d @@ -0,0 +1 @@ +Projects/pr_06/sooner_date.d: ../Projects/pr_06/sooner_date.c diff --git a/16_Structures_Unions_Enumerations/Debug/Projects/pr_06/sooner_date.o b/16_Structures_Unions_Enumerations/Debug/Projects/pr_06/sooner_date.o new file mode 100644 index 0000000..ace7b92 Binary files /dev/null and b/16_Structures_Unions_Enumerations/Debug/Projects/pr_06/sooner_date.o differ diff --git a/16_Structures_Unions_Enumerations/Debug/Projects/pr_06/subdir.mk b/16_Structures_Unions_Enumerations/Debug/Projects/pr_06/subdir.mk new file mode 100644 index 0000000..b06c1c7 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/Projects/pr_06/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_06/sooner_date.c + +OBJS += \ +./Projects/pr_06/sooner_date.o + +C_DEPS += \ +./Projects/pr_06/sooner_date.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/pr_06/%.o: ../Projects/pr_06/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/16_Structures_Unions_Enumerations/Debug/makefile b/16_Structures_Unions_Enumerations/Debug/makefile new file mode 100644 index 0000000..e6afbee --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/makefile @@ -0,0 +1,44 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include Projects/pr_06/subdir.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 16_Structures_Unions_Enumerations + +# Tool invocations +16_Structures_Unions_Enumerations: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "16_Structures_Unions_Enumerations" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 16_Structures_Unions_Enumerations + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/16_Structures_Unions_Enumerations/Debug/sources.mk b/16_Structures_Unions_Enumerations/Debug/sources.mk new file mode 100644 index 0000000..55a3c01 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Debug/sources.mk @@ -0,0 +1,17 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +O_SRCS := +C_SRCS := +S_UPPER_SRCS := +OBJ_SRCS := +ASM_SRCS := +OBJS := +C_DEPS := +EXECUTABLES := + +# Every subdirectory with source files must be described here +SUBDIRS := \ +Projects/pr_06 \ + diff --git a/16_Structures_Unions_Enumerations/Examples/inventory.c b/16_Structures_Unions_Enumerations/Examples/inventory.c new file mode 100644 index 0000000..1b1789d --- /dev/null +++ b/16_Structures_Unions_Enumerations/Examples/inventory.c @@ -0,0 +1,132 @@ +/* + * inventory.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + + +/* Maintains a parts database (array version) */ +#include +#include "readline.h" + +#define NAME_LEN 25 +#define MAX_PARTS 100 + +struct part { + int number; + char name[NAME_LEN + 1]; + int on_hand; +} inventory [MAX_PARTS]; + +int num_parts = 0; + +int find_part(int number); +void insert(void); +void search(void); +void update(void); +void print(void); + +int main(void) { + char code; + + while (1) { + printf("Enter operation code: "); + scanf(" %c", &code); + while (getchar() != '\n') + ; + switch (code) { + case 'i': + insert(); + break; + case 's': + search(); + break; + case 'u': + update(); + break; + case 'p': + print(); + break; + case 'q': + return 0; + default: + printf("Illegal code\n"); + break; + } + printf("\n"); + } +} + +int find_part(int number) { + int i; + + for (i = 0; i < num_parts; i++) + if (inventory[i].number == number) + return i; + return -1; +} + +void insert(void) { + int part_number; + + if (num_parts == MAX_PARTS) { + printf("Database is full; can't add more parts.\n"); + return; + } + + printf("Enter part number: "); + scanf("%d", &part_number); + + if (find_part(part_number) >= 0) { + printf("Part already exists.\n"); + return; + } + + inventory[num_parts].number = part_number; + printf("Enter part name: "); + read_line(inventory[num_parts].name, NAME_LEN); + printf("Enter quantity on hand: "); + scanf("%d", &inventory[num_parts].on_hand); + num_parts++; +} + +void search(void) { + int i, number; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number); + if (i >= 0) { + printf("Part name: %s\n", inventory[i].name); + printf("Quantity on hand: %d\n", inventory[i].on_hand); + } + else + printf("Part not found.\n"); +} + +void update(void) { + int i, number, change; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number); + if (i >= 0) { + printf("Enter change in quantity on hand: "); + scanf("%d", &change); + inventory[i].on_hand += change; + } + else + printf("Part not found.\n"); +} + +void print(void) { + int i; + printf("Part Number Part Name " + "Quantity on Hand\n"); + for (i = 0; i < num_parts; i++) + printf("%7d %-25s%11d\n", inventory[i].number, + inventory[i].name, inventory[i].on_hand); +} + + diff --git a/16_Structures_Unions_Enumerations/Examples/readline.c b/16_Structures_Unions_Enumerations/Examples/readline.c new file mode 100644 index 0000000..4e09c5e --- /dev/null +++ b/16_Structures_Unions_Enumerations/Examples/readline.c @@ -0,0 +1,25 @@ +/* + * readline.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + +#include +#include +#include "readline.h" + +int read_line(char str[], int n) { + int ch, i = 0; + + while (isspace(ch = getchar())) + ; + while (ch != '\n' &&ch != EOF) { + if (i < n) + str[i++] = ch; + ch = getchar(); + } + str[i] = '\0'; + return i; +} + diff --git a/16_Structures_Unions_Enumerations/Examples/readline.h b/16_Structures_Unions_Enumerations/Examples/readline.h new file mode 100644 index 0000000..70225f9 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Examples/readline.h @@ -0,0 +1,13 @@ +/* + * readline.h + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + +#ifndef READLINE_H_ +#define READLINE_H_ + +int read_line(char str[], int n); + +#endif /* READLINE_H_ */ diff --git a/16_Structures_Unions_Enumerations/Exercises/ex_01_06.c b/16_Structures_Unions_Enumerations/Exercises/ex_01_06.c new file mode 100644 index 0000000..a583ddc --- /dev/null +++ b/16_Structures_Unions_Enumerations/Exercises/ex_01_06.c @@ -0,0 +1,120 @@ +#include + +// ex_01 +// They are different structures - LEGAL +struct { int x, y; } x; +struct { int x, y; } y; + +// ex_02 +struct { + double real, imaginary; +} c1 = {.real = 0.0, .imaginary = 1.0}, + c2 = {.real = 1.0, .imaginary = 0.0}, + c3; + +// ex_03 +struct complex { + double real, imaginary; +}; + +struct complex make_complex1(double real, double imaginary) { + struct complex c; + + c.real = real; + c.imaginary = imaginary; + return c; +} + +struct complex add_complex1(struct complex c1, struct complex c2) { + struct complex c3; + + c3.real = c1.real + c2.real; + c3.imaginary = c1.imaginary + c2.imaginary; + + return c3; +} + + + +// ex_04 +typedef struct { + double real, imaginary; +} Complex; + +Complex make_complex2(double real, double imaginary) { + Complex c; + + c.real = real; + c.imaginary = imaginary; + return c; +} + +Complex add_complex2(Complex c1, Complex c2) { + Complex c3; + + c3.real = c1.real + c2.real; + c3.imaginary = c1.imaginary + c2.imaginary; + + return c3; +} + +// ex_05 +struct date { + int day, month, year; +}; + +int day_of_year(struct date d); +int compare_dates(struct date d1, struct date d2); + +// ex_06 +struct time { + short hours, minutes, seconds; +}; + +struct time split_time(long total_seconds); + +// MAIN +int main(void) { + long s = 86401 * 5; + struct time t = split_time(s); + printf("%ld seconds is %hd hours, %hd minutes and %hd seconds", + s, t.hours, t.minutes, t.seconds); + + return 0; +} + +int day_of_year(struct date d) { + int feb = (d.year % 4 == 0) ? 29 : 28; + int days_in_months[] = {0, + 31, feb, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; + int i, days = d.day; + for (i = 1; i < d.month; i++) + days += days_in_months[i]; + + return days; +} + +int compare_dates(struct date d1, struct date d2) { + // Trasnforms date into days + int days1 = day_of_year(d1) + d1.year * 365 + (d1.year % 4); + int days2 = day_of_year(d2) + d2.year * 365 + (d2.year % 4); + + if (days1 < days2) + return -1; + else if (days1 == days2) + return 0; + else + return 1; +} + +struct time split_time(long total_seconds) { + struct time t; + t.hours = total_seconds / 3600; + total_seconds %= 3600; + t.minutes = total_seconds / 60; + t.seconds = total_seconds % 60; + return t; +} + + diff --git a/16_Structures_Unions_Enumerations/Exercises/ex_07.c b/16_Structures_Unions_Enumerations/Exercises/ex_07.c new file mode 100644 index 0000000..64dcf14 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Exercises/ex_07.c @@ -0,0 +1,88 @@ +/* + * ex_07.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + +// Fuctions for working with fractions + +#include + +struct fraction { + int numerator, denominator; +}; + +struct fraction reduce(struct fraction f); +struct fraction add(struct fraction f1, struct fraction f2); +struct fraction substract(struct fraction f1, struct fraction f2); +struct fraction multiply(struct fraction f1, struct fraction f2); +struct fraction divide(struct fraction f1, struct fraction f2); + + +int main() { + struct fraction f, f1, f2; + printf("fraction 1: "); + scanf("%d / %d", &f1.numerator, &f1.denominator); + printf("fraction 2: "); + scanf("%d / %d", &f2.numerator, &f2.denominator); + + f = add(f1, f2); + printf("added: %d/%d\n", f.numerator, f.denominator); + f = substract(f1, f2); + printf("substracted: %d/%d\n", f.numerator, f.denominator); + f = multiply(f1, f2); + printf("multiplied: %d/%d\n", f.numerator, f.denominator); + f = divide(f1, f2); + printf("divided: %d/%d\n", f.numerator, f.denominator); + + return 0; +} + +struct fraction reduce(struct fraction f) { + int remainder; + struct fraction g = f; + + while (g.denominator != 0) { + remainder = g.numerator % g.denominator; + g.numerator = g.denominator; + g.denominator = remainder; + } + // g.numerator is the GCD of both now + f.numerator /= g.numerator; + f.denominator /= g.numerator; + + return f; +} + +struct fraction add(struct fraction f1, struct fraction f2) { + struct fraction f; + f.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator; + f.denominator = f1.denominator * f2.denominator; + + return reduce(f); +} + +struct fraction substract(struct fraction f1, struct fraction f2) { + struct fraction f; + f.numerator = f1.numerator * f2.denominator - f2.numerator * f1.denominator; + f.denominator = f1.denominator * f2.denominator; + + return reduce(f); +} + +struct fraction multiply(struct fraction f1, struct fraction f2) { + struct fraction f; + f.numerator = f1.numerator * f2.numerator; + f.denominator = f1.denominator * f2.denominator; + + return reduce(f); +} + +struct fraction divide(struct fraction f1, struct fraction f2) { + struct fraction f; + f.numerator = f1.numerator * f2.denominator; + f.denominator = f1.denominator * f2.numerator; + + return reduce(f); +} diff --git a/16_Structures_Unions_Enumerations/Exercises/ex_08.c b/16_Structures_Unions_Enumerations/Exercises/ex_08.c new file mode 100644 index 0000000..c556a75 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Exercises/ex_08.c @@ -0,0 +1,14 @@ +/* + * ex_08.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + + + +#define MAGNETA struct color(.red = 255, .blue = 255) + +struct color { + int red, green, blue; +}; diff --git a/16_Structures_Unions_Enumerations/Projects/pr_01/main.c b/16_Structures_Unions_Enumerations/Projects/pr_01/main.c new file mode 100644 index 0000000..7e85e09 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Projects/pr_01/main.c @@ -0,0 +1,52 @@ +/* + * main.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + +#include + +#define COUNTRY_COUNT \ + ((int) (sizeof(country_codes) / sizeof(country_codes[0]))) + +struct dialing_code { + char *country; + int code; +}; + +const struct dialing_code country_codes[] = + {{"Argentina", 54}, {"Bangladesh", 880}, + {"Brazil", 55}, {"Burma (Myanmar)", 95}, + {"China", 86}, {"Colombia", 57}, + {"Congo, Dem. Rep. of", 243}, {"Egypt", 20}, + {"Ethiopia", 251}, {"France", 33}, + {"Germany", 49}, {"India", 91}, + {"Indonesia", 62}, {"Iran", 98}, + {"Italy", 39}, {"Japan", 81}, + {"Mexico", 52}, {"Nigeria", 234}, + {"Pakistan", 92}, {"Philippines", 63}, + {"Poland", 48}, {"Russia", 7}, + {"South Africa", 27}, {"South Korea", 82}, + {"Spain", 34}, {"Sudan", 249}, + {"Thailand", 66}, {"Turkey", 90}, + {"Ukraine", 380}, {"United Kingdom", 44}, + {"United States", 1}, {"Vietnam", 84}}; + +int main(void) +{ + int code, i; + + printf("Enter dialing code: "); + scanf("%d", &code); + + for (i = 0; i < COUNTRY_COUNT; i++) + if (code == country_codes[i].code) { + printf("The country with dialing code %d is %s\n", + code, country_codes[i].country); + return 0; + } + + printf("No corresponding country found\n"); + return 0; +} diff --git a/16_Structures_Unions_Enumerations/Projects/pr_02/inventory.c b/16_Structures_Unions_Enumerations/Projects/pr_02/inventory.c new file mode 100644 index 0000000..2ddcdf4 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Projects/pr_02/inventory.c @@ -0,0 +1,167 @@ +/* + * inventory.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + + +/* Maintains a parts database (array version) + * Sorts output by part number before printing */ +#include +#include +#include "readline.h" +//#include "string.h" + +#define NAME_LEN 25 +#define MAX_PARTS 100 + +//typedef int (*compfn)(const void*, const void*); + +struct part { + int number; + char name[NAME_LEN + 1]; + int on_hand; +} inventory [MAX_PARTS]; + +int num_parts = 0; + +int find_part(int number); +void insert(void); +void search(void); +void update(void); +void print(void); +int compare(struct part *elem1, struct part *elem2); + +int main(void) { +// inventory[0].number = 3; +// strcpy(inventory[0].name, "b3"); +// inventory[0].on_hand = 1; +// +// inventory[1].number = 4; +// strcpy(inventory[1].name, "d4"); +// inventory[1].on_hand = 1; +// +// inventory[2].number = 2; +// strcpy(inventory[2].name, "c2"); +// inventory[2].on_hand = 1; +// +// inventory[3].number = 1; +// strcpy(inventory[3].name, "a1"); +// inventory[3].on_hand = 1; +// +// num_parts = 4; + + char code; + + while (1) { + printf("Enter operation code: "); + scanf(" %c", &code); + while (getchar() != '\n') + ; + switch (code) { + case 'i': + insert(); + break; + case 's': + search(); + break; + case 'u': + update(); + break; + case 'p': + print(); + break; + case 'q': + return 0; + default: + printf("Illegal code\n"); + break; + } + printf("\n"); + } +} + +int find_part(int number) { + int i; + + for (i = 0; i < num_parts; i++) + if (inventory[i].number == number) + return i; + return -1; +} + +void insert(void) { + int part_number; + + if (num_parts == MAX_PARTS) { + printf("Database is full; can't add more parts.\n"); + return; + } + + printf("Enter part number: "); + scanf("%d", &part_number); + + if (find_part(part_number) >= 0) { + printf("Part already exists.\n"); + return; + } + + inventory[num_parts].number = part_number; + printf("Enter part name: "); + read_line(inventory[num_parts].name, NAME_LEN); + printf("Enter quantity on hand: "); + scanf("%d", &inventory[num_parts].on_hand); + num_parts++; +} + +void search(void) { + int i, number; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number); + if (i >= 0) { + printf("Part name: %s\n", inventory[i].name); + printf("Quantity on hand: %d\n", inventory[i].on_hand); + } + else + printf("Part not found.\n"); +} + +void update(void) { + int i, number, change; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number); + if (i >= 0) { + printf("Enter change in quantity on hand: "); + scanf("%d", &change); + inventory[i].on_hand += change; + } + else + printf("Part not found.\n"); +} + +void print(void) { + int i; + printf("Part Number Part Name " + "Quantity on Hand\n"); + qsort(inventory, num_parts, sizeof(struct part), compare); + for (i = 0; i < num_parts; i++) + printf("%7d %-25s%11d\n", inventory[i].number, + inventory[i].name, inventory[i].on_hand); +} + +int compare(struct part *elem1, struct part *elem2) { + if ( elem1->number < elem2->number) + return -1; + + else if (elem1->number > elem2->number) + return 1; + + else + return 0; +} + diff --git a/16_Structures_Unions_Enumerations/Projects/pr_03/inventory.c b/16_Structures_Unions_Enumerations/Projects/pr_03/inventory.c new file mode 100644 index 0000000..19a0410 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Projects/pr_03/inventory.c @@ -0,0 +1,165 @@ +/* + * inventory.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ +// ORDERED LIST +#include +#include "readline.h" + +#define NAME_LEN 25 +#define MAX_PARTS 100 + +struct part { + int number; + char name[NAME_LEN+1]; + int on_hand; +}; + +int find_part(int number, const struct part inv[], int np); +void insert(struct part inv[], int *np); +void search(const struct part inv[], int np); +void update(struct part inv[], int np); +void print(const struct part inv[], int np); + +/********************************************************** + * main: Prompts the user to enter an operation code, * + * then calls a function to perform the requested * + * action. Repeats until the user enters the * + * command 'q'. Prints an error message if the user * + * enters an illegal code. * + **********************************************************/ +int main(void) +{ + char code; + struct part inventory[MAX_PARTS]; + int num_parts = 0; + + for (;;) { + printf("Enter operation code: "); + scanf(" %c", &code); + while (getchar() != '\n') /* skips to end of line */ + ; + switch (code) { + case 'i': insert(inventory, &num_parts); + break; + case 's': search(inventory, num_parts); + break; + case 'u': update(inventory, num_parts); + break; + case 'p': print(inventory, num_parts); + break; + case 'q': return 0; + default: printf("Illegal code\n"); + break; + } + printf("\n"); + } +} + +/********************************************************** + * find_part: Looks up a part number in the inv array. * + * Returns the array index if the part number * + * is found; otherwise, returns -1. * + **********************************************************/ +int find_part(int number, const struct part inv[], int np) +{ + int i; + + for (i = 0; i < np; i++) + if (inv[i].number == number) + return i; + return -1; +} + +/********************************************************** + * insert: Prompts the user for information about a new * + * part and then inserts the part into the inv * + * array. Prints an error message and returns * + * prematurely if the part already exists or the * + * array is full. * + **********************************************************/ +void insert(struct part inv[], int *np) +{ + int part_number; + + if (*np == MAX_PARTS) { + printf("Database is full; can't add more parts.\n"); + return; + } + + printf("Enter part number: "); + scanf("%d", &part_number); + if (find_part(part_number, inv, *np) >= 0) { + printf("Part already exists.\n"); + return; + } + + inv[*np].number = part_number; + printf("Enter part name: "); + read_line(inv[*np].name, NAME_LEN); + printf("Enter quantity on hand: "); + scanf("%d", &inv[*np].on_hand); + (*np)++; +} + +/********************************************************** + * search: Prompts the user to enter a part number, then * + * looks up the part in the inv array. If the * + * part exists, prints the name and quantity on * + * hand; if not, prints an error message. * + **********************************************************/ +void search(const struct part inv[], int np) +{ + int i, number; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number, inv, np); + if (i >= 0) { + printf("Part name: %s\n", inv[i].name); + printf("Quantity on hand: %d\n", inv[i].on_hand); + } else + printf("Part not found.\n"); +} + +/********************************************************** + * update: Prompts the user to enter a part number. * + * Prints an error message if the part can't be * + * found in the inv array; otherwise, prompts the * + * user to enter change in quantity on hand and * + * updates the array. * + **********************************************************/ +void update(struct part inv[], int np) +{ + int i, number, change; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number, inv, np); + if (i >= 0) { + printf("Enter change in quantity on hand: "); + scanf("%d", &change); + inv[i].on_hand += change; + } else + printf("Part not found.\n"); +} + +/********************************************************** + * print: Prints a listing of all parts in the inv array, * + * showing the part number, part name, and * + * quantity on hand. Parts are printed in the * + * order in which they were entered into the * + * array. * + **********************************************************/ +void print(const struct part inv[], int np) +{ + int i; + + printf("Part Number Part Name " + "Quantity on Hand\n"); + for (i = 0; i < np; i++) + printf("%7d %-25s%11d\n", inv[i].number, + inv[i].name, inv[i].on_hand); +} diff --git a/16_Structures_Unions_Enumerations/Projects/pr_04/inventory.c b/16_Structures_Unions_Enumerations/Projects/pr_04/inventory.c new file mode 100644 index 0000000..4064f88 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Projects/pr_04/inventory.c @@ -0,0 +1,141 @@ +/* + * inventory.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + + +/* Maintains a parts database (array version) + * MODIFIED: added price */ +#include +#include "readline.h" + +#define NAME_LEN 25 +#define MAX_PARTS 100 + +struct part { + int number; + char name[NAME_LEN + 1]; + int on_hand; + double price; +} inventory [MAX_PARTS]; + +int num_parts = 0; + +int find_part(int number); +void insert(void); +void search(void); +void update(void); +void print(void); + +int main(void) { + char code; + + while (1) { + printf("Enter operation code: "); + scanf(" %c", &code); + while (getchar() != '\n') + ; + switch (code) { + case 'i': + insert(); + break; + case 's': + search(); + break; + case 'u': + update(); + break; + case 'p': + print(); + break; + case 'q': + return 0; + default: + printf("Illegal code\n"); + break; + } + printf("\n"); + } +} + +int find_part(int number) { + int i; + + for (i = 0; i < num_parts; i++) + if (inventory[i].number == number) + return i; + return -1; +} + +void insert(void) { + int part_number; + + if (num_parts == MAX_PARTS) { + printf("Database is full; can't add more parts.\n"); + return; + } + + printf("Enter part number: "); + scanf("%d", &part_number); + + if (find_part(part_number) >= 0) { + printf("Part already exists.\n"); + return; + } + + inventory[num_parts].number = part_number; + printf("Enter part name: "); + read_line(inventory[num_parts].name, NAME_LEN); + printf("Enter quantity on hand: "); + scanf("%d", &inventory[num_parts].on_hand); + printf("Enter price of a part: "); + scanf("%lf", &inventory[num_parts].price); + num_parts++; +} + +void search(void) { + int i, number; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number); + if (i >= 0) { + printf("Part name: %s\n", inventory[i].name); + printf("Quantity on hand: %d\n", inventory[i].on_hand); + printf("Price of the part: %d\n", inventory[i].price); + } + else + printf("Part not found.\n"); +} + +void update(void) { + int i, number, change; + double changee; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number); + if (i >= 0) { + printf("Enter change in quantity on hand: "); + scanf("%d", &change); + inventory[i].on_hand += change; + printf("Enter change in price: "); + scanf("%lf", &changee); + inventory[i].price += changee; + } + else + printf("Part not found.\n"); +} + +void print(void) { + int i; + printf("Part Number Part Name " + "Qty Price\n"); + for (i = 0; i < num_parts; i++) + printf("%7d %-25s%4d%15.2f\n", inventory[i].number, + inventory[i].name, inventory[i].on_hand, inventory[i].price); +} + + diff --git a/16_Structures_Unions_Enumerations/Projects/pr_05/departures.c b/16_Structures_Unions_Enumerations/Projects/pr_05/departures.c new file mode 100644 index 0000000..e50a8e8 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Projects/pr_05/departures.c @@ -0,0 +1,56 @@ +/* + * departures.c + * + * Created on: Jun 17, 2013 + * Author: delmadord + */ + +#include + +#define NUM_FLIGHTS \ + ((int) (sizeof(ft) / sizeof(ft[0]))) + +#define ABS(x) ((x) >= 0 ? (x) : -(x)) + +// number of minutes since midnight +struct flight { + int departure, arrival; +}; + +struct time { + int hours, minutes; +}; + +// Flight departures +int main(void) { + // Departures + const struct flight ft[] = { + {480, 616}, {583, 712}, {679, 811}, + {767, 900}, {840, 968}, {945, 1075}, + {1140, 1280}, {1305, 1438}}; + // Pointer to closest departure + struct flight *cp; + // Stored time + struct time t; + + printf("Enter a 24-hour time: "); + scanf("%2d:%2d", &t.hours, &t.minutes); + + // Minutes + int since_midnight = t.hours * 60 + t.minutes; + // Anything sooner than midnight (1440 min) will fit + int i, closest = 1440; + for (i = 0; i < NUM_FLIGHTS; i++) { + int delta = ABS(ft[i].departure - since_midnight); + if (delta < closest) { + closest = delta; + cp = &ft[i]; + } + } + + printf("Closest departure time is %2d:%.2d a.m., arriving at %2d:%.2d a.m.", + cp->departure / 60, cp->departure % 60, + cp->arrival /60, cp->arrival % 60); + + return 0; +} diff --git a/16_Structures_Unions_Enumerations/Projects/pr_06/sooner_date.c b/16_Structures_Unions_Enumerations/Projects/pr_06/sooner_date.c new file mode 100644 index 0000000..d42e215 --- /dev/null +++ b/16_Structures_Unions_Enumerations/Projects/pr_06/sooner_date.c @@ -0,0 +1,61 @@ +/* + * sooner_date.c + * + * Created on: Jun 17, 2013 + * Author: delmadord + */ + +#include + +struct date { + int day, month, year; +}; + +int day_of_year(struct date d); +int compare_dates(struct date d1, struct date d2); + +// Which date is sooner +int main(void) { + struct date d1, d2; + + printf("Enter first date: "); + scanf("%d/%d/%d", &d1.day, &d1.month, &d1.year); + printf("Enter second date: "); + scanf("%d/%d/%d", &d2.day, &d2.month, &d2.year); + + if (compare_dates(d1, d2) < 0) + printf("%d/%d/%d is earlier than %d/%d/%d.", + d1.day, d1.month, d1.year, d2.day, d2.month, d2.year); + else if (compare_dates(d1, d2) > 0) + printf("%d/%d/%d is earlier than %d/%d/%d.", + d2.day, d2.month, d2.year, d1.day, d1.month, d1.year); + else + printf("Dates are the same."); + + return 0; +} + +int day_of_year(struct date d) { + int feb = (d.year % 4 == 0) ? 29 : 28; + int days_in_months[] = {0, + 31, feb, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; + int i, days = d.day; + for (i = 1; i < d.month; i++) + days += days_in_months[i]; + + return days; +} + +int compare_dates(struct date d1, struct date d2) { + // Trasnforms date into days + int days1 = day_of_year(d1) + d1.year * 365 + (d1.year % 4); + int days2 = day_of_year(d2) + d2.year * 365 + (d2.year % 4); + + if (days1 < days2) + return -1; + else if (days1 == days2) + return 0; + else + return 1; +} diff --git a/17_Advanced_Uses_of_Pointers/Debug/17_Advanced_Uses_of_Pointers b/17_Advanced_Uses_of_Pointers/Debug/17_Advanced_Uses_of_Pointers new file mode 100644 index 0000000..3f1fbe2 Binary files /dev/null and b/17_Advanced_Uses_of_Pointers/Debug/17_Advanced_Uses_of_Pointers differ diff --git a/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_06/subdir.mk b/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_06/subdir.mk new file mode 100644 index 0000000..d42c34f --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_06/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_06/words_sort.c + +OBJS += \ +./Projects/pr_06/words_sort.o + +C_DEPS += \ +./Projects/pr_06/words_sort.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/pr_06/%.o: ../Projects/pr_06/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_07/remind2.d b/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_07/remind2.d new file mode 100644 index 0000000..95ad846 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_07/remind2.d @@ -0,0 +1 @@ +Projects/pr_07/remind2.d: ../Projects/pr_07/remind2.c diff --git a/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_07/remind2.o b/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_07/remind2.o new file mode 100644 index 0000000..291c628 Binary files /dev/null and b/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_07/remind2.o differ diff --git a/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_07/subdir.mk b/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_07/subdir.mk new file mode 100644 index 0000000..2ae40fa --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Debug/Projects/pr_07/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Projects/pr_07/remind2.c + +OBJS += \ +./Projects/pr_07/remind2.o + +C_DEPS += \ +./Projects/pr_07/remind2.d + + +# Each subdirectory must supply rules for building sources it contributes +Projects/pr_07/%.o: ../Projects/pr_07/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/17_Advanced_Uses_of_Pointers/Debug/makefile b/17_Advanced_Uses_of_Pointers/Debug/makefile new file mode 100644 index 0000000..25fe705 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Debug/makefile @@ -0,0 +1,44 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include Projects/pr_07/subdir.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 17_Advanced_Uses_of_Pointers + +# Tool invocations +17_Advanced_Uses_of_Pointers: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "17_Advanced_Uses_of_Pointers" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 17_Advanced_Uses_of_Pointers + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/17_Advanced_Uses_of_Pointers/Debug/objects.mk b/17_Advanced_Uses_of_Pointers/Debug/objects.mk new file mode 100644 index 0000000..519277b --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Debug/objects.mk @@ -0,0 +1,8 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +USER_OBJS := + +LIBS := -lm + diff --git a/17_Advanced_Uses_of_Pointers/Debug/sources.mk b/17_Advanced_Uses_of_Pointers/Debug/sources.mk new file mode 100644 index 0000000..3881b90 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Debug/sources.mk @@ -0,0 +1,17 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +O_SRCS := +C_SRCS := +S_UPPER_SRCS := +OBJ_SRCS := +ASM_SRCS := +OBJS := +C_DEPS := +EXECUTABLES := + +# Every subdirectory with source files must be described here +SUBDIRS := \ +Projects/pr_07 \ + diff --git a/17_Advanced_Uses_of_Pointers/Examples/inventory2/inventory2.c b/17_Advanced_Uses_of_Pointers/Examples/inventory2/inventory2.c new file mode 100644 index 0000000..18344f6 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Examples/inventory2/inventory2.c @@ -0,0 +1,149 @@ +/* + * inventory2.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + + +/* Maintains a parts database (array version) */ +#include +#include +#include "readline.h" + +#define NAME_LEN 25 + +struct part { + int number; + char name[NAME_LEN + 1]; + int on_hand; + struct part *next; +}; + +struct part *inventory = NULL; + +struct part *find_part(int number); +void insert(void); +void search(void); +void update(void); +void print(void); + +int main(void) { + char code; + + while (1) { + printf("Enter operation code: "); + scanf(" %c", &code); + while (getchar() != '\n') + ; + switch (code) { + case 'i': + insert(); + break; + case 's': + search(); + break; + case 'u': + update(); + break; + case 'p': + print(); + break; + case 'q': + return 0; + default: + printf("Illegal code\n"); + break; + } + printf("\n"); + } +} + +struct part *find_part(int number) { + struct part *p; + + for (p = inventory; + p != NULL && number > p->number; + p = p->next) + ; + if (p != NULL && number == p->number) + return p; + return NULL; +} + +void insert(void) { + struct part *cur, *prev, *new_node; + + new_node = malloc(sizeof(struct part)); + if (new_node == NULL) { + printf("Database is full; can't add more parts.\n"); + return; + } + + printf("Enter part number: "); + scanf("%d", &new_node->number); + + for (cur = inventory, prev = NULL; + cur != NULL && new_node->number > cur->number; + prev = cur, cur = cur->next) + ; + + if (cur != NULL && new_node->number == cur->number) { + printf("Part already exists.\n"); + free(new_node); + return; + } + + printf("Enter part name: "); + read_line(new_node->name, NAME_LEN); + printf("Enter quantity on hand: "); + scanf("%d", &new_node->on_hand); + + new_node->next = cur; + if (prev == NULL) + inventory = new_node; + else + prev->next = new_node; +} + +void search(void) { + int number; + struct part *p; + + printf("Enter part number: "); + scanf("%d", &number); + p = find_part(number); + if (p != NULL) { + printf("Part name: %s\n", p->name); + printf("Quantity on hand: %d\n", p->on_hand); + } + else + printf("Part not found.\n"); +} + +void update(void) { + int number, change; + struct part *p; + + printf("Enter part number: "); + scanf("%d", &number); + p = find_part(number); + if (p != NULL) { + printf("Enter change in quantity on hand: "); + scanf("%d", &change); + p->on_hand += change; + } + else + printf("Part not found.\n"); +} + +void print(void) { + struct part *p; + printf("Part Number Part Name " + "Quantity on Hand\n"); + for (p = inventory; p != NULL; p = p->next) + printf("%7d %-25s%11d\n", p->number, + p->name, p->on_hand); +} + + diff --git a/17_Advanced_Uses_of_Pointers/Examples/remind2.c b/17_Advanced_Uses_of_Pointers/Examples/remind2.c new file mode 100644 index 0000000..dae2f28 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Examples/remind2.c @@ -0,0 +1,72 @@ +/* + * remind2.c + * + * Created on: Jun 17, 2013 + * Author: delmadord + */ + + + +// Prints a one-month reminder list + +#include +#include +#include + +#define MAX_REMIND 50 +#define MSG_LEN 60 + +int read_line(char str[], int n); + +int main(void) { + char *reminders[MAX_REMIND]; + char day_str[3], msg_str[MSG_LEN + 1]; + int day, i, j, num_remind = 0; + + while (1) { + if (num_remind == MAX_REMIND) { + printf("-- No space left --n"); + break; + } + + printf("Enter day reminder: "); + scanf("%2d", &day); + if (day == 0) + break; + sprintf(day_str, "%2d", day); + read_line(msg_str, MSG_LEN); + + for (i = 0; i < num_remind; i++) + if (strcmp(day_str, reminders[i]) < 0) + break; + for (j = num_remind; j > i; j--) + reminders[j] = reminders[j - i]; + + reminders[i] = malloc(2 + strlen(msg_str) + 1); + if (reminders[i] == NULL) { + printf("-- No space left --\n"); + break; + } + + strcpy(reminders[i], day_str); + strcat(reminders[i], msg_str); + + num_remind++; + } + + printf("\nDay Reminder\n"); + for (i = 0; i < num_remind; i++) + printf(" %s\n", reminders[i]); + + return 0; +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} diff --git a/17_Advanced_Uses_of_Pointers/Examples/tabulate.c b/17_Advanced_Uses_of_Pointers/Examples/tabulate.c new file mode 100644 index 0000000..4e1d1d7 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Examples/tabulate.c @@ -0,0 +1,53 @@ +/* + * tabulate.c + * + * Created on: Jun 17, 2013 + * Author: delmadord + */ + + +#include +#include + +void tabulate(double (*f)(double), double first, + double last, double incr); + +int main(void) { + double final, increment, initial; + + printf("Enter initial value: "); + scanf("%lf", &initial); + + printf("Enter final value: "); + scanf("%lf", &final); + + printf("Enter increment: "); + scanf("%lf", &increment); + + printf("\n x cos(x)" + "\n ------- -------\n"); + tabulate(cos, initial, final, increment); + + printf("\n x sin(x)" + "\n ------- -------\n"); + tabulate(sin, initial, final, increment); + + printf("\n x tan(x)" + "\n ------- -------\n"); + tabulate(tan, initial, final, increment); + + return 0; +} + +void tabulate(double (*f)(double), double first, + double last, double incr) { + double x; + int i, num_intervals; + + num_intervals = ceil((last - first) / incr); + for (i = 0; i <= num_intervals; i++) { + x = first + i * incr; + printf("%10.5f %10.5f\n", x, (*f)(x)); + } +} + diff --git a/17_Advanced_Uses_of_Pointers/Exercises/ex_01_05.c b/17_Advanced_Uses_of_Pointers/Exercises/ex_01_05.c new file mode 100644 index 0000000..4c3a0a3 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Exercises/ex_01_05.c @@ -0,0 +1,88 @@ +/* + * ex_01_05.c + * + * Created on: Jun 17, 2013 + * Author: delmadord + */ + +#include +#include +#include + +#define COUNT(x) ((int) (sizeof(x) / sizeof(x[0]))) + +// ex_01 +void *my_malloc(size_t size); +// ex_02 +char *duplicate(const char *s); +// ex_03 +int *create_array(int n, int init); +// ex_04 +struct point {int x, y; }; +struct rectangle {struct point upper_left, lower_right; }; +struct rectangle *p; +// ex_05 +struct { + union { + char a, b; + int c; + } d; + int e[5]; +} f, *q = &f; + + +int main(void) { + char *str = "String to duplicate."; + char *dup = duplicate(str); + printf("%s\n\n", dup); + + + + int i, n = 5, *a = create_array(n, 5); + printf("The a array: "); + for (i = 0; i < n; i++) + printf("%d ", a[i]); + printf("\n\n"); + + + p->upper_left.x = 10; + p->upper_left.x = 25; + p->lower_right.x = 20; + p->lower_right.x = 15; + + +// q->b = ' '; + q->e[3] = 10; + (*q).d.a = '*'; +// q->d->c = 20; + + + return 0; +} + + +void *my_malloc(size_t size) { + void *p = malloc(size); + if (p == NULL) { + printf("Memory allocation unsuccessful.\n"); + exit(EXIT_FAILURE); + } + return p; +} + +char *duplicate(const char *s) { + char *temp = malloc(strlen(s) + 1); + + if (temp == NULL) + return NULL; + + strcpy(temp, s); + return temp; +} + +int *create_array(int n, int init) { + int i, *a = my_malloc(n * sizeof(int)); + for (i = 0; i < n; i++) + a[i] = init; + return a; +} diff --git a/17_Advanced_Uses_of_Pointers/Exercises/ex_08.c/stack.c b/17_Advanced_Uses_of_Pointers/Exercises/ex_08.c/stack.c new file mode 100644 index 0000000..2ac1735 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Exercises/ex_08.c/stack.c @@ -0,0 +1,63 @@ +/* + * stack.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + +#include /* C99 only */ +#include +#include +#include "stack.h" + +struct node { + int value; + struct node *next; +}; + +struct node *top = NULL; + +void make_empty(void) { + struct node *temp; + + while (top != NULL) { + temp = top; + top = top->next; + free(temp); + } +} + +bool is_empty(void) { + return top == NULL; +} + +bool push(int i) { + struct node *new_node; + + new_node = malloc(sizeof(struct node)); + if (new_node == NULL) + return false; + + new_node->value = i; + new_node->next = top; + top = new_node; + + return true; +} + +int pop(void) { + struct node *temp; + int i; + + if (is_empty()) { + printf("*** Stack underflow; program terminated. ***\n"); + exit(EXIT_FAILURE); + } + + i = top->value; + temp = top; + top = top->next; + free(temp); + + return i; +} diff --git a/17_Advanced_Uses_of_Pointers/Exercises/ex_09.c b/17_Advanced_Uses_of_Pointers/Exercises/ex_09.c new file mode 100644 index 0000000..99e2e24 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Exercises/ex_09.c @@ -0,0 +1,34 @@ +/* + * ex_09.c + * + * Created on: Jun 18, 2013 + * Author: delmadord + */ +#include +#include +#include + + +struct node{ + int value; + struct node *next; +}; + +int main(void) { + // ex_09 + struct node x; + if ((&x)->value == (*(&x)).value) + printf("(&x)->value is the same as (*(&x)).value\n"); + if ((*(&x)).value == (*&x).value) + printf("(*(&x)).value is the same as (*&x).value\n"); + if ((*&x).value == x.value) + printf("(*&x).value is the same as x.value\n"); + if ((&x)->value == x.value) + printf("So (&x)->value is the same as x.value\n\n"); + + + + + return 0; +} + diff --git a/17_Advanced_Uses_of_Pointers/Exercises/ex_15.c b/17_Advanced_Uses_of_Pointers/Exercises/ex_15.c new file mode 100644 index 0000000..9e5e9b0 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Exercises/ex_15.c @@ -0,0 +1,34 @@ +/* + * ex_15.c + * + * Created on: Jun 19, 2013 + * Author: delmadord + */ + +//Answer: 3 +//The program tests the values of f2(0), f2(1), f2(2), and so on, +//stopping when f2 returns zero. It then prints the argument that +//was passed to f2 to make it return zero. + +#include + +int f1(int (*f)(int)); +int f2(int i); + +int main(void) { + printf("Answer: %d\n", f1(f2)); + + return 0; +} + +int f1(int (*f)(int)) { + int n = 0; + while ((*f)(n)) + n++; + + return n; +} + +int f2(int i) { + return i * i + i - 12; +} diff --git a/17_Advanced_Uses_of_Pointers/Exercises/ex_16.c b/17_Advanced_Uses_of_Pointers/Exercises/ex_16.c new file mode 100644 index 0000000..98e84b5 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Exercises/ex_16.c @@ -0,0 +1,30 @@ +/* + * ex_16.c + * + * Created on: Jun 20, 2013 + * Author: delmadord + */ +#include + + +int sum(int (*f)(int), int start, int end); +int square(int x); + +int main(void) { + int s, e; + scanf("%d %d", &s, &e); + printf("%d", sum(square, s, e)); + + return 0; +} + +int sum(int (*f)(int), int start, int end) { + int sum = 0; + while (start <= end) + sum += (*f)(start++); + return sum; +} + +int square(int x) { + return x * x; +} diff --git a/17_Advanced_Uses_of_Pointers/Exercises/ex_19.c b/17_Advanced_Uses_of_Pointers/Exercises/ex_19.c new file mode 100644 index 0000000..0382949 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Exercises/ex_19.c @@ -0,0 +1,90 @@ +/* + * ex_19.c + * + * Created on: Jun 20, 2013 + * Author: delmadord + */ + +#include +#include + +#define COUNT(x) ((int) (sizeof(x) / sizeof(x[0]))) + +void new_cmd(void); +void open_cmd(void); +void close_cmd(void); +void close_all_cmd(void); +void save_cmd(void); +void save_as_cmd(void); +void save_all_cmd(void); +void print_cmd(void); +void exit_cmd(void); + +struct { + char *cmd_name; + void (*cmd_pointer)(void); +} file_cmd[] = { + {"new", new_cmd}, + {"open", open_cmd}, + {"close", close_cmd}, + {"close_all", close_all_cmd}, + {"save", save_cmd}, + {"save as", save_as_cmd}, + {"save_all", save_all_cmd}, + {"print", print_cmd}, + {"exit", exit_cmd} +}; + +int main(void) { + char user_cmd[15]; + printf("Enter command: "); + scanf("%s", user_cmd); + + int i; + for (i = 0; i < COUNT(file_cmd); i++) + if (strcmp(file_cmd[i].cmd_name, user_cmd) == 0) { + printf("command found: "); + file_cmd[i].cmd_pointer(); + return 0; + } + + printf("command not found"); + return 0; +} + +void new_cmd(void) { + printf("new"); +} + +void open_cmd(void) { + printf("open"); +} + +void close_cmd(void) { + printf("close"); +} + +void close_all_cmd(void) { + printf("close all"); +} + +void save_cmd(void) { + printf("save"); +} + +void save_as_cmd(void) { + printf("save as"); +} + +void save_all_cmd(void) { + printf("save all"); +} + +void print_cmd(void) { + printf("print"); +} + +void exit_cmd(void) { + printf("exit"); +} + diff --git a/17_Advanced_Uses_of_Pointers/Exercises/linked_exercises.c b/17_Advanced_Uses_of_Pointers/Exercises/linked_exercises.c new file mode 100644 index 0000000..8f7b56a --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Exercises/linked_exercises.c @@ -0,0 +1,176 @@ +/* + * linked_exercises.c + * + * Created on: Jun 24, 2013 + * Author: delmadord + */ + +#include +#include + + +struct node{ + int value; + struct node *next; +}; + +struct node *add_list_beginnig(struct node *list, int n); +struct node *add_list_end(struct node **list, int n); +struct node *search_list(struct node *list, int n); +void delete_from_list(struct node **list, int n); + +void truncate_list(struct node *list); + +int count_occurences(struct node *list, int n); +struct node *find_last(struct node *list, int n); + +void *my_malloc(size_t size); + +int main(void) { + struct node *q, *list = NULL; + add_list_end(&list, 1); + add_list_end(&list, 2); + add_list_end(&list, 3); +// truncate_list(list); + add_list_end(&list, 4); + add_list_end(&list, 5); + add_list_end(&list, 6); + + delete_from_list(&list, 1); + + + // Change n + int i, n = 2, c = count_occurences(list, n); + printf("occurences of %d: %d\n", n, c); + if (c > 0) { + struct node *p, *last_n = find_last(list, n); + for (i = 1, p = list; p != last_n; p = p->next, i++) + ; + printf("last occurence of %d is at %d. node\n\n", n, i); + } + printf("list itself:\n"); + q = list; + while (q != NULL) { + printf("\t%d\n", list->value); + list = list->next; + } + + return 0; +} + + +struct node *add_list_beginnig(struct node *list, int n) { + struct node *new_node = my_malloc(sizeof(struct node)); + + new_node->value = n; + new_node->next = list; + return new_node; +} + +// adds element to the end of the list +// in some cases, the brackets around *list aren't necessary, +// but I left there for consistency +struct node *add_list_end(struct node **list, int n) { + // make list point to pointer to last element + // (that is pointing to NULL) + while ((*list) != NULL) + list = &((*list)->next); + + // now list points to pointer to new node + // (the new last element, which now points to NULL) + (*list) = my_malloc(sizeof(struct node)); + (*list)->value = n; + (*list)->next = NULL; + + // returns the pointer to the new node (last element) + return (*list); +} + +struct node *insert_into_ordered_list + (struct node *list, struct node *new_node) { + // new_node is empty + if (new_node == NULL) + return NULL; + + // list is empty + if (list == NULL) { + list = new_node; + list->next = NULL; + return list; + } + + struct node *cur = list, *prev = NULL; + while (cur->value <= new_node->value) { + prev = cur; + cur = cur->next; + } + + prev->next = new_node; + new_node->next = cur; + return list; +} + +struct node *search_list(struct node *list, int n) { + while (list != NULL && list->value != n) + list = list->next; + return list; +} + +void delete_from_list(struct node **list, int n) { + // make list point to pointer to node before node with n + while ((*list)->next->value != n) { + list = &((*list)->next); + // next iteration would cause SF (otherwise, n wasnt found) + if ((*list)->next == NULL) + return; + } + + struct node *jump = (*list)->next->next; + free((*list)->next); + (*list)->next = jump; +} + + +void truncate_list(struct node *list) { + struct node *temp, *p = list; + while (p != NULL) { + temp = p; + p = p->next; + free(temp); + } +} + + + +// find how many times n occurs in the list, +int count_occurences(struct node *list, int n) { + int count = 0; + while (list != NULL) { + if (list->value == n) + count++; + list = list->next; + } + + return count; +} + +// returns pointer to the last node cointaining n, NULL if n not found +struct node *find_last(struct node *list, int n) { + struct node *p = NULL; + while (list != NULL) { + if (list->value == n) + p = list; + list = list->next; + } + return p; +} + +void *my_malloc(size_t size) { + void *p = malloc(size); + if (p == NULL) { + printf("Memory allocation unsuccessful.\n"); + exit(EXIT_FAILURE); + } + return p; +} + diff --git a/17_Advanced_Uses_of_Pointers/Projects/pr_01/inventory.c b/17_Advanced_Uses_of_Pointers/Projects/pr_01/inventory.c new file mode 100644 index 0000000..172a707 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Projects/pr_01/inventory.c @@ -0,0 +1,147 @@ +/* + * inventory.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + + +/* Maintains a parts database (array version) */ +#include +#include +#include "readline.h" + +#define NAME_LEN 25 +#define INIT_PARTS 10 + +struct part { + int number; + char name[NAME_LEN + 1]; + int on_hand; +}; + +struct part *inventory; + +int num_parts = 0; +int max_parts = INIT_PARTS; + +int find_part(int number); +void insert(void); +void search(void); +void update(void); +void print(void); + +int main(void) { + char code; + + inventory = malloc(max_parts * sizeof(struct part)); + if (inventory == NULL) { + printf("Can't allocate initial inventory space.\n"); + exit(EXIT_FAILURE); + } + + while (1) { + printf("Enter operation code: "); + scanf(" %c", &code); + while (getchar() != '\n') + ; + switch (code) { + case 'i': + insert(); + break; + case 's': + search(); + break; + case 'u': + update(); + break; + case 'p': + print(); + break; + case 'q': + return EXIT_SUCCESS; + default: + printf("Illegal code\n"); + break; + } + printf("\n"); + } +} + +int find_part(int number) { + int i; + + for (i = 0; i < num_parts; i++) + if (inventory[i].number == number) + return i; + return -1; +} + +void insert(void) { + int part_number; + struct part *temp; + + if (num_parts == max_parts) { + max_parts *= 2; + temp = realloc(inventory, max_parts * sizeof(struct part)); + if (temp == NULL) { + printf("Insufficient memory; can't add more parts.\n"); + return; + } + inventory = temp; + } + + printf("Enter part number: "); + scanf("%d", &part_number); + if (find_part(part_number) >= 0) { + printf("Part already exists.\n"); + return; + } + + inventory[num_parts].number = part_number; + printf("Enter part name: "); + read_line(inventory[num_parts].name, NAME_LEN); + printf("Enter quantity on hand: "); + scanf("%d", &inventory[num_parts].on_hand); + num_parts++; +} + +void search(void) { + int i, number; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number); + if (i >= 0) { + printf("Part name: %s\n", inventory[i].name); + printf("Quantity on hand: %d\n", inventory[i].on_hand); + } + else + printf("Part not found.\n"); +} + +void update(void) { + int i, number, change; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number); + if (i >= 0) { + printf("Enter change in quantity on hand: "); + scanf("%d", &change); + inventory[i].on_hand += change; + } + else + printf("Part not found.\n"); +} + +void print(void) { + int i; + printf("Part Number Part Name " + "Quantity on Hand\n"); + for (i = 0; i < num_parts; i++) + printf("%7d %-25s%11d\n", inventory[i].number, + inventory[i].name, inventory[i].on_hand); +} + + diff --git a/17_Advanced_Uses_of_Pointers/Projects/pr_02/inventory.c b/17_Advanced_Uses_of_Pointers/Projects/pr_02/inventory.c new file mode 100644 index 0000000..35da8ac --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Projects/pr_02/inventory.c @@ -0,0 +1,169 @@ +/* + * inventory.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + + +// COPY OF 16_pr_02 + +/* Maintains a parts database (array version) + * Sorts output by part number before printing */ +#include +#include +#include "readline.h" +//#include "string.h" + +#define NAME_LEN 25 +#define MAX_PARTS 100 + +//typedef int (*compfn)(const void*, const void*); + +struct part { + int number; + char name[NAME_LEN + 1]; + int on_hand; +} inventory [MAX_PARTS]; + +int num_parts = 0; + +int find_part(int number); +void insert(void); +void search(void); +void update(void); +void print(void); +int compare(struct part *elem1, struct part *elem2); + +int main(void) { +// inventory[0].number = 3; +// strcpy(inventory[0].name, "b3"); +// inventory[0].on_hand = 1; +// +// inventory[1].number = 4; +// strcpy(inventory[1].name, "d4"); +// inventory[1].on_hand = 1; +// +// inventory[2].number = 2; +// strcpy(inventory[2].name, "c2"); +// inventory[2].on_hand = 1; +// +// inventory[3].number = 1; +// strcpy(inventory[3].name, "a1"); +// inventory[3].on_hand = 1; +// +// num_parts = 4; + + char code; + + while (1) { + printf("Enter operation code: "); + scanf(" %c", &code); + while (getchar() != '\n') + ; + switch (code) { + case 'i': + insert(); + break; + case 's': + search(); + break; + case 'u': + update(); + break; + case 'p': + print(); + break; + case 'q': + return 0; + default: + printf("Illegal code\n"); + break; + } + printf("\n"); + } +} + +int find_part(int number) { + int i; + + for (i = 0; i < num_parts; i++) + if (inventory[i].number == number) + return i; + return -1; +} + +void insert(void) { + int part_number; + + if (num_parts == MAX_PARTS) { + printf("Database is full; can't add more parts.\n"); + return; + } + + printf("Enter part number: "); + scanf("%d", &part_number); + + if (find_part(part_number) >= 0) { + printf("Part already exists.\n"); + return; + } + + inventory[num_parts].number = part_number; + printf("Enter part name: "); + read_line(inventory[num_parts].name, NAME_LEN); + printf("Enter quantity on hand: "); + scanf("%d", &inventory[num_parts].on_hand); + num_parts++; +} + +void search(void) { + int i, number; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number); + if (i >= 0) { + printf("Part name: %s\n", inventory[i].name); + printf("Quantity on hand: %d\n", inventory[i].on_hand); + } + else + printf("Part not found.\n"); +} + +void update(void) { + int i, number, change; + + printf("Enter part number: "); + scanf("%d", &number); + i = find_part(number); + if (i >= 0) { + printf("Enter change in quantity on hand: "); + scanf("%d", &change); + inventory[i].on_hand += change; + } + else + printf("Part not found.\n"); +} + +void print(void) { + int i; + printf("Part Number Part Name " + "Quantity on Hand\n"); + qsort(inventory, num_parts, sizeof(struct part), compare); + for (i = 0; i < num_parts; i++) + printf("%7d %-25s%11d\n", inventory[i].number, + inventory[i].name, inventory[i].on_hand); +} + +int compare(struct part *elem1, struct part *elem2) { + if ( elem1->number < elem2->number) + return -1; + + else if (elem1->number > elem2->number) + return 1; + + else + return 0; +} + diff --git a/17_Advanced_Uses_of_Pointers/Projects/pr_03/inventory2.c b/17_Advanced_Uses_of_Pointers/Projects/pr_03/inventory2.c new file mode 100644 index 0000000..eae66aa --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Projects/pr_03/inventory2.c @@ -0,0 +1,173 @@ +/* + * inventory2.c + * + * Created on: Jun 16, 2013 + * Author: delmadord + */ + + +/* Maintains a parts database (array version) */ +#include +#include +#include "readline.h" + +#define NAME_LEN 25 + +struct part { + int number; + char name[NAME_LEN + 1]; + int on_hand; + struct part *next; +}; + +struct part *inventory = NULL; + +struct part *find_part(int number); +void insert(void); +void erase(void); +void search(void); +void update(void); +void print(void); + +int main(void) { + char code; + + while (1) { + printf("Enter operation code: "); + scanf(" %c", &code); + while (getchar() != '\n') + ; + switch (code) { + case 'i': + insert(); + break; + case 'e': + erase(); + break; + case 's': + search(); + break; + case 'u': + update(); + break; + case 'p': + print(); + break; + case 'q': + return 0; + default: + printf("Illegal code\n"); + break; + } + printf("\n"); + } +} + +struct part *find_part(int number) { + struct part *p; + + for (p = inventory; + p != NULL && number > p->number; + p = p->next) + ; + if (p != NULL && number == p->number) + return p; + return NULL; +} + +void insert(void) { + struct part *cur, *prev, *new_node; + + new_node = malloc(sizeof(struct part)); + if (new_node == NULL) { + printf("Database is full; can't add more parts.\n"); + return; + } + + printf("Enter part number: "); + scanf("%d", &new_node->number); + + for (cur = inventory, prev = NULL; + cur != NULL && new_node->number > cur->number; + prev = cur, cur = cur->next) + ; + + if (cur != NULL && new_node->number == cur->number) { + printf("Part already exists.\n"); + free(new_node); + return; + } + + printf("Enter part name: "); + read_line(new_node->name, NAME_LEN); + printf("Enter quantity on hand: "); + scanf("%d", &new_node->on_hand); + + new_node->next = cur; + if (prev == NULL) + inventory = new_node; + else + prev->next = new_node; +} + +void erase(void) { + int number; + printf("Enter part number: "); + scanf("%d", &number); + struct part *p = inventory, *temp; + while (p->next != NULL) { + if (p->next->number == number) { + temp = p->next->next; + free(p->next); + p->next = temp; + printf("%d erased successfuly.\n", number); + return; + } + p = p->next; + } + + printf("%d not found.\n", number); +} + + +void search(void) { + int number; + struct part *p; + + printf("Enter part number: "); + scanf("%d", &number); + p = find_part(number); + if (p != NULL) { + printf("Part name: %s\n", p->name); + printf("Quantity on hand: %d\n", p->on_hand); + } + else + printf("Part not found.\n"); +} + +void update(void) { + int number, change; + struct part *p; + + printf("Enter part number: "); + scanf("%d", &number); + p = find_part(number); + if (p != NULL) { + printf("Enter change in quantity on hand: "); + scanf("%d", &change); + p->on_hand += change; + } + else + printf("Part not found.\n"); +} + +void print(void) { + struct part *p; + printf("Part Number Part Name " + "Quantity on Hand\n"); + for (p = inventory; p != NULL; p = p->next) + printf("%7d %-25s%11d\n", p->number, + p->name, p->on_hand); +} + + diff --git a/17_Advanced_Uses_of_Pointers/Projects/pr_04/NOTE b/17_Advanced_Uses_of_Pointers/Projects/pr_04/NOTE new file mode 100644 index 0000000..c6d9f1b --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Projects/pr_04/NOTE @@ -0,0 +1,8 @@ +Modify the justify program of section 15.3 by rewriting line.c file so that +it sotres the current line in a linked list. Each node in the list will +store a single word. The linr array will be replaced by a pointer variable +that points to the node containing the first word. This variable will store +a null pointer whenever the line is empty. + + +I DID NOT DO THIS...IT IS UNMODIFIED. \ No newline at end of file diff --git a/17_Advanced_Uses_of_Pointers/Projects/pr_04/line.c b/17_Advanced_Uses_of_Pointers/Projects/pr_04/line.c new file mode 100644 index 0000000..cc1c927 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Projects/pr_04/line.c @@ -0,0 +1,62 @@ +/* + * line.c + * + * Created on: Jun 13, 2013 + * Author: delmadord + */ + + +#include +#include +#include "line.h" + + +#define MAX_LINE_LEN 60 + +char line[MAX_LINE_LEN + 1]; +int line_len = 0; +int num_words = 0; + +void clear_line(void) { + line[0] = '\0'; + line_len = 0; + num_words = 0; +} + +void add_word(const char *word) { + if (num_words > 0) { + line[line_len] = ' '; + line[line_len + 1] = '\0'; + line_len++; + } + strcat(line, word); + line_len += strlen(word); + num_words++; +} + +int space_remainig(void) { + return MAX_LINE_LEN - line_len; +} + +void write_line(void) { + int extra_spaces, spaces_to_insert, i, j; + + extra_spaces = MAX_LINE_LEN - line_len; + for (i = 0; i < line_len; i++) { + if (line[i] != ' ') + putchar(line[i]); + else { + spaces_to_insert = extra_spaces / (num_words - 1); + for (j = 1; j <= spaces_to_insert + 1; j++) + putchar(' '); + extra_spaces -= spaces_to_insert; + num_words--; + } + } + putchar('\n'); +} + +void flush_line(void) { + if (line_len > 0) + puts(line); +} diff --git a/17_Advanced_Uses_of_Pointers/Projects/pr_05/NOTE b/17_Advanced_Uses_of_Pointers/Projects/pr_05/NOTE new file mode 100644 index 0000000..5d07a5b --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Projects/pr_05/NOTE @@ -0,0 +1 @@ +I DID PROJECT 6 WITHOUT PROJECT 5 \ No newline at end of file diff --git a/17_Advanced_Uses_of_Pointers/Projects/pr_06/words_sort.c b/17_Advanced_Uses_of_Pointers/Projects/pr_06/words_sort.c new file mode 100644 index 0000000..3cb4b87 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Projects/pr_06/words_sort.c @@ -0,0 +1,90 @@ +/* + * words_sort.c + * + * Created on: Jun 24, 2013 + * Author: delmadord + */ + + +#include +#include +#include + +#define WORD_LEN 20 +#define INIT_WORD_COUNT 10 + + +int read_line(char str[], int n); +void *my_malloc(size_t size); +void *my_realloc(void *p, size_t size); +int compare (const void *a, const void *b); + +int main(void) { + int wlen, count = 0, max = INIT_WORD_COUNT; + char **words = my_malloc(max * sizeof(char *)), word[WORD_LEN + 1]; + + while (1) { + printf("Enter word: "); + // there are some characters, not just enter + if ((wlen = read_line(word, WORD_LEN)) == 0) + break; + + // just make sure there is enough memory + if (count == max) { + max *= 2; + words = my_realloc(words, max * sizeof(char *)); + } + + // add pointer to newly added word to array of pointers to strings + words[count] = my_malloc(wlen + 1); + strcpy(words[count++], word); + } + + int i; +// printf("\nYou entered words: "); +// for (i = 0; i < count; i++) +// printf("%s ", words[i]); + + qsort(words, count, sizeof(char *), compare); + printf("\nIn sorted order: "); + for (i = 0; i < count; i++) + printf("%s ", words[i]); + + return EXIT_SUCCESS; +} + + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} + +void *my_malloc(size_t size) { + void *p = malloc(size); + if (p == NULL) { + printf("Memory allocation unsuccessful.\n"); + exit(EXIT_FAILURE); + } + return p; +} + +void *my_realloc(void *p, size_t size) { + void *temp = realloc(p, size); + if (temp == NULL) { + printf("Insufficient memory; can't add more items.\n"); + exit(EXIT_FAILURE); + } + return temp; +} + +int compare (const void *a, const void *b) { + const char **aa = (const char **)a; + const char **bb = (const char **)b; + + return strcmp(*aa, *bb); +} diff --git a/17_Advanced_Uses_of_Pointers/Projects/pr_07/remind2.c b/17_Advanced_Uses_of_Pointers/Projects/pr_07/remind2.c new file mode 100644 index 0000000..45589e9 --- /dev/null +++ b/17_Advanced_Uses_of_Pointers/Projects/pr_07/remind2.c @@ -0,0 +1,89 @@ +/* + * remind2.c + * + * Created on: Jun 17, 2013 + * Author: delmadord + */ + + + +// Prints a one-month reminder list + +// USING VSTRING STRUCTURE BUT FUCK IT, IT IS NOT WORKING + +#include +#include +#include + +#define MAX_REMIND 50 +#define MSG_LEN 60 + +struct vstring { + int len; + char chars[]; +}; + + +int read_line(char str[], int n); + +int main(void) { + + struct vstring *reminders[MAX_REMIND]; + char day_str[3], msg_str[MSG_LEN + 1]; + int day, i, j, k, n, num_remind = 0; + + while (1) { + if (num_remind == MAX_REMIND) { + printf("-- No space left --n"); + break; + } + + printf("Enter day reminder: "); + scanf("%2d", &day); + if (day == 0) + break; + sprintf(day_str, "%2d", day); + read_line(msg_str, MSG_LEN); + + for (i = 0; i < num_remind; i++) + if (strcmp(day_str, reminders[i]->chars) < 0) + break; + for (j = num_remind; j > i; j--) + reminders[j] = reminders[j - i]; + + n = strlen(msg_str); + reminders[i] = malloc(sizeof(struct vstring) + n); + if (reminders[i] == NULL) { + printf("-- No space left --\n"); + break; + } + reminders[i]->len = n; + + strcpy(reminders[i]->chars, day_str); + strcat(reminders[i]->chars, msg_str); + + num_remind++; + } + + printf("\nDay Reminder\n"); + for (i = 0; i < num_remind; i++) { + putchar(' '); + for (k = 0; k < reminders[i]->len; k++) + putchar(reminders[i]->chars); + putchar('\n'); + } + +// printf(" %s\n", reminders[i]->chars); + + return 0; +} + +int read_line(char str[], int n) { + int ch, i = 0; + + while ((ch = getchar()) != '\n') + if (i < n) + str[i++] = ch; + str[i] = '\0'; + return i; +} diff --git a/18_Declarations/Debug/18_Declarations b/18_Declarations/Debug/18_Declarations new file mode 100644 index 0000000..0dd1011 Binary files /dev/null and b/18_Declarations/Debug/18_Declarations differ diff --git a/18_Declarations/Debug/Exercises/ex_01_15.d b/18_Declarations/Debug/Exercises/ex_01_15.d new file mode 100644 index 0000000..59ea0f6 --- /dev/null +++ b/18_Declarations/Debug/Exercises/ex_01_15.d @@ -0,0 +1 @@ +Exercises/ex_01_15.d: ../Exercises/ex_01_15.c diff --git a/18_Declarations/Debug/Exercises/ex_01_15.o b/18_Declarations/Debug/Exercises/ex_01_15.o new file mode 100644 index 0000000..f2fa491 Binary files /dev/null and b/18_Declarations/Debug/Exercises/ex_01_15.o differ diff --git a/18_Declarations/Debug/Exercises/subdir.mk b/18_Declarations/Debug/Exercises/subdir.mk new file mode 100644 index 0000000..6a30cc7 --- /dev/null +++ b/18_Declarations/Debug/Exercises/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Exercises/ex_01_15.c + +OBJS += \ +./Exercises/ex_01_15.o + +C_DEPS += \ +./Exercises/ex_01_15.d + + +# Each subdirectory must supply rules for building sources it contributes +Exercises/%.o: ../Exercises/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/18_Declarations/Debug/sources.mk b/18_Declarations/Debug/sources.mk new file mode 100644 index 0000000..1656871 --- /dev/null +++ b/18_Declarations/Debug/sources.mk @@ -0,0 +1,17 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +O_SRCS := +C_SRCS := +S_UPPER_SRCS := +OBJ_SRCS := +ASM_SRCS := +OBJS := +C_DEPS := +EXECUTABLES := + +# Every subdirectory with source files must be described here +SUBDIRS := \ +Exercises \ + diff --git a/18_Declarations/Exercises/ex_01_15.c b/18_Declarations/Exercises/ex_01_15.c new file mode 100644 index 0000000..f9218b1 --- /dev/null +++ b/18_Declarations/Exercises/ex_01_15.c @@ -0,0 +1,44 @@ +/* + * ex_01_15.c + * + * Created on: Jun 26, 2013 + * Author: delmadord + */ + +//int f(int i) { +// static int j = 0; +// return i * j++; +//} +// + + +int main(void) { +// int x = f(10); // x = 0 +// x = f(10); +// x = f(10); +// x = f(10); +// x = f(10); +// x = f(10); // x = 50 + + + + // ex_10 +// char *(*p)(char *); +// void *f(struct t *p, long int n)(void); +// void (*a[])(void) = {insert, search, update, print}; +// struct t (*b[10])(int, int); + + // f is function with two arguments - first is pointer to function + // that has long as an argument, returning float, second is pointer + // to char; f is returning a pointer to function having double as an + // argument and returning an int +// int (*f(float (*)(long), char *))(double); + +// #define PI 3.14159 +// char c = 65; +// static int i = 5, j = i * i; // INITIALIZER NEEDS CONTANST IN STATIC +// double d = 2 * PI; +// double angles[] = {0, PI / 2, PI, 3 * PI / 2}; + + return 0; +} diff --git a/20_Bitwise_Operators/Debug/20_Bitwise_Operators b/20_Bitwise_Operators/Debug/20_Bitwise_Operators new file mode 100644 index 0000000..9c7ed4f Binary files /dev/null and b/20_Bitwise_Operators/Debug/20_Bitwise_Operators differ diff --git a/20_Bitwise_Operators/Debug/Examples/subdir.mk b/20_Bitwise_Operators/Debug/Examples/subdir.mk new file mode 100644 index 0000000..5681688 --- /dev/null +++ b/20_Bitwise_Operators/Debug/Examples/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Examples/viewmemory.c + +OBJS += \ +./Examples/viewmemory.o + +C_DEPS += \ +./Examples/viewmemory.d + + +# Each subdirectory must supply rules for building sources it contributes +Examples/%.o: ../Examples/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/20_Bitwise_Operators/Debug/Exercises/ex_01.d b/20_Bitwise_Operators/Debug/Exercises/ex_01.d new file mode 100644 index 0000000..fbc388d --- /dev/null +++ b/20_Bitwise_Operators/Debug/Exercises/ex_01.d @@ -0,0 +1 @@ +Exercises/ex_01.d: ../Exercises/ex_01.c diff --git a/20_Bitwise_Operators/Debug/Exercises/ex_01.o b/20_Bitwise_Operators/Debug/Exercises/ex_01.o new file mode 100644 index 0000000..8e1ac9f Binary files /dev/null and b/20_Bitwise_Operators/Debug/Exercises/ex_01.o differ diff --git a/20_Bitwise_Operators/Debug/Exercises/subdir.mk b/20_Bitwise_Operators/Debug/Exercises/subdir.mk new file mode 100644 index 0000000..3c20f4e --- /dev/null +++ b/20_Bitwise_Operators/Debug/Exercises/subdir.mk @@ -0,0 +1,24 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../Exercises/ex_01.c + +OBJS += \ +./Exercises/ex_01.o + +C_DEPS += \ +./Exercises/ex_01.d + + +# Each subdirectory must supply rules for building sources it contributes +Exercises/%.o: ../Exercises/%.c + @echo 'Building file: $<' + @echo 'Invoking: GCC C Compiler' + gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/20_Bitwise_Operators/Debug/makefile b/20_Bitwise_Operators/Debug/makefile new file mode 100644 index 0000000..4a91b8e --- /dev/null +++ b/20_Bitwise_Operators/Debug/makefile @@ -0,0 +1,44 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include Exercises/subdir.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: 20_Bitwise_Operators + +# Tool invocations +20_Bitwise_Operators: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + gcc -o "20_Bitwise_Operators" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C_DEPS)$(EXECUTABLES) 20_Bitwise_Operators + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/20_Bitwise_Operators/Examples/msg b/20_Bitwise_Operators/Examples/msg new file mode 100644 index 0000000..415e20b --- /dev/null +++ b/20_Bitwise_Operators/Examples/msg @@ -0,0 +1,3 @@ +Trust not him with your secrets, who, when left +alone in your room, turns over your papers. + --Johann Kaspar Lavater (1741-1801) \ No newline at end of file diff --git a/20_Bitwise_Operators/Examples/newmsg b/20_Bitwise_Operators/Examples/newmsg new file mode 100644 index 0000000..0927d8b --- /dev/null +++ b/20_Bitwise_Operators/Examples/newmsg @@ -0,0 +1,3 @@ +rTSUR HIR NOK QORN _IST UCETCRU, QNI, QNCH JC@R +GJIHC OH _IST TIIK, RSTHU IPCT _IST VGVCTU. + --lINGHH mGUVGT jGPGRCT (1741-1801) \ No newline at end of file diff --git a/20_Bitwise_Operators/Examples/viewmemory.c b/20_Bitwise_Operators/Examples/viewmemory.c new file mode 100644 index 0000000..db060f6 --- /dev/null +++ b/20_Bitwise_Operators/Examples/viewmemory.c @@ -0,0 +1,52 @@ +/* + * viewmetmory.c + * + * Created on: Jun 28, 2013 + * Author: delmadord + */ + +/* Allows the user to view regions of computer memory */ + +#include +#include + +typedef unsigned char BYTE; + +int main(void) { + unsigned int addr; + int i, n; + BYTE *ptr; + + printf("Address of main function: %x\n", (unsigned int) main); + printf("Address of addr variable: %x\n", (unsigned int) &addr); + + printf("\nEnter a (hex) address: "); + scanf("%x", &addr); + printf("Enter number of bytes to view: "); + scanf("%d", &n); + + printf("\n"); + printf(" Address Bytes Characters\n"); + printf(" ------- ----------------------------- ----------\n"); + + ptr = (BYTE *) addr; + for (; n > 0; n -= 10) { + printf("%8X ", (unsigned int) ptr); + for (i = 0; i < 10 && i < n; i++) + printf("%.2X ", *(ptr + i)); + for (; i < 10; i++) + printf(" "); + printf(" "); + for (i = 0; i < 10 && i < n; i++) { + BYTE ch = *(ptr + i); + if (!isprint(ch)) + ch = '.'; + printf("%c", ch); + } + printf("\n"); + ptr += 10; + } + + return 0; +} + diff --git a/20_Bitwise_Operators/Examples/xor.c b/20_Bitwise_Operators/Examples/xor.c new file mode 100644 index 0000000..96518b6 --- /dev/null +++ b/20_Bitwise_Operators/Examples/xor.c @@ -0,0 +1,26 @@ +/* + * xor.c + * + * Created on: Jun 28, 2013 + * Author: delmadord + */ + +#include +#include + +#define KEY '&' + +int main(void) { + int orig_char, new_char; + + while ((orig_char = getchar()) != EOF) { + new_char = orig_char ^ KEY; + if (isprint(orig_char) && isprint(new_char)) + putchar(new_char); + else + putchar(orig_char); + } + + return 0; +} + diff --git a/20_Bitwise_Operators/Exercises/ex_01.c b/20_Bitwise_Operators/Exercises/ex_01.c new file mode 100644 index 0000000..ded6599 --- /dev/null +++ b/20_Bitwise_Operators/Exercises/ex_01.c @@ -0,0 +1,28 @@ +/* + * ex_01.c + * + * Created on: Jun 28, 2013 + * Author: delmadord + */ + +#include + +int main(void) { + unsigned short i, j, k; + + i = 8; j = 9; + printf("%d\n", i >> (1 + j) >> 1); // 0 + + i = 1; + printf("%d\n", i & ~i); // 0 + + i = 2; j = 1; k = 0; + printf("%d\n", (~i & j) ^ k); // 1 + + i = 7; j = 8; k = 9; + printf("%d\n", i ^ (j & k)); // 15 + + + + return 0; +}