While loop problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cmb3587
    New Member
    • Mar 2009
    • 5

    While loop problem

    My task is to take a user input that ranges from 1-50 and use it to create a triangle of asterisks. I.E:

    Enter number: 5

    *
    **
    ***
    ****
    *****
    ****
    ***
    **
    *

    I know that i need 2 seperate embedded while loops and that the first one creates a row of asterisks equal to the row number until you reach the input and the second subtracts 1 asterisk until you reach 0.

    I can not figure out what is wrong with my code to do this...can someone help please.

    Code:
    import java.util.Scanner;
    
    public class triangle {
    
    	public static void main(String[] args) {
    		Scanner kbd = new Scanner(System.in);
    		String asterisk;
    		System.out.print("Enter a triangle size (between 1 and 50): ");
    		int number = kbd.nextInt();
    		asterisk = "*";
    		int length = asterisk.length();
    		int lines = 0;
    		while (lines <= number){
    			System.out.println(asterisk);
    			lines++;
    			while (length <= number) {
    				System.out.print(asterisk);
    				length++;
    			}
    		}
    		while (lines > 0 ) {
    			System.out.println(asterisk);
    			lines--;
    			while (length <= number) {
    				System.out.print(asterisk);
    				length++;
    			}
    		}
    
    		
    	}
    }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    This has been discussed before; have a look at this thread.

    kind regards,

    Jos

    Comment

    • bharat bhaskar
      New Member
      • Apr 2012
      • 1

      #3
      Use this code
      i am writing this in c language.
      #include <stdio.h>
      #include<conio. h>

      void main()
      {
      int i,j,k,l,n;

      scanf("%d",&n);
      k=n;
      l= 1
      for(i=0;i<=n;i+ +)
      {

      for(j=0;j<=k;j+ +)
      {
      printf(" ");
      if(j>=k-l)
      {
      printf("*");
      }
      }
      l= 2*l + 1;
      k = n+1;
      printf("/n");


      }
      }

      Comment

      Working...