If this is the proper place to ask for feedback on the efficiency of code, then here is a short program I wrote today. I just started C++ today, and have no other
experience with coding.
#include <iostream>
#include <math.h>
usingnamespace std;
int main() {
string n,answers;
double a,b;
double c,d;
int i,is_prime;
label1:
cout << "Input a number.\n";
cin >> a;
cout << "The square of " << a << " is " << a*a << ".\n";
cout << "The cube of " << a << " is " << a*a*a << ".\n";
if ((int)a % 2 == 0)
cout << a << " is an even number.\n";
else
cout << a << " is an odd number.\n";
i = 2;
while (i <= sqrt(static_cast<double>(a))) {
if ((int)a % i == 0)
is_prime = false;
i++;
}
if (is_prime)
cout << a << " is a prime number.\n";
else
cout << a << " is not a prime number.\n";
cout << "Would you like to continue? (y/n): ";
cin >> n;
if (n == "y")
goto labelcont;
if (n == "yes")
goto labelcont;
if (n == "n")
goto labelend;
if (n== "no")
goto labelend;
else
cout << "Improper syntax, closing... \n";
goto labelend;
labelcont:
cout << "What would you like to do? (+,-,*,/,restart,end): ";
cin >> answers;
if (answers == "+")
goto label_plus;
if (answers == "-")
goto label_minus;
if (answers == "*")
goto label_mult;
if (answers == "/")
goto label_div;
if (answers == "r")
goto label1;
if (answers == "restart")
goto label1;
if (answers == "e")
goto labelend;
if (answers == "end")
goto labelend;
else cout << "Incorrect syntax. Closing...";
goto labelend;
label_plus:
cout << "Enter a number to start with: ";
cin >> a;
cout << "\nEnter a number to add to " << a << ": ";
cin >> b;
cout << "\n" << a << " + " << b << " = " << a+b << "\n\n";
goto labelcont;
label_minus:
cout << "Enter the first number: ";
cin >> a;
cout << "\nEnter the second number: ";
cin >> b;
cout << "\n" << a << " - " << b << " = " << abs((int)a-(int)b) << "\n\n";
goto labelcont;
label_mult:
cout << "Enter the first number: ";
cin >> a;
cout << "\nEnter the number to multiply by " << a << ": ";
cin >> b;
cout << "\n" << a << " * " << b << " = " << a*b << "\n\n";
goto labelcont;
label_div:
cout << "Enter the first number: ";
cin >> a;
cout << "\nEnter the second number: ";
cin >> b;
cout << "\n" << a << " / " << b << " = " << a/b << "\n\n";
goto labelcont;
labelend:
return 0;
}
I would just like some feedback on the code, preferably methods on how I can optimize it. I have noticed a lot of people hate 'goto', but I could not think of another way to have the program go back to the start without it.