Monday, April 1, 2013

The double_triple function: two results by reference


A function that takes in an integer number and "returns" both twice the number and three times the number.


/* Problem: Write a function that takes in an integer number and
"returns" both twice the number and three times the number. */

#include <stdio.h>

/* double_triple function begins */
int
double_triple (int x, int *d)
{
 int t;
 *d=2*x; /* double "returned" via pointer */
 t=3*x;
 return (t); /* triple returned the standard way */
}
/* double_triple function ends */



/* main program begins */
int
main(void)
{

 int a,twice,thrice;
 a=10;
 thrice = double_triple (a, &twice);
 printf("%d is two times %d.\n",twice,a);
 printf("%d is three times %d.\n",thrice,a);

 return(0);
}
/* main program ends */



Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
20 is two times 10.
30 is three times 10.
Philip R. Brown

Hawaii Lawyer - Honolulu Attorney

Proudly Serving Honolulu, Maui, Kauai and the Big Island

Mr. Brown is AV Rated. The AV Peer Review Rating "shows that a lawyer has reached the height of professional excellence. He or she has usually practiced law for many years, and is recognized for the highest levels of skill and integrity." 

Prime numbers (by reference)

Philip R. Brown

A function that determines if a number is prime or not. The function returs 1 if prime, 0 if not. In addition, the function will "return" the value of one of the divisors.


/* Problem: Write a function that determines if a number 
is prime or not. The function must return 1 if prime, 0 if not. 
In addition, the function must "return" the value of one 
of the divisors. */

#include <stdio.h>
#include <math.h>

/* function returns true if n is even.  */ 
/* it returns false if n is odd         */
int
even (int n)
{
 return (!(n%2));
}


/* function returns true if n is prime, 
the pointer variable references the divisor value */
int
prime2 (int n, int *divisor)
{ 
 int i, is_prime;
 
 /* looking for a divisor. if found, it 
  is not a prime number */
 *divisor = 0;

 /* eliminating even numbers except 2 */
 if (even (n))
 {
  if (n==2)
   *divisor=0;
  else
   *divisor=2;
 }
 else
 {
  if (n==1)
   *divisor=0; /* 1 is a prime number */
  else
   /* trying to divide number by 3,5,7,... */
   /* to find a divisor until sqrt(n)      */
   for (i=3; i<=sqrt(n); i=i+2)
   {
    if (!(n%i))
     *divisor=i;
   }
 }
 
 is_prime = *divisor;

 /* if there is a divisor then NOT prime */

 return (!is_prime);
}

int
main (void)
{
int x, div;

   printf ("Enter a positive integer number: ");
   scanf ("%d", &x);

   /*  testing for prime and printing the report */
   if (prime2 (x, &div))
      printf ("%d is a prime number.\n", x);
   else
      printf ("%d not prime number. Divisible by %d.\n", x, div);

return (0);
}

Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter a positive integer number: 77
77 not prime number. Divisible by 7.

The bigger2 function: using pointer arguments

This function returns nothing but will change the value of the variable in the calling function's memory area.

/* Problem: Write a void function that "returns" the largest
value of two real numbers. */

/* this function returns nothing but will
change the value of the variable in the calling
function's memory area */

void
bigger2 (double n1, double n2, double *result)
{

 if (n1>n2)
  *result = n1;
 else
  *result = n2;

/* *result in bigger2 uses the same 
memory cell as result in main */
}



int
main (void)
{
 double x, y, result;

 printf ("Enter a real number: ");
 scanf ("%lf", &x);

 printf ("Enter a real number: ");
 scanf ("%lf", &y);

 /* calling the function (3 arguments) */
 /* &result is the address where variable result is stored */
 bigger2 (x, y, &result);

 /* printing the report */
 printf ("The largest number is %f.\n", result); 

 return (0);
}

Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter a real number: 12.4
Enter a real number: 67.3
The largest number is 67.300000.

A function with two results

This program shows a function that generates two results. One result is returned, the other accessed from the main via an address


/* Problem: This program shows a function that generates two results. 
One result is returned (-), the other accessed from the main via an address (+). */



#include <stdio.h>
#include <math.h>

double
quadratic (int a, int b, int c, double* xplus)
{
 double xminus;

 xminus  = (-b - sqrt (b * b - 4 * a * c))/ (2 * a);
 *xplus  = (-b + sqrt (b * b - 4 * a * c))/ (2 * a);
 return (xminus);
}


int
main (void)
{
 int a = 10, b = 40, c = 30;
 double xplus, xminus;

 /* calling the function. the address of xplus is sent as an argument */
 xminus = quadratic (a, b, c, &xplus);
 
 printf ("Using +: %lf\n", xplus);
 printf ("Using -: %lf\n", xminus);

 return (0);
}

Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Using +: -1.000000
Using -: -3.000000

A list of prime numbers

A program displaying the list of all prime numbers between 1 and 1000. It uses the previous function

/* Problem: Write a program that prints out all the
prime numbers between 1 and 1000. */

#include <stdio.h>
#include <math.h>

/* function returns true if n is even.  */ 
/* it returns false if n is odd         */
int
even (int n)
{
 return (!(n%2));
}


/* function returns true if n is prime */
int
prime3 (int n)
{
 
 int divisor, i;
 /* looking for a divisor. if found, it 
  is not a prime number */

 divisor = 0;

 /* eliminating even numbers except 2 */
 if (even (n))
 {
  if (n==2)
   divisor=0;
  else
   divisor=1;
 }
 else
 {
  if (n==1)
   divisor=0; /* 1 is a prime number */
  else
   /* trying to divide number by 3,5,7,... */
   /* to find a divisor until sqrt(n)      */
   for (i=3; i<=sqrt(n); i=i+2)
   {
    if (!(n%i))
     divisor=i;
   }
 }

 /* if there is a divisor then NOT prime */
 return (!divisor);

}


/* This main program prints all prime numbers
between 1 and 1000 */

int
main (void)
{
 int x;

 for (x=1; x<=1000; ++x)
  if (prime3 (x))
   printf (" %d ", x);


 return (0);
}

Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
 1  2  3  5  7  11  13  17  19  23  29  31  37  41  43  47  53  59  
61  67  71  73  79  83  89  97  101  103  107  109  113  127  131  
137  139  149  151  157  163  167  173  179  181  191  193  197  
199  211  223  227  229  233  239  241  251  257  263  269  271  
277  281  283  293  307  311  313  317  331  337  347  349  353  
359  367  373  379  383  389  397  401  409  419  421  431  433  
439  443  449  457  461  463  467  479  487  491  499  503  509  
521  523  541  547  557  563  569  571  577  587  593  599  601  
607  613  617  619  631  641  643  647  653  659  661  673  677  
683  691  701  709  719  727  733  739  743  751  757  761  769  
773  787  797  809  811  821  823  827  829  839  853  857  859  
863  877  881  883  887  907  911  919  929  937  941  947  953  
967  971  977  983  991  997 

Prime numbers (by value)

A function that returns 1 if a number is prime and 0 otherwise.

/* Function finding prime numbers (no pointers) */
#include <stdio.h> #include <math.h> /* function returns true if n is even. */ /* it returns false if n is odd */ int even (int n) { return (n%2==0); } /* function returns true if n is prime */ int prime (int n) { int divisor, i; /* looking for a divisor. if found, it is not a prime number */ divisor = 0; /* eliminating even numbers except 2 */ if (even (n)) { if (n == 2) divisor = 0; else divisor = 2; } else { if (n == 1) divisor = 0; /* 1 is a prime number */ else /* trying to divide number by 3,5,7,... */ /* to find a divisor until we reach n-1 */ for (i = 3; i < n; i = i + 2) { if (n % i == 0) divisor = i; } } /* if there is a divisor (not zero) then NOT prime */ return (!divisor); } int main (void) { int x; printf ("Enter a positive integer number: "); scanf ("%d", &x); /* testing for prime and printing the report */ if (prime (x)) printf ("%d is a prime number.\n", x); else printf ("%d is not a prime number.\n", x); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter a positive integer number: 59
59 is a prime number.

The bigger function: two arguments, one result

A function that takes in two numbers and returns the largest value of the two.

/* The bigger function: two arguments, one result */
#include <stdio.h> /* a function taking two double numbers and returning the larger number of the two */ /* this function will return a double */ double bigger (double n1, double n2) { double big; if (n1>n2) big = n1; else big = n2; return (big); } int main (void) { double x, y, result; printf ("Enter a real number: "); scanf ("%lf", &x); printf ("Enter a real number: "); scanf ("%lf", &y); /* calling the function (2 arguments) */ result = bigger (x,y); /* printing the report */ printf ("The bigger number is %lf.\n", result); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter a real number: 12.4
Enter a real number: 67.3
The bigger number is 67.300000.

The factorial function: one argument, one result

A function that computes the factorial of an integer number.

/* The factorial function: one argument, one result */
#include <stdio.h> /* this function will return an integer */ int factorial (int n) { int i, product; product = 1; /* initialization */ /* computes n*n-1... */ for (i=n; i>1; i=i-1) { product = product * i; } /* the value that goes out */ return (product); } int main (void) { int a, result; printf ("Enter an integer number: "); scanf ("%d", &a); /* calling the function */ result = factorial (a); /* printing the report */ printf ("The factorial of %d is %d.\n", a, result); return (0); } /* NOTE: a large number will produce an arithmetic overflow */
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter an integer number: 13
The factorial of 13 is 1932053504.

The stars2 function using a prototype

The same function as before but with a prototype declared at the top of the program.

/* A function with a prototype */
/* You can put only the prototype (header) on top */ /* and define the function at the bottom */ #include <stdio.h> /* the function prototype */ void stars2 (int n); /* the main program */ int main (void) { int a; a=10; /* the argument may be a constant, a variable or an expression */ stars2 (20); stars2 (a); stars2 (a+2); return (0); } /* the function definition */ void stars2 (int n) { int i; /* a loop displaying a star at each iteration */ for (i=1; i<=n; ++i) { printf ("*"); } /* change line after each series */ printf ("\n"); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
********************
**********
************

The stars2 function: a void function with one argument

A function that displays a line of stars of variable length depending on a numerical value.


/* A void function with one argument */
#include <stdio.h> /* a void function returns nothing */ void stars2 (int n) { int i; /* a loop displaying a star at each iteration */ for (i=1; i<=n; ++i) { printf ("*"); } /* change line after each series */ printf ("\n"); } int main (void) { int a; a=10; /* the argument may be a constant, a variable or an expression */ stars2 (20); stars2 (a); stars2 (a+2); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
********************
**********
************

The stars function: a void function without argument

A function that displays a line of stars on the screen.

/* A user-defined function without argument nor result */
#include <stdio.h> /* the function definition */ void stars (void) { printf ("********************************\n"); } /* end of function definition */ /* main program */ int main (void) { printf ("The line of stars comes from a function.\n"); /* calling the function */ stars (); /* the function can be called as will*/ printf ("\n"); stars (); printf ("Hello world!\n"); stars (); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
The line of stars comes from a function.
********************************

********************************
Hello world!
********************************

Input validation loop (do-while)

A program that shows the best use of a do-while loop, an input validation loop. This particular program validates that the color entered is a valid traffic light color.

/* Input validation loop (do-while) */
#include <stdio.h> int main (void) { char colour; /* ask user for colour */ do { printf ("Enter the colour of the light (R,G,Y,A): "); scanf (" %c", &colour); /* very important to leave space before %c here */ }while (colour!='R' && colour!='r' && colour!='G' && colour!='g' && colour!='Y' && colour!='y' && colour!='A' && colour!='a'); /* test the alternatives */ switch (colour) { /* red light */ case 'R': case 'r': printf ("STOP! \n"); break; /* yellow or amber light */ case 'Y': case 'y': case 'A': case 'a': printf ("CAUTION! \n"); break; /* green light */ case 'G': case 'g': printf ("GO! \n"); break; /* no default case necessary here */ } return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter the colour of the light (R,G,Y,A): b
Enter the colour of the light (R,G,Y,A): x
Enter the colour of the light (R,G,Y,A): G
GO!

Birdwatching program (fixed loop & file input)

This program reads a file that contains 12 lines of bird sightings and adds up all the sightings for a year.

/* Birdwatching program (fixed loop / file input) */
#include <stdio.h> int main (void) { FILE *birdfile; int birds, days, total, i, j; birdfile = fopen ("birds.txt", "r"); total = 0; /* loop goes though all 12 months */ for (i=1; i<=12; ++i) { /* reading the number of days of sightings */ fscanf (birdfile, "%d", &days); /* loop varies with number of days of sightings */ for (j=1; j<=days; ++j) { /* reading the number of birds */ fscanf (birdfile, "%d", &birds); total = total + birds; } } fclose (birdfile); printf ("Total number of birds sighted: %d\n", total); return(0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Total number of birds sighted: 219

birds.txt file contains:
3 4 6 7
3 1 1 1
1 1
0
7 1 5 9 11 5 4 1
2 9 1
1 3
8 2 4 6 9 12 23 4 12
6 4 6 3 9 4 11
3 2 3 7
1 9
2 9 10

Sums and averages

A program that counts, sums and calculates the average of all the numbers in a file of integers.

/* sums and averages */ /* this program calculates the average of all the numbers in a file of integers */
#include <stdio.h> int main (void) { int number, sum, count; double average; FILE *in; in = fopen ("numbers.data", "r"); /* sums and counts must always be initialized to zero */ sum = 0; count = 0; /* read number by number until the end of file */ while (fscanf (in, "%d", &number) != EOF) { /* count and sum the numbers */ sum = sum + number; count = count + 1; } fclose (in); /* final report */ printf ("There are %d numbers in the file.\n", count); printf ("The sum of all the numbers is %d.\n", sum); average = (double)sum / count; printf ("There average of all the numbers is %5.2lf.\n", average); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
numbers.data: 11 18 5 101 6 78 47 3
There are 8 numbers in the file. The sum of all the numbers is 269. There average of all the numbers is 33.63.

Simple countdown using a for loop

A program that displays all the numbers between 60 and 0 and then prints the word LIFTOFF afterwards.

/* Simple countdown using a for loop */
#include <stdio.h> int main (void) { int time; /* the loop */ for (time=60; time>=0; time=time-1) { printf ("%d ", time); } printf ("\n\nLIFTOFF!\n\n"); return(0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
60  59  58  57  56  55  54  53  52  51  50  49  48  47  46  
45  44  43  42  41  40  39  38  37  36  35  34  33  32  31  
30  29  28  27  26  25  24  23  22  21  20  19  18  17  16  
15  14  13  12  11  10  9  8  7  6  5  4  3  2  1  0



LIFTOFF!

The fuel tank program

A program that monitors the amount of fuel in a tank and gives a warning if the supply falls below 10% of the tank's capacity.

/* The fuel tank program */
#include <stdio.h> int main (void) { double capacity, supply, pumped; /* in liters */ /* initialize capacity of tank */ capacity = 5000.0; /* ask user for initial supply already in tank */ printf ("Enter the the initial supply: "); scanf ("%lf", &supply); /* the program loops until supply falls below 10% */ while (supply > capacity * 0.10) { /* ask user for quantity removed or delivered */ printf ("\nEnter the amount delivered(+)/removed(-): "); scanf ("%lf", &pumped); supply = supply + pumped; /* test so that you don't pump more when tank is empty */ if (supply < 0.0) supply = 0.0; /* test so that you don't fill more when tank is full */ if (supply > capacity) supply = capacity; } printf ("\nSupply below 10%% (%.2lf l remaining)\n", supply); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter the the initial supply: 2000

Enter the amount delivered(+)/removed(-): -900

Enter the amount delivered(+)/removed(-): 1100

Enter the amount delivered(+)/removed(-): -1400

Enter the amount delivered(+)/removed(-): -200

Enter the amount delivered(+)/removed(-): -250

Supply below 10% (350.00 l remaining)

Mission to the Moon

This program computes the length of a mission to take photographs around the Moon given the time it takes to get there and to go around the Moon once


/* Mission to the Moon */
#include <stdio.h> int main (void) { double transit, period, time; int n_orbits, orbit; /* 73 hours from Earth to Moon */ transit = 72; /* 1.5 hours per orbit around Moon */ period = 1.5; /* mission begins */ printf ("Mission to the Moon - Times in hours\n"); printf ("====================================\n"); time = 0.0; n_orbits = 10; /* mission is 10 orbits */ printf ("Time - %4.1lf - Mission begins\n", time); /* we are at the moon */ time = time + transit; printf ("Time = %4.1lf - At the moon\n", time); orbit = 1; /* doing the orbits around the Moon */ while (orbit <= n_orbits) { time = time + period; printf ("Time = %4.1lf - %2d orbits completed\n", time, orbit); orbit = orbit + 1; } /* back to Earth */ time = time + transit; printf ("Time = %5.1lf - Mission complete.\n", time); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Mission to the Moon - Times in hours
====================================
Time -  0.0 - Mission begins
Time = 72.0 - At the moon
Time = 73.5 -  1 orbits completed
Time = 75.0 -  2 orbits completed
Time = 76.5 -  3 orbits completed
Time = 78.0 -  4 orbits completed
Time = 79.5 -  5 orbits completed
Time = 81.0 -  6 orbits completed
Time = 82.5 -  7 orbits completed
Time = 84.0 -  8 orbits completed
Time = 85.5 -  9 orbits completed
Time = 87.0 - 10 orbits completed
Time = 159.0 - Mission complete.

A simple count from 1 to 100

A program that displays the numbers between 1 and 100.

/* A simple count from 1 to 100 */
#include <stdio.h> int main (void) { int n; n = 1; /* loop initialization */ /* the loop */ while (n <= 100) /* loop condition */ { printf ("%d ", n); /* loop body */ n = n + 1; /* loop update */ } return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 
92 93 94 95 96 97 98 99 100

Even vs. odd

A program that determines if an integer number is odd or even.


/* Even vs. Odd */
#include <stdio.h> int main (void) { int number, even; /* ask user for number */ printf ("Enter an integer number: "); scanf ("%d", &number); /* determine if number is even and put in variable */ even = (number % 2 == 0); /* display report */ if (even) printf ("%d is an even number.\n", number); else printf ("%d is an odd number. \n", number); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter an integer number: 56
56 is an even number.

The traffic light program (switch)

A program that displays the recommended actions depending on the color of a traffic light. Unlike the previous program, this implementation uses the switch statement.

/* The traffic light program (switch) */
#include <stdio.h> int main (void) { char colour; /* ask user for colour */ printf ("Enter the colour of the light (R,G,Y,A): "); scanf ("%c", &colour); /* test the alternatives */ switch (colour) { /* red light */ case 'R': case 'r': printf ("STOP! \n"); break; /* yellow or amber light */ case 'Y': case 'y': case 'A': case 'a': printf ("CAUTION! \n"); break; /* green light */ case 'G': case 'g': printf ("GO! \n"); break; /* other colour */ default: printf ("The colour is not valid.\n"); } return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter the colour of the light (R,G,Y,A): G
GO!

The traffic light program (nested ifs)

A program that displays the recommended actions depending on the color of a traffic light. This program uses nested if statements.

/* The traffic light program (nested ifs) */
#include <stdio.h> int main (void) { char colour; /* ask user for colour */ printf ("Enter the colour of the light (R, G or Y): "); scanf ("%c", &colour); /* test if colour is red */ if (colour == 'r' || colour == 'R') printf ("STOP! \n"); else if (colour == 'y' || colour == 'Y') /* yellow colour test */ printf ("CAUTION! \n"); else if (colour == 'g' || colour == 'G') /* green colour test */ printf ("GO! \n"); else /* if not Y or G or R then invalid colour */ printf ("INVALID COLOUR! \n"); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter the colour of the light (R, G or Y): G
GO!

A simple if statement



/* A simple if statement */
#include <stdio.h> int main (void) { int temp; printf ("What is the current temperature? "); scanf ("%d", &temp); printf ("------------------------------------\n"); /* this if statement contains a true and a false branch */ /* with a compound statement in each branch*/ if (temp >= 20) { printf ("The temperature is %d degrees. \n", temp); printf ("It is quite warm. \n"); } else { printf ("The temperature is %d degrees. \n", temp); printf ("It is quite cool. \n"); } return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
What is the current temperature? 13
------------------------------------
The temperature is 13 degrees.
It is quite cool.

Playing with pointers

Just a silly program playing with pointers

/* Problem: This is just a silly program playing with pointers */

#include <stdio.h>

int
main (void)
{
   /* a and e are integers */
   int a, e;  

   /* b is a pointer to an integer */
   int* b; 

   /* c is a pointer to a pointer to an integer */   
   int** c;

   /* d is a pointer to a pointer to a pointer to an integer */
   int*** d;     
 
   a = 25;   /* a contains the integer 25 */
   b = &a;   /* b contains the address of a */
   c = &b;   /* c contains the address of b */
   d = &c;   /* d contains the address of c */

   /* Do you understand that ***d is actually a? */
   e = ***d * 2;   
 
   printf ("%d", e);
 
   return (0);
}
 


Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
50

Understanding pointers

This program just demonstrates how to assign values to pointer variables. It serves no other purpose.


/* Problem: This program just demonstrates how to assign values 
to pointer variables. It serves no other purpose. */

#include <stdio.h>

int
main (void)
{
 /* c and d are pointers to integers */
 int a, b, *c, *d, e;

 a = 10;
 b = a * 3;
 c = &a; /* address of a goes into c */
 d = &b; /* address of b goes into d */
 e = *c + *d; /* *c is a and *d is b */
 *d = a;
 d = &a;
 *c = *d - a % b + *c;

 printf ("Do you understand why\n");
 printf ("a= %d, b= %d, e= %d ?\n", a, b, e);

 return (0);
}

Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Do you understand why
a= 20, b= 10, e= 40 ?

Generating random numbers

A program showing the generation of random numbers with proper initialization using the system clock.

/* The random [rand()] function */
#include <stdio.h> #include <time.h> #include <stdlib.h> int main (void) { /* initialize random generator */ srand (time(NULL)); /* generate random numbers */ printf("RAND_MAX = %d\n", RAND_MAX); printf ("A number between 0 and RAND_MAX : %d\n", rand()); printf ("A number between 0 and 99: %d\n", rand() % 100); printf ("A number between 0 and 9: %d\n", rand() % 10); printf ("A number between 1 and 6: %d\n", (rand() % 6) + 1); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
RAND_MAX = 32767
A number between 0 and RAND_MAX : 10746
A number between 0 and 99: 43
A number between 0 and 9: 8
A number between 1 and 6: 2

Increment and decrement

A program showing the different uses of the increment and decrement operators.


/* Increment (++) and decrement (--) */
#include <stdio.h> int main (void) { int a, b; a = 5; /* increment (++) */ /* a is incremented by 1 */ ++a; printf ("After ++a, a is now %d\n", a); /* a is once more incremented by 1 */ a++; printf ("After a++, a is now %d\n", a); /* a is incremented but b gets the current a */ b = a++; printf ("After b=a++, a is now %d and b is %d\n", a, b); /* a is incremented and b gets the incremented a */ b = ++a; printf ("After b=++a, a is now %d and b is %d\n", a, b); /* decrement (--) */ /* a is decremented by 1 */ --a; printf ("After --a, a is now %d\n", a); /* a is once more decremented by 1 */ a--; printf ("After a--, a is now %d\n", a); /* a is decremented but b gets the current a */ b = a--; printf ("After b=a--, a is now %d and b is %d\n", a, b); /* a is decremented and b gets the decremented a */ b = --a; printf ("After b=++a, a is now %d and b is %d\n", a, b); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
After ++a, a is now 6
After a++, a is now 7
After b=a++, a is now 8 and b is 7
After b=++a, a is now 9 and b is 9
After --a, a is now 8
After a--, a is now 7
After b=a--, a is now 6 and b is 7
After b=++a, a is now 5 and b is 5

The (-) unary operator

A program showing simple uses of the unary minus operator.

/* The (-)unary operator */
#include <stdio.h> int main (void) { int a, b, c; a = 10; b = 20; /* b is 20 so -b is -20 */ b = -b + a; /* with multiple similar unary operators, use parentheses */ /* do you understand why c is 30? */ c = -b - (-a) + -b; printf ("The value of b is %d ", b); printf ("and the value of c is %d\n", c); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
The value of b is -10 and the value of c is 30

getchar() and putchar()

A simple program that reads one character from the keyboard and prints it out on the screen.

/* getchar() and putchar() */
#include <stdio.h> int main (void) { char c; printf ("Enter a character: "); /* getchar() gets a single character from the keyboard */ c = getchar(); printf ("The character is: "); /* putchar() prints a single character on the screen */ putchar (c); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter a character: @
The character is: @

Math functions

A program showing the results of a few of the most popular functions of the math library

/* Functions from the math library */
#include <stdio.h> #include <math.h> #define PI 3.1416 int main (void) { double before, after, x, y, z; /* the ceil function */ before = -217.5; after = ceil (before); printf ("The ceiling of %3.1lf is %3.1lf\n", before, after); /* the floor function */ before = -217.5; after = floor (before); printf ("The floor of %3.1lf is %3.1lf\n", before, after); /* the log function */ before = 200.0; after = log (before); printf ("The ln of %3.1lf is %3.1lf\n", before, after); /* the log10 function*/ before = 200.0; after = log10 (before); printf ("The log of %3.1lf is %3.1lf\n", before, after); /* the sqrt function*/ before = 200.0; after = sqrt (before); printf ("The square root of %3.1lf is %3.1lf\n", before, after); /* the fabs function (for doubles)*/ before = -413.56; after = fabs (before); printf ("The absolute value of %3.1lf is %3.1lf\n", before, after); /* the sin function */ before = 45.0; after = sin (before * PI / 180); printf ("The sine of %3.1lf is %5.3lf\n", before, after); /* the cos function */ before = 45.0; after = cos (before * PI / 180); printf ("The cosine of %3.1lf is %5.3lf\n", before, after); /* the tan function */ before = 45.0; after = tan (before * PI / 180); printf ("The tangent of %3.1lf is %5.3lf\n", before, after); /* the exp function */ before = 10.0; after = exp (before); printf ("e to the power of %3.1lf is %5.3lf\n", before, after); /* the pow function */ x = 9.0; y = 3.0; z = pow (x, y); printf ("%3.1lf to the power of %3.1lf is %3.1lf\n", x, y, z); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
The ceiling of -217.5 is -217.0
The floor of -217.5 is -218.0
The ln of 200.0 is 5.3
The log of 200.0 is 2.3
The square root of 200.0 is 14.1
The absolute value of -413.6 is 413.6
The sine of 45.0 is 0.707
The cosine of 45.0 is 0.707
The tangent of 45.0 is 1.000
e to the power of 10.0 is 22026.466
9.0 to the power of 3.0 is 729.0

Integer division and explicit conversions

A program showing a few examples of the casting operator.


/* Integer division */
#include <stdio.h> int main (void) { int a, b, c; double x, y, z, w; a = 10; b = 20; /* dividing two integers */ z = a / b; c = a / b; printf ("The value of z is %5.3lf ", z); printf ("and the value of c is %d\n", c); /* converting (casting) one operand before the division*/ x = (double)a / b; printf ("The value of x is %5.3lf\n", x); /* casting the quotient after the division*/ y = (double) (a / b); printf ("The value of y is %5.3lf\n", y); /* casting both operands before the division*/ w = (double)a / (double)b; printf ("The value of w is %5.3lf\n", w); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
The value of z is 0.000 and the value of c is 0
The value of x is 0.500
The value of y is 0.000
The value of w is 0.500

Remainder operator (%)

A program showing a few examples of results with the remainder (modulus) operator.


/* The remainder (%) operator */
#include <stdio.h> int main (void) { int a, b, c, d; /* a few operations */ a = 10 % 3; b = -10 % 3; c = 10 % -3; d = -10 % -3; /* you need to double the % to display on screen */ printf ("10 %% 3 is %d\n", a); printf ("-10 %% 3 is %d\n", b); printf ("10 %% -3 is %d\n", c); printf ("-10 %% -3 is %d\n", d); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
10 % 3 is 1
-10 % 3 is -1
10 % -3 is 1
-10 % -3 is -1

Maximum values

A program that displays the maximum values allowed in int and double variables on a particular system.


/* Maximum Values */
#include <stdio.h> #include <limits.h> #include <float.h> int main (void) { printf ("The largest integer is: %d\n", INT_MAX); printf ("The largest double is: %e\n", DBL_MAX); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
The largest integer is: 2147483647
The largest double is: 1.797693e+308

Input and output files

A program that reads 3 numbers from one file, 2 more numbers from another file, sums them all up and display the sum on the screen and places the sum in a new file.

/* Working with multiple files */ /* (This program contains a few syntax errors. Try to correct them) */
#include <stdio.h> #define PI 3.1416 int main (void) { int a, b, c, d, e, total; FILE *f1, *f2, *f3; /* opening input files */ f1 = fopen ("file1.dat", "r"); f2 = fopen ("file2.dat", "r"); /* reading data */ fscanf (f1, "%d%d%d", &a, &b, &c); fscanf (f2, "%d%d%, &d, &e); /* adding the numbers */ total = a + b + c + d + e; /* closing input files */ fclose (f1); fclose (f2); /* opening output file */ f3 = fopen ("total.dat", "w"); /* output report on both screen and file */ printf ("Read from first file: %d %d %d\n", a, b, c); printf ("Read from second file: %d %d\n", d, e); printf ("The sum is: %d\n\n", total); fprintf ("f3, "%d", total); printf ("\nFILE total.dat CREATED.\n"); /* check your directory for the new file! */ /* closing output file */ fclose (f3); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Read from first file: 34 78 122
Read from second file: 45 90
The sum is : 369

FILE total.dat CREATED.

The assignment operator (=)

A program that makes a few changes in variable values using the assignment operator

/* The = operator puts the value on the right */ /* into the variable on the left */
#include <stdio.h> int main (void) { /* declarations */ int a, b, c, d, e; /* fill variable a */ a = 10; /* modify variable a few times*/ a = 20; a = 10 + a; a = a + a + 2; a = 2 + a; /* a few more assignments */ b = a; c = b = 5; c = 10 + a; d = a + a + 2; e = 20 + a; a = a - b + c; /* the final values are... */ printf ("a:%4d\n b:%4d\n c:%4d\n d:%4d\n e:%4d\n", a, b, c, d, e); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
a: 133
b:   5
c:  74
d: 130
e:  84

The circle program (from a text file)

A program that reads from a file the diameter of a circle and prints out its circumference and area.


/* The "circle" program (using files) */

#include <stdio.h>
#define PI 3.1416

int
main (void)
{
     double diam, area, circ, r;
     FILE *in, *out;

     /* opening files */
     in = fopen ("diameter.data", "r");
     out = fopen ("report_circle.txt", "w");
 
     /* get diameter from file */
     printf ("Reading data from file...    ");
     fscanf (in, "%lf", &diam);
     printf ("Value read: %lf\n\n", diam);
        
     /* do the computations */
     r = diam / 2;
     area = PI * r * r;
     circ = 2 * PI * r;
 
     /* send results to report file */
     fprintf (out, "%4.2lf %4.2lf\n", area, circ);
     printf ("Sending results to file report_circle.txt...\n\n");

     /* closing files */
     fclose (in);
     fclose (out);
     printf ("Program completed.");
 
     return (0);
}

Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Reading data from file...    Value read: 10.400000

Sending results to file report_circle.txt...

Program completed.

The circle program (from keyboard)

A program that ases the user for the diameter of a circle and prints out its circumference and area.

#include <stdio.h>
#define PI 3.1416

int
main (void)
{
     /* declarations */
     double diam, area, circ, r;
 
     /* get diameter from user */
     printf ("Enter a value for the diameter: ");
     scanf ("%lf", &diam);
        
     /* do the computations */
     r = diam / 2;
     area = PI * r * r;
     circ = 2 * PI * r;
 
     /* display the report on the screen */
     printf ("\nA circle with a diameter of %3.1lf cm, ", diam);
     printf ("has an area of %5.3lf cm2\n", area);
     printf ("and a circumference of %4.2lf cm.\n", circ);
 
     return (0);
}

Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter a value for the diameter: 10

A circle with a diameter of 10.0 cm, has an area of 78.540 cm2
and a circumference of 31.42 cm.