Objective Implement a nonItrivial algorithm in C Problem A M
Objective: Implement a nonItrivial algorithm in C++.
Problem: A Magic Square of order N consists of N2 squares, each of which contains a number from 1 through N2 such that the rows, columns, and diagonals sum to the same thing (called the magic sum).
Input: Your program should ask the user to enter an odd integer. For the purposes of this program, treat the input as an unsigned short. Every odd number up to 999 is valid for this program. The program should continue prompting for numbers and printing magic squares until the user enters a zero. If an even number is entered, print an appropriate error message and prompt the user to enter another number.
Output: The program should output the magic squares to a text file. You don’t need to print the boxes around the numbers, but arrange the numbers in columns and rows so the square is readable using print formatting. In addition to the magic square, also print out the magic sum.
Miscellaneous: This program must use functions and arrays. It is your decision how many functions are used and how they are defined. There is an algorithm for creating magic squares; make sure you do your research before tackling this program.
Solution
#include<iostream>
#include<string>
#include <fstream>
using namespace std;
// A function to generate odd sized magic squares
void GenerateMagicSquare(int n)
{
int magicSquareArr[n][n];
// initializing array with all zeros
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
magicSquareArr[i][j] = 0;
}
}
// filling first positions values
int i = n/2;
int j = n-1;
// filling remaining matrix array
for (int m=1; m <= n*n; )
{
if (i==-1 && j==n) //our third condition
{
j = n-2;
i = 0;
}
else
{
if (j == n)
j = 0;
if (i < 0)
i=n-1;
}
if (magicSquareArr[i][j]) //second condition
{
j -= 2;
i++;
continue;
}
else
magicSquareArr[i][j] = m++;
j++; i--;// first condition
}
// print output
ofstream outputFile;
outputFile.open (\"output.txt\");
outputFile<<\"\ For matrix square length: \"<<n;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
outputFile<<\" \"<<magicSquareArr[i][j];
cout<<\"\ \";
}
}
// Driver program to test above function
int main()
{
int n;
while(true){
cout<<\"Enter matrix odd n length and -1 to exit\";
cin>>n;
if(n == -1){
break;
}
else if(n%2 == 0){
cout<<\"\ please enter odd number only\";
}
else{
GenerateMagicSquare(n);
}
}
return 0;
}

