Categories
Programming

C++ Overloading Functions 1

Functions can be overloaded when they have different types of arguments. Write a pair of functions cube which return the cube of their arguments. The first takes an int, the other a double.

Examine the tester program to see how the functions are used.

cube.cpp

#include "cube.h"
using namespace std;
   // Write your functions here

double cube(int a)
{
   double result{0};
   result = pow(a, 3);
   return result;
}

double cube(double b)
{
   double result{0};
   result = pow(b, 3);
   return result;
}

cube.h

#ifndef CUBE_H
#define CUBE_H
#include <cmath>

double cube(int a);
double cube(double b);

#endif

Tester.cpp

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

#include "cube.h"

int main()
{
   cout << "cube(2.5): " << cube(2.5) << endl;
   cout << "Expected: 15.625" << endl;
   cout << "cube(7): " << cube(7) << endl;
   cout << "Expected: 343" << endl;
   cout << "cube(4.7): " << cube(4.7) << endl;
   cout << "Expected: 103.82300000000002" << endl;
   cout << "cube(6.0): " << cube(6.0) << endl;
   cout << "Expected: 216.0" << endl;
   cout << "cube(5): " << cube(5) << endl;
   cout << "Expected: 125" << endl;
   cout << "cube(6): " << cube(6) << endl;
   cout << "Expected: 216" << endl;
}

Functions can be overloaded on the types of their arguments, or on the number of arguments. Write a pair of functions product which return the product of their arguments. The first takes two, and the second takes three.

Examine the tester program to see how the functions are used.

overload.cpp

#include "overload.h"

   // Write your functions here

double product(double a, double b)
{
   double result{0};
   result = a * b;
   return result;
}

double product(double a, double b, double c)
{
   double result{0};
   result = a * b * c;
   return result;
}

overload.h

#ifndef OVERLOAD_H
#define OVERLOAD_H

#include <string>

double product(double a, double b);
double product(double a, double b, double c);

#endif

Tester.cpp

#include <iostream>
using namespace std;

#include "overload.h"

int main()
{
   // 2 arguments
   cout << "product(8.6, 9.3): " << product(8.6, 9.3) << endl;
   cout << "Expected: 79.98" << endl;
   
   // 3 arguments
   cout << "product(5.7, 1.5, 6.6): " << product(5.7, 1.5, 6.6) << endl;
   cout << "Expected: 56.43" << endl;
}

Ken Tank Company Ltd manufactures water containers of different shapes. The most common containers include spherical, rectangular and cylindrical tanks. Write three overloaded volume() functions to compute the different volumetric capacities of the three containers. All parameters will be of type double.

Hint:

  • Volume of a cylinder: PI * r2 * h
  • Volume of a sphere: 43 * PI * r2
  • Volume of rectangular tank: w * h * l

Examine the tester program to see how the functions are used.

tanks.cpp

#include "tanks.h"
using namespace std;

// sphere
double volume(double a)
{
   double result{0};
   result = (4/3.0) * PI * pow(a, 2);
   return result;
}

// cylinder
double volume(double a, double b)
{
   double result{0};
   result = PI * pow(a, 2) * b;
   return result;
}

//rectangular tank
double volume(double a, double b, double c)
{
   double result{0};
   result = a * b * c;
   return result;
}

tanks.h

#include <cmath>
#ifndef TANKS_H
#define TANKS_H

const double PI{acos(-1.0)};

double volume(double a);
double volume(double a, double b);
double volume(double a, double b, double c);

#endif

Tester.cpp

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

#include "tanks.h"

int main()
{
   cout << fixed;
   // Sphere
   cout << "Sphere with a radius 4.1: " << volume(4.1) << endl;
   cout << "Expected: 70.41356334245921" << endl << endl;
   
   // Cylinder
   cout << "Cylinder, r=4.4, h=13.6: " << volume(4.4, 13.6) << endl;
   cout << "Expected: 827.1687793195783" << endl << endl;

   // Rectangular tank
   cout << "Rectangular tank 11.3x6.5x9.1: " << volume(11.3, 6.5, 9.1) << endl;
   cout << "Expected: 668.395" << endl;
}

Write a pair of overloaded functions named indexOf(). See the tester to see how they are the two functions are used.

util.cpp

#include <string>
using namespace std;
#include "util.h"

const size_t NOT_FOUND = string::npos;

int indexOf(const string& str, const char& c)
{
   int result{0};
   size_t pos = str.find(c);
   result = (pos == NOT_FOUND)? -1: pos;
   return result;
}

int indexOf(const string& str, const string& s)
{
   int result{0};
   size_t pos = str.find(s);
   result = (pos == NOT_FOUND)? -1: pos;
   return result;
}

util.h

#include <string>
#ifndef UTIL_H
#define UTIL_H

/**
    @file util.h
    @author
    @version CS 150 Spring 2021
*/

int indexOf(const std::string& str, const char& c);
int indexOf(const std::string& str, const std::string& s);

#endif

Tester.cpp

#include <iostream>
using namespace std;

#include "util.h"

int main()
{
    cout << indexOf("provincial", "nci") << endl;
    cout << "Expected: 5" << endl;
    cout << indexOf("corpus", 'u') << endl;
    cout << "Expected: 4" << endl;
    cout << indexOf("banally", "al") << endl;
    cout << "Expected: 3" << endl;
    cout << indexOf("cyclotrons", "rx") << endl;
    cout << "Expected: -1" << endl;
}

Categories
Programming

C++ Simple Math

Now that you’ve traced through using the while loop to count the digits in an integer, why don’t you try summing the digits?

#include <iostream>
using namespace std;

int main()
{
   int n = 853269; 
   int sum = 0; 
   int temp = n;
   while(temp > 0)
   {
      sum += temp % 10;
      temp = temp / 10;
   }
cout << "The sum of the digits in " << n << " is " << sum << endl;
}

Suppose we add $100 to a checking account in year 1, $200 in year 2, $300 in year 3, and so on. The account earns no interest. After how many years will the balance reach a given target? Modify the program below to produce the answer.

#include <iostream>

using namespace std;

int main()
{  
   double balance = 0;
   int year = 0;

   cout << "Target: " << endl;
   double target; 
   cin >> target;

   // Add $100 in year 1, $200 in year 2, ..., until the 
   // target has been reached

   while (balance < target)
   {  
      year++;
      double amount = 100 * year;
      balance = balance + amount;
   }
   
   cout << "Year: " << year << endl;
   cout << "Balance: " << balance << endl;
   
   return 0;
}

The sum of the reciprocals 1 + 1/2 + 1/3 + 1/4 + … is infinite. Write a program that reads in a target and finds the first n such that 1 + 1/2 + 1/3 + … + 1/n > target.

#include <iostream>

using namespace std;

int main()
{
   double sum = 0;
   int n = 0;

   cout << "Target: " << endl;
   double target; 
   cin >> target;

   while (sum <= target)
   {  
      sum += 1.0/++n;
   }

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

   return 0;
}

Write a while loop that prints all powers of 2 that are less than a given number n. For example, if n is 100, print 1 2 4 8 16 32 64.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
   cout << "n: " << endl;
   int n; 
   cin >> n;
   int sum{0}, power{0};
   
   while (pow(2, power) < n)
   {
      
      sum = pow(2, power);
      cout << sum << " ";
      ++power;
   }
   cout << endl;
    
   return 0;
}

Write a while loop that prints all positive numbers that are divisible by 10 and less than a given number n. For example, if n is 100, print 10 20 30 40 50 60 70 80 90.

#include <iostream>

using namespace std;

int main()
{
   cout << "n: " << endl;
   int n; 
   cin >> n;
   int count{1};
   
   while (count < n)
   {
      if(count % 10 == 0)
      {
         cout << count << " ";
      }
      ++count;
   }
   cout << endl;
    
   return 0;
}

Complete this program, prompting the user to to enter two positive numbers a and b so that a is less than b.

#include <iostream>
using namespace std;

int main()
{
   int a, b;

   // Keep prompting the user until the input is correct
   do
   {
      cout << "Enter two positive integers, the first smaller than the second." 
         << endl;
      cout << "First: " << endl;
      cin >> a;
      cout << "Second: " << endl;
      cin >> b;
   }while(b < a || a == 0);
   
   // Only print this when the input is correct
   cout << "You entered " << a << " and " << b << endl;
}

Write a do loop that reads integers and computes their sum. Stop when a zero is read or the when the same value is read twice in a row. For example, if the input is 1 2 3 4 4, then the sum is 14 and the loop stops.

#include <iostream>

using namespace std;

int main()
{
   int previous;
   int sum = 0;
   int input = 0;
   do
   {
      previous = input;
      cin >> input;
      sum += input;
   }
   while (input != previous && input != 0);
   cout << "Sum: " << sum << endl;
   return 0;
}
Categories
Programming

C++ String Manipulation

Unlike Java, the C++ string class has no toLowerCase member function. Write a regular function toLowerCase. You may use any loop you like. You may also use the character functions in the <cctype> header.

#include <string>
#include <cctype>
using namespace std;

string toLowerCase(const string& s)
{
   string result;
   for(int i = 0; i < s.size(); ++i)
   {
      result += tolower(s.at(i));
   }
   return result;
}

Unlike Java, the C++ string class does not have the member functions startsWith or endsWith. Write your own function:

    endsWith(const string& a, const string& b)

which returns true if a ends with b. You do not need a loop for this problem, but you may use one if you like.

#include <string>
using namespace std;

   bool endsWith(const string& a, const string& b)
   {
      bool result = false;
      auto alen = a.size();
      auto blen = b.size();
      int pos{0};
      if(a == b)
      {
         result = true;
         return result;
      }
      else if(alen > blen)
      {
         pos += (alen - blen);
         string temp = a.substr(pos);
         if(temp == b)
         {
            result = true;
         }
         else
         {
            result = false;
         }
         return result;
      }
      else
      {
         result = false;
         return result;
      }
   }

It’s raining frogs and fleas. Write a function that tells you if the number of frogs in a sentence is the same as the number of fleas.

#include <string>
#include <cctype>
using namespace std;

bool fleasNFrogs(const string& s)
{
   bool result{false};
   int frogCount{0}, fleaCount{0};
   for(int i = 0; i < s.size(); ++i)
   {
      if(i + 3 < s.size())
      {
         if(s.at(i) == 'f')
         {
            if(s.at(i + 1) == 'r' && s.at(i + 2) == 'o' && s.at(i + 3) == 'g')
            {
               frogCount += 1;
            }
         }
      }
   }
   
   for(int i = 0; i < s.size(); ++i)
   {
      if(i + 3 < s.size())
      {
         if(s.at(i) == 'f')
         {
            if(s.at(i + 1) == 'l' && s.at(i + 2) == 'e' && s.at(i + 3) == 'a')
            {
               fleaCount += 1;
            }
         }
      }
   }
   
   if(frogCount == fleaCount)
   {
      result = true;
   }
   return result;
}

Given a string, return a new string where there are i copies of each individual character, where i is the loop index. (That is there will be 0 copies of the first character, 1 of the second, and so on.)

#include <string>
using namespace std;

string expando(const string& s)
{
   string result;
   auto len = s.size();
   auto j{0};
   for(auto i = 0; i < len; ++i)
   {
      j = 0;
      while(j < i)
      {
         result += s.at(i);
         j++;
      }
   }
   return result;
}

Return the number of times that the string "code" appears anywhere in the given string, except, we’ll accept any letter for the 'd', so "cope" and "cooe" both count.

#include <string>
using namespace std;

int countCode(const string& s)
{
   int count{0};
   for(int i = 0; i < s.size(); ++i)
   {
      if(i + 3 < s.size())
      {
         if(s.at(i) == 'c' && s.at(i+1) == 'o' &&  s.at(i+3) == 'e' )
         {
            ++count; 
         }
      }
   }
return count;
}

Write a function named addCommas that accepts a string representing a number and returns a new string with a comma at every third position, starting from the right. For example:

addCommas("12345678") -> "12,345,678"

strings.cpp

#include <string>
using namespace std;

string addCommas(const string& s)
{
   string result = s;
   auto length = s.size();
   if(length < 4)
   {
      result = s;
   }
   else
   {
      int inserted = 0;
      int i = length % 3;
      if(i == 0)
      {
        i = 3;
      }
      for(; i < length + inserted; i = i + 4)
      {
        result.insert(i, ",");
        inserted++;
      }
   }
   return result;
}

strings.h

#include <string>
#ifndef STRINGS_H
#define STRINGS_H
std::string addCommas(const std::string& s);
#endif

client.cpp

#include <iostream>
using namespace std;

#include "strings.h"

int main()
{
    cout << "What number to process: ";
    string n;   // note string input
    cin >> n;
    
    cout << addCommas(n) << endl;
}
Categories
Programming

C++ Grids Distance

In city street grids, intersections are often defined by two integers, counting the position of horizontal and vertical streets (sometimes called streets and avenues). Imagine traveling from position (h1v1) to (h2v2). How many blocks do you traverse?

Even though there are many possible routes, the distance only depends on the differences h2 – h1 and v2 – v1. However, you need to take the absolute value because the differences might be negative.

Complete the following program that prints the number of blocks traveled, given the origin and destination of the trip (which will change as your code is tested).

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
   // Other values will be set during testing.
   // Your program needs to work with any coordinates.

   int h1 = 3; 
   int v1 = 4; 
   int h2 = 4; 
   int v2 = 4; 
   
   // Compute the distance between the two positions
   int distance = abs(h2 - h1);
   distance += abs(v2 - v1);
   cout << "Distance: " << distance << endl;

   return 0;
}
Categories
Programming

C++ for loops

Use a range loop to count the number of vowels in a string.

#include <string>
using namespace std;

int numVowels(const string& s)
{
   int vowels{0};
   for(int i = 0; i < s.size(); ++i)
   {
      if(i + 3 < s.size())
      {
         if(s.at(i) == 'c' && s.at(i+1) == 'o' &&  s.at(i+3) == 'e' )
         {
            ++count; 
         }
      }
   }
return count;
}

Complete the function using a range loop. The function should return a single string with all spaces replaced with '+'.

#include <string>
using namespace std;

string despace(const string& s)
{
   string result;
   for(char c : s)
   {
      if(c == ' ')
      {
         c = '+';
      }
      result += c;
   }
   return result;
}

Complete the countWords function using a range loop. The function should return the number of words in a string. Words are separated by whitespace (space, newline or tab). You may use the character classification functions from <cctype>.

#include <string>
using namespace std;

int countWords(const string& s)
{
   int words{0};
   int temp{0};
   for(char c : s)
   {
      if(isspace(c))
      {
         temp = 0;
      }
      else if(temp == 0)
      {
         temp = 1;
         words++;
      }
   }
   return words;
}

Complete the function using a range loop. Given a string, return the sum of the digits 0-9 that appear in the string, ignoring all other characters. Return 0 if there are no digits in the string.

#include <string>
using namespace std;

int sumDigits(const string& s)
{
   int sum{0};
   for(char c : s)
   {
      if(isdigit(c))
      {
         sum += c - 48;
      }
   }
   return sum;
}
Categories
Programming

C++ First Last Name

Write a program that reads in the first and last name of a person and formats the full name as the last name, followed by a comma, a space, and the first name. For example:

Please enter your first and last name on the next line.
Harry Morgan
Morgan, Harry
#include <iostream>
#include <string>

using namespace std;

int main()
{
   cout << "Please enter your first and last name on the next line." << endl;
   string name;
   getline(cin, name);
   size_t pos = name.find(" ");
   string last_name = name.substr(pos);
   string first_name = name.substr(0, pos);
   string full_name = last_name + ", " + first_name;
   cout << full_name.substr(1) << endl;
   return 0;
}

Write a sequence of input statements to read a user’s first, middle, and last name and then print a monogram. For instance, if the user enters Franklin Delano Roosevelt, then the program prints FDR.

#include <iostream>
#include <string>
using namespace std;

int main()
{
   cout << "Enter your first, middle, and last name: ";
   string first;
   string middle;
   string last;
   cin >> first >> middle >> last;
   cout << first.front() <<  middle.front() << last.front();
   return 0;
}

Write the function processName(). It’s input is a full name in the form (First MI. Last). Your job is to use string member functions to break the name into the first name, last name and middle initial, and return the processed name in the form “Last, First MI.”.

Use the string member functions substr()find()rfind()find_first_not_of()find_last_not_of() and at() to solve this problem.

You may assume:

  • that every name will have exactly one word for the first and last names and a single character, followed by a period for the middle initial.
  • There will be at least one space separating each of the portions of the input name, but there may be more spaces.
#include <string>
using namespace std;

/**
    Processes a name containing First MI. Last.
    @param s the name formatted as described.
    @return the name processed to "Last, First MI."
    Include the quotes in the returned name.
*/
string processName(const string& s)
{
   string result;
   size_t pos1 = s.find_first_not_of(' ');
   size_t pos2 = s.find_last_not_of(' ');
   string clean = s.substr(pos1, pos2 - pos1 + 1);
   size_t pos3 = clean.find(' ');
   string first = clean.substr(0, pos3);
   string last = clean.substr(clean.rfind(' ') + 1);
   string middle = clean.substr(clean.find(' '), clean.rfind(' ') - clean.find(' '));
   middle = middle.substr(middle.find_first_not_of(' '), middle.find_last_not_of(' ') - middle.find_first_not_of(' ') + 1);
   result = last + ", " + first + " ";
   result += middle;
   return result;
}
Categories
Programming

C++ Ballon Diameter

Inflate the balloon so that the diameter grows by an inch, and display the amount the volume has grown. Repeat that step: grow the diameter by another inch and show the growth of the volume.

Here is a typical program run:

Diameter: 10
Increase: 173
Increase: 208

Match the formatting of the sample program run in your solution.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
   const double PI = 3.14159265358979323846;   
   double diameter;
   cout << "Diameter: ";
   cin >> diameter;
   double volume1 = PI * diameter * diameter * diameter / 6;
   diameter++;
   double volume2 = PI * diameter * diameter * diameter / 6;
   double growth = volume2 - volume1;
   cout << "Increase: " << setprecision(0) << fixed << growth << endl;
   diameter++;
   double volume3 = PI * diameter * diameter * diameter / 6;
   growth = volume3 - volume2;
   cout << "Increase: " << fixed << growth << endl;
   
   return 0;
}