Question

#include <iostream> #include <fstream> using namespace std; //constants const int CAP = 100; //function prototypes bool...

#include <iostream>

#include <fstream>

using namespace std;

//constants

const int CAP = 100;

//function prototypes

bool openFile(ifstream &);

void readData(ifstream &, int [], int &);

void printData(const int [], int);

void sum(const int[], int);

void removeItem(int[], int &, int);

int main()

{

ifstream inFile;

int list[CAP], size = 0;

if (!openFile(inFile))

{

cout << "Program terminating!! File not found!" << endl;

return -1;

}

//read the data from the file

readData(inFile, list, size);

inFile.close();

cout << "Data in file:" << endl;

printData(list, size);

//remove a few items

removeItem(list, size, 9);

printData(list, size);

removeItem(list, size, 200);

printData(list, size);

removeItem(list, size, 15);

printData(list, size);

//call the sum function

sum(list, size);

//end program

cin.ignore(100, '\n');

cout << "Press any key to continue...";

getchar();

return 0;

}

//function to open file

bool openFile(ifstream &inFile)

{

inFile.open("numbers.txt");

if (!inFile)

{

return false;

}

return true;

}

//reads the data from the file

void readData(ifstream &inFile, int list[], int &size)

{

while (!inFile.eof())

{

inFile >> list[size++];

}

}

//print the contents of the array

void printData(const int list[], int size)

{

for (int i = 0; i < size; i++)

{

cout << list[i] << endl;

}

cout << endl;

}

//remove an item (delNum) and return the number removed to main. If number does not exist, return -1.

void removeItem(int list[], int &size, int delNum)

{

//insert code here

for (int i = 0; i < size; i++)

{

if (list[i] < delNum)

{

delNum = list[i];

  

  

}

}

  

}

//count the even numbers in the list and output in this function

void sum(const int list[], int size)

{

int sum = 0, n = 0;

  

for (int i = 0; i < size; i++)

{

sum = sum + list[i];

  

if(list[i] %2 == 0)

  

n++;

cout <<"even numbers: "<< n <<"sum: " << sum << endl;

  

  

  

}

}

help me fix the remove and sum functions please

0 0
Add a comment Improve this question Transcribed image text
Answer #1

C++ code

============================================================================================

#include <iostream>

#include <fstream>

using namespace std;

//constants

const int CAP = 100;

//function prototypes

bool openFile(ifstream &);

void readData(ifstream &, int [], int &);

void printData(const int [], int);

void sum(const int[], int);

void removeItem(int[], int &, int);

int main()

{

ifstream inFile;

int list[CAP], size = 0;

if (!openFile(inFile))

{

cout << "Program terminating!! File not found!" << endl;

return -1;

}

//read the data from the file

readData(inFile, list, size);

inFile.close();

cout << "Data in file:" << endl;

printData(list, size);

//remove a few items

removeItem(list, size, 9);

printData(list, size);

removeItem(list, size, 200);

printData(list, size);

removeItem(list, size, 15);

printData(list, size);

//call the sum function

sum(list, size);

//end program

cin.ignore(100, '\n');

cout << "Press any key to continue...";

getchar();

return 0;

}

//function to open file

bool openFile(ifstream &inFile)

{

inFile.open("numbers.txt");

if (!inFile)

{

return false;

}

return true;

}

//reads the data from the file

void readData(ifstream &inFile, int list[], int &size)

{

while (!inFile.eof())

{

inFile >> list[size++];

}

}

//print the contents of the array

void printData(const int list[], int size)

{

for (int i = 0; i < size; i++)

{

cout << list[i] << endl;

}

cout << endl;

}

//remove an item (delNum) and return the number removed to main. If number does not exist, return -1.

void removeItem(int list[], int &size, int delNum)

{
   //insert code here
int loc=-1;
int i;
//find if items is present in list or not
for (i = 0; i < size; i++)
{
   if(list[i]==delNum)
   {
       loc=i;
       break;
   }
}

if(loc!=-1)
{
   for(i=loc;i<size-1;i++)
   {
       list[i]=list[i+1];
   }
   size=size-1;
}

}


//count the even numbers in the list and output in this function

void sum(const int list[], int size)

{

int sum = 0,n=0;
for (int i = 0; i < size; i++)
{
if(list[i] %2 == 0)
{
   sum = sum + list[i];
   n++;
}


}
cout <<"even numbers: "<< n <<" sum: " << sum << endl;

}

============================================================================================

Output

Add a comment
Answer #2

It seems that you have provided a C++ code that reads data from a file, manipulates an array, and performs some calculations. However, there are a couple of issues in the code:

  1. In the removeItem function, the logic is not correct for removing an item from the array. The current code is comparing elements of the array with delNum, and if the element is less than delNum, it assigns delNum to the element, which doesn't make sense. To remove an element from the array, you should shift all the elements after the one to be removed to the left.

  2. In the sum function, the variable n is used to count the even numbers in the list. However, it is declared inside the loop, so it will always start from 0 at each iteration. To count the even numbers, you should declare n outside the loop and only increment it when an even number is encountered.

Here's an updated version of the code with the issues fixed:

cppCopy code#include <iostream>#include <fstream>using namespace std;// Constantsconst int CAP = 100;// Function prototypesbool openFile(ifstream &);void readData(ifstream &, int[], int &);void printData(const int[], int);void removeItem(int[], int &, int);void sum(const int[], int);int main(){
    ifstream inFile;    int list[CAP], size = 0;    if (!openFile(inFile))
    {
        cout << "Program terminating!! File not found!" << endl;        return -1;
    }    // Read the data from the file
    readData(inFile, list, size);
    inFile.close();

    cout << "Data in file:" << endl;    printData(list, size);    // Remove a few items
    removeItem(list, size, 9);    printData(list, size);    removeItem(list, size, 200);    printData(list, size);    removeItem(list, size, 15);    printData(list, size);    // Call the sum function
    sum(list, size);    // End program
    cin.ignore(100, '\n');
    cout << "Press any key to continue...";    getchar();    return 0;
}// Function to open the filebool openFile(ifstream &inFile){
    inFile.open("numbers.txt");    if (!inFile)
    {        return false;
    }    return true;
}// Reads the data from the filevoid readData(ifstream &inFile, int list[], int &size){    while (!inFile.eof())
    {
        inFile >> list[size++];
    }
}// Print the contents of the arrayvoid printData(const int list[], int size){    for (int i = 0; i < size; i++)
    {
        cout << list[i] << endl;
    }
    cout << endl;
}// Remove an item (delNum) from the arrayvoid removeItem(int list[], int &size, int delNum){    int i;    for (i = 0; i < size; i++)
    {        if (list[i] == delNum)
        {            break;
        }
    }    if (i < size)
    {        // Shift elements after the element to be removed to the left
        for (int j = i; j < size - 1; j++)
        {
            list[j] = list[j + 1];
        }
        size--;
    }
}// Count the even numbers in the list and output the sumvoid sum(const int list[], int size){    int sum = 0, n = 0;    for (int i = 0; i < size; i++)
    {
        sum = sum + list[i];        if (list[i] % 2 == 0)
        {
            n++;
        }
    }
    cout << "Even numbers: " << n << " Sum: " << sum << endl;
}

Please note that the provided code assumes that the file "numbers.txt" exists and contains the data to be read into the array. Additionally, the code performs basic operations like reading data, printing data, removing items from the array, and calculating the sum of elements in the array. You may need to provide the file "numbers.txt" with the desired input data before running the program.

answered by: Hydra Master
Add a comment
Know the answer?
Add Answer to:
#include <iostream> #include <fstream> using namespace std; //constants const int CAP = 100; //function prototypes bool...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • //This program is your final exam. //Please fill in the functions at the bottom of the...

    //This program is your final exam. //Please fill in the functions at the bottom of the file. (evenCount and insertItem) //DO NOT CHANGE ANYTHING ELSE. //main has all the code needed to test your functions. Once your functions are written, please build and make sure it works fine //Note that in this case, the list is not sorted and does not need to be. Your goal is to insert the number in the given position. #include <iostream> #include <fstream> using...

  • //This program is your final exam. //Please fill in the functions at the bottom of the...

    //This program is your final exam. //Please fill in the functions at the bottom of the file. (evenCount and insertItem) //DO NOT CHANGE ANYTHING ELSE. //main has all the code needed to test your functions. Once your functions are written, please build and make sure it works fine //Note that in this case, the list is not sorted and does not need to be. Your goal is to insert the number in the given position. #include <iostream> #include <fstream> using...

  • This is the creatList and printList function #include <iostream> #include <fstream> using namespace std; struct nodeType...

    This is the creatList and printList function #include <iostream> #include <fstream> using namespace std; struct nodeType {    int info;    nodeType *link;    nodeType *next;    double value; }; void createList(nodeType*& first, nodeType*& last, ifstream& inf); void printList(nodeType* first); int main() {    nodeType *first, *last;    int num;    ifstream infile;    infile.open("InputIntegers.txt");    createList(first, last, infile);    printList(first);    infile.close();    system("pause");    return 0; } void createList(nodeType*& first, nodeType*& last, ifstream& infile) {    int number;...

  • CODES: main.cpp #include <iostream> #include <string> #include "ShoppingCart.h" using namespace std; char PrintMenu() { char answer;...

    CODES: main.cpp #include <iostream> #include <string> #include "ShoppingCart.h" using namespace std; char PrintMenu() { char answer; cout << "MENU" << endl; cout << "a - Add item to cart" << endl; cout << "d - Remove item from cart" << endl; cout << "c - Change item quantity" << endl; cout << "i - Output items' descriptions" << endl; cout << "o - Output shopping cart" << endl; cout << "q - Quit" << endl << endl; while (true) {...

  • #include <iostream> using namespace std; const int SIZE = 10; void displayGreaterThan(int[], int); void displaySmallerThan(int[],int); void...

    #include <iostream> using namespace std; const int SIZE = 10; void displayGreaterThan(int[], int); void displaySmallerThan(int[],int); void displayArrayContent(int[]); void displayLargestValue(int[]); void displaySmallestValue(int[]); int main(){    int number;    int numbers[SIZE] = {9,1,90,98,53,22,76,29,37,65}; cout <<"Enter a number: "; cin >> number; cout << endl;    displayGreaterThan(numbers,number); cout << endl; displaySmallerThan(numbers,number); cout << endl; displayArrayContent(numbers); cout << endl; displayLargestValue(numbers); cout << endl; displaySmallestValue(numbers); cout << endl;    return 0;       } void displayGreaterThan(int value[],int num){ cout << " All larger value(s)than" <<...

  • #include "stdafx.h" #include <iostream> using namespace std; class dateType {    private:        int dmonth;...

    #include "stdafx.h" #include <iostream> using namespace std; class dateType {    private:        int dmonth;        int dday;        int dyear;       public:       void setdate (int month, int day, int year);    int getday()const;    int getmonth()const;    int getyear()const;    int printdate()const;    bool isleapyear(int year);    dateType (int month=0, int day=0, int year=0); }; void dateType::setdate(int month, int day, int year) {    int numofdays;    if (year<=2008)    {    dyear=year;...

  • Answer this in c++ #include <iostream> #include <fstream> #include <string> using namespace std; class Person {...

    Answer this in c++ #include <iostream> #include <fstream> #include <string> using namespace std; class Person { public: Person() { setData("unknown-first", "unknown-last"); } Person(string first, string last) { setData(first, last); } void setData(string first, string last) { firstName = first; lastName = last; } void printData() const { cout << "\nName: " << firstName << " " << lastName << endl; } private: string firstName; string lastName; }; class Musician : public Person { public: Musician() { // TODO: set this...

  • C++ #include <iostream> using namespace std; bool checkinventoryid(int id) {    return id > 0; }...

    C++ #include <iostream> using namespace std; bool checkinventoryid(int id) {    return id > 0; } bool checkinventoryprice(float price) {    return price > 0; } void endProgram() {    system("pause");    exit(0); } void errorID(string str) {    cout << "Invalid Id!!! " << str << " should be greater than 0" << endl; } void errorPrice(string str) {    cout << "Invalid Price!!!" << str << " should be greater than 0" << endl; } int inputId() {...

  • Find and fix errors #include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int MIN...

    Find and fix errors #include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int MIN = 1; const int MAX = 10; int getRandom(int low, int high); int main() {    int random_num = 0; int player_num; int tries; int seed = static_cast<int>(time(0)); bool guessed = false;    srand(seed); // call the getRandom function below       tries = 4; while ( tries > 0 && !guessed ) { cout << "Enter a number within the range 1 to...

  • #include <iostream> using namespace std; bool binarySearch(int arr[], int start, int end, int target){ //your code...

    #include <iostream> using namespace std; bool binarySearch(int arr[], int start, int end, int target){ //your code here } void fill(int arr[], int count){ for(int i = 0; i < count; i++){ cout << "Enter number: "; cin >> arr[i]; } } void display(int arr[], int count){ for(int i = 0; i < count; i++){ cout << arr[i] << endl; } } int main() { cout << "How many items: "; int count; cin >> count; int * arr = new...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT