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 [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>
#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("nt%.8gn", 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 %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);
}


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

for( i = 0; i < MAXVARS; ++i)
{
var[i].name[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] != '' && 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] = '';

if(isalpha(c))
{
i = 0;
while(isalpha(s[i++] = c ))
{
c = getch();
}
s[i - 1] = '';
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('');
return c;
}
if('' == 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] = '';
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 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-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 [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>
#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("nt%.8gn", 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 %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);
}

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

if(isalpha(c))
{
i = 0;
while(isalpha(s[i++] = c ))
c = getch();
s[i - 1] = '';
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] = '';
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 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

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 [email protected]
* 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 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

Like to get updates right inside your feed reader? Grab our feed!
(c) www.c-program-example.com

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 [email protected]
* 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("nn Overflow!!!!nn");
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("nnUnderflow!!!!nn");
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 Queuen");
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) ### nn");
printf("n Press 1-Insert, 2-Delete,3-Display,4-Exitn");
printf("n Your option ? ");
scanf("%d",&opn);
switch(opn)
{
case 1: printf("nnRead 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("nnDeleted Element is %d n",p.ele);
break;
case 3: printf("nnStatus of Queuenn");
display(); break;
case 4: printf("nn Terminating nn"); break;
default: printf("nnInvalid Option !!! Try Again !! nn");
break;
}
printf("nnnn 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 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-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