This code is for recursive function practice. When I run the code, it stops at the "POWER" cout line, then my compiler shows a segmentation error. The function that follows the POWER line is supposed to recursively raise number "a" to the power of number "b". I'm not sure how to fix this, can anyone help?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**** Recursive backwards print, prints a string starting from last index to first*****/
void printReverse(string s, int i)
{
if(i < s.size())
{
printReverse(s.substr(1), i);
cout<<s[i];
}
else
{
return;
}
}
/**** Recursive power function, computes a^b, where b can be positive or negative*****/
int recPower(double a, int b)
{
int i = b; //i = b, so int a can be multiplied int b times
if (i == 0) //base
return 1;
else //multiply A by B, B times
{
a *= b;
return recPower(a, b); //recursive
i--; //decrement i until it equals 0
}
}
/**** Recursive string replace, replaces all instances of a character in a string with another character*****/
string recReplace(string s2, int i, char old, char neW)
{
if(s2[i] == old) //search for old char
{
i = neW; //replace it
i++; //iterate i
}
recReplace(s2, i, old, neW); //call function
return s2;
}
/**** Recursive list find > Searches if x exists in list, returns true if found, false otherwise*****/
int recListFind(vector<int> v, int i, int x)
{
if(v[i] == x)
{
cout << x << " exists in the vector."<<endl;
i++;
recListFind(v, i, x);
}
return true;
}
int main()
{
cout << "PRINT REVERSE" << endl;
cout << "----------" << endl;
string s1 = "hello world";
cout << "String: " << s1 << endl;
cout << "Reversed: ";
printReverse(s1, 0);
cout << endl;
/* Computes a^b (power function) */
cout << "POWER" << endl;
cout << "----------" << endl;
int a = 2, b = -3;
cout << a << "^" << b << " = ";
cout << recPower(a, b) << endl;
cout << endl;
/* Replaces a character in a string with a new one */
cout << "REPLACE" << endl;
cout << "----------" << endl;
string s2 = "-h-e-l-l-o-";
char oldChar = '-';
char newChar = ' ';
cout << "String: " << s2 << endl;
cout << "> Replace '" << oldChar << "' with '" << newChar << endl;
recReplace(s2, 0, oldChar, newChar);
cout << "String: " << s2 << endl;
cout << endl;
/* Searches for value in vector */
cout << "FIND" << endl;
cout << "----------" << endl;
int x = 7;
cout << "Does " << x << " exist in the vector? "; vector<int> v = {5, 1, 6, 7, 9};
cout << recListFind(v, 0, 7) << endl;
cout << endl;
return 0;
}
The issue is quite straight forward, you are doing the recPower function with b. In the function, if b is not 0, you call recPower with an unmodified value of b (whilst ever modifying a). This will always end up with infinite recursion which is going to overflow your stack.
A solution could be:
int recPower(double a, int b, int times) {
if (times == 0)
return a;
else
return b * recPower(a, b, --times);
}
int recPower(double a, int b) {
return recPower(a, b, b);
}
Even if you fix this, you have another problem. b can be negative, which based on your logic will continue to recurse while decrementing until it overflows and goes back to 0. You will cause this case with your first test case. You should think about the types that are allowed in this function, consider making them unsigned, or dealing explicitly with the negative b case.
Related
Im having trouble with this recursion code. Basically I want the computer to "guess" in as little steps as possible the number that I am thinking of. However, everything works except the final output. The bounds are fine, and it narrows down the guess until it asks me if the number im thinking of is say 16, if I input "=" it should output 16 instead it always outputs 50. Could anyone help me locate the error?
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
unsigned int search (unsigned int boundInf, unsigned int boundSup);
int main ()
{
int b;
b = search (1, 100);
cout << "Your number must be : " << b << endl;
}
unsigned int search (unsigned int boundInf, unsigned int boundSup)
{
string magnitude;
int b;
b = (boundSup + boundInf) / 2;
cout << "Is your number <, > or = to " << b << "? ";
cin >> magnitude;
if (magnitude == "<") {
cout << "Between " << boundInf << " and " << b << endl;
search (boundInf, b);
}
else if (magnitude == ">") {
cout << "Between " << b << " and " << boundSup << endl;
search (b, boundSup);
}
return b;
}
You forgot to change the value of b when going deeper into the recursive function, this can be easily fixed by changing the search function like so:
unsigned int search(unsigned int boundInf, unsigned int boundSup)
{
string magnitude;
int b;
b = (boundSup + boundInf) / 2;
cout << "Is your number <, > or = to " << b << "? ";
cin >> magnitude;
if (magnitude == "<")
{
cout << "Between " << boundInf << " and " << b << endl;
b = search(boundInf, b);
}
else if (magnitude == ">")
{
cout << "Between " << b << " and " << boundSup << endl;
b = search(b, boundSup);
}
return b;
}
I am a beginner at c++ programming, and this is only my second program. I am getting a consistent error of "expected unqualified-id before..." idk what it means and cannot solve it. This is on lines 21,27,29,33,35,38,40,43,45.48,54,56,59,61,64,66,70.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
int main ();
int a, b, c, x,y;
int discriminant;
double x1, x2;
int countdataisinvalid=0;
int countdataisvalid=0;
int countnolastterm=0;
int countonexvalue=0;
int countnomiddleterm=0;
int counttwoxterms=0;
while(!cin.eof)
{
a*x*x+b*x+c;
}
if (a==0),
countdataisinvalid++;
{
cout << "A is 0, data invalid." << endl;
}
else if, (discriminant < 0),
countdataisinvalid++;
{
cout << "The square is a negative number, data invalid." << endl;
}
else,
countdataisvalid++;
{
cout << " Data set is valid." << endl;
}
if (c==0),
countnolastterm++;
{
cout << "C is 0, there is no last term." << endl;
}
{
x1 = (-b + sqrt(b*b-4*a*c))/(2*a);
x2 = (-b - sqrt(b*b-4*a*c))/(2*a);
cout.precision(3);
}
if (x1==x2),
countonexvalue++;
{
cout << "Only one x value." << endl;
}
else, if (x1==-x2),
countnomiddleterm++;
{
cout << "There is no middle term." << endl;
}
else
counttwoxterms++;
{
cout << "There are two x values." << endl;
}
{
y = a*x1*x1+b*x1+c
y = a*x2*x2+b*x2+c
cout << "When x is " << x << "y is " << y << endl;
}
Your code contains too many errors. You should learn C++ again with writing simple programs.
At least this code compiles.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
int main ()
{ // use { to begin definition of function, not ;
// initialize ariables for in case the reading fails
int a = 0, b = 0, c = 0, x = 0, y = 0;
int discriminant = 0;
double x1 = 0, x2 = 0;
int countdataisinvalid=0;
int countdataisvalid=0;
int countnolastterm=0;
int countonexvalue=0;
int countnomiddleterm=0;
int counttwoxterms=0;
// you should read numbers instead of writing possibly infinite loop and meaningless statement
cin >> a >> b >> c >> x >> discriminant >> x1 >> x2;
if (a==0) // remove extra comma
{
countdataisinvalid++; // move this statement to right position
cout << "A is 0, data invalid." << endl;
}
else if (discriminant < 0) // remove extra commas
{
countdataisinvalid++; // move this statement to right position
cout << "The square is a negative number, data invalid." << endl;
}
else // remove extra comma
{
countdataisvalid++; // move this statement to right position
cout << " Data set is valid." << endl;
}
if (c==0) // remove extra comma
{
countnolastterm++; // move this statement to right position
cout << "C is 0, there is no last term." << endl;
}
{
x1 = (-b + sqrt(b*b-4*a*c))/(2*a);
x2 = (-b - sqrt(b*b-4*a*c))/(2*a);
cout.precision(3);
}
if (x1==x2) // remove extra comma
{
countonexvalue++; // move this statement to right position
cout << "Only one x value." << endl;
}
else if (x1==-x2) // remove extra commas
{
countnomiddleterm++; // move this statement to right position
cout << "There is no middle term." << endl;
}
else
{
counttwoxterms++; // move this statement to right position
cout << "There are two x values." << endl;
}
{
y = a*x2*x2+b*x2+c; // add semicolon and remove useless statement
cout << "When x is " << x << "y is " << y << endl;
}
return 0; // add a statement to return some value
} // add this as end of definition of function
I'm not quite sure why the answer for the larger string ("cat" and "dog") is not consistent. I was doing some things with Linked Lists and the use of templates. My curiosity got me to revise templates and function overloading. If anyone can explain what is going on, I would appreciate it.
Thank you.
#include <iostream>
using namespace std; // for the sake of simplicity. (otherwise, std::)
// Function overloading and the use of templates
// overloading the function larger
int larger(int, int);
char larger(char, char);
double larger(double, double);
string larger(string, string);
template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2);
int main() {
cout << endl;
cout << "Function Overloading" << endl;
cout << "larger(15, 27) = " << larger(15, 27) << endl;
cout << "larger('X', 'P') = " << larger('X', 'P') << endl;
cout << "larger(4.9, 3.2) = " << larger(4.9, 3.2) << endl;
cout << "larger(cat, dog) = " << larger("cat", "dog") << endl;
cout << endl;
cout << "Using the function template to find the larger of two items" << endl;
cout << "anyLarger(15, 27) = " << anyLarger(15, 27) << endl;
cout << "anyLarger('X', 'P') = " << anyLarger('X', 'P') << endl;
cout << "anyLarger(4.9, 3.2) = " << anyLarger(4.9, 3.2) << endl;
cout << "anyLarger(cat, dog) = " << anyLarger("cat", "dog") << endl;
cout << endl;
cout << "Compare two strings: cat, dog" << endl;
if ("cat" >= "dog") {
cout << "cat is greater than dog" << endl;
}
else {
cout << "dog is greater than cat" << endl;
}
cout << endl;
string strCat = "cat";
string strDog = "dog";
cout << "string strCat = cat" << endl;
cout << "string strDog = dog" << endl;
if (strCat >= strDog) {
cout << "strCat is greater than strDog" << endl;
}
else {
cout << "strDog is greater than strCat" << endl;
}
cout << endl;
} // end main
// Overloading larger
int larger(int x, int y) {
if (x >= y)
return x;
else
return y;
}
char larger(char a, char b) {
if (a >= b)
return a;
else
return b;
}
double larger(double p, double q) {
if (p >= q)
return p;
else
return q;
}
string larger(string y, string z) {
if (y >= z)
return y;
else
return z;
}
// Defining the template function
template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2)
{
if (parameter1 >= parameter2)
return parameter1;
else
return parameter2;
}
Here is the result after running the program.
Function Overloading
larger(15, 27) = 27
larger('X', 'P') = X
larger(4.9, 3.2) = 4.9
larger(cat, dog) = dog
Using the function template to find the larger of two items
anyLarger(15, 27) = 27
anyLarger('X', 'P') = X
anyLarger(4.9, 3.2) = 4.9
anyLarger(cat, dog) = cat
Compare two strings: cat, dog
cat is greater than dog
string strCat = cat
string strDog = dog
strDog is greater than strCat
==============================================
Update: Made some changes and used strcmp
#include <iostream>
#include <string.h>
using namespace std;
// Function overloading and the use of templates
// overloading the function larger
int larger(int, int);
char larger(char, char);
double larger(double, double);
string larger(string, string);
template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2);
int main(){
cout << endl;
cout << "// Function Overloading" << endl;
cout << "larger(15, 27) = " << larger(15, 27) << endl;
cout << "larger('X', 'P') = " << larger('X', 'P') << endl;
cout << "larger(4.9, 3.2) = " << larger(4.9, 3.2) << endl;
cout << "larger(\"cat\", \"dog\") = " << larger("cat", "dog") << endl;
cout << endl;
cout << "// Using the function template to find the larger of two items" << endl;
cout << "anyLarger(15, 27) = " << anyLarger(15, 27) << endl;
cout << "anyLarger('X', 'P') = " << anyLarger('X', 'P') << endl;
cout << "anyLarger(4.9, 3.2) = " << anyLarger(4.9, 3.2) << endl;
cout << "anyLarger(\"cat\", \"dog\") = " << anyLarger("cat", "dog") << endl;
cout << endl;
cout << "// Compare two strings using >= : \"cat\", \"dog\"" << endl;
if ("cat" >= "dog") {
cout << "\"cat\" is greater than \"dog\"" << endl;
}
else {
cout << "\"dog\" is greater than \"cat\"" << endl;
}
cout << endl;
cout << "// The use of variables: strCat and strDog. Compare using >=" << endl;
string strCat = "cat";
string strDog = "dog";
cout << "string strCat = \"cat\";" << endl;
cout << "string strDog = \"dog\";" << endl;
if (strCat >= strDog) {
cout << "strCat is greater than strDog" << endl;
}
else {
cout << "strDog is greater than strCat" << endl;
}
cout << endl;
cout << "// Using strcmp. strcmp(\"cat\", \"dog\")" << endl;
int result = strcmp("cat", "dog");
if (result > 0) {
cout << "\"cat\" is greater than \"dog\"" << endl;
}
else {
cout << "\"dog\" is greater than \"cat\"" << endl;
}
}
// Overloading larger
int larger(int x, int y) {
if (x >= y)
return x;
else
return y;
}
char larger(char a, char b) {
if (a >= b)
return a;
else
return b;
}
double larger(double p, double q) {
if (p >= q)
return p;
else
return q;
}
string larger(string y, string z) {
if (y >= z)
return y;
else
return z;
}
// Defining the template function
template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2)
{
if (parameter1 >= parameter2)
return parameter1;
else
return parameter2;
}
================
Update: Output
// Function Overloading
larger(15, 27) = 27
larger('X', 'P') = X
larger(4.9, 3.2) = 4.9
larger("cat", "dog") = dog
// Using the function template to find the larger of two items
anyLarger(15, 27) = 27
anyLarger('X', 'P') = X
anyLarger(4.9, 3.2) = 4.9
anyLarger("cat", "dog") = cat
// Compare two strings using >= : "cat", "dog"
"cat" is greater than "dog"
// The use of variables: strCat and strDog. Compare using >=
string strCat = "cat";
string strDog = "dog";
strDog is greater than strCat
// Using strcmp. strcmp("cat", "dog")
"dog" is greater than "cat"
You are not lexicographically comparing strings in both cases.
"cat" >= "dog"
This is comparing char pointers because the type of the literals "cat" and "dog" is const char*. It could give either result, depending on how the compiler decided to materialize the literals.
To lexicographically compare C-style strings (including literals like these) the function strcmp must be used instead.
strCat >= strDog
This is comparing strings lexicographically because std::string provides comparison operators that explicitly implement this kind of comparison.
"cat" >= "dog"
You are comparing pointers but not the actual values. Use strcmp.
That's because string literal (e.g. "cat") isn't of type std::string. You're doing a pointer comparison on two unrelated arrays of const char.
The literal string "cat" and "dog" are actually pointers to arrays of characters when you come to compare them, so the greatest will be the one that happens to be stored in memory at a higher location.
Your string larger(string y, string z) works because std::string can be constructed from a char* and so "cat" and "dog" get converted to std::string objects before being compared.
The template function, on the other hand, accepts them as their actual types which, when passed as parameters, become const char* and only their addresses get compared.
As others have already mentioned, in your line
cout << "anyLarger(cat, dog) = " << anyLarger("cat", "dog") << endl;
you are invoking anyLarger<const char &[]>, i.e. you call anyLarger with string literal arguments, which indeed boils down to comparing pointers instead of strings. You can fix this by either calling your function with std::string arguments by one of the following lines:
larger("cat", "dog");
anyLarger<std::string>("cat", "dog");
anyLarger(std::string("cat"), std::string("dog"));
anyLarger("cat"s, "dog"s); // C++14
or you could do a template specialization for string literals (or just any C-type strings, whatever you choose):
template <>
elementType anyLarger<char*>(char* parameter1, char* parameter2)
{
if (strcmp(parameter1, parameter2) >= 0)
return parameter1;
else
return parameter2;
}
I'm having problems with my program's output. It keeps spitting out 12345.
Here's the details:
It's split in three files: program8.cpp (the part that runs tests), myRandom.cpp (implementation of the class), and myRandom.h (specification of the class).
myRandom.h:
#ifndef MYRANDOM_H_
#define MYRANDOM_H_
class myRandom
{
public:
myRandom(); //Constructor
~myRandom(); //Destructor
void seed(unsigned long theSeed); //Mutator for current
unsigned long next(); //Mutator or Accessor for current
int randInt(int start, int end); //Scales result to a range
double randNormal(); //Future expansion
private:
unsigned long current; //Current random #
static const unsigned long a = 1103515245; //Multiplier for LGC
static const unsigned long c = 12345; //Increment for LGC
static const unsigned long m = 2147483648; //Modulus for LGC
};
#endif /* MYRANDOM_H_ */
myRandom.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
myRandom::myRandom() //Constructor
{
current = 0;
}
myRandom::~myRandom() //Destructor
{
}
void myRandom::seed(unsigned long theSeed) //Mutator for current
{
if (theSeed < 0 || theSeed > m-1)
{
// ERROR
return;
}
else
current = theSeed;
}
unsigned long myRandom::next() //Mutator or Accessor for current
{
if (current < 0)
{
cout << "Error: cannot set seed to a negative number" << endl;
return 0;
}
else
{
current = (m*current+c)%m; //Formula
return current;
}
}
int myRandom::randInt(int start, int end) //Scales result to a range
{
if (start >= end)
{
cout << "Error: cannot set start greater than or equal to end" << endl;
return 0;
}
else
{
return ((this->next() % (end - start)) + start);
}
}
double myRandom::randNormal() //Future expansion
{
cout << "Warning: randNormal not implemented" << endl;
return 0;
}
program8.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
int main()
{
myRandom theRand;
unsigned long theSeed;
cout << "Verify that the sequence generated by next() is the same on each run" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.next() << endl;
}
cout << "Verify that you can set the seed to 0 and 1" << endl;
theSeed = 0;
cout << theRand.next() << endl;
theSeed = 1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to -1 generates an error" << endl;
theSeed = -1;
cout << theRand.next() << endl;
cout << "Verify that you can set the seed to m-2 and m-1" << endl;
theSeed = 2147483648-2;
cout << theRand.next() << endl;
theSeed = 2147483648-1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to m generates and error" << endl;
theSeed = 2147483648;
cout << theRand.next() << endl;
cout << "Verify that next() produces a sequence predicted by hand/calc for the chosen seed" << endl;
cout << "Please enter a seed: ";
cin >> theSeed;
cout << theRand.next() << endl;
cout << "Verify that using start == end generates and error. Set both to 10." << endl;
theRand.randInt(10,10);
cout << theRand.next() << endl;
cout << "Verify that using start > end generates and error. Set start to 10 and end to 5." << endl;
theRand.randInt(10,5);
cout << theRand.next() << endl;
theRand.seed(theSeed);
cout << "Testing randInt for start=0 end=1,000" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.randInt(0 , 1000) << endl;
}
return 0;
}
I think the problem lies in the next() function, since that's what gets called all those times in program8.cpp cout statements. I could understand getting 12345 once, but it should be updated once that function runs successive times. I apologize if it's a dumb question. Thank you for your time and patience.
Your problem isn't a code specific one - it is Math-related from here:
current = (m*current+c)%m;
This always returns the value of c if c < m, otherwise (or more generally) it returns c % m. Why? From this theorem:
(m*n + a)%m = a
Example:
m = 10
n = 3
a = 7
(10*3 + 7)%10 = 7
See this for more:
http://en.wikipedia.org/wiki/Modulo_operation
I was trying to count the number of characters in a string class but for some reason the program is skipping over my function completely. This is just the test code from the main program, it still was giving me the same results. How come the counter function is skipped over?
#include <iostream>
#include <string>
using namespace std;
void prompt(string& dna)
{
cout << "Input: ";
getline(cin, dna);
}
void counter(const string DNA,
int* a_count, int* t_count, int* c_count, int* g_count)
{
for (int i = 0; i < DNA.size(); i++)
{
if (DNA.at(i) == 'a')
{
*a_count++;
}
else if (DNA.at(i) == 't')
{
*t_count++;
}
else if (DNA.at(i) == 'c')
{
*c_count++;
}
else if (DNA.at(i) == 'g')
{
*g_count++;
}
}
}
int main()
{
string dna;
int a = 0;
int t = 0;
int c = 0;
int g = 0;
prompt(dna);
if (! dna.empty())
{
cout << "Before:\n"
<< "A: " << a << endl
<< "T: " << t << endl
<< "C: " << c << endl
<< "G: " << g << endl;
counter(dna, &a, &t, &c, &g);
cout << "\n\nAfter:\n"
<< "A: " << a << endl
<< "T: " << t << endl
<< "C: " << c << endl
<< "G: " << g << endl;
}
system("pause");
return 0;
}
You're applying operator ++ the wrong way. It should be:
if (DNA.at(i) == 'a')
{
(*a_count)++;
}
else if (DNA.at(i) == 't')
{
(*t_count)++;
}
else if (DNA.at(i) == 'c')
{
(*c_count)++;
}
else if (DNA.at(i) == 'g')
{
(*g_count)++;
}
You've got a priority problem between the ++ and * operators. You are incrementing the pointer address, not the value. (*a_count)++; would be correct.
You may find it easier to use reference parameters for the counts instead, since you don't actually need to do any pointer arithetic. ie:
void counter(const string DNA, int& a_count, int& t_count, int& c_count, int& g_count)
And, yes a switch statement would be neater.