/* Week 4 code sample for CPS125. Ferworn Fall 06 if and switch examples */ #include <stdio.h> #include <math.h> #define LIMIT 0.0000001 int main() { int first = 1, second = 2, third =3, temp =0; char answer; /* Two very close double values */ double firstd = 17.00000001; double secondd = 17.0; if(first) /* first is evaluated and its value is either zero or not. Zero means false */ printf("first is not zero\n\n"); if(!first) printf("This statement will not be printed\n\n"); if(third == (first + second)) printf("This statement is printed if third is first plus second\n\n"); if(first = second) { printf("This statement will be printed as long as second is not zero. Why?\n\n"); first = 1; } /* figure out which is greatest or are they equal */ if((first == 1) && (second == 2) && (third == 3)) printf("This is true\n\n"); else printf("This is false\n\n"); if((first > second) && (first > third)) printf("first is the greatest\n\n"); else /* oh oh nested if coming! Why don't we need to make a block?*/ if((second > first) && (second > third)) printf("second is the greatest\n\n"); else if((third > first) && (third > second)) printf("third is the greatest\n\n"); else { printf("At least two of first, second or third are equal\n\n"); if(first == second) printf("first == second\n\n"); if(first == third) printf("first == third\n\n"); if(second == third) printf("second == third\n\n"); } /* swap values code */ if(second > first) { temp = first; first = second; second = temp; } /* dealing with double values */ if(firstd == secondd) printf("The two double values are equal.\n\n"); else printf("The two double values are not equal because I am a tight ass.\n\n"); if(fabs((fabs(firstd) - fabs(secondd))) < LIMIT) printf("The two doubles are close enough for government work.\n\n"); /* switch */ printf("Hey punk, enter 'a', 'b', 'e', 'z' or '1'.\n"); printf("If you enter anything else I'll swear.\n\n"); scanf("%c", &answer); /* An example using the switch construct */ switch(answer) { case 'a': case 'b': case 'e': case 'z': case '1': printf("Thank you!\n"); break; default: printf("#$%^&*%^&*!\n"); } } /* Sample output first is not zero This statement is printed if third is first plus second This statement will be printed as long as second is not zero. Why? This is true third is the greatest The two double values are not equal because I am a tight ass. The two doubles are close enough for government work. Hey punk, enter 'a', 'b', 'e', 'z' or '1'. If you enter anything else I'll swear. a Thank you! */