/************************************************************************** |* *| |* LEARNING C BY EXAMPLES *| |* Saied Hosseini *| |* 1382/2003 *| |* *| |* *| |* C is a general-purpose programming language that was originally *| |* designed by Dennis Ritchie of Bell Laboratories in 1972. After gaining *| |* tremendous popularity, C became an ANSI standard in 1989. *| |* *| |* All example programs below are written in ANSI standard C. *| |* Therefore they can be compiled on any ANSI C compiler. *| |* *| |* Recommended references: *| |* 1. Deitel & Deitel, "C: How To Program," Prentice Hall *| |* 2. Al Kelly, Ira Pohl, "A Book on C," Addison-Wesley *| |* 3. Brian Kernighan, Dennis Ritchie, "C Programming Language" *| |* *| |* Almost all examples were taken from reference 1. *| |* *| **************************************************************************/ ================================EXAMPLE 00================================ /* The smallest C program that is syntactically correct. But it does nothing useful. */ int main() { return 0; } ================================EXAMPLE 01================================ /* A simple C program */ #include <stdio.h> int main() { printf("Welcome to C!\n"); printf("Welcome "); printf("to C!\n"); printf("Welcome\nto\nC!\n"); return 0; } ================================EXAMPLE 02================================ /* Print a banner */ #include <stdio.h> int main() { printf("\n\n\n\n\n\n\n\n\n\n"); printf(" ***********************\n"); printf(" * From sea *\n"); printf(" * to the shining C *\n"); printf(" ***********************\n"); printf("\n\n\n\n\n\n\n\n\n\n"); return 0; } ================================EXAMPLE 03================================ /* Ring the bell */ #include <stdio.h> int main() { char bell='\a'; printf("%c", bell); /* "%c" means print a character value */ return 0; } ================================EXAMPLE 04================================ /* Initial C program that demonstrates the C comments and shows a few variables and their declarations */ #include <stdio.h> int main() { int i, j; /* These 4 lines declare 5 variables */ char c; float x; double y; i = 4; /* i and j are assigned integer values */ j = i + 7; c = 'A'; /* All character constants are enclosed in single quotes */ x = 9.087f; /* x requires a floating-point value since it was declared as a floating-point variable */ x = x * 4.5f; y = 802327.010092; /* Sends the values of the variables to the screen */ printf("%d\n%d\n%c\n%f\n%lf\n", i, j, c, x, y); return 0; /* End programs and functions with return */ } ================================EXAMPLE 05================================ /* Addition program */ #include <stdio.h> int main() { int integer1, integer2, sum; /* declaration */ printf("Enter first integer\n"); /* prompt */ scanf("%d", &integer1); /* read an integer */ printf("Enter second integer\n"); /* prompt */ scanf("%d", &integer2); /* read an integer */ sum = integer1 + integer2; /* assignment of sum */ printf("Sum is %d\n", sum); /* print sum */ return 0; /* indicate that program ended successfully */ } ================================EXAMPLE 06================================ /* Using if statements, relational operators, and equality operators */ #include <stdio.h> int main() { int num1, num2; printf("Enter two integers, and I will tell you\n"); printf("the relationships they satisfy: "); scanf("%d%d", &num1, &num2); /* read two integers */ if (num1 == num2) printf("%d is equal to %d\n", num1, num2); if (num1 != num2) printf("%d is not equal to %d\n", num1, num2); if (num1 < num2) printf("%d is less than %d\n", num1, num2); if (num1 > num2) printf("%d is greater than %d\n", num1, num2); if (num1 <= num2) printf("%d is less than or equal to %d\n", num1, num2); if (num1 >= num2) printf("%d is greater than or equal to %d\n", num1, num2); return 0; /* indicate program ended successfully */ } ================================EXAMPLE 07================================ /* Class average program with counter-controlled repetition */ #include <stdio.h> int main() { int counter, grade, total, average; /* initialization phase */ total = 0; counter = 1; /* processing phase */ while (counter <= 10) { printf("Enter grade: "); scanf("%d", &grade); total = total + grade; counter = counter + 1; } /* termination phase */ average = total / 10; printf("Class average is %d\n", average); return 0; /* indicate program ended successfully */ } ================================EXAMPLE 08================================ /* Class average program with sentinel-controlled repetition */ #include <stdio.h> int main() { float average; /* new data type */ int counter, grade, total; /* initialization phase */ total = 0; counter = 0; /* processing phase */ printf("Enter grade, -1 to end: "); scanf("%d", &grade); while (grade != -1) { total = total + grade; counter = counter + 1; printf("Enter grade, -1 to end: "); scanf("%d", &grade); } /* termination phase */ if (counter != 0) { average = (float) total / counter; printf("Class average is %.2f", average); } else printf("No grades were entered\n"); return 0; /* indicate program ended successfully */ } ================================EXAMPLE 09================================ /* Analysis of examination results */ #include <stdio.h> int main() { /* initializing variables in declarations */ int passes = 0, failures = 0, student = 1, result; /* process 10 students; counter-controlled loop */ while (student <= 10) { printf("Enter result (1=pass,2=fail): "); scanf("%d", &result); if (result == 1) /* if/else nested in while */ passes = passes + 1; else failures = failures + 1; student = student + 1; } printf("Passed %d\n", passes); printf("Failed %d\n", failures); if (passes > 8) printf("Raise tuition\n"); return 0; /* successful termination */ } ================================EXAMPLE 10================================ /* Preincrementing and postincrementing */ #include <stdio.h> main() { int c; c = 5; printf("%d\n", c); printf("%d\n", c++); /* postincrement */ printf("%d\n\n", c); c = 5; printf("%d\n", c); printf("%d\n", ++c); /* preincrement */ printf("%d\n", c); return 0; /* successful termination */ } ================================EXAMPLE 11================================ /* Counter-controlled repetition */ #include <stdio.h> main() { int counter = 1; /* initialization */ while (counter <= 10) { /* repetition condition */ printf ("%d\n", counter); ++counter; /* increment */ } return 0; } ================================EXAMPLE 12================================ /* Counter-controlled repetition with the for structure */ #include <stdio.h> main() { int counter; /* initialization, repetition condition, and increment */ /* are all included in the for structure header */ for (counter = 1; counter <= 10; counter++) printf("%d\n", counter); return 0; } ================================EXAMPLE 13================================ /* Summation with for */ #include <stdio.h> main() { int sum = 0, number; for (number = 2; number <= 100; number += 2) sum += number; printf("Sum is %d\n", sum); return 0; } ================================EXAMPLE 14================================ /* Calculating compound interest */ #include <stdio.h> #include <math.h> main() { int year; double amount, principal = 1000.0, rate = .05; printf("%s\t%s\n", "Year", "Amount on deposit"); for (year = 1; year <= 10; year++) { amount = principal * pow(1.0 + rate, year); printf("%d\t%f\n", year, amount); } return 0; } ================================EXAMPLE 15================================ /* Counting letter grades with switch statement */ #include <stdio.h> main() { int grade; int aCount = 0, bCount = 0, cCount = 0, dCount = 0, fCount = 0; printf("Enter the letter grades.\n"); printf("Enter the EOF character to end input.\n"); while ( ( grade = getchar() ) != EOF) { switch (grade) { /* switch nested in while */ case 'A': case 'a': /* grade was uppercase A */ ++acount; /* or lowercase a */ break; case 'B': case 'b': /* grade was uppercase B */ ++bcount; /* or lowercase b */ break; case 'C': case 'c': /* grade was uppercase C */ ++ccount; /* or lowercase c */ break; case 'D': case 'd': /* grade was uppercase D */ ++dcount; /* or lowercase d */ break; case 'F': case 'f': /* grade was uppercase F */ ++fcount; /* or lowercase f */ break; case '\n': case' ': /* ignore these in input */ break; default: /* catch all other characters */ printf("Incorrect letter grade entered."); printf(" Enter a new grade.\n"); break; } } printf("\nTotals for each letter grade are:\n"); printf("A: %d\n", aCount); printf("B: %d\n", bCount); printf("C: %d\n", cCount); printf("D: %d\n", dCount); printf("F: %d\n", fCount); return 0; } ================================EXAMPLE 16================================ /* Using the do/while repetition structure */ #include <stdio.h> main() { int counter = 1; do { printf("%d ", counter); } while (++counter <= 10); return 0; } ================================EXAMPLE 17================================ /* Using the break statement in a for structure */ #include <stdio.h> main() { int x; for (x = 1; x <= 10; x++) { if (x == 5) break; /* break loop only if x == 5 */ printf("%d ", x); } printf("\nBroke out of loop at x == %d\n", x); return 0; } ================================EXAMPLE 18================================ /* Using the continue statement in a for structure */ #include <stdio.h> main() { int x; for (x = 1; x <= 10; x++) { if (x == 5) continue; /* skip remaining code in loop only if x == 5 */ printf("%d ", x); } printf("\nUsed continue to skip printing the value 5\n"); return 0; } ================================EXAMPLE 19================================ /* A programmer-defined square function */ #include <stdio.h> int square(int); /* function prototype */ main() { int x; for (x = 1; x <= 10; x++) printf("%d ", square(x)); printf("\n"); return 0; } /* Function definition */ int square(int y) { return y * y; } ================================EXAMPLE 20================================ /* Finding the maximum of three integers */ #include <stdio.h> int maximum(int, int, int); /* function prototype */ main() { int a, b, c; printf("Enter three integers: "); scanf("%d%d%d", &a, &b, &c); printf("Maximum is: %d\n", maximum(a, b, c)); return 0; } /* Function maximum definition */ int maximum(int x, int y, int z) { int max = x; if (y > max) max = y; if (z > max) max = z; return max; } ================================EXAMPLE 21================================ /* Generating pseudo-random numbers with rand() */ /* Shifted, scaled integers produced by 1 + rand() % 6 */ #include <stdio.h> #include <stdlib.h> main() { int i; for (i = 1; i <= 20; i++) { printf("%10d", 1 + (rand() % 6)); if (i % 5 == 0) printf("\n"); } return 0; } ================================EXAMPLE 22================================ /* Rolling a six-sided die 6000 times */ #include <stdio.h> #include <stdlib.h> main() { int face, roll, frequency1 = 0, frequency2 = 0, frequency3 = 0, frequency4 = 0, frequency5 = 0, frequency6 = 0; for (roll = 1; roll <= 6000; roll++) { face = 1 + rand() % 6; switch (face) { case 1: ++frequency1; break; case 2: ++frequency2; break; case 3: ++frequency3; break; case 4: ++frequency4; break; case 5: ++frequency5; break; case 6: ++frequency6; break; } } printf("%s%13s\n", "Face", "Frequency"); printf(" 1%13d\n", frequency1); printf(" 2%13d\n", frequency2); printf(" 3%13d\n", frequency3); printf(" 4%13d\n", frequency4); printf(" 5%13d\n", frequency5); printf(" 6%13d\n", frequency6); return 0; } ================================EXAMPLE 23================================ /* Randomizing the rand() function */ #include <stdlib.h> #include <stdio.h> main() { int i; unsigned seed; printf("Enter seed: "); scanf("%u", &seed); srand(seed); for (i = 1; i <= 10; i++) { printf("%10d", 1 + (rand() % 6)); if (i % 5 == 0) printf("\n"); } return 0; } ================================EXAMPLE 24================================ /* A scoping example */ #include <stdio.h> void a(void); /* function prototype */ void b(void); /* function prototype */ void c(void); /* function prototype */ int x = 1; /* global variable */ main() { int x = 5; /* local variable to main */ printf("local x in outer scope of main is %d\n", x); { /* start new scope */ int x = 7; printf("local x in inner scope of main is %d\n", x); } /* end new scope */ printf("local x in outer scope of main is %d\n", x); a(); /* a has automatic local x */ b(); /* b has static local x */ c(); /* c uses global x */ a(); /* a reinitializes automatic local x */ b(); /* static local x retains its previous value */ c(); /* global x also retains its value */ printf("local x in main is %d\n", x); return 0; } void a(void) { int x = 25; /* initialized each time a is called */ printf("\nlocal x in a is %d after entering a\n", x); ++x; printf("local x in a is %d before exiting a\n", x); } void b(void) { static int x = 50; /* static initialization only */ /* first time b is called */ printf("\nlocal static x is %d on entering b\n", x); ++x; printf("local static x is %d on exiting b\n", x); } void c(void) { printf("\nglobal x is %d on entering c\n", x); x *= 10; printf("global x is %d on exiting c\n", x); } ================================EXAMPLE 25================================ /* Recursive fibonacci function */ #include <stdio.h> long fibonacci(long); main() { long result, number; printf("Enter an integer: "); scanf("%ld", &number); result = fibonacci(number); printf("Fibonacci(%ld) = %ld\n", number, result); return 0; } /* Recursive definition of function fibonacci */ long fibonacci(long n) { if (n == 0 || n == 1) return n; else return fibonacci(n - 1) + fibonacci(n - 2); } ================================EXAMPLE 26================================ /* defining and using preprocessor macros */ #include <stdio.h> #include <stdlib.h> /* This defines a macro constant. */ #define PI 3.14159 /* The following are macro functions. */ #define MIN(x,y) ( (x)<(y) ? (x):(y) ) #define RAND_CHAR() ( rand()%26+'a' ) #define RECTANGLE_AREA(x,y) ( (x)*(y) ) #define SQ(x) ((x)*(x)) #define CUBE(x) ((x)*(x)*(x)) #define CIRCLE_AREA(x) ( PI*SQ(x) ) #define DECIMAL_PART(x) ((x)-(int)(x)) main() { int a=316, b=42; /* sides of rectangle */ float r=1.34f; double x=4.50 ,y=7.23; printf("MIN(%d,%d) = %d\n", a,b,MIN(a,b) ); printf("Two random characters: %c %c\n", RAND_CHAR(),RAND_CHAR()); printf("Area of rectangle = %d\n", RECTANGLE_AREA(a,b) ); printf("Area of circle = %f\n", CIRCLE_AREA(r) ); printf("Square of x+y = %f\n", SQ(x+y) ); printf("Cube of x+y = %f\n", CUBE(x+y) ); printf("Decimal part of Cube of x+y = %f\n", DECIMAL_PART(CUBE(x+y)) ); return 0; } ================================EXAMPLE 27================================ /* Format specification in printf() */ #include <stdio.h> main() { int i=123; double x=0.123456789; char c='A'; char s[] = "Blue Moon!"; printf("-->%c<--\n",c); /* -->A<-- */ printf("-->%2c<--\n",c); /* --> A<-- */ printf("-->%-3c<--\n",c); /* -->A <-- */ printf("-->%s<--\n",s); /* -->Blue Moon!<-- */ printf("-->%3s<--\n",s); /* -->Blue Moon!<-- */ printf("-->%.6s<--\n",s); /* -->Blue M<-- */ printf("-->%11.6s<--\n",s); /* --> Blue M<-- */ printf("-->%-11.6s<--\n",s); /* -->Blue M <-- */ printf("-->%d<--\n",i); /* -->123<-- */ printf("-->%05d<--\n",i); /* -->00123<-- */ printf("-->%5d<--\n",i); /* --> 123<-- */ printf("-->%o<--\n",i); /* -->173<-- */ printf("-->%7o<--\n",i); /* --> 173<-- */ printf("-->%x<--\n",i); /* -->7b<-- */ printf("-->%X<--\n",i); /* -->7B<-- */ printf("-->%-9x<--\n",i); /* -->7b <-- */ printf("-->%#9x<--\n",i); /* --> 0x7b<-- */ printf("-->%-#9x<--\n",i); /* -->0x7b <-- */ printf("-->%f<--\n",x); /* -->0.123457<-- */ printf("-->%e<--\n",x); /* -->1.234568e-001<-- */ printf("-->%E<--\n",x); /* -->1.234568E-001<-- */ printf("-->%g<--\n",x); /* -->0.123457<-- */ printf("-->%10.5f<--\n",x); /* --> 0.12346<-- */ printf("-->%-12.5f<--\n",x); /* -->0.12346 <-- */ printf("-->%-12.5e<--\n",x); /* -->1.23457e-001<-- */ return 0; } ================================EXAMPLE 28================================ /* Using the integer conversion specifiers */ #include <stdio.h> main() { printf("%d\n", 455); printf("%i\n", 455); /* i same as d in printf */ printf("%d\n", +455); printf("%d\n", -455); printf("%hd\n", 32000); printf("%ld\n", 2000000000); printf("%o\n", 455); printf("%u\n", 455); printf("%u\n", -455); printf("%x\n", 455); printf("%X\n", 455); return 0; } ================================EXAMPLE 29================================ /* Printing floating-point numbers with floating-point conversion specifiers */ #include <stdio.h> main() { printf("%e\n", 1234567.89); printf("%e\n", +1234567.89); printf("%e\n", -1234567.89); printf("%E\n", 1234567.89); printf("%f\n", 1234567.89); printf("%g\n", 1234567.89); printf("%G\n", 1234567.89); return 0; } ================================EXAMPLE 30================================ /* Printing strings and characters */ #include <stdio.h> main() { char character = 'A'; char string[] = "This is a string"; char *stringPtr = "This is also a string"; printf("%c\n", character); printf("%s\n", "This is a string"); printf("%s\n", string); printf("%s\n", stringPtr); return 0; } ================================EXAMPLE 31================================ /* Using the p, n, and % conversion specifiers */ #include <stdio.h> main() { int *ptr; int x = 12345, y; ptr = &x; printf("The value of ptr is %p\n", ptr); printf("The address of x is %p\n\n", &x); printf("Total characters printed on this line is:%n", &y); printf(" %d\n\n", y); y = printf("This line has 28 characters\n"); printf("%d characters were printed\n\n", y); printf("Printing a %% in a format control string\n"); return 0; } ================================EXAMPLE 32================================ /* Printing integers right-justified */ #include <stdio.h> main() { printf("%4d\n", 1); printf("%4d\n", 12); printf("%4d\n", 123); printf("%4d\n", 1234); printf("%4d\n\n", 12345); printf("%4d\n", -1); printf("%4d\n", -12); printf("%4d\n", -123); printf("%4d\n", -1234); printf("%4d\n", -12345); return 0; } ================================EXAMPLE 33================================ /* Using precision while printing integers, floating-point numbers, and strings */ #include <stdio.h> main() { int i = 873; float f = 123.94536; char s[] = "Happy Birthday"; printf("Using precision for integers\n"); printf("\t%.4d\n\t%.9d\n\n", i, i); printf("Using precision for floating-point numbers\n"); printf("\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f); printf("Using precision for strings\n"); printf("\t%.11s\n", s); return 0; } ================================EXAMPLE 34================================ /* Right justifying and left justifying values */ #include <stdio.h> main() { printf("%10s%10d%10c%10f\n\n", "hello", 7, 'a', 1.23); printf("%-10s%-10d%-10c%-10f\n", "hello", 7, 'a', 1.23); return 0; } ================================EXAMPLE 35================================ /* Printing numbers with and without the + flag */ #include <stdio.h> main() { printf("%d\n%d\n", 786, -786); printf("%+d\n%+d\n", 786, -786); return 0; } ================================EXAMPLE 36================================ /* Printing a space before signed values not preceded by + or - */ #include <stdio.h> main() { printf("% d\n% d\n", 547, -547); return 0; } ================================EXAMPLE 37================================ /* Using the # flag with conversion specifiers o, x, X, and any floating-point specifier */ #include <stdio.h> main() { int c = 1427; float p = 1427.0; printf("%#o\n", c); printf("%#x\n", c); printf("%#X\n", c); printf("\n%g\n", p); printf("%#g\n", p); return 0; } ================================EXAMPLE 38================================ /* Printing with the 0(zero) flag fills in leading zeros */ #include <stdio.h> main() { printf("%+09d", 452); printf("%09d", 452); return 0; } ================================EXAMPLE 39================================ /* Reading integers */ #include <stdio.h> main() { int a, b, c, d, e, f, g; printf("Enter seven integers: "); scanf("%d%i%i%i%o%u%x", &a, &b, &c, &d, &e, &f, &g); printf("The input displayed as decimal integers is:\n"); printf("%d %d %d %d %d %d %d\n", a, b, c, d, e, f, g); return 0; } ================================EXAMPLE 40================================ /* Reading floating-point numbers */ #include <stdio.h> main() { float a, b, c; printf("Enter three floating-point numbers: \n"); scanf("%e%f%g", &a, &b, &c); printf("Here are the numbers entered in plain\n"); printf("floating-point notation:\n"); printf("%f %f %f\n", a, b, c); return 0; } ================================EXAMPLE 41================================ /* Reading characters and strings */ #include <stdio.h> main() { char x, y[9]; printf("Enter a string: "); scanf("%c%s", &x, y); printf("The input was:\n"); printf("the character \"%c\" ", x); printf("and the string \"%s\"\n", y); return 0; } ================================EXAMPLE 42================================ /* Using a scan set */ #include <stdio.h> main() { char z[9]; printf("Enter string: "); scanf("%[aeiou]", z); printf("The input was \"%s\"\n", z); return 0; } ================================EXAMPLE 43================================ /* Using an inverted scan set */ #include <stdio.h> main() { char z[9]; printf("Enter a string: "); scanf("%[^aeiou]", z); printf("The input was \"%s\"\n", z); return 0; } ================================EXAMPLE 44================================ /* inputting data with a field width */ #include <stdio.h> main() { int x, y; printf("Enter a six digit integer: "); scanf("%2d%d", &x, &y); printf("The integers input were %d and %d\n", x, y); return 0; } ================================EXAMPLE 45================================ /* Reading and discarding characters from the input stream */ #include <stdio.h> main() { int month1, day1, year1, month2, day2, year2; printf("Enter a date in the form mm-dd-yy: "); scanf("%d%*c%d%*c%d", &month1, &day1, &year1); printf("month = %d day = %d year = %d\n\n", month1, day1, year1); printf("Enter a date in the form mm/dd/yy: "); scanf("%d%*c%d%*c%d", &month2, &day2, &year2); printf("month = %d day = %d year = %d\n", month2, day2, year2); return 0; } ================================EXAMPLE 46================================ /* defining and initializing an array */ #include <stdio.h> main() { int n[10], i; for (i = 0; i <= 9; i++) /* initialize array */ n[i] = 0; printf("%s%13s\n", "Element", "Value"); for(i = 0; i <= 9; i++) /* print array */ printf("%7d%13d\n", i, n[i]); return 0; } ================================EXAMPLE 47================================ /* Initializing an array with a declaration */ #include <stdio.h> main() { int n[10] = {32, 27, 64, 18, 95, 14, 90, 70, 60, 37}; int i; printf("%s%13s\n", "Element", "Value"); for(i = 0; i <= 9; i++) printf("%7d%13d\n", i, n[i]); return 0; } ================================EXAMPLE 48================================ /* Initialize the elements of array s to the even integers from 2 to 20 */ #include <stdio.h> #define SIZE 10 main() { int s[SIZE], j; for (j = 0; j <= SIZE - 1; j++) /* set the values */ s[j] = 2 + 2 * j; printf("%s%13s\n", "Element", "Value"); for (j = 0; j <= SIZE - 1; j++) /* print the values */ printf("%7d%13d\n", j, s[j]); return 0; } ================================EXAMPLE 49================================ /* Compute the sum of the elements of the array */ #include <stdio.h> #define SIZE 12 main() { int a[SIZE] = {1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45}; int i, total = 0; for (i = 0; i <= SIZE - 1; i++) total += a[i]; printf("Total of array element values is %d\n", total); return 0; } ================================EXAMPLE 50================================ /* Student poll program */ #include <stdio.h> #define RESPONSE_SIZE 40 #define FREQUENCY_SIZE 11 main() { int answer, rating; int responses[RESPONSE_SIZE] = {1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10}; int frequency[FREQUENCY_SIZE] = {0}; for(answer = 0; answer <= RESPONSE_SIZE - 1; answer++) ++frequency[responses[answer]]; printf("%s%17s\n", "Rating", "Frequency"); for(rating = 1; rating <= FREQUENCY_SIZE - 1; rating++) printf("%6d%17d\n", rating, frequency[rating]); return 0; } ================================EXAMPLE 51================================ /* Histogram printing program */ #include <stdio.h> #define SIZE 10 main() { int n[SIZE] = {19, 3, 15, 7, 11, 9, 13, 5, 17, 1}; int i, j; printf("%s%13s%17s\n", "Element", "Value", "Histogram"); for (i = 0; i <= SIZE - 1; i++) { printf("%7d%13d ", i, n[i]); for(j = 1; j <= n[i]; j++) /* print one bar */ printf("%c", '*'); printf("\n"); } return 0; } ================================EXAMPLE 52================================ /* Roll a six-sided die 6000 times */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 7 main() { int face, roll, frequency[SIZE] = {0}; srand(time(NULL)); for (roll = 1; roll <= 6000; roll++) { face = rand() % 6 + 1; ++frequency[face]; /* replaces 20-line switch */ } /* of Fig. 5.10 */ printf("%s%17s\n", "Face", "Frequency"); for (face = 1; face <= SIZE - 1; face++) printf("%4d%17d\n", face, frequency[face]); return 0; } ================================EXAMPLE 53================================ /* Treating character arrays as strings */ #include <stdio.h> main() { char string1[20], string2[] = "string literal"; int i; printf("Enter a string: "); scanf("%s", string1); printf("string1 is: %s\nstring2: is %s\n" "string1 with spaces between characters is:\n", string1, string2); for (i = 0; string1[i] != '\0'; i++) printf("%c ", string1[i]); printf("\n"); return 0; } ================================EXAMPLE 54================================ /* Using gets and putchar */ #include <stdio.h> main() { char sentence[80]; void reverse(char *); printf("Enter a line of text:\n"); gets(sentence); printf("\nThe line printed backwards is:\n"); reverse(sentence); return 0; } void reverse(char *s) { if (s[0] == '\0') return; else { reverse(&s[1]); putchar(s[0]); } } ================================EXAMPLE 55================================ /* Using getchar and puts */ #include <stdio.h> main() { char c, sentence[80]; int i = 0; puts("Enter a line of text:"); while ( ( c = getchar() ) != '\n') sentence[i++] = c; sentence[i] = '\0'; /* insert NULL at end of string */ puts("\nThe line entered was:"); puts(sentence); return 0; } ================================EXAMPLE 56================================ /* Static arrays are initialized to zero */ #include <stdio.h> void staticArrayInit(void); void automaticArrayInit(void); main() { printf("First call to each function:\n"); staticArrayInit(); automaticArrayInit(); printf("\n\nSecond call to each function:\n"); staticArrayInit(); automaticArrayInit(); return 0; } /* function to demonstrate a static local array */ void staticArrayInit(void) { static int a[3]; int i; printf("\nValues on entering staticArrayInit:\n"); for (i = 0; i <= 2; i++) printf("array1[%d] = %d ", i, a[i]); printf("\nValues on exiting staticArrayInit:\n"); for (i = 0; i <= 2; i++) printf("array1[%d] = %d ", i, a[i] += 5); } /* function to demonstrate an automatic local array */ void automaticArrayInit(void) { int a[3] = {1, 2, 3}; int i; printf("\n\nValues on entering automaticArrayInit:\n"); for (i = 0; i <= 2; i++) printf("array1[%d] = %d ", i, a[i]); printf("\nValues on exiting automaticArrayInit:\n"); for (i = 0; i <= 2; i++) printf("array1[%d] = %d ", i, a[i] += 5); } ================================EXAMPLE 57================================ /* The name of an array is the same as &array[0] */ #include <stdio.h> main() { char array[5]; printf(" array = %p\n&array[0] = %p\n", array, &array[0]); return 0; } ================================EXAMPLE 58================================ /* Passing arrays and individual array elements to functions */ #include <stdio.h> #define SIZE 5 void modifyArray(int [], int); /* appears strange */ void modifyElement(int); main() { int a[SIZE] = {0, 1, 2, 3, 4}; int i; printf("Effects of passing entire array call " "by reference:\n\nThe values of the " "original array are:\n"); for (i = 0; i <= SIZE - 1; i++) printf("%3d", a[i]); printf("\n"); modifyArray(a, SIZE); /* array a passed call by reference */ printf("The values of the modified array are:\n"); for (i = 0; i <= SIZE - 1; i++) printf("%3d", a[i]); printf("\n\n\nEffects of passing array element call " "by value:\n\nThe value of a[3] is %d\n", a[3]); modifyElement(a[3]); printf("The value of a[3] is %d\n", a[3]); return 0; } void modifyArray(int b[], int size) { int j; for (j = 0; j <= size - 1; j++) b[j] *= 2; } void modifyElement(int e) { printf("Value in modifyElement is %d\n", e *= 2); } ================================EXAMPLE 59================================ /* Demonstrating the const type qualifier */ #include <stdio.h> void tryToModifyArray(const int []); main() { int a[] = {10, 20, 30}; printf("%d %d %d\n", a[0], a[1], a[2]); return 0; } void tryToModifyArray(const int b[]) { b[0] /= 2; /* error */ b[1] /= 2; /* error */ b[2] /= 2; /* error */ } ================================EXAMPLE 60================================ /* This program sorts an array's values into ascending order */ #include <stdio.h> #define SIZE 10 main() { int a[SIZE] = {2, 6, 4, 8, 10, 12, 89, 68, 45, 37}; int i, pass, hold; printf("Data items in original order\n"); for (i = 0; i <= SIZE - 1; i++) printf("%4d", a[i]); for (pass = 1; pass <= SIZE - 1; pass++) /* passes */ for (i = 0; i <= SIZE - 2; i++) /* one pass */ if (a[i] > a[i + 1]) { /* one comparison */ hold = a[i]; /* one swap */ a[i] = a[i + 1]; a[i + 1] = hold; } printf("\nData items in ascending order\n"); for (i = 0; i <= SIZE - 1; i++) printf("%4d", a[i]); printf("\n"); return 0; } ================================EXAMPLE 61================================ /* This program introduces the topic of survey data analysis. It computes the mean, median, and mode of the data */ #include <stdio.h> #define SIZE 99 void mean(int []); void median(int []); void mode(int [], int []); void bubbleSort(int[]); void printArray(int[]); main() { int frequency[10] = {0}, response[SIZE] = {6, 7, 8, 9, 8, 7, 8, 9, 8, 9, 7, 8, 9, 5, 9, 8, 7, 8, 7, 8, 6, 7, 8, 9, 3, 9, 8, 7, 8, 7, 7, 8, 9, 8, 9, 8, 9, 7, 8, 9, 6, 7, 8, 7, 8, 7, 9, 8, 9, 2, 7, 8, 9, 8, 9, 8, 9, 7, 5, 3, 5, 6, 7, 2, 5, 3, 9, 4, 6, 4, 7, 8, 9, 6, 8, 7, 8, 9, 7, 8, 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 4, 5, 6, 1, 6, 5, 7, 8, 7}; mean(response); median(response); mode(frequency, response); return 0; } void mean(int answer[]) { int j, total = 0; printf("%s\n%s\n%s\n", "********", " Mean", "********"); for (j = 0; j <= SIZE - 1; j++) total += answer[j]; printf("The mean is the average value of the data\n" "items. The mean is equal to the total of\n" "all the data items divided by the number\n" "of data items (%d). The mean value for\n" "this run is: %d / %d = %.4f\n\n", SIZE, total, SIZE, (float) total / SIZE); } void median(int answer[]) { printf("\n%s\n%s\n%s\n%s", "********", " Median", "********", "The unsorted array of responses is"); printArray(answer); bubbleSort(answer); printf("\n\nThe sorted array is"); printArray(answer); printf("\n\nThe median is element %d of\n" "the sorted %d element array.\n" "For this run the median is %d\n\n", SIZE / 2, SIZE, answer[SIZE / 2]); } void mode(int freq[], int answer[]) { int rating, j, h, largest = 0, modeValue = 0; printf("\n%s\n%s\n%s\n", "********", " Mode", "********"); for (rating = 1; rating <= 9; rating++) freq[rating] = 0; for (j = 0; j <= SIZE - 1; j++) ++freq[answer[j]]; printf("%s%11s%19s\n\n%54s\n%54s\n\n", "Response", "Frequency", "Histogram", "1 1 2 2", "5 0 5 0 5"); for (rating = 1; rating <= 9; rating++) { printf("%8d%11d ", rating, freq[rating]); if (freq[rating] > largest) { largest = freq[rating]; modeValue = rating; } for (h = 1; h <= freq[rating]; h++) printf("*"); printf("\n"); } printf("The mode is the most frequent value.\n" "For this run the mode is %d which occurred" " %d times.\n", modeValue, largest); } void bubbleSort(int a[]) { int pass, j, hold; for (pass = 1; pass <= SIZE - 1; pass++) for (j = 0; j <= SIZE - 2; j++) if (a[j] > a[j+1]) { hold = a[j]; a[j] = a[j+1]; a[j+1] = hold; } } void printArray(int a[]) { int j; for (j = 0; j <= SIZE - 1; j++) { if (j % 20 == 0) printf("\n"); printf("%2d", a[j]); } } ================================EXAMPLE 62================================ /* Linear search of an array */ #include <stdio.h> #define SIZE 100 int linearSearch(int [], int, int); main() { int a[SIZE], x, searchKey, element; for (x = 0; x <= SIZE - 1; x++) /* create some data */ a[x] = 2 * x; printf("Enter integer search key:\n"); scanf("%d", &searchKey); element = linearSearch(a, searchKey, SIZE); if (element != -1) printf("Found value in element %d\n", element); else printf("Value not found\n"); return 0; } int linearSearch(int array[], int key, int size) { int n; for (n = 0; n <= size - 1; ++n) if (array[n] == key) return n; return -1; } ================================EXAMPLE 63================================ /* Binary search of an array */ #include <stdio.h> #define SIZE 15 int binarySearch(int [], int, int, int); void printHeader(void); void printRow(int [], int, int, int); main() { int a[SIZE], i, key, result; for (i = 0; i <= SIZE - 1; i++) a[i] = 2 * i; printf("Enter a number between 0 and 28: "); scanf("%d", &key); printHeader(); result = binarySearch(a, key, 0, SIZE - 1); if (result != -1) printf("\n%d found in array element %d\n", key, result); else printf("\n%d not found\n", key); return 0; } int binarySearch(int b[], int searchKey, int low, int high) { int middle; while (low <= high) { middle = (low + high) / 2; printRow(b, low, middle, high); if (searchKey == b[middle]) return middle; else if (searchKey < b[middle]) high = middle - 1; else low = middle + 1; } return -1; /* searchKey not found */ } /* Print a header for the output */ void printHeader(void) { int i; printf("\nSubscripts:\n"); for (i = 0; i <= SIZE - 1; i++) printf("%3d ", i); printf("\n"); for (i = 1; i <= 4 * SIZE; i++) printf("-"); printf("\n"); } /* Print one row of output showing the current part of the array being processed. */ void printRow(int b[], int low, int mid, int high) { int i; for (i = 0; i <= SIZE - 1; i++) if (i < low || i > high) printf(" "); else if (i == mid) printf("%3d*", b[i]); /* mark middle value */ else printf("%3d ", b[i]); printf("\n"); } ================================EXAMPLE 64================================ /* Initializing multidimensional arrays */ #include <stdio.h> void printArray(int [][3]); main() { int array1[2][3] = { {1, 2, 3}, {4, 5, 6} }, array2[2][3] = { 1, 2, 3, 4, 5 }, array3[2][3] = { {1, 2}, {4} }; printf("Values in array1 by row are:\n"); printArray(array1); printf("Values in array2 by row are:\n"); printArray(array2); printf("Values in array3 by row are:\n"); printArray(array3); return 0; } void printArray(int a[][3]) { int i, j; for (i = 0; i <= 1; i++) { for (j = 0; j <= 2; j++) printf("%d ", a[i][j]);; printf("\n"); } } ================================EXAMPLE 65================================ /* Double-subscripted array example */ #include <stdio.h> #define STUDENTS 3 #define EXAMS 4 int minimum(int [][EXAMS], int, int); int maximum(int [][EXAMS], int, int); float average(int [], int); void printArray(int [][EXAMS], int, int); main() { int student, studentGrades[STUDENTS][EXAMS] = {{77, 68, 86, 73}, {96, 87, 89, 78}, {70, 90, 86, 81}}; printf("The array is:\n"); printArray(studentGrades, STUDENTS, EXAMS); printf("\n\nLowest grade: %d\nHighest grade: %d\n", minimum(studentGrades, STUDENTS, EXAMS), maximum(studentGrades, STUDENTS, EXAMS)); for (student = 0; student <= STUDENTS - 1; student++) printf("The average grade for student %d is %.2f\n", student, average(studentGrades[student], EXAMS)); return 0; } /* Find the minimum grade */ int minimum(int grades[][EXAMS], int pupils, int tests) { int i, j, lowGrade = 100; for (i = 0; i <= pupils - 1; i++) for (j = 0; j <= tests - 1; j++) if (grades[i][j] < lowGrade) lowGrade = grades[i][j]; return lowGrade; } /* Find the maximum grade */ int maximum(int grades[][EXAMS], int pupils, int tests) { int i, j, highGrade = 0; for (i = 0; i <= pupils - 1; i++) for (j = 0; j <= tests - 1; j++) if (grades[i][j] > highGrade) highGrade = grades[i][j]; return highGrade; } /* Determine the average grade for a particular exam */ float average(int setOfGrades[], int tests) { int i, total = 0; for (i = 0; i <= tests - 1; i++) total += setOfGrades[i]; return (float) total / tests; } /* Print the array */ void printArray(int grades[][EXAMS], int pupils, int tests) { int i, j; printf(" [0] [1] [2] [3]"); for (i = 0; i <= pupils - 1; i++) { printf("\nstudentGrades[%d] ", i); for (j = 0; j <= tests - 1; j++) printf("%-5d", grades[i][j]); } } ================================EXAMPLE 66================================ /* Using the & and * operators */ #include <stdio.h> main() { int a; /* a is an integer */ int *aPtr; /* aPtr is a pointer to an integer */ a = 7; aPtr = &a; /* aPtr set to address of a */ printf("The address of a is %p\n" "The value of aPtr is %p\n\n", &a, aPtr); printf("The value of a is %d\n" "The value of *aPtr is %d\n\n", a, *aPtr); printf("Proving that * and & are complements of " "each other.\n&*aPtr = %p\n*&aPtr = %p\n", &*aPtr, *&aPtr); return 0; } ================================EXAMPLE 67================================ /* Cube a variable using call by value */ #include <stdio.h> int cubeByValue(int); main() { int number = 5; printf("The original value of number is %d\n", number); number = cubeByValue(number); printf("The new value of number is %d\n", number); return 0; } int cubeByValue(int n) { return n * n * n; /* cube local variable n */ } ================================EXAMPLE 68================================ /* Cube a variable using call by reference */ #include <stdio.h> void cubeByReference(int *); main() { int number = 5; printf("The original value of number is %d\n", number); cubeByReference(&number); printf("The new value of number is %d\n", number); return 0; } void cubeByReference(int *nPtr) { *nPtr = (*nPtr) * (*nPtr) * (*nPtr); /* cube number in main */ } ================================EXAMPLE 69================================ /* Converting lowercase letters to uppercase letters */ /* using a non-constant pointer to non-constant data */ #include <stdio.h> void convertToUppercase(char *); main() { char string[] = "characters"; printf("The string before conversion is: %s\n", string); convertToUppercase(string); printf("The string after conversion is: %s\n", string); return 0; } void convertToUppercase(char *s) { while (*s != '\0') { if (*s >= 'a' && *s <= 'z') *s -= 32; /* convert to ASCII uppercase letter */ ++s; /* increment s to point to the next character */ } } ================================EXAMPLE 70================================ /* Printing a string one character at a time using */ /* a non-constant pointer to constant data */ #include <stdio.h> void printCharacters(const char *); main() { char string[] = "print characters of a string"; printf("The string is:\n"); printCharacters(string); putchar('\n'); return 0; } void printCharacters(const char *s) { for ( ; *s != '\0'; s++) /* no initialization */ putchar(*s); } ================================EXAMPLE 71================================ /* Attempting to modify data through a */ /* non-constant pointer to constant data */ #include <stdio.h> void f(const int *); main() { int y; f(&y); /* f attempts illegal modification */ return 0; } void f(const int *x) { *x = 100; /* cannot modify a const object */ } ================================EXAMPLE 72================================ /* Attempting to modify a constant pointer to non-constant data */ #include <stdio.h> main() { int x, y; int * const ptr = &x; ptr = &y; return 0; } ================================EXAMPLE 73================================ /* Attempting to modify a constant pointer to constant data */ */ #include <stdio.h> main() { int x = 5, y; const int *const ptr = &x; *ptr = 7; ptr = &y; return 0; } ================================EXAMPLE 74================================ /* This program puts values into an array, sorts the values into ascending order, and prints the resulting array */ #include <stdio.h> #define SIZE 10 void bubbleSort(int *, const int); main() { int i, a[SIZE] = {2, 6, 4, 8, 10, 12, 89, 68, 45, 37}; printf("Data items in original order\n"); for (i = 0; i <= SIZE - 1; i++) printf("%4d", a[i]); bubbleSort(a, SIZE); /* sort the array */ printf("\nData items in ascending order\n"); for (i = 0; i <= SIZE - 1; i++) printf("%4d", a[i]); printf("\n"); return 0; } void bubbleSort(int *array, const int size) { int pass, j; void swap(int *, int *); for (pass = 1; pass <= size - 1; pass++) for (j = 0; j <= size - 2; j++) if (array[j] > array[j + 1]) swap(&array[j], &array[j + 1]); } void swap(int *element1Ptr, int *element2Ptr) { int temp; temp = *element1Ptr; *element1Ptr = *element2Ptr; *element2Ptr = temp; } ================================EXAMPLE 75================================ /* sizeof operator when used on an array name returns the number of bytes in the array */ #include <stdio.h> main() { float array[20]; printf("The number of bytes in the array is %d\n", sizeof(array)); return 0; } ================================EXAMPLE 76================================ /* Demonstrating the sizeof operator */ #include <stdio.h> main() { printf(" sizeof(char) = %d\n" " sizeof(short) = %d\n" " sizeof(int) = %d\n" " sizeof(long) = %d\n" " sizeof(float) = %d\n" " sizeof(double) = %d\n" "sizeof(long double) = %d\n", sizeof(char), sizeof(short), sizeof(int), sizeof(long), sizeof(float), sizeof(double), sizeof(long double)); return 0; } ================================EXAMPLE 77================================ /* Using subscripting and pointer notations with arrays */ #include <stdio.h> main() { int i, offset, b[] = {10, 20, 30, 40}; int *bPtr = b; /* set bPtr to point to array b */ printf("Array b printed with:\n" "Array subscript notation\n"); for (i = 0; i <= 3; i++) printf("b[%d] = %d\n", i, b[i]); printf("\nPointer/offset notation where \n" "the pointer is the array name\n"); for (offset = 0; offset <= 3; offset++) printf("*(b + %d) = %d\n", offset, *(b + offset)); printf("\nPointer subscript notation\n"); for (i = 0; i <= 3; i++) printf("bPtr[%d] = %d\n", i, bPtr[i]); printf("\nPointer/offset notation\n"); for (offset = 0; offset <= 3; offset++) printf("*(bPtr + %d) = %d\n", offset, *(bPtr + offset)); return 0; } ================================EXAMPLE 78================================ /* Copying a string using array notation and pointer notation */ #include <stdio.h> void copy1(char *, const char *); void copy2(char *, const char *); main() { char string1[10], *string2 = "Hello", string3[10], string4[] = "Good Bye"; copy1(string1, string2); printf("string1 = %s\n", string1); copy2(string3, string4); printf("string3 = %s\n", string3); return 0; } /* copy s2 to s1 using array notation */ void copy1(char *s1, const char *s2) { int i; for (i = 0; s1[i] = s2[i]; i++) ; /* do nothing in body */ } /* copy s2 to s1 using pointer notation */ void copy2(char *s1, const char *s2) { for ( ; *s1 = *s2; s1++, s2++) ; /* do nothing in body */ } ================================EXAMPLE 79================================ /* Multipurpose sorting program using function pointers */ #include <stdio.h> #define SIZE 10 void bubble(int *, const int, int (*)(int, int)); int ascending(const int, const int); int descending(const int, const int); main() { int a[SIZE] = {2, 6, 4, 8, 10, 12, 89, 68, 45, 37}; int counter, order; printf("Enter 1 to sort in ascending order,\n"); printf("Enter 2 to sort in descending order: "); scanf("%d", &order); printf("\nData items in original order\n"); for (counter = 0; counter <= SIZE - 1; counter++) printf("%4d", a[counter]); if (order == 1) { bubble(a, SIZE, ascending); printf("\nData items in ascending order\n"); } else { bubble(a, SIZE, descending); printf("\nData items in descending order\n"); } for (counter = 0; counter <= SIZE - 1; counter++) printf("%4d", a[counter]); printf("\n"); return 0; } void bubble(int *work, const int size, int (*compare)(int, int)) { int pass, count; void swap(int *, int *); for (pass = 1; pass <= size - 1; pass++) for (count = 0; count <= size - 2; count++) if ((*compare)(work[count], work[count + 1])) swap(&work[count], &work[count + 1]); } void swap(int *element1Ptr, int *element2Ptr) { int temp; temp = *element1Ptr; *element1Ptr = *element2Ptr; *element2Ptr = temp; } int ascending(const int a, const int b) { return b < a; } int descending(const int a, const int b) { return b > a; } ================================EXAMPLE 80================================ /* Demonstrating an array of pointers to functions */ #include <stdio.h> void function1(int); void function2(int); void function3(int); main() { void (*f[3])(int) = {function1, function2, function3}; int choice; printf("Enter a number between 0 and 2, 3 to end: "); scanf("%d", &choice); while (choice >= 0 && choice < 3) { (*f[choice])(choice); printf("Enter a number between 0 and 2, 3 to end: "); scanf("%d", &choice); } printf("You entered 3 to end\n"); return 0; } void function1(int a) { printf("You entered %d so function1 was called\n\n", a); } void function2(int b) { printf("You entered %d so function2 was called\n\n", b); } void function3(int c) { printf("You entered %d so function3 was called\n\n", c); } ================================EXAMPLE 81================================ /* Using the structure member and structure pointer operators */ #include <stdio.h> struct Name { char *first; char *last; unsigned id; }; main() { struct Name a; struct Name *aPtr; a.first = "Ali"; a.last = "Salimi"; aPtr = &a; aPtr->id = 81379; printf("%s%s%s\t%d\n%s%s%s\t%d\n%s%s%s\t%d\n", a.first, " ", a.last, a.id, aPtr->first, " ", aPtr->last, aPtr->id, (*aPtr).first, " ", (*aPtr).last, (*aPtr).id ); return 0; } ================================EXAMPLE 82================================ /* Printing an unsigned integer in bits */ #include <stdio.h> main() { unsigned x; void displayBits(unsigned); printf("Enter an unsigned integer: "); scanf("%u", &x); displayBits(x); return 0; } void displayBits(unsigned value) { unsigned c, displayMask = 1 << 31; printf("%#8x = ", value); for (c = 1; c <= 32; c++) { putchar(value & displayMask ? '1' : '0'); value <<= 1; if (c % 8 == 0) putchar(' '); } putchar('\n'); } ================================EXAMPLE 83================================ /* Using the bitwise AND, bitwise inclusive OR, bitwise exclusive OR, and bitwise complement operators */ #include <stdio.h> void displayBits(unsigned); main() { unsigned number1, number2, mask, setBits; number1 = 0x289cb07f; mask = 1; printf("The result of combining the following\n"); displayBits(number1); displayBits(mask); printf("using the bitwise AND operator & is\n"); displayBits(number1 & mask); number1 = 0xaf015; setBits = 0xf0241; printf("\nThe result of combining the following\n"); displayBits(number1); displayBits(setBits); printf("using the bitwise inclusive OR operator | is\n"); displayBits(number1 | setBits); number1 = 78139; number2 = 522199; printf("\nThe result of combining the following\n"); displayBits(number1); displayBits(number2); printf("using the bitwise exclusive OR operator ^ is\n"); displayBits(number1 ^ number2); number1 = 0x21845; printf("\nThe one's complement of\n"); displayBits(number1); printf("is\n"); displayBits(~number1); return 0; } ================================EXAMPLE 84================================ /* Using the bitwise shift operators */ #include <stdio.h> void displayBits(unsigned); main() { unsigned number1 = 0x397fa960; printf("\nThe result of left shifting\n"); displayBits(number1); printf("8 bit positions using the "); printf("left shift operator << is\n"); displayBits(number1 << 8); printf("\nThe result of right shifting\n"); displayBits(number1); printf("8 bit positions using the "); printf("right shift operator >> is\n"); displayBits(number1 >> 8); return 0; } ================================EXAMPLE 85================================ /* Defining a new name for an exiting type using typedef */ typedef char* string; int main(void) { string a[] = {"I", "like", "to", "fight,"}, b[] = {"pinch,", "and", "bight."}; printf("%s %s %s %s %s %s %s\n", a[0], a[1], a[2], a[3], b[0], b[1], b[2]); return 0; } ================================EXAMPLE 86================================ /* An example of a union */ #include <stdio.h> union number { int x; float y; }; main() { union number value; value.x = 100; printf("%s\n%s\n%s%d\n%s%f\n\n", "Put a value in the integer member", "and print both members.", "int: ", value.x, "float: ", value.y); value.y = 100.0; printf("%s\n%s\n%s%d\n%s%f\n", "Put a value in the floating member", "and print both members.", "int: ", value.x, "float: ", value.y); return 0; } ================================EXAMPLE 87================================ /* Example using a bit field */ #include <stdio.h> struct WordBytes { unsigned b0:8, b1:8, b2:8, b3:8; }; typedef struct WordBytes WordBytes; struct WordBits { unsigned b0 :1, b1 :1, b2 :1, b3 :1, b4 :1, b5 :1, b6 :1, b7 :1, b8 :1, b9 :1, b10:1, b11:1, b12:1, b13:1, b14:1, b15:1, b16:1, b17:1, b18:1, b19:1, b20:1, b21:1, b22:1, b23:1, b24:1, b25:1, b26:1, b27:1, b28:1, b29:1, b30:1, b31:1; }; typedef struct WordBits WordBits; typedef union { int n; WordBits bit; WordBytes byte; } Word; void displayBits(unsigned); main() { Word w = {0}; w.bit.b8 = 1; w.bit.b11 = 1; w.byte.b0 = 'a'; w.byte.b3 = 'h'; printf("w.n = %x\n", w.n); displayBits(w.n); return 0; } ================================EXAMPLE 88================================ /* Using an enumeration type */ #include <stdio.h> enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; main() { enum months month; char *monthName[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; for (month = JAN; month <= DEC; month++) printf("%2d%11s\n", month, monthName[month]); return 0; } ================================EXAMPLE 89================================ /* Using functions isdigit, isalpha, isalnum, and isxdigit */ #include <stdio.h> #include <ctype.h> main() { printf("%s\n%s%s\n%s%s\n\n", "According to isdigit: ", isdigit('8') ? "8 is a " : "8 is not a ", "digit", isdigit('#') ? "# is a " : "# is not a ", "digit"); printf("%s\n%s%s\n%s%s\n%s%s\n%s%s\n\n", "According to isalpha:", isalpha('A') ? "A is a " : "A is not a ", "letter", isalpha('b') ? "b is a " : "b is not a ", "letter", isalpha('&') ? "& is a " : "& is not a ", "letter", isalpha('4') ? "4 is a " : "4 is not a ", "letter"); printf("%s\n%s%s\n%s%s\n%s%s\n\n", "According to isalnum:", isalnum('A') ? "A is a " : "A is not a ", "digit or a letter", isalnum('8') ? "8 is a " : "8 is not a ", "digit or a letter", isalnum('#') ? "# is a " : "# is not a ", "digit or a letter"); printf("%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n", "According to isxdigit:", isxdigit('F') ? "F is a " : "F is not a ", "hexadecimal digit", isxdigit('J') ? "J is a " : "J is not a ", "hexadecimal digit", isxdigit('7') ? "7 is a " : "7 is not a ", "hexadecimal digit", isxdigit('$') ? "$ is a " : "$ is not a ", "hexadecimal digit", isxdigit('f') ? "f is a " : "f is not a ", "hexadecimal digit"); return 0; } ================================EXAMPLE 90================================ /* Using functions islower, isupper, tolower, toupper */ #include <stdio.h> #include <ctype.h> main() { printf("%s\n%s%s\n%s%s\n%s%s\n%s%s\n\n", "According to islower:", islower('p') ? "p is a " : "p is not a ", "lowercase letter", islower('P') ? "P is a " : "P is not a ", "lowercase letter", islower('5') ? "5 is a " : "5 is not a ", "lowercase letter", islower('!') ? "! is a " : "! is not a ", "lowercase letter"); printf("%s\n%s%s\n%s%s\n%s%s\n%s%s\n\n", "According to isupper:", isupper('D') ? "D is an " : "D is not an ", "uppercase letter", isupper('d') ? "d is an " : "d is not an ", "uppercase letter", isupper('8') ? "8 is an " : "8 is not an ", "uppercase letter", isupper('$') ? "$ is an " : "$ is not an ", "uppercase letter"); printf("%s%c\n%s%c\n%s%c\n%s%c\n", "u converted to uppercase is ", toupper('u'), "7 converted to uppercase is ", toupper('7'), "$ converted to uppercase is ", toupper('$'), "L converted to lowercase is ", tolower('L')); return 0; } ================================EXAMPLE 91================================ /* Using functions isspace, iscntrl, ispunct, isprint, isgraph */ #include <stdio.h> #include <ctype.h> main() { printf("%s\n%s%s%s\n%s%s%s\n%s%s\n\n", "According to isspace:", "Newline", isspace('\n') ? " is a " : " is not a ", "whitespace character", "Horizontal tab", isspace('\t') ? " is a " : " is not a ", "whitespace character", isspace('%') ? "% is a " : "% is not a ", "whitespace character"); printf("%s\n%s%s%s\n%s%s\n\n", "According to iscntrl:", "Newline", iscntrl('\n') ? " is a " : " is not a ", "control character", iscntrl('$') ? "$ is a " : "$ is not a ", "control character"); printf("%s\n%s%s\n%s%s\n%s%s\n\n", "According to ispunct:", ispunct(';') ? "; is a " : "; is not a ", "punctuation character", ispunct('Y') ? "Y is a " : "Y is not a ", "punctuation character", ispunct('#') ? "# is a " : "# is not a ", "punctuation character"); printf("%s\n%s%s\n%s%s%s\n\n", "According to isprint:", isprint('$') ? "$ is a " : "$ is not a ", "printing character", "Alert", isprint('\a') ? " is a " : " is not a ", "printing character"); printf("%s\n%s%s\n%s%s%s\n", "According to isgraph:", isgraph('Q') ? "Q is a " : "Q is not a ", "printing character other than a space", "Space", isgraph(' ') ? " is a " : " is not a ", "printing character other than a space"); return 0; } ================================EXAMPLE 92================================ /* Using atof */ #include <stdio.h> #include <stdlib.h> main() { double d; d = atof("99.0"); printf("%s%.3f\n%s%.3f\n", "The string \"99.0\" converted to double is ", d, "The converted value divided by 2 is ", d / 2.0); return 0; } ================================EXAMPLE 93================================ /* Using atoi */ #include <stdio.h> #include <stdlib.h> main() { int i; i = atoi("2593"); printf("%s%d\n%s%d\n", "The string \"2593\" converted to int is ", i, "The converted value minus 593 is ", i - 593); return 0; } ================================EXAMPLE 94================================ /* Using atol */ #include <stdio.h> #include <stdlib.h> main() { long l; l = atol("1000000"); printf("%s%ld\n%s%ld\n", "The string \"1000000\" converted to long int is ", l, "The converted value divided by 2 is ", l / 2); return 0; } ================================EXAMPLE 95================================ /* Using strtod */ #include <stdio.h> #include <stdlib.h> main() { double d; char *string = "51.2% are admitted"; char *stringPtr; d = strtod(string, &stringPtr); printf("The string \"%s\" is converted to the\n", string); printf("double value %.2f and the string \"%s\"\n", d, stringPtr); return 0; } ================================EXAMPLE 96================================ /* Using strtol */ #include <stdio.h> #include <stdlib.h> main() { long x; char *string = "-1234567abc", *remainderPtr; x = strtol(string, &remainderPtr, 0); printf("%s\"%s\"\n%s%ld\n%s\"%s\"\n%s%ld\n", "The original string is ", string, "The converted value is ", x, "The remainder of the original string is ", remainderPtr, "The converted value plus 567 is ", x + 567); return 0; } ================================EXAMPLE 97================================ /* Using strtoul */ #include <stdio.h> #include <stdlib.h> main() { unsigned long x; char *string = "1234567abc", *remainderPtr; x = strtoul(string, &remainderPtr, 0); printf("%s\"%s\"\n%s%lu\n%s\"%s\"\n%s%lu\n", "The original string is ", string, "The converted value is ", x, "The remainder of the original string is ", remainderPtr, "The converted value minus 567 is ", x - 567); return 0; } ================================EXAMPLE 98================================ /* Using sprintf */ #include <stdio.h> main() { char s[80]; int x; float y; printf("Enter an integer and a float:\n"); scanf("%d%f", &x, &y); sprintf(s, "Integer:%6d\nFloat:%8.2f", x, y); printf("%s\n%s\n", "The formatted output stored in array s is:", s); return 0; } ================================EXAMPLE 99================================ /* Using sscanf */ #include <stdio.h> main() { char s[] = "31298 87.375"; int x; float y; sscanf(s, "%d%f", &x, &y); printf("%s\n%s%6d\n%s%8.3f\n", "The values stored in character array s are:", "Integer:", x, "Float:", y); return 0; } ================================EXAMPLE 100================================ /* Using strcpy and strncpy */ #include <stdio.h> #include <string.h> main() { char x[] = "Happy Birthday to You"; char y[25], z[15]; printf("%s%s\n%s%s\n", "The string in array x is: ", x, "The string in array y is: ", strcpy(y, x)); strncpy(z, x, 14); z[14] = '\0'; printf("The string in array z is: %s\n", z); return 0; } ================================EXAMPLE 101================================ /* Using strcat and strncat */ #include <stdio.h> #include <string.h> main() { char s1[20] = "Happy "; char s2[] = "New Year "; char s3[40] = ""; printf("s1 = %s\ns2 = %s\n", s1, s2); printf("strcat(s1, s2) = %s\n", strcat(s1, s2)); printf("strncat(s3, s1, 6) = %s\n", strncat(s3, s1, 6)); printf("strcat(s3, s1) = %s\n", strcat(s3, s1)); return 0; } ================================EXAMPLE 102================================ /* Using strcmp and strncmp */ #include <stdio.h> #include <string.h> main() { char *s1 = "Happy New Year"; char *s2 = "Happy New Year"; char *s3 = "Happy Holidays"; printf("%s%s\n%s%s\n%s%s\n\n%s%2d\n%s%2d\n%s%2d\n\n", "s1 = ", s1, "s2 = ", s2, "s3 = ", s3, "strcmp(s1, s2) = ", strcmp(s1, s2), "strcmp(s1, s3) = ", strcmp(s1, s3), "strcmp(s3, s1) = ", strcmp(s3, s1)); printf("%s%2d\n%s%2d\n%s%2d\n", "strncmp(s1, s3, 6) = ", strncmp(s1, s3, 6), "strncmp(s1, s3, 7) = ", strncmp(s1, s3, 7), "strncmp(s3, s1, 7) = ", strncmp(s3, s1, 7)); return 0; } ================================EXAMPLE 103================================ /* Using strchr */ #include <stdio.h> #include <string.h> main() { char *string = "This is a test"; char character1 = 'a', character2 = 'z'; if (strchr(string, character1) != NULL) printf("\'%c\' was found in \"%s\".\n", character1, string); else printf("\'%c\' was not found in \"%s\".\n", character1, string); if (strchr(string, character2) != NULL) printf("\'%c\' was found in \"%s\".\n", character2, string); else printf("\'%c\' was not found in \"%s\".\n", character2, string); return 0; } ================================EXAMPLE 104================================ /* Using strcspn */ #include <stdio.h> #include <string.h> main() { char *string1 = "The value is 3.14159"; char *string2 = "1234567890"; printf("%s%s\n%s%s\n\n%s\n%s%u", "string1 = ", string1, "string2 = ", string2, "The length of the initial segment of string1", "containing no characters from string2 = ", strcspn(string1, string2)); return 0; } ================================EXAMPLE 105================================ /* Using strpbrk */ #include <stdio.h> #include <string.h> main() { char *string1 = "This is a test"; char *string2 = "beware"; printf("%s\"%s\"\n'%c'%s\n\"%s\"\n", "Of the characters in ", string2, *strpbrk(string1, string2), " is the first character to appear in ", string1); return 0; } ================================EXAMPLE 106================================ /* Using strrchr */ #include <stdio.h> #include <string.h> main() { char *string1 = "A zoo has many animals including zebras"; int c = 'z'; printf("%s\n%s'%c'%s\"%s\"\n", "The remainder of string1 beginning with the", "last occurrence of character ", c, " is: ", strrchr(string1, c)); return 0; } ================================EXAMPLE 107================================ /* Using strspn */ #include <stdio.h> #include <string.h> main() { char *string1 = "The value is 3.14159"; char *string2 = "aehilsTuv "; printf("%s%s\n%s%s\n\n%s\n%s%u\n", "string1 = ", string1, "string2 = ", string2, "The length of the initial segment of string1", "containing only characters from string2 = ", strspn(string1, string2)); return 0; } ================================EXAMPLE 108================================ /* Using strstr */ #include <stdio.h> #include <string.h> main() { char *string1 = "abcdefabcdef"; char *string2 = "def"; printf("%s%s\n%s%s\n\n%s\n%s%s\n", "string1 = ", string1, "string2 = ", string2, "The remainder of string1 beginning with the", "first occurrence of string2 is: ", strstr(string1, string2)); return 0; } ================================EXAMPLE 109================================ /* Using strtok */ #include <stdio.h> #include <string.h> main() { char string[] = "This is a sentence with 7 tokens"; char *tokenPtr; printf("%s\n%s\n\n%s\n", "The string to be tokenized is:", string, "The tokens are:"); tokenPtr = strtok(string, " "); while (tokenPtr != NULL) { printf("%s\n", tokenPtr); tokenPtr = strtok(NULL, " "); } return 0; } ================================EXAMPLE 110================================ /* Using memcpy */ #include <stdio.h> #include <string.h> main() { char s1[17], s2[] = "Copy this string"; memcpy(s1, s2, 17); printf("%s\n%s\"%s\"\n", "After s2 is copied into s1 with memcpy,", "s1 contains ", s1); return 0; } ================================EXAMPLE 111================================ /* Using memmove */ #include <stdio.h> #include <string.h> main() { char x[] = "Home Sweet Home"; printf("%s%s\n", "The string in array x before memmove is: ", x); printf("%s%s\n", "The string in array x after memmove is: ", memmove(x, &x[5], 10)); return 0; } ================================EXAMPLE 112================================ /* Using memcmp */ #include <stdio.h> #include <string.h> main() { char s1[] = "ABCDEFG", s2[] = "ABCDXYZ"; printf("%s%s\n%s%s\n\n%s%2d\n%s%2d\n%s%2d\n", "s1 = ", s1, "s2 = ", s2, "memcmp(s1, s2, 4) = ", memcmp(s1, s2, 4), "memcmp(s1, s2, 7) = ", memcmp(s1, s2, 7), "memcmp(s2, s1, 7) = ", memcmp(s2, s1, 7)); return 0; } ================================EXAMPLE 113================================ /* Using memchr */ #include <stdio.h> #include <string.h> main() { char *s = "This is a string"; printf("%s\'%c\'%s\"%s\"\n", "The remainder of s after character ", 'r', " is found is ", memchr(s, 'r', 16)); return 0; } ================================EXAMPLE 114================================ /* Using memset */ #include <stdio.h> #include <string.h> main() { char string1[15] = "BBBBBBBBBBBBBB"; printf("string1 = %s\n", string1); printf("string1 after memset = %s\n", memset(string1, 'b', 7)); return 0; } ================================EXAMPLE 115================================ /* Using strerror */ #include <stdio.h> #include <string.h> main() { printf("%s\n", strerror(2)); return 0; } ================================EXAMPLE 116================================ /* Using strlen */ #include <stdio.h> #include <string.h> main() { char *string1 = "abcdefghijklmnopqrstuvwxyz"; char *string2 = "four"; char *string3 = "Boston"; printf("%s\"%s\"%s%lu\n%s\"%s\"%s%lu\n%s\"%s\"%s%lu\n", "The length of ", string1, " is ", strlen(string1), "The length of ", string2, " is ", strlen(string2), "The length of ", string3, " is ", strlen(string3)); return 0; } ================================EXAMPLE 117================================ /* Create a sequential file */ #include <stdio.h> main() { int account; char name[30]; float balance; FILE *cfPtr; /* cfPtr = clients.dat file pointer */ if ((cfPtr = fopen("clients.dat", "w")) == NULL) printf("File could not be opened\n"); else { printf("Enter the account, name, and balance.\n"); printf("Enter EOF to end input.\n"); printf("? "); scanf("%d%s%f", &account, name, &balance); while (!feof(stdin)) { fprintf(cfPtr, "%d %s %.2f\n", account, name, balance); printf("? "); scanf("%d%s%f", &account, name, &balance); } fclose(cfPtr); } return 0; } ================================EXAMPLE 118================================ /* Reading and printing a sequential file */ #include <stdio.h> main() { int account; char name[30]; float balance; FILE *cfPtr; /* cfPtr = clients.dat file pointer */ if ((cfPtr = fopen("clients.dat", "r")) == NULL) printf("File could not be opened\n"); else { printf("%-10s%-13s%s\n", "Account", "Name", "Balance"); fscanf(cfPtr, "%d%s%f", &account, name, &balance); while (!feof(cfPtr)) { printf("%-10d%-13s%7.2f\n", account, name, balance); fscanf(cfPtr, "%d%s%f", &account, name, &balance); } fclose(cfPtr); } return 0; } ================================EXAMPLE 119================================ /* Creating a randomly accessed file sequentially */ #include <stdio.h> struct clientData { int acctNum; char lastName[15]; char firstName[10]; float balance; }; main() { int i; struct clientData blankClient = {0, "", "", 0.0}; FILE *cfPtr; if ((cfPtr = fopen("credit.dat", "w")) == NULL) printf("File could not be opened.\n"); else { for (i = 1; i <= 100; i++) fwrite(&blankClient, sizeof(struct clientData), 1, cfPtr); fclose (cfPtr); } return 0; } ================================EXAMPLE 120================================ /* Writing to a random access file */ #include <stdio.h> struct clientData { int acctNum; char lastName[15]; char firstName[10]; float balance; }; main() { FILE *cfPtr; struct clientData client; if ((cfPtr = fopen("credit.dat", "r+")) == NULL) printf("File could not be opened.\n"); else { printf("Enter account number" " (1 to 100, 0 to end input)\n? "); scanf("%d", &client.acctNum); while (client.acctNum != 0) { printf("Enter lastname, firstname, balance\n? "); scanf("%s%s%f", &client.lastName, &client.firstName, &client.balance); fseek(cfPtr, (client.acctNum - 1) * sizeof(struct clientData), SEEK_SET); fwrite(&client, sizeof(struct clientData), 1, cfPtr); printf("Enter account number\n? "); scanf("%d", &client.acctNum); } } fclose(cfPtr); return 0; } ================================EXAMPLE 121================================ /* Reading a random access file sequentially */ #include <stdio.h> struct clientData { int acctNum; char lastName[15]; char firstName[10]; float balance; }; main() { FILE *cfPtr; struct clientData client; if ((cfPtr = fopen("credit.dat", "r")) == NULL) printf("File could not be opened.\n"); else { printf("%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance"); while (!feof(cfPtr)) { fread(&client, sizeof(struct clientData), 1, cfPtr); if (client.acctNum != 0) printf("%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance); } } fclose(cfPtr); return 0; } ================================EXAMPLE 122================================ /* This program reads a random access file sequentially, * * updates data already written to the file, creates new * * data to be placed in the file, and deletes data * * already in the file. */ #include <stdio.h> struct clientData { int acctNum; char lastName[15]; char firstName[10]; float balance; }; int enterChoice(void); void textFile(FILE *); void updateRecord(FILE *); void newRecord(FILE *); void deleteRecord(FILE *); main() { FILE *cfPtr; int choice; if ((cfPtr = fopen("credit.dat", "r+")) == NULL) printf("File could not be opened.\n"); else { while ((choice = enterChoice()) != 5) { switch (choice) { case 1: textFile(cfPtr); break; case 2: updateRecord(cfPtr); break; case 3: newRecord(cfPtr); break; case 4: deleteRecord(cfPtr); break; } } } fclose(cfPtr); return 0; } void textFile(FILE *readPtr) { FILE *writePtr; struct clientData client; if ((writePtr = fopen("accounts.txt", "w")) == NULL) printf("File could not be opened.\n"); else { rewind(readPtr); fprintf(writePtr, "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name","Balance"); while (!feof(readPtr)) { fread(&client, sizeof(struct clientData), 1, readPtr); if (client.acctNum != 0) fprintf(writePtr, "%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance); } } fclose(writePtr); } void updateRecord(FILE *fPtr) { int account; float transaction; struct clientData client; printf("Enter account to update (1 - 100): "); scanf("%d", &account); fseek(fPtr, (account - 1) * sizeof(struct clientData), SEEK_SET); fread(&client, sizeof(struct clientData), 1, fPtr); if (client.acctNum == 0) printf("Acount #%d has no information.\n", account); else { printf("%-6d%-16s%-11s%10.2f\n\n", client.acctNum, client.lastName, client.firstName, client.balance); printf("Enter charge (+) or payment (-): "); scanf("%f", &transaction); client.balance += transaction; printf("%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance); fseek(fPtr, (account - 1) * sizeof(struct clientData), SEEK_SET); fwrite(&client, sizeof(struct clientData), 1, fPtr); } } void deleteRecord(FILE *fPtr) { struct clientData client, blankClient = {0, "", "", 0}; int accountNum; printf("Enter account number to delete (1 - 100): "); scanf("%d", &accountNum); fseek(fPtr, (accountNum - 1) * sizeof(struct clientData), SEEK_SET); fread(&client, sizeof(struct clientData), 1, fPtr); if (client.acctNum == 0) printf("Account %d does not exist.\n", accountNum); else { fseek(fPtr, (accountNum - 1) * sizeof(struct clientData), SEEK_SET); fwrite(&blankClient, sizeof(struct clientData), 1, fPtr); } } void newRecord(FILE *fPtr) { struct clientData client; int accountNum; printf("Enter new account number (1 - 100): "); scanf("%d", &accountNum); fseek(fPtr, (accountNum - 1) * sizeof(struct clientData), SEEK_SET); fread(&client, sizeof(struct clientData), 1, fPtr); if (client.acctNum != 0) printf("Account #%d already contains information.\n", client.acctNum); else { printf("Enter lastname, firstname, balance\n? "); scanf("%s%s%f", &client.lastName, &client.firstName, &client.balance); client.acctNum = accountNum; fseek(fPtr, (client.acctNum - 1) * sizeof(struct clientData), SEEK_SET); fwrite(&client, sizeof(struct clientData), 1, fPtr); } } int enterChoice(void) { int menuChoice; printf("\nEnter your choice\n" "1 - store a formatted text file of acounts called\n" " \"accounts.txt\" for printing\n" "2 - update an account\n" "3 - add a new account\n" "4 - delete an account\n" "5 - end program\n? "); scanf("%d", &menuChoice); return menuChoice; } ================================EXAMPLE 123================================ /* Using variable-length argument lists */ #include <stdio.h> #include <stdarg.h> double average(int, ...); main() { double w = 37.5, x = 22.5, y = 1.7, z = 10.2; printf("%s%.1f\n%s%.1f\n%s%.1f\n%s%.1f\n\n", "w = ", w, "x = ", x, "y = ", y, "z = ", z); printf("%s%.3f\n%s%.3f\n%s%.3f\n", "The average of w and x is ", average(2, w, x), "The average of w, x, and y is ", average(3, w, x, y), "The average of w, x, y, and z is ", average(4, w, x, y, z)); return 0; } double average(int i, ...) { double total = 0; int j; va_list ap; va_start(ap, i); for (j = 1; j <= i; j++) total += va_arg(ap, double); va_end(ap); return total / i; } ================================EXAMPLE 124================================ /* Using command-line arguments */ #include <stdio.h> main(int argc, char *argv[]) { FILE *inFilePtr, *outFilePtr; int c; if (argc != 3) printf("Usage: copy infile outfile\n"); else if ((inFilePtr = fopen(argv[1], "r")) != NULL) if ((outFilePtr = fopen(argv[2], "w")) != NULL) while ((c = fgetc(inFilePtr)) != EOF) fputc(c, outFilePtr); else printf("File \"%s\" could not be opened\n", argv[2]); else printf("File \"%s\" could not be opened\n", argv[1]); return 0; } ================================EXAMPLE 125================================ /* Concatenating two files and printing to standard output */ #include <stdio.h> main(int argc, char* argv[]) { FILE *ifp1, *ifp2; int c; if (argc!=3) { printf("Usage: %s file1 file2\n", argv[0]); return 1; } ifp1 = fopen(argv[1],"r"); ifp2 = fopen(argv[2],"r"); if ( (ifp1==NULL) || (ifp2==NULL) ) { printf("Couldn't open file!\n"); return 1; } while ((c=fgetc(ifp1))!=EOF) putchar(c); while ((c=fgetc(ifp2))!=EOF) putchar(c); return 0; } ================================EXAMPLE 126================================ /* Using the exit and atexit functions */ #include <stdio.h> #include <stdlib.h> void print(void); main() { int answer; atexit(print); /* register function print */ printf("Enter 1 to terminate program with function exit\n" "Enter 2 to terminate program normally\n"); scanf("%d", &answer); if (answer == 1) { printf("\nTerminating program with function exit\n"); exit(EXIT_SUCCESS); } printf("\nTerminating program by reaching the end of main\n"); return 0; } void print(void) { printf("Executing function print at program termination\n" "Program terminated\n"); } ================================EXAMPLE 127================================ /* Using temporary files */ #include <stdio.h> main() { FILE *filePtr, *tempFilePtr; int c; char fileName[30]; printf("This program changes tabs to spaces.\n" "Enter a file to be modified: "); scanf("%s", fileName); if ( ( filePtr = fopen(fileName, "r+") ) != NULL) if ( ( tempFilePtr = tmpfile() ) != NULL) { printf("\nThe file before modification is:\n"); while ( ( c = getc(filePtr) ) != EOF) { putchar(c); putc(c == '\t' ? ' ': c, tempFilePtr); } rewind(tempFilePtr); rewind(filePtr); printf("\n\nThe file after modification is:\n"); while ( ( c = getc(tempFilePtr) ) != EOF) { putchar(c); putc(c, filePtr); } } else printf("Unable to open temporary file\n"); else printf("Unable to open %s\n", fileName); return 0; } ================================EXAMPLE 128================================ /* Using signal handling */ #include <stdio.h> #include <signal.h> #include <stdlib.h> #include <time.h> void signal_handler(int); main() { int i, x; signal(SIGINT, signal_handler); srand(clock()); for (i = 1; i <= 100; i++) { x = 1 + rand() % 50; if (x == 25) raise(SIGINT); printf("%4d", i); if (i % 10 == 0) printf("\n"); } return 0; } void signal_handler(int signalValue) { int response; printf("%s%d%s\n%s", "\nInterrupt signal (", signalValue, ") received.", "Do you wish to continue (1 = yes or 2 = no)? "); scanf("%d", &response); while (response != 1 && response != 2) { printf("(1 = yes or 2 = no)? "); scanf("%d", &response); } if (response == 1) signal(SIGINT, signal_handler); else exit(EXIT_SUCCESS); } ================================EXAMPLE 129================================ /* Using goto */ #include <stdio.h> main() { int count = 1; start: /* label */ if (count > 10) goto end; printf("%d ", count); ++count; goto start; end: /* label */ putchar('\n'); return 0; } /* Avoid using gotos as much as possible because 1. They can make the code unreadable. 2. They can make the code very hard to debug. 3. It has been proven that no program really needs gotos. */ =============================================================================