/* char.c Written by Tanya Amert for Fall 2024. Demonstrates working with char arrays in C, as well as how values stored in a char can be printed different ways. To compile this program: gcc -Wall -Werror -g -o char char.c To run this program: ./char */ #include // We can use "#define"s to do things like set a flag for debugging. // We'll talk more about what these are later. When DEBUG is set to 1 // the program prints out extra messages for debugging; if it's anything // else (say, 0), then the debugging prints won't appear. #define DEBUG 1 // By very common convention, main() will appear at the top of many of // my C samples. But if main appears before a function that it calls, // the compiler won't recognize the function in main, so you'll get an // error. It is thus common to provide "function prototypes" (i.e., // declaration of function signatures without the corresponding function // bodies) at the top, before main. Function prototypes also appear in // *.h files for similar reasons. int get_aA_count(char arr[], int n); // Calls another function to count the number of a/A characters // in a char array. int main() { // Create a 6-element char array for us to work with char some_bytes[6] = { 10, 42, 65, 88, 97, 125 }; // fun: change one to 8 // Call another function to do the work int num_aA = get_aA_count(some_bytes, 6); // Print the results printf("Found %d characters that were either 'a' or 'A'.\n", num_aA); // By convention, we should return 0 to indicate successful completion // of this program. return 0; } // Returns the number of 'a' and 'A' characters in a given array. // Prints some helpful debugging info along the way. // // Inputs: // arr: a char array // n: the number of chars in arr // // Returns: the number of chars equal to 'a' or 'Z' int get_aA_count(char arr[], int n) { int count = 0; // We can use a for loop to iterate through the array for (int i = 0; i < n; i++) { char current_char = arr[i]; // If we're printing debugging messages, print the current char if (DEBUG == 1) { // We can use %c for the ASCII character representation (e.g., 'A') // and %d for the decimal number (e.g., 65) printf("Current char: '%c' (decimal: %d)\n", current_char, current_char); } // If this character is an 'a' or 'A' (e.g., decimal 97 or 65), // increment our counter by 1 if ((current_char == 'a') || (current_char == 'A')) { count++; } } return count; }