I'm trying to print a pyramid of stars using nested while loops. I know I am able to achieve this using for loops but I want to do it with while loop instead. This is my code so far:
public class WhileNest
{
public static void main(String[]args)
{
int rows = 5, i = 1, j = 1;
while(i <= rows)
{
while(j <= i)
{
System.out.print("*");
j++;
}
System.out.print("\n");
i++;
}
}
}
The output has to be like this:
*
**
***
****
*****
But my output is this:
*
*
*
*
*
Any help is appreciated, thanks.
you have to reset j like this:
public class test {
public static void main(String[] args) {
int rows = 5, i = 1, j = 1;
while (i <= rows) {
while (j <= i) {
System.out.print("*");
j++;
}
System.out.print("\n");
i++;
j = 1;
}
}
}
You have forgotten to assign 1 to j at the end of the outer while loop.
public class WhileNest {
public static void main(String[] args) {
int rows = 5, i = 1, j = 1;
while (i <= rows) {
while (j <= i) {
System.out.print("*");
j++;
}
System.out.print("\n");
i++;
j = 1;
}
}
}
int rows = 5, i = 1, j = 1;
while(i <= rows)
{
while(j <= i)
{
System.out.print("*");
j++;
}
j=1;
System.out.println();
i++;
}
You are not reassigning j to start from beginning. Your i and j were always staying same. Re-initialize j to 1 after the inner while loop as shown. It will work
Pyramid using two for loops:
String STAR = "*";
String SPACE = " ";
int SIZE = 10;
for(int i=0;i<SIZE;i++) {
int start = SIZE-i;
int end = (SIZE*2) - SIZE + i;
for(int j = 0; j<SIZE*2; j++) {
if(j>=start && j<=end && j%2 == i%2) {
System.out.print(STAR);
} else {
System.out.print(SPACE);
}
}
System.out.println();
}
output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
public static void main(String[] args) {
for(int i=0;i<10;i++){
for(int k=0;k<i;k++){
System.out.print("*");
}
System.out.println();
}
}
*Instead of initializing "j" at the beginning, include it in the first while loop that'll do the work.( * will be printed at the beginning of each row)
public class WhileNest
{
public static void main(String[]args)
{
int rows = 5, i = 1;
while(i <= rows)
{
int j = 1;
while(j <= i)
{
System.out.print("*");
j++;
}
System.out.print("\n");
i++;
}
}
}
Related
I want to make a java pattern like this using while loops
* * * *
* * *
* *
*
and here is my code
int i = 4;
int j = 0;
while (i >= 0) {
while (j < i) {
System.out.print(" * ");
j++;
}
System.out.print("\n");
i--;
}
but its giving output like this:
* * * *
Does anyone knows what to do....?
TRY CONSIDERING THIS ONE MIGHT HELP YOU !!
Using FOR Loop
public class DownwardTrianglePattern {
public static void main(String[] args) {
int rows = 4;
//outer loop
for (int i = rows-1; i >= 0 ; i--) {
//inner loop
for (int j = 0; j <= i; j++) {
//prints star and space
System.out.print("*" + " ");
}
//throws the cursor in the next line after printing each line
System.out.println();
}
}
}
Using While Loop
public class Itriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter N : ");
int n = sc.nextInt();
System.out.print("Enter Symbol : ");
char c = sc.next().charAt(0);
int i = n, j;
while(i > 0) {
j = 0;
while(j++ < i) {
System.out.print(c);
}
System.out.println();
i--;
}
}
}
After i--;
you can j=0;
The problem in your code is that in first iteration after completing both the while loops the value of variables is i=3 and j=4. So for the next iteration the first while loop will run as the condition is true i.e. 3>=0 but for the next while loop the condition will be false as j i.e. 3 not less than i i.e. 3. So that's why the next loop does not executes and you are getting that output.
The j needs to be initialized inside loop.
I changed the code as below. it's giving correct output
int i = 4;
while (i >= 0) {
int j = 0;
while (j < i) {
System.out.print(" * ");
j++;
}
System.out.print("\n");
i--;
}
please reset j after j loop
int i = 4;
int j = 0;
while (i >= 0) {
while (j < i) {
System.out.print(" * ");
j++;
}
j = 0;
System.out.print("\n");
i--;
}
when you're finished with inner loop you have to reset j value else it's value will remain 4 which is not less then i value. you can reset the value before starting inner while
int i = 4;
int j = 0;
while (i >= 0) {
j = 0;
while (j < i) {
System.out.print(" * ");
j++;
}
System.out.println(""); // println will work same as System.out.print("\n") in this scenario
i--;
}
By the way your problem can be nicely solved using recursion
public static void main(String[] args) {
printLine(4);
}
private static void printLine(int numberOfStars) {
if(numberOfStars == 0) {
return;
}
System.out.println("* ".repeat(numberOfStars));
printLine(numberOfStars - 1);
}
Output
* * * *
* * *
* *
*
I'm trying to write a square shape of asterisk around border using the https://stackoverflow.com/a/34209565 answer.
But I cannot get it working at all.
Here is the code I'm trying.
int _i = 10;
int _j = 10;
String[][] array = new String[_i][_j];
for (int i = 0; i < _i; i++) {
System.out.println();
for (int j = 0; j < _j; j++) {
if(i==0 || j == 0 || i == _i - 1|| j == _j - 1){
array[i][j] = "*";
System.out.print(array[i][j]);
}
}
}
The output I'm getting is:
**********
**
**
**
**
**
**
**
**
**********
I tried running tthe code from the answer but it produces a one line of asterisk. Something from the code in the answer has been omitted.
The code provdied in the answer is:
int _i = 10;
int _j = 10;
String[][] array = new String[_i][_j];
for (int i = 0; i < _i; i++) {
for (int j = 0; j < _j; j++) {
if(i==0 || j == 0 || i == _i-1|| j == _j-1){
array[i][j] = "*";
}
}
}
And the output in the answer is:
**********
* *
* *
* *
* *
* *
* *
* *
* *
**********
You need an else to print a space when the entry is not a star. Also, I would move the println() to the end of the loop (instead of the beginning). Assuming you actually want to fill the array too, populate it with a space as well. Like,
for (int j = 0; j < _j; j++) {
if (i == 0 || j == 0 || i == _i - 1 || j == _j - 1) {
array[i][j] = "*";
} else {
array[i][j] = " ";
}
System.out.print(array[i][j]);
}
System.out.println();
Outputs
**********
* *
* *
* *
* *
* *
* *
* *
* *
**********
You can use the repeat method, so the code is less verbose, also enclosing the generation in a method you can make it dynamic bu setting two arguments: number of lines and number of columns:
class Test
{
public static void main(String[] args)
{
System.out.println(createBox(10, 10));
System.out.println(createBox(10, 5));
}
public static String createBox(int qtaRig, int qtaCol)
{
String result = "";
for(int r = 1; r <= qtaRig; r++)
{
if(r == 1 || r == qtaRig)
{
result += "*".repeat(qtaCol);
}
else
{
result += "*" + " ".repeat(qtaCol-2) + "*";
}
result += "\n";
}
return result;
}
}
Result:
**********
* *
* *
* *
* *
* *
* *
* *
* *
**********
*****
* *
* *
* *
* *
* *
* *
* *
* *
*****
So I have to print the following pattern by accepting a value of n
Input : 7
Output has to be this :
*
**
***
****
*****
******
*******
******
*****
****
***
**
*
code:
public static void printPattern(int n)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
System.out.println("*");
}
System.out.println("\n");
}
for (int a = n-1; a >= 1; a--)
{
for (int b = 1; b <= a; b++)
{
System.out.print("*");
}
System.out.println("\n");
}
}
But for some reason it prints this pattern(say n=8):
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*******
******
*****
****
***
**
*
What is the mistake here?
Use System.out.print instead of System.out.println in the first for loop, the latter one always appends a newline character at the end which is what you are trying to do manually.
And either do System.out.print("\n"); OR System.out.println(""); to add the newline after the inner loop iteration.
System.out.println already adds a line break at the end, therefore System.out.println("\n") adds two line breaks.
The code can be condensed to a single double-for loop. The following routine accepts a single parameter which defines the maximum number of '*' on a single line:
/**
* #param width
* the maximum width of the pattern.
*/
public static void print(int width) {
for (int i = 1; i < 2 * width; ++i) {
for (int j = 0; j < width - Math.abs(width - i); ++j)
System.out.print("*");
System.out.println();
}
}
public static void main(String[] args) {
print(4);
}
Output:
*
**
***
****
***
**
*
first for loop should be like this,
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.print("\n");
}
System.out.println();
always move the cursor to a new line
in your code when we use System.out.println("\n"); this will move cursor to 2 lines
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
for (int a = n - 1; a >= 1; a--) {
for (int b = 1; b <= a; b++) {
System.out.print("*");
}
System.out.println();
}
By changing println to print you won't go to another line after each * and remove the \n to not skip 2 lines because println it's already there
Hi there i want to create a triangle using java loops. But what i need is only the borders. I've tried using this syntax but it always shows error. any advice?
int lines = 5;
int c = 2*lines;
for (int i = lines-1; i>=0; i--)
{
for (int j = i; j < lines; j++)
{
System.out.print(" ");
}
for (int k = 1; k <= c; k++)
{
if (k % 2 == 0)
{
System.out.print(" ");
}
else
{
if (k == 0 || k == lines - 1) {
System.out.print("*");
}
}
}
System.out.print("\n");
c -= 2;
}
can you kindly help me . thanks
There's a lot of things wrong with your code...
for (int k = 1; k <= c; k++)
// and then:
if (k == 0 || k == lines - 1) {
k will never be 0
if (k % 2 == 0)
// and then
else
{
if (k == 0 || k == lines - 1) {
a even if k was 0, then 0%2 == 0, so k==0 can never occur
As of right now, your app only prints spaces.
If you want to draw a triangle, the (possibly) simplest way would be to do
public static void main(String[] args) {
int lines = 6;
int cols = lines+1;
for (int line =0; line < lines-1; line++) {
for (int col = 0; col<cols; col++) {
if (col == 0 || col == line) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
for (int col=0; col<cols; col++) {
System.out.print("*");
}
System.out.println();
}
Triangle.java
public class Triangle {
private int lines;
public Triangle(int lines) {
this.lines = lines;
display();
}
public void display() {
int spaces = lines - 1;
int last;
int min = 1;
int max;
for (int i = 0; i < lines; i++) {
last = 2 * i + 1;
max = spaces + last;
for (int j = min; j <= max; j++) {
if (j == spaces + 1 || j == max || i == lines - 1)
System.out.print('*');
else
System.out.print(' ');
}
System.out.println();
spaces--;
}
}
public static void main(String[] args) {
new Triangle(3);
new Triangle(4);
new Triangle(5);
new Triangle(6);
}
}
Output
*
* *
*****
*
* *
* *
*******
*
* *
* *
* *
*********
*
* *
* *
* *
* *
***********
Ex:
*
* *
* *
* *
*********
Code:
int numberOfRows = 5;
for(int i=0; i<numberOfRows; i++)
{
for(int a=0; a<=numberOfRows; a++)
{
int x = numberOfRows - i;
if (a > x) {
if (x==(a-1) || i==(numberOfRows-1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
} else {
System.out.print(" ");
}
}
for(int b=0; b<=i; b++)
{
if(b==i || i==(numberOfRows-1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.print("\n");
}
I have used two methods and repeated those two methods using for loop.
public class OpenWord {
int i;
String k = " ";
public void space(){
System.out.println("*"+k+"*");
}
public void star(){
System.out.println("*");
}
public void trainagle(){
star();
for ( i=1; i<=10;i++){
space();
k =k+" ";
if(i==10){
k=k.replace(" ", "*");
space();
}
}
}
public static void main(String args[]) {
OpenWord a = new OpenWord();
a.trainagle();
}
}
Output:
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
******************
I got a problem to create a rhombus, my code here:
package random;
public class asd {
public static void main(String args[]) {
for (int j = 1; j <= 4; j++) {
for (int kong = 4 - j; kong >= 1; kong--) {
System.out.print(" ");
}
for (int xing = 1; xing <= 2 * j - 1; xing++) {
System.out.print("*");
}
System.out.println();
}
for (int a = 1; a <= 3; a++) {
for (int b = 1; b <= a; b++) {
System.out.print(" ");
}
for (int c = 5; c >= 1; c -= 2) { // <==== here
System.out.print("*");
}
System.out.println();
}
}
}
However, the output is:
*
***
*****
*******
***
***
***
I think the problem is in the code which I highlighted.
java-11
By using String#repeat, introduced as part of Java-11, you can do it with a single loop.
public class Main {
public static void main(String[] args) {
int size = 9;
int midRowNum = size / 2 + 1;
for (int i = 1 - midRowNum; i < midRowNum; i++) {
System.out.println(" ".repeat(Math.abs(i)) + "*".repeat((midRowNum - Math.abs(i)) * 2 - 1));
}
}
}
Output:
*
***
*****
*******
*********
*******
*****
***
*
By increasing the amount of space by one character, you can also print a variant of the shape:
public class Main {
public static void main(String[] args) {
int size = 9;
int midRowNum = size / 2 + 1;
for (int i = 1 - midRowNum; i < midRowNum; i++) {
System.out.println(" ".repeat(Math.abs(i)) + "* ".repeat((midRowNum - Math.abs(i)) * 2 - 1));
}
}
}
Output:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
You are right in indicating the possible problematic line. Surprised that you did it right in first half:
for (int c = 5; c >= 2 * a - 1; c -= 1) { // <==== here
System.out.print("*");
Using Math.abs will make it a lot easier:
import java.util.Scanner;
public class MakeDiamond {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Let's Creat Diamonds");
System.out.println("If number increases Diamonds gets bigger. " +
"Please input number lager than 1 : ");
int user_input = sc.nextInt(); //gets user's input
System.out.println("");
int x = user_input;
int front_space = -5;
for (int i = 0; i < 2 * user_input + 1; i++) {
for (int a = front_space; a < Math.abs(i - user_input); a++) {
System.out.print(" ");
}
if (i < user_input + 1) {
for (int b = 0; b < 2 * i + 1; b++) {
System.out.print("* ");
}
} else if (i > user_input) {
for (int c = 0; c < 2 * x - 1; c++) {
System.out.print("* ");
}
x--;
}
System.out.print('\n');
}
System.out.println("\nRun Again? 1 = Run, 2 = Exit : ");
int restart = sc.nextInt();
System.out.println("");
if (restart == 2) {
System.out.println("Exit the Program.");
System.exit(0);
sc.close();
}
}
}
}
You can simplify your code by using two nested for loops and one if else statement.
int n = 4;
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) <= n)
System.out.print("*");
else
System.out.print(" ");
System.out.println();
}
Output:
*
***
*****
*******
*********
*******
*****
***
*
See also: Output an ASCII diamond shape using loops