nested for loop for alphabet increment - java

I have searched everywhere and I cannot figure out how to create this output using a nested for loop in java:
"a
ab
abc
abcd"
continued until z
this is what I have tried
String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i = 0; i <= 25; i++)
{
for(char j = (char)(alphabet.charAt(i)); j<=i; j++)
{
System.out.print(j);
}
System.out.println();
}
Please help me!

Here is the answer:
for (int x = 'a'; x <= 'z'; x++) { /* Loop from 'a' to 'z' */
for (int i = 'a'; i<=x; i++){ /* Loop from 'a' to int x */
System.out.print((char)i);
}
System.out.println(); /* New Line */
}
The outer loop switches from one row to another while the inner loop prints the characters ('a' to x)for that particular row.

Here you go !
print capital Alphabet
public class Main
{
public static void main(String[] args)
{
int i, j;
for(i = 1; i<=26; i++) {
for(j = 1; j <= 1-i; j++) {
System.out.print(" ");
for(j = 1; j <= i; j++)
System.out.print((char)(char)(i+64)+" ");
System.out.println(); //for line break
}
}
}

here you go!!
class nested_loop {
void display () {
char i,j;//i loop controls number of lines and j controls number of times in each line
for(i='A';i<='E';i++) {
{
for(j='A';j<='E';j++) {
System.out.print(j);
}
System.out.println();//blank print statement takes control to the next line
}
}
}
}

Related

How to hide characters using for loops, respectively?

I want to basically hide characters following three constant dots (...), the pattern goes like this:
Inputs a phrase from the user and outputs the phrase followed by three dots (...), then the phrase minus one character followed by three dots (...), then the phrase minus two characters followed by the dots, and so on until only one dot is left.
Note: This has to be done using nested for loops only
Sample input
1
disappear
Expected output:
disappear...
disappea...
disappe...
disapp...
disap...
disa...
dis...
di...
d...
...
..
.
This is my attempt:
Problem: I am unable to make it so the phrase decreases each time (minus 1 each time)
I tried using the charAt(); method, but it wouldn't work, I am sure that you would need a for loop separate for each of the dots or a whole set of dots, in this case.
import java.util.Scanner;
public class Dissappear{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
String phrase = keyboard.next();
if (option == 1){
for (int x = 0; x <= phrase.length(); x++){
System.out.print(phrase + "...");
for (int y = 0; y <= phrase.length(); y++){
char n = phrase.charAt(y);
System.out.print(n+"...");
}
}
}
}
}
This is how I got it to work:
public class Disappear {
public static void main(String... args) {
String word = "disappear";
int originalLength = word.length();
for(int i = 0; i < originalLength; i++) {
System.out.println(word.substring(0, originalLength - i) + "...");
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3 - i; j++) {
System.out.print(".");
}
System.out.println();
}
}
}
Without substring:
public class Disappear {
public static void main(String... args) {
String word = "disappear";
int originalLength = word.length();
for(int i = 0; i < originalLength; i++) {
for(int j = 0; j < originalLength - i; j++) {
System.out.print(word.charAt(j));
}
System.out.println("...");
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3 - i; j++) {
System.out.print(".");
}
System.out.println();
}
}
}
You can do it with StringBuilder:
StringBuilder stringBuilder = new StringBuilder(str);
System.out.println(str + "...");
for (int i = 0; i < length; i++) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
System.out.println(stringBuilder.toString() + "...");
if (i == length - 1) {
for (int j = 0; j < 2; j++) {
for (int k = j; k < 2; k++) {
System.out.print(".");
}
System.out.println();
}
}
Ok! Nested for loops. But the outer one is only included to meet the requirement. Probably not in the spirit of the assignment though. Just keep decrementing k until it is zero and then latch it there until the StringBuilder length is 0 and the inner loop terminates.
StringBuilder sb = new StringBuilder("disappear...");
for (;;) {
for (int k = sb.length() - 4; sb.length() > 0;) {
System.out.println(sb);
sb.delete(k, k + 1);
k = k > 0 ? --k : 0;
}
break;
}

Java save alphabet to array

I try save alphabet A-Z to my array, but I don't understand, why I get only this output: Z.
public class Main {
public static void main(String[] args) {
char []tab = new char[25];
for (int i = 0; i<25; i++) {
for (int j=65; j<91; j++) {
tab[i] = (char)j;
}
}
for (int i=0; i<25; i++) {
System.out.println(tab[i]);
}
}
}
Your algorithm is wrong.
Check this simpler solution:
public static void main(String[] args)
{
char []tab = new char[25];
for (int i = 0; i<25; i++) {
tab[i] = (char)(i+65);
}
for (int i=0; i<25; i++) {
System.out.println(tab[i]);
}
}
Your code puts all the letters from A to Z in each slot of the tab array, when executing the 'j' loop, that's why you have only Zs.
You don't need nested loop, try this:
char[] tab = new char[26];
for (int i = 0, j = 65; j < 91; j++, i++) {
tab[i] = (char) j;
}
for (int i = 0; i < 26; i++) {
System.out.println(tab[i]);
}
Also, array size should be 26 not 25.
Lets see how your code works:
for (int i = 0; i<25; i++) { //1
for (int j=65; j<91; j++) { //2
tab[i] = (char)j; //3
} //4
} //5
1) Outer loop sets i=0,
2) Inner loop sets j=65
3) (char)65 represents 'A' ant is placed in tab[0]
2) Inner loop sets j=66
3) (char)66 represents 'B' and is also placed in tab[0]
Here you should notice the problem, which is that inner loop is working on same i, so while iterating over A...Z it is modifying same array location, which means that location will hold last value placed there, which is 'Z'.
(BTW i<25 should be i<26)
Possible solution
don't use inner loop, you can calculate value which should be placed at index by adding i to 65 which in Unicode Table is codepoint of 'A'
for (int i=0; i<26; i++)
tab[i] = (char)(65+i);
BTW you can farther improve readability of this code by avoiding magic numbers (more info: What is a magic number, and why is it bad?). So this code can be rewritten into something like:
int amountOfLetters = 'Z' - 'A' + 1;
char[] tab = new char[amountOfLetters];
int i = 0;
for (char ch = 'A'; ch <= 'Z'; ch++) {
tab[i++] = ch;
}
System.out.println(new String(tab));

printing v shape in java

I am a newbie to java programming and I am working on this excercise from my textbook. The goal is to print a V shape pattern of numbers. From the picture below, you can see what the output should look like. I am having trouble creating the other half of numbers. I have pasted my code down below for reference.
for (int i = 7; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int k = 1; k >= i*2; k++) {
System.out.print(" ");
}
System.out.println(i);
Use the following code (just made a few modifications to your code, did not check its efficiency):
public static void main(String[] args) {
for (int i = 7; i >= 1; i--) {
for (int k = 7; k >= i; k--) {
System.out.print(" "); // Print 7-i number of spaces before start of each line
}
System.out.print(i); // Print i
for (int j = 1; j <= i*2; j++) {
System.out.print(" "); // Print i*2 number of spaces after printing i
}
System.out.println(i); // Print i
}
}
Rather then nesting loops (and iterating backwards), I would decompose the generating of white-space with a method to repeat a given String a given number of times. Like,
private static String repeat(String s, int n) {
return Stream.generate(() -> s).limit(n).collect(Collectors.joining());
}
Then I would prefer a StringBuilder and a single call to println like
public static void main(String[] args) {
int start = 6;
for (int i = 0; i < start; i++) {
int v = start - i;
StringBuilder sb = new StringBuilder();
sb.append(repeat(" ", i)).append(v);
sb.append(repeat(" ", 2 * v)).append(v);
System.out.println(sb);
}
}

Java: Printing two dimensional array in grid format

I'm having difficulty figuring out the code to print a two dimensional array in grid format.
public class TwoDim {
public static void main (String[] args) {
int[][] ExampleArray = new int [3][2];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
ExampleArray[i][j] = i * j;
System.out.println(j);
}
System.out.println(i);
}
}
}
System.out.println(s) prints s, then prints a line return character. So if you want multiple print calls to end up on the same line, you should use System.out.print(s) instead.
Additionally, you can use System.out.println() (with no argument) to print nothing, but move to the next line. Bringing all of that together:
public class TwoDim {
public static void main (String[] args) {
int[][] ExampleArray = new int [3][2];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 2; j++){
ExampleArray[i][j] = i * j;
System.out.print(j + " ");
}
System.out.println();
}
}
}
When you use System.out.println(...);, it prints a newline char ('\n') after the string you intended to print. This should only happen if your line is over (i.e., outside the innest for statement). So, your for loops should be:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
ExampleArray[i][j] = i * j;
System.out.print(ExampleArray[i][j] + ' '); //You can replace ' ' by '\t', if
//you want a tab instead of a space
}
System.out.println("");
}
Hope that helps.

Printing special characters in a for loop instead of numbers

This is what the program is printing:
(0,0)(0,1)(0,2)
(1,0)(1,1)(1,2)
(2,0)(2,1)(2,2)
What I want it to do is to print ( * ) in replace of (1,1). I know an if statement is involved, but I'm having a hard time trying to figure out the condition I should put.
public class loops {
public static void main(String[] args)
{
int i=1;
for (int k = i-1; i< 4; i++)
{
int j =1;
for (int l = j-1; j < 4; j++)
{
if (k ==i+1 && l == j+1) System.out.print("( * )");
else System.out.print("("+k+","+l+")");
l++;
}
System.out.println();
k++;
}
}
}
The if condition is part of it, but you are also complicating your for loops, try this:
public class loops {
public static void main(String[] args)
{
for (int k = 0; k<3; k++)
{
for (int j = 0; j<3; j++)
{
if (k ==1 && j == 1)
{
System.out.print("( * )");
} else {
System.out.print("("+k+","+j+")");
}
}
System.out.println("");
}
}
}
you should just validate if both values are equal to 1 then print (*) , otherwise the result

Categories