Eight queens are to be placed on an 8 x 8 chessboard in such a way that one quee
ID: 3763827 • Letter: E
Question
Eight queens are to be placed on an 8 x 8 chessboard in such a way that one queen is to be in each row. A program will store an array x[] with capacity 8 to represent such a configuration. If x[r] has value c then in row r there is a queen in column c. Write a program that asks a user to enter the columns that contain queens in the 8 rows. The program makes sure there are no queens in the same column.The program then prints the board. For example, if the user enters: 0,3,4,0,0,7,6,7 the program should print: No Good. (Hint: Use nested for loop, if column c == array[r] Print ‘Q’, otherwise Print ‘.’) For example, if the user enters: 1,3,4,5,2,8,6,7 the program should print: Q....... ..Q..... ...Q.... ....Q... .Q...... .......Q .....Q.. ......Q.
Explanation / Answer
This below C++ program will work the as per given problem statement in this question, and I have written
very detailed commnets for each section of the source code. which part of the source code what it will do.
#include <iostream>
using namespace std;
int main()
{
int x[8], i, j, flag, count =0;
// Reading Array Elements into the Array
cout << "Enter 8 columns for queens(Between 0- 7):";
for (int r = 0; r < 8; r++)
{
cin >> x[r];
}
// Find the First Occurence of Duplicate Element in the Given array Elements
for (i=0, j=1; j< 8; ++i,++j)
{
if (x[i] == x[j])
{
//cout << "No Good"<<endl;
count++;
break; // If Duplicate element found it will break the loop and print the No Good Statement in Console
}
else
{
flag = 2;
// If the array doesn't have the duplicate the flag value has to be 2
}
}
// Logic for printing Queens in the Chess Board
if( count < 1)
{
for (int r = 1; r < 8; r++)
{
for (int c = 1; c < 8; c++)
{
if (c == x[r])
cout << "Q";
else
cout << ".";
}
cout << endl;
}
}
else
{
cout << "No Good"<<endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.