Recursion function C++ - c++

Hi is there way to check that your code is Recursion or not in c++? I write code but someone tell me that it isn't Recursion. I want to make sure.
#include <iostream>
#include <conio.h>
using namespace std;
bool winding(string str, int len) {
int counttrue = 0;
for(int i = 0; i < len; i++){
if(str[i] == '1') counttrue++;
else if(i != len - 1 && str[i] == '0' && str[i + 1] == '0') {
counttrue += 2; i++;
}
}
return (counttrue == len);
}
int main() {
string strwinding;
cin >> strwinding;
cout << winding(strwinding, strwinding.length()) << endl;
cout << "Continue...";
getch();
return 0;
}

A recursive function calls itself, and yours doesn't, so it's not recursive.
Assuming that the definition of a "winding" string is
The empty string, or
A 1 followed by a "winding" string, or
00 followed by a "winding" string,
a straightforward translation could look like this:
bool winding(const string& str, int index)
{
return index >= str.size()
|| ((str[index] == '1') && winding(str, index+1))
|| ((index < str.size() - 1)
&& str[index] == '0'
&& str[index+1] == '0'
&& winding(str, index+2));
}
// ...
cout << winding(strwinding, 0) << endl;

A recursive function is a function that calls itself, like for instance:
int fac(int x)
{
if (x <= 1) return 1; else return x * fac(x - 1);
}
You can easily check if a function is recursive if you create a breakpoint at the beginning of the function and see if this breakpoint is reached more than once if you call the function from outside once.

Related

Why does the program print 0 instead of the average?

Wrote a function that calculates the average length of words in a sentence.
Why does the program print 0 instead of the average?
Please help me fix my mistake.
If you know how to make an implementation in one function, please write.
#include <iostream>
#include <string>
using namespace std;
int CountWordsAndLetters(char* str, int& words, int& letters)
{
words = 0;
int i = 0;
letters = 0;
while (str[i] == ' ')
i++;
for (; str[i]; i++) {
if (((str[i] >= 'a') && (str[i] <= 'z'))
|| ((str[i] >= 'A') && (str[i] <= 'Z')))
letters++;
if (str[i] == ' ') {
words++;
while (1)
if (str[i] == ' ')
i++;
else {
i--;
break;
}
}
}
words = words + 1;
return (words);
}
float AverageLetters(float words, float letters)
{
float a = (double)(letters / words);
return a;
}
int main()
{
char array[255];
int words = 0;
int letters = 0;
cout << "Enter the string\n\n";
gets_s(array);
int size;
for (size = 0; array[size]; size++)
;
char* str = new char[size];
CountWordsAndLetters(str, words, letters);
cout << "\nAverage number of letters per word: "
<< AverageLetters(words, letters);
return 0;
}
If you know how to make an implementation in one function, please write.
Here, you are allocating an uninitialized array of char:
char* str = new char[size];
You put nothing in it.
You then pass it to CountWordsAndLetters:
// here -------v
CountWordsAndLetters(str, words, letters);
You should consider simply sending array instead:
CountWordsAndLetters(array, words, letters);
Here's a live example of your code working.

What is wrong with my sentence palindrome code (C++)?

The below code is of a sentence palindrome checker. I'm a newbie programmer so I'm having a hard time debugging this code. It's showing incorrect output.
For example, if the sentence is "A man, a plan, a canal: Panama"
It's giving false as a result instead of true. (Blank spaces and punctuations are to be neglected.)
#include <iostream>
class Solution
{
public:
bool isPalindrome(std::string s)
{
int l, i;
i = 0;
l = s.length();
while (i <= (l - 1))
{
if (s[i] == ' ' || ispunct(s[i]) == true)
i++;
else if (s[l - 1] == ' ' || ispunct(s[l - 1]) == true)
l--;
else if (tolower(s[i]) == tolower(s[l - 1]))
{
l--;
i++;
}
else
return false;
}
return true;
}
};
int main(void)
{
Solution s;
const std::string text = "Panama";
std::cout << s.isPalindrome(text);
return 0;
}
The problem is very likely that the character classification functions (like e.g. ispunct) does not return a bool result.
They return an int whose value can be any non-zero value for "true".
That means the condition like ispunct(s[i]) == true might actually be false for punctuation characters.
You need to use e.g. ispunct(s[i]) != 0 (or just plain ispunct(s[i])) instead.
And also, that is not how one checks for palindrome. I suggest the following code:
#include <iostream>
int main() {
std::string str;
std::cin >> str;
for (auto i = 0, j = str.size() - 1; i < j; i++, j--) {
if (//check for punctuation) {
}
else if (str.at(i) != str.at(j)) {
//not a palindrome
break;
}
}
return 0;
}

Int function not returning any value

I made this function to convert a string to an integer (school assignment) and my function is not seeming to work, if it picks up any non-numeric data it should return INT_MAX. It's not returning any data no matter what, and seemingly not returning to main either.
#include <iostream>
#include <climits>
#include <string>
using namespace std;
int stringToInt(string input){
int i = 0;
if(input[i] == '-'){
i++;
//First while loop controls valid input
while(input[i] != '\0'){
if(input[i] < 49 || input [i] > 47){///Can't figure this out
return INT_MAX;
}
i++;
}
}
//Now to calculate result
int result = 0;
i = 0;
if (input[i] == '-'){
i++;
while (input[i] != '\0'){
result = (input[i] - 49) + (result * 10);
i++;
}
result = result * (-1);
return result;
}
else{
while (input[i] != '\0'){
result = (input[i] - 49) + (result * 10);
i++;
}
return result;
}
}
//////MAIN////////
int main(){
string number;
int actualNumber;
int answer;
cout << "This is my main function. Enter a string to evaluate" << endl;
getline(cin, number);
actualNumber = stringToInt(number);
cout << actualNumber;
cout << endl;
return 0;
}
Your 2nd and 3rd while loops don't increment i so you end up looping on the same number forever and never get to '\0'.
ie this one
while (input[i] != '\0'){
result = (input[i] - 48) + (result * 10);
}
i never changes.

Only read numbers out of users input

I'm trying to write a function which only reads four ints out of a users input like this: ewzge242jfdsiii23 So it is supposed to save only 2422.
This is my code and it just gives me some weird output, if I let it cout number.
Can you maybe see my mistakes and explain why I can't do it how I did and what I could do instead? Thanks a lot!
int readnumber ( ) {
char kar, ont_kar, ont_ont_kar;
int number;
while (kar != '\n' ){
cin.get (kar);
if (kar >= '0' && kar <= '9') {
old_kar=kar;
old_kar = old_kar*10 + (kar - '0');
old_old_kar = old_kar ;
} //if
} //while
if (old_kar < 9999) {
number=old_kar;
}//if
else {
number=old_old_kar;
}//else
}//readnumber
This looks too complicated, why do you need so many variables?
Also old_kar and old_old_kar are misstyped. The function does not return, that should be the main problem.
Here's a quick simple example:
unsigned readnumber(int number_of_chars) {
char ch;
unsigned number = 0;
while (number_of_chars > 0) {
std::cin.get(ch);
if ('\n' == ch)
break; // Stop on new line
if (ch < '0' or ch > '9')
continue; // Skip non-digits
--number_of_chars; // One digit processed
number = number * 10 + ch - '0'; // And added to the result
}
return number;
}
And here is a full version without break or continue:
#include <iostream> // std::cin, std::cout
#include <fstream> // std::ifstream
using namespace std;
int readnumber(int number_of_chars) {
char ch;
int number = 0;
while (number_of_chars > 0) {
std::cin.get(ch);
if ('\n' == ch)
return number;
if (ch >= '0' and ch <= '9') {
--number_of_chars;
number = number * 10 + ch - '0';
}
}
return number;
}
int main() {
int n = readnumber(4);
cout << "You entered: " << n << endl;
return 0;
}
NB: Always compile with all warnings on, this will save you a lot of time.

Counting Multi-Character Characters in String

For example, how do you count the occurrence of "TJ" in OAEKOTJEOTJ?
if (s[i] == 'TJ') and (s[i] == 'T'+'J')
x += 1;
First one gives me an error, second one doesn't count. I need a beginner solution to this, I haven't learned very much about c++ commands yet. Thanks
int x = 0
string s;
cin >> s;
for (int i = 0; i < 100; i++)
if (s[i] == T || s[i] == t) && (s[i+1] == J || s[i+1] == j)
x += 1
cout << x << endl;
That's the excerpt from my code, it doesn't count any tj, tJ, Tj or TJ
Try using:
if(s[i] == 'T' && s[i+1] == 'J') // and make sure you do not run out of bounds of string with index i.
x += 1;
EDIT:
Based on your code:
int x = 0
string s;
cin >> s;
for (int i = 0; i < 100; i++)
if (s[i] == T || s[i] == t) && (s[i+1] == J || s[i+1] == j)
x += 1
cout << x << endl;
You should do it like following:
int x = 0
string s;
cin >> s;
for (int i = 0; i < s.length()-1; i++) // use size of string s.length()-1 to iterate the string instead of 100
if (s[i] == 'T' || s[i] == 't') && (s[i+1] == 'J' || s[i+1] == 'j') // compare the ascii values of characters like - 'T' 'J' etc.
x += 1
cout << x << endl;
std::string provides a function find which searches the string for substrings, including multi-character substrings (below, I am using C++11 syntax):
#include <iostream>
#include <string>
int main()
{
using namespace std;
string text { "OAEKOTJEOTJ" };
unsigned int occ { 0 };
size_t pos { 0 };
for (;;) {
pos = text.find("TJ",pos); // Search for the substring, start at pos
if (pos == string::npos) // Quit if nothing found
break;
++pos; // Continue from next position
++occ; // Count the occurrence
}
std::cout << "Found " << occ << " occurrences." << std::endl;
}
The way it's done above we advance by one character only after each match. Depending on whether/how we want to deal with overlapping matches, we might want to advance pos by the length of the search pattern. (See chris's comment as well.)
Try this:
#include <locale> // for tolower() function
string tolower(string s) {
tolower(s[0]);
tolower(s[1]);
return s;
}
...
int main() {
string s;
cin >> s;
int n = s.size(),cont = 0;
for(int i = 0; i < n ; ++i) {
if(tolower(s.substr(i,2)) == "tj") {
++cont;
}
}
cout << cont << endl;
return 0;
}