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...
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.
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 =...
I have to translate C++ code into MIPS. It is expected to have an output of:...
I have to translate C++ code into MIPS. It is expected to have an output of: Value of a: 25 Value of b: 31 Value of c: 18 Value of d: 49 Here is the C++ code: I need to translate this C++ into MIPS code. #include using namespace std; int main(void) { int a = 5; int b = 6; int c = 7; int d; d = -1; if ( a < 10){ a++; }else{ a--; } d...
So I have written a code for it but i just have a problem with the...
So I have written a code for it but i just have a problem with the output. For the month with the highest temperature and lowest temperature, my code starts at 0 instead of 1. For example if I input that month 1 had a high of 20 and low of -10, and every other month had much warmer weather than that, it should say "The month with the lowest temperature is 1" but instead it says "The month with...
in java: In my code at have my last two methods that I cannot exactly figure...
in java: In my code at have my last two methods that I cannot exactly figure out how to execute. I have too convert a Roman number to its decimal form for the case 3 switch. The two methods I cannot figure out are the public static int valueOf(int numeral) and public static int convertRomanNumber(int total, int length, String numeral). This is what my code looks like so far: public static void main(String[] args) { // TODO Auto-generated method stub...
The code following is what I have so far. It does not meet my requirements. My...
The code following is what I have so far. It does not meet my requirements. My problem is that while this program runs, it doesn't let the user execute the functions of addBook, isInList or compareLists to add, check, or compare. Please assist in correcting this issue. Thank you! Write a C++ program to implement a singly linked list of books. The book details should include the following: title, author, and ISBN. The program should include the following functions: addBook:...
I'm getting an error with my code on my EvenDemo class. I am supposed to have...
I'm getting an error with my code on my EvenDemo class. I am supposed to have two classes, Event and Event Demo. Below is my code.  What is a better way for me to write this? //******************************************************** // Event Class code //******************************************************** package java1; import java.util.Scanner; public class Event {    public final static double lowerPricePerGuest = 32.00;    public final static double higherPricePerGuest = 35.00;    public final static int cutOffValue = 50;    public boolean largeEvent;    private String...
I have an error on my code. the compiler says 'setLastName' was not declared in this...
I have an error on my code. the compiler says 'setLastName' was not declared in this scope. this is my code : #include <iostream> using std::cout; using std::cin; using std::endl; #include <string> using std::string; class Employee {    public :               Employee(string fname, string lname, int salary)        {            setFirstName(fname);            setLastName(lname);            setMonthlySalary(salary);        }               void setFirstName(string fname)        {       ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT