How to load picture in C Program.

You can make use of OleLoadPicture function. This function converts different formats not only gif file format but .jpg, .bmp, .ico, .emf, .wmf into an IPicture interface. Then you can make use of IPicture::Render function to display the picture.

Try and let us know whether you could succeed.

Related Links :

How to make the password in to asterisk and asign a exact password for char In C



#include
#include
#include
//#include
main()
{
int c;
int i;
char pwd[80];
// clrscr();
printf("ENTER Password");
for ( i = 0; i < 79 &&
(c = getch()) != '\r'; ++i )
{
pwd[i] = c;
putch('*');
}
pwd[i] = '\0';
printf("\n");;
if ( strcmp(pwd, "liza") == 0 )
{
printf("Correct \n");
}
else
{
printf("Incorrect \n");
}
return 0;
}

Related Links :

what abstraction and encapsulation is through example?

class eg
{

int rn;
char n[20];
//by default memebers of the class are private
public:

void getd()
{

}


void dispd()
{
}
};

//encapsulation wrapping or binding up of data and functions into a single unit called class so classes are used to encapsulate data and functions.

hide the information to outside world from direct use..

Abstraction is hiding internal implementation details ,just hilights the set of services to the outside world.for example..
University hides student information(like name,sex) to the examiner.but hiligthing the service as putMarks()..

class HallTicket

{
private:
char *name;
char *sex;
public:
void putMarks(){}
};
so examiner don't have any knowledge about name and sex etc..but he can put the marks by putMarks() service through the HallTicket object.

Encapsulation
holding the data behind the methods is called encapsulation..

Related Links :

how is the precedence and associativity?

#define multiply(x) x*x

main()
{
int result;
result = multiply(2) + 1;
}

what is the result value?
i told the answer is 5 since the macro gets expanded as 2*2+1
and here the multiplication takes first and addition latter.
but the interviewer said ans is 6 since the evaluation takes place from Left to right so first addition and then multiplcation.
i am not sure now what is correct ? i think * and + have L to R associativity and * has higher precedence.
So, Friends....Can someone correct me if i am wrong?

Related Links :

String Handling

char *t1 = malloc(sizeof(char)*10);
char *t2 = malloc(sizeof(char)*10);
writing above statements is not ANSI standard and is wrong to get desired result because malloc returns void* (pointer to void mean it returns pointer that points to nothing)

you have to parse the pointer returned by malloc as given below

char *t1 =(char*) malloc(sizeof(char)*10);
char *t2 = (char*)malloc(sizeof(char)*10);


sencondly, t1 and t2 do not hold values, t1 and t2 hold memory address as allocated by malloc so the statement t1=t2 does not assigns the values pointed by t2 but it assigns the address of the location pointed by t2 and after that statement t1 and t2 will hold same address or they will point to the same memory location. if you want to copy values
*t1 = *t2; is the statement.

Related Links :

Want to know the derived Class

LicenseProvider class provides an abstract base class for implementing a license provider. It derives from System.Object and the inheritance hierarchy is as follows


System.Object
System.ComponentModel.LicenseProvider
System.ComponentModel.LicFileLicenseProvider

Related Links :

Difference between Interface and Abstract Class in C

an abstract class is just a outline of the entire class. u can have only method name inside it. u can't create objects for them. a abstract class should always be inherited. where as a inteface is a collection or a group of empty methods.

An abstract class is a class which may or maynot consist of the abstract methods while an interface must have all the functions as abstract.

the abstract class with all the functions as abstract must be defined as an interface.

Abstract class can (or not ) have methods in it and it has no use in instantiating it since it has no meaning in instantiation.
It has to be inherited for use .
You need to INHERIT to use an abstract class.
You can have a variable in Abstract class. ( a silly difference )
Basically u use an abstract class when you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.

Interface - group of related methods with empty bodies .
You need to IMPLEMENT to use an interface.
I dont think you can have a variable in a interface.
When you want a few classes to use a few methods which you dont want to be included in the class ,then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface. But the problem with the interface is that, u have to implement all the methods defined in the interface , even if you dont need some of them.

Related Links :

C program to find given number positive , negative or smaller number


#include
main()
{ int count=0;
float value, high, low, sum=0, average, range;
clrscr();
printf("Enter numbers in a line: input a NEGAATIVE number to end\n");
input:
scanf("%f",&value);
if(value<0)
goto output;
count+=1;
if(count==1)
high=low=value;
else if(value>high)
high=value;
else if(value<=low)
low=value;
sum+=value;
goto input;
output:
average=sum/count;
range=high-low;
printf("\n\n");
printf("Total values: %d\n", count);
printf("Highest-value: %f\n Lowest-value: %f\n", high, low);
printf("Range : %f\nAverage : %f\n", range, average);
getch();
}


Related Links :

c program to sorting the given number in c


#include
void sort(int m, int x[]);
main()
{
int i;
int marks[5]={40, 90, 73, 81, 35};
clrscr();
printf("Marks before sorting\n");
for(i=0; i<5; i++)
printf("%4d", marks[i]);
printf("\n\n");
sort(5,marks);
printf("Marks after sorting\n");
for(i=0; i<5; i++)
printf("%4d", marks[i]);
printf("\n");
getch();
}
void sort(int m, int x[])
{
int i, j, temp;
for(i=1; i<=m-1; i++)
{
for(j=1;j<=m-1;j++)
{
if(x[j-1]>=x[j]
{
temp=x[j-1];
x[j-1]=x[j];
x[j]=temp;
}
}
}
}



Related Links :

C Program to find difference between given two numbers by using user define function


#include
float ratio(int x, int y, int z);
int difference(int x, int y);
main()
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
printf("%f \n", ratio(a,b,c));
getch();
}

float ratio(int x, int y, int z)
{
if(difference(y,z))
return(x/(y-z));
else
return(0.0);
}

int difference(int p, int q)
{
if(p!=q)
return(1);
else
return(0);
}


Related Links :

Program on Array implementation of stack in C

 

# include< stdio.h>
# include< string.h>
# define size 3
int tos= -1;
/*this variable will keep track of the top of the stack */
int flag = 0;
/* this variable will determine whether push or pop will be granted. */
int stack[size];
/* array , within this array stack will grow and shrink. */
void push(int s[], int d)
{
if(tos==size-1)
{
/* this condition becomes true when the stack can not grow further */
flag=0;
}
else
{
flag = 1;
++tos;
s[tos] = d;
}
}
int pop(int s[])
{
int p;
if(tos == -1)
{
p = 0;
flag = 0;
}
else
{
flag = 1;
p = s[tos];
--tos;
}
return p;
}
void display(int s[])
{
int i;
if(tos == -1)
{
printf("\n Stack is empty");
}
else
{
for(i = tos; i >= 0; --i)
printf("\n %d", s[i] );
}
}
void main()
{
int data;
char choice;
int q = 0;
clrscr();
do
{
printf(" \nPush->i Pop->p Quit->q:");
printf("\nInput the choice : ");
do
{
choice = getchar();
choice =tolower(choice);
}while(strchr("ipq",choice)==NULL);
printf("Your choice is: %c",choice);
switch(choice)
{
case 'i' :
printf("\n Input the element to push:");
scanf("%d", &data);
push(stack, data);
if(flag)
{
printf("\n After inserting ");
display(stack);
if(tos == (size-1))
printf("\n Stack is full");
}
else
printf("\n capacity is exhausted");
break;
case 'p' :
data = pop(stack);
if(flag)
{
printf("\n Data is popped: %d", data);
printf("\n Rest data in stack is as follows:\n");
display(stack);
}
else
printf("\n No popping took place" );
break;
case 'q':
q = 1;
}
} while(!q);
getch();
}


Related Links :

C Program to show Linked list implementation of stack

 

# include< stdio.h>
# include< stdlib.h>
struct link
{
int info;
struct link *next;
};
void display(struct link *rec)
{
while(rec != NULL)
{
printf(" %d ",rec->info);
rec = rec->next;
}
}
struct link * push(struct link *rec)
{
struct link *new1;
printf("\n Enter value for stack:-");
new1 = (struct link *)malloc(sizeof(struct link));
scanf("%d", &new1->info);
new1->next = rec;
/* next pointer of new1 is holding the address of the first node of the list. so new1 is the first node now.*/
rec = new1;
/* from this point the pointer rec is pointing the first node of the list. */
return rec;
}
struct link * pop(struct link *rec)
{
struct link *temp;
if(rec == NULL)
{
printf("\n Stack is empty");
}
else
{
/*rec is pointing the first node of the list.*/
temp = rec->next;
/*temp is pointing the second node of the list. */
free(rec);
rec = temp;
printf("\n After pop operation the stack is as follows:\n");
display(rec);
if(rec == NULL)
printf("\n Stack is empty");
}
return rec;
}
int selection()
{
int choice;
do
{
printf("\n 1<-Push ");
printf("\n 2<-Pop");
printf("\n 3<-Quit");
printf("\n Input your choice :");
scanf("%d", &choice);
if(choice <1 || choice >3)
printf("\n Incorrect choice-> Try once again");
} while(choice <1 || choice >3);
return choice;
}
void main()
{
struct link *start ;
int choice;
clrscr();
start = NULL;
do
{
choice = selection();
switch(choice)
{
case 1:
start = push(start);
printf("\n After push operation stack is as follows:\n");
display(start);
break;
case 2:
start = pop(start);
break;
default :
printf("\n End of session");
}
} while(choice != 3);
getch();
}


Related Links :

C Program of reversing linked list using stack

This Program Shows the Demonstration of reversing linked list using stack.


 
#include< stdio.h>
#include< stdlib.h>
struct tag
{
int a;
struct tag *next;
};
int i=0;
struct tag *node,*p,*p1;
void create(struct tag *n)
{
char ch;
node=n;
printf("\n Do You Want to create(y/n)");
ch=getche();
while(ch!='n')
{
node->next=(struct tag*)malloc(sizeof(struct tag));
node=node->next;
printf("\n Value");
scanf("%d",&node->a);
printf("\nany more(y/n)");
ch=getche();
}
node->next=NULL;
}
void display(struct tag*n)
{
node=n;
if(node==NULL)
i=0;
else
i=1;
while(node)
{
printf("%4d",node->a);
node=node->next;
}
}
struct tag *push(struct tag *p1,struct tag *p2)
{
p2->next=p1;
return(p2);
}
struct tag *delF(struct tag *n)
{
node=n->next;
n->next=node->next;
return(node);
}
struct tag *pop(struct tag *n)
{
node=n->next;
free(n);
return node;
}
void main()
{
struct tag *n,*link,*stack,*p;
clrscr();
link=NULL;
stack=NULL;
create(link);
printf("\nList is as follows\n");
display(link->next);
do
{
p=delF(link);
stack=push(stack,p);
}while(link->next!=NULL);
printf("\nList is as follows (after converting it into a stack.)");
display(link->next);
if(i==0)
printf("\nNo element in the list.");
printf("\nStack is\n");
display(stack);
n=link;
while(stack!=NULL)
{
n->next=stack;
n=n->next;
stack=pop(stack);
}
printf("\nStack is as follows (after converting it into a linked list.)");
display(stack);
if(i==0)
printf("\nNo element in the stack.");
printf("\nFinal list\n");
display(link->next);
getch();
}

Related Links :

Program to read PC Type from BIOS Data Area and display it.


# include
# include


int main( )
{
clrscr( );

unsigned char far* ptrPcType=(unsigned char far*)0xF000FFFE;

printf("Model Identification Code:\n\n");
printf(" Code (Hex) ::: Meanings\n");
printf(" FC : AT\n");
printf(" FE : XT\n");
printf(" FB : XT\n");
printf(" FF : PC\n");

printf("\n\nYour PC Type Code (Hex): %X",*ptrPcType);

getch( );
return 0;
}


Related Links :

Program to find greatest number from one dimensional array in C Programming


#include
#include

int main()
{
int a[20],n,i,max=0; // declared the array a with size 20
clrscr();

printf("\n Enter the number of elements for 1-D array : ");
scanf("%d",&n);

for(i=0;i<=n;i++) n="" enter="" element="" d="" i="0;i




Output:

Enter the number of elements for 1-D array : 5

Enter element [1] : 1
Enter element [2] : 8
Enter element [3] : 2
Enter element [4] : 5
Enter element [5] : 9

Greatest element from above array inserted is: 9

Related Links :

Arrays of Pointers to functions In C

 
#include

/* Function prototypes */
int sum(int, int);
int product(int, int);
int difference(int, int);
int main(void)
{
int a = 10; /* Initial value for a */
int b = 5; /* Initial value for b */
int result = 0; /* Storage for results */
int (*pfun[3])(int, int); /* Function pointer array declaration */
/* Initialize pointers */
pfun[0] = sum;
pfun[1] = product;
pfun[2] = difference;
/* Execute each function pointed to */
for(int i = 0 ; i < 3 ; i++)
{
result = pfun[i](a, b); /* Call the function through a pointer */
printf("\nresult = %d", result); /* Display the result */
}
/* Call all three functions through pointers in an expression */
result = pfun[1](pfun[0](a, b), pfun[2](a, b));
printf("\n\nThe product of the sum and the difference = %d\n", result);
return 0;
}


int sum(int x, int y)
{
return x + y;
}


int product(int x, int y)
{
return x * y;
}


int difference(int x, int y)
{
return x - y;
}





Related Links :

Passing a Pointer to a function In C

  
#include

/* Function prototypes */
int sum(int,int);
int product(int,int);
int difference(int,int);
int any_function(int(*pfun)(int, int), int x, int y);
int main(void)
{
int a = 10; /* Initial value for a */
int b = 5; /* Initial value for b */
int result = 0; /* Storage for results */
int (*pf)(int, int) = sum; /* Pointer to function */

/* Passing a pointer to a function */
result = any_function(pf, a, b);

printf("\nresult = %d", result );

/* Passing the address of a function */
result = any_function(product,a, b);
printf("\nresult = %d", result );
printf("\nresult = %d\n", any_function(difference, a, b));
return 0;
}

/* Definition of a function to call a function */
int any_function(int(*pfun)(int, int), int x, int y)
{
return pfun(x, y);
}
/* Definition of the function sum */
int sum(int x, int y)
{
return x + y;
}

/* Definition of the function product */
int product(int x, int y)
{
return x * y;
}

/* Definition of the function difference */
int difference(int x, int y)
{
return x - y;
}

Related Links :

Static versus automatic variables In C

  

#include
/* Function prototypes */
void test1(void);
void test2(void);
int main(void)
{
for(int i = 0; i < 5; i++ )
{
test1();
test2();
}
return 0;
}
/* Function test1 with an automatic variable */
void test1(void)
{
int count = 0;
printf("\ntest1 count = %d ", ++count );
}
/* Function test2 with a static variable */
void test2(void)
{
static int count = 0;
printf("\ntest2 count = %d ", ++count );
}

Related Links :

Calculating factorials using recursion Function In C

Calculating factorials using recursion Function In C


#include

unsigned long factorial(unsigned long);
int main(void)
{
unsigned long number = 0L;
printf("\nEnter an integer value: ");
scanf(" %lu", &number);
printf("\nThe factorial of %lu is %lu\n", number, factorial(number));
return 0;
}
/* Our recursive factorial function */
unsigned long factorial(unsigned long n)
{
if(n < 2L)
return n;
else
return n*factorial(n - 1L);
}

Related Links :

Calculating an average using variable argument lists in C

Calculating an average using variable argument lists in C



#include
#include
double average(double v1 , double v2,...); /* Function prototype */

int main(void)
{
double Val1 = 10.5, Val2 = 2.5;
int num1 = 6, num2 = 5;
long num3 = 12, num4 = 20;
printf("\n Average = %lf", average(Val1, 3.5, Val2, 4.5, 0.0));
printf("\n Average = %lf", average(1.0, 2.0, 0.0));
printf("\n Average = %lf\n", average( (double)num2, Val2,(double)num1,
(double)num4,(double)num3, 0.0));
return 0;
}

/* Function to calculate the average of a variable number of arguments */
double average( double v1, double v2,...)
{
va_list parg; /* Pointer for variable argument list */
double sum = v1+v2; /* Accumulate sum of the arguments */
double value = 0; /* Argument value */
int count = 2; /* Count of number of arguments */

va_start(parg,v2); /* Initialize argument pointer */

while((value = va_arg(parg, double)) != 0.0)
{
sum += value;
count++;
}
va_end(parg); /* End variable argument process */
return sum/count;
}



Related Links :

REVERSI An Othello type game In C

REVERSI An Othello type game In C


  

#include
#include
#include
#include

const int SIZE = 6; /* Board size - must be even */
const char comp_c = '@'; /* Computer's counter */
const char player_c = 'O'; /* Player's counter */

/* Function prototypes */
void display(char board[][SIZE]);
int valid_moves(char board[][SIZE], bool moves[][SIZE], char player);
void make_move(char board[][SIZE], int row, int col, char player);
void computer_move(char board[][SIZE], bool moves[][SIZE], char player);
int best_move(char board[][SIZE], bool moves[][SIZE], char player);
int get_score(char board[][SIZE], char player);

int main(void)
{
char board [SIZE][SIZE] = { 0 }; /* The board */
bool moves[SIZE][SIZE] = { false }; /* Valid moves */
int row = 0; /* Board row index */
int col = 0; /* Board column index */
int no_of_games = 0; /* Number of games */
int no_of_moves = 0; /* Count of moves */
int invalid_moves = 0; /* Invalid move count */
int comp_score = 0; /* Computer score */
int user_score = 0; /* Player score */
char y = 0; /* Column letter */
int x = 0; /* Row number */
char again = 0; /* Replay choice input */

/* Player indicator: true for player and false for computer */
bool next_player = true;

printf("\nREVERSI\n\n");
printf("You can go first on the first game, then we will take turns.\n");
printf(" You will be white - (%c)\n I will be black - (%c).\n",
player_c, comp_c);
printf("Select a square for your move by typing a digit for the row\n "
"and a letter for the column with no spaces between.\n");
printf("\nGood luck! Press Enter to start.\n");
scanf("%c", &again);

/* The main game loop */
do
{
/* On even games the player starts; */
/* on odd games the computer starts */
next_player = !next_player;
no_of_moves = 4; /* Starts with four counters */

/* Blank all the board squares */
for(row = 0; row < SIZE; row++)
for(col = 0; col < SIZE; col++)
board[row][col] = ' ';

/* Place the initial four counters in the center */
int mid = SIZE/2;
board[mid - 1][mid - 1] = board[mid][mid] = player_c;
board[mid - 1][mid] = board[mid][mid - 1] = comp_c;
/* The game play loop */
do
{
display(board); /* Display the board */
if(next_player=!next_player)
{ /* It is the player's turn */
if(valid_moves(board, moves, player_c))
{
/* Read player moves until a valid move is entered */
for(;;)
{
printf("Please enter your move (row column): ");
scanf(" %d%c", &x, &y); /* Read input */
y = tolower(y) - 'a'; /* Convert to column index */
x--; /* Convert to row index */
if( x>=0 && y>=0 && x {
make_move(board, x, y, player_c);
no_of_moves++; /* Increment move count */
break;
}
else
printf("Not a valid move, try again.\n");
}
}
else /* No valid moves */
if(++invalid_moves < 2)
{
printf("\nYou have to pass, press return");
scanf("%c", &again);
}
else
printf("\nNeither of us can go, so the game is over.\n");
}
else
{ /* It is the computer's turn */
if(valid_moves(board, moves, '@')) /* Check for valid moves */
{
invalid_moves = 0; /* Reset invalid count */
computer_move(board, moves, '@');
no_of_moves++; /* Increment move count */
}
else
{
if(++invalid_moves < 2)
printf("\nI have to pass, your go\n"); /* No valid move */
else
printf("\nNeither of us can go, so the game is over.\n");
}

}
}while(no_of_moves < SIZE*SIZE && invalid_moves<2);

/* Game is over */
display(board); /* Show final board */

/* Get final scores and display them */
comp_score = user_score = 0;
for(row = 0; row < SIZE; row++)
for(col = 0; col < SIZE; col++)
{
comp_score += board[row][col] == comp_c;
user_score += board[row][col] == player_c;
}
printf("The final score is:\n");
printf("Computer %d\n User %d\n\n", comp_score, user_score);

printf("Do you want to play again (y/n): ");
scanf(" %c", &again); /* Get y or n */
}while(tolower(again) == 'y'); /* Go again on y */

printf("\nGoodbye\n");

return 0;
}

/***********************************************
* Function to display the board in its *
* current state with row numbers and column *
* letters to identify squares. *
* Parameter is the board array. *
***********************************************/
void display(char board[][SIZE])
{
/* Display the column labels */
char col_label = 'a'; /* Column label */
printf("\n "); /* Start top line */
for(int col = 0 ; col printf(" %c", col_label+col); /* Display the top line */
printf("\n"); /* End the top line */

/* Display the rows… */
for(int row = 0; row < SIZE; row++)
{
/* Display the top line for the current row */
printf(" +");
for(int col = 0; col printf("---+");
printf("\n%2d|",row + 1);

/* Display the counters in current row */
for(int col = 0; col printf(" %c |", board[row][col]); /* Display counters in row */
printf("\n");
}

/* Finally display the bottom line of the board */
printf(" +"); /* Start the bottom line */
for(int col = 0 ; col printf("---+"); /* Display the bottom line */
printf("\n"); /* End the bottom line */
}

/***********************************************
* Calculates which squares are valid moves *
* for player. Valid moves are recorded in the *
* moves array - true indicates a valid move, *
* false indicates an invalid move. *
* First parameter is the board array *
* Second parameter is the moves array *
* Third parameter identifies the player *
* to make the move. *
* Returns valid move count. *
**********************************************/
int valid_moves(char board[][SIZE], bool moves[][SIZE], char player)
{
int rowdelta = 0; /* Row increment around a square */
int coldelta = 0; /* Column increment around a square */
int x = 0; /* Row index when searching */
int y = 0; /* Column index when searching */
int no_of_moves = 0; /* Number of valid moves */

/* Set the opponent */
char opponent = (player == player_c)? comp_c : player_c;

/* Initialize moves array to false */
for(int row = 0; row < SIZE; row++)
for(int col = 0; col < SIZE; col++)
moves[row][col] = false;

/* Find squares for valid moves. */
/* A valid move must be on a blank square and must enclose */
/* at least one opponent square between two player squares */
for(int row = 0; row < SIZE; row++)
for(int col = 0; col < SIZE; col++)
{
if(board[row][col] != ' ') /* Is it a blank square? */
continue; /* No - so on to the next */

/* Check all the squares around the blank square */
/* for the opponents counter */
for(rowdelta = -1; rowdelta <= 1; rowdelta++)
for(coldelta = -1; coldelta <= 1; coldelta++)
{
/* Don't check outside the array, or the current square */
if(row + rowdelta < 0 || row + rowdelta >= SIZE ||
col + coldelta < 0 || col + coldelta >= SIZE ||
(rowdelta==0 && coldelta==0))
continue;

/* Now check the square */
if(board[row + rowdelta][col + coldelta] == opponent)
{
/* If we find the opponent, move in the delta direction */
/* over opponent counters searching for a player counter */
x = row + rowdelta; /* Move to */
y = col + coldelta; /* opponent square */

/* Look for a player square in the delta direction */
for(;;)
{
x += rowdelta; /* Go to next square */
y += coldelta; /* in delta direction*/

/* If we move outside the array, give up */
if(x < 0 || x >= SIZE || y < 0 || y >= SIZE)
break;

/* If we find a blank square, give up */
if(board[x][y] == ' ')
break;

/* If the square has a player counter */
/* then we have a valid move */
if(board[x][y] == player)
{
moves[row][col] = true; /* Mark as valid */
no_of_moves++; /* Increase valid moves count */
break; /* Go check another square */
}
}
}
}
}
return no_of_moves;
}

/********************************************************************
* Makes a move. This places the counter on a square and reverses *
* all the opponent's counters affected by the move. *
* First parameter is the board array. *
* Second and third parameters are the row and column indices. *
* Fourth parameter identifies the player. *
********************************************************************/
void make_move(char board[][SIZE], int row, int col, char player)
{
int rowdelta = 0; /* Row increment */
int coldelta = 0; /* Column increment */
int x = 0; /* Row index for searching */
int y = 0; /* Column index for searching */

/* Identify opponent */
char opponent = (player == player_c) ? comp_c : player_c;

board[row][col] = player; /* Place the player counter */

/* Check all the squares around this square */
/* for the opponents counter */
for(rowdelta = -1; rowdelta <= 1; rowdelta++)
for(coldelta = -1; coldelta <= 1; coldelta++)
{
/* Don't check off the board, or the current square */
if(row + rowdelta < 0 || row + rowdelta >= SIZE ||
col + coldelta < 0 || col + coldelta >= SIZE ||
(rowdelta==0 && coldelta== 0))
continue;

/* Now check the square */
if(board[row + rowdelta][col + coldelta] == opponent)
{
/* If we find the opponent, search in the same direction */
/* for a player counter */
x = row + rowdelta; /* Move to opponent */
y = col + coldelta; /* square */

for(;;)
{
x += rowdelta; /* Move to the */
y += coldelta; /* next square */

/* If we are off the board give up */
if(x < 0 || x >= SIZE || y < 0 || y >= SIZE)
break;

/* If the square is blank give up */
if(board[x][y] == ' ')
break;

/* If we find the player counter, go backward from here */
/* changing all the opponents counters to player */
if(board[x][y] == player)
{
while(board[x-=rowdelta][y-=coldelta]==opponent) /* Opponent? */
board[x][y] = player; /* Yes, change it */
break; /* We are done */
}
}
}
}
}

/*******************************************************************
* Calculates the score for the current board position for the *
* player. player counters score +1, opponent counters score -1 *
* First parameter is the board array *
* Second parameter identifies the player *
* Return value is the score. *
*******************************************************************/
int get_score(char board[][SIZE], char player)
{
int score = 0; /* Score for current position */

/* Identify opponent */
char opponent = (player == player_c) ? comp_c : player_c;

/* Check all board squares */
for(int row = 0; row < SIZE; row++)
for(int col = 0; col < SIZE; col++)
{
score -= board[row][col] == opponent; /* Decrement for opponent */
score += board[row][col] == player; /* Increment for player */
}
return score;
}

/*******************************************************************
* Calculates the score for the best move out of the valid moves *
* for player in the current position. *
* First parameter is the board array *
* Second parameter is the moves array defining valid moves. *
* Third parameter identifies the player *
* The score for the best move is returned *
*******************************************************************/
int best_move(char board[][SIZE], bool moves[][SIZE], char player)
{
/* Identify opponent */
char opponent = (player == player_c) ? comp_c : player_c;

char new_board[SIZE][SIZE] = { 0 }; /* Local copy of board */
int score = 0; /* Best score */
int new_score = 0; /* Score for current move */

/* Check all valid moves to find the best */
for(int row = 0 ; row for(int col = 0 ; col {
if(!moves[row][col]) /* Not a valid move? */
continue; /* Go to the next */

/* Copy the board */
memcpy(new_board, board, sizeof(new_board));

/* Make move on the board copy */
make_move(new_board, row, col, player);

/* Get score for move */
new_score = get_score(new_board, player);

if(score score = new_score; /* Yes, save it as best score */
}
return score; /* Return best score */
}


/*******************************************************************
* Finds the best move for the computer. This is the move for *
* which the opponent's best possible move score is a minimum. *
* First parameter is the board array. *
* Second parameter is the moves array containing valid moves. *
* Third parameter identifies the computer. *
*******************************************************************/
void computer_move(char board[][SIZE], bool moves[][SIZE], char player)
{
int best_row = 0; /* Best row index */
int best_col = 0; /* Best column index */
int new_score = 0; /* Score for current move */
int score = 100; /* Minimum opponent score */
char temp_board[SIZE][SIZE]; /* Local copy of board */
int temp_moves[SIZE][SIZE]; /* Local valid moves array */

/* Identify opponent */
char opponent = (player == player_c) ? comp_c : player_c;

/* Go through all valid moves */
for(int row = 0; row < SIZE; row++)
for(int col = 0; col < SIZE; col++)
{
if(!moves[row][col])
continue;

/* First make copies of the board array */
memcpy(temp_board, board, sizeof(temp_board));

/* Now make this move on the temporary board */
make_move(temp_board, row, col, player);

/* find valid moves for the opponent after this move */
valid_moves(temp_board, temp_moves, opponent);

/* Now find the score for the opponent's best move */
new_score = best_move(temp_board, temp_moves, opponent);

if(new_score { /* Yes, so save this move */
score = new_score; /* Record new lowest opponent score */
best_row = row; /* Record best move row */
best_col = col; /* and column */
}
}
/* Make the best move */
make_move(board, best_row, best_col, player);
}


Related Links :

Inputting Characters in the format control string

 
#include
int main(void)
{
int i = 0;
int j = 0;
int value_count = 0;
float fp1 = 0.0;
printf("Input:\n");
value_count = scanf("fp1 = %f i = %d %d", &fp1, &i , &j);
printf("\nOutput:\n");
printf("\nCount of values read = %d", value_count);
printf("\nfp1 = %f\ti = %d\tj = %d\n", fp1, i, j);
return 0;
}

Related Links :

C Program to Reading hexadecimal and octal values

C Program to Reading hexadecimal and octal values


#include

int main(void)
{
int i = 0;
int j = 0;
int k = 0;
int n = 0;
printf("Input:\n");
n = scanf(" %d %x %o", &i , &j, &k );
printf("\nOutput:\n");
printf("%d values read.", n);
printf("\ni = %d j = %d k = %d\n", i, j, k );
/* Alternative to statement above
printf("\ni = %x j = %X k = %d\n", i, j, k );
*/
return 0;
}



Related Links :

Reading a string with gets() Function In C



#include
#include
/* For strlen() in the alternate code */

int main(void)
{
char initial[2] = {0};
char name[80] = {0};

printf("Enter your first initial: ");
gets(initial);
printf("Enter your name: " );
gets(name);

/* A safer version of the 4 lines above is as follows:*/
/*
printf("Enter your first initial: ");
fgets(initial, sizeof(initial), stdin);
fflush(stdin);
printf("Enter your name: " );
fgets(name, sizeof(name), stdin);
size_t length = strlen(name);
name[length-1] = name[length];
*/

if(initial[0] != name[0])
printf("\n%s,you got your initial wrong.\n", name);
else
printf("\nHi, %s. Your initial is correct. Well done!\n", name);
return 0;
}





Related Links :

Integer output variations in C


#include

int main(void)
{
int i = 15;
int j = 345;
int k = 4567;
long li = 56789L;
long lj = 678912L;
long lk = 23456789L;

printf("\ni = %d j = %d k = %d i = %6.3d j = %6.3d k = %6.3d\n",
i ,j, k, i, j, k);
printf("\ni = %-d j = %+d k = %-d i = %-6.3d j = %-6.3d k ="
" %-6.3d\n",i ,j, k, i, j, k);
printf("\nli = %d lj = %d lk = %d\n", li, lj, lk);
printf("\nli = %ld lj = %ld lk = %ld\n", li, lj, lk);
return 0;
}




Related Links :

Printing Value Variations on a single integer


#include

int main(void)
{
int k = 678;

printf("%%d %%o %%x %%X");
/* Display format as heading */
printf("\n%d %o %x %X", k, k, k, k );
/* Display values */

/* Display format as heading then display the values */
printf("\n\n%%8d %%-8d %%+8d %%08d %%-+8d");
printf("\n%8d %-8d %-+8d %08d %-+8d\n", k, k, k, k, k );
return 0;
}


Related Links :

Printing outputting floating-point values in Different Decimal Formats.

 
#include
int main(void)
{
float fp1 = 345.678f;
float fp2 = 1.234E6f;
double fp3 = 234567898.0;
double fp4 = 11.22334455e-6;
printf("\n%f %+f % 10.4f %6.4f\n", fp1, fp2, fp1, fp2);
printf("\n%e %+E\n", fp1, fp2);
printf("\n%f %g %#+f %8.4f %10.4g\n", fp3,fp3, fp3, fp3, fp4);
return 0;
}


Related Links :

Printing on a printer in C, Getting Hard Copy by C

 
#include
int main(void)
{
fprintf(stdprn, "The barber shaves all those who do not"
" shave themselves.");
fprintf(stdprn, "\n\rQuestion: Who shaves the barber?\n\r");
fprintf(stdprn, "\n\rAnswer: She doesn't need to shave.\f");
return 0;
}



Related Links :

Pointing out the horses using Memory allocation in C

 
#include
#include
#include /* For malloc() */

int main(void)
{
struct horse /* Structure declaration */
{
int age;
int height;
char name[20];
char father[20];
char mother[20];
};

struct horse *phorse[50]; /* pointer to structure array declaration */
int hcount = 0; /* Count of the number of horses */
char test = '\0'; /* Test value for ending input */

for(hcount = 0; hcount < 50 ; hcount++ )
{
printf("\nDo you want to enter details of a%s horse (Y or N)? ",
hcount?"nother " : "" );
scanf(" %c", &test );
if(tolower(test) == 'n')
break;

/* allocate memory to hold a structure */
phorse[hcount] = (struct horse*) malloc(sizeof(struct horse));

printf("\nEnter the name of the horse: " );
scanf("%s", phorse[hcount]->name ); /* Read the horse's name */

printf("\nHow old is %s? ", phorse[hcount]->name );
scanf("%d", &phorse[hcount]->age ); /* Read the horse's age */

printf("\nHow high is %s ( in hands )? ", phorse[hcount]->name );
scanf("%d", &phorse[hcount]->height ); /* Read the horse's height */

printf("\nWho is %s's father? ", phorse[hcount]->name );
scanf("%s", phorse[hcount]->father ); /* Get the father's name */

printf("\nWho is %s's mother? ", phorse[hcount]->name );
scanf("%s", phorse[hcount]->mother ); /* Get the mother's name */
}

/* Now tell them what we know. */
for (int i = 0 ; i < hcount ; i++ )
{
printf("\n\n%s is %d years old, %d hands high,",
phorse[i]->name, phorse[i]->age, phorse[i]->height);
printf(" and has %s and %s as parents.",
phorse[i]->father, phorse[i]->mother);
free(phorse[i]);
}
return 0;
}




Related Links :

Daisy chaining the horses both ways

 
#include
#include
#include

int main(void)
{
struct horse /* Structure declaration */
{
int age;
int height;
char name[20];
char father[20];
char mother[20];
struct horse *next; /* Pointer to next structure */
struct horse *previous; /* Pointer to previous structure */
};

struct horse *first = NULL; /* Pointer to first horse */
struct horse *current = NULL; /* Pointer to current horse */
struct horse *last = NULL; /* Pointer to previous horse */

char test = '\0'; /* Test value for ending input */

for( ; ; )
{
printf("\nDo you want to enter details of a%s horse (Y or N)? ",
first == NULL?"nother " : "");
scanf(" %c", &test );
if(tolower(test) == 'n')
break;

/* Allocate memory for each new horse structure */
current = (struct horse*)malloc(sizeof(struct horse));

if( first == NULL )
{
first = current; /* Set pointer to first horse */
current->previous = NULL;
}
else
{
last->next = current; /* Set next address for previous horse */
current->previous = last; /* Previous address for current horse */
}

printf("\nEnter the name of the horse: ");
scanf("%s", current -> name ); /* Read the horse's name */

printf("\nHow old is %s? ", current -> name);
scanf("%d", ¤t -> age); /* Read the horse's age */

printf("\nHow high is %s ( in hands )? ", current -> name);
scanf("%d", ¤t -> height); /* Read the horse's height */

printf("\nWho is %s's father? ", current -> name);
scanf("%s", current -> father); /* Get the father's name */

printf("\nWho is %s's mother? ", current -> name);
scanf("%s", current -> mother); /* Get the mother's name */

current -> next = NULL; /* In case it's the last horse..*/
last = current; /* Save address of last horse */
}

/* Now tell them what we know. */
while(current != NULL) /* Output horse data in reverse order */
{
printf("\n\n%s is %d years old, %d hands high,",
current->name, current->age, current->height);
printf(" and has %s and %s as parents.", current->father,
current->mother);
last = current; /* Save pointer to enable memory to be freed */
current = current->previous; /* current points to previous in list */
free(last); /* Free memory for the horse we output */
}
return 0;
}




Related Links :

Basics of a family tree in C

 
#include
#include
#include

struct Family *get_person(void); /* Prototype for input function */

struct Date
{
int day;
int month;
int year;
};

struct Family /* Family structure declaration */
{
struct Date dob;
char name[20];
char father[20];
char mother[20];
struct Family *next; /* Pointer to next structure */
struct Family *previous; /* Pointer to previous structure */
};

int main(void)
{
struct Family *first = NULL; /* Pointer to first person */
struct Family *current = NULL; /* Pointer to current person */
struct Family *last = NULL; /* Pointer to previous person */
char more = '\0'; /* Test value for ending input */

for( ; ; )
{
printf("\nDo you want to enter details of a%s person (Y or N)? ",
first != NULL?"nother" : "");
scanf(" %c", &more);
if(tolower(more) == 'n')
break;

current = get_person();

if(first == NULL)
{
first = current; /* Set pointer to first Family */
last = current; /* Remember for next iteration */
}
else
{
last->next = current; /* Set next address for previous Family */
current->previous = last; /* Set previous address for current */
last = current; /* Remember for next iteration */
}
}

/* Now tell them what we know */

/* Output Family data in reverse order */
while (current != NULL)
{
printf("\n%s was born %d/%d/%d, and has %s and %s as parents.",
current->name, current->dob.day, current->dob.month,
current->dob. year, current->father, current->mother );

last = current; /* Save pointer to enable memory to be freed */
current = current->previous; /* current points to previous list */
free(last); /* Free memory for the Family we output */
}
return 0;
}

/* Function to input data on Family members */
struct Family *get_person(void)
{
struct Family *temp; /* Define temporary structure pointer */

/* Allocate memory for a structure */
temp = (struct Family*) malloc(sizeof(struct Family));

printf("\nEnter the name of the person: ");
scanf("%s", temp -> name ); /* Read the Family's name */

printf("\nEnter %s's date of birth (day month year); ", temp->name);
scanf("%d %d %d", &temp->dob.day, &temp->dob.month, &temp->dob.year);

printf("\nWho is %s's father? ", temp->name );
scanf("%s", temp->father ); /* Get the father's name */

printf("\nWho is %s's mother? ", temp->name );
scanf("%s", temp -> mother ); /* Get the mother's name */

temp->next = temp->previous = NULL; /* Set pointers to NULL */

return temp; /* Return address of Family structure */
}




Related Links :

Operation of a union in C with example

 
#include
int main(void)
{
union u_example
{
float decval;
int pnum;
double my_value;
} U1;

U1.my_value = 125.5;
U1.pnum = 10;
U1.decval = 1000.5f;
printf("\ndecval = %f pnum = %d my_value = %lf",
U1.decval, U1.pnum, U1.my_value );
printf("\nU1 size = %d\ndecval size = %d pnum size = %d my_value"
" size = %d",sizeof U1, sizeof U1.decval,
sizeof U1.pnum, sizeof U1.my_value);
return 0;
}


Related Links :

Generating a bar chart in C

 

#include
#include
#include
#include

#define PAGE_HEIGHT 20
#define PAGE_WIDTH 40

typedef struct barTAG
{
double value;
struct barTAG *pnextbar;
}bar;

typedef unsigned int uint; /* Type definition*/

/* Function prototype */
int bar_chart(bar *pfirstbar, uint page_width, uint page_height, char *title);

int main(void)
{
bar firstbar; /* First bar structure */
bar *plastbar = NULL; /* Pointer to last bar */
char value[80]; /* Input buffer */
char title[80]; /* Chart title */

printf("\nEnter the chart title: ");
gets(title); /* Read chart title */

for( ;; ) /* Loop for bar input */
{
printf("Enter the value of the bar, or use quit to end: ");
gets(value);

if(strcmp(value, "quit") == 0) /* quit entered? */
break; /* then input finished */

/* Store in next bar */
if(!plastbar) /* First time? */
{
firstbar.pnextbar = NULL; /* Initialize next pointer */
plastbar = &firstbar; /* Use the first */
}
else
{
/* Get memory */
if(!(plastbar->pnextbar = malloc(sizeof(bar))))
{
printf("Oops! Couldn't allocate memory\n");
return -1;
}
plastbar = plastbar->pnextbar; /* Old next is new bar */
plastbar->pnextbar = NULL; /* New bar next is NULL */
}
plastbar->value = atof(value); /* Store the value */
}

/* Create bar-chart */
bar_chart(&firstbar, PAGE_WIDTH, PAGE_HEIGHT, title);

/* We are done, so release all the memory we allocated */
while(firstbar.pnextbar)
{
plastbar = firstbar.pnextbar; /* Save pointer to next */
firstbar.pnextbar = plastbar->pnextbar; /* Get one after next */
free(plastbar); /* Free next memory */
}
return 0;
}

int bar_chart(bar *pfirstbar, uint page_width, uint page_height,
char *title)
{
bar *plastbar = pfirstbar; /* Pointer to previous bar */
double max = 0.0; /* Maximum bar value */
double min = 0.0; /* Minimum bar value */
double vert_scale = 0.0; /* Unit step in vertical direction */
double position = 0.0; /* Current vertical position on chart */
uint bar_count = 1; /* Number of bars - at least 1 */
uint barwidth = 0; /* Width of a bar */
uint space = 2; /* spaces between bars */
uint i = 0; /* Loop counter */
uint bars = 0; /* Loop counter through bars */
char *column = NULL; /* Pointer to bar column section */
char *blank = NULL; /* Blank string for bar+space */
bool axis = false; /* Indicates axis drawn */
/* Find maximum and minimum of all bar values */

/* Set max and min to first bar value */
max = min = plastbar->value;

while((plastbar = plastbar->pnextbar) != NULL)
{
bar_count++; /* Increment bar count */
max = (max < plastbar->value)? plastbar->value : max;
min = (min > plastbar->value)? plastbar->value : min;
}
vert_scale = (max - min)/page_height; /* Calculate step length */

/* Check bar width */
if((barwidth = page_width/bar_count - space) < 1)
{
printf("\nPage width too narrow.\n");
return -1;
}

/* Set up a string that will be used to build the columns */

/* Get the memory */
if((column = malloc(barwidth + space + 1)) == NULL)
{
printf("\nFailed to allocate memory in barchart()"
" - terminating program.\n");
exit(1);
}
for(i = 0 ; i *(column+i)=' '; /* Blank the space between bars */
for( ; i *(column+i)='#'; /* Enter the bar characters */
*(column+i) = '\0'; /* Add string terminator */

/* Set up a string that will be used as a blank column */

/* Get the memory */
if((blank = malloc(barwidth + space + 1)) == NULL)
{
printf("\nFailed to allocate memory in barchart()"
" - terminating program.\n");
exit(1);
}

for(i = 0 ; i *(blank+i) = ' '; /* Blank total width of bar+space */
*(blank+i) = '\0'; /* Add string terminator */

printf("^ %s\n", title); /* Output the chart title */

/* Draw the bar chart */
position = max;
for(i = 0 ; i <= page_height ; i++)
{
/* Check if we need to output the horizontal axis */
if(position <= 0.0 && !axis)
{
printf("+"); /* Start of horizontal axis */
for(bars = 0; bars < bar_count*(barwidth+space); bars++)
printf("-"); /* Output horizontal axis */
printf(">\n");
axis = true; /* Axis was drawn */
position -= vert_scale;/* Decrement position */
continue;
}
printf("|"); /* Output vertical axis */
plastbar = pfirstbar; /* start with the first bar */

/* For each bar... */
for(bars = 1; bars <= bar_count; bars++)
{
/* If position is between axis and value, output column */
/* otherwise output blank */
printf("%s", position <= plastbar->value &&
plastbar->value >= 0.0 && position > 0.0 ||
position >= plastbar->value &&
plastbar->value <= 0.0 &&
position <= 0.0 ? column: blank);
plastbar = plastbar->pnextbar;
}
printf("\n"); /* End the line of output */
position -= vert_scale; /* Decrement position */
}
if(!axis) /* Have we output the horizontal axis? */
{ /* No, so do it now */
printf("+");
for(bars = 0; bars < bar_count*(barwidth+space); bars++)
printf("-");
printf(">\n");
}

/* Code for rest of the function... */
free(blank); /* Free memory for blank string */
free(column); /* Free memory for column string */
return 0;
}





Related Links :

C Program Macro to generate pseudo-random number from 0 to NumValues

 
/* Program to Debugging using preprocessing directives */
#include
#include
#include

/* Macro to generate pseudo-random number from 0 to NumValues */

#define random (NumValues) ((int)(((double)(rand())*(NumValues))/(RAND_MAX+1.0)))

#define iterations 6
#define test
/* Select testing output */
#define testf
/* Select function call trace */
#define repeatable
/* Select repeatable execution */

/* Function prototypes */
int sum(int, int);
int product(int, int);
int difference(int, int);

int main(void)
{
int funsel = 0;
/* Index for function selection */
int a = 10, b = 5;
/* Starting values */
int result = 0;
/* Storage for results */

/* Function pointer array declaration */
int (*pfun[])(int, int) = {sum, product, difference};

/* Conditional code for repeatable execution */
#ifdef repeatable
srand(1);
#else
srand((unsigned int)time(NULL));
/* Seed random number generation */
#endif

/* Execute random function selections */
int element_count = sizeof(pfun)/sizeof(pfun[0]);
for(int i = 0 ; i < iterations ; i++)
{
/* Generate random index to pfun array */

funsel = random(element_count);
if( funsel>element_count-1 )
{
printf("\nInvalid array index = %d", funsel);
exit(1);
}

#ifdef test
printf("\nRandom index = %d", funsel);
#endif

result = pfun[funsel](a , b);
/* Call random function */
printf("\nresult = %d", result );
}
return 0;
}

/* Definition of the function sum */
int sum(int x, int y)
{
#ifdef testf
printf("\nFunction sum called args %d and %d.", x, y);
#endif

return x + y;
}

/* Definition of the function product */
int product( int x, int y )
{
#ifdef testf
printf("\nFunction product called args %d and %d.", x, y);
#endif

return x * y;
}

/* Definition of the function difference */
int difference(int x, int y)
{
#ifdef testf
printf("\nFunction difference called args %d and %d.", x, y);
#endif

return x - y;
}



Related Links :

Program to Show Demonstrating assertions in C Language

 
/*Program to Show Demonstrating assertions in C Language */


#undef NDEBUG /* Switch on assertions */
#include
#include

int main(void)
{
int y = 5;
for(int x = 0 ; x < 20 ; x++)
{
printf("\nx = %d y = %d", x, y);
assert(x<=y);
}
return 0;
}


Related Links :

C Program to Reading monetary amounts separated by commas and spaces.


#include
void main()
{
double amounts[4] = {0.0};
double total = 0.0;
int i = 0;

printf("Enter the four amounts:\n");
for(i = 0 ; i<4 ; i++)
{
scanf("%*[ ,$]%lf", &amounts[i]);
total += amounts[i];
}
printf("The total of the input is: $%.2lf\n", total);
}


Related Links :

C Program A function to output double values in a given width.


#include
#include
#include
#define MAX_COUNT 100

void show(double array[], size_t array_size, unsigned int field_width);

void main()
{
double array[MAX_COUNT] = {0.0};
int count = 0;
char answer = 'n';
do
{
printf("Enter a value: ");
scanf("%lf", &array[count++]);
printf("Do you want to enter another (y or n)?: ");
scanf(" %c",&answer);
}
while(count<= MAX_COUNT && tolower(answer) == 'y');
show(array, count, 12);
printf("\n");
}

void show(double array[], size_t array_size, unsigned int field_width)
{
char format[10] = "%"; /* Holds the format string */
char width_str[4]; /* Holds the width value in character form */
size_t i = 0;
size_t j = 1;
do
{
width_str[i++] = '0'+field_width%10;
}while((field_width /= 10) != 0);
do
{
format[j++] = width_str[--i];
}while(i>0);
format[j] = '\0';
strcat(format, "lf");

for(j = 0 ; j {
if(j%5 == 0)
printf("\n");
printf(format, array[j]);
}
}


Related Links :

C Program function to read a string terminated by an arbitrary character.


#include
#include

#define MAX_SIZE 100
#define STRING_COUNT 5
char* getString(char *buffer, char end_char);
void main()
{
char buffer[MAX_SIZE] = {0};
int i = 0;
for(i = 0 ; i<=STRING_COUNT ; i++)
{
printf("Enter a string terminated by a semi-colon:\n");
getString(buffer, ';');
printf("The string you entered was:\n%s\n", buffer);
}
}

char* getString(char *buffer, char end_char)
{
size_t i = 0;
/* Read a character until end_char is entered */
while((buffer[i++] = getchar()) != end_char)
;
buffer[i-1] = '\0'; /* Overwrite end_char with string terminator */
return buffer;
}


Related Links :

Program to representing a length Using a structure



#include
#include

#define INCHES_PER_FOOT 12
#define FEET_PER_YARD 3

struct Length
{
unsigned int yards;
unsigned int feet;
unsigned int inches;
};

struct Length add(struct Length first, struct Length second);
void show(struct Length length);

int main(void)
{
char answer = 'n';
struct Length length;
struct Length total = { 0,0,0};
int i = 0;
do
{
printf("Enter a length in yards, feet, and inches: ");
scanf(" %d %d %d", &length.yards, &length.feet, &length.inches);
total = add(total,length);
printf("Do you want to enter another(y or n)?: ");
scanf(" %c", &answer);
fflush(stdin);
}while(tolower(answer) == 'y');
printf("The total of all the lengths is: ");
show(total);
printf("\n");
return 0;
}

struct Length add(struct Length first, struct Length second)
{
unsigned long inches = 0;
struct Length sum;
inches = first.inches + second.inches+
INCHES_PER_FOOT*(first.feet+second.feet+FEET_PER_YARD*(first.yards+second.yards));
sum.inches = inches%INCHES_PER_FOOT;
sum.feet = inches/INCHES_PER_FOOT;
sum.yards = sum.feet/FEET_PER_YARD;
sum.feet %= FEET_PER_YARD;
return sum;
}

void show(struct Length length)
{
printf("%d yards %d feet %d inches", length.yards,length.feet, length.inches);
}

Related Links :

Using structure representing a person's name from given array.


#include
#include
#include
#include

#define FIRST_NAME_LEN 31
#define SECOND_NAME_LEN 51
#define NUMBER_LEN 16
#define MAX_NUMBERS 50


/* Structure defining a name */
struct Name
{
char firstname[FIRST_NAME_LEN];
char secondname[SECOND_NAME_LEN];
};

/* Structure defining a phone record */
struct PhoneRecord
{
struct Name name;
char number[NUMBER_LEN];
};

/* Function prototypes */
void show(struct PhoneRecord record); /* Output a phone record */
bool has_name(struct PhoneRecord record, struct Name name); /* Test for a name */
struct Name read_name(); /* Read a name from the keyboard */

int main(void)
{
char answer = 'n';
struct PhoneRecord records[MAX_NUMBERS]; /* Array of phone records */
struct Name aName; /* Stores a name */
int count = 0; /* Number of phone records */
bool found = false; /* Records when a name has been found */

/* Read an arbitrary number of phone records from the keyboard */
do
{
records[count].name = read_name(); /* Read the name */
printf("Enter the number for this name: ");
scanf(" %[ 0123456789]",records[count++].number); /* Read the number - including spaces */

printf("Do you want to enter another(y or n)?: ");
scanf(" %c", &answer);
}while(count<=MAX_NUMBERS && tolower(answer) == 'y');

/* Search the array of phone records for a number */
do
{
printf("Enter a name for which you want the number.");
aName = read_name();
for(int i = 0 ; i {
if(has_name(records[i], aName)) /* Test for the name */
{
if(!found) /* If this is the first time */
{
found = true; /* Reset found flag */
printf("The numbers for this name are:\n"); /* and output the heading */
}
printf("%s\n", records[i].number); /* Output the number for the name */
}
}
if(found) /* If the name was found */
found = false; /* Reset the found flag */
else /* Otherwise output message */
printf("No numbers found for this name.\n");
printf("Do you want to search for another (y or n)? ");
scanf(" %c" , &answer);
}while(tolower(answer) == 'y');

for(int i = 0 ; i show(records[i]);
printf("\n");
return 0;
}

/* Function to output a record */
void show(struct PhoneRecord record)
{
printf("\n%s %s %s", record.name.firstname,record.name.secondname, record.number);
}

/* Function to test whether the name is the same as in a record */
bool has_name(struct PhoneRecord record, struct Name name)
{
return (strcmp(name.firstname, record.name.firstname)==0 && strcmp(name.secondname, record.name.secondname) == 0);
}

/* Function to read a name and store it in a Name structure */
struct Name read_name()
{
struct Name name;
printf("Enter a first name: ");
scanf(" %s", &name.firstname);
printf("Enter a second name: ");
scanf(" %s", &name.secondname);
return name;
}




Related Links :

Using a linked list of structures representing a person's name.


#include
#include
#include
#include
#include

#define FIRST_NAME_LEN 31
#define SECOND_NAME_LEN 51
#define NUMBER_LEN 16


/* Structure defining a name */
struct Name
{
char firstname[FIRST_NAME_LEN];
char secondname[SECOND_NAME_LEN];
};

/* Structure defining a phone record */
struct PhoneRecord
{
struct Name name;
char number[NUMBER_LEN];
};

/* Structure defining a node in a linked list of PhoneRecord structures */
struct Node
{
struct PhoneRecord *pRecord; /* Pointer to a PhoneRecord structure */
struct Node *pNext; /* Pointer to the next node in the list */
};

struct Name read_name(); /* Read a name from the keyboard */
void show(struct PhoneRecord *pRecord); /* Output a phone record */
bool has_name(struct PhoneRecord record, struct Name name); /* Test for a name */
struct Node* create_node(); /* Create a new list node */
struct PhoneRecord* create_record(); /* Create a new phone record */
void insert_node(struct Node *pNode); /* Insert a node in the list */
int compare_records(struct PhoneRecord *pFirst, struct PhoneRecord *pSecond); /* Compare records */
int compare_names(struct Name first, struct Name second); /* Compare two names */
void list_numbers(struct Name name); /* List all numbers for a Name structure */

struct Node *pStart = NULL;

int main(void)
{
char answer = 'n';
struct Node *pNode = NULL; /* Pointer to a list node */
struct PhoneRecord *pRecord = NULL; /* Pointer to a PhoneRecord structure */
bool found = false; /* Records when a name has been found */

/* Read an arbitrary number of phone records from the keyboard */
do
{
insert_node(create_node()); /* Create and insert new node */

printf("Do you want to enter another(y or n)?: ");
scanf(" %c", &answer);
}while(tolower(answer) == 'y');

/* Search the list of phone records for a number */
do
{
printf("\nEnter a name for which you want the number.");
list_numbers(read_name());
printf("Do you want to search for another (y or n)? ");
scanf(" %c" , &answer);
}while(tolower(answer) == 'y');

/* List all the records in the linked list */
pNode = pStart;
do
{
show(pNode->pRecord);
}while((pNode = pNode->pNext) != 0);
printf("\n");

/* Don't forget to free the memory! */
pNode = pStart;
do
{
free(pNode->pRecord); /* Free memory for the record from the current node */
pStart = pNode; /* Save current node address */
pNode = pNode->pNext; /* Get next node address */
free(pStart); /* Free memory for the current node */
}while((pNode = pNode->pNext) != 0);

return 0;
}

/* Read a name from the keyboard and store in a structure */
struct Name read_name()
{
unsigned long inches = 0;
struct Name name;
printf("\nEnter a first name: ");
scanf(" %s", &name.firstname);
printf("Enter a second name: ");
scanf(" %s", &name.secondname);
return name;
}

/* Output a record */
void show(struct PhoneRecord *pRecord)
{
printf("\n%s %s %s", pRecord->name.firstname, pRecord->name.secondname, pRecord->number);
}

bool has_name(struct PhoneRecord record, struct Name name)
{
return (strcmp(name.firstname, record.name.firstname)==0 && strcmp(name.secondname, record.name.secondname)==0);
}

/* Create a new list node */
struct Node* create_node()
{
struct Node *pNode = NULL; /* Pointer to the new node */
pNode = (struct Node*)malloc(sizeof(struct Node)); /* Allocate memory for node */
pNode->pNext = NULL; /* No next node yet */
pNode->pRecord = create_record(); /* Create record and store address in node */
return pNode;
}

/* Create a new phone record */
struct PhoneRecord* create_record()
{
struct PhoneRecord *pRecord = NULL; /* Pointer to the new record */
pRecord = (struct PhoneRecord*)malloc(sizeof(struct PhoneRecord)); /* Allocate memory */
pRecord->name = read_name(); /* Read the name */

/* Get the number for the name */
printf("Enter the number for this name: ");
scanf(" %[ 0123456789]",pRecord->number); /* Read the number - including spaces */
return pRecord; /* Return the address of the record */
}

/*
Compare two PhoneRecord structures
Returns -1 if the name for the first is <> name for the second
*/
int compare_records(struct PhoneRecord *pFirst, struct PhoneRecord *pSecond)
{
return compare_names(pFirst->name, pSecond->name);
}

/* Compare two names
Returns -1 if the first is <> the second

The comparison is by second name. If second names are equal,
first names are compared.
*/
int compare_names(struct Name first, struct Name second)
{
int result = 0;
result = strcmp(first.secondname,second.secondname);
return (result != 0 ? result : strcmp(first.firstname,second.firstname));
}

/* Insert a node into the list */
void insert_node(struct Node *pNode)
{
struct Node *pCurrent = NULL;
struct Node *pPrevious = NULL;
struct Node *pTemp = NULL;

/* Check for empty list */
if(!pStart)
{
pStart = pNode; /* Store address of the node as the start node */
return;
}

/* Find position to insert the new node */
pCurrent = pStart;
while(pCurrent)
{
if(compare_records(pNode->pRecord, pCurrent->pRecord) <= 0) { /* New node goes before current list node */ pNode->pNext = pCurrent; /* Set new node next pointer to current */
if(!pPrevious) /* If pCurrent is the first node */
{
pNode->pNext = pStart; /* New node next pointer points to current */
pStart = pNode; /* New node is the first node */
}
else
{ /* Otherwise... */
pPrevious->pNext = pNode; /* Previous node next pointer points to new node */
pNode->pNext = pCurrent; /* New node next pointer points to current */
}
return;
}
pPrevious = pCurrent; /* Previous node will be the current node */
pCurrent = pCurrent->pNext; /* Current node is now the next node */
}
/* If we reach here, add pNode to the end */
pPrevious->pNext = pNode;
}

/* List the numbers for a name */
void list_numbers(struct Name name)
{
struct Node *pNode = NULL;
bool found = false;
int result = 0;

/* Go through the list comparing names */
pNode = pStart;
while(pNode)
{
result = compare_names(name, pNode->pRecord->name);
if(result == 0)
{
if(!found) /* If this is the first time */
{
found = true; /* Reset found flag */
printf("The numbers for this name are:\n"); /* and output the heading */
}
printf("%s\n", pNode->pRecord->number); /* Output the number for the name */
}
else if(result < pnode =" pNode-">pNext; /* Otherwise move to next node */
}

if(!found) /* If the name was not found */
printf("No numbers found for this name.\n"); /* Say so */
}


Related Links :

Program on inserting new node at first location of linked list in C

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

struct link
{
int info;
struct link *next;
};
int i;
int number;
struct link *p, *new1;

void create(struct link *n)
{
char ch;
p=n;
printf("\n Enter choice ‘n’ for break: ");
ch = getche();
i = 1;
while(ch != 'n')
{
p->next = (struct link* ) malloc(sizeof(struct link));
p = p->next;
printf("\n Input the node: %d: ", (i+1));
scanf("%d", &p->info);
p->next = NULL;
printf("\n Input choice n for break: ");
ch = getche();
i++;
}
}
struct tag *insertion(struct link *n)
{
p=n;
new1 = (struct link* ) malloc(sizeof(struct link));
printf("\n Input the fisrt node value: ");
scanf("%d", &new1->info);
new1->next=p;
return new1;
}
void display(struct link *n)
{

p=n;
printf("\nNow displaying the current linked list:-\n");
while(p)
{
printf("%d\n",p->info);
p=p->next;
}
}



void main()
{
struct link *list;
clrscr();
list = (struct link *) malloc(sizeof(struct link));
printf("\nEnter the value :-");
scanf("%d",&list->info);
list->next=NULL;
create(list);
list=insertion(list);
display(list);
getch();
}

Related Links :

Program on inserting new node at first location of linked list in C


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

struct link
{
int info;
struct link *next;
};
int i;
int number;
struct link *p, *new1;

void create(struct link *n)
{
char ch;
p=n;
printf("\n Enter choice ‘n’ for break: ");
ch = getche();
i = 1;
while(ch != 'n')
{
p->next = (struct link* ) malloc(sizeof(struct link));
p = p->next;
printf("\n Input the node: %d: ", (i+1));
scanf("%d", &p->info);
p->next = NULL;
printf("\n Input choice n for break: ");
ch = getche();
i++;
}
}
struct tag *insertion(struct link *n)
{
p=n;
new1 = (struct link* ) malloc(sizeof(struct link));
printf("\n Input the fisrt node value: ");
scanf("%d", &new1->info);
new1->next=p;
return new1;
}
void display(struct link *n)
{

p=n;
printf("\nNow displaying the current linked list:-\n");
while(p)
{
printf("%d\n",p->info);
p=p->next;
}
}



void main()
{
struct link *list;
clrscr();
list = (struct link *) malloc(sizeof(struct link));
printf("\nEnter the value :-");
scanf("%d",&list->info);
list->next=NULL;
create(list);
list=insertion(list);
display(list);
getch();
}

Related Links :

Writing a binary file with an update mode (Append File) In C


#include
#include
#include
#include

const int MAXLEN = 30; /* Size of name buffer */

void listfile(char *filename); /* List the file contents */

int main(void)
{
const char *filename = "C:\\temp\\mydata.bin";
char name[MAXLEN]; /* Stores a name */
size_t length = 0; /* Length of a name */
int age = 0; /* Person's age */
char answer = 'y';

FILE *pFile = fopen(filename, "wb+");

do
{
fflush(stdin); /* Remove whitespace */

printf("\nEnter a name less than %d characters:", MAXLEN);
gets(name); /* Read the name */

printf("Enter the age of %s: ", name);
scanf(" %d", &age); /* Read the age */

/* Write the name & age to file */
length = strlen(name); /* Get name length */
fwrite(&length, sizeof(length), 1, pFile); /* Write name length */
fwrite(name, sizeof(char), length, pFile); /* then the name */
fwrite(&age, sizeof(age), 1, pFile); /* then the age */

printf("Do you want to enter another(y or n)? " );
scanf("\n%c", &answer);
} while(tolower(answer) == 'y');

fclose(pFile); /* Close the file */

listfile(filename); /* List the contents */
return 0;
}

/* List the contents of the binary file */
void listfile(char *filename)
{
size_t length = 0; /* Name length */
char name[MAXLEN]; /* Stores a name */
int age = 0;
char format[20]; /* Format string */

/* Create the format string for names up to MAXLEN long */
sprintf(format, "\n%%-%ds Age:%%4d", MAXLEN);

FILE *pFile = fopen(filename, "rb"); /* Open to read */
printf("\nThe contents of %s are:", filename);

/* Read records as long as we read a length value */
while(fread(&length, sizeof(length), 1, pFile) == 1)
{
if(length+1>MAXLEN)
{
printf("\nName too long.");
exit(1);
}
fread(name, sizeof(char), length, pFile); /* Read the name */
name[length] = '\0'; /* Append terminator */
fread(&age, sizeof(age), 1, pFile); /* Read the age */
printf(format, name, age); /* Output the record */
}
fclose(pFile);
}



Related Links :

Writing, reading and updating a binary file in C



#include
#include
#include
#include
#include
const int MAXLEN = 30; /* Size of name buffer */
const char *dirpath = "C:\\temp\\"; /* Directory path for file */
const char *file = "mydata.bin"; /* File name */
/* Structure encapsulating a name and age */
struct Record
{
char name[MAXLEN];
int age;
};
void listfile(char *filename); /* List the file contents */
void updatefile(char *filename); /* Update the file contents */
struct Record *getrecord(struct Record *precord); /* Read a record from stdin */
void getname(char *pname); /* Read a name from stdin */
void writefile(char *filename, char *mode); /* Write records to a file */
void writerecord(struct Record *precord, FILE *pFile);
struct Record * readrecord(struct Record *precord, FILE *pFile);
int findrecord(struct Record *precord, FILE *pFile);
void duplicatefile(struct Record *pnewrecord,
int index, char *filename, FILE *pFile);

int main(void)
{
char filename[strlen(dirpath)+strlen(file)+1]; /* Stores file path */
strcpy(filename, dirpath); /* Copy directory path */
strcat(filename, file); /* and append file name */
/* Choose activity option */
char answer = 'q';
while(true)
{
printf("\nChoose from the following options:"
"\nTo list the file contents enter L"
"\nTo create a new file enter C"
"\nTo add new records enter A"
"\nTo update existing records enter U"
"\nTo delete the file enter D"
"\nTo end the program enter Q\n : ");
scanf("\n%c", &answer);

switch(tolower(answer))
{
case 'l': /* List file contents */
listfile(filename);
break;
case 'c': /* Create new file */
writefile(filename,"wb+");
printf("\nFile creation complete.");
break;
case 'a': /* Append records */
writefile(filename, "ab+");
printf("\nFile append complete.");
break;
case 'u': /* Update existing records */
updatefile(filename);
break;
case 'd':
printf("Are you sure you want to delete %s (y or n)? ", filename);
scanf("\n%c", &answer);
if(tolower(answer) == 'y')
remove(filename);
break;
case 'q': /* Quit the program */
printf("\nEnding the program.", filename);
return 0;
default:
printf("Invalid selection. Try again.");
break;
}
}
return 0;
}

/* Read the name and age for a record from the keyboard */
struct Record *getrecord(struct Record *precord)
{
/* Verify the argument is good */
if(!precord)
{
printf("No Record object to store input.");
return NULL;
}

printf("\nEnter a name less than %d characters:", MAXLEN);
getname(precord->name); /* readf the name */

printf("Enter the age of %s: ", precord->name);
scanf(" %d", &precord->age); /* Read the age */
return precord;
}

/* Read a name from the keyboard */
void getname(char *pname)
{
fflush(stdin);
fgets(pname, MAXLEN, stdin); /* Read the name */
int len = strlen(pname);
if(pname[len-1] == '\n') /* if there's a newline */
pname[len-1] = '\0'; /* overwrite it */
}

/* Write a new record to the file at the current position */
void writerecord(struct Record *precord, FILE *pFile)
{
/* Verify the arguments are good */
if(!precord)
{
printf("No Record object to write to the file.");
return;
}
if(!pFile)
{
printf("No stream pointer for the output file.");
return;
}

/* Write the name & age to file */
size_t length = strlen(precord->name); /* Get name length */
fwrite(&length, sizeof(length), 1, pFile); /* Write name length */
fwrite(precord->name, sizeof(char), length, pFile); /* then the name */
fwrite(&precord->age, sizeof(precord->age), 1, pFile); /* then the age */
}

/* Reads a record from the file at the current position */
struct Record * readrecord(struct Record *precord, FILE *pFile)
{
/* Verify the arguments are good */
if(!precord)
{
printf("No Record object to store data from the file.");
return NULL;
}
if(!pFile)
{
printf("No stream pointer for the input file.");
return NULL;
}

size_t length = 0; /* Name length */
fread(&length, sizeof(length), 1, pFile); /* Read the length */
if(feof(pFile)) /* If it's end file */
return NULL; /* return NULL */

/* Verify the name can be accommodated */
if(length+1>MAXLEN)
{
fprintf(stderr, "\nName too long. Ending program.");
exit(1);
}

fread(precord->name, sizeof(char), length, pFile); /* Read the name */
precord->name[length] = '\0'; /* Append terminator */
fread(&precord->age, sizeof(precord->age), 1, pFile); /* Read the age */

return precord;
}

/* Write to a file */
void writefile(char *filename, char *mode)
{
char answer = 'y';

FILE *pFile = fopen(filename, mode); /* Open the file */
if(pFile == NULL) /* Verify file is open */
{
fprintf(stderr, "\n File open failed.");
exit(1);
}

do
{
struct Record record; /* Stores a record name & age */

writerecord(getrecord(&record), pFile); /* Get record & write the file */

printf("Do you want to enter another(y or n)? " );
scanf("\n%c", &answer);
fflush(stdin); /* Remove whitespace */
} while(tolower(answer) == 'y');

fclose(pFile); /* Close the file */
}

/* List the contents of the binary file */
void listfile(char *filename)
{
/* Create the format string for names up to MAXLEN long */
/* format array length allows up to 5 digits for MAXLEN */
char format[15]; /* Format string */
sprintf(format, "\n%%-%ds Age:%%4d", MAXLEN);

FILE *pFile = fopen(filename, "rb"); /* Open file to read */
if(pFile == NULL) /* Check file is open */
{
printf("Unable to open %s. Verify it exists.\n", filename);
return;
}

struct Record record; /* Stores a record */
printf("\nThe contents of %s are:", filename);

while(readrecord(&record, pFile) != NULL) /* As long as we have records */
printf(format, record.name, record.age); /* Output the record */

printf("\n"); /* Move to next line */

fclose(pFile); /* Close the file */
}

/* Modify existing records in the file */
void updatefile(char *filename)
{ char answer = 'y';

FILE *pFile = fopen(filename, "rb+"); /* Open the file for update */
if(pFile == NULL) /* Check file is open */
{
fprintf(stderr, "\n File open for updating records failed.");
return;
}

struct Record record; /* Stores a record */
int index = findrecord(&record, pFile); /* Find the record for a name */
if(index<0) /* If the record isn't there */
{
printf("\nRecord not found."); /* ouput a message */
return; /* and we are done. */
}

printf("\n%s is aged %d,", record.name, record.age);
struct Record newrecord; /* Stores replacement record */
printf("\nYou can now enter the new name and age for %s.", record.name);
getrecord(&newrecord); /* Get the new record */

/* Check if we can update in place */
if((strlen(record.name) == strlen(newrecord.name)))
{ /* Name lengths are the same so we can */
/* Move to start of old record */
fseek(pFile,
-(long)(sizeof(size_t)+strlen(record.name)+sizeof(record.age)),
SEEK_CUR);

writerecord(&newrecord, pFile); /* Write the new record */
fflush(pFile); /* Force the write */
}
else
duplicatefile(&newrecord, index, filename, pFile);

printf("File update complete.\n");
}

/* Duplicate the existing file replacing the record to be update */
/* The record to be replaced is index records from the start */
void duplicatefile(struct Record *pnewrecord, int index, char *filename, FILE *pFile)
{
/* Create and open a new file */
char tempname[L_tmpnam];
if(tmpnam(tempname) == NULL)
{
printf("\nTemporary file name creation failed.");
return;
}
char tempfile[strlen(dirpath)+strlen(tempname)+1];
strcpy(tempfile, dirpath); /* Copy original file path */
strcat(tempfile, tempname); /* Append temporary name */
FILE *ptempfile = fopen(tempfile, "wb+");

/* Copy first index records from old file to new file */
rewind(pFile); /* Old file back to start */
struct Record record; /* Store for a record */
for(int i = 0 ; i writerecord(readrecord(&record, pFile), ptempfile);


writerecord(pnewrecord, ptempfile); /* Write the new record */
readrecord(&record,pFile); /* Skip the old record */

/* Copy the rest of the old file to the new file */
while(readrecord(&record,pFile))
writerecord(&record, ptempfile);

/* close the files */
if(fclose(pFile)==EOF)
printf("\n Failed to close %s", filename);
if(fclose(ptempfile)==EOF)
printf("\n Failed to close %s", tempfile);

if(remove(filename)) /* Delete the old file */
{
printf("\nRemoving the old file failed. Check file in %s", dirpath);
return;
}

/* Rename the new file same as original */
if(rename(tempfile, filename))
printf("\nRenaming the file copy failed. Check file in %s", dirpath);
}

/* Find a record */
/* Returns the index number of the record */
/* or -1 if the record is not found. */
int findrecord(struct Record *precord, FILE *pFile)
{
char name[MAXLEN];
printf("\nEnter the name for the record you wish to find: ");
getname(name);

rewind(pFile); /* Make sure we are at the start */
int index = 0; /* Index of current record */

while(true)
{
readrecord(precord, pFile);
if(feof(pFile)) /* If end-of-file was reached */
return -1; /* record not found */
if(!strcmp(name, precord->name))
break;
++index;
}
return index; /* Return record index */
}


Related Links :


If you face any Problem in viewing code such as Incomplete "For Loops" or "Incorrect greater than or smaller" than equal to signs then please collect from My Web Site CLICK HERE


More Useful Topics...

 

History Of C..

In the beginning was Charles Babbage and his Analytical Engine, a machine
he built in 1822 that could be programmed to carry out different computations.
Move forward more than 100 years, where the U.S. government in
1942 used concepts from Babbage’s engine to create the ENIAC, the first
modern computer.
Meanwhile, over at the AT&T Bell Labs, in 1972 Dennis Ritchie was working
with two languages: B (for Bell) and BCPL (Basic Combined Programming
Language). Inspired by Pascal, Mr. Ritchie developed the C programming
language.

My 1st Program...


#include
#include
void main ()
{
clrscr ();
printf ("\n\n\n\n");
printf ("\t\t\t*******Pankaj *******\n");
printf ("\t\t\t********************************\n");
printf ("\t\t\t\"Life is Good...\"\n");
printf ("\t\t\t********************************");
getch ();
}

Next Step...


#include
#include

void main ()
{
clrscr ();
printf ("\n\n\n\n\n\n\n\n");
printf ("\t\t\t --------------------------- \n\n");

printf ("\t\t\t | IGCT, Info Computers, INDIA | \n\n");
printf ("\t\t\t --------------------------- ");

getch ();

}

Hits!!!