I have created a program to generate the alternate squares of 0 and 1 but it's not showing the expected output. Pls help.
import java.util.Scanner;
public class LEDLights {
public static void main(String[] args) {
int size;
System.out.println("Enter the size of an array:");
Scanner sc=new Scanner(System.in);
size=sc.nextInt();
System.out.println("Enter the array elements:");
int myarr[][]=new int[size][size];
for(int i = 0; i < size; i )
{
for(int j = 0; j < size; j )
{
myarr[i][j]=sc.nextInt();
}
}
System.out.println("Status of the lights");
for(int i = 0; i < size; i )
{
for(int j = 0; j < size; j )
{
System.out.print( myarr[i][j] " ");
}
System.out.println();
}
//int n=5;
//printing the outer loop
for(int i = 0; i < size; i )
{
for(int j = 0; j < size; j )
{
if(i==0 || i==size-1 || j==0 || j==size-1)
myarr[i][j]=1;
}
}
// inner loops of 1
// int p=size;
for(int p=size-3;p>=size/2;p-=2) {
for(int t =2 ; t <=size/2; t =2)
{
// int p=size-3;
//while(p>=size/2) {
for(int i = t; i <=p; i )
{
for(int j = t; j <=p; j )
{
if(i==t || i==p || j==t || j==p)
myarr[i][j]=1;
}
}
}
//p-=2;
}
// inner loops of 0
for(int k =1 ; k <size/2; k =2)
{
for(int p=size-2;p>size/2;p-=2) {
for(int i = k; i <=p; i )
{
for(int j = k; j <=p; j )
{
if(i==k || i==p || j==k || j==p)
myarr[i][j]=0;
}
}
}
}
System.out.println("LED lights blinking\n");
for(int i = 0; i < size; i )
{
for(int j = 0; j < size; j )
{
System.out.print( myarr[i][j] " ");
}
System.out.println();
}
}
}
expected output for 8*8
1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 1
1 0 1 1 1 1 0 1
1 0 1 0 0 1 0 1
1 0 1 0 0 1 0 1
1 0 1 1 1 1 0 1
1 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1
CodePudding user response:
import java.util.Scanner;
class LEDLights {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of an array:");
int size = sc.nextInt();
System.out.println("Enter the outer status of light. Either 0 or 1");
int startPoint = sc.nextInt();
int[][] myarr = new int[size][size];
myarr = updateArr(myarr, 0, size, startPoint);
for (int i = 0; i < size; i ) {
for (int j = 0; j < size; j )
System.out.print(myarr[i][j] " ");
System.out.println();
}
}
private static int[][] updateArr(int[][] myarr, int startsize, int endsize, int startPoint) {
if (startsize > endsize)
return myarr;
for (int i = startsize; i < endsize; i )
for (int j = startsize; j < endsize; j )
myarr[i][j] = startPoint;
return updateArr(myarr, startsize 1, endsize - 1, (startPoint == 0) ? 1 : 0);
}
}
This gives you an alternate code but will be doing more iterations