I'm a beginner in C++ (4 days or so into my course) i created a small program that seems to work the way i want it to.
Quick summary:
The program asks for your name. then asks for two numbers to add together. displays the answer. then asks if you want to calculate again y/n.
However, i can't help but feel like its a total train wreck in terms of formatting.
In particular the Again()
function...
Inside of it, i created a loop by calling on another function if
the condition was true. like so:
bool Again() {
std::cout << "Would you like to calculate again y/n?\n";
std::string answer = "";
std::cin >> answer;
if (answer[0] == 'y') {
std::cout << "Cool lets do it then \n";
PickTwo();
Again();
}
else {
std::cout << "alright, goodbye\n";
}
return 0;
}
Is it proper or improper to create a loop the way i did in Again() ? if so, is there a right way to do it ?
This is the entire program:
#include <iostream>
#include <string>
void Greetings();
int PickTwo();
bool Again();
int main() {
Greetings();
PickTwo();
Again();
system("pause");
return 0;
}
void Greetings() {
std::cout << "Hi my name is Program, we're going to do something today. \n";
std::cout << "Whats your name?\n";
std::string Name;
std::getline(std::cin, Name);
std::cout << "Hi " << Name << ", we're going to try to do math\n";
return;
}
int PickTwo() {
std::cout << "Please pick the numbers to be added\n";
int firstNumber;
std::cin >> firstNumber;
int secondNumber;
std::cin >> secondNumber;
int Answer = firstNumber + secondNumber;
std::cout << "This are your numbers " << firstNumber << " and " << secondNumber << std::endl;
std::cout << "If we add them you have " << Answer << std::endl;
return Answer;
}
bool Again() {
std::cout << "Would you like to calculate again y/n?\n";
std::string answer = "";
std::cin >> answer;
if (answer[0] == 'y') {
std::cout << "Cool lets do it then \n";
PickTwo();
Again();
}
else {
std::cout << "alright, goodbye\n";
}
return 0;
}
Thank you in advance, knowing what NOT to do will help me fix the bad habits before they get worst.
Is it proper or improper to create a loop the way i did in Again() ? if so, is there a right way to do it ?
In a language that does not support tail recursion, your program has the potential to cause stack overflow. I would not recommend using it they way you have it coded.
It will be better to use a while
loop or a do-while
loop. In the loop, do whatever you need to do again.