I have written a program to print the given string diagonally (like x)
Input: PROGRAM
Expected output:
P M
R A
O R
G
O R
R A
P M
My output:
P
M
R
A
O
R
G
R
O
A
R
M
P
My Java class:
import java.util.*;
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
char[] word = new char[100];
word = s.toCharArray();
int count=0;
int k = s.length()-1;
for (int i=0;i<s.length();i++){
for (int j=0;j<s.length();j++){
if(!(i==k))
System.out.println(word[i]);
for(int x=0;x<s.length()-count;x++)
System.out.print(" ");
System.out.println(word[k]);
k--;
count++;
break;
}
for(int j=0;j<count;j++)
System.out.print(" ");
}
}
}
Your logic works only upper part of Horizontal line. Go through the below Program:
import java.util.*;
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
char[] word = new char[100];
word = s.toCharArray();
int k = s.length()-1;
int x ;
for (int i=0;i<s.length();i++){
if((i<k))
{
for (x=0; x<i; x++)
System.out.print(" ");
System.out.print(word[i]);
for ( x=0; x<k-i-1; x++)
System.out.print(" ");
System.out.println(word[k]);
k--;
}
else if(i == k){
for ( x=0; x<i; x++)
System.out.print(" ");
System.out.println(word[k]);
k--;
}
else{
for(x = k; x >= 0 ; x--)
System.out.print(" ");
System.out.print(word[k]);
for (x=0; x<i-k-1; x++)
System.out.print(" ");
System.out.println(word[i]);
k--;
}
}
}
}
It gives output as you saying.