Recursive Function Error1 - c++

I am making a program that the user inputs integers and outputs them in reverse. It is a recursive function. The Problem now is that it outputs an infinite of 0's. Please tell me where is the error in my code. and I need some pointers. Please help.
#include <iostream>
using namespace std;
void printreverse(int);
int main()
{
int x;
cout << "Enter numbers: ";
cin >> x;
printreverse(x);
return 0;
}
void printreverse(int x)
{
if(x<10)
cout << x;
else
cout << x%10;
printreverse(x/10);
}

You have wrong identing in printreverse. It should be like this:
void printreverse(int x)
{
if(x<10)
cout << x;
else
cout << x%10;
printreverse(x/10);
}
First it prints x or x%10, then it recurses regardless of what x is. If you wanted more than one statement done in a consequent or alternative you need to use a block. Blocks are denoted with {} in C-decendants. They are so usual that some people actually think conditionals and control flow syntax need to have them. Anyway if the identing was the intended behaviour you should write it like:
void printreverse(int x)
{
if(x<10) {
cout << x;
} else {
cout << x%10;
printreverse(x/10);
}
}
Whenever I use braces on one term in an if I add them for every one even when it's not really needed. Some coding standards, like PSR2, require blocks always to remove the chance of ever getting bugs like this.

C++ is not Python. You need to surround your else block by braces, like so
else
{ // need brace here
cout << x%10;
printreverse(x/10);
} // and here
otherwise only the first statement after the else is being executed (and the final printreverse(x/10) will always be executed, even for 0, so you end up overflowing the stack).
I recommend you to always put braces, even for a single statement in an if/else, precisely for reasons similar to the one you just bumped into.

Related

My C++ file expected a 'while' in place of an if. And at the end it expected a '('

I have recently started to program in C++ and i wrote a simple file to try and test. It converts Celsius to Fahrenheit and vice versa. It keeps giving me an error about expecting a 'while', and a '('
As i said I'm new to this and really don't know what to try. I've moved the if else and else onto the same line as the ending curly brace, of the former if/if else statement.
#include <iostream>
int main()
{
int f;
int c;
char choice;
ask:do {
std::cout << "Hello welcome! Would you like to convert from C to F (a) or F to C (b)?\n";
std::cin >> choice;
}
if (choice == "a") { // that if before this comment has squiggly red line
std::cout << "Great, What is the temperature in Celcius? (No decimals please)\n";
std::cin >> c;
f = (c * 1.8) + 32;
std::cout << "The temp in Farenheight is " << f << "degrees\n";
}
if else (choice == "b") {
std::cout << "Great, What is the temperature in Celcius? (No decimals please)\n";
std::cin >> c;
c = (f / 1.8) - 32;
std::cout << "The temp in Celsius is " << c << "degrees\n";
}
else {
std::cout << "Sorry that wasn't an option. Please try again.";
goto ask;
}
} // this also is squiggly
I would like it to output the number of c to f vice versa, but it wont run and it says:
expected a 'while' 18 ,5
expected a '(' 42 ,1
The code here has a syntax error:
do {
std::cout << "Hello welcome! Would you like to convert from C to F (a) or F to C (b)?\n";
std::cin >> choice;
}
The do keyword needs to be paired with a while, as the loop is do ... while rather than just do. So, for example, you might say something like
do {
std::cout << "Hello welcome! Would you like to convert from C to F (a) or F to C (b)?\n";
std::cin >> choice;
} while (!isValidInput(choice));
where isValidInput would be some helper function that validates the input.
So in other words, the issue isn't that you can't use an if statement here as much as your do ... while loop is incomplete.
There are some other syntax errors here as well. For example, you can't say if else, though else if is perfectly fine. Another issue: in C++, double-quotes are used for strings while single-quotes are used for characters, so comparisons of the form choice == "b" won't compile, because you're comparing a char and a string. Those errors will likely surface after you fix the aforementioned one.
As a final note, while goto is indeed legal in C++, it's generally frowned upon in favor of other options like regular styles of loop. If you follow the above approach of having your loop continue until you get a valid input, then you should be able to eliminate the goto that takes you back to the point where you ask for input.
Hope this helps!
The do is a loop in c++. Specifically it is part of the do … while loop. It expects you to clarify how long the loop should be executed until the condition is met (and the do... while loop is different from while loop in that it executes the code at least once no matter what).
A ///
Your do is not enclosing your entire program in curly braces, so if you're not trying to loop your entire program then you may not need do at all. Simply make it
std::cout << "Hello welcome! Would you like to convert from C to F (a) or F to C (b)?\n";
std::cin >> choice;
B ///
If you want to loop the entire program the curly braces after do must capture everything and be finished with a while. In this scenario you can remove your goto statement; this answer can explain why you may want to avoid this What is wrong with using goto?.
E.g.
bool loop = true;
do {
// your program
} while (loop); // this will loop while "loop" variable continues to be true
You can then have a condition in your loop somewhere that changes loop = false to break the loop, for example asking the user if they want to continue or not.
///
Some other things I noticed about your code:
char is assigned values with ' and note ".
if else is not correct, instead it is else if (…

C++ Char checking gives outrageous value

i am trying to make a program to check and list the genders of a number of student, m being fem and l being male.
I'm not sure what's wrong with my code but when i print out the m and l variable they have either really huge.
Have been trying to solve this for hours, your help is greatly appreciated, cheers.
P.S sorry for my bad english.
#include<iostream>
#include<string>
using namespace std;
main()
{
char gender[20];
int jlh,i,j,m,l;
cin>>jlh;
system("cls");
for(i=0;i<jlh;i++)
{ cout<<"Data "<<i+1<<endl;
cout<<"Enter your gender - "<<endl;
cin>>gender[i];
}
m,l=0;
for(i=0;i<jlh;i++){
if(gender[i]=='p'){
m=m+1;
}
else if(gender[i]=='l'){
l=l+1;
}
}
cout<<endl<<l<<endl;
cout<<m;
}
The line
m,l=0;
does not work as you expect. Look up the comma operator, it evaluates the first operand (just m in this case), discards the result, and evaluates and returns the second operand. So only l is set to zero. I would recommend moving the declaration to this line and initializing the variables in one go, like so
int m=0, l=0;
for (int i=0; i<jlh; i++)
...
I would also move the declaration of variables like i to where they are needed, as shown above; there is no need to put all declaration at the beginning of the function.
Then the output
cout<<endl<<l<<endl;
cout<<m;
places the endl before and after the first variable, but not after the second. You should have an endl after the last line of your output, otherwise your console prompt is right after your value. It would improve readability to have something like this:
std::cout << "Number of females: " << m << std::endl;
std::cout << "Number of males: " << l << std::endl;
You should also make sure that not more than 20 values are entered, as your array has this size. But there is not even a need for this (maybe there is in your real code, but not in the MCVE): You can just increment the variables when reading the input, no need to store it in the array. This gets rid off this arbitrary limit. If you really need the values, you should use a std::vector instead of a fixed size array.

Can someone explain the error in this while loop?

So I'm a beginner programmer... and I can't figure out what the problem is in this bit of code I'm writing for a text adventure. All I want it do At the moment is let the user enter a command, and then it converts it to ALLCAPS and prints that out. It should output this:
What shall I do?
pie
Your raw command was: PIE
But instead, it outputs this:
What shall I do?
pie
PIE
...and then it freezes. Here's the code:
#include <iostream>
#include <string>
#include <cctype>
#include <cstring>
#include <vector>
using namespace std;
void command_case();
string userIn;
string raw_command;
int x = 0;
int main()
{
while(raw_command != "QUIT")
{
cout << "What shall I do?\n";
cin >> userIn;
command_case();
cout << "Your raw command was: " << raw_command << endl;
}
return 0;
}
void command_case()
{
char command[userIn.size()+1];
strcpy(command, userIn.c_str());
while(x < userIn.size()+1)
{
if(islower(command[x]))
{
command[x] = toupper(command[x]);
cout << command[x];
x++;
}
else if(isupper(command[x]))
{
cout << command[x];
x++;
}
}
raw_command = command;
}
I think it may be a problem with the while loop in void command_case(), but I can't figure out exactly what that problem is. I'd appreciate any advice you can give me.
One too much:
while(x < userIn.size()+1)
The problem is with the x variable in the command_case() function.
When x becomes 3 (and "command[x] points to the null character at the end of "pie")
neither islower(command[x]) or isupper(command[x]) are true.
Neither section of the if statement executes, so x stays at 3 forever.
Since "userIn.size()+1" is 4, and x never reaches 4, the loop never exits.
A possible solution is remove the "x++" from both sections of the if statement, and have a single "x++" after the if statement. This will increment x during every loop regardless of what character "command[x]" points to.
You could easily do something like
void command_case()
{
for(int i =0; i<userIn.size(); i++)
{
userIn[i] = toupper(userIn[i]);
}
}
then cout<<userIn in the main
You should remove all cout calls from command_case() function. In fact the whole if-branch in the function is useless and you could just replace it with the following:
command[x]=toupper(command[x]);
For the simplicity you could replace the whole command_case() function with (just remember to #include <algorithm>):
std::transform(userIn.begin(), userIn.end(), userIn.begin(), toupper);

Recursive function? [beginner]

I don't understand recursive functions.
I wrote this code to help me but i don't understand why it works the way it does.
It prints backwards the steps from 0 to the number n/2 i input but don't know what makes it print every step it skipped from low to high because it went recursive. I am close but not yet there...
#include <iostream>
#include <conio.h>
using namespace std;
int recursiv(int );
int times;
int main(){
int x;
cout<<"Imput number\n";
cin>>x;
recursiv(x);
getch();
return 0;
}
int recursiv(int x){
times++;
if(x)
recursiv(x/2);
cout<<"We are now at "<<x/2<<endl;
if (!x)
cout<< "We reached "<<x<<" but it took "<<times-1<< " steps\n";
return 0;
}
When you are dealing with recursion you have to understand two main part of the function code: the one that is executed on the way forward, and the one that is executed on the way back:
void X() {
// way forward
X();
// way back
}
The way forward part is executed while calling the function over and over until the end of the recursion; the way back is executed while coming back from the last call to the first.
void print(int x) {
if (!x) return; // end of recursion
std::cout << x << " ";
print(x-1);
}
The above example contains std::cout << x on the way forward which means that the call print(5) will print: 5 4 3 2 1.
void print(int x) {
if (!x) return; // end of recursion
print(x-1);
std::cout << x << " ";
}
The above example moved the actual printing to the way back part of the function which means that the same call print(5) will print: 1 2 3 4 5.
Let's take your function (cleaned up a bit):
int recursiv(int x){
times++;
if(!x) return 0; // split
recursiv(x/2);
cout << "We are now at "<< x / 2 << endl;
return 0;
}
We can distinguish our two parts quite easily. The way forward is:
times++;
if(x) return;
In which we just increment our int parameter times (we just ignore the conditional for the end of recursion here).
The way back is:
cout<<"We are now at "<<x/2<<endl;
return 0;
Which will be executed from the last call to the first one (just like the second version of the example). Therefore taking from the lowest number (the one nearer to 0 because of the end recursion condition) which is the last called before the end of recursion to the first, just like our example.
If i understand your question correctly:
It should print from high to low, but it actually prints from low to high. why is that?
The line cout<<"We are now at "<<x/2<<endl; is after the call for recursion.
so the function calls itself with a smaller amount again and again until it hits the break criteria.
the the function with the smallest amount calls the std::cout, return the second smallest amount does the std::cout and so on until the last one does it.
If you want the result in the other order, move the mentioned line two lines higher, so each iteration echos before calling the child.
example:
int recursiv(int x, int times = 0) {
std::cout << "We are now at " << x/2 << std::endl;
if(x)
return recursiv(x/2, times + 1);
else
std::cout << "We reached " << x << " but it took " << times << " steps" << std::endl;
return 0;
}
Unrelated: Global variables are considered a bad practice. There are use cases for them, this is not one of them. I fixed that within the function.

Why does it say that my 'destroystack' isn't declared?

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
string name;
double gpa;
double high = 0;
stack<string>names;
for (int i=0;i<7;i++)
{
cout << " Enter student's name and gpa " <<endl;
cin >> gpa ;
cin >> name ;
if (gpa > high)
{
names.destroyStack();
high = gpa;
names.push(name);
}
else
if (gpa==high)
{
names.push(name);
}
}
cout << "Highest gpa is " << high << "Names with the highest gpa are"<< endl;
while (!names.empty)
{
cout << names.top() << endl;
names.pop();
}
return 0;
}
In order to display only the names with the highest gpa, I have to put a code to remove the stack before with the lower gpa scores.So for this I thought I could use the "destroystack()" operation but when I use that and try and execute it, the compiler says that the destroyStack wasn't declared in the scope.
This AND the bottom one where I want to display the stack.It even says that empty wasn't declared.
I'm confused with these errors and I don't know what it means by declaring the operations? I'm using codeblocks (Not Visual studio) so does that affect anything?
Because, quite simply, there is no such function destroyStack in std::stack. I have no idea where you got the idea that there is.
This code should work to empty your stack:
replace:
names.destroyStack();
with:
while (!names.empty())
{
names.pop();
}
As you can see, empty is a function; it returns a value. In this case, it returns a boolean (true/false), so you'll need to have parenthesis after it, in order to call it.
That's why you're getting the message about empty not being declared; it means that the compiler is looking for a variable called empty, but it doesn't exist. By adding the parens, you're telling it that you want to call a function, not access a variable.
The "while loop" iterates through all of the items in the stack until the stack is empty. This effectively means that, for every item that the stack has in it, the item is "pop'd" off (pop is also a function, but it returns the item that was on the stack). Eventually, the stack has nothing left in it, and the while loop exits, because empty() returns true.
For a good reference on what functions and properties the stack template has on it, check out:
http://www.cppreference.com/wiki/container/stack/start
You should implement that destroyStack yourself. A function such as:
void destroyStack(stack<string>& _stack)
{
// Do whatever
}
And call it with:
destroyStack(names);
empty should be empty() instead.
Your editor, codeblocks or Visual Studio, doesn't affect anything.