// CS 350, Spring 2012 // Lab 1 -- Introduction to C #include // to access printf, scanf #include // to access strlen, strcmp /* Note: strcmp(s1, s2) compares two strings s1 and s2 and returns 0 if the strings are equal; it returns a value < 0 if s1 is less than s2; it returns a value > 0 if s1 is greater than s2. [Here, "less than" and "greater than" refer to lexicographic ordering -- we compare the strings character by character from left to right.] */ void handle(char str[], int m); // (function prototype) int main(void) { // Read in a floating-point and double precision floating-point number // (using the %f and %lf (long float) formats respectively). // Echo the values, find the larger of the two, and print it out in // exponential format. // float x; double y; printf("Enter two floating point numbers (separated by white space and followed by a carriage return): "); scanf("%f %lf", &x, &y); printf("You entered %f and %lf; the larger of the two is %le\n", x, y, (x > y ? x : y)); // We repeatedly read and handle an integer and string typed in by the user. // We quit if the user enters q as the string. // int m; char str[256] = ""; // Space for a string of length <= 255 printf("Enter an integer, some white space, a string (q to quit) and a carriage return: "); scanf("%d %s", &m, str); // read m and the input string while (strcmp(str, "q")) { // while string is not "q" handle(str, m); // call subroutine to handle string and m printf("Enter an integer and a string (q to quit): "); scanf("%d %s", &m, str); // read next str and m } return 0; } // handle(str, m) takes a string and an index m. It prints out the length // of the string, prints out the character at position m of the string (if // m is in bounds), figures out which character of the string is the largest // (using the ASCII encoding), and prints out the largest character both in // character and integer form. // void handle(char str[], int m) { // Calculate and print out the string's length. // int len = strlen(str); printf("%s has length %d. ", str, len); // If the index m is legal for str, print str[m], else // say that m is out of bounds. // if (m < 0 || m >= len) { printf("Index %d is outside the string.\n", m); } else { printf("Character %d of the string is %c\n", m, str[m]); } // If str isn't the empty string, find its largest character // and print it out in character and integer form. // if (strcmp(str, "") == 0) { // or, if len == 0 printf("The string is empty\n"); } else { int i; // 0 <= i < len char max = str[0]; // max = largest char of str[0..i] for (i = 1 ; i < len ; i++) { if (max < str[i]) max = str[i]; // reestablish max for current i } printf("The largest character of %s is %c; it has numeric value %d\n", str, max, (int) max ); } }