9
999
99999
9999999
this is a computer program.......
please do this program......
i can't....
I want correct answer.......
Answers
ANSWER
9
999
99999
9999999
0000
Question:-
- Write a Java program to print the pattern.
9
9 9 9
9 9 9 9 9
9 9 9 9 9 9 9
Program:-
import java.util.*;
class Pattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int n=sc.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=2*i-1;j++)
System.out.print(9+" ");
System.out.println();
}
}
}
Do you know?
This can be solved using 1 loop also,
This is the program..
import java.util.*;
class Pattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int n=sc.nextInt(), a=1;
for(int i=1;i<=n;)
{
if(a<=2*i-1)
{
System.out.print("9 ");
a++;
}
else
{
i++;
a=1;
System.out.println();
}
}// end of for loop.
}// end of main() method.
}// end of class.
Output:-
Enter the number of rows: 2
9
9 9 9
Enter the number of rows: 4
9
9 9 9
9 9 9 9 9
9 9 9 9 9 9 9
Explanation:-
I have taken input which asks the user for the number of rows. (variable n)
Now, I have created a for loop where initial value of i is 1 and it runs till the value of i is less than or equal to n.
Now, inside the loop, another loop is created in which, initial value of j is 1 and it runs till the value of j is 1,3,...(2*i-1). Inside the loop, 9 is printed.
When i=1;
j=1 and j<=2*1-1=2-1=1 (loop runs for 1 time after first iteration of outer loop)
When i=2;
j=1 and j<=2*2-1=3 (loop runs for 3 times and 9 is printed 3 times ..)
Similarly, 9 is printed 5,7,9 times.