K & R C Programs Exercise 4-4.

K and R C, Solution to Exercise 4-4:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C program to implement the following:
Show the top item of the stack without permanently popping it.
Swap the top two items on the stack.
Duplicate the top item on the stack.
Clear the stack, with the previous cases i. e K and R C Programs Exercise 4-3. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include "stdlib.h"
#include"stdio.h"
#include "ctype.h"
#include "math.h"

#define MAXOP 100
#define NUMBER 0
#define TRUE 1
#define FALSE 0

int Getop(char s[]);
void push(double val);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();

int main(void)
{
int type;
double op2;
char s[MAXOP];
int flag = TRUE;

while((type = Getop(s)) != EOF)
{
switch(type)
{
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop()- op2);
break;
case '/':
op2 = pop();
if(op2)
push(pop() / op2);
else
printf("nError: division by zero!");
break;
case '%':
op2 = pop();
if(op2)
push(fmod(pop(), op2));
else
printf("nError: division by zero!");
break;
case '?':
showTop();
break;
case '#':
duplicate();
break;
case '~':
swapItems();
break;
case '!':
clearStack();
case 'n':
printf("nt%.8gn", pop());
break;
default:
printf("nError: unknown command %s.n", s);
break;
}
}
return EXIT_SUCCESS;
}

#define MAXVAL 100

int sp = 0; /* Next free stack position. */
double val[MAXVAL]; /* value stack. */

/* push: push f onto stack. */
void push(double f)
{
if(sp < MAXVAL)
val[sp++] = f;
else
printf("nError: stack full can't push %gn", f);
}

/*pop: pop and return top value from stack.*/
double pop(void)
{
if(sp > 0)
return val[--sp];
else
{
printf("nError: stack emptyn");
return 0.0;
}
}

void showTop(void)
{
if(sp > 0)
printf("Top of stack contains: %8gn", val[sp-1]);
else
printf("The stack is empty!n");
}


void duplicate(void)
{
double temp = pop();

push(temp);
push(temp);
}

void swapItems(void)
{
double item1 = pop();
double item2 = pop();

push(item1);
push(item2);
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
sp = 0;
}

int getch(void);
void unGetch(int);

/* Getop: get next operator or numeric operand. */
int Getop(char s[])
{
int i = 0;
int c;
int next;

/* Skip whitespace */
while((s[0] = c = getch()) == ' ' || c == 't')
;
s[1] = '';

/* Not a number but may contain a unary minus. */
if(!isdigit(c) && c != '.' && c != '-')
return c;

if(c == '-')
{
next = getch();
if(!isdigit(next) && next != '.')
{
return c;
}
c = next;
}
else
c = getch();

while(isdigit(s[++i] = c))
c = getch();
if(c == '.') /* Collect fraction part. */
while(isdigit(s[++i] = c = getch()))
;
s[i] = '';
if(c != EOF)
unGetch(c);
return NUMBER;
}

#define BUFSIZE 100

char buf[BUFSIZE];
int bufp = 0;

/* Getch: get a ( possibly pushed back) character. */
int getch(void)
{
return (bufp > 0) ? buf[--bufp]: getchar();
}

/* unGetch: push character back on input. */
void unGetch(int c)
{
if(bufp >= BUFSIZE)
printf("nUnGetch: too many charactersn");
else
buf[bufp++] = c;
}
Read more Similar C Programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 4-3.

K and R C, Solution to Exercise 4-3:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
Write a c program to implement Basic framework, it’s straight forward to extend the calculate. Add the modulus(%) operator and provisions for negative numbers. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<math.h> /*for atof()*/
#define MAXTOP 100 /* max size of operand or operator */
#define NUMBER '0' /* SIGNAL THAT A NUMBER WAS FOUND */
int gettop(char []);
void push(double);
double pop(void);

//reverse Polish calulator
int main(void)
{
int type;
double op2;
char s[MAXOP];

while((type = getop(s)) != EOF)
{
switch(type)
{
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;

case '-':
op2=pop();
push(pop() - op2);
break;
case '-':
op2=pop();
if(op2 != 0.0)
push(pop() / op2);
else printf("nError: Zero divissorn")
break;
case '%':
op2 = pop();
if(op2)
push(fmod(pop(), op2));
else
printf("nError: Division by zero!");
break;
case 'n':
printf("t%.8gn",pop());
break;
default:
printf("error: unknown command %sn", s);
brak;

}
}
return 0;
}




/* Getop: get next operator or numeric operand. */
int getop(char s[])
{
#define PERIOD '.'
int i = 0;
int c;
int next;

/* Skip whitespace */
while((s[0] = c = getch()) == ' ' || c == 't')
;
s[1] = '';

/* Not a number but may contain a unary minus. */
if(!isdigit(c) && c != PERIOD && c != '-')
return c;

if(c == '-')
{
next = getch();
if(!isdigit(next) && next != PERIOD)
{
return c;
}
c = next;
}
else
{
c = getch();
}

while(isdigit(s[++i] = c))
c = getch();
if(c == PERIOD) /* Collect fraction part. */
while(isdigit(s[++i] = c = getch()))
;
s[i] = '';
if(c != EOF)
unGetch(c);
return NUMBER;

#define MAXVAL 100

int sp = 0; /* Next free stack position. */
double val[MAXVAL]; /* value stack. */

/* push: push f onto stack. */
void push(double f)
{
if(sp < MAXVAL)
val[sp++] = f;
else
printf("nError: stack full can't push %gn", f);
}

/*pop: pop and return top value from stack.*/
double pop(void)
{
if(sp > 0)
return val[--sp];
else
{
printf("nError: stack emptyn");
return 0.0;
}
}
}
Read more Similar C Programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 4-2.

K and R C, Solution to Exercise 4-2:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
Write a C Program to extend the atof function to handle scientific notations of the form 5234.73e-12
atof function converts the intial nptr string to the double. atof means ASCII to float. In this program that atof function handles the scientific notations also like 12.e-3.. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <ctype.h>
#include <limits.h>
#include <float.h>
#include <signal.h>
#include <stdio.h>

int my_atof(char *string, double *pnumber) {
/* Convert char string to double data type. */
double retval;
double one_tenth = 0.1;
double ten = 10.0;
double zero = 0.0;
int found_digits = 0;
int is_negative = 0;
char *num;

/* Check pointers. */
if (pnumber == 0) {
return 0;
}
if (string == 0) {
*pnumber = zero;
return 0;
}
retval = zero;

num = string;

/* Advance past white space. */
while (isspace(*num))
num++;

/* Check for sign. */
if (*num == '+')
num++;
else if (*num == '-') {
is_negative = 1;
num++;
}
/* Calculate the integer part. */
while (isdigit(*num)) {
found_digits = 1;
retval *= ten;
retval += *num - '0';
num++;
}

/* Calculate the fractional part. */
if (*num == '.') {
double scale = one_tenth;
num++;
while (isdigit(*num)) {
found_digits = 1;
retval += scale * (*num - '0');
num++;
scale *= one_tenth;
}
}
/* If this is not a number, return error condition. */
if (!found_digits) {
*pnumber = zero;
return 0;
}
/* If all digits of integer & fractional part are 0, return 0.0 */
if (retval == zero) {
*pnumber = zero;
return 1; /* Not an error condition, and no need to
* continue. */
}
/* Process the exponent (if any) */
if ((*num == 'e') || (*num == 'E')) {
int neg_exponent = 0;
int get_out = 0;
long index;
long exponent = 0;
double getting_too_big = DBL_MAX * one_tenth;
double getting_too_small = DBL_MIN * ten;

num++;
if (*num == '+')
num++;
else if (*num == '-') {
num++;
neg_exponent = 1;
}
/* What if the exponent is empty? Return the current result. */
if (!isdigit(*num)) {
if (is_negative)
retval = -retval;

*pnumber = retval;

return (1);
}
/* Convert char exponent to number <= 2 billion. */
while (isdigit(*num) && (exponent < LONG_MAX / 10)) {
exponent *= 10;
exponent += *num - '0';
num++;
}

/* Compensate for the exponent. */
if (neg_exponent) {
for (index = 1; index <= exponent && !get_out; index++)
if (retval < getting_too_small) {
get_out = 1;
retval = DBL_MIN;
} else
retval *= one_tenth;
} else
for (index = 1; index <= exponent && !get_out; index++) {
if (retval > getting_too_big) {
get_out = 1;
retval = DBL_MAX;
} else
retval *= ten;
}
}
if (is_negative)
retval = -retval;

*pnumber = retval;

return (1);
}

double atof(char *s) {
double d = 0.0;
if (!my_atof(s, &d)) {
#ifdef DEBUG
fputs("Error converting string in [sic] atof()", stderr);
#endif
raise(SIGFPE);
}
return d;
}

#ifdef UNIT_TEST
char *strings[] = {
"1.0e43",
"999.999",
"123.456e-9",
"-1.2e-3",
"1.2e-3",
"-1.2E3",
"-1.2e03",
"cat",
"",
0
};
int main(void)
{
int i = 0;
for (; *strings[i]; i++)
printf("atof(%s) = %gn", strings[i], atof(strings[i]));
return 0;
}
#endif

Read more Similar C Programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

C Program implement Kruskal’s algorithm.

Write a C Program implement Kruskal’s algorithm.
Kruskal’s algorithm is a greedy algorithm that finds the minimum spanning tree of a graph. Graph should be weighted, connected, and undirected.Minimum spanning tree is a spanning tree with weight less than or equal to the weight of every other spanning tree. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
clrscr();
printf("nntImplementation of Kruskal's algorithmnn");
printf("nEnter the no. of verticesn");
scanf("%d",&n);
printf("nEnter the cost adjacency matrixn");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("nThe edges of Minimum Cost Spanning Tree arenn");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("n%d edge (%d,%d) =%dn",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("ntMinimum cost = %dn",mincost);
getch();
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}
Read more Similar C Programs
Data Structures
Dijkstras Algorithm

Learn C Programming

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 4-1.

K and R C, Solution to Exercise 4-1:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
Write a C program which returns the position of the occurrence of sub string t in string s, or -1 if there is none.

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<conio.h>
void main()
{
int flag=0;
char str[80],search[10];
puts("Enter a string:");
gets(str);

puts("Enter search substring:");
gets(search);
flag=strindex(str, search);
if (flag == -1)
{
printf("SEARCH UNSUCCESSFUL! AND POSITION IS:%d",flag);
}
else{
printf("SEARCH SUCCESSFUL! AND POSITION IS:%d",flag);
}
getch();
}

//strindex: returns the right most index of t in s, -1 if none*/
int strindex(char s[], char t[])
{
int k,i,j,pos;
pos = -1;
for(i=0;s[i] != ''; i++)
{
for(j=i, k = 0; t[k] != '' && s[j] == t[k]; j++, k++)
;
if (k > 0 && t[k] == '')
pos=i;
}
return pos;
}
Read more Similar C Programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

C program to implement bit flipping.

Write a C program to implement bit flipping.
C Program to setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged in the least number of lines.
Bit flipping or flip bit is the complement(~) of bits. i.e., 0 to 1 and vise versa. bit flipping is the bits manipulation or processing individual bits within a byte. Bit flipping is used in the very low-level programming and is often used in graphics and systems programming.Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdio.h>
#include <math.h>
#include <limits.h>

unsigned setbits(unsigned x, unsigned p, unsigned n, unsigned y) {
x |= (y & ~(~0 << n)) << p;
size_t s = (int)(log(INT_MAX)/log(2)) + 1;
printf("nnnSuccess! Number after bit flipping: n", s);
int mask = pow(2.0, (int)s);
do {
((x & mask) == 0) ? printf("0") : printf("1");
((s%4)==0) ? printf(" ") : printf("");
x <<= 1;
} while (s--);
printf("n");
}


void main( ) {
unsigned retrn=1, begin=0, nbits=0, num=0;

printf("Enter the number to bit flip!n");
scanf("%d",&num);
printf("Enter the number of bits to be flip!n");
scanf("%d",&nbits);
printf("Enter the position to begin bit flip!n");
scanf("%d",&begin);
unsigned x = setbits(retrn, begin, nbits, num);

}
Read more Similar C Programs
C Basic
C Search Algorithms
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

C Program to print factors of the number.

Write a C Program to print factors of a number. Factors of a whole number are the whole numbers which are exactly divides the number. i.e reminder is equal to zero.
Example: Factors of 8 are: 1, 2, 4, and 8.
Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<conio.h>
{
void main( )
{
int num,x;
clrscr( );
printf("Enter the required number:");
scanf("%d",&num);
printf("nThe factors are:");
for(x=1; x<=num; x++)
{
if(num%x==0)
printf("n%d",x);
}
getch( );
}
Read more Similar C Programs
C Basic
C Search Algorithms
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

C Program to implement topological sort.

Write a c program to implement topological sort.
Topological sort is the ordering vertices of a directed, acyclic graph(DAG), so that if there is an arc from vertex i to vertex j, then i appears before j in the linear ordering. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#define MAX 200
int n,adj[MAX][MAX];
int front = -1,rear = -1,queue[MAX];
void main()
{
int i,j = 0,k;
int topsort[MAX],indeg[MAX];
create_graph();
printf(“The adjacency matrix is:n”);
display();
for(i=1;i<+n;i++)
{
indeg[i]=indegree(i);
if(indeg[i]==0)
insert_queue(i);
}
while(front<=rear)
{
k=delete_queue();
topsort[j++]=k;
for(i=1;i<=n;i++)
{
if(adj[k][i]==1)
{
adj[k][i]=0;
indeg[i]=indeg[i]-1;
if(indeg[i]==0)
insert_queue(i);
}
}
}
printf("Nodes after topological sorting are:n");
for(i=0;i<=n;i++)
printf("%d",topsort[i]);
printf("n");
}
create_graph()
{
int i,max_edges,origin,destin;
printf("n Enter number of vertices:");
scamf("%d",&n);
max_edges = n * (n - 1);
for(i = 1;i <= max_edges;i++)
{
printf("n Enter edge %d (00 to quit):",i);
scanf("%d%d",&origin,&destin);
if((origin == 0) && (destin == 0))
{
printf("Invalid edge!!n");
i–;
}
else
adj[origin][destin] = 1;
}return;
}
display()
{
int i,j;
for(i = 0;i <= n;i++)
{
for(j = 1;jrear)
{
printf(“Queue Underflow”);
return;
}
else
{
del_item = queue[front];
front = front + 1;
return del_item;
}
}
int indegree(int node)
{
int i,in_deg = 0;
for(i = 1;i <= n;i++)
if(adj[i][node] == 1)
in_deg++;
returnin_deg;
}




Read more Similar C Programs
Data Structures
C Sorting
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 3-6.

K and R C, Solution to Exercise 3-6:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C program to change version of itoa that accepts three arguments instead of two(K and R C Exercise 3-4). The third argument is a minimum field width; the converted number must be paddle with blanks on the left if necessary to make it wide enough. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#define abs(x) ((x) < 0 ? -(x) : (x))
void itoa(int n, char s[], int w);
void reverse(char s[]);

int main(void) {
char buffer[20];

printf("INT_MIN: %dn", INT_MIN);
itoa(INT_MIN, buffer);
printf("Buffer : %sn", buffer);

return 0;
}
//itoa: convert to n characters in s, w characters wide.
void itoa(int n, char s[], int w)
{
void int i, sign;
void everse(char s[]);
sign = n;
i = 0;
do{
s[i++] = abs(n%10) + '0';
printf("%d %% %d + '0' = %dn", n, 10, s[i-1]);
}while((n/=10)!=0);
if(sign < 0)
s[i++] = '-';
while(i < w)
s[i++] = ' ';
s[i] = '';
reverse(s);
}
void reverse(char s[]) {
int c, i, j;
for ( i = 0, j = strlen(s)-1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
Read more Similar C Programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 3-5.

K and R C, Solution to Exercise 3-5:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
Write a c program to convert the integer n into a base b character representation in the string s. In particular, itob(n, s, 16) formats n as a hexadecimal integer in s. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/


#include <stdlib.h>
#include <stdio.h>

void itob(int n, char s[], int b);
void reverse(char s[]);

int main(void) {
char buffer[10];
int i;

for ( i = 2; i <= 20; ++i ) {
itob(255, buffer, i);
printf("Decimal 255 in base %-2d : %sn", i, buffer);
}
return 0;
}


/* itob: convert n to charecters in s - base b */

void itob(int n, char s[], int b) {

int i, j, sign;
void reverse(char s[]);


if ((sign = n) < 0)
n = -n;
i = 0;
do {
j = n%b;
s[i++] = (j <= 9) ? j+'0' : j+'a'-10;
} while ((n /= b) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '';
reverse(s);
}


/* Reverses string s[] in place */

void reverse(char s[]) {
int c, i, j;
for ( i = 0, j = strlen(s)-1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}


Read more Similar C Programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com