Print number of spaces using printf in C

I was wondering how I can do this to print a certain number of spaces using printf in C. I thought of something like that, but my code does not print after the first printf statement, my program compiles tho.I'm fine, assuming that I should print N-1 spaces, but I'm not quite sure how to do this therefore.

Thanks.

#include <stdio.h> #include <limits.h> #include <math.h> int f(int); int main(void){ int i, t, funval,tempL,tempH; int a; // Make sure to change low and high when testing your program int low=-3, high=11; for (t=low; t<=high;t++){ printf("f(%2d)=%3d\n",t,f(t)); } printf("\n"); if(low <0){ tempL = low; tempL *=-1; char nums[low+high+1]; for(a=low; a <sizeof(nums)/sizeof(int);a+5){ printf("%d",a); } } else{ char nums[low+high]; for(a=low; a <sizeof(nums)/sizeof(int);a+5){ printf("%d",a); } } // Your code here... return 0; } int f(int t){ // example 1 return (t*t-4*t+5); // example 2 // return (-t*t+4*t-1); // example 3 // return (sin(t)*10); // example 4 // if (t>0) // return t*2; // else // return t*8; } 

the output should be something like this:

  1 6 11 16 21 26 31 | | | | | | | 
+7
c printf
source share
2 answers

Print n spaces

printf has a width specification format that allows you to pass an int to specify the width. If the number of spaces, n , is greater than zero:

 printf("%*c", n, ' '); 

gotta do the trick. This also holds true for me, you can do this for n greater than or equal to zero with:

 printf("%*s", n, ""); 

Print 1, 6, 11, ... pattern

I still don’t quite understand what you want, but to create the exact template that you described at the bottom of your post, you can do this:

 for (i=1; i<=31; i+=5) printf("%3d ", i); printf("\n"); for (i=1; i<=31; i+=5) printf(" | "); printf("\n"); 

It is output:

  1 6 11 16 21 26 31 | | | | | | | 
+19
source share

If your goal were:

Start printing with the specified width using printf

You can achieve this as shown below:

 printf("%*c\b",width,' '); 

Add the material above before printing the actual materials, for example. before the cycle.

Here \b positions the cursor one point in front of the current position, thereby creating the conclusion that the output will start with a certain width, width in this case.

0
source share

All Articles