1. 程式人生 > >C學習示例

C學習示例

本文來自:http://www.cis.temple.edu/~ingargio/cis71/code/

Adding two integers

/* add2.c -- Add two numbers and print them out together 
             with their sum
             AUTHOR:
	     DATE:
 */

#include <stdio.h>

int main(void) {
  int first, second;

  printf("Enter two integers > ");
  scanf("%d %d", &first, &second);
  printf("The two numbers are: %d  %d\n", first, second);
  printf("Their sum is %d\n", first+second);
}

Adding n integers

/* addn.c -- Read a positive number N. Then read N integers and
 *           print them out together with their sum.
 */

#include <stdio.h>

int main(void) {
  int n;       /* The number of numbers to be read */
  int sum;     /* The sum of numbers already read  */
  int current; /* The number just read             */
  int lcv;     /* Loop control variable, it counts the number
                  of numbers already read */

  printf("Enter a positive number n > "); 
  scanf("%d",&n); /* We should check that n is really positive*/
  sum = 0;
  for (lcv=0; lcv < n; lcv++) {
    printf("\nEnter an integer > ");
    scanf("%d",&current);
    /*    printf("\nThe number was %d\n", current); */
    sum = sum + current;
  }
  printf("The sum is %d\n", sum);
  return 0;
}

Finding the value of a collection of coins

/* FILE: coins.c
 * DETERMINES THE VALUE OF A COIN COLLECTION
 * A Variation of the Hanly/Koffman book's example
 */

#include <stdio.h>

int main (void)
{
   // Local data ...
   int pennies;              // input: count of pennies
   int nickels;              // input: count of nickels
   int dimes;                // input: count of dimes
   int quarters;             // input: count of quarters
   int temp, left;           // temporaries for various
                             // computations 

   // Read in the count of quarters, dimes, nickels and pennies.
   printf("Enter the number of quarters, dimes, nickels, and pennies: ");
   scanf("%d %d %d %d", &quarters, &dimes, &nickels, &pennies);

   // Compute the total value in cents.
   left = 25 * quarters + 10 * dimes + 5 * nickels + pennies;

   // Find and display the value in dollars
   printf("Your collection is worth\n "); 
   temp = left / 100;
   printf("\t%d dollar", temp);
   if (temp==1) 
      printf(", ");
   else
      printf("s, ");
   left = left % 100;

   // Find and display the value left in quarters
   temp = left / 25;
   printf("%d quarter", temp);
   if (temp==1) 
      printf(", ");
   else
      printf("s, ");
   left = left % 25;

   // Find and display the value left in dimes
   temp = left / 10;
   printf("%d dime", temp);
   // Here, just for fun, instead of using a conditional statement, 
   // I use a conditional expression and string concatenation
   printf ((temp==1) ? ", " : "s, ");
   left = left % 10;

   // Find and display the value left in nickels
   temp = left / 5;
   printf("%d nickel", temp);
   if (temp==1) 
      printf(", and ");
   else
      printf("s, and ");
   left = left % 5;

   // Find and display the value left in pennies
   printf("%d penn", left);
   if (left==1) 
      printf("y\n");
   else
      printf("ies\n");
   return 0;
}

Computing the factorial of a number

/* factorial.c -- It computes repeatedly the factorial of an integer entered 
 *        by the user. It terminates when the integer entered is not
 *        positive.
 */

#include <stdio.h>

int fact(int n);

int main(void) {
  int current;

  printf("Enter a positive integer [to terminate enter non-positive] > ");
  scanf("%d", &current);
  while (current > 0) {
    printf("The factorial of %d is %d\n", current, fact(current)); 
    printf("Enter a positive integer [to terminate enter non-positive] > ");
    scanf("%d", &current);
  }
}

/* n is a positive integer. The function returns its factorial */
int fact(int n) {
  int lcv;    /* loop control variable */
  int p;      /* set to the product of the first lcv positive integers */

  for(p=1, lcv=2; lcv <= n; p=p*lcv, lcv++);
  return p;
}

Determining if a number is a prime

/* prime1.c  It prompts the user to enter an integer N. It prints out
 *           if it is a prime or not. If not, it prints out a factor of N.
 */

#include <stdio.h>

int main(void) {
  int n;
  int i;
  int flag;

  printf("Enter value of N > ");
  scanf("%d", &n);
  flag = 1;
  for (i=2; (i<(n/2)) && flag; ) { /* May be we do not need to test
			values of i greater than the square root of n? */
    if ((n % i) == 0) /* If true n is divisible by i */
      flag = 0;
    else
      i++;
  }
 
  if (flag)
    printf("%d is prime\n", n);
  else
    printf("%d has %d as a factor\n", n, i);
  return 0;
}

Finding all the proper factors of a number

/* factor1.c -- It prompts the user to enter an integer N. It prints out
 *        if it is a prime or not. If not, it prints out all of its
 *        proper factors.
 */

#include <stdio.h>

int main(void) {
  int n, 
    lcv, 
    flag; /* flag initially is 1 and becomes 0 if we determine that n
	     is not a prime */
 
  printf("Enter value of N > ");
  scanf("%d", &n);
  for (lcv=2, flag=1; lcv <= (n / 2); lcv++) {
    if ((n % lcv) == 0) {
      if (flag)
	printf("The non-trivial factors of %d are: \n", n);
      flag = 0;
      printf("\t%d\n", lcv);
    }
  }
  if (flag)
    printf("%d is prime\n", n);
}

What are in C the values of TRUE and FALSE?

/* true.c  -- What are in C the values of TRUE and FALSE? 
 */

 #include <stdio.h>

 int main(void) {
    printf("The value of 1<2 is %d\n", (1<2));
    printf("The value of 2<1 is %d\n", (2<1));
 }

 /* The program prints out

 The value of 1<2 is 1
 The value of 2<1 is 0

*/

Computing Fibonacci numbers

/* fibo.c -- It prints out the first N Fibonacci
 *           numbers.
 */

#include <stdio.h>

int main(void) {
    int n;        /* The number of fibonacci numbers we will print */
    int i;        /* The index of fibonacci number to be printed next */ 
    int current;  /* The value of the (i)th fibonacci number */
    int next;     /* The value of the (i+1)th fibonacci number */
    int twoaway;  /* The value of the (i+2)th fibonacci number */

    printf("How many Fibonacci numbers do you want to compute? ");
    scanf("%d", &n);
    if (n<=0)
       printf("The number should be positive.\n");
    else {
      printf("\n\n\tI \t Fibonacci(I) \n\t=====================\n");
      next = current = 1;
      for (i=1; i<=n; i++) {
	printf("\t%d \t   %d\n", i, current);
	twoaway = current+next;
	current = next;
	next    = twoaway;
      }
    }
}

/* The output from a run of this program was:

How many Fibonacci numbers do you want to compute? 9

	I 	 Fibonacci(I) 
	=====================
	1 	   1
	2 	   1
	3 	   2
	4 	   3
	5 	   5
	6 	   8
	7 	   13
	8 	   21
	9 	   34

*/

More simple functions

/* funcs.c  -- More examples of functions
 */

#include <stdio.h>

int getint(void); /*It prompts user to enter an integer, which it returns*/

int getmax(int a, int b, int c); /*It returns value of largest of a, b, c*/

/* Main program: Using the various functions */
int main (void) {
  int x, y, z;

  x = getint();
  y = getint();
  z = getint();
  printf("The largest of %d, %d, and %d is %d\n", x, y, z, getmax(x,y,z));
}

int getint(void) {
  int a;

  printf("Please enter an integer > ");
  scanf("%d", &a);
  return(a);
}

int getmax(int a, int b, int c){
  int m = a;

  if (m<b)
    m = b;
  if (m<c)
    m = c;
  return(m);
}

Simple example on scope rules

/* scope1.c -- Simple example showing effects of the scope rules
 */

#include <stdio.h>

int a=0;    /* This is a global variable */

void foo(void);

int main(void) {
  int a=2;  /* This is a variable local to main */
  int b=3;  /* This is a variable local to main */

  printf("1. main_b = %d\n", b);
  printf("main_a = %d\n", a);
  foo();
  printf("2. main_b = %d\n", b);
}

void foo(void){
  int b=4;  /* This is a variable local to foo */

  printf("foo_a = %d\n", a);
  printf("foo_b = %d\n", b);
}

Another example on scope rules

/* scope2.c -- Example on scope rules
 */

#include <stdio.h>
int x = 2;
int y = 3;
int z = 4;
void moo(int x, int *y){
  int z;
  x = x+3;
  *y = *y+3;
  z = z+3;  /*Here z is the local z. Notice that it has not been
              initialized. As you see from the output below
              in this case it was implicitly initialized to 0.
              In general that is not the case and the compiler 
	      should give you a warning
	      */
  printf("moo :  x = %1d, *y = %1d, y = %1d, z = %1d\n", x,*y,y,z);
}
int main(void){
  moo(x, &y);
  printf("main: x = %1d1, y = %1d, z = %1d\n", x,y,z);
}

/* The output is

moo :  x = 5, *y = 6, y = 1073742056, z = 3
main: x = 2, y = 6, z = 4

*/

 Operations on arrays

/* array.c  -- Operations on arrays
 */

#include <stdio.h>

int main(void) {
  int a[2] = {1,2};  /* The aggregates like {1,2} are literals for arrays */
  int b[2] = {2,3};
  int i;

  /* It is legal to use subscripts on arrays, both on the left and on 
   * the right hand side of assignments. */
  for(i=0;i<2;i++)
    a[i]=b[i];

  /* It is not legal to assign arrays, like in a=b; */

  /* The comparison of two distinct arrays with the same content
   * results in FALSE. So below we print "They are not equal"
   */
  if(a==b)
    printf("They are equal\n");
  else
    printf("They are not equal\n");

  /* The following comparison results in TRUE. */
  if(a==a)
    printf("Of course a is equal to a\n");
  else
    printf("No, a is not equal to a\n");
  /* The behavior of comparison is explained when we note that the
   * comparison is a comparison of addresses, not contents.
   */
  /* We cannot print out an array as a single unit. We have to print out
   * its elements one at a time.
   */
  for(i=0;i<2;i++)
    printf("a[%1d] = %3d\n", i, a[i]);
}

 Simple uses of arrays

/* array1.c -- Simple operations with arrays.
 */

#include <stdio.h>
#define N 10

void oneWay(void);
void anotherWay(void);

int main(void) {
  printf("\noneWay:\n");
  oneWay();
  printf("\nantherWay:\n");
  anotherWay();
}

/*Array initialized with aggregate */
void oneWay(void) {
  int vect[N] = {1,2,3,4,5,6,7,8,9,0};
  int i;
  
  for (i=0; i<N; i++)
    printf("i = %2d  vect[i] = %2d\n", i, vect[i]);
} 

/*Array initialized with loop */
void anotherWay(void) {
  int vect[N];
  int i;
  
  for (i=0; i<N; i++)
    vect[i] = i+1;

  for (i=0; i<N; i++)
    printf("i = %2d  vect[i] = %2d\n", i, vect[i]);
} 

Reading, writing, reversing an integer array

/* array2.c -- Read/writing/reversing integer arrays
 */

#include <stdio.h>

#define NMAX 10

void intSwap(int *x, int *y);
int getIntArray(int a[], int nmax, int sentinel);
void printIntArray(int a[], int n);
void reverseIntArray(int a[], int n);

int main(void) {
  int x[NMAX];
  int hmny;

  hmny = getIntArray(x, NMAX, 0);
  printf("The array was: \n");
  printIntArray(x,hmny);
  reverseIntArray(x,hmny);
  printf("after reverse it is:\n");
  printIntArray(x,hmny);
}

void intSwap(int *x, int *y)
     /* It swaps the content of x and y */
{
  int temp = *x;
  *x = *y;
  *y = temp;
}

void printIntArray(int a[], int n)
     /* n is the number of elements in the array a.
      * These values are printed out, five per line. */
{
  int i;

  for (i=0; i<n; ){
    printf("\t%d ", a[i++]);
    if (i%5==0)
      printf("\n");
  }
  printf("\n");
}

int getIntArray(int a[], int nmax, int sentinel)
     /* It reads up to nmax integers and stores then in a; sentinel 
      * terminates input. */
{
  int n = 0;
  int temp;

  do {
    printf("Enter integer [%d to terminate] : ", sentinel);
    scanf("%d", &temp);
    if (temp==sentinel) break;
    if (n==nmax)
      printf("array is full\n");
    else 
      a[n++] = temp;
  }while (1);
  return n;
}

void reverseIntArray(int a[], int n)
     /* It reverse the order of the first n elements of a */
{
  int i;

  for(i=0;i<n/2;i++){
    intSwap(&a[i],&a[n-i-1]);
  }
}

Various C features: __DATE__, sizeof, conditional expressions, ..

/* misc.c -- various C constructs */

#include <stdio.h>

int main(void) {
  int answer;
  short x = 1;
  long y = 2;
  float u = 3.0;
  double v = 4.4;
  long double w = 5.54;
  char c = 'p';;

  /* __DATE__, __TIME__, __FILE__, __LINE__ are predefined symbols */
  printf("Date : %s\n", __DATE__);
  printf("Time : %s\n", __TIME__);
  printf("File : %s\n", __FILE__);
  printf("Line : %d\n", __LINE__);
  printf("Enter 1 or 0 : ");
  scanf("%d", &answer);

  /* answer?"you said yes":"You said no" is a conditional expression */
  printf("%s\n", answer?"You sayd YES":"You said NO");

  /* The size of various types */
  printf("The size of int %d\n", sizeof(answer));
  printf("The size of short %d\n", sizeof(x));
  printf("The size of long %d\n", sizeof(y));
  printf("The size of float %d\n", sizeof(u));
  printf("The size of double %d\n", sizeof(v));
  printf("The size of long double %d\n", sizeof(w));
  printf("The size of char %d\n", sizeof(c));

}
/*
  The output from a run was:

Date : Aug  2 2018
Time : 14:23:16
File : 1.cpp
Line : 20
Enter 1 or 0 : 1
You sayd YES
The size of int 4
The size of short 2
The size of long 8
The size of float 4
The size of double 8
The size of long double 16
The size of char 1

 */

Addresses and values of variables

/* addresses.c -- Playing with addresses of variables and their contents:
 *                what is done by C with variables, addresses, and values.
 */

#include <stdio.h>

void moo(int a, int * b);

int main(void) {
  int x;
  int *y;

  x=1;
  y=&x;
  printf("Address of x = %d, value of x = %d\n", &x, x);
  printf("Address of y = %d, value of y = %d, value of *y = %d\n", &y, y, *y);
  moo(9,y);
}

void moo(int a, int *b){
  printf("Address of a = %d, value of a = %d\n", &a, a);
  printf("Address of b = %d, value of b = %d, value of *b = %d\n", &b, b, *b);
}

/* Output from running this program on my computer:

Address of x = 536869640, value of x = 1
Address of y = 536869632, value of y = 536869640, value of *y = 1
Address of a = 536869608, value of a = 9
Address of b = 536869600, value of b = 536869640, value of *b = 1

 */

Numeric value of printable characters

/* codes.c  -- It prints out the numerical codes of the printable ascii
 *             characters
 */

#include <stdio.h>

int main(void){
  int c;

  printf("\tCharacter  Code\n"
         "\t===============\n");
  for (c=32; c<127; c++)
    printf("\t  %c     %4d\n", c, c);
}

/* Here is the ouput from this program:

	Character  Code
	===============
	          32
	  !       33
	  "       34
	  #       35
	  $       36
	  %       37
	  &       38
	  '       39
	  (       40
	  )       41
	  *       42
	  +       43
	  ,       44
	  -       45
	  .       46
	  /       47
	  0       48
	  1       49
	  2       50
	  3       51
	  4       52
	  5       53
	  6       54
	  7       55
	  8       56
	  9       57
	  :       58
	  ;       59
	  <       60
	  =       61
	  >       62
	  ?       63
	  @       64
	  A       65
	  B       66
	  C       67
	  D       68
	  E       69
	  F       70
	  G       71
	  H       72
	  I       73
	  J       74
	  K       75
	  L       76
	  M       77
	  N       78
	  O       79
	  P       80
	  Q       81
	  R       82
	  S       83
	  T       84
	  U       85
	  V       86
	  W       87
	  X       88
	  Y       89
	  Z       90
	  [       91
	  \       92
	  ]       93
	  ^       94
	  _       95
	  `       96
	  a       97
	  b       98
	  c       99
	  d      100
	  e      101
	  f      102
	  g      103
	  h      104
	  i      105
	  j      106
	  k      107
	  l      108
	  m      109
	  n      110
	  o      111
	  p      112
	  q      113
	  r      114
	  s      115
	  t      116
	  u      117
	  v      118
	  w      119
	  x      120
	  y      121
	  z      122
	  {      123
	  |      124
	  }      125
	  ~      126

 */

A simple linear congruence random number generator

/* Generating random number sequences using the formula (linear congruence)
	x[k+1] = (a*x[k] + c)mod m
   where a, c, and m are parameters set by the user and passed as command line 
   parameters together with a seed i.e. x[0]
   As a simple example try  a=7, c=1, m=13, and seed=5
   A more sophisticated selection would be a=69069, c=0, 
   m=2^32=4294967296, and seed=31
   It will print out, in a sort of random order, up to m-1 distinct values. 
   Then it loops.
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

static long seed = 13;
static long a;
static long c;
static long m;

void random_init(long s) {
    if (s != 0) seed = s;
}

long random() {
	seed = (a*seed + c)%m;
	return seed;
    }

int main(int argc, char * argv[]) {
    if (argc != 5) {
	printf("usage: %s a, c, m, seed\n", argv[0]);
	return 1;
    }
    a = atoi(argv[1]);
    c = atoi(argv[2]);
    m = atoi(argv[3]);
    long s = atoi(argv[4]);
    random_init(s);
    int k;
    for (k = 0; k < m-1; k++) { 
	printf("%8ld", random());
	if (k % 8 == 7) { // after 8 elements go to a new line
	    printf("\n");
	    sleep(1); // sleep for a second
	} 
    }
    printf("\n");
    return 0;
}

 

 

本文來自:https://cis.temple.edu/~ingargio/cis71/code/