Lab Activity 7

Objectives

In this lab, you will:

·         Get familiar with C operations %, +, -, *, / on values of integer

·         Get familiar with if-else and switch statement

·         Get familiar with printf and scanf IO functions

·         Write a simple time conversion program


Part 1: Prelab


You should use the material found in Lecture 10,11 and 12 of the course notes and/or the course C book Chapters 1,2 ,3.1 -3.5,7.1-7.3. As with all prelabs/labs, if you are not sure of the answer you may go to any EWS lab on campus and check your results by using the gcc compiler, or you can ask anyone of the CS101 staff for help. However, if you obtain some or all of your answers by writing the results produced by the compiler, please make sure to understand the results. If something is puzzling, be sure to ask for help.

The following exercises should help prepare you for the in-lab activities and MP2.
You will use the C operations % ,+ , * , / on values of datatype int, use the printf and scanf functions and along with the if-else and switch statements.

Complete Part 1 before you start working on the Part 2. Of course you can check your answers by opening gedit (or xemacs) and copying and pasting each program into a separate file and then compiling and running each program as you have learned in lab 6.

Part A: Operations on integer values

1.      Write the results you would see on your terminal screen if the following C code were inserted in a complete C program , compiled (without errors) and executed. See lecture 11, slides 16, 17, and 22.

The following program demonstrates the use of the "printf" and "scanf" functions in C.

Note that all variables in a program must be "declared" . A declaration statement is of the form:
data-type VariableName ;

The data-type int means that the variable only holds integers, -1, 12, 0 but not 3.14 .
The data-types float and double hold real numbers (including integers). The only difference between float and double is how many digits they can hold. In Matlab all real numbers were held in data-type double variables.

Comments in C are of the form /* blah blah blah */ . Comments in your C program are ignored by the compiler (gcc). The comments below do NOT need to be typed if you are typing the code manually.

We use the conversion specifiers %i (integer) , %d (integer), %f (float) and %lf (double) in the printf and scanf functions below to control where the numbers are printed on the computer screen.

   #include <stdio.h>   

   void main(void)
  {

int j = 5;

int k = 15;

int hours;

int mins;

int secs;

float x = 1.23456789; /* float type data holds about 6-7 digits */

double y = 1.234567891234; /* double type data holds about 14 digits */

/* integer variables and operations */

printf( " Placement %i \n", j / k ); /* a) Answer: _____________________________ (computations involving only integers return integer values) */

printf( "%i Placement \n", k / j ); /* b) Answer: _____________________________ (notice that the %i controls where the integer appears on the computer screen */

printf( "%i \n", j % k ); /* c) Answer: _____________________________ ( % means "remainder" just like doing 5th grade math) */

/* %f shows as default 6 digits to the right of the decimal point. %.2f will show 2 digits to the right of the decimal. */

printf( "x = %f \n", x ); /* d) Answer: ______________________________ */

printf( " Your cost = $%.4f \n", x ); /* e) Answer: ______________________________ */

printf( " Forgetting the change = $%.0f\n", x ); /* f) Answer: ______________________________ */

/* double data-type variables holds more digits than float variables. */

printf( "x = %.8f \n", x ); /* g) Answer: ______________________________ */

printf( "y = %.10lf \n", y ); /* h) Answer: ______________________________ */

/* common errors */

printf(" Enter 9.8765 :");

scanf( "%lf", &x ); /* Oops, x is of float data-type so we should have used %f rather than %f. */

printf("x = %f \n",x); /* i) Answer: ______________________________ */

printf(" Enter 3.45 : ");

scanf( " Hello World! %lf", &y ); /* For scanf, text inside " " doesn't display on screen and causes problems. */

printf(" y = %lf \n", y); /* j) Answer: ______________________________ */

/* print time in format hh:mm:ss , for example 11:09:08 */

hours = 6;

mins = 5;

secs = 1;

printf(" %i:%i:%i \n", hours, mins, secs); /* k) Answer: ______________________________ */

printf(" %02i:%02i:%02i \n", hours, mins, secs); /* l) Answer: ______________________________ */

  }

Part B: If, nested if and switch statements

2. The following program compiles and runs without errors. Write the ouput the following code produces.

    #include <stdio.h>

     void main(void)
    {

        int num;

        num = 0;

        if (num >= 0)

            printf("Non-negative!\n");

        num = 1;

        if ( num == 0)

             printf("Equal!\n");

        else

             printf("Not equal!\n");

        num = 4;

        if (num == 1)

        {

             printf("One\n");

             if ( num == 2 )

             {

                  printf("Two\n");

             }

             else if ( num == 3 )

                    {

                        printf("Three\n");

                    }

                    else

                    {

                        printf( "The input is not valid!\n" );

                     }

        }

        num = 2;

        switch(num)
       {

           case 1: printf("One ");

                       break;

           case 2: printf("Two ");

                       break;

           case 3: printf("Three ");

                       break;

          default: printf( "The input is not valid! " );

       }

       printf("\n");

    }

Write the output of the program (above).

m) __________________________________________


n) __________________________________________


o) __________________________________________

3. Common errors in writing if, nested if and switch statements.


#include <stdio.h>

void main(void)
{

    int num;

    num = -1;

    if (num > 0); /* ; semicolon here means end of statement so the printf immediately below is not part of the if */

   printf("Positive!\n");

    num = 0;

    if ( num = 1) /* == means test for equality = means assign. If no is assigned 1 that means true in C. */

        printf(" Equal!\n");

    else

       printf("Not equal!\n");

    num = 2;

    switch(num)
   {

      case 1: printf("One ");

      case 2: printf("Two "); /* note that the break statements are missing */

      case 3: printf("Three  ");

      default: printf( "Not valid! " );

    }

    printf("\n");

}


Write the output of the program (above).

p) __________________________________________


q) _________________________________________


r) _________________________________________

 


Part 2: Simple C programs

 References

·         Lecture 10 on C program compilation

·         Lecture 11 on variables, integers, arithmetic operators (+,-,*,/,%), and printf and scanf functions

·         Lecture 12 on if-else and switch statements


Instructions

·         In this lab you will may in groups

·         Read the instructions for each part before filling out the answer sheet


Part A. Nested If and switch statements.

Answer questions 1 and 2 on the answer sheet.

Part B. Write a program to make change.

1. Requirements Specification (Problem Definition)

Using US quarters, dimes, nickels and pennies make change for an amount of money that's less than 1.00 .

2. Analysis---Refine, Generalize, Decompose the problem definition

The user input is in the form .98 or .07 or any two digit number between 0 and 1.00 . You may assume that negative inputs aren't allowed and that quantites greater than 1.00 are not allowed (although this program will work for larger amounts).

The output for a user input of .89 would be:
3 quarters
1 dimes
4 pennies

Note that since there are no nickels used in making change we wouldn't write 0 nickels.

3. Design---Develop Algorithm

We will first try to use as many quarters in making change, then use as many dimes, then use as many nickels and finally use pennies.
For example: If the user's input is .89 then multply this by 100 to convert to an integer. We can then use the / and % operators and they work in the following manner:

89 / 25 = 3 quarters
89 % 25 = 14

14 / 10 = 1 dimes
14 % 10 = 4

4 / 5 = 0 nickels
4 % 5 = 4 pennies

Our algorithm in pseudo-code is: (remember that pseudo-code isn't quite legal C)

(THE SHELL OF THE CODE IS GIVEN BELOW THE PSEUDO-CODE)

float amount;
int cents;
int quarters, dimes, nickels, pennies;

printf ("Enter the amount:");
scanf (‘%f’, &amount);
amount = amount + .005; /* correct for any round-off errors */
cents = 100 * amount;

quarters = cents / 25;
if (quarters > 0)
printf %i quarters
cents = cents % 25;

dimes = cents / 10
if ( dimes > 0)
printf %i dimes
cents = cents % 10;

Complete the remainder of the algorithm on the answer sheet to include nickels and pennies answer question #1

1. Complete the algorithm for the change program.

4. Implementation --- Write the "Program" (Code)

Click the Applications button (top left-hand corner of the EWS desktop) then click Accessories/Terminal to open a Unix window. At the Unix prompt type the following:

cd

mkdir lab 7

cd lab7

gedit change.c &

and include the code below,

#include <stdio.h>

void main(void)
{

   /* your code goes between the pair of curly braces */

   /* use the algorithm above to write the C code here */
}

5. Run the code

Make sure to click the save button in gedit before you proceed.
At the Unix prompt type the following:

gcc change.c -o change ( that's -oh, not -zero )

./change 

Check your code with the following inputs:

.89 , .99 , 1 , .05, 0.07.

Answer question #2 on the Answer sheet.

Part C. Reading and displaying a date

1. Requirements Specification (Problem Definition)

We will write a C program that prompts the user to enter the date in the format mm/dd/yyyy. Our program will read the values for month, day and year into separate variables of datatype int. Next, our program will then check to see if the date is valid and if so prints the date the user entered. If the date entered by the user is not valid then print a message corresponding to the error before the program terminates.

2. Analysis---Refine, Generalize, Decompose the problem definition

The user's input is in the format:
2/26/2006
and the output would be
02/26/2006
that is all single digit numbers would be prefixed with 0's.
Also our program would catch (some) bad dates such as the input
2/-5/2006
would produce the output
"Invalid date, all entries must be positive."
and the bad input
13/2/2006
would produce the outptut
"Invalid month!"
And finally the bad input
2/31/2006
would produce the output
"Invalid number of days in month!"

3. Design---Develop Algorithm

Again using pseudo-code (in red) our algorithm is:

int month, day, year;
int maxdays;
printf Enter a date in the format mm/dd/yy(yy):
scanf("%d/%d/%d", &month, &day ,&year);
/* check for non-negative month day and year */
if ( month <= 0 OR day <= 0 OR year < 0 )
{
   printf("Invalid date, all entries must be positive.\n");
   return; /* finish the program’s execution */
}

/* convert a year in the format 09 to 2009 */

if (year / 100 == 0) /* two digit year */
if ( year < 50)
   year = year + 2000;
else
   year = year + 1900;

/* determine the maximum number of days in month and check that month is between 1 and 12 inclusive. */
switch(month)
{
   case 1: maxdays = 31;
               break;
   case 2: maxdays = 28;
               break;
   case 3: maxdays = 31;
               break;
   case 4: maxdays = 30;
               break;
   case 5: maxdays = 31;
               break;
   case 6: maxdays = 30;
               break;
   case 7: maxdays = 31;
               break;
   case 8: maxdays = 31;
               break;
   case 9: maxdays = 30;
               break;
   case 10: maxdays = 31;
                 break;
   case 11: maxdays = 30;
                  break;
   case 12: maxdays = 31;
                 break;
   default: printf("Invalid month!\n");

}


/* now verify that the day is less than maxdays and if so print the date */
if day <= maxdays
printf(" The date entered is %02i/%02i/%04i \n", month , day , year);
else
printf("Invalid number of days in month!\n");

4. Implementation --- Write the "Program" (Code)

Open gedit (if you have closed the editor) or click the NEW button on the toolbar to create a new file named “date.c”.
Type (or copy and paste) the following statements into your file. (If Ctrl-C/Ctrl-V doesn' copy and paste, then select the text and then middle click where you want to paste it.)

#include <stdio.h>

void main(void)
{

    /* your code goes between the curly braces */


}


Note: The "/" symbols in the scanf function,

scanf ( "%d/%d/%d", &month, &day ,&year);

are delimiters and scanf will skip these characters and not try to convert these into month, day, year integer variables. There is nothing special about the / symbol , if we asked the user to enter a date in the format mm?dd?yyyy then we would use a ? as our delimiter in the scanf above.


Note: The "%d" symbols in the scanf function,

scanf ( "%d/%d/%d", &month, &day ,&year); is equivalent to the %i, except if you enter a number beginning with a zero, like 02, %i thinks 02 is a hexidecimal number but %d treats it as 2.

5. Run the code

Make sure to click the save button in gedit before you proceed.
At the Unix prompt type the following:

gcc date.c -o isdate ( that's -oh not -zero )

./isdate

Enter a date in the format mm/dd/yyyy:

Try the following dates,
11/-11/2012
2/35/2012
13/2/2012

Answer question #3 on the Answer sheet.

C'est finis!


The End