Control Statements


if

Formally:
    if ( expression )
        statement-1
    [ else
        statement-2 ]
...for example...
    if ( colour == 'b' || colour == 'B')   /* double-equals */
        blue_things++;                     /* increment: b_t = b_t + 1 */
    else
        other_colours++;

Multi-branch version:
    if ( expression )
        statement
    else if ( expression )
        statement

        ...

    [ else
        statement  ]


switch

The C switch statement provides multi-way selection based on the value of an integer variable. Formally:
    switch ( expression ) {
        case const-expr : statements
        case const-expr : statements

        ...

        default: statements
      }


Example

    switch (c) {
        case '0': case '2': case '4': 
            printf("Value was even \n");
            break;                          /* note the break statement */
        case '1': case '3': case '5': 
            printf("Value was odd \n");
            break;
        default: printf("No idea \n");
      }


Example

#include <stdio.h>

main(){

    char c = 'a';

    switch (c) {
        case 'a' : 
	  printf("\n a");
	case 'b' : 
	  printf("\n b");
      }
    printf("\n");
  }
produces
   prompt> ./a.out

     a
     b
  prompt>


while

Formally:
    while ( expression )
        statement
The expression is evaluated and if it is true (non-zero), statement is executed and expression re-evaluated; the cycle completes when the value of the expression becomes zero (false).
    int number_left = 10;

    while (number_left) {
        printf("%d \n", number_left);
        number_left--;
      }


for

Formally:
    for  ( expr1 ; expr2 ; expr3 )
        statement

For example
    int i;

    for (i = 0; i < 3; i++)
        printf("The value of i is %d\n", i);

Equivalent to:
    expr1 ;

    while (expr2) {
        statement;
        expr3;
      }

Also,
    int i;

    for (i = 0; i < 3; i++) {
        printf("The value of i is: \n");
        printf("    %d\n", i);
      }


goto


...previousup (conts)next...



About this document:

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