Question

In: Computer Science

Split the main function given into multiple functions. You have been given a very simple program...

  1. Split the main function given into multiple functions.

You have been given a very simple program that performs basic operations (addition, subtraction, editing) on two randomly generated integer vectors. All functionality has been included in main, causing code segments to be repeated as well as diminishing the readability.

Rewrite the program by grouping calculations and related operations into functions. In particular, your program should include the following functions.

  • InitializeVectors: This is a void function that initializes the two vectors by random numbers. Inside this function, the user will be prompted to enter the maximum random number. After the vectors have been populated with random numbers, print the vectors side by side. The parameters are the two arrays and their size.
  • EditVector: This is a void function that allows the user to update a value belonging to either vector. The user specifies the vector he wants to edit, the index he wants edit, and finally the updated value. The entire vector must then be printed on the screen. You need to pass the two arrays and their sizes.
  • CalculateAverage: This is a function that returns the average value in a vector. It returns a double and receives as parameters an array and its size.
  • printVector: A void function that takes a vector as a parameter along with its size, and prints it on the screen.

As you introduce each function, replace the code in main() by the appropriate function call. Also, keep in mind that for some functions, any changes that occur within the function body must also be visible in main. Finally, some functions can be called within other functions.

Remember that this program was already working. You should not alter the code, you just need to restructure it.

By the end of this assignment, the program’s structure and functionality will be more transparent, making it both easier and faster to understand.

Here is the code I need altered:

#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <bits/stdc++.h>

using namespace std;

int main()
{
    int v_size = 0; //variable for the size of the arrays, its the same for both so that we can do addition and subtraction
    int v_id = 0;   //use it to determine which vector to operate on, used for average computation
    int ceiling = 0;    //when generating random numbers to place in vector, this constraints the maximum number attainable by the random number generator
    int action = 0; //determine which course of action the program will take
    double avg = 0.0;

    GetSize:
    cout<<"Enter size for vectors: ";
    cin>>v_size;

    if(cin.fail() == true)
    {
        system("CLS");
        cout<<"Invalid Input. Please Re-enter vector size: ";
        cin.clear();
        cin.ignore(10000, '\n');
        goto GetSize;
    }

    GetCeiling:
    cout<<"Enter Maximum Random Number for Vector: ";
    cin>>ceiling;

    if(cin.fail() == true)
    {
        system("CLS");
        cout<<"Invalid Input. Please Re-enter Maximum Random Number: ";
        cin.clear();
        cin.ignore(10000, '\n');
        goto GetCeiling;
    }

    int v1[v_size];
    int v2[v_size];

    int result[v_size];
    int run_sum =0;
    //randomly initialize the vectors
    srand (time(NULL));  //seed
    for(int i=0; i<v_size; i++)
    {
        v1[i]=rand() % ceiling;
        v2[i]=rand() % ceiling;
        cout<<setw(5)<<v1[i]<<setw(5)<<v2[i]<<endl;
    }

    GetAction:
    cout<<"Enter Action: vector addition(0), vector subtraction(1), average(2), edit(3), print vectors(4), clear screen(5), exit(-1): ";
    cin>>action;
    //system("CLS");
    if(cin.fail() == true || action<-1 || action>5)
    {
        system("CLS");
        cout<<"Invalid Input. Please Re-enter Desired Action: ";
        cin.clear();
        cin.ignore(10000, '\n');
        goto GetAction;
    }

    if(action == -1)
        goto end;

    if(action == 0)
    {
         for(int i=0; i<v_size; i++)
         {
             result[i]=v1[i]+v2[i];
             cout<<result[i]<<endl;
         }
    }

    else if(action == 1)
         for(int i=0; i<v_size; i++)
         {
             result[i]=v1[i]-v2[i];
             cout<<result[i]<<endl;
         }

    else if(action == 2)
    {
        getVector:
        cout<<"Average of Vector 1, or Vector 2 (Enter 1 or 2)? "<<endl;
        cin>>v_id;
        if(cin.fail() == true || (v_id!=1 && v_id!=2))
        {
        system("CLS");
        cout<<"Invalid Input. Please Re-enter Vector Selection(1 or 2): ";
        cin.clear();
        cin.ignore(10000, '\n');
        goto getVector;
        }
        if(v_id == 1 )
            for(int i=0; i<v_size; i++)
                run_sum += v1[i];

        else if(v_id == 2)
            for(int i=0; i<v_size; i++)
                run_sum += v2[i];

    avg = (double)run_sum/(double)v_size;
    cout<<"Average: "<<avg<<endl;
    run_sum = 0; //reset
    }

    else if(action == 3)
    {
        int index;
        GetVector:
        cout<<"Which Vector would you like to edit? (Enter 1 or 2): ";
        cin>>v_id;
        if(cin.fail() == true || (v_id!=1 && v_id!=2))
        {
        system("CLS");
        cout<<"Invalid Input. Please Re-enter Vector Selection(1 or 2): ";
        cin.clear();
        cin.ignore(10000, '\n');
        goto GetVector;
        }
        GetIndex:
        cout<<"Select Index to be Updated: "<<endl;
        cin>>index;
        if(cin.fail() == true || index<0 || index>(v_size+1))
        {
        system("CLS");
        cout<<"Invalid Input. Please Re-enter index to be updated: ";
        cin.clear();
        cin.ignore(10000, '\n');
        goto GetIndex;
        }
        cout<<"Enter updated value: ";
        if(v_id == 1)
        {
            cin>>v1[index];
            for(int i=0; i< v_size; i++)
                cout<<v1[i]<<endl;

        }

        else if(v_id == 2)
        {
             cin>>v2[index];
             for(int i=0; i< v_size; i++)
                cout<<v2[i]<<endl;
        }
    }
    if(action == 4)
         for(int i=0; i<v_size; i++)
             cout<<setw(5)<<v1[i]<<setw(5)<<v2[i]<<endl;


    if(action == 5)
        system("CLS");

    goto GetAction;
    end:
    return 0;
}

Solutions

Expert Solution

code:


#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <bits/stdc++.h>

using namespace std;


int v_size = 0; //variable for the size of the arrays, its the same for both so that we can do addition and subtraction
int v_id = 0; //use it to determine which vector to operate on, used for average computation
int ceiling = 0; //when generating random numbers to place in vector, this constraints the maximum number attainable by the random number generator
int action = 0; //determine which course of action the program will take
double avg = 0.0;

void InvalidInput(){
system("CLS");
cout<<"Invalid Input. Please Re-enter vector size: ";
cin.clear();
cin.ignore(10000, '\n');
}
void printVector(int v[], int size){
for(int i=0; i< size; i++)
cout<<setw(5)<<v[i]<<endl;
}

void printVectorSidebySide(int v1[],int v2[],int size){
for(int i=0; i<size; i++)
cout<<setw(5)<<v1[i]<<setw(5)<<v2[i]<<endl;
}

void InitializeVectors(int v1[],int v2[],int size){
GetCeiling:
cout<<"Enter Maximum Random Number for Vector: ";
cin>>ceiling;

if(cin.fail() == true)
{
InvalidInput();
goto GetCeiling;
}
//randomly initialize the vectors
srand (time(NULL)); //seed
for(int i=0; i<v_size; i++)
{
v1[i]=rand() % ceiling;
v2[i]=rand() % ceiling;
}
printVectorSidebySide(v1,v2,v_size);
}

void EditVector(int v1[],int v2[],int size){
int index;
GetVector:
cout<<"Which Vector would you like to edit? (Enter 1 or 2): ";
cin>>v_id;
if(cin.fail() == true || (v_id!=1 && v_id!=2))
{
InvalidInput();
goto GetVector;
}
GetIndex:
cout<<"Select Index to be Updated: "<<endl;
cin>>index;
if(cin.fail() == true || index<0 || index>(v_size+1))
{
InvalidInput();
goto GetIndex;
}
cout<<"Enter updated value: ";
if(v_id == 1)
{
cin>>v1[index];
printVector(v1,v_size);

}

else if(v_id == 2)
{
cin>>v2[index];
printVector(v2,v_size);
}
}


double CalculateAverage(int v[],int size){
int run_sum =0;
double average;
for(int i=0; i<size; i++)
run_sum += v[i];

average = (double)run_sum/(double)size;
return average;
}

int main()
{
GetSize:
cout<<"Enter size for vectors: ";
cin>>v_size;

if(cin.fail() == true)
{
InvalidInput();
goto GetSize;
}

int v1[v_size];
int v2[v_size];

int result[v_size];

InitializeVectors(v1,v2,v_size);

GetAction:
cout<<"Enter Action: vector addition(0), vector subtraction(1), average(2), edit(3), print vectors(4), clear screen(5), exit(-1): ";
cin>>action;
//system("CLS");
if(cin.fail() == true || action<-1 || action>5)
{
InvalidInput();
goto GetAction;
}

if(action == -1)
goto end;

if(action == 0)
{
for(int i=0; i<v_size; i++)
{
result[i]=v1[i]+v2[i];
cout<<result[i]<<endl;
}
}

else if(action == 1)
for(int i=0; i<v_size; i++)
{
result[i]=v1[i]-v2[i];
cout<<result[i]<<endl;
}

else if(action == 2)
{
getVector:
cout<<"Average of Vector 1, or Vector 2 (Enter 1 or 2)? "<<endl;
cin>>v_id;
if(cin.fail() == true || (v_id!=1 && v_id!=2))
{
InvalidInput();
goto getVector;
}
if(v_id == 1 )
avg = CalculateAverage(v1,v_size);


else if(v_id == 2)
avg = CalculateAverage(v2,v_size);

// avg = (double)run_sum/(double)v_size;
cout<<"Average: "<<avg<<endl;
// run_sum = 0; //reset
}

else if(action == 3)
{
EditVector(v1,v2,v_size);
}
if(action == 4)
printVectorSidebySide(v1,v2,v_size);

if(action == 5)
system("CLS");

goto GetAction;
end:
return 0;
}


Related Solutions

Write a C++ program which consists of several functions besides the main() function. The main() function,...
Write a C++ program which consists of several functions besides the main() function. The main() function, which shall ask for input from the user (ProcessCommand() does this) to compute the following: SumProductDifference and Power. There should be a well designed user interface. A void function called SumProductDifference(int, int, int&, int&, int&), that computes the sum, product, and difference of it two input arguments, and passes the sum, product, and difference by-reference. A value-returning function called Power(int a, int b) that...
C++ Write a program that has two functions. The 1st function is the main function. The...
C++ Write a program that has two functions. The 1st function is the main function. The main function should prompt the user for three inputs: number 1, number 2, and an operator. The main function should call a 2nd function called calculate. The 2nd function should offer the choices of calculating addition, subtraction, multiplication, and division. Use a switch statement to evaluate the operator, then choose the appropriate calculation and return the result to the main function.
python code Write a simple calculator: This program must have 9 functions: •main() Controls the flow...
python code Write a simple calculator: This program must have 9 functions: •main() Controls the flow of the program (calls the other modules) •userInput() Asks the user to enter two numbers •add() Accepts two numbers, returns the sum •subtract() Accepts two numbers, returns the difference of the first number minus the second number •multiply() Accepts two numbers, returns the product •divide() Accepts two numbers, returns the quotient of the first number divided by the second number •modulo() Accepts two numbers,...
This program must have 9 functions: •main() Controls the flow of the program (calls the other...
This program must have 9 functions: •main() Controls the flow of the program (calls the other modules) •userInput() Asks the user to enter two numbers •add() Accepts two numbers, returns the sum •subtract() Accepts two numbers, returns the difference of the first number minus the second number •multiply() Accepts two numbers, returns the product •divide() Accepts two numbers, returns the quotient of the first number divided by the second number •modulo() Accepts two numbers, returns the modulo of the first...
Language Python with functions and one main function Write a program that converts a color image...
Language Python with functions and one main function Write a program that converts a color image to grayscale. The user supplies the name of a file containing a GIF or PPM image, and the program loads the image and displays the file. At the click of the mouse, the program converts the image to grayscale. The user is then prompted for a file name to store the grayscale image in.
You have been given the following specifications for a simple database about the requests for software...
You have been given the following specifications for a simple database about the requests for software that staff members make for their units (note that primary keys are shown underlined, foreign keys in bold). You should run your SQL to demonstrate that it works correctly, and paste in the statements used plus the output from Oracle. LAB (RoomNo, Capacity) SOFTWARE (SoftwareID, SoftwareName, Version) REQUEST (SoftwareID, RoomNo, RequestDate, TeachingPeriod, Progress) Based on the table specifications provided, answer the following questions. Each...
You have been instructed to use C++ to develop, test, document, and submit a simple program...
You have been instructed to use C++ to develop, test, document, and submit a simple program with the following specifications. The program maintains a short data base of DVDs for rent with their name, daily rental charge, genre, and a a short description . The program will welcomes the user, user will enter the name of the movie from a displayed list of all movies that are available, the user will enter the number next to the movie's name, number...
create a C++ program where you have 2 functions with two parameters. Limit the first function...
create a C++ program where you have 2 functions with two parameters. Limit the first function allowed input to values of numbers from 1-10 and from 5 to 20 for the second function. have each function add their two-parameter together then add the functions final values together. Show error message if wrong input is entered   Ask the user if they wish to continue the program (use loop or decision for this question).
1G. This program, unlike the previous 6 programs, will have several functions in it: besides main,...
1G. This program, unlike the previous 6 programs, will have several functions in it: besides main, it willhave the following 7 functions:public static int triangle( int n )public static int multiply( int a, int b )public static void square( int size )public static void hollowSquare( int size )public static int factorial( int n )public static long fibonacci( int n )public static boolean prime( long n )These 7 functions should work as described below.Your main program should call each of these...
Intro C++ Programming Chapter 6 Functions You have been tasked to write a new program for...
Intro C++ Programming Chapter 6 Functions You have been tasked to write a new program for the Research Center's shipping department. The shipping charges for the center are as follows: Weight of Package (in kilograms)                Rate per mile Shipped 2 kg or less                                                      $0.05 Over 2 kg but no more than 6 kg    $0.09 Over 6 kg but not more than 10 kg    $0.12 Over 10 kg    $0.20 Write a function in a program that asks for...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT