In: Computer Science
. . . . .
. . . . .
. . r . .
. . . . .
. . . . .
Grow 1
. . . . .
. . r . .
. r r r .
. . r . .
. . . . .
Grow 2
. . r . .
. r r r .
r r r r r
. r r r .
. . r . .
Grow 3
. r r r .
r r r r r
r r r r r
r r r r r
. r r r .
Grow 4
r r r r r
r r r r r
r r r r r
r r r r r
r r r r r
Hello, I need help creating a grow function that grows the rose based on the user input. This is in java
CODE:
package rose;
import java.util.Scanner;
public class Rose
{
//function that grows the rose
private static void growRose(char[][] arr, int
n)
{
//initialising the array
with dosts
for(int
i=0;i<5;i++)
for(int j=0;j<5;j++)
arr[i][j]='.';
//calculating start and
end index, which is basically sucstracting value of (n-1) from 2
and adding 2 for end
//rose variable stores
the number of rose to start with
int startRowIndex =
2-(n-1),endRowIndex = 2+(n-1),rose = 1;
//if startIndex after
substracting becomes less than 0, then we make it to 0, and change
the number of rose
if(startRowIndex<0)
{
rose+=(2*(-startRowIndex)-1);
startRowIndex = 0;
}
//if endIndex becomes
greater tahn 4, or goes out of size of array, then assign it to
endRowindex
if(endRowIndex
>4)
endRowIndex = 4;
//Now we start a for
loop from startRowIndex to startColIndex
for(int
i=startRowIndex;i<=endRowIndex;i++)
{
//we calculate startColIndex and End column index value by
following formula
int startColIndex = 2-rose/2;
int endColIndex = 2+rose/2;
//check if out of bound, then maki it in the bounds
if(startColIndex<0)
startColIndex=0;
if(endColIndex>4)
endColIndex=4;
//we run for loop to change the array index to value 'r'
for(int j=startColIndex;j<=endColIndex;j++)
arr[i][j]='r';
//if value of 'i' is less than 2, then we increment the number of
rose by 2
if(i<2)
rose+=2;
//else we decrement by 2
else
rose-=2;
}
}
public static void main(String[] args)
{
//defining the
2d-array
char[][] arr = new
char[5][5];
Scanner scan = new
Scanner(System.in);
//taking input from
user
int n =
scan.nextInt();
//calling function to
grow the rose according to user input
growRose(arr,n);
//prints the 2d
array
for(int
i=0;i<5;i++)
{
for(int j=0;j<5;j++)
System.out.print(arr[i][j]);
System.out.println();
}
}
}
OUTPUT:
3
..r..
.rrr.
rrrrr
.rrr.
..r..
Ask any question if you have in comment section below.
Please rate the answer.