/* functions.c Jeff Ondich, 26 April 2019 Part of a quick intro to C This variant of functions.c is used in our very short intro to lldb. */ #include #include int fibonacci(int n); int factorialRecursive(int n); void squashCharacterInString(char character, char *string); void makeTrouble(); int main() { // Fibonacci int n = 10; int result = fibonacci(n); printf("Fibonacci number %d = %d\n", n, result); // Some recursion n = 6; result = factorialRecursive(n); printf("%d! = %d\n", n, result); // Some string manipulation char word[20]; strcpy(word, "Mississippi"); char character = 'i'; squashCharacterInString(character, word); printf("Squashed string: %s\n", word); // An opportunity for mischief makeTrouble("dog", "cat"); return 0; } // Returns the nth Fibonacci number. Assumes that the Fibonacci // numbers start at index 0, so fib0 = 1, fib1 = 1, fib2 = 2, etc. int fibonacci(int n) { int previous = 1; int current = 1; for (int k = 1; k <= n; k++) { int new = current + previous; previous = current; current = new; } return current; } int factorialRecursive(int n) { if (n <= 1) { return 1; } int previousFactorial = factorialRecursive(n - 1); return previousFactorial * n; } // Replaces each occurrence of the specified character with an underscore // inside the specified string. void squashCharacterInString(char character, char *s) { int n = 0; for (int k = 0; s[k] != '\0'; k++) { if (s[k] == character) { s[k] = '_'; } } } void makeTrouble(const char *s1, const char *s2) { int a = 5; char string1[8]; int b = 6; char string2[8]; int c = 7; strcpy(string1, s1); strcpy(string2, s2); printf("\n==== makeTrouble ====\n"); printf("a = %d\n", a); printf("string1 = %s\n", string1); printf("b = %d\n", b); printf("string2 = %s\n", string2); printf("c = %d\n", c); printf("\n"); }