I'm new to C++, and I made a simple code to multiply two numbers, but I don't know how to return to the beginning to repeat the code without restarting it. Should I use "goto"?
main() generally has int type. If you want to go back to beginning, I can think of two ways. First, is using "goto". Second is using a while loop. You can also include a conditional statement at the end (before system("pause")) to exit the program when you wish. I'll give you an example of this. I apologize for not taking time to align brackets.
#include <iostream>
usingnamespace std;
int main()
{
int a = 1; //Defined an int of type
while (a>0)
{
int x;
cout<<"x=";
cin>>x;
int y;
cout<<"y=";
cin>>y;
cout<<endl;
cout<<x;
cout<<"*";
cout<<y;
cout<<"=";
cout<<x*y;
cout<<""<<endl;
cout<<""<<endl;
int exit_status;
cout << "enter 0 to exit and 1 to continue " << endl;
cin >> exit_status;
if (exit_status == 0)
{
break;
}
else //not needed but whatever.
{
continue;
}
a++;
}
system ("pause");
return 0;
}
I believe the command line for that is system("CLS");
I was checking some other forums and found this. This might be better since it was posted by pretty well known people on this forums.
cout << string(50, '\n');
I hope it helps.
Where do you want to clear the screen? I assume you want to clear the screen after you decide to continue, so place it after that check.
By the way, continue skips everything after it in the loop. Also, incrementing a in that loop is pointless. As long as a is non-zero, your loop condition will be true.
Thank you so much. And this isn't for a professor, Protomega. I just wanted to learn C++. It's definitely so much more complicated than calculator programming.
Hahaha yes, but calculator programming is definitely an easy way to get sucked into the programming world but when you begin to learn about Object Oriented Programming you will have a hard time going back to the calculator because of how limited it is and your mind may not be able to switch back to a non-"dynamic" language. Welcome to the world of C++ by the way.
@Sargon94
You can definitely do that but C++ doesn't recommend you doing it. It also eats up memory. Also, what will the main function return here? I guess you were trying to ask
You're not wrong, I was just curious, 4 years of programming and I'd never considered calling the main for any reason. Why does it eat up memory? Does re-declare variables without them passing out of scope somehow?