L-8 MCS 260 Fri 7 Sep 2001

Below are listings for programs we discussed in class.
/* L-8 MCS 260 Fri 7 Sep 2001 : finding minimum of two integers */

#include<stdio.h>

int main(void)
{
   int a,b;        /* two user given integers */
   int min;        /* will be the minimum of a and b */

   printf("Give two integers : ");
   scanf("%d %d", &a, &b);

   if (a <= b)
      min = a;
   else
      min = b;

   printf("  min(%d,%d) = %d\n", a, b, min);

   return 0;
}
In the second program we extend the program :
/* L-8 MCS 260 Fri 7 Sep 2001 : Finding minimum of two integers,
   with in addition the program prints out the position of the
   minimum, whether it occurred on first or second in the input.
   For example,
                  min(2,3) = 2, at position 1
                  min(3,2) = 3, at position 2 */

#include<stdio.h>

int main(void)
{
   int a,b;     /* two user given integers */
   int min;     /* will be the minimum of a and b */
   int pos;     /* pos == 1,2 means min == a,b respectively */

   printf("Give two integers : ");
   scanf("%d %d", &a, &b);

   if (a <= b)
   {
      min = a;
      pos = 1;
   }
   else
   {
      min = b;
      pos = 2;
   }

   printf("  min(%d,%d) = %d, at position %d\n", a, b, min, pos);

   return 0;
}
Next we see some nested if-else statements :
/* L-8 MCS 260 Fri 7 Sep 2001 : a hat function

    consider f(x) = 0 for x in [0,1[ union ]2,3]
                  = 1 for x in [1,2]
                  undefined elsewhere  */

#include<stdio.h>

int main(void)
{
   float x;

   printf("a hat function\n");
   printf("Give number : ");
   scanf("%f", &x);

   printf("\nImplementation using or : \n");
   if ((x < 0) || (x > 3))
      printf("  function undefined at %f\n", x);
   else
      if ((x < 1) || (x > 2))
         printf("  value at %f is zero\n", x);
      else
         printf("  value at %f is one\n", x);

   printf("\nImplementation using and : \n");
   if ((x >= 0) && (x <= 3))
      if ((x >= 1) && (x <= 2))
         printf("  value at %f is one\n", x);
      else
         printf("  value at %f is zero\n", x);
   else
      printf("  function undefined at %f\n", x);

   return 0;
}
Notice that the intendation in the program above is very important to verify the correctness.