Answer to Question #300300 in Programming & Computer Science for Aljon

Question #300300

Machine Exercise # 1 : Arrays and Strings


Write a program that uses a 3 3 3 array and randomly place each integer from 1 to 9 into the


nine squares. The program calculates the magic number by adding all the numbers in the array


and then dividing the sum by 3. The 3 3 3 array is a magic square if the sum of each row, each


column, and each diagonal is equal to the magic number. Your program must contain at least


the following functions: a function to randomly fill the array with the numbers and a function to


determine if the array is a magic square. Run these functions for some large number of times,


say 1,000, 10,000, or 1,000,000, and see the number of times the array is a magic square.


NOTE : SUBMISSION IN CPP FORMAT

1
Expert's answer
2022-02-20T14:40:25-0500




#include <iostream>
#include<ctime>   //For time()
#include<cstdlib> //For rand() and srand()


using namespace std;






void fillArray(int numbers[3][3]){
	for(int i=0;i<3;i++){
		for(int j=0;j<3;j++){
			numbers[i][j]=rand()%10+1;
		}
	}
}
//calculates the magic number by adding all the numbers in the array and then dividing the sum by 3.
int calculateMagicNumber(int numbers[3][3]){
	int sum=0;
	for(int i=0;i<3;i++){
		for(int j=0;j<3;j++){
			sum+=numbers[i][j];
		}
	}
	return (int)(sum/3);
}


//The 3 3 array is a magic square if the sum of each row, each column, and each diagonal is equal to the magic number.
bool isMagicSquare(int numbers[3][3],int magicNumber){
	int sum;
	for(int i=0;i<3;i++){
		sum=0;
		for(int j=0;j<3;j++){
			sum+=numbers[i][j];
		}
		if(sum!=magicNumber){
			return false;
		}
		sum=0;
		for(int j=0;j<3;j++){
			sum+=numbers[j][i];
		}
		if(sum!=magicNumber){
			return false;
		}
	}


	sum=0;
	for(int j=0;j<3;j++){
		sum+=numbers[j][j];
	}
	if(sum!=magicNumber){
		return false;
	}
	sum=numbers[0][2]+numbers[1][1]+numbers[2][0];
	if(sum!=magicNumber){
		return false;
	}


	return true;
}
//the number of times the array is a magic square
void calculateNumberTimesArrayIsMagicSquare(int times){
	int numberTimes=0;
	for(int i=0;i<times;i++){
		int numbers[3][3];
		fillArray(numbers);
		int magicNumber=calculateMagicNumber(numbers);
		if(isMagicSquare(numbers,magicNumber)){
			numberTimes++;
		}
	}
	cout<<"Times = "<<times<<". The number of times the array is a magic square: "<<numberTimes<<"\n\n";
}


int main() {
	srand(time(NULL));	
	calculateNumberTimesArrayIsMagicSquare(1000);
	calculateNumberTimesArrayIsMagicSquare(10000);
	calculateNumberTimesArrayIsMagicSquare(1000000);


	system("pause");
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS