Chapter 2 Algorithms - the Soul of Programs
Example 2.1 Factorial of Five
#include <stdio.h> int main() { int i = 1, j; for ( j = 1; j < 6; j++ ) i = i * j; printf( "5!=%d\n", i ); }
The results are as follows:
Example 2.3 determines whether each year from 2000 to 2500 is a leap year and outputs the results.
#include <stdio.h> int main() { int i; for ( i = 2000; i <= 2500; i++ ) if ( i % 4 = 0 && i % 100 != 0 || i % 400 = 0 ) printf( "%d\t", i ); else continue; } //The results are as follows:
Example 2.4 Seek 1-1/2+1/3-1/4+'''+1/99-1/100
#include <stdio.h> int main() { int sign = 1; double deno = 2.0, sum = 1.0, term; while ( deno <= 100 ) { sign = -sign; term = sign / deno; sum += term; deno += 1; } printf( "The output is:%f\n", sum ); }
The results are as follows:
Exercise 1: Input 10 numbers in turn and output the maximum value
#include <stdio.h> int main() { int n = 1, max, a; printf( "Enter ten numbers:" ); while ( n <= 10 ) { scanf( "%d", &a ); if ( a > max ) max = a; n++; } printf( "max=%d\n", max ); }
The results are as follows:
Exercises 2 and 3 from small to large output
#include <stdio.h> int main() { int a, b, c, t; printf( "Input three numbers:" ); scanf( "%d%d%d", &a, &b, &c ); if ( a > b ) { t = a; a = b; b = t; } if ( a > c ) { t = a; a = c; c = t; } if ( b > c ) { t = b; b = c; c = t; } printf( "%d %d %d\n", a, b, c ); }
The results are as follows:
Exercise 3: 1 + 2 + 3 * 100
#include <stdio.h> int main() { int i, sum = 0; for ( i = 1; i <= 100; i++ ) sum = sum + i; printf( "The result is:%d\n", sum ); }
The results are as follows.
Exercise 4 after class to determine whether a number can be divided by three and five at the same time
#include <stdio.h> int main() { int i; printf( "Enter a number:" ); scanf( "%d", &i ); if ( i % 3 == 0 && i % 5 == 0 ) printf( "\n Can be divisible at the same time\n" ); else printf( "\n Not divisible at the same time\n" ); }
The results are as follows:
Exercise 5 will output prime numbers between 100 and 200
#include <stdio.h> int main() { int i,j; int count=0; for (i=101; i<=200; i++) { for (j=2; j<i; j++) { if (i%j==0) break; } if (j>=i) { count++; printf("%d ",i); if (count % 5 == 0) printf("\n"); } } }
The results are as follows:
Exercise 6 Finding the Maximum Common Number of Two Numbers m and n
#include <stdio.h> int main() { int m, n, t; printf( "Enter two numbers:" ); scanf( "%d%d", &m, &n ); if ( m < n ) { t = n; n = m; m = t; } t = m % n; while ( t != 0 ) { m = n; n = t; t = m % n; } printf( "Maximum common denominator%d\n", n ); }
The results are as follows: