Search code examples
c++for-loopnested-loops

Not Displaying Spaces


I'm very new to c++ and everything in general. I dont understand why my code doesn't work:

#include <cstdio>

int main(){
 
int a;

scanf("%d", &a);

for(int i = 1; i < a; i++){
 printf(" ");

}

printf("*");

}

what I'm trying to do is make the number of spaces as the value inputted by the user minus and add a * at the end so if a = 10 :

     *

but when I try it the spaces don't show. Ideally what I'm trying to do is get an output something like:

   *
  **
 ***
****

The length depends on user input if it was 10 then the spaces would be 9 and the * at the end would be the tenth.


Solution

  • You will have to use 3 for-loops (two of them nested inside one). The parent for loop for each row. And the nested two are for spaces and stars.

    #include <cstdio>
    int main()
    {
    
        int a;
    
        scanf("%d", &a);
    
        for(int i=1; i<a; i++)
        {
            for(int j=i; j<a; j++)
                printf(" ");
            for(int k=0; k<i; k++)
                printf("*");
    
            printf("\n");
        }
        return 0;
    }
    

    You will get your desired output if you put the value 5 for a, i.e., a=5.

    To learn more in detail, you can follow this link star patterns in c

    Your code may contain many errors. That's understandable, cause you are new to C/C++. Try problem-solving in beecrowd to improve your problem-solving capabilities and learn C/C++ in a better way. These errors will automatically go away day by day as you progress. But the secret is to practice and never give up. Good luck!