Write a program in java to get an output
aaaa
aaaa
aaaa
Answers
For Loop - Java
The question requires us to understand and use the For Loop in Java.
The for loop is used to execute a specific part of code for a given number of times.
The syntax of the for loop is:
The start condition can be anything simple. Like . After this, we need a semicolon (;) and we mention the end condition. Like . After this we put a semicolon again and mention the increment/decrement operation. For example, .
Let's see a simple example:
for(int num = 0; num < 5; num++)
{
System.out.println(num);
}
Output:
0
1
2
3
4
The loop starts with num = 0. The end condition is num < 5. So, the loop will keep running until the value of num becomes greater than or equal to 5.
So, the loop starts with num = 0. It checks if num < 5, which is true (as 0 < 5) and then executes the print statement inside. It prints the value of num to the screen. Then, the num++ part increments value of num by 1.
Now, num = 1. It checks the num < 5 again, which is true, and so prints num to the screen. It goes like this. Now at the end, we have num = 4 printed. The num++ will make num = 5. Now, num < 5 evaluates to false, so the loop terminates.
The loop printed 0 to 4 on the screen.
Analysing the Pattern
We need the output:
The pattern has three lines. So, we will need a loop to run 3 times. We can accomplish this using a for loop.
On each line, we have the letter "a" printed 4 times. So, inside the loop, we can create another loop which will run 4 times and print "a". So, we are creating a loop inside a loop, which is called a nested loop.
Using this nested loop concept, we can create the required output.
We have an outer loop running 3 times, and an inner loop running 4 times. Here's the Program Code.
Program Code - SimpleForLoop.java
public class SimpleForLoop
{
public static void main(String[] args)
{
//Create Outer Loop to run 3 times for 3 lines
for(int i = 0; i < 3; i++)
{
//Create Inner Loop to run 4 times for 4 "a"s
for(int j = 0; j < 4; j++)
{
System.out.print("a"); //Print "a"
}
//Print new line after each row
System.out.println();
}
}
}
Answer:
hope it helps...........