0% found this document useful (0 votes)
36 views1 page

Spiral

This Java program accepts the number of rows and columns from the user to create a 2D array. It then populates the array in a spiral pattern, starting with the top row, right column, bottom row, and left column, continuing with inner rows and columns and decrementing the size by 2 each iteration. Finally, it displays the populated array in spiral form.

Uploaded by

Subhasish Dhar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views1 page

Spiral

This Java program accepts the number of rows and columns from the user to create a 2D array. It then populates the array in a spiral pattern, starting with the top row, right column, bottom row, and left column, continuing with inner rows and columns and decrementing the size by 2 each iteration. Finally, it displays the populated array in spiral form.

Uploaded by

Subhasish Dhar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Class spiral

1/1

import java.io.*; class spiral { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in )); System.out.println("enter the no. of rows and columns");//accepting size of array from user int n=Integer.parseInt(br.readLine()); int a[][]=new int[n][n];//declaring the array int copy=n; int k=1,r=0,c=-1;//initialising variables while(n>0)//populating the array { for(int i=1;i<=n;i++)//populating top row { a[r][++c]=k++; } for(int i=1;i<=n-1;i++)//populating right column { a[++r][c]=k++; } for(int i=1;i<=(n-1);i++)//populating last row { a[r][--c]=k++; } for(int i=1;i<=(n-2);i++)//populating left column { a[--r][c]=k++; } n=n-2;//populating inner rows and columns } for(int i=0;i<copy;i++)//displaying the array in spiral form { for(int j=0;j<copy;j++) { if (a[i][j]/10==0) System.out.print(a[i][j]+" "); else System.out.print(a[i][j]+" "); } System.out.println(); } } }

Sep 14, 2011 12:08:35 AM

You might also like