Mohamed Abdelrahman
Mohamed Abdelrahman

Reputation: 81

magic square algorithm without array (C)

I am trying to solve magic square problem using c programming language. But when I run the below code nothing happened. what is wrong with it ?

Here is my code

Logic:

  1. Ask user to enter size of magic square

  2. Loop through total size

  3. Get the position of number 1

  4. Also get the position of other numbers


#include<stdio.h>
#include<conio.h>
int main()
        {
          int col,row,i,size,totalSize;
          printf("please enter size of magic box\n");
          scanf("%d",&size);
          totalSize =size * size ;
          printf("total magic square size %d\n",totalSize);
          for(i=1;i<=totalSize;i++)
          {
                if(i==1)
                {
                  row =1;
                  col=(size+1)/2;
                }else if(((i-1) % size) == 0){
                  row++;
                }else{
                  row--; col--;
                  if(row == 0)
                   row = size;
                  if(col == 0)
                   col = size;
                }
                gotoxy(col,row);
           printf("%d",i);

          }
          return 0;
        }

Upvotes: 0

Views: 5510

Answers (1)

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33273

Your problem seems to be related to your development environment. It seems like, in your IDE, when the program ends, the program window is closed.

There are two ways to work around the problem.

The first way is to compile your program into an exe file and run it from a cmd window.

The second way is to introduce a delay before the program ends. You could insert a call to sleep for a number of seconds or read/scanf something from standard input.

I ran your program and instead of printing at coordinate col, row I printed (col, row) i.

The output looked like this (looks fine to me):

please enter size of magic box
3
total magic square size 9
(2, 1) 1
(1, 3) 2
(3, 2) 3
(3, 3) 4
(2, 2) 5
(1, 1) 6
(1, 2) 7
(3, 1) 8
(2, 3) 9

Upvotes: 1

Related Questions