char one[21], two[21]; puts("enter two words: "); scanf("%s", one); scanf("%s", two); if (strcmp(one, two) < 0) printf ("your words are: %s and %s\n", one, two); else printf ("your words are: %s and %s\n", two, one);
char one[21], two[21], three[21]; puts("enter three words: "); scanf("%s", one); scanf("%s", two); scanf("%s", three); if (strcmp(one, two) < 0) if (strcmp(three, one) < 0) printf ("your words are: %s %s %s\n", three, one, two); else if (strcmp(three, two) < 0) printf ("your words are: %s %s %s\n", one, three, two); else printf ("your words are: %s %s %s\n", one, two, three); else if (strcmp(three, two) < 0) printf ("your words are: %s %s %s\n", three, two, one); else if (strcmp(three, one) < 0) printf ("your words are: %s %s %s\n", two, three, one); else printf ("your words are: %s %s %s\n", two, one, three);
int countwords(char str[]) { int i; int numwords = 0; for (i = 0 ; str[i] != '\0' ; i++) { // every blank is the end of a word unless it comes before the first word if (str[i] == ' ' && i != 0) numwords++; } // i is now the position of the null byte; if there wasn't a blank at // the end of the string then we still need to count the last word if (str[i-1] != ' ') numwords++; return numwords; }
char line[81]; puts("enter a line: "); gets(line); printf("your line contains %d words\n", countwords(line));
int countvowels(char str[]) { int numvowels = 0; int i; for (i = 0 ; str[i] != '\0' ; i++) { if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') numvowels++; else if (str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') numvowels++; }
// use backslashes to enter " inside a string (the backslash changes the // meaning of " to a character instead of using it to end the string puts("enter a line (enter \"end\" to end): "); gets(line); // strmcp returns 0 (false) if they are equal so this loop will run as long // as they are not equal while (strcmp(line, "end")) { printf("your line contains %d vowels\n", countvowels(line)); puts("enter a line: "); gets(line); }
int mystrlen(char line[]) { int len; // stop loop at position of null byte, which is the length // no body needed for this loop for (len = 0 ; line[len] != '\0' ; len++); return len; }
void mystrcpy(char dest[], char source[]) { int i; for (i = 0 ; source[i] != '\0' ; i++) dest[i] = source[i]; // i is position of null byte in source, copy it into dest dest[i] = '\0'; }
void mystrcat(char one[], char two[]) { int i; // get length of one int len = mystrlen(one); // start at beginning of two and end of one // copy everything from two into one for (i = 0 ; two[i] != '\0' ; i++, len++) one[len] = two[i]; // add null byte to the end of one one[len] = '\0'; }
Email Me |
Office Hours |
My Home Page |
Department Home |
MCC Home Page
© Copyright Emmi Schatz 2020