Massassi Forums Logo

This is the static archive of the Massassi Forums. The forums are closed indefinitely. Thanks for all the memories!

You can also download Super Old Archived Message Boards from when Massassi first started.

"View" counts are as of the day the forums were archived, and will no longer increase.

ForumsDiscussion Forum → Massassi, can you help me with my homework? (C/C++)
Massassi, can you help me with my homework? (C/C++)
2007-11-26, 11:16 PM #1
After a week off from school and lots of turkey, I can't figure this out, hopefully someone here can help me.

Here's the deal: I have to write a program in C (or C++) to read a set of numbers from an input file and determine if it's a magic square and output the result to a text file. Ok, Got that done. Now the problem, I have to get it to continue reading from the input file with an undetermined number of 'squares' and output the results to the output file until there are no more squares to read.

the format of the square is this:
n
a[sub]11[/sub] a[sub]12[/sub] a[sub]13[/sub] a[sub]1n[/sub]
a[sub]21[/sub] a[sub]22[/sub] a[sub]23[/sub] a[sub]2n[/sub]
a[sub]31[/sub] a[sub]32[/sub] a[sub]33[/sub] a[sub]3n[/sub]
a[sub]n1[/sub] a[sub]n2[/sub] a[sub]n3[/sub] a[sub]nn[/sub]

where n is the size of the square

and here is what I have with some of the debug statements commented out(I know there are easier ways to go about doing this, but my instructor wants it done in this manner, he wants a separate function for every operation):
Code:
//Assignment 7

//test reading function and to determine magic square value for assign 7
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10

void readem(int x[MAX_SIZE][MAX_SIZE],int *n, int *end);
void get_the_value(int x[MAX_SIZE][MAX_SIZE],int *n,int *value);
void off_diag(int x[MAX_SIZE][MAX_SIZE], int *n, int *value, int *okay);
void rows(int x[MAX_SIZE][ MAX_SIZE], int *n, int *value, int *okay);
void cols(int x[MAX_SIZE][ MAX_SIZE], int *n, int *value, int *okay);
void output_file(int x[MAX_SIZE][ MAX_SIZE], int *n, int *num, int *ismagic, int *eof);

int main()
{
int row, col; //dummy variable to access the array values
int okay = 1; //dummy variable to test if the function should continue to the next test, assume true
int endoffile = 0; // dummy variable to hold if the source.txt has been read to the end
int mn; //magic number of the current square
int ms[MAX_SIZE][MAX_SIZE]; //table for holding matrix values for magic square
int size; // array size
	readem (ms, &size, &endoffile);

	//prints out the values of the square to the console
	for (row = 1; row <=size; row++)
	{
		for (col = 1; col <= size; col++)
			printf("%4d",ms[row][col]);
		printf("\n");
	}
	
	get_the_value(ms,&size,&mn);
	printf("The magic value is %d\n",mn);

	off_diag(ms, &size, &mn, &okay);
	//printf("\noff_diag okay? %d\n", okay);
	if(okay)
	{
		rows(ms, &size, &mn, &okay);
		//printf("rows okay? %d\n", okay);
	}
	if(okay)
	{
		cols(ms, &size, &mn, &okay);
		//printf("cols okay? %d\n", okay);
	}
	//outputs the results to a text file
	output_file(ms, &size, &mn, &okay, &endoffile);

	return (0);
}

//This function reads the size of the array and then array elements 
//and returns the filled array and size to the main program
void readem(int x[MAX_SIZE][MAX_SIZE],int *n, int *end)
{
	FILE *fin;
	int i,j;
	int input_status;
	if((fin = fopen("source.txt", "r")) == NULL)
	{
		printf ("cannot open the file for reading\n");
		exit(1);
	}
	input_status =fscanf(fin,"%d", n);
	//printf ("size of matrix is %d\n",*n);

	//assigns the read values to the array
	for (i=1; i<= *n;i++)
	{
		for (j=1; j<= *n; j++)
		{
			input_status = fscanf(fin, "%d",&x[j]);
		}
	}
	if(input_status == EOF)
	{
		//printf("FILE END!");
		fclose(fin);
		*end = 1;
	}
}

void get_the_value(int x[MAX_SIZE][MAX_SIZE],int *n,int *value)
{
	int i,sum=0;
	for (i=1;i<=*n;i++)
		sum +=x;  // add the diagonal elements
	*value = sum;      //this time only
	// printf("%d\n",*value);
}


void off_diag(int x[MAX_SIZE][MAX_SIZE], int *n, int *value, int *okay)
{
	int i, sum = 0;
	for(i=0; i<=*n-1; i++)
	{
		sum = sum + x[i+1][*n-i];
		//printf("%d sum of off diagonal = %d\n", i, sum);
	}
	if(sum == *value)
	{
		*okay = 1;
	}		
	else
	{
		*okay = 0;
	}
}

void rows(int x[MAX_SIZE][ MAX_SIZE], int *n, int *value, int *okay)
{
	int i, j, sum = 0;
		for(i = 1; i<=*n; i++)
		{
			sum = 0;
			for(j=1; j<=*n; j++)
			{
				sum = sum + x[j];
				//printf("[%d][%d] sum of rows = %d\n", i, j, sum);
			}
			if(sum != *value)
				*okay=0;
		}
}

void cols(int x[MAX_SIZE][ MAX_SIZE], int *n, int *value, int *okay)
{
	int i, j, sum = 0;
		for(j = 1; j<=*n; j++)
		{
			sum = 0;
			for(i=1; i<=*n; i++)
			{
				sum = sum + x[j];
				//printf("[%d][%j] sum of cols = %d\n", i, j, sum);
			}
			if(sum != *value)
				*okay=0;
		}
}

void output_file(int x[MAX_SIZE][ MAX_SIZE], int *n, int *num, int *ismagic, int *eof){
	int row, col;//dummy variable to access the array values

	FILE *fout;
	if((fout = fopen("output.txt", "w")) == NULL)
	{
		printf ("cannot open the file for writing\n");
		exit(1);
	}
	//display the square in the output file
	for (row = 1; row <=*n; row ++)
	{
		for (col = 1; col <= *n; col++)
			fprintf(fout, "%4d ",x[row][col]);
		fprintf(fout, "\n");
	}
	//tell if it is a magic square or not
	if(*ismagic)
	{
		fprintf(fout, "is a magic square whose constant is %d\n\n", *num);
	}
	else
	{
		fprintf(fout, "is not a magic square\n\n");
	}
	//close files if the end of the input file has been reached
	if(*eof == 1)
		fclose(fout);

}

readem() reads the size and the square from source.txt
get_the_value() finds the sum of the diagonal from top left to bottom right
off_diag() same as above, but the opposite way
rows() finds the sums of the rows
cols() finds the sums of the columns
output_file() outputs the results to output.txt


Now that works for reading the first square (of any size) from source.txt and does output to output.txt correctly, but I cannot for the life of me get it to continue to read the input file. I tried a do-while loop in main(), but it only succeeded in the first square being reprinted in the console about 508 times before it printed "unable to open file for reading" with the output file having the first square's results in it. Other things I tried got it to display the first square then do nothing, not freeze, just do nothing.

How can I get this to continue reading from the input file? Please help.

[EDIT]I will post the input file if needed, but it should be easy enough to make a small one yourself[/EDIT]
2007-11-26, 11:42 PM #2
I don't have it any more (damn student licenses!) but if anyone has access to MATLAB it has an in-built function magic.m that will show you a complete and working way to implement it. It might not be exactly what you're after, but it might be a start.
2007-11-27, 12:59 AM #3
Read in each line to a string, split the string, convert each element of the resulting array to an int.

You should really be using the STL...
Bassoon, n. A brazen instrument into which a fool blows out his brains.
2007-11-27, 2:10 PM #4
I can't change the way it reads from the source file, the function for reading the file (readem()) was given to us in the assignment directions. I have to use that function without changing how it reads the data, I can only add a check to it to see if it's at the end of the file.
2007-11-27, 5:37 PM #5
Oh, that's completely retarded. It seems as if your assignment is more about convoluted file IO than it is about magic squares.
Bassoon, n. A brazen instrument into which a fool blows out his brains.
2007-11-27, 5:43 PM #6
Yeah, I don't understand my instructor either. He wants us to learn how to do things the complicated way while telling us that any company we work for will want us to use the most simple to understand way of programming.
Its' completely backwards.

:suicide:
2007-11-27, 7:17 PM #7
Originally posted by Stormtrooper:
I can't change the way it reads from the source file, the function for reading the file (readem()) was given to us in the assignment directions. I have to use that function without changing how it reads the data, I can only add a check to it to see if it's at the end of the file.

I hate when instructors did that to me. Although, I can see a point of showing you what it is like to work with ****ty code. Trust me, you will get ****ty code in the workforce.
Code to the left of him, code to the right of him, code in front of him compil'd and thundered. Programm'd at with shot and $SHELL. Boldly he typed and well. Into the jaws of C. Into the mouth of PERL. Debug'd the 0x258.
2007-11-27, 8:00 PM #8
Yeah, but he's just beginning, and now is not at all the time to do that.
Bassoon, n. A brazen instrument into which a fool blows out his brains.
2007-11-28, 5:25 AM #9
Look at this line in readem:
FILE *fin;

Each time readem is called, that fin variable goes out of scope, so that when readem is called again, a *new* fin variable is used and the file is opened *again*. Upon opening that file 508 *different* times, the OS complains that the program has reached a limit.

Although I disagree with using such antiquated coding (C-style file IO), there are plenty of important concepts in the assignment you needed to learn.

:)
2007-11-28, 6:44 AM #10
Originally posted by ZeqMacaw:
Look at this line in readem:
FILE *fin;

Each time readem is called, that fin variable goes out of scope, so that when readem is called again, a *new* fin variable is used and the file is opened *again*. Upon opening that file 508 *different* times, the OS complains that the program has reached a limit.

Although I disagree with using such antiquated coding (C-style file IO), there are plenty of important concepts in the assignment you needed to learn.

:)


readem was written by the teacher, confirming my initial suspicion from when I first read the thread.

I would bet that "FILE END!" is never reached because readem contains zero sanity checking. It assumes the file is perfectly written and assumes an EOF condition immediately after the data. I can pretty much guarantee that real life doesn't work that way and as a direct consequence this teacher's code is crap. Change:

Code:
void readem(int x[MAX_SIZE][MAX_SIZE],int *n, int *end)
{
	FILE *fin;
	int i,j;
	int input_status;
	if((fin = fopen("source.txt", "r")) == NULL)
	{
		printf ("cannot open the file for reading\n");
		exit(1);
	}
	input_status =fscanf(fin,"%d", n);
	//printf ("size of matrix is %d\n",*n);

	//assigns the read values to the array
	for (i=1; i<= *n;i++)
	{
		for (j=1; j<= *n; j++)
		{
			input_status = fscanf(fin, "%d",&x[j]);
		}
	}
	if(input_status == EOF)
	{
		//printf("FILE END!");
		fclose(fin);
		*end = 1;
	}
}


to this

Code:
void readem(int x[MAX_SIZE][MAX_SIZE],int *n, int *end)
{
	FILE *fin;
	int i,j;
	int input_status;
	if((fin = fopen("source.txt", "r")) == NULL)
	{
		printf ("cannot open the file for reading\n");
		exit(1);
	}
	input_status =fscanf(fin,"%d", n);
	//printf ("size of matrix is %d\n",*n);

	//assigns the read values to the array
	for (i=1; i<= *n;i++)
	{
		for (j=1; j<= *n; j++)
		{
			input_status = fscanf(fin, "%d",&x[j]);
		}
	}

	if(input_status == EOF)
	{
		//printf("FILE END!");
		fclose(fin);
		*end = 1;
	}
else
{
printf("My teacher writes crappy code");
fclose(fin);
}
}


and then hand it in like that
2007-11-28, 8:23 AM #11
Quote:
Yeah, I don't understand my instructor either. He wants us to learn how to do things the complicated way while telling us that any company we work for will want us to use the most simple to understand way of programming.
Its' completely backwards.

we had to do all kinds of stuff in chemistry and biology and then when we got out into the world we found out there was no need. even the poorest companies had 20 year old second hand automated equipment.
easier than what we were doing. :/
2007-11-28, 7:03 PM #12
So i pointed out to him the bad code and he said others have shows it to him too (unfortunately he never told us as a class, just those that pointed it out to him :\) and gave me working code. Thanks everyone.
2007-11-29, 4:33 PM #13
teachers tend to write crappy code on a regular basis.

my adviser writes some code, runs it on 1k of events, it works, he hands it to me and asks me to add it to my analysis. I run over 100k events and it crashes...I normally end up re-writing everything he gives me now.
People of our generation should not be subjected to mornings.

Rbots

↑ Up to the top!