Flag Pattern in Java
The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers.
We separate the entire procedure into the following steps that are required to print an Indian flag:
- The flag's topmost layer.
- The flag's second tier.
- The flag's third layer.
- The flagpole.
- Stairs separate.
We only use a single nested for loop to print every section of the Indian flag.
Program to Print Flag Pattern in Java
import java.io.*;
import java.util.*;
// To print the Indian flag star pattern, build the class IndianFlag
public class IndianFlag
{
// start the main() method
public static void main(String[] args)
{
// declaring and setting up variables
int height = 26;
int width = 40;
int temp = 3;
// To print the entire flag, we only require one nested loop.
for(int m = 1; m<= height; m++) {
for(int n = 1; n <= width; n++){
// create the first part of the Indian flag
if(m <= 4) {
if(m == 1 || m == 4) {
if(n >= 15 && n<= 35) {
System.out.print("*");
} else {
System.out.print(" ");
}
} else {
if(m ==2 || m ==3) {
if(n == 15 || n == 35) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
}
if(m > 4 && m <= 8) {
// second part of the flag
if(m <= 7) {
if(n == 15 || n == 35) {
System.out.print("*");
} else {
if(n >= 22 && n<= 28) {
System.out.print("-");
} else {
System.out.print(" ");
}
}
} else {
if(n >= 15 && n<= 35) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
if(m > 8 && m <= 11) {
// third part of the flag
if(m <= 10) {
if(n == 15 || n == 35) {
System.out.print("*");
} else {
System.out.print(" ");
}
} else {
if(n >= 15 && n <= 35) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
if( m>= 12 && m <= 19) {
// stick of the flag
if(n == 15) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
// to print the stairs of the flag
if( m>= 20) {
if(m % 2 == 0) {
if(n >= 15 - temp && n <= 15 + temp) {
System.out.print("*");
} else {
System.out.print(" ");
}
} else {
if(n == 15 - temp || n == 15 + temp) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
}
if(m >= 20) {
if(m % 2 != 0) {
temp++;
}
}
System.out.print("\n");
}
}
}
The output of the above program
