+ 4
How can I optimize this code? I want to delete the second part for loop and complete it in one part for loop
4 Answers
+ 5
i don't know if it's better because I had to make a specific if loop for the central rows
#include<stdio.h>
#define VAL(x) sqrt((x)*(x))
int main(){
int a;
scanf("%d",&a);
for(int i=1;i<2*a;i++){
for(int j=0;j<a-VAL(i-a);j++){
printf("%.0lf",a-VAL(i-a));
}
printf("\n");
if(VAL(i-a)==0){
for(int j=0;j<a;j++){
printf("%d",a);
}
printf("\n");
}
}
}
+ 4
You could use a manipulated for loop like this one:
for(int k=1,i=1;k<=2*a;k++,i=(k>a)?2*a+1-k:k)
But it would make the code a bit slower and a lot uglier.
Shorter code doesn't necessarily optimize run time and is usually less readable. It only guarantees you, well, shorter code.
in my opinion, using two loops is the best option.
+ 3
int main(){
int a,j=0;
scanf("%d",&a);
for(int i=1;i<=a;i++){
if(j<i){
for(j=0;j<i;j++){
printf("%d",i);
}
printf("\n"); if(j==a-1){j++;}}
else {
for(int k=i;k>0;k--){
printf("%d",i);
}i-=2;
printf ("\n");
}
}
}