how this recursion is reaching the cout statement ? - c++

I have this function to solve the Tower of Hanoi problem and fortunately It's working good but can anybody explain to me if the function is calling it self before the cout statement in case m!=0 then how does it ever reach the cout statement or even the other call of itself ??
#include <iostream>
using namespace std;
void Hanoi(int m, char a, char b, char c){
if(m == 1){
cout << "Move disc " << m << " from " << a << " to " << c << endl;
}else{
Hanoi(m-1, a,c,b);
cout << "Move disc " << m << " from " << a << " to " << c << endl;
Hanoi(m-1,b,a,c);
}
}
int main(){
int discs;
cout << "Enter the number of discs: " << endl;
cin >> discs;
Hanoi(discs, 'A', 'B', 'C');
return 0;
}

Calling Hanoi(m), where m > 1: First it executes Hanoi(m-1) and all resulting calls. Then it executes cout. Then it executes Hanoi(m-1) and all resulting calls a second time.
Consider m == 3:
Hanoi(3)
Hanoi(2)
Hanoi(1)
cout
cout
Hanoi(1)
cout
cout
Hanoi(2)
Hanoi(1)
cout
cout
Hanoi(1)
cout

Related

Swapping Integers using pointer

1 : http://itweb.fvtc.edu/ag/?u=3&f=cpp-assignment3
I am to swap the integer using a SwapInteger function outside the main function type using pointer. The user input a number and then the computer will compile and change the result to the given result that our professor have assigned.
I've tried creating a void swapInteger function and input some code in to see if that swap the code but that does nothing. So i just added some code into the main function but I don't think that's what our professor wanted us to do. He did stated "do not modify the main function"
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
// TODO: Implement the "SwapIntegers" function
void swapIntegers(int *first, int *second)
{
int *pSwapIntegers = first;
first = second;
second = pSwapIntegers;
}
// Do not modify the main function!
int main()
{
int first = 0;
int second = 0;
int *pFirst = new int (first);
int *pSecond = new int (second);
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
swapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
I expected the computer to compile the two integer that the user input and then show the swapped integer to the user. Please take a look at my code if you have questions
Inside of your swapIntegers(), you are swapping the pointers themselves, not the values of the variables they are pointing at. The caller's variables are not being updated.
swapIntegers() needs to look more like this instead:
void swapIntegers(int *first, int *second)
{
int saved = *first;
*first = *second;
*second = saved;
}
Also, your main() is buggy. It dynamically allocates 2 int variables that it leaks and never assigns the user's input values to. The final "After swapping" output is printing out values from those pointers, not from the variables that were actually swapped. The code will NOT display the expected output. So, despite what the instructions say, main() NEEDS to be modified in order to operate properly, and if your professor has a problem with that, tough. He made a mistake in the code he gave you.
main() should look more like this:
int main()
{
int first = 0;
int second = 0;
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
swapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
Or, like this:
// Do not modify the main function!
int main()
{
int first = 0;
int second = 0;
int *pFirst = &first;
int *pSecond = &second;
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
swapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
Or, like this:
int main()
{
int *pFirst = new int (0);
int *pSecond = new int (0);
cout << "Enter the first integer: ";
cin >> *pFirst;
cout << "Enter the second integer: ";
cin >> *pSecond;
cout << "\nYou entered:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
swapIntegers(pFirst, pSecond);
cout << "\nAfter swapping:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
delete pFirst;
delete pSecond;
cout << "\nPress any key to quit.";
_getch();
return 0;
}
UPDATE: oh wait, it is not your professor's fault, it is YOUR fault. The main() you have presented here DOES NOT match the main() given in the actual assignment!. This is what the original main() looks like:
// Do not modify the main function!
int main()
{
int first = 0;
int second = 0;
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
SwapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
This code is correct. So YOU are the one who introduced the bad use of pointers in main(). So just revert back to the original main() code you were given. And then implement swapIntegers() properly. As the instructions told you to do.

Creating a Simple Calculator, having an issue with the addition

I'm trying to create a simple calculator and i already encountered an issue when addition is being used. I created a function for addition and whenever i pass in two values i get a different answer. For Example when i add 4,5 i would expect to get 9 but the answer i get is 0029144C . Im still a beginner, so at first i wasn't sure if using type bool for the adding function would affect my result, but i changed it to type float and still getting the same result (in case anyone asks).
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void SimCalcMenu();
void additionSign();
bool makeSum(float num1, float num2);
int main() {
float firstNum, SecondNum;
char operationLetter;
SimCalcMenu();
cout << " Please Select an Operation You Would Like to Perform ";
cin >> operationLetter;
if (operationLetter == 'a' || operationLetter == 'A')
{
additionSign();
cout << " Enter the First Number : ";
cin >> firstNum;
cout << " Enter the Second Number: ";
cin >> SecondNum;
makeSum(firstNum, SecondNum);
cout << " The Sum of " << firstNum << " and " << SecondNum << " is :" << makeSum << endl;
}
else
{
cout << " Error ";
}
return 0;
}
void SimCalcMenu() {
cout << "------------------------------------------------------------------------------" << endl;
cout << " WELCOME TO SIM CALCULATOR " << endl;
cout << "------------------------------------------------------------------------------" << endl;
cout << endl;
cout << " Please Select an Operation : " << endl;
cout << " A.) Addition " << endl;
cout << " B.) Subtraction " << endl;
cout << " C.) Multiplication " << endl;
cout << " D.) Division " << endl;
cout << " E.) Roots ( Only Positive Number)" << endl;
cout << " F.) Power ( Only Positive Number " << endl;
cout << " G.) Percentage " << endl;
cout << " H.) Display functions execution " << endl;
cout << " I.) Quit " << endl;
cout << "------------------------------------------------------------------------------" << endl;
}
void additionSign() {
cout << "------------------------------------------------------------------------------" << endl;
cout << " ADDITION " << endl;
cout << "------------------------------------------------------------------------------" << endl;
}
bool makeSum(float num1, float num2) {
float totSum;
totSum = num1 + num2;
return totSum;
}
makeSum() should return float, because you are returning the sum of two floats.
You are not getting the right result because you are printing makeSum, which is the address of the function. You want to print the value of makeSum(firstNum, SecondNum).
this line
cout << " The Sum of " << firstNum << " and " << SecondNum << " is :" << makeSum << endl;
IS 'printing' 'makesum', makesum is a function so its printing the address of makesum
you need
cout << " The Sum of " << firstNum << " and " << SecondNum << " is :" << makeSum(firstNum, SecondNum) << endl;
now at least it will print the result of makesum. As other have pointerd out that function is wrong (it returns a bool).
should be
float makeSum(float num1, float num2) {
float totSum;
totSum = num1 + num2;
return totSum;
}

While loop seems to be passing variables inversely from the Boolean condition

I've tested so many scenarios and it works without the while loop; but I just cant seem to figure out whats messing it up. if I pick an int in the target range 1-3 it passes and then freezes and i have to ctrl c the program out.
And if I pick a number outside that range it lets it pass in to the while loop and call the function. I'm very confused and this is the first program I've written with classes; so I feel like that probably is the issue.
Thanks.
#include <iostream>
using namespace std;
class Elevator
{
public:
void floorControl();
// Outputs floor actions and lets a user pick a floor number
int status();
// outputs floor positon
private:
int floorPosition = 1;
};
int main()
{
Elevator building[3];
int elevatorSelect;
cout << "\tElevator Status\n\tA\tB\tC\n"
<< "\t" << building[0].status() << "\t" << building[1].status()
<< "\t" << building[2].status() << endl
<< "\tWhich elevator do you want (1=A, 2=B, 3=C, or other to exit) ? ";
cin >> elevatorSelect;
cout << "\t" << elevatorSelect << endl;
while((elevatorSelect <= 3) && (elevatorSelect >=1));
{
building[elevatorSelect-1].floorControl();
cout << "\tElevator Status\n\tA\tB\tC\n"
<< "\t" << building[0].status() << "\t" << building[1].status()
<< "\t" << building[2].status() << endl
<< "\tWhich elevator do you want (1=A, 2=B, 3=C, or other to exit) ? ";
cin >> elevatorSelect;
cout << "\t" << elevatorSelect << endl;
}
return 0;
}
void Elevator::floorControl()
{
int floorSelect;
if(floorPosition > 1)
{
cout << "\tStarting at floor " << floorPosition << endl;
for(int i=1; i>floorPosition; floorPosition--)
cout << "\t Going down - now at floor " << floorPosition-1 << endl;
cout << "\tStopping at floor " << floorPosition << endl;
}
cout << "\tWhich floor do you want? ";
cin >> floorSelect;
if ((floorSelect < 1 )|| (floorSelect > 10))
cout << "\t**You pick up some dust off the wall; you missed**\n";
else
{
cout << "\tStarting at floor " << floorPosition << endl;
for (floorSelect; floorSelect > floorPosition; floorPosition++)
cout << "\t Going up - now at floor " << floorPosition+1 << endl;
cout << "\tStopping at floor " << floorPosition << endl;
}
}
int Elevator::status()
{
return floorPosition;
}

Printing multiple outputs on same line

there. I'm self learning C++ out of "C++ without fear". There is an exercise dealing with the GCD of 2 numbers that asks to print "GCD(a,b) =>" at each step in the proceedure. I was able to get this working:
int gcd (int a, int b);
int main() {
int i,j;
cout << "Enter the first integer" << endl;
cin >> i;
cout << "Enter the second integer" << endl;
cin >> j;
int k = gcd(i,j);
cout << "The GCD is " << k << endl;
system("PAUSE");
return 0;
}
int gcd (int a, int b){
if(b==0){
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " <<endl;
return a;
}
else {
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " << endl;
return gcd(b,a%b);
}
}
I was just wondering if there is a nicer way to go about printing each step of finding the GCD. That is, is there a "nicer" way to write this part of the code:
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " << endl;
? Thanks in advance.
You can do something like:
cout << "GCF(" << a << ',' << b << ") =>" << endl;
It is not C++ but you could use the C way of printing it which in my opinion looks better in this situation because there are far fewer stream operators, << in the way.
#include <cstdio>
printf("GCF(%d, %d) =>\n", a, b);
But this is a C way of doing things... You could use something like boost::format as is mentioned in this SO answer.
try this one
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
cout << 6+2 <<"\n" << 6-2;
}

program crashes at CIN input | C++

so i made a DOS program however my game always crashes on my second time running to the cin function.
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
//call functions
int create_enemyHP (int a);
int create_enemyAtk (int a);
int find_Enemy(int a);
int create_enemyDef (int a);
// user information
int userHP = 100;
int userAtk = 10;
int userDef = 5;
string userName;
//enemy Information
int enemyHP;
int enemyAtk;
int enemyDef;
string enemies[] = {"Raider", "Bandit", "Mugger"};
int sizeOfEnemies = sizeof(enemies) / sizeof(int);
string currentEnemy;
int chooseEnemy;
// ACTIONS
int journey;
int test;
int main()
{
// main menu
cout << "welcome brave knight, what is your name? " ;
cin >> userName;
cout << "welcome " << userName << " to Darland" << endl;
//TRAVELING
MENU:
cout << "where would you like to travel? " << endl;
cout << endl << " 1.> Theives Pass " << endl;
cout << " 2.> Humble Town " << endl;
cout << " 3.> Mission HQ " << endl;
cin >> journey;
if (journey == 1)
{
// action variable;
string c_action;
cout << "beware your journey grows dangerous " << endl;
//begins battle
// Creating the enemy, HP ATK DEF AND TYPE. ;
srand(time(0));
enemyHP = create_enemyHP(userHP);
enemyAtk = create_enemyAtk(userAtk);
enemyDef = create_enemyDef(userDef);
chooseEnemy = find_Enemy(sizeOfEnemies);
currentEnemy = enemies[chooseEnemy];
cout << " Here comes a " << currentEnemy << endl;
cout << "stats: " << endl;
cout << "HP :" << enemyHP << endl;
cout << "Attack : " << enemyAtk << endl;
cout << "Defense : " << enemyDef << endl;
ACTIONS:
cout << "Attack <A> | Defend <D> | Items <I>";
cin >> c_action;
//if ATTACK/DEFEND/ITEMS choice
if (c_action == "A" || c_action == "a"){
enemyHP = enemyHP - userAtk;
cout << " you attack the enemy reducing his health to " << enemyHP << endl;
userHP = userHP - enemyAtk;
cout << "however he lashes back causing you to have " << userHP << "health left " << endl;
//end of ATTACK ACTION
}
the last line "cin >> c_action crashes. i use two other pages. they just create the functions. is it a complier issue. also why does my complier always shutdown after it runs he app. is there a way to stop it?
A few hints:
I never use forward declarations of functions ( such as "int create_enemyHP (int a);" ) if I can avoid them. If you do this then there are two places in your code that must be correct for your program to work. It makes life easier if there is always a "single source of truth"
Have you run this code through the debugger? It will help you find problems much more quickly.
If your c_action variable is only intended to be a char, I'd suggest to use a char variable, rather than a string.
You might want to try this way, and if you're still faced with an error, you might give
scanf("%c", &c_action); //assuming you used a char.
I didn't understand if the program crashes before you type the "action" or after. Because if it crashes before, then I think your problems are caused by white spaces characters in the input buffer.