Reputation:
I was wondering how can I do it ,to print certain number of spaces using printf in C I was thinking something like this,but also my code doesn't print after the first printf statement,my program compiles perfectly fine tho.I'm guessing I have to print N-1 spaces but I'm not quite sure how to do so.
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
| | | | | | |
Upvotes: 23
Views: 109899
Reputation: 21965
Had your objective been :
Start printing at a specified width using printf
You could achieve it like below :
printf("%*c\b",width,' ');
Add the above stuff before printing actual stuff, eg. before a for-loop.
Here the \b
positions the cursor one point before the current position thereby making the output appear to start at a particular width, width
in this case.
Upvotes: 1
Reputation: 1183
n
spacesprintf
has a cool width specifier format that lets you pass an int
to specify the width. If the number of spaces, n
, is greater than zero:
printf("%*c", n, ' ');
should do the trick. It also occurs to me you could do this for n
greater than or equal to zero with:
printf("%*s", n, "");
It's still not fully clear to me what you want, but to generate the exact pattern you described at the bottom of your post, you could do this:
for (i=1; i<=31; i+=5)
printf("%3d ", i);
printf("\n");
for (i=1; i<=31; i+=5)
printf(" | ");
printf("\n");
This outputs:
1 6 11 16 21 26 31
| | | | | | |
Upvotes: 65