Jan 12, 2012

K & R C Programs Exercise 4-10.

K and R C, Solution to Exercise 4-10:
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 modify the K & R C Programs Exercise 4-5, An alternate organization uses getline to read an entire input line; this makes getch and ungetch unnecessary. revise the caluculater to use this aproach. 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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<ctype.h>

#define MAXLINE 100
#define NUMBER '0' //SIGNAL THAT A NUMBER WAS FOUND
int getline(char line[], int limit);
int li = 0;
char line[MAXLINE];
/* Getop: get next operator or numeric operand. */
int Getop(char s[])
{
int i;
int c;

if(line[li] == '\0')
if(getline(line, MAXLINE) == 0)
return EOF;
else li = 0;
/* Skip whitespace */
while((s[0] = c = line[li++]) == ' ' || c == '\t')
{
;
}
s[1] = '\0';

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

if(isdigit(c))
while(isdigit(s[++i] = c =line[i++]))
;

if(c == '.')
while(isdigit(s[++i] = c =line[i++]))
;
s[i] = '\0';
li--;
return NUMBER;
}

```
```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

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

K & R C Programs Exercise 4-9.

K and R C, Solution to Exercise 4-9:
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 modify the K & R C Programs Exercise 4-8, getch and ungetch do not handlea pushed back EOF correctly. Decide what their properties ought to be if an EOF is pushed back, then implement the design
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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#define BUFSIZE 100
int buf[BUFSIZE];
int bufp = 0;

//getch: get a (possibly pushed back) character
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
//ungetch: push a character back onto the input
void ungetch(int c)
{
if(bufp >= BUFSIZE)
printf("ungetch: too many characters!");
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

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

Jan 11, 2012

C Program which produces its own source code as its output.

Write a c program which produces its own source code as its output.
This C program uses the C File i/o operations like fopen(), fclose(). In this program, We pritn the source code of the program.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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include<stdio.h>
int main()
{
FILE *fp;
char c;

fp = fopen(__FILE__,"r");

do{

c= getc(fp);

putchar(c);

}
while(c!=EOF);

fclose(fp);

return 0;

}

```
```Read more Similar C Programs
C Basic

C File i/o```
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

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 Program to print ASCII values of all characters.

C Program to print ASCII values of all characters.
ASCII value is the American Standard Code for Information Interchange.
ASCII value is the numerical value, or order, of an character. There are 128 standard ASCII characters, numbered from 0 to 127. Extended ASCII adds another 128 values and goes to 255. The numbers are typically represented in decimal or in hexadecimal. 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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<conio.h>
int main(){

int i;
clrscr();
for(i=0;i<=255;i++)
printf("ASCII value of
character %c: %d\n",i,i);
getch();
return 0;

}
```
```Read more Similar C Programs
Learn C Programming

Number System```

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

To get regular updates on new C programs, you can

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 Program to find the strong number.

Write a C Program to find the given number is strong or not?
A number is called strong number if sum of the factorial of its digit is equal to number itself.
Example: 145 since 1! + 4! + 5! = 1 + 24 + 120 = 145.
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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/
#include<stdio.h>
#include<conio.h>

int main()
{
int num,i,f,r,sum=0,num1;
clrscr();
printf("Enter a number: ");
scanf("%d",&num);

num1=num;
while(num){
i=1,f=1;
r=num%10;

while(i<=r){
f=f*i;
i++;
}
sum=sum+f;
num=num/10;

}
if(sum==num1)
printf("%d is a strong number",num1);
else
printf("%d is not a strong number",num1);
getch();
return 0;

}
```
```Read more Similar C Programs
Learn C Programming

Number System```

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

To get regular updates on new C programs, you can

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

Jan 10, 2012

C Program to find the two sets Intersection and Union

Write a C Program to find the two sets Intersection and Union
A Set is a collection of well defined and distinct objects.
Intersection of two sets A and B is defined as, all the elements of set A, which are also elements of set B.Union of two sets A and B is defined as, all the elements of A and B, but not belonged to both.
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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<conio.h>
void Union(int set1[10],int set2[10],int m,int n);
void Intersection(int set1[10],int set2[10],int m,int n);
void main()
{
int a[10],b[10],m,n,i,j;
int ch;
clrscr();
printf("\nEnter the number of elements in first set:\n");
scanf("%d",&m);
printf("\nEnter the elements:\n");
for(i=0;i<m;i++)
{
scanf("%d",&a[i]);
}
printf("\nElement of First set:\n\n");
for(i=0;i<m;i++)
{
printf("%d\t",a[i]);
}
printf("\nEnter the number of elements in second set:\n");
scanf("%d",&n);
printf("\nEnter the elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
printf("\nElement of second set\n");
for(i=0;i<n;i++)
{
printf("%d\t",b[i]);
}
for(;;)
{
printf("\n\nMenu\n\n1.Union\n2.Intersection");
printf("\n3.exit");
printf("\nEnter your choice:\n");
scanf("%d",&ch);
switch(ch) {
case 1:
Union(a,b,m,n);
break;
case 2:
Intersection(a,b,m,n);
break;
case 3:
exit(0);
}
getch();
}
}

void Union(int a[10],int b[10],int m,int n)
{
int c[20],i,j,k=0,flag=0;
for(i=0;i<m;i++)
{
c[k]=a[i];
k++;
}
for(i=0;i<n;i++)
{
flag=0;
for(j=0;j<m;j++)
{
if(b[i]==c[j])
{
flag=1;
break;
}
}
if(flag==0)
{
c[k]=b[i];
k++;
}
}
printf("\nElement of resultant set\n\n");
for(i=0;i<k;i++)
{
printf("\t%d",c[i]);
}
}
void Intersection(int a[10],int b[10],int m,int n)
{
int c[20],i,j,k=0,flag=0;
for(i=0;i<m;i++)
{
flag=0;
for(j=0;j<n;j++)
{
if(a[i]==b[j])
{
flag=1;
break;
}
}
if(flag==1)
{
c[k]=a[i];
k++;
}
}
if(k==0)
{
printf("\n\nResultant set is null set!\n");
}else{
printf("\nElement of resultant set\n");
for(i=0;i<k;i++)
{
printf("\t%d",c[i]);
}
}
}

```
```Read more Similar C Programs
Learn C Programming

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

To get regular updates on new C programs, you can

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

K & R C Programs Exercise 4-8.

K and R C, Solution to Exercise 4-8:
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 modify the K & R C Programs Exercise 4-7, Suppose there will never be more than one character of pushback. Modify getch and ungetch accordingly. 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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include
char buf = 0;

//getch: get a (possible pushed character back) character
int getch(void)
{
int c;
if(buf != 0)
c = buf;
else
c getchar();
buf = =0;
return c;
}

/*ungetch: push string back onto the input*/
void ungetch(int c)
{
if (buf != 0)
printf("ungetch: too many characters!\n");
else
buf = c;
}
int main(void)
{
int c;

while ((c = getch()) != EOF) {
if (c == '/') {
putchar(c);
if ((c = getch()) == '*') {
ungetch('!');
}
}
putchar(c);
}
return 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

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

K & R C Programs Exercise 4-7.

K and R C, Solution to Exercise 4-7:
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 C program that will push back an entire string onto the the input.
ungets calls the routine ungetch len times, each time pushing back a character from the string s onto the input. ungets pushes the string back in reverse order.
The routine ungets does not need to worried about the buf and bufp. The routine ungetch handles buf, bufp, and error handling. 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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include<stdio.h>
/*ungets: push string back onto the input*/

void ungets(char s[])
{
int len=strlen(s);
void ungetch(int);
while (len >0)
ungetch(s[--len]);
}
int main(void)
{
char *s = "oh! this is for testing!";
int c;

ungets(s);
while ((c = getch()) != EOF)
putchar(c);
return 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

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

K & R C Programs Exercise 4-6.

K and R C, Solution to Exercise 4-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 Add commands for handling variables.(It's easy to provide twenty-six variables with single-letter names.). Add a variable for the most recently printed value.

```/***********************************************************
* 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 info@c-program-example.com
* 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>
#include <string.h>

#define MAXOP      100
#define NUMBER       0
#define IDENTIFIER   1
#define ENDSTRING    2
#define TRUE         1
#define FALSE        0
#define MAX_ID_LEN  32
#define MAXVARS     30

struct varType{
char name[MAX_ID_LEN];
double val;
};

int Getop(char s[]);
void push(double val);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStacks(struct varType var[]);
void dealWithName(char s[],  struct varType var[]);
void dealWithVar(char s[], struct varType var[]);

int pos = 0;
struct varType last;

int main(void)
{
int type;
double op2;
char s[MAXOP];
struct varType var[MAXVARS];

clearStacks(var);

while((type = Getop(s)) != EOF)
{
switch(type)
{
case NUMBER:
push(atof(s));
break;
case IDENTIFIER:
dealWithName(s, var);
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 '!':
clearStacks(var);
break;
case '\n':
printf("\n\t%.8g\n", pop());
break;
case ENDSTRING:
break;
case '=':
pop();
var[pos].val = pop();
last.val = var[pos].val;
push(last.val);
break;
case '<':
printf("The last variable used was: %s (value == %g)\n",
last.name, last.val);
break;

default:
printf("\nError: unknown command %s.\n", s);
break;
}
}
return EXIT_SUCCESS;
}

#define MAXVAL 100

int sp = 0;
double val[MAXVAL];

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

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

void showTop(void)
{
if(sp > 0)
printf("Top of stack contains: %8g\n", 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);
}

void clearStacks(struct varType var[])
{
int i;
sp = 0;

for( i = 0; i < MAXVARS; ++i)
{
var[i].name[0] = '\0';
var[i].val = 0.0;
}
}

void dealWithName(char s[], struct varType var[])
{
double op2;

if(!strcmp(s, "sin"))
push(sin(pop()));
else if(!strcmp(s, "cos"))
push(cos(pop()));
else if (!strcmp(s, "exp"))
push(exp(pop()));
else if(!strcmp(s, "pow"))
{
op2 = pop();
push(pow(pop(), op2));
}

else
{
dealWithVar(s, var);
}
}

void dealWithVar(char s[], struct varType var[])
{
int i = 0;

while(var[i].name[0] != '\0' && i < MAXVARS-1)
{
if(!strcmp(s, var[i].name))
{
strcpy(last.name, s);
last.val = var[i].val;
push(var[i].val);
pos = i;
return;
}
i++;
}

/* variable name not found so add it */
strcpy(var[i].name, s);
/* And save it to the last variable */
strcpy(last.name, s);
push(var[i].val);
pos = i;
}

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] = '\0';

if(isalpha(c))
{
i = 0;
while(isalpha(s[i++] = c ))
{
c = getch();
}
s[i - 1] = '\0';
if(c != EOF)
unGetch(c);
return IDENTIFIER;
}

/* Not a number but may contain a unary minus. */
if(!isdigit(c) && c != '.' && c != '-')
{
/* 4-6 Deal with assigning a variable. */
if('=' == c && '\n' == (next = getch()))
{
unGetch('\0');
return c;
}
if('\0' == c)
return ENDSTRING;

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] = '\0';
if(c != EOF)
unGetch(c);
return NUMBER;
}

#define BUFSIZE 100

int 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 characters\n");
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

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

K & R C Programs Exercise 4-5.

K and R C, Solution to Exercise 4-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 access to library functions like sin, exp, and pow. See "math.h" for more details.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 info@c-program-example.com
* 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>
#include <string.h>

#define MAXOP 100
#define NUMBER       0
#define IDENTIFIER   1
#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();
void mathfnc(char s[]);

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 IDENTIFIER:
mathfnc(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("\n\t%.8g\n", pop());
break;
default:
printf("\nError: unknown command %s.\n", s);
break;
}
}
return EXIT_SUCCESS;
}

#define MAXVAL 100

int sp = 0;
double val[MAXVAL];

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

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

void showTop(void)
{
if(sp > 0)
printf("Top of stack contains: %8g\n", 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);
}

void clearStack(void)
{
sp = 0;
}

/*check string s for supported math functions */
void mathfnc(char s[])
{
double op2;

if( 0 == strcmp(s, "sin"))
push(sin(pop()));
else if( 0 == strcmp(s, "cos"))
push(cos(pop()));
else if (0 == strcmp(s, "exp"))
push(exp(pop()));
else if(!strcmp(s, "pow"))
{
op2 = pop();
push(pow(pop(), op2));
}
else
printf("%s Error: is not a supported function.\n", s);
}

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] = '\0';

if(isalpha(c))
{
i = 0;
while(isalpha(s[i++] = c ))
c = getch();
s[i - 1] = '\0';
if(c != EOF)
unGetch(c);
return IDENTIFIER;
}

/* 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] = '\0';
if(c != EOF)
unGetch(c);
return NUMBER;
}

#define BUFSIZE 100

char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp]: getchar();
}

void unGetch(int c)
{
if(bufp >= BUFSIZE)
printf("\nUnGetch: too many characters\n");
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

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

Jan 9, 2012

C Program to implement bucket sort.

Write C program to implement bucket sort.
The idea of Bucket Sort is to divide the interval [0, 1] into n equal-sized sub intervals, or buckets, and then distribute the n input numbers into the buckets. To produce the output, we simply sort the numbers in each bucket and then go through the buckets in order, listing elements in each.
Bucket sort runs in linear time when the input is drawn from a uniform distribution. 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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include<stdio.h>
void Bucket_Sort(int array[], int n)
{
int i, j;
int count[n];
for(i=0; i < n; i++)
{
count[i] = 0;
}
for(i=0; i < n; i++)
{
(count[array[i]])++;
}
for(i=0,j=0; i < n; i++)
{
for(; count[i]>0;(count[i])--)
{
array[j++] = i;
}
}
}
int main()
{
int array[100];
int num;
int i;
printf("Enter How many Numbers : ");
scanf("%d",&num);
printf("Enter the %d elements to be sorted:\n",num);
for(i = 0; i < num; i++ )
{
scanf("%d",&array[i]);
}
printf("\nThe array of elements before sorting : \n");
for (i = 0;i < num;i++)
{
printf("%d ", array[i]);
}
printf("\nThe array of elements after sorting : \n");
Bucket_Sort(array, num);
for (i = 0;i < n;i++)
{
printf("%d ", array[i]);
}
printf("\n");
return 0;
}

```
```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

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 Program to add one to digits of a number.

Write C Program to add one to digits of a number.
C Program that adds the 1 to each single digit of a number, i.e for Example 12345's output is 23456.
If the digit is 9 it adds 1 and follows the carry system, 9 becomes 0 and 9's left digit adds one more 1. I.e., 3491's output is 4602. 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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<conio.h>
int main()
{
int num,sum=0;
int rem,check=0;
clrscr( );
printf("Enter the required number:");
scanf("%d",&num);
printf("\nGiven Number: %d",num);
while(num>0)
{
rem=num%10;
if(rem!=9)
{
if(check==0)
sum=(10*sum)+(rem+1);
else{
sum=(10*sum)+(rem+2);
check=0;
}
}
else{
sum=(10*sum)+0;
check=1;
}
num=num/10;
}

num=sum; sum=0;
while(num>0)
{
rem=num%10;
sum=(10*sum)+rem;
num=num/10;
}
printf("\nAfter Adding one: %d",sum);
getch( );
return 0;
}
```
```Read more Similar C Programs
Learn C Programming

Number System```

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

To get regular updates on new C programs, you can

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!

C Program to implement Priority Queue using structure.

Data structures using C,
Write a C Program to implement Priority Queue using structure.
Priority QUEUE is a abstract data type in which the objects are inserted with respect to certain priority. In this program, we created the simple ascending order priority queue using the structure, here items are inserted in ascending order. Structure is a c composite data type, in which we can define all the data types under the same name or object.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 info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#define SIZE 5            /* Size of Queue */
int f=0,r=-1;       /* Global declarations */
typedef struct PRQ
{
int ele;
int pr;
}PriorityQ;

PriorityQ PQ[SIZE];

PQinsert(int elem, int pre)
{
int i;       /* Function for Insert operation */
if( Qfull()) printf("\n\n Overflow!!!!\n\n");
else
{
i=r;
++r;
while(PQ[i].pr >= pre && i >= 0) /* Find location for new elem */
{
PQ[i+1]=PQ[i];
i--;
}
PQ[i+1].ele=elem;
PQ[i+1].pr=pre;
}
}

PriorityQ PQdelete()
{                      /* Function for Delete operation */
PriorityQ p;
if(Qempty()){ printf("\n\nUnderflow!!!!\n\n");
p.ele=-1;p.pr=-1;
return(p); }
else
{
p=PQ[f];
f=f+1;
return(p);
}
}

int Qfull()
{                     /* Function to Check Queue Full */
if(r==SIZE-1) return 1;
return 0;
}

int Qempty()
{                    /* Function to Check Queue Empty */
if(f > r) return 1;
return 0;
}

display()
{                  /* Function to display status of Queue */
int i;
if(Qempty()) printf(" \n Empty Queue\n");
else
{
printf("Front->");
for(i=f;i<=r;i++)
printf("[%d,%d] ",PQ[i].ele,PQ[i].pr);
printf("<-Rear");
}
}

main()
{                         /* Main Program */
int opn;
PriorityQ p;
do
{
clrscr();
printf("\n ### Priority Queue Operations(DSC order) ### \n\n");
printf("\n Press 1-Insert, 2-Delete,3-Display,4-Exit\n");
printf("\n Your option ? ");
scanf("%d",&opn);
switch(opn)
{
case 1: printf("\n\nRead the element and its Priority?");
scanf("%d%d",&p.ele,&p.pr);
PQinsert(p.ele,p.pr); break;
case 2: p=PQdelete();
if( p.ele != -1)
printf("\n\nDeleted Element is %d \n",p.ele);
break;
case 3: printf("\n\nStatus of Queue\n\n");
display(); break;
case 4: printf("\n\n Terminating \n\n"); break;
default: printf("\n\nInvalid Option !!! Try Again !! \n\n");
break;
}
printf("\n\n\n\n  Press a Key to Continue . . . ");
getch();
}while(opn != 4);
}

```
```Read more Similar C Programs
Data Structures

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

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

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 info@c-program-example.com
* 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("\n\t%.8g\n", 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 %g\n", f);
}

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

void showTop(void)
{
if(sp > 0)
printf("Top of stack contains: %8g\n", 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] = '\0';

/* 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] = '\0';
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 characters\n");
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

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

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 info@c-program-example.com
* 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 divissor\n")
break;
case '%':
op2 = pop();
if(op2)
push(fmod(pop(), op2));
else
printf("\nError: Division by zero!");
break;
case '\n':
printf("\t%.8g\n",pop());
break;
default:
printf("error: unknown command %s\n", 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] = '\0';

/* 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] = '\0';
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 %g\n", f);
}

/*pop: pop and return top value from stack.*/
double pop(void)
{
if(sp > 0)
return val[--sp];
else
{
printf("\nError: stack empty\n");
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

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

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 info@c-program-example.com
* 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) = %g\n", 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

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