tags:

views:

208

answers:

4

Assume that the int variables i and j have been declared, and that n has been declared and initialized.

Using for loops (you may need more than one), write code that will cause a triangle of asterisks of size n to be output to the screen.

For example, if the value of n is 4, the output should be

 *
 **
 ***
 ****
+8  A: 

I won't do your homework, so here is a hint:

  • The first line is always 1 element long.
  • The last line is always N elements long.
  • The are a total of N lines.

Surely, with the above, you can create the necessary program.

Michael Aaron Safyan
nice answer....I couldn't think of more appropriate one...+1!
Night Shade
Well so obviously we have the answer below, but Im still not understanding how this code works exactly. So we start with i=0, then we go to the next loop where j=0 and j<=i, so we print one *. Now we do the loop again, so we increment i to 1, we increment j as well to 1, 1<=i(1) so we print another *. I dont understand how triangles begin to form?
fprime
A: 

Incase you're in school/college and more interested in getting some, more power to you buddy:

for(int i = 0; i < n; i++)
{
    for(int j = 0; j <= i; j++)
        System.out.print("*");
    System.out.println();
}
Sam Day
Why would you give him the answers damn it! Your only hurting him!
thyrgle
It was stupid to post the full answer, but the down-vote is also for the smart aleck "getting some" remark.
Matthew Flaschen
If he/she's serious about programming, perhaps this snippet shall enlighten him. Besides, if he/she can't figure out something this basic he'll likely move on to better things (bricklaying, for example).
Sam Day
Well I had this already: for(i=0;i<=n;i++){for(j=0;j<=n;j++)System.out.print("*");but that wasnt doing the trick}
fprime
@Mathew: I don't mind the downrate, I do hope for your sake you get a sense of humor someday however :)
Sam Day
@mohabitar, if you have partial code, you should always post it in the question.
Matthew Flaschen
@mohabitar: You are still here!?!? Try it by yourself first!
Night Shade
A: 
    for(int i = 0; i < n; i++){
        for(int j = 0; j <= i; j++)
            System.out.print("*");
        System.out.println();
    }
Proger
+1  A: 

Just for fun - single for-loop solution:

public void doIt(int n) {
  String temp = String.copyValueOf(char[n]);
  for (int i = 1; i <= n; i++)
    System.out.println(temp.substring(n-i).replace((char) 0, 'x'));
}

And some recursion - zero for-loop solution:

public void doItAgain(int n, String display) {
  if (n==0) return;
  System.out.println(display);
  doItAgain(n-1, display+'x');
}

(call it with doItAgain(4,"x") for your example)

Andreas_D