Question

C++ Modify this program (or create your own) so that it performs the following tasks: 1....

C++

Modify this program (or create your own) so that it performs the following tasks: 1. Insert the numbers into the list in sorted order (ascending). This will require you to keep the list sorted as you continue to insert new numbers. 2. When adding a new number, first check to see whether it is larger than the last number currently in the list. If it is, add it directly to the end of the list, i.e., do not traverse the list to get to the end of the list and then add it. Should this improve the average performance of the list building portion of your code? If so, when? Be prepared to discuss this in class. 3. If the new number is less than the last number in the list, start at the head of the list and scan the list until you find the next larger number. Insert your new number into the list at that point. 4. Check for duplicates; do not add a number to the list more than once. 5. After inserting all the random numbers, count the number of elements (numbers) in the list and report it. 6. Print the list of numbers to the console, 5 numbers to a row. 7. Add a function that will search for a specified number. Search for a minimum of 3 different numbers and report whether the number was found or not.

#include <iostream>
#include <iomanip> //setw
using namespace std;


// ----- globals ----- //
const int maxNumsInaRow = 5; //number of numbers to print in a single row
const int numsToGenerate = 25; //number of random numbers to generate
const int maxValueToGenerate = 50; //max value of a number to generate

// ----- basic utility routines - these are shown for examples only ----- //

bool dbgprinting = false; //set to true to see all debugging msgs

void dprint(string msg,int val) {
   if (dbgprinting)
      cout << msg << " " << val << endl;
}//dprint


void dprint(string msg,string str2) {
   if (dbgprinting)
      cout << msg << " " << str2 << endl;
}//dprint


void show(string msg,string msg2="") {
   cout << msg << " " << msg2 << endl;
} //show

void show(string msg,int num) {
   cout << msg << " " << num << endl;
} //show

void ckError(bool condition,string errorString) {
   if (condition) {
      cout << errorString << endl;
      system("pause");
   }
} //ckError

void line() {
   cout << "---------------------------------------" << endl;
} //line


// --------------------------------------------------------//
struct Number { //this is the main data structure for this program
   int numValue;; //the number's value
   Number *nextNumber; //points to next Number in the list, or nullptr if none
};

// declare the necessary pointers for the Number list
Number *listHead; //always points to the first element in the list
Number *listTail; //always points to the last element in the list
// --------------------------------------------------------//


int countNumbersInList() {
   int count=0;
   Number* aNumberPtr = listHead;
   do {
      dprint("counting ",aNumberPtr->numValue);
      count++;
      aNumberPtr = aNumberPtr->nextNumber;
   } while (aNumberPtr != nullptr);
   return count;
} //countNumbersInList


void showAllNumbers() {
        static int rowLength = 0; //this is just for pretty-printing
   Number *nextNum; //for traversing the Number list

   line();
   if (listHead == nullptr) {
      show("There are no numbers in the list");
      return;
   };

   show("Number of numbers in the list = ",countNumbersInList());
   nextNum = listHead; //ok, now let's show each Number
   do {
      cout << setw(6) << nextNum->numValue;
      rowLength++;
      if ((rowLength % maxNumsInaRow) == 0)
                        cout << endl; //advance to next line
      nextNum = nextNum->nextNumber;
   } while (nextNum != nullptr);
   cout << endl;
} //showAllNumbers


// this routine doesn't insert the numbers in numeric order - fix it
void addNumberToList(int numberToAdd) {
   dprint("Adding a new Number:",numberToAdd);
   Number* newNum;
   newNum = new Number;
   newNum->numValue = numberToAdd;
   newNum->nextNumber = listHead;
   listHead = newNum;
} //addNumberToList


bool findANumber(int theNumberToFind) {
   dprint("Entering findANumber ",theNumberToFind);
   Number *curNumber = listHead;
   while (curNumber != nullptr) {
      if (curNumber->numValue == theNumberToFind) {
         show("Yes, we found the Number:",theNumberToFind);
         return true;
      }
      curNumber = curNumber->nextNumber;
   }
   show("Sorry, we couldn't find the Number:",theNumberToFind);
   return false;
} //findANumber


// ----- main function ----- //
main() {

   srand(time(0));

   //define an empty list
   listHead = nullptr;
   listTail = nullptr;

   showAllNumbers(); //there should be none

        //generate some random numbers and insert them into the list
   for (int n=0; n<numsToGenerate; n++)
      addNumberToList((rand() % maxValueToGenerate)+1);

   showAllNumbers(); //there should be some now, but not in order :-(

   //now search for some numbers, no need to count duplicates
   line();
   findANumber(16);
   findANumber(32);
   findANumber(-24); //note that we can search for any number

   return 0;
} //main
0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have made few changes in your code and have written the code for addNumberToList.

Note: While initialising the Struct data structure, it is a better practise to initialise the pointer as NULL. This was the reason why your countNumbersInList() and showAllNumbers() were having segmentation fault.

#include <iostream>
#include <iomanip> //setw
using namespace std;


// ----- globals ----- //
const int maxNumsInaRow = 5; //number of numbers to print in a single row
const int numsToGenerate = 25; //number of random numbers to generate
const int maxValueToGenerate = 50; //max value of a number to generate

// ----- basic utility routines - these are shown for examples only ----- //

bool dbgprinting = false; //set to true to see all debugging msgs

void dprint(string msg,int val) {
if (dbgprinting)
cout << msg << " " << val << endl;
}//dprint


void dprint(string msg,string str2) {
if (dbgprinting)
cout << msg << " " << str2 << endl;
}//dprint


void show(string msg,string msg2="") {
cout << msg << " " << msg2 << endl;
} //show

void show(string msg,int num) {
cout << msg << " " << num << endl;
} //show

void ckError(bool condition,string errorString) {
if (condition) {
cout << errorString << endl;
system("pause");
}
} //ckError

void line() {
cout << "---------------------------------------" << endl;
} //line


// --------------------------------------------------------//
struct Number { //this is the main data structure for this program
int numValue;; //the number's value
Number *nextNumber = NULL; //points to next Number in the list, or nullptr if none
};

// declare the necessary pointers for the Number list
Number *listHead; //always points to the first element in the list
Number *listTail; //always points to the last element in the list
// --------------------------------------------------------//


int countNumbersInList() {
int count=0;
Number* aNumberPtr = listHead;
do {
dprint("counting ",aNumberPtr->numValue);
count++;
aNumberPtr = aNumberPtr->nextNumber;
} while (aNumberPtr != NULL);
return count;
} //countNumbersInList


void showAllNumbers() {
static int rowLength = 0; //this is just for pretty-printing
Number *nextNum; //for traversing the Number list

line();
if (listHead == NULL) {
show("There are no numbers in the list");
return;
}

show("Number of numbers in the list = ",countNumbersInList());
nextNum = listHead; //ok, now let's show each Number
do {
cout << setw(6) << nextNum->numValue;
rowLength++;
if ((rowLength % maxNumsInaRow) == 0)
cout << endl; //advance to next line
nextNum = nextNum->nextNumber;
} while (nextNum != nullptr);
cout << endl;
} //showAllNumbers


// this routine doesn't insert the numbers in numeric order - fixed it ;)
void addNumberToList(int numberToAdd) {
dprint("Adding a new Number:",numberToAdd);
Number* temp = new Number;
temp->numValue = numberToAdd;
if(listHead == NULL){
listHead = temp;
listTail = temp;
return;
}

if(numberToAdd > listTail->numValue){
listTail->nextNumber = temp;
listTail = temp;
return;
}
if(numberToAdd < listHead->numValue){
temp->nextNumber = listHead;
listHead = temp;
return ;
}
Number* temp1 = listHead;
Number* prev = temp1;
while(temp1->numValue <= numberToAdd && temp1 != NULL){
if(temp1->numValue == numberToAdd){
return;
}
prev = temp1;
temp1 = temp1->nextNumber;
}
prev->nextNumber = temp;
temp->nextNumber = temp1;
return;

} //addNumberToList


bool findANumber(int theNumberToFind) {
dprint("Entering findANumber ",theNumberToFind);
Number *curNumber = listHead;
while (curNumber != NULL) {
if (curNumber->numValue == theNumberToFind) {
show("Yes, we found the Number:",theNumberToFind);
return true;
}
curNumber = curNumber->nextNumber;
}
show("Sorry, we couldn't find the Number:",theNumberToFind);
return false;
} //findANumber


// ----- main function ----- //
main() {

srand(time(0));

//define an empty list
listHead = NULL;
listTail = NULL;

showAllNumbers(); //there should be none

//generate some random numbers and insert them into the list
for (int n=0; n<numsToGenerate; n++)
addNumberToList((rand() % maxValueToGenerate)+1);
  
showAllNumbers(); //there should be some now, and now in order ;)

//now search for some numbers, no need to count duplicates
line();
findANumber(16);
findANumber(32);
findANumber(-24); //note that we can search for any number

return 0;
}

Add a comment
Know the answer?
Add Answer to:
C++ Modify this program (or create your own) so that it performs the following tasks: 1....
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...

  • For the LinkedList class, create a getter and setter for the private member 'name', constructing your...

    For the LinkedList class, create a getter and setter for the private member 'name', constructing your definitions based upon the following declarations respectively: std::string get_name() const; and void set_name(std::string); In the Main.cpp file, let's test your getter and setter for the LinkedLIst private member 'name'. In the main function, add the following lines of code: cout << ll.get_name() << endl; ll.make_test_list(); ll.set_name("My List"); cout << ll.get_name() << endl; Output should be: Test List My List Compile and run your code;...

  • Please help fix my code C++, I get 2 errors when running. The code should be...

    Please help fix my code C++, I get 2 errors when running. The code should be able to open this file: labdata.txt Pallet PAG PAG45982IB 737 4978 OAK Container AYF AYF23409AA 737 2209 LAS Container AAA AAA89023DL 737 5932 DFW Here is my code: #include <iostream> #include <string> #include <fstream> #include <vector> #include <cstdlib> #include <iomanip> using namespace std; const int MAXLOAD737 = 46000; const int MAXLOAD767 = 116000; class Cargo { protected: string uldtype; string abbreviation; string uldid; int...

  • Hi there, I am working on a binary search tree code in c++. The program must...

    Hi there, I am working on a binary search tree code in c++. The program must store and update students' academic records, each node includes the student name, credits attempted, credits earned and GPA. I have made some progress with the code and written most of the functions in the .cpp file (already did the .h file) but i am struggling with what to put in the main and how to put an update part in the insert function. I...

  • Using C++ Use the below program. Fill in the code for the 2 functions. The expected...

    Using C++ Use the below program. Fill in the code for the 2 functions. The expected output should be: The:fox:jumps:over:the:fence.: The:fox:jumps:over:the:fence.: The:fox:jumps:over:the:fence.: The:fox:jumps:over:the:fence.: #include #include #include using namespace std; //Assume a line is less than 256 //Prints the characters in the string str1 from beginIndex //and inclusing endIndex void printSubString( const char* str1 , int beginIndex, int endIndex ) { } void printWordsInAString( const char* str1 ) { } int main() { char str1[] = "The fox jumps over the...

  • The following code is for Chapter 13 Programming Exercise 21. I'm not sure what all is...

    The following code is for Chapter 13 Programming Exercise 21. I'm not sure what all is wrong with the code written. I get errors about stockSym being private and some others after that.This was written in the Dev C++ software. Can someone help me figure out what is wrong with the code with notes of what was wrong to correct it? #include <cstdlib> #include <iostream> #include <iomanip> #include <fstream> #include <cassert> #include <string> using namespace std; template <class stockType> class...

  • Problem with C++ program. Visual Studio say when I try to debug "Run-Time Check Failure #2...

    Problem with C++ program. Visual Studio say when I try to debug "Run-Time Check Failure #2 - Stack around the variable 'string4b' was corrupted. I need some help because if the arrays for string4a and string4b have different sizes. Also if I put different sizes in string3a and string4b it will say that those arrays for 3a and 3b are corrupted. But for the assigment I need to put arrays of different sizes so that they can do their work...

  • Please zoom in so the pictures become high resolution. I need three files, FlashDrive.cpp, FlashDrive.h and...

    Please zoom in so the pictures become high resolution. I need three files, FlashDrive.cpp, FlashDrive.h and user_main.cpp. The programming language is C++. I will provide the Sample Test Driver Code as well as the codes given so far in text below. Sample Testing Driver Code: cs52::FlashDrive empty; cs52::FlashDrive drive1(10, 0, false); cs52::FlashDrive drive2(20, 0, false); drive1.plugIn(); drive1.formatDrive(); drive1.writeData(5); drive1.pullOut(); drive2.plugIn(); drive2.formatDrive(); drive2.writeData(2); drive2.pullOut(); cs52::FlashDrive combined = drive1 + drive2; // std::cout << "this drive's filled to " << combined.getUsed( )...

  • Modify PartTwo.cpp so that it is uses a vector, named vect, instead of an array. PartTwo.cpp...

    Modify PartTwo.cpp so that it is uses a vector, named vect, instead of an array. PartTwo.cpp Is posted here: // This program reads data from a file into an array. Then, it // asks the user for a number. It then compares the user number to // each element in the array, displays the array element if it is larger. // After looking at entire array, it displays the number of elements in the array larger // than the user...

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