+ 1

How to make this pattern only used 3for?

n = 3 1 2 3 4 5 6 7 8 9 8 7 6 5

28th Oct 2018, 5:17 AM
Rifqim
2 Answers
+ 1
int line=3,count=0,limit=1,inc=1,sp=3,splimit=-2; for(int i=0;i<2*line;++i) { for(sp=0;sp<abs(splimit);++sp) cout<<" "; ++splimit; for(int j=1;j<2*limit;++j) { count=count+inc; cout<<count; } cout<<endl; if(i<line-1) {++limit;inc=1;} else {--limit;inc=-1;} } This is a not so good c++ implementation but it does work and has three for loops. Hope someone sees it and helps out me with it in java. EDIT: removed few unnecessary variables int line=3,count=1; for(int i=0;i<2*line-1;++i) { for(int sp=0;sp<abs(line-1-(abs(line-1-abs(line-1-i))));++sp) cout<<" "; for(int j=0;j<2*(abs(line-1-abs(line-1-i)))+1;++j) { cout<<count; (i<line)?count++:count--; } cout<<endl; if(i==line-1) count-=2; }
28th Oct 2018, 5:47 AM
Megatron
Megatron - avatar
+ 1
thanks :)
28th Oct 2018, 11:49 AM
Rifqim