Programme Structure --- a Second Programme

C programmes consist of a sequence of declarations of functions and variables --- this must include a function named main:
/* Programme to display the least of three integer values read from 
   the input. */

#include <stdio.h>

/* Function to compare two given integers and return the least, or the second
   if they are the same : */
int min(int a, int b) {

    if (a < b) return a;
    else return b;
  }

/* Main function --- prompts for and reads in three integers, calls min to
   determine the least and displays this : */
main(void) {

    int n1, n2, n3, least;

    printf("Enter three numbers each separated by a space:\n ");
    scanf("%d %d %d", &n1, &n2, &n3);

    least=min(n1,n2);  
    least=min(least,n3);

    printf("Least is %d\n",least);
  }

  1. int min declares the integer function min which returns an integer, or int, value.

  2. (int a, int b) are the formal parameters to min --- replaced by actual values when min is called. e.g., min(n1,n2) calls min with the current values of variables n1 and n2 which will be used in place of a and b respectively.

    The return passes the value back which replaces the call to min in the programme, and is therefore assigned to the variable least.

  3. scanf reads from the standard input stream and converts the character data to integers in the computer; conversion determined by the %d in the format control string of scanf; &n1 means the address of n1, the memory location assigned to n1.

  4. min is called twice with different actual parameters.

  5. The final printf displays the message and inserts the value of variable least converted to its printable format (by the %d) and outputs a newline (\n).

...previouscont's...



About this document:

Produced from the SGML: /home/isd/public_html/_course_crash_in_c/_reml_grp/introduction.reml
On: 3/3/2003 at 16:16:4
Options: reml2 -i noindex -l long -o html -p multiple