I'm writing a program for magic square and I'm a relative beginner to C++ and programming. I was hoping someone could help me find alternate or better ways to implement my code. This is the main function. I also entered a function to check if the input is odd, max 19, and to quit.
Is there a way to not have back-to-back for
and if
statements?
#include <iostream>
#include <limits>
#include <iomanip>
using namespace std;
int oddfunction(int &a);
int endfunction(int &exit);
int maxfunction();
int main()
{
int r, c, d, e, z=0;
int *f = new(nothrow) int;
int *g= new(nothrow) int;
int magic[120][120];
cout << "EML 2032 Final Project: Magic Square (odd numbers) " << endl;
while(*g != 0)
{
cout << "\n\nMagic Squares for integers less than 20. ";
for ( r=0 ; r<120 ; r++ )
for ( c=0 ; c<120 ; c++ )
magic[r][c] = 0;
*f = oddfunction(*f);
z = *f;
cout <<"\n\n";
d = 0 ;
e = (z-1) / 2;
magic[d][e] = 1;
for ( r=2 ; r <= z * z ; r++ )
{
d--;
e++;
if ( d < 0 && e == z )
{
d = d + 2;
e--;
}
if ( d < 0 ) { d = z - 1; } if ( e >= z ) { e = 0; } if ( magic[d][e] != 0 )
{
d = d + 2;
e = e - 1;
}
magic[d][e] = r;
}
for(r=0;r < z;r++)
{
for(c = 0; c < z; c++)
{
cout << setw(4) << magic[r][c];
}
cout << endl;
}
endfunction(*g);
}
cout << endl;
cout << "Have a nice day! THE END \n";
system("pause");
return 0;
}
int maxfunction()
{
int c=0;
cin >> c;
while(c >= 20)
{
cin.clear();
cin.ignore(numeric_limits<int>::max(),'\n');
cout << "Input an odd integer up to 19.\n";
cin >> c;
}
return c;
}
int oddfunction(int &a)
{
int cont=0;
while(cont == 0)
{
cout << "Input an odd number: " << endl;
a = maxfunction();
if(a % 2 == 0 )
{
if(a % 2 == 0 )
{
cout << "That wasn't odd! (odd numbers aren't divisible by 2)\nEnter any number to continue:" << endl;
a = maxfunction();
}
else
{
a = maxfunction();
cont++;
}
}
else
{
cont++;
}
}
return a;
}
int endfunction(int &exit)
{
int h=0;
int i=2032;
h = exit;
cout << "\n-Input 2032 to quit... \n-Input any other number to continue..." << endl;
cin >> h;
if(h == i)
{
exit = 0;
return exit;
}
else
{
exit = 1;
return exit;
}
}