Search code examples
cloopsseries

C program to print a series


I am writing a program in C to print following series.

   1
  121
 12321
1234321

Below is my code which works perfectly fine but is there any change which i can make to make the program use less loops.

#include <stdio.h>
int main() {
int num, i, j, terms, x;
printf("ENTER NUMBER OF TERMS: ");
scanf("%d", &terms);
x = terms--;
for(num=1;num<=terms;num++){
    for(i=1;i<=x;i++){
        printf(" ");
    }
    for(i=1; i<=num; i++) {
        printf("%d", i);
    }
    for(j=num-1 ; j>0; j--){
        printf("%d", j);
     }
    printf("\n");
    x--;
   }
}

Solution

  • You can fusion the two first loops making an if else statement and using de answer below to print x spaces with one single print
    
    for(i=1;i<=x;i++){
        printf(" ");
    }
    for(i=1; i<=num; i++) {
        printf("%d", i);
    }
    
    
    
    printf("%*c", n+1, '1');
    for(i=1; i<=num; i++) {
        printf("%d", i);
    }
    

    or specify the number of spaces like the answer below, deleting the first loop