Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_3.6_itoa-3.c
1240 views
1
/* a function of itoa, which accepts the third argument as the width of the number.
2
the string representation is padded with blanks in the left to get the required width */
3
4
#include<stdio.h>
5
#include<string.h>
6
7
#define MAXLIMIT 100
8
9
void itoa(int n,char s[],int w);
10
void reverse(char s[]);
11
12
int main(void)
13
{
14
int number,width;
15
char str[MAXLIMIT];
16
17
number= -343565;
18
width=10;
19
20
itoa(number,str,width);
21
22
printf("%s",str);
23
24
return 0;
25
}
26
27
void itoa(int n,char s[],int w)
28
{
29
int i,sign;
30
31
if((sign=n) < 0)
32
n = -n;
33
i=0;
34
35
do
36
{
37
s[i++] = (n %10) + '0';
38
39
}while((n/=10)>0);
40
41
if(sign <0)
42
s[i++]='-';
43
44
while(i<w)
45
s[i++]=' ';
46
47
s[i]='\0';
48
49
reverse(s);
50
}
51
52
void reverse(char s[])
53
{
54
int i,j,c;
55
56
for(i=0,j=strlen(s)-1;i<j;i++,j--)
57
c=s[i],s[i]=s[j],s[j]=c;
58
}
59
60
61