Question

In: Computer Science

This is the code I have. My problem is my output includes ", 0" at the...

This is the code I have. My problem is my output includes ", 0" at the end and I want to exclude that.

// File: main.cpp

/*---------- BEGIN - DO NOT EDIT CODE ----------*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;


using index_t = int;
using num_count_t = int;
using isConnected_t = bool;
using sum_t = int;

const int MAX_SIZE = 100;

// Global variable to be used to count the recursive calls.
int recursiveCount = 0;

// Function prototypes.
isConnected_t isFileOpenForInput(ifstream& ifs, const string& filename);
num_count_t loadNumbersFromFile(ifstream& ifs, int numbers[]);
void displayNumbers(const int numbers[], const int length);
sum_t sumOfNumbers(const int numbers[], const int length);

int main() {
ifstream ifs;
int numbers[MAX_SIZE];

if ( !isFileOpenForInput(ifs, "numbers.txt") ) {
cerr << "Error opening file for reading." << endl;
exit(1);
}

cout << setw(26) << "Numbers: ";
int length = loadNumbersFromFile(ifs, numbers);

displayNumbers(numbers, length);
cout << endl
<< setw(26) << "The sum of all values is: " << sumOfNumbers(numbers, length);
  
cout << endl;
return 0;
}// end main()
/*---------- END - DO NOT EDIT CODE ----------*/

/* TODO (1):
* Implement the isFileOpenForInput() function.
*
* Open the connection to the filename and return the connection
* status.
*/
isConnected_t isFileOpenForInput(ifstream &ifs, const string &filename)
{
ifs.open(filename);

return ifs.is_open();
}


/* TODO (2):
* Implement the loadNumbersFromFile() function.
*
* Read each number from the given stream and store
* it into the array.
*
* Return a count of the numbers read.
*/

num_count_t loadNumbersFromFile(ifstream &ifs, int numbers[])
{
int count = 0;

while (!ifs.eof())
{
ifs >> numbers[count++];
}
return count;
}

void displayNumbers(const int numbers[], const int length) {
ostringstream oss;

oss << "[ ";
for (int i = 0; i <= length - 1; i++) {
oss << numbers[i] << ", ";
}
oss.seekp(-2, ios::end);
oss << " ]";

cout << oss.str();
}// end displayEmployees()

/* TODO (3):
* Implement the recursive sumOfNumbers() function.
*
* The function recursively adds all the elements of
* the array together.
*
* Upon entry increment the recursiveCount by 1. This
* will keep track of the number of times the function
* is called.
*
* Return the sum of all elements in the array.
*/

sum_t sumOfNumbers(const int numbers[], const int length)
{
if (recursiveCount == length)

return 0;

recursiveCount++;

return numbers[recursiveCount - 1] + sumOfNumbers(numbers, length);
}

Solutions

Expert Solution

Code:- There is not much to change the output is correct. Go through the code below and ask if you have any doubts

#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;


using index_t = int;
using num_count_t = int;
using isConnected_t = bool;
using sum_t = int;

const int MAX_SIZE = 100;

// Global variable to be used to count the recursive calls.
int recursiveCount = 0;

// Function prototypes.
isConnected_t isFileOpenForInput(ifstream& ifs, const string& filename);
num_count_t loadNumbersFromFile(ifstream& ifs, int numbers[]);
void displayNumbers(const int numbers[], const int length);
sum_t sumOfNumbers(const int numbers[], const int length);

int main() {
ifstream ifs;
int numbers[MAX_SIZE];

if ( !isFileOpenForInput(ifs, "numbers.txt") ) {
cerr << "Error opening file for reading." << endl;
exit(1);
}

cout << "Numbers: ";
int length = loadNumbersFromFile(ifs, numbers);

displayNumbers(numbers, length);
cout << endl
<< setw(26) << "The sum of all values is: " << sumOfNumbers(numbers, length);
  
cout << endl;
return 0;
}// end main()
/*---------- END - DO NOT EDIT CODE ----------*/

/* TODO (1):
* Implement the isFileOpenForInput() function.
*
* Open the connection to the filename and return the connection
* status.
*/
isConnected_t isFileOpenForInput(ifstream &ifs, const string &filename)
{
ifs.open(filename);

return ifs.is_open();
}


/* TODO (2):
* Implement the loadNumbersFromFile() function.
*
* Read each number from the given stream and store
* it into the array.
*
* Return a count of the numbers read.
*/

num_count_t loadNumbersFromFile(ifstream &ifs, int numbers[])
{
int count = 0;

while (!ifs.eof())
{
ifs >> numbers[count++];
}
return count;
}

void displayNumbers(const int numbers[], const int length) {
ostringstream oss;

oss << "[ ";
for (int i = 0; i <= length - 1; i++) {
oss << numbers[i] << ", ";
}
oss.seekp(-2, ios::end);
oss << " ]";

cout << oss.str();
}// end displayEmployees()

/* TODO (3):
* Implement the recursive sumOfNumbers() function.
*
* The function recursively adds all the elements of
* the array together.
*
* Upon entry increment the recursiveCount by 1. This
* will keep track of the number of times the function
* is called.
*
* Return the sum of all elements in the array.
*/

sum_t sumOfNumbers(const int numbers[], const int length)
{
if (recursiveCount == length)

return 0;

recursiveCount++;

return numbers[recursiveCount - 1] + sumOfNumbers(numbers, length);
}

Screenshots

Input\output


Related Solutions

In Python I have a code: here's my problem, and below it is my code. Below...
In Python I have a code: here's my problem, and below it is my code. Below that is the error I received. Please assist. Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same. Examples: swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER' swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I...
Hi I have a java code for my assignment and I have problem with one of...
Hi I have a java code for my assignment and I have problem with one of my methods(slice).the error is Exception in thread "main" java.lang.StackOverflowError Slice method spec: Method Name: slice Return Type: Tuple (with proper generics) Method Parameters: Start (inclusive) and stop (exclusive) indexes. Both of these parameters are "Integer" types (not "int" types). Like "get" above, indexes may be positive or negative. Indexes may be null. Description: Positive indexes work in the normal way Negative indexes are described...
I have a problem with the code for my project. I need the two clients to...
I have a problem with the code for my project. I need the two clients to be able to receive the messages but the code I have done only the server receives the messages. I need the clients to be able to communicate with each other directly not throught the server. The requirements of this "local chat" program must meet are: 1. The chat is performed between 2 clients and a server. 2. The server will first start up and...
I am having an issue with trying to make my code to have a required output...
I am having an issue with trying to make my code to have a required output ////////////Input////////// With computer science, you can work in any industry. 0 //////////Output////////// Required Output Enter some text to encrypt\n Enter a key\n Error: Key is divisible by 26. That's a bad key!\n Useless key: 0\n ///////////Cipher.java///////// ------------ My code. public class Cipher { private String plainText; private int key; public Cipher(String text, int key) throws EmptyPlainText, UselessKeyException { if (text == null || text.length()...
I have a problem with my code. It does not run. Please can someone check the...
I have a problem with my code. It does not run. Please can someone check the code and tell me where I went wrong? This is the question: Program Specification: Write a C program that takes the length and width of a rectangular yard, and the length and width of a rectangular house (that must be completely contained in the yard specified) as input values. Assuming that the yard has grass growing every where that the house is not covering,...
Hello, I have a problem with understanding this code. value.parseHtml().select("p")[0].innerHtml() This code is for the open...
Hello, I have a problem with understanding this code. value.parseHtml().select("p")[0].innerHtml() This code is for the open refine program. Could you tell me what this code is trying to do? I have no idea what this is for... For your information, this code appeared when professor was talking about 'Fetching and Parsing HTML'.. Thank you for answering my question and have a good day! p.s. I don't know whether value.parseHtml().select("p")[0].innerHtml() is a code. Anyways, my professor told us to insert that...
Here is my java code. It works and has the correct output, but I need to...
Here is my java code. It works and has the correct output, but I need to add a file and I am not sure how. I cannot use the FileNotFoundException. Please help! import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,0,0}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: "...
What's wrong with my Python code. We have to find the regularexpression in Python My output...
What's wrong with my Python code. We have to find the regularexpression in Python My output should look like this My IP address 128. 0. 0. 1 My IP address 53. 20. 62. 201 My code ipAddresses = [] ipRegEx = re.compile(r"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")    result = myRegEx.find all(Search Text)    def Regular_expression(ipAddresses)       for i in ipAddresses:          print(i) ipSearchResult = ipRegEx.search(line)    if ipSearchResult != None and ipSearchResult.group() not in ipAddresses:       ipAddresses.append(ipSearchResult.group()) we have to use loop too.
I need my code output values edited to be formatted to two decimal places (i believe...
I need my code output values edited to be formatted to two decimal places (i believe using setprecision), i will need you to edit my code toformat each menu option to 2 decimal places: provided is my code #include <iostream> #include <iomanip> using namespace std; int main() {    double radius;    double base;    double height;    double length;    double width;    double Area;    const double PI = 3.14159;    int choice;    // display menu   ...
Show the output of the following code segment. int count=0;                         for (int i=2; i <=...
Show the output of the following code segment. int count=0;                         for (int i=2; i <= 4; i++ ) {                                     StdOut.println(i);                                     for (int j=1; j <3; j++) {                                                 count++;                                                 StdOut.println(i +" " + j +" "+ count);                                     }                         } count i j I print 0 2 1 3 1 1 1 2 3 2 2 3 3 3 3 4 3 Show the output of the function call statements shown.             double x =...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT