pseudocode interpreter: java while - java

for x = 0 to 9
set stars = "*"
set count = 0
while count < x
stars = stars + "*"
count = count + 1
endwhile
display stars
endfor
This is the pseudocode and this is what I've done so far
for(int i=0;i<9;i++) {
for(int j=0;j<9-i;j++) {
System.out.print(" ");
}
for(int k=0;k<=i;k++) {
System.out.print("* ");
}
System.out.println();
I need this code to be changed so it uses BOTH a FOR and WHILE, but i can only manage a FOR.

Any for-loop can be written as a while-loop, just move around the components:
for (init; check; update) {
body...
}
init;
while (check) {
body...
update;
}

As per your pseudo-code:
set count = 0
while count < x
stars = stars + "*"
count = count + 1
you can change your inner loop from:
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
into:
int k = 0;
while (k <= i) {
System.out.print("* ");
k++;
}

a for and while can be easily converted between each other if you know that:
for (a;b;c) {
d;
}
actually (mostly) means
a;
while(b) {
d;
c;
}
Just a reminder, in psuedo code for x = 0 to 9 actually means for (x = 0; x < 10; x++)

for (int i = 0; i < 9; i++)
{
String stars = "";
int count = 0;
while (count < i)
{
stars += "*";
count++;
}
System.out.println(stars);
}

For above pseudo code you can have following Java code
String star = '*';
int count =0;
for(int x =0; x < 9; x++)
{
count =0;
while(count < x)
{
star += star;
count++;
}
System.out.println(star);
}

Related

Why is there a single backlash which doesn't even continue with the pyramid?

The assignment was to create a pyramid by using for loops, print and println functions. I wrote the following code, though without errors, the last backslash is one character before where it should be. There should be five slashes/backslashes on the sides of the pyramid.
public static void main(String[] args) {
for ( int i = 0; i <5; i++) {
if ( i < 4) {
for ( int a = 4 - i; a > 0; a--) {
System.out.print(" ");
}
System.out.print("/");
}
for ( int a = 2 * i; a > 0; a--) {
System.out.print(" ");
}
System.out.println("\\");
}
}
The output should be like in
But it turns out like
What am I doing wrong?
The print for '/' is in the wrong place - it should be outside of the if:
for ( int i = 0; i < 5; i++) {
if ( i < 4) {
for ( int a = 4 - i; a > 0; a--) {
System.out.print(" ");
}
}
System.out.print("/");
for ( int a = 2 * i; a > 0; a--) {
System.out.print(" ");
}
System.out.println("\\");
}
But you don't actually need that if, the for loop condition will deal with not printing a blank on the last row:
for ( int i = 0; i < 5; i++) {
for ( int a = 4 - i; a > 0; a--) {
System.out.print(" ");
}
System.out.print("/");
for ( int a = 2 * i; a > 0; a--) {
System.out.print(" ");
}
System.out.println("\\");
}
And, just for fun, if you are using Java 11 or later you can replace the inner loops with the repeat method of String:
final int limit = 5;
for (int row = 0; row < limit; row++) {
System.out.println(" ".repeat(limit - (row + 1)) + '/' + " ".repeat(2 * row) + '\\');
}
But that is probably not how you are expected to do this assignment.

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 - Hourglass

I'm missing by just a little bit. What I want:
*******
*****
***
*
***
*****
*******
What I'm getting
*******
*****
***
*
*
***
*****
*******
The code
public class HD404 {
public static void main(String[] args) {
int N = StdIn.readInt();
int x = N*2-1;
for (int i = 0; i < N; i++) {
for (int j = i; j > 0; j--) {
StdOut.print(" ");
}
for (int k = 0; k < x; k++) {
StdOut.print("*");
}
x-=2;
StdOut.println();
}
x = 1;
for (int i = 0; i < N; i++) {
for (int j = i; j < N-1; j++) {
StdOut.print(" ");
}
for (int k = 0; k < x; k++) {
StdOut.print("*");
}
x += 2;
StdOut.println();
}
}
}
Right now I'm mostly just guessing and I just can't pin point my error. What am I missing here?
The problems lays with the second part of your code where you ask to draw one star and you start at zero where you should start at one.
Solution
x = 1;
for (int i = 0; i < N; i++)
should be replaced with
x = 3;
for (int i = 1; i < N; i++)
The problem is that you are starting to draw the bottom of the hourglass with 1 asterisk (x = 1) instead of 3.
The second issue is that the bottom of the hourglass only has N-2 lines, not N-1 so the loop should start at 1 instead of 0. This is because the line with a single asterisk was already drawn in the upper-half.
Corrected code:
public static void main(String[] args) {
int N = StdIn.readInt();
int x = N*2-1;
for (int i = 0; i < N; i++) {
for (int j = i; j > 0; j--) {
StdOut.print(" ");
}
for (int k = 0; k < x; k++) {
StdOut.print("*");
}
x-=2;
StdOut.println();
}
x = 3; // <-- not 1 here, the first line has 3 asterisks
for (int i = 1; i < N; i++) { // <-- i starts at 1 because the first line was already drawn in the upper half
for (int j = i; j < N-1; j++) {
StdOut.print(" ");
}
for (int k = 0; k < x; k++) {
StdOut.print("*");
}
x += 2;
StdOut.println();
}
}
As a side-note, you could rewrite this code a lot shorter by making the following observations:
There are x lines to draw so we can loop from 0 to x included (to respect the symmetry) and skip the middle line so as not to draw it twice
For every line, there are x columns to draw and it is either a space or a *.
For every line, * is drawn only if the current column is between min(i, x-i) and max(i, x-i) (if we're in the upper-part, i < x-i and if we're in the bottom-part, i > x-i).
Code:
public static void main(String[] args) {
int N = 4;
int x = 2 * N - 1;
for (int i = 0; i <= x; i++) {
if (i == N) continue; // skip the middle-line for it not to be drawn twice
for (int j = 0; j < x; j++) {
System.out.print(j >= Math.min(i, x-i) && j < Math.max(i, x-i) ? "*" : " ");
}
System.out.println();
}
}
Sample output:
*******
*****
***
*
***
*****
*******
The easiest way I can think up is probably to prevent the last iteration of your first outer loop, that way you'll prevent the first single star line to be shown.
I would probably do it this way:
for(int i = 0; i < N && x > 1; i++)
{
/*Code of the first inner loop*/
}
For those whose still looking for a simpler and lesser code regarding hourglass challenge. This contains 2 for loops only.
You may use this as reference.
public static void hourGlass(int size) {
// 2 for loops only
int dimension = (size * 2) - 1, space = 0, stars = size - 1, printed = 0;
for(int i=0; i<dimension; i++) {
int actual = space;
for (int j=dimension; j > 0; j--) {
if(actual > 0) {
System.out.print(" ");
actual--;
}
else {
System.out.print("*");
if(stars==printed) {
actual = space;
printed = 0;
} else {
actual = 1;
printed++;
}
}
}
if(i <= size-2) { // will pattern spaces and stars from top to middle
space++;
stars--;
}
else { // will pattern spaces and stars from middle to top
space--;
stars++;
}
System.out.println();
}
}

Printing Reverse Triangle with Numbers - Java

I have some problem printing a reverse triangle I want to achieve, like this pattern:
******
***
*
But my goal is to achieve that pattern with this numbers:
333221
221
1
So, this is my code so far:
int x = 1;
for(int r=0;r<3;r++)
{
x=x+r;
for(int c=0;c<x;c++)
{
System.out.print("*");
}
x+=1;
System.out.println();
}
Which the output is upright like this:
*
***
******
I want to make the pattern reverse with the numbers as it shown above.
Can anyone give me some idea how to deal with it? Thanks!
This is how i would do it:
for (i = 3; i > 0; i--) {
for (j = i; j > 0; j--) {
for (c = j; c > 0; c--) {
System.out.print(j);
}
}
System.out.println();
}
first loop: you want to print 3 lines;
second loop: each line has i distinct numbers
third loop: print number j j times
You just need to reverse the order of your loops and decrement x instead of incrementing it. I change the code a bit though :
int level = 3;
for(int r=level ; r>0 ; r--) {
for(int c=r ; c>0 ; c--)
for (int x=0 ; x<c ; x++)
System.out.print("*");
System.out.println();
}
int depth = 3;
for (int r = depth + 1; r >= 0; r--) {
for (int c = 0; c < r; c++)
for (int b = 0; b < c; b++)
System.out.print("*");
System.out.println();
}
#Test
public void reverseTriangle(){
int num = 3;
for (int i = num; i > 0; i--) {
this.draw(i);
System.out.println();
}
}
private void draw(int num) {
int total = 0;
for (int i = 0; i <= num; i++) {
total = total + i;
}
for (int i = 0; i < total; i++) {
System.out.print("*");
}
}

Printing a triangle in Java

I'm practicing basic coding exercises and trying to print the following triangle in Java:
*
***
*****
***
*
The following code gives me the results but I feel like there must be a much more elegant solution
for (int i = 1; i <= 5; i++) {
if (i % 2 == 1) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
for (int i = 3; i > 0; i--) {
if (i % 2 == 1) {
for (int j = 1; j < i + 1; j++) {
System.out.print("*");
}
System.out.println("");
}
}
Can anyone provide some insight into how to make this work in a better way?
Ok, here's some more code that produces the correct result that uses just the two for loops, but it looks even uglier:
for (int i = 1; i <= 10; i += 2) {
if (i <= 5) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
else if(i > 5 && i < 8){
for(int j = i/2; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
else{
for(int j = 1; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
}
First, you are skipping each 2nd iteration of the loop because you want to increase two steps at once. You can do this by changing the "i++" in your loop to "i += 2" and "i--" to "i -= 2", that will have the same effect and allows you to remove the if inside both loops.
Another improvement would be using a single outer loop and figuring out whether the inner loop should be increasing or decreasing the amount of asterisks. Maybe you can come up with an equation that gives you the amount of asterisks based on the value of i? (I didn't want to solve it completely so you have some exercise left, just comment if you want a full solution)
Updated with a solution that might be considered elegant as you can change the height of the triangle and there is no repetition:
int height = 5;
for (int i = 1; i <= 2 * height; i += 2) {
int numAsterisks;
if (i <= height) {
numAsterisks = i;
} else {
numAsterisks = 2 * height - i;
}
for (int j = 0; j < numAsterisks; j++) {
System.out.print("*");
}
System.out.println();
}
What about the following?
public void printTriangle(int size) {
int half = size / 2;
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
char[] a = new char[stars];
Arrays.fill(a, '*');
System.out.println(new String(a));
}
}
Or just a bit more optimized:
public void printTriangle(int size) {
int half = size / 2;
char[] a = new char[size];
Arrays.fill(a, '*');
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
System.out.println(new String(a, 0, stars));
}
}
for(int i = 0; i < 7; i++) {
for(int j = 0; j < i; j++) {
print("*");
}
print("\n");
}
This can be another solution to print a regular right triangle...
Here's a different way of looking at the problem. By using an integer array, I can solve lots of shape drawing problems by changing the values in the array.
When solving more difficult problems, you would use model classes instead of simple integers. The idea, however, is the same.
Here's the output.
*
***
*****
***
*
And here's the code:
public class Triangle {
public static void main(String[] args) {
int[] heights = {1, 3, 5, 3, 1};
for (int i = 0; i < heights.length; i++) {
for (int j = 0; j < heights[i]; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
How about...
int width = 5;
for (int i = 1; i <= width; i+=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
for (int i = width-2; i > 0; i-=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
Or, even better yet...
int width = 7;
double half = width / 2
for (int i = 0; i < width; i++){
System.out.println(String.format("%"+((i < half ? i : (width-i-1))*2+1)+"s", "").replaceAll(" ", "*"));
}
Gives
*
***
*****
***
*

Categories