next up previous
Next: About this document ...

Lecture 3: Statements and Flow of Control

C Statements


The If Statement

if (condition)
  statement1
else
  statement2

More Examples of If



if(x < 17)
  printf(``The if branch$\backslash$n'');
else {
  printf(``The more fascinating '');
  printf(``else branch$\backslash$n'');
}



if(x < 17)
  printf(``The if branch$\backslash$n'');
  printf(``Another statement$\backslash$n'');
else
  printf(``The more fascinating else branch$\backslash$n'');


Else if

Whiling Your Time Away

while (condition)
  statement



int main(void)
{
  int n, fact = 1;
 
  scanf(``%d'',&n);
  while(n > 0){
    fact = fact * n;
    n = n - 1;
  }
  printf(``fact = %d$\backslash$n'',fact);
  return 0;
}


For Loops


More For Loops

And More For Loops




Functions

# include <stdio.h>
 
$\backslash \! *$ print_witticism:
   Inputs: a witticism number(w_num)
   Side Effects: Prints witticism given by w_num
$* \! \backslash$
void print_witticism(int w_num)
{
  printf(``printing witticism %d$\backslash$n'', w_num);
  return;   $\backslash \! *$ returning void $* \! \backslash$
}
 
int main()
{
  int x = 17, y = 3;
 
  print_witticism(x);
  print_witticism(y);
  print_witticism(42);
 
  return 0;
}


Functions Cont'd ...


Casts Revisited

... And More Casts


The Switch Statement

switch (expression) {
  case const-expr: statements break;
  case const-expr: statements break;
  ...
  default: statements break;
}


An Example - The calculator



int main(void)
{
  float arg1, arg2, res;
  char op;
 
  while ((scanf(``%f %c %f'', &arg1, &op, &arg2)) == 3)
  {
    switch (op) {
    case '+':
      res = arg1 + arg2;
      break;
    case '-':
      res = arg1 - arg2;
      break;
    ...
    default:
      printf(``Unknown operator: %c$\backslash$n'', op);
      res = 0.0; $\backslash \! *$ default result $* \! \backslash$
      break;
    }
    printf(``%f$\backslash$n'',res);
  }
  printf(``Input error: program terminated!$\backslash$n'');
  return 1;
}


More on Switch



Watch Out!


More About the Break Statements


Summary



 
next up previous
Next: About this document ...

10/5/1997