Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Triangular Output

 
Moni Marva
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying the program that can generate following output

0
1 4
9 16 25
36 49 64 81


I tried to do it in following ways, but not getting the exact output.
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
U can modify this...

public class Triangle {

public static void main(String[] args) {
int num=14; //u can make it as a user input
int val=0;
System.out.println(val);

int showval=2,count=1;

for(int i=1;i<= num; i++,count++){

val=(int)Math.pow(i,2);

if(count==showval){
showval++;
count=0;
System.out.println(val);
continue;
}

System.out.print(val + (val < 10 ? " ":val < 100 ?" ":" "));
}

}
}


[ August 10, 2005: Message edited by: A Kumar ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd look for something that expresses what we're doing as clearly as I could:

Your code dealt with leading spaces, but I don't see them in your sample output. If you want to right justify this thing:

you might pick a line length & pad each line to that length before you print it.

You could figure the line length ... this kind of thing would be close enough to play with and fix up ...

Any of that sound like fun?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic