How can I optimize this code? I want to delete the second part for loop and complete it in one part for loop | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 4

How can I optimize this code? I want to delete the second part for loop and complete it in one part for loop

https://code.sololearn.com/cU5D2wpg8GB3/?ref=app

20th Aug 2019, 5:03 PM
Geek
Geek - avatar
3 Réponses
+ 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"); } } }
20th Aug 2019, 5:54 PM
Lea
+ 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.
20th Aug 2019, 6:30 PM
daniel
daniel - avatar
+ 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"); } } }
21st Aug 2019, 9:11 AM
Batul Makada
Batul Makada - avatar