EECS168 09:Lab5

From ITTC
Jump to: navigation, search
Navigation
Home
Information

Syllabus
Schedule
Lecture Notes
Exam Reviews

Classwork

Labs
Homework
Submitting Work

Objectives

  • Use switch statement
  • Introduction to functions

Switch Statement

By now you have made multi-way branches using if-else structure. Another way for making multi-way branches, is using switch statement. You can find detailed explanation about switch statement starting on page 129 of your book. The following code is an example for use of switch statement. The code gets a number within the range of 1 to 7 and maps it to a week day, starting by the number 1 mapping to Monday. Copy the following code into a file named weekdays.cpp, complete the missing parts of the code and run it.

// TO DO: COMPLETE THE INCLUDE STATEMENT AND DECLARATION OF THE MAIN FUNCTION

int weekday_number;
cout << "Please enter a number between 1 to 7: ";
cin >> weekday_number;

switch(weekday)
{
  case 1:
     cout<<"Monday!"<<endl;
     break;
  case 2:
     cout<<"Tuesday!"<<endl;
     break;

  // TO DO: COMPLETE THE RANGE OF NUMBERS TO COVER ALL THE WEEK DAYS

  case 7:
     cout<<"Sunday!"<<endl;
     break;
  default:
     cout<<"Invalid entry!"<<endl;
}

Later in this lab, you will use the switch statement inside a bigger program.

Functions

Functions are like small subprograms that you call from your code. They are introduced in Chapter 4 of your text. C++ has some predefined functions. You have used at least one of them before, when you included the cmath library in your code and used the pow() function. In this lab we will learn how to write our own functions and use them later on. The following example will show you how to declare, define, and use functions. Copy the code into a file called square_function.cpp and first run the program as it is. After you run the program at least once, make the necessary changes specified as TO DO comments.

#include <iostream>
using namespace std;

// =========================
// = function declarations =
// =========================
float get_side(); // function for getting the side of a square from the user and returning it to the program
float calculate_area(float side); // function for calculating the area of a square by having the square side as the parameter
//TO DO: PUT A FUNCTION DECLARATION FOR CALCULATING THE PERIMETER OF A SQUARE


// ================
// = main program =
// ================
int main()
{
  float square_side; // variable for holding the side of a square
  float square_area; // variable for holding the area of a square

  square_side = get_side();  // call the get_side() function and put the return value of the function in the suare_side variable
  square_area = calculate_area(square_side);  // call the calculate_area() function by passing the square_side to it as
                                              // parameter and keep the return value of the function in the square_area variable

  cout << "The area of the square with a side length of "<<square_side<< " is: "<< square_area << endl;

  // calculate the area of a square with a side length of 4
  square_area = calculate_area(4);
  cout<< "The area of the square with a side length of 4 is: "<< square_area << endl;

  // TO DO: CALL THE PERIMETER FUNCTION with square_side as its parameter
  // TO DO: OUTPUT THE PERIMETER TO THE SCREEN

  return 0;
}


// ========================
// = function definitions =
// ========================

// function that gets the side of a square from the user and returns it to the main program
float get_side()
{
  float side_variable;  // variable for holding the length of a square side
  cout << "Please enter the length of a square's side: ";
  cin >> side_variable;

  return side_variable;
}

// function that calculates the area of a square by receiving the square side as its parameter
float calculate_area(float side)
{
  float area; // variable for holding the result of calculating area of a square
  area = side * side;
  return area;
}

//TO DO: ADD THE FUNCTION DEFINITION FOR A FUNCTION THAT RECEIVES THE SIDE OF A SQUARE AS INPUT, CALCULATES AND RETURNS THE 
//PERIMETER OF THE SQUARE

  • Note: Please pay attention that in all the above function definitions, any variable that is defined inside a function is local to that function and as a result it is not known to the other functions. For example the variable side_variable is local to the get_side() function and if you try to use it in the calculate_area() function, you will get a compile error for the variable not being defined.

Use Functions

Copy the following code into a file named volume_function.cpp:

#include <iostream>
using namespace std;
 
// =========================
// = function declarations =
// =========================
double cubeVolume( double sideLength );
double sphereVolume( double radius );
double cylinderVolume( double radius, double height );


// ================
// = main program =
// ================
int main()
{

    char choice;
    cout<< "Enter C to calculate the volume of a cube. \n";
    cout<< "Enter S to calculate the volume of a sphere. \n";
    cout<< "Enter Y to calculate the volume of a cylinder. \n";
    cout<< "Enter your choice and press Return: ";

    cin>>choice;

    switch (choice)
    {
      // Problem 1: Under this comment, make the function call needed to compute 
      // the volume of a cube whose sides are 4 long, and print the result:
 
      // Problem 2: Under this comment, prompt the user for sphere radius, make 
      // the function call needed to calculate the sphere volume, and print out 
      // the answer:
 
      // Problem 3: A Coke can has a radius of 3.3 cm and a height of 12.1 cm.
      // Calculate and print the volume of a coke can:

      default:
        cout<< "Invalid choice!" << endl;
     }

     return 0;
}


// ========================
// = function definitions =
// ========================

// Calculate the volume of a cube
double cubeVolume( double sideLength )
{
   return ( sideLength * sideLength * sideLength );
}

 
// Calculate the volume of a sphere
double sphereVolume( double radius )
{
   return ( (4.0 / 3.0) * 3.14159 * radius * radius * radius );
}
 

// Calculate the volume of a cylinder
double cylinderVolume( double radius, double height )
{
   return ( 3.14159 * radius * radius * height );
}

Comments in the code describe three problems. Add code to volume_function.cpp which calls the defined functions in order to solve these problems.

void Functions

The functions above calculated a value for you, but not all functions behave the same way. Functions that don't return a value have the void return type. One way we use this type of function is to separate different logical pieces of code. Copy the following code into a file called void_function.cpp, try compiling and running the following code:

#include <iostream>
using namespace std;

void add_three_numbers();


int main()
{
    char input_repeat = 'y';
    
    while (input_repeat == 'y')
    {
        add_three_numbers();
        
        cout << "Enter y to add three more: ";
        cin >> input_repeat;
    } 
     
    return 0;
}


void add_three_numbers()
{
    int x, y, z;
    cout << "Enter three numbers separated by spaces: ";
    cin >> x >> y >> z;
    cout << "The sum is: " << x + y + z << endl;
    return;
}

The work that is done inside the loop has been pulled out into a function. This can make programs easier to write and understand.

Lab Submission

Submit the following files following the submission criteria as the previous labs:

  • weekdays.cpp
  • square_function.cpp
  • volume_function.cpp
  • void_function.cpp