Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

10. Cartesian Circle- Use just one function and pass by reference— please follow

ID: 3695318 • Letter: 1

Question

10. Cartesian Circle- Use just one function and pass by reference— please follow the instructions below to complete this assignment.

NAME OF UNIT: USER-DEFINED FUNCTIONS

UNIT OBJECTIVE: To develop the technique of writing modular C++ programs through the use of programmer-written functions.

LEARNING OBJECTIVES: The student will learn how to:

1. Incorporate modular functions in the process of developing algorithms and solving problems.

2. Differentiate between void functions and functions that return values.

3. Use reference parameters and value parameters in functions.

4. Identify the scope of an identifier and levels of function calls.

5. Differentiate between pass by value and pass by reference.

5. Distinguish between global variables, static variables, automatic variables.

Explanation / Answer

10. Cartesian Circle- Use just one function and pass by reference— please follow the instructions below to complete this assignment.

NAME OF UNIT: USER-DEFINED FUNCTIONS

The following formula gives the distance between two points, (x1, y1) and (x2, y2) in the Cartesian plane:

Given the center and a point on the circle, you can use this formula to find the radius of the circle. Your program must have at least the following functions:

distance: This function takes as its parameters four numbers that represent two points in the plane and returns the distance between them.

radius: This function takes as its parameters four numbers that represent the center and a point on the circle, calls the function distance to find the radius of the circle, and returns the circle’s radius.

circumference: This function takes as its parameter a number that represents the radius of the circle, and returns the circle’s circumference. (If r is the radius, the circumference is 2pr)

area: This function takes as its parameter a number that represents the radius of the circle, and returns the circle’s area. (If r is the radius, the circumference is pr2)

#include <iostream>

#include<cmath>

#include<iomanip>

#define PI 3.1416

#define sq 2

using namespace std;

double distance(double x1, double x2, double y1, double y2);

double raduis(double x1, double x2, double y1, double y2);

double circumference(double r);

double area(double r);

int main(int argc, char *argv[])

{

            double x1;

            double x2;

            double y1;

            double y2;

           

   

    cout<<"Enter the x and y cordinates of center of the circle: ";

    cin>>x1>>y1;

    cout <<endl<<"Enter the x and y coordinates of a point on the circle: ";

    cin>>x2>>y2;

   

        cout<<endl<<"Raduis = "<<fixed<<setprecision(2)<<raduis(x1,x2,y1,y2)<<endl;

        cout<<"Diameter = "<<raduis(x1,x2,y1,y2) + raduis(x1,x2,y1,y2)<<endl;

        cout<<"Circumference = "<<circumference(raduis(x1,x2,y1,y2))<<endl;

        cout<<"Area = "<<area(raduis(x1,x2,y1,y2))<<endl;

   system("pause");

return 0;

}

double distance(double x1, double x2, double y1, double y2)

{        

      return sqrt(pow(x2 - x1, sq) + pow(y2 - y1, sq));                   

}

double raduis(double x1, double x2, double y1, double y2)

{

return distance(x1, x2, y1, y2);                                  

}

double circumference(double r)

{

   return sq * PI * r;

}

double area(double r)

{

   return PI * pow(r, sq);

}

A set of related procedures with the data they manipulate is often called a module. The programming paradigm becomes this:

Decide which modules you want; partition the program so that data is hidden within modules.

This paradigm is also known as the data-hiding principle. The most common example of a module is the definition of a stack.

For example, the user interface of a Stack module could be declared and used like this:

namespace Stack{     // interface

void push(char);

char pop();

}

void f()

{

Stack::push('c');

if (Stack::pop() != 'c') error("impossible");

}

The Stack:: qualification indicates that the push() and pop() are those from the Stack namespace. Other uses of those names will not interfere or cause confusion.

The definition of the Stack could be provided in a separately compiled part of the program:

namespace Stack{       // implementation

const int max_size = 200;

char v[max_size];

int top = 0;

void push(char c) { /* check for overflow and push c */ }

char pop() { /* check for underflow and pop */ }

}

The key point about this Stack module is that the user code is insulated from the data representation of Stack by the code implementing Stack::push() and Stack::pop(). The user doesn't need to know that the Stack is implemented using an array, and the implementation can be changed without affecting user code.

Separate Compilation

C++ supports C's notion of separate compilation. This can be used to organize a program into a set of semi-independent fragments. Place the declarations that specify the interface to a module in a file with a name indicating its intended use. Thus,

namespace Stack{        // interface

void push(char);

char pop();

}

would be placed in a file stack.h, and users will include that file, called a header file, like this:

#include "stack.h"      // get the interface

void f()

{

Stack::push('c');

if (Stack::pop() != 'c') error("impossible");

}

To help the compiler ensure consistency, the file providing the implementation of the Stack module will also include the interface:

#include "stack.h"      // get the interface

namespace Stack{       // representation

const int max_size = 200;

char v[max_size];

int top = 0;

}

void Stack::push(char c) { /* check for overflow and push c */ }

char Stack::pop() { /* check for underflow and pop */ }

The user code goes in a third file, say user.c. The code in user.c and stack.c shares the stack interface information presented in stack.h, but the two files are otherwise independent and can be separately compiled. Graphically, the program fragments can be represented like this:

Separate compilation is an issue in all real programs. It is not simply a concern in programs that present facilities, such as a Stack, as modules. Strictly speaking, using separate compilation isn't a language issue; it is an issue of how best to take advantage of a particular language implementation.The best approach is to maximize modularity, represent that modularity logically through language features, and then exploit the modularity physically through files for effective separate compilation.

Exception Handling

When a program is designed as a set of modules, error handling must be considered in light of these modules. Which module is responsible for handling what errors? Often, the module that detects an error doesn't know what action to take. The recovery action depends on the module that invoked the operation rather than on the module that found the error while trying to perform the operation. As programs grow, and especially when libraries are used extensively, standards for handling errors (or, more generally, "exceptional circumstances") become important.

The solution is for the Stack implementer to detect the overflow and then tell the (unknown) user. The user can then take appropriate action. For example:

namespace Stack{       // interface

void push(char);

char pop();

class Overflow { };    // type representing overflow exceptions

}

When detecting an overflow, Stack::push() can invoke the exception-handling code; that is, "throw an Overflow exception:"

void Stack::push(char c)

{

if (top == max_size) throw Overflow();

// push c

}

The throw transfers control to a handler for exceptions of type Stack::Overflow in some function that directly or indirectly called Stack::push(). To do that, the implementation will unwind the function call stack as needed to get back to the context of that caller. Thus, the throw acts as a multilevel return. For example:

void f()

{

// ...

try { // exceptions here are handled by the handler defined below

     while (true) Stack::push('c');

}

catch (Stack::Overflow) {

    // oops: stack overflow; take appropriate action

}

// ...

}

The while loop will try to loop forever. Therefore, the catch-clause providing a handler for Stack::Overflow will be entered after some call of Stack::push() causes a throw.

Use of the exception-handling mechanisms can make error handling more regular and readable.

2. Differentiate between void functions and functions that return values.

When to use Void or Value-Returning Functions:

When/How to Pass/Return Values Recommendations:

   

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value. Even without the return statement, control will return to the caller automatically at the end of the function. A good utilization of a void function would be to print a header/footer to a screen or file.

A value-returning function can only return one value to the calling environment. The caller invokes (calls) a value-returning function by using its name and argument list in an expression (i.e., 1. assignment, 2. output, or as an 3. argument in another function call):

//value-returning function call (assignment):

y = 2.0 * sqrt(x);

A void function (method or procedure, in other languages) does not return a function value. Nor is it called from within an expression. Instead, the function call appears as a complete, stand-alone statement. One example is the get function associated with the istream and ifstream classes:

//void function call:

cin.get();

Another example:

//void function call:

printName(name);

Similarities Between Value-Returning and Void (NonValue-Returning) functions:

Differences Between Value-Returning and Void (NonValue-Returning) functions:

//Void (NonValue-returning) function definition syntax: including header and body

void functionName(formal parameter list) //function header

{

   //function body

statements...

   //void (nonvalue-returning) function can still use return statement

   //but, does not return any values...

   return;

}

//function call syntax:

functionName(actual parameter list); //stand-alone statement only

functionName(); //stand-alone statement only

***Void function calls can ONLY be used w/in stand-alone statements.

***Conversely, value-returning function calls can be used in

3. Use reference parameters and value parameters in functions.

Function Parameter Types:
Two Types of Function Parameters:

Using Value and Reference Parameters:
Value Parameters:

Void Function Definition Using Value Parameters Example:

//Void (NonValue-returning) function definition syntax: including header and body

void functionName(dataType variable, dataType variable) //function header

{

   //function body

   statements...

   //void (nonvalue-returning) function can still use return statement

   //but, does not return any values...

   return;

}

Reference Parameters:

Void Function Definition Using Reference Parameters Example:

//Void (NonValue-returning) function definition syntax: including header and body

void functionName(dataType& variable, dataType& variable) //function header

{

   //function body

   statements...

   //void (nonvalue-returning) function can still use return statement

   //but, does not return any values...

   return;

}

Function Calls Using Value and Reference Parameter Examples:
Void function call using value parameters (can use expression, constant, or variable):

//Void (NonValue-returning) function call with arguments

functionName(expression or constant or variable, expression or constant or variable); //stand-alone statement only

Void function call using reference parameters (can NOT use expression or constant, ONLY variables):

//Void (NonValue-returning) function call with arguments

functionName(variable, variable); //stand-alone statement only

4. Identify the scope of an identifier and levels of function calls.

scope

Scope (accessibility) rules:

A global variable, that is a variable declared outside of all functions in a file, is accessible by any code in that file. By declaring extern variables, for programs that require multiple files, variables declared in one file can be accessible in other files. Variables that are declared as extern are often placed in an include file that is used by any file requiring access to the external variable. If there are multiple variables with the same name whose scopes overlap at one point in a program, the variable with the innermost scope will be used.

                                //   scopes:

                                // x i j k

float x;                        // |

int main()                      // |

{                              // |

int i;                        // | |

for (int j = 0; j < 100; ++j) // | | |

{                             // | | |

    std::cin >> i;              // | | |

    int k = i;                  // | | | |

    // more code                // | | | |

}                             // | |

return 0;                     // | |

}                               // |

Note that x is global, i and j are local. The following code is more subtle.

#include <iostream>

int main()

{

std::cout << " Starting Program ";

{

    int x = 5;// declare new variable

    std::cout << "x = " << x << ' ';

    {

      int x = 8;

      std::cout << "x = " << x << ' ';

    }

    std::cout << "x = " << x << ' ';

    {

      x = 3;

    }

    std::cout << "x = " << x << ' ';

}

}

You can run the program to be sure you understand how scope rules affect the

values of the variables.

Namespace Scope:

std::cout << "Namespace test";

using std::cout;

cout << "Namespace test";

using namespace std;

cout << "Namespace test";

5. Differentiate between pass by value and pass by reference.

When a function is called:

Summary of pass by value vs. pass by reference:
Pass by value:

Pass by reference:

Although the C++ language allows value-returning functions to have both value parameters and reference parameters, it is not recommended. By definition, a value-returning function returns a single value; this value is returned via the return statement. Use void functions with reference parameters to return (modify) more than one value.

/*

This program demos void functions using

value parameters vs. reference parameters

/*

//header files

#include<iostream>

using std::cout;

using std::cin;

using std::endl;

//prototype functions

void readDate(int& month, int& day, int& year); //reference parameters

void printDate(int month, int day, int year); //value parameters

//initialize constants

//initialize global variables

int main()

{

//initialize automatic variables

int mm, dd, yy;

readDate(mm, dd, yy);

printDate(mm, dd, yy);

cout << "Press Enter key to exit...";

cin.get(); cin.get(); // make DOS window stay open

return 0;

}

//function definitions

void readDate(int& month, int& day, int& year)

{

char ch; //local variable

cout << "Enter a date (mm/dd/year): ";

cin >> month >> ch >> day >> ch >> year;

}

void printDate(int month, int day, int year)

{

cout << "The date is " << month << '-' << day;

cout << '-' << year << endl;

}

5. Distinguish between global variables, static variables, automatic variables.

Global variable problems:

Scope Summary Rules:

Automatic variable:

Static variable:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote