Monday, November 30, 2009

Chap 13[B](a) Reverse words in text file

Write a program to carry out the following:
(a) Read a text file provided at command prompt
(b) Print each word in reverse order
For example if the file contains
INDIA IS MY COUNTRY
Output should be
AIDNI SI YM YRTNUOC


How to use:
1) Compile the below program to obtain .exe file.
2) In turbo C press F9 to compile and go to C:\TC\BIN to find your .exe file
3) Rename your.exe file to any name for example reverse.exe.
4) In the folder where reverse.exe is, create a text file (e.g test.txt) and input any text in it.
5) For vista, in the same folder hold shift and right click anywhere in the folder and click open command prompt here.
6) Then in command prompt type :
reverse test.txt test2.txt
7)The reversed text is found in test2.txt.




#include "stdio.h"
void main(int argc,char *argv[])
{
int i,j,f=1;
FILE *fs,*ft;
char ch,word[25],word2[25];

if(argc!=3)
{
puts("Improper number of arguments");
exit();
}

fs=fopen(argv[1],"r");
if(fs==NULL)
{
puts("\nCannot open source file");
exit();
}

ft=fopen(argv[2],"w");

while(1)
{
word2[0]='\0';
word[0]='\0';
for(i=0;;i++)
{
ch=fgetc(fs);
if(ch==EOF)
{
f=0;
break;
}
if(ch==32)
{
f=2;
break;
}
if(ch==44)
{
f=3;
break;
}
if(ch==46)
{
f=4;
break;
}
if(ch=='\n')
{
f=5;
break;
}
word[i]=ch;

}
word[i]='\0';
for(j=0,i-=1;i>=0;i--,j++)
word2[j]=word[i];

word2[j]='\0';
fputs(word2,ft);
if(f==2)
fputc(32,ft);
if(f==3)
fputc(44,ft);
if(f==4)
fputc(46,ft);
if(f==5)
fputc('\n',ft);
if(f==0)
break;
}
fclose(fs);
fclose(ft);
}

Sunday, November 15, 2009

Chap12[C]j Sort data in file according to date

There are 100 records present in a file with the following structure:
struct date
{
int d, m, y ;
} ;
struct employee
{ int empcode[6] ;
char empname[20] ;
struct date join_date ;
float salary ;
} ;
Write a program to read these records, arrange them in ascending order of join_date and write them in to a target file.


#include "stdio.h"
struct date
{
int d,m,y;
};
struct employee
{
int empcode;
char empname[20];
struct date da;
float salary;
};

void main()
{
int choice;
char another,another2;
FILE *fs;
struct employee e;
fs=fopen("c:\\ctxt\\join.txt","a+");
while(1)
{
clrscr();
printf("1) Input new employee data");
printf("\n2) Sort employee data");
printf("\n3) Exit");
printf("\n\nKey in your choice(1,2 or 3)\n");
scanf("%d",&choice);

switch(choice)
{
case 1:
while(1)
{
clrscr();
printf("\nKey in employee's code\n");
scanf("%d",&e.empcode);
printf("\nKey in employee's name\n");
scanf("%s",e.empname);
printf("\nKey in year that employee joined\n");
scanf("%d",&e.da.y);
printf("\nKey in month that employee joined\n");
scanf("%d",&e.da.m);
printf("\nKey in day that employee joined\n");
scanf("%d",&e.da.d);
printf("\nKey in salary of employee\n");
scanf("%f",&e.salary);
fprintf(fs,"%d %s %d %d %d %f\n",e.empcode,e.empname,e.da.y,e.da.m,e.da.d,e.salary);
printf("\nDo you want to key in another data?(y/n)\n");
fflush(stdin);
another=getche();
if(another!='y')
break;
}
break;

case 2:
funcsort(fs);
break;

case 3:
fclose(fs);
exit();
}
}
}

funcsort(FILE *fs)
{
int i,j,flag=0,count=0;
struct employee temp1,temp2;
struct employee e1[1000];
char ch;
FILE *fp;
fp=fopen("c:\\ctxt\\join2.txt","w");
rewind(fs);
for(i=0;i<1000;i++)
{
if(flag==0)
{
ch=fscanf(fs,"%d%s%d%d%d%f",&e1[i].empcode,e1[i].empname,&e1[i].da.y,&e1[i].da.m,&e1[i].da.d,&e1[i].salary);
count++;
if(ch==EOF)
flag=1;
}
if(flag==1)
{
e1[i].empname[0]='\0';
}
}
for(i=0;e1[i].empname[0]!=0;i++)
{
for(j=i+1;j {
if(e1[i].da.y>e1[j].da.y)
{
temp1=e1[i];
temp2=e1[j];
e1[i]=temp2;
e1[j]=temp1;
}
else if((e1[i].da.y==e1[j].da.y)&&(e1[i].da.m==e1[j].da.m))
{
if(e1[i].da.d>e1[j].da.d)
{
temp1=e1[i];
temp2=e1[j];
e1[i]=temp2;
e1[j]=temp1;
}
}
else if(e1[i].da.y==e1[j].da.y)
{
if(e1[i].da.m>e1[j].da.m)
{
temp1=e1[i];
temp2=e1[j];
e1[i]=temp2;
e1[j]=temp1;
}
}

}
}

for(i=0;e1[i].empname[0]!=0;i++)
{
fprintf(fp,"%d %s %d %d %d %f\n",e1[i].empcode,e1[i].empname,e1[i].da.y,e1[i].da.m,e1[i].da.d,e1[i].salary);
}
fclose(fp);
fclose(fs);
remove("c:\\ctxt\\join.txt");
rename("c:\\ctxt\\join2.txt","c:\\ctxt\\join.txt");
fs=fopen("c:\\ctxt\\join.txt","a+");
}

Chap12[C]i Updating customer transactions with sorting feature

In the file ‘CUSTOMER.DAT’ there are 100 records with the following structure:
struct customer
{
int accno ;
char name[30] ;
float balance ;
} ;

In another file ‘TRANSACTIONS.DAT’ there are several records with the following structure:
struct trans
{
int accno ;
char trans_type ;
float amount ;
} ;
The parameter trans_type contains D/W indicating deposit or withdrawal of amount. Write a program to update ‘CUSTOMER.DAT’ file, i.e. if the trans_type is ‘D’ then update the balance of ‘CUSTOMER.DAT’ by adding amount to balance for the corresponding accno. Similarly, if trans_type is ‘W’ then subtract the amount from balance. However, while subtracting the amount make sure that the amount should not get overdrawn, i.e. at least 100 Rs. Should remain in the account.


Create a folder "ctxt" in C drive. In the "ctxt" folder create two text files with name cust.txt and trans.txt.
when option 4 is executed trans.txt get deleted while new transactions can be created with option 5 in program.

#include "stdio.h"
struct customer
{
int accno;
char name[30];
float balance;
};

struct trans
{
int accno;
char trans_type[1];
float amount;
};

void main()
{
char another,name1[30];
FILE *fs,*ft,*ftemp;
struct customer c;
struct trans t;
int choice,no,f2,no2,counter;
long pos1,pos2,pos3;
fs=fopen("c:\\ctxt\\cust.txt","r+");

if(fs==NULL)
{
puts("Cannot open file");
exit();
}

while(1)
{
clrscr();
printf("1)List Customer Data");
printf("\n2)Add Customer Data");
printf("\n3)Remove Customer Data");
printf("\n4)Update Customer Data from transactions");
printf("\n5)Perform transactions");
printf("\n6)Exit\n");
scanf("%d",&choice);
rewind(fs);

switch(choice)
{
case 1:

another='y';
clrscr();
while(fscanf(fs,"%d%s%f",&c.accno,c.name,&c.balance)!=EOF)
printf("\nAccount no: %3d Name: %-20s Balance: %.1f",c.accno,c.name,c.balance);
while(1)
{
printf("\n\nHit enter to escape");
fflush(stdin);
another=getche();
if(another!='y')
break;
}
break;

case 2:

clrscr();
another='y';
no=1;
funcsort(fs);
while(1)
{

f2=0;

for(no=1;fscanf(fs,"%d%s%f",&c.accno,c.name,&c.balance)!=EOF;no++)
{
if(f2==0)
{
if(c.accno!=no)
{
no2=no;
f2=1;
}

}

}
printf("\nKey in Customer name\n");
scanf("%s",c.name);
printf("\nKey in balance\n");
scanf("%f",&c.balance);
if(f2==1)
{
fprintf(fs,"%d %s %f\n",no2,c.name,c.balance);
}
else
{
fprintf(fs,"%d %s %f\n",no,c.name,c.balance);
no++;
}
funcsort(fs);
printf("\nAdd another customer Data(y/n)?\n");
fflush(stdin);
another=getche();
if(another!='y')
break;
}
break;

case 3:

another='y';
clrscr();

while(1)
{
ftemp=fopen("c:\\ctxt\\cust2.txt","w");
printf("\nKey in name to delete\n");
scanf("%s",name1);
while(fscanf(fs,"%d%s%f",&c.accno,c.name,&c.balance)!=EOF)
{
if(strcmp(c.name,name1)!=0)
fprintf(ftemp,"%d %s %f\n",c.accno,c.name,c.balance);
}
fclose(fs);
fclose(ftemp);
remove("c:\\ctxt\\cust.txt");
rename("c:\\ctxt\\cust2.txt","c:\\ctxt\\cust.txt");
printf("\nDelete another data?(y/n)\n");
fflush(stdin);
fs=fopen("c:\\ctxt\\cust.txt","r+");
another=getche();
if(another!='y')
break;
}
break;

case 4:

clrscr();
ft=fopen("c:\\ctxt\\trans.txt","r");
if(ft==NULL)
{
puts("No active transactions");
exit();
}
while(fscanf(ft,"%d%s%f",&t.accno,t.trans_type,&t.amount)!=EOF)
{
counter=0;
pos1=0;
rewind(fs);
while(fscanf(fs,"%d%s%f",&c.accno,c.name,&c.balance)!=EOF)
{
counter++;
pos2=pos1;
pos1=ftell(fs);
pos3=pos1-pos2;
if(t.accno==c.accno)
{
if(t.trans_type[0]=='w')
{
c.balance-=t.amount;
if(c.balance<100)
{
c.balance+=t.amount;
printf("\nTransaction for account no: %d not processed due to insufficient funds");
}
}
if(t.trans_type[0]=='d')
{
c.balance+=t.amount;

}
if(counter==1)
fseek(fs,-(pos3),SEEK_CUR);
if(counter>1)
fseek(fs,-(pos3-2),SEEK_CUR);
fprintf(fs,"%d %s %f\n",c.accno,c.name,c.balance);
counter=1;
}

}
}
fclose(ft);
remove("c:\\ctxt\\trans.txt");
break;

case 5:

clrscr();
another='y';
ft=fopen("c:\\ctxt\\trans.txt","a+");
if(ft==NULL)
{
puts("Cannot open file");
break;
}
while(1)
{
printf("\nKey in acc no.\n");
scanf("%d",&t.accno);
printf("\nWithdraw (w) or Deposit (d)\n");
scanf("%s",t.trans_type);
printf("\nKey in amount\n");
scanf("%f",&t.amount);
fprintf(ft,"%-3d %s %-6.2f\n",t.accno,t.trans_type,t.amount);
printf("\nDo you want to key another transaction(y/n)?\n");
fflush(stdin);
another=getche();
if(another!='y')
break;
}
fclose(ft);
break;

case 6:

fclose(fs);
exit();

}
}
fclose(fs);
}

funcsort(FILE *fp)
{
char ch;
int flag=0,i,j,count;
struct customer a[1000],temp1,temp2;
FILE *ftemp;
rewind(fp);
ftemp=fopen("c:\\ctxt\\cust2.txt","w");
for(i=0,count=0;i<1000;i++)
{
if(flag==0)
{
ch=fscanf(fp,"%d%s%f",&a[i].accno,a[i].name,&a[i].balance);
count++;
if(ch==EOF)
{
flag=1;
}
}
if(flag==1)
{
a[i].name[0]=0;
}
}

for(i=0;a[i].name[0]!=0;i++)
{
for(j=i+1;j<(count-1);j++)
{
if(a[i].accno>a[j].accno)
{
temp1=a[i];
temp2=a[j];
a[i]=temp2;
a[j]=temp1;
}
}
}

for(i=0;a[i].name[0]!=0;i++)
{
fprintf(ftemp,"%d %s %f\n",a[i].accno,a[i].name,a[i].balance);
}
fclose(fp);
fclose(ftemp);
remove("c:\\ctxt\\cust.txt");
rename("c:\\ctxt\\cust2.txt","c:\\ctxt\\cust.txt");
fp=fopen("c:\\ctxt\\cust.txt","r+");
}

Chap12[C]h Encrypting/Decrypting file

Write a program to encrypt/decrypt a file using:
An offset cipher: In an offset cipher each character from the source file is offset with a fixed value and then written to the target file. For example, if character read from the source file is ‘A’, then convert this into a new character by offsetting ‘A’ by a fixed value, say 128, and then writing the new character to the target file.


Program to encrypt file

#include "stdio.h"
void main()
{
FILE *fp,*ft;
char ch;

fp=fopen("c:\\ctxt\\cipher.txt","r");
if(fp==NULL)
{
puts("Cannot open file");
exit();
}
ft=fopen("c:\\ctxt\\cipher2.txt","w");
if(ft==NULL)
{
puts("Cannot open file");
exit();
}

while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
ch+=128;
fputc(ch,ft);
};
fclose(fp);
fclose(ft);
remove("c:\\ctxt\\cipher.txt");
rename("c:\\ctxt\\cipher2.txt","c:\\ctxt\\cipher.txt");
}

Program to decrypt the same file


#include "stdio.h"
void main()
{
FILE *fp,*ft;
char ch;
fp=fopen("c:\\ctxt\\cipher.txt","r");
if(fp==NULL)
{
puts("Cannot open file");
exit();
}
ft=fopen("c:\\ctxt\\cipher2.txt","w");
if(ft==NULL)
{
puts("Cannot open file");
exit();
}
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
ch-=128;
fputc(ch,ft);
};
fclose(fp);
fclose(ft);
remove("c:\\ctxt\\cipher.txt");
rename("c:\\ctxt\\cipher2.txt","c:\\ctxt\\cipher.txt");
}

Saturday, November 14, 2009

Chap12[C]d Sorting to alphabetical order in a file

Suppose a file contains student’s records with each record containing name and age of a student. Write a program to read these records and display them in sorted order by name.

Program to input students name
#include "stdio.h"

void main()
{
char j='y';
FILE *fp;

struct record
{
char name[20];
int age;
};
struct record a;

fp=fopen("c:\\ctxt\\record.txt","a");
if(fp==NULL)
{
puts("Cannot open file");
exit();
}
while(j=='y')
{
printf("\nKey in the name of the student\n");
scanf("%s",a.name);
printf("\nKey in the age of the student\n");
scanf("%d",&a.age);
fprintf(fp,"%s %d\n",a.name,a.age);
printf("\nAdd another record?(Y/N)");
fflush(stdin);
j=getche();
}
fclose(fp);
}

Program to sort students name


#include "stdio.h"
struct record
{
char name[10];
int age;
};
void main()
{
FILE *fp,*ft;

int i,f=1;

struct record a[5000];

clrscr();


fp=fopen("c:\\ctxt\\record.txt","r");
if(fp==NULL)
{
puts("Cannot open file");
exit();
}
for(i=0;i<5000;i++)
{
if(f==1)
{
if((fscanf(fp,"%s%d",a[i].name,&a[i].age)==EOF))
f=0;
}
if(f==0)
a[i].name[0]='\0';

}

funcsort(a,4);

for(i=0;a[i].name[0]!='\0';i++)
printf("\nName is %s. Age is %d",a[i].name,a[i].age);
printf("\nFile sorted according to alphabetical order");

ft=fopen("c:\\ctxt\\record2.txt","w");
for(i=0;a[i].name[0]!=0;i++)
fprintf(ft,"%s %d\n",a[i].name,a[i].age);
fclose(fp);
fclose(ft);
remove("c:\\ctxt\\record.txt");
rename("c:\\ctxt\\record2.txt","c:\\ctxt\\record.txt");

}
/* Function "funcsort()" is in picture below type it in for it to work */

Thursday, November 12, 2009

Chap12[C]g Reading text on console with pages

Write a program to display the contents of a text file on the screen. Make following provisions: Display the contents inside a box drawn with opposite corner co-ordinates being ( 0, 1 ) and ( 79, 23 ). Display the name of the file whose contents are being displayed, and the page numbers in the zeroth row. The moment one screenful of file has been displayed, flash a message ‘Press any key...’ in 24th row. When a key is hit, the next page’s contents should be displayed, and so on till the end of file.

Create a folder called "ctxt" in C drive and create a text file called page.txt in the ctxt folder.
Input lots of words into the page.txt file then run this program.

#include "stdio.h"
#include "dos.h"

void main()
{
void creategrid();
FILE *fp;
char ch,k;
int page=1,i,j,pgno,flag=0,count;


fp=fopen("c:\\ctxt\\page.txt","r");
while(1)
{
count=0;
clrscr();
creategrid();
for(i=3;i<=21&&flag!=1;i++)
{

for(j=4;j<=77&&flag!=1;j++)
{
ch=fgetc(fp);
if(ch==EOF)
{
flag=1;
break;
}
gotoxy(j,i);
printf("%c",ch);
count++;
}
}
gotoxy(38,24);
printf("Page %d",page);
if(page>1)
{
gotoxy(3,24);
printf("Key %c to go to page %d",17,page-1);
}
if(flag!=1)
{
gotoxy(58,24);
printf("Key %c to go to page %d",16,page+1);
}
if(flag==1)
{
gotoxy(66,24);
printf("Key %c to quit",16);
}
while(1)
{
pgno=getkey();
if(flag==1&&pgno==77)
break;
if(page==1&&pgno==75)
continue;

if(pgno==77&&flag!=1)
{
page+=1;
clrscr();
creategrid();
break;
}

if(pgno==75&&page!=1)
{
page-=1;
clrscr();
fseek(fp,-(1413+count),SEEK_CUR);
creategrid();
flag=0;
break;
}
}
if(flag==1&&pgno==77)
break;



}
fclose(fp);
}

getkey()
{
union REGS i,o;
while(!kbhit())
;
i.h.ah=0;
int86(22,&i,&o);
return(o.h.ah);
}

void creategrid()
{
int i;
gotoxy(2,1);
printf("%c",218);
gotoxy(79,1);
printf("%c",191);
gotoxy(2,23);
printf("%c",192);
gotoxy(79,23);
printf("%c",217);

for(i=3;i<=78;i++)
{
gotoxy(i,1);
printf("%c",196);
gotoxy(i,23);
printf("%c",196);
}

for(i=2;i<=22;i++)
{
gotoxy(2,i);
printf("%c",179);
gotoxy(79,i);
printf("%c",179);
}
}

Wednesday, November 11, 2009

Chap12[C]f Merge alternate lines from two files

Write a program that merges lines alternately from two files and writes the results to new file. If one file has less number of lines than the other, the remaining lines from the larger file should be simply copied into the target file.

#include "stdio.h"
void main()
{
FILE *fp,*ft,*fs;
char ch;
int f1=1,f2=1,counter=1;

fp=fopen("c:\\ctxt\\first.txt","r");
ft=fopen("c:\\ctxt\\second.txt","r");
fs=fopen("c:\\ctxt\\combine.txt","w");

while(1)
{
if(counter==1||f2==0)
{
ch=fgetc(fp);
if(ch==EOF)
f1=0;
if(ch=='\n'||ch==46)
counter=2;
if(f1!=0)
fputc(ch,fs);
}

if(counter==2||f1==0)
{
ch=fgetc(ft);
if(ch==EOF)
f2=0;

if(ch=='\n'||ch==46)
counter=1;
if(f2!=0)
fputc(ch,fs);

if(f1==0&&f2==0)
break;
}
}

fclose(fp);
fclose(ft);
fclose(fs);
}

Chap12[C]e Lowercase to uppercase in file

Write a program to copy one file to another. While doing so replace all lowercase characters to their equivalent uppercase characters.

#include "stdio.h"

void main()
{
FILE *fp,*ft;
char ch;

fp=fopen("c:\\ctxt\\txt1.txt","r");
ft=fopen("c:\\ctxt\\txt2.txt","w");

if(fp==NULL)
{
puts("Cannot open file");
exit();
}

if(ft==NULL)
{
puts("Cannot open file");
exit();
}

while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
if(ch>=97&&ch<=122)
ch-=32;
fputc(ch,ft);
}

fclose(fp);
fclose(ft);
}

Chap12[C]c Add contents of file on another

Write a program to add the contents of one file at the end of another.

#include "stdio.h"

void main()
{
FILE *fp,*ft;
char ch,ch2;
int f=0;
fp=fopen("c:\\ctxt\\12cc1.txt","a");
ft=fopen("c:\\ctxt\\12cc2.txt","r");

fprintf(fp,"\n");
while(1)
{

ch=fgetc(ft);
if(ch==EOF)
break;

fputc(ch,fp);


}
fclose(fp);
fclose(ft);
}

Chap12[C]a Read file and display line numbers

Write a program to read a file and display contents with its line numbers.

#include "stdio.h"
void main()
{
FILE *fp;
char ch;
int c=1;
fp=fopen("c:\\ctxt\\12ca.txt","r");
if(fp==NULL)
{
puts("File cannot be opened");
exit();
}
clrscr();
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
if(ch=='\n')
c++;
printf("%c",ch);
}
printf("\nThe number of lines is %d",c);
}

Wednesday, November 4, 2009

Chap10D[h] Creating link list(inserting from front)

Linked list is a very common data structure often used to store similar data in memory. While the elements of an array occupy contiguous memory locations, those of a linked list are not constrained to be stored in adjacent location. The individual elements are stored “somewhere” in memory, rather like a family dispersed, but still bound together. The order of the elements is maintained by explicit links between them. Thus, a linked list is a collection of elements called nodes, each of which stores two item of information—an element of the list, and a link, i.e., a pointer or an address that indicates explicitly the location of the node containing the successor of this list element. Write a program to build a linked list by adding new nodes at the beginning, at the end or in the middle of the linked list. Also write a function display( ) which display all the nodes present in the linked list.

Reference: http://en.wikipedia.org/wiki/Malloc
http://cslibrary.stanford.edu/103/LinkedListBasics.pdf


#include alloc.h (include arrows)
struct list
{
int x;
struct list *next;
};

void main()
{
struct list *newlist();
struct list *a1=newlist();
struct list *current;
int i,k;
char j[1];


for(i=1,current=a1;current!=NULL;current=current->next,i++)
{
printf("\nThe No. %d in the list is %d",i,current->x);
}


while(1)
{
printf("\nEnter a value to key into the No. %d list",i);
scanf("%d",&k);
push(&a1,k);
printf("\nKey q to quit or any other key to continue keying");
scanf("%s",j);
if(j[0]==113)
break;
}

printf("\nThe new list is as below\n");


for(i=1,current=a1;current!=NULL;current=current->next,i++)
{
printf("\nThe No. %d in the list is %d",i,current->x);
}





}

struct list *newlist()
{
struct list *a1;
struct list *a2;
struct list *a3;

a1=malloc(sizeof(struct list));
a2=malloc(sizeof(struct list));
a3=malloc(sizeof(struct list));

a1->x=1;
a1->next=a2;

a2->x=2;
a2->next=a3;

a3->x=3;
a3->next=NULL;

return(a1);
}

push(struct list **head,int g)
{
struct list *nod=malloc(sizeof(struct list));
nod->x=g;
nod->next=*head;
*head=nod;

}

Manipulating Addresses

DIFFERENTIATING BETWEEN CHANGING ADDRESSES AND CHANGING VALUES
















1)For a pointer to an integer

void main()
{
int a=3;
int *b;
b=&a;
func(b);
printf("The output is %d",b);
}

func(int *b)
{
b=b+1;
}

For the above the answer is 4.

2)For this

void main()
{
int a=1,b=2;
int *aa,*bb;
aa=&a;
bb=&b;
printf("\nAddress at aa is %u, Address at bb is %u",aa,bb);

/*Lets say address at a is 001 and b is 002
We create a function to try and swap these addresses so aa has address b and bb has address a*/

fswap(&aa,&bb);
printf("\nValue at aa is %d, Address at aa is %u,\nValue at bb is %d, Address at bb is %u",*aa,aa,*bb,bb);
}

fswap(int **addressaa,int **addressbb)
{
int **tempcc;
*tempcc=*addressaa;
*addressaa=*addressbb;
*addressbb=*tempcc;
}

Sunday, November 1, 2009

Chap10[D]f Creating a library system

Write a menu driven program that depicts the working of a library. The menu options should be:
1. Add book information
2. Display book information
3. List all books of given author
4. List the title of specified book
5. List the count of books in the library
6. List the books in the order of accession number
7. Exit Create a structure called library to hold accession number, title of the book, author name, price of the book, and flag indicating whether book is issued or not.


struct library
{
int num;
char title[20];
char author[20];
float price;
int flag;
};

void main()
{
void accbook(struct library *l,int count);
void addbook(struct library *l,int count);
int count,a,ac;
char key[20],j[1];
struct library l[100]={
{1,"Rabbit","MrR",5.6,1},
{3,"Hamster","MrH",10.1,1},
{2,"Rice","MrR",7.0,0},
{5,"Hamlet","MrH",20.7,0},
{4,"Mouse","MrM",15.3,1}
};
clrscr();

while(1)
{
a=menu();

if(a==1)
{
clrscr();
count=countbook(&l);
addbook(&l,count);
}
if(a==2)
{
clrscr();
displaybook(&l);
}
if(a==3)
{
clrscr();
printf("\nKey in the author's name\n");
scanf("%s",key);
authorbook(&l,key);
}
if(a==4)
{
clrscr();
printf("\nKey in the accession number of the book\n");
scanf("%d",&ac);
specbook2(&l,ac);
}
if(a==5)
{
clrscr();
count=countbook(&l);
printf("\nNumber of books in the library is %d",count);
}
if(a==6)
{
clrscr();
count=countbook(&l);
accbook(&l,count);
displaybook(&l);
}
if(a==7)
exit();
printf("\n\n\nHit q and enter to quit and any other value to go back to menu\n");
scanf("%s",j);
if(j[0]==113)
break;
clrscr();
}
}

menu()
{
int acc;


printf("\n1. Add book information");
printf("\n2. Display book information");
printf("\n3. List all books of given author");
printf("\n4. List the title of specified book (Accession Number)");
printf("\n5. List the count of books in the library");
printf("\n6. Sort the books in order of accession number and display them");
printf("\n7. Exit");
printf("\n\nTo access the menu, key in the corresponding number\n");
while(1)
{
scanf("%d",&acc);
if(acc<1||acc>7)
{
printf("\nYou keyed an invalid value, key again\n");
}
else
break;
}
return(acc);
}

countbook(struct library *l)
{
int i,count=0;

for(i=0;l[i].num!=0;i++)
count++;

return(count);
}

void addbook(struct library *l,int count)
{
char j[1];
int s=0,c=0,i;

while(1)
{
if(count>99)
{
printf("\nLibrary has no more space");
break;
}
s=0;
printf("\nKey in accession number\n");
scanf("%d",&l[count].num);
if(l[count].num==0)
s=1;
for(i=0;i {
if(l[i].num==l[count].num)
{
printf("\nSimilar accession number,Key again\n");

s=1;
}
}
if(s==1)
continue;
printf("\nKey in title (no spacings)\n");
scanf("%s",l[count].title);
printf("\nKey in author (no spacings)\n");
scanf("%s",l[count].author);
printf("\nKey in price\n");
scanf("%f",&l[count].price);

while(1)
{
printf("\nKey 0 if the book is borrowed otherwise key 1 if available\n");
scanf("%d",&l[count].flag);

if(l[count].flag==0||l[count].flag==1)
break;
}

c++;

printf("\nKey any value to continue adding books or key q to quit to menu");
scanf("%s",j);
if(j[0]==113)
break;

clrscr();
count++;
}

if(c==1)
printf("\nYou keyed in 1 new book");

else if (c>1)
printf("\nYou keyed in %d new books",c);
}

displaybook(struct library *l)
{
int i;

for(i=0;l[i].num!=0;i++)
{
printf("\nNo: %d, Title: %s, Author: %s, Price: %f",l[i].num,l[i].title,l[i].author,l[i].price);
if(l[i].flag==1)
printf(", Availability: Yes");

else
printf(", Availability: No");
}
}

specbook(struct library *l)
{
printf("\nNo: %d, Title: %s, Author: %s, Price: %f",l->num,l->title,l->author,l->price);
if(l->flag==1)
printf(", Availability: Yes");
else
printf(", Availability: No");
}

specbook2(struct library *l,int j)
{
int i,f=0;

for(i=0;l[i].num!=0;i++)
{
if(l[i].num==j)
{
specbook(&l[i]);
f=1;
break;
}
}
if(f==0)
printf("\nNo such book with this accession number");
}

authorbook(struct library *l,char *key)
{
int i,j,c,len,f=0;
len=strlen(key);
for(i=0;l[i].num!=0;i++)
{
for(j=0,c=0;l[i].author[j]!=0;j++)
{
if(*(key+j)==l[i].author[j])
c++;
}
if(c==len)
{
specbook(&l[i]);
f=1;
}
}
if(f==0)
printf("\nThere are no books with this author's name");
}

void accbook(struct library *l,int count)
{
int i,j;
struct library a1,a2;
for(i=0;l[i].num!=0;i++)
{
for(j=i+1;j {
if(l[i].num>l[j].num)
{
a1=l[i];
a2=l[j];
l[i]=a2;
l[j]=a1;
}
}
}
}

linkfloat()
{
float a,*b;
b=&a;
a=*b;
}

Friday, October 30, 2009

Chap10[D]g Use structure to check dates

Write a program that compares two given dates. To store date use structure say date that contains three members namely date, month and year. If the dates are equal then display message as "Equal" otherwise "Unequal".


void main()
{
int i,f=0;

struct date
{
int date;
int month;
int year;
};

struct date d[2];

for(i=0;i<2;i++)
{
printf("\nEnter day for the %d) date\n",i+1);
scanf("%d",&d[i].date);
printf("\nEnter the month for the %d) date\n",i+1);
scanf("%d",&d[i].month);
printf("\nEnter the year for the %d) date\n",i+1);
scanf("%d",&d[i].year);
}

if(d[0].date==d[1].date)
{
if(d[0].month==d[1].month)
{
if(d[0].year==d[1].year)
{
f=1;
}
}
}

if(f==1)
printf("\nThe dates are equal");

else
printf("\nThe dates are not equal");
}

Chap10[D]e Displaying data in structure with condition

There is a structure called employee that holds information like employee code, name, date of joining. Write a program to create an array of the structure and enter some data into it. Then ask the user to enter current date. Display the names of those employees whose tenure is 3 or more than 3 years according to the given current date.

This program doesn't check whether your date is correct so even if you put 99990001 it is still valid.

void main()
{
int i,k;
char date[8];
char j[1];

struct em
{
int code;
char name[20];
char datej[8];
};

struct em e[5];

for(i=0;i<5;i++)
{
printf("\nKey in code, name and date(ddmmyyy) of employment for %d) employee\n",i+1);
scanf("%d%s%s",&e[i].code,e[i].name,e[i].datej);
if(strlen(e[i].datej)!=8)
{
printf("\nYou keyed the date wrongly, key again");
i--;
continue;
}
}

while(1)
{
clrscr();
printf("\nEnter current date\n");
scanf("%s",date);


for(i=0;i<5;i++)
{
k=0;
k=funccheck(date,e[i].datej);

if(k==1)
printf("\nEmployee code= %d Employee name= %s has tenure more than or equal 3 years",e[i].code,e[i].name);
}

printf("\nKey q to quit or any other key to continue\n");
scanf("%s",j);

if(j[0]==113)
break;
}
}

funccheck(char *date,char *datej)
{
int a,a1,i,t;

for(i=7,t=1,a=0;i>3;i--,t*=10)
{
a=a+((*(date+i)-48)*t);
}

for(i=7,t=1,a1=0;i>3;i--,t*=10)
{
a1=a1+((*(datej+i)-48)*t);
}

if(a-a1>3)
return(1);
else if(a-a1<0)
return(0);

for(i=3,a=0,t=1;i>1;i--,t*=10)
{
a=a+((*(date+i)-48)*t);
}

for(i=3,a1=0,t=1;i>1;i--,t*=10)
{
a1=a1+((*(datej+i)-48)*t);
}

if(a-a1>0)
return(1);
else if(a-a1<0)
return(0);

for(i=1,a=0,t=1;i>=0;i--,t*=10)
{
a=a+((*(date+i)-48)*t);
}

for(i=1,a1=0,t=1;i>=0;i--,t*=10)
{
a1=a1+((*(datej+i)-48)*t);
}

if(a-a1>=0)
return(1);
else if(a-a1<0)
return(0);
}

Chap10[D]d Play Cricket

A record contains name of cricketer, his age, number of test matches that he has played and the average runs that he has scored in each test match. Create an array of structure to hold records of 20 such cricketer and then write a program to read these records and arrange them in ascending order by average runs. Use the qusort( ) standard library function.


Chap10[D]c Automobile has weird serial numbers

An automobile company has serial number for engine parts starting from AA0 to FF9. The other characteristics of parts to be specified in a structure are: Year of manufacture, material and quantity manufactured.
(a) Specify a structure to store information corresponding to a part.
(b) Write a program to retrieve information on parts with serial numbers between BB1 and CC6.


***When keying in the parts key alphabets in uppercase.

void main()
{
int i,j,letter,a,b,c,d;
char m[3],n[3],q[1];

struct parts
{
int year;
char material[20];
int qty;
};

struct parts p[27]={
{1991,"rubber",5},{1992,"rubber",6},{1991,"metal",7},{1997,"wood",8},{1993,"plastic",9},{1992,"wood",6},{1997,"metal",6},{1992,"rubber",7},{1991,"wood",2},
{1992,"metal",6},{1995,"wood",4},{1992,"rubber",5},{1998,"wood",2},{1997,"plastic",8},{1998,"plastic",9},{1998,"metal",8},{1991,"metal",8},{1992,"wood",5},
{1993,"wood",8},{1993,"rubber",7},{1997,"metal",2},{1998,"wood",1},{1999,"plastic",8},{1995,"wood",6},{1990,"rubber",3},{1997,"plastic",9},{1998,"wood",7}
};

/* for(i=0,letter=65;i<2;i++,letter++)
{
for(j=0;j<9;j++)
{
printf("\Key in values for year,material and quantity respectively for part %c%c%d\n",letter,letter,j+1);
scanf("%d%s%d",&p[i][j].year,&p[i][j].material,&p[i][j].qty);
}
} */

while(1)
{
clrscr();

printf("\nKey in the part number to retrieve the information from\n");
scanf("%s",m);
printf("\nKey the part number till the information is retrieved(End)\n");
scanf("%s",n);

a=((m[0]-65)*9+(m[2]-49));
b=((n[0]-65)*9+(n[2]-49));
printf("\na is %d,\nb is %d,\nm[0] is %d, n[0] is %d",a,b,m[0],n[0]);
c=a;
d=a;
while(c>=9)
{
c-=9;

}
printf("\nc after while is %d",c);
while( d>9)
d-=9;



for(i=a;i<=b;i++,c++,d++)
{
if(c==9)
{
m[0]+=1;
c=0;
}
if(d==9)
{
d=0;
}
printf("\nPart: %c%c%d, Year: %d, Material: %s, Quantity: %d",m[0],m[0],d+1,p[i].year,p[i].material,p[i].qty);
}






printf("\nKey q to quit or any other key to continue\n");
scanf("%s",q);

if(q[0]==113)
break;
}
}

Chap10[D]b Structure data of bank

Create a structure to specify data of customers in a bank. The data to be stored is: Account number, Name, Balance in account. Assume maximum of 200 customers in the bank. (a) Write a function to print the Account number and name of each customer with balance below Rs. 100. (b) If a customer request for withdrawal or deposit, it is given in the form: Acct. no, amount, code (1 for deposit, 0 for withdrawal) Write a program to give a message, “The balance is insufficient for the specified withdrawal”.

Chap10[D]a Printing specfic datas in structures

Create a structure to specify data on students given below: Roll number, Name, Department, Course, Year of joining Assume that there are not more than 450 students in the collage. (a) Write a function to print names of all students who joined in a particular year. (b) Write a function to print the data of a student whose roll number is given.


void main()
{
char j[1];
int yearc,rollc,i;

struct book
{
int roll;
char name[20];
char department[20];
char course[20];
int year;

};

struct book b[5]={
{1,"MrA","Science","Physics",2009},
{2,"MrB","Science","Maths",2008},
{3,"MrC","Arts","History",2009},
{4,"MrsD","Arts","History",2010},
{5,"MrsE","Science","Maths",2009}
};

while(1)
{
clrscr();
printf("\nEnter a year(2000 or 2001)\n");
scanf("%d",&yearc);
for(i=0;i<5;i++)
{
if(yearc==b[i].year)
printf("\nName: %s Year: %d",b[i].name,b[i].year);
}

printf("\nEnter a roll number(1-5)\n");
scanf("%d",&rollc);

for(i=0;i<5;i++)
{
if(rollc==b[i].roll)
{
printf("\nRoll number: %d, Name: %s, Department: %s\nCourse: %s,Year: %d",b[i].roll,b[i].name,b[i].department,b[i].course,b[i].year);
break;
}
}

printf("\nPress q to quit or any key to continue\n");

scanf("%s",j);
if(j[0]==113)
break;
}

}

linkfloat()
{
float a=0,*b;
b=&a;
a=*b;
}

Chap9[F]k Removing two vowels in succession

Write a program to count the number of occurrences of any two vowels in succession in a line of text. For example, in the sentence “Pleases read this application and give me gratuity” such occurrences are ea, ea, ui.


void main()
{
char sent[]="Pleases read this application and give me gratuity";

int i,c;

for(i=0,c=0;sent[i]!='\0';i++)
{
if((sent[i]==97||sent[i]==101||sent[i]==105||sent[i]==117)&&(sent[i+1]==97||sent[i+1]==101||sent[i+1]==105||sent[i+1]==111||sent[i+1]==117))
c++;
}

printf("\nThere are %d occurences of two vowels in succession",c);
}

Chap9[F]j Abbreviating names

Write a program that takes a set of names of individuals and abbreviates the first, middle and other names except the last name by their first letter.

void main()
{
char names[5][30]={
"My Name Very Very Long",
"Alien Ray Gun",
"Berry Berry White",
"Berry Berry Orange",
"Name Short"
};



int i,j,c,k,f,len,a;

for(i=0;i<5;i++)
{
for(j=0;names[i][j]!=0;j++)
{
len=strlen(&names[i][0]);
for(k=len;k>0;k--)
{
if(names[i][k]==32)
{
a=k;
break;
}
}

if(j==0)
{
c=j;

for(k=0,f=0;names[i][k]!=0;k++)
{
if(names[i][k]==32||f==1)
{
names[i][j+1]=names[i][k];
f=1;
j++;
}
}

names[i][j+1]='\0';
j=c;
}

else if(j==a)
break;

else if(names[i][j]==32&&names[i][j+2]!=32)
{
c=j;
for(k=j+2,j=j+2,f=0;names[i][k]!=0;k++)
{
if(names[i][k]==32||f==1)
{
names[i][j]=names[i][k];
f=1;
j++;
}
}

names[i][j]='\0';
j=c;
}
}
}

for(i=0;i<5;i++)
printf("\n%s",&names[i][0]);





}

Chap9[F]i Deleting of all occurences of "the"

Write a program that will read a line and delete from it all occurrences of the word ‘the’.

void main()
{
char sent[]="The time when the night comes is when the sun sets in the west";

int i;

for(i=0;sent[i]!=0;i++)
{
if(sent[i]==116&&sent[i+1]==104&&sent[i+2]==101&&sent[i+3]==32)
{
for(;sent[i+4]!=0;i++)
sent[i]=sent[i+4];

sent[i]='\0';
i=-1;
}
}

printf("\n%s",sent);
}

Chap9[F]h Deleting all vowels from a sentence

Write a program to delete all vowels from a sentence. Assume that the sentence is not more than 80 characters long.

void main()
{
char sent[]="She sells seashells on the seashore";

int i;

for(i=0;sent[i]!=0;i++)
{
if(sent[i]==97||sent[i]==101||sent[i]==105||sent[i]==111||sent[i]==117)
{
for(;sent[i+1]!=0;i++)
sent[i]=sent[i+1];

sent[i]='\0';

i=-1;
}
}
printf("\n%s",sent);
}

Chap9[F]e Creating a dynamic calendar

Develop a program that receives the month and year from the keyboard as integers and prints the calendar in the following format.



Note that according to the Gregorian calendar 01/01/1900 was Monday. With this as the base the calendar should be generated.
Modify the above program suitably so that once the calendar for a particular month and year has been displayed on the screen, then using arrow keys the user must be able to change the calendar in the following manner: Up arrow key : Next year, same month Down arrow key : Previous year, same month Right arrow key : Same year, next month Left arrow key : Same year, previous month If the escape key is hit then the procedure should stop. Hint: Use the getkey( ) function discussed in Chapter 8, problem number [L](c).




#include "dos.h"

void main()
{
int f=0,year,month,mod,i,j,k,m;
char z[1];

clrscr();
while(1)
{
if(f==0)
{ gotoxy(20,2);
printf("\nKey in the year");
scanf("%d",&year);
gotoxy(20,4);
printf("\nKey in the month(digits)");
scanf("%d",&month);
clrscr();
if(year<1900||year>3500)
{
printf("\nCalendar out of range");
continue;
}
if(month>12||month<1)
{
printf("\nInvalid month");
continue;
}
creategrid();
header(year,month);
f=1;
}


if(year<1900)
break;

mod=dayofmonth(year,month);

if(mod==0)
mod=7;

j=daysinmonth(year,month);


for(i=1,k=mod;i<=j;i++,k++)
{
gotoarr(k);
printf("%d",i);
}


m=getkey();

if(m==72)
year=year+1;

if(m==80)
year=year-1;

if(m==75)
month=month-1;

if(m==77)
month=month+1;

if(month==13)
{
month=1;
year=year+1;
}

if(month==0)
{
month=12;
year=year-1;
}

if(year<1900)
break;

clrscr();
creategrid();
header(year,month);


}
}

creategrid()
{
int i;

for(i=17;i<=59;i++)
{
if(i==17)
{

gotoxy(i,1);
printf("%c",218);
gotoxy(i,22);
printf("%c",192);
}
else if(i==59)
{
gotoxy(i,1);
printf("%c",191);
gotoxy(i,22);
printf("%c",217);
}
else
{
gotoxy(i,1);
printf("%c",196);
gotoxy(i,22);
printf("%c",196);
}
}

for(i=20;i<=56;i++)
{
if(i==20)
{
gotoxy(i,4);
printf("%c",218);
gotoxy(i,21);
printf("%c",192);
}
else if(i==56)
{
gotoxy(i,4);
printf("%c",191);
gotoxy(i,21);
printf("%c",217);
}
else
{
gotoxy(i,4);
printf("%c",196);
gotoxy(i,21);
printf("%c",196);
}
}

for(i=2;i<=21;i++)
{
gotoxy(17,i);
printf("%c",179);
gotoxy(59,i);
printf("%c",179);
}

for(i=5;i<=20;i++)
{
gotoxy(20,i);
printf("%c",179);
gotoxy(56,i);
printf("%c",179);
}

gotoxy(22,7);
printf("Mon");

gotoxy(27,7);
printf("Tue");

gotoxy(32,7);
printf("Wed");

gotoxy(37,7);
printf("Thu");

gotoxy(42,7);
printf("Fri");

gotoxy(47,7);
printf("Sat");

gotoxy(52,7);
printf("Sun");

gotoxy(21,23);
printf("%c=Next year",30);

gotoxy(39,23);
printf("%c=Previous year",31);

gotoxy(21,24);
printf("%c=Next month",16);

gotoxy(39,24);
printf("%c=Previous month",17);

}

getkey()
{
union REGS i,o;
while(!kbhit())
;
i.h.ah=0;
int86(22,&i,&o);
return(o.h.ah);
}

header(int year,int month)
{
int len;
char *m;

switch(month)
{
case 1:
m="January";
break;

case 2:
m="February";
break;

case 3:
m="March";
break;

case 4:
m="April";
break;

case 5:
m="May";
break;

case 6:
m="June";
break;

case 7:
m="July";
break;

case 8:
m="August";
break;

case 9:
m="September";
break;

case 10:
m="October";
break;

case 11:
m="November";
break;

case 12:
m="December";
break;
}

len=strlen(m)+5;
len=len/2;
gotoxy(38-len,5);
printf("%s %d",m,year);
}

dayofmonth(int year,int month)
{
int leap,mod,check=0,i,diff;
float days;
long days1;

if((year%4==0&&year%100!=0)||year%400==0)

check=1;


year=year-1;
diff=year-1900;
leap=(year-1900)/4-(year-1900)/100+((year/400)-4);
days=((diff-leap)*365.0)+(leap*366.0)+365+1;


for(i=1;i<=12;i++)
{
if(i==month+1)
break;

else if(i==1)
continue;

else if(i==3)
{
if(check==0)
days=days+28;

else if(check==1)
days=days+29;
}

else if(i<9)
{
if(i%2==0)
days=days+31;

else
days=days+30;
}

else if(i==9)
days=days+31;

else if(i>9)
{
if(i%2==0)
days=days+30;

else
days=days+31;
}
}

days1=days;

mod=days1%7;
return(mod);
}

daysinmonth(int year,int month)
{
int days;
if(((year%4==0&&year%100!=0)||year%400==0)&&month==2)
days=29;

else if(month==2)
days=28;

else if(month<8)
{
if(month%2==0)
days=30;
else
days=31;
}

else if(month==8)
days=31;

else if(month>8)
{
if(month%2==0)
days=31;
else
days=30;
}

return(days);
}

gotoarr(int i)
{
int row,col,x,y;

row=((i-1)/7)+1;

if(i<=7)
i=i+7;

col=i%7;

if(col==0)
col=7;

y=7+(2*row);
x=17+(5*col);
gotoxy(x,y);
}

Chap9[F]c Reversing strings

Write a program to reverse the strings stored in the following array of pointers to strings:
char *s[ ] = {
"To err is human...",
"But to really mess things up...",
"One needs to know C!!"
} ;

Hint: Write a function xstrrev ( string ) which should reverse the contents of one string. Call this function for reversing each string stored in s.


void main()
{
char *s[]={
"To err is human...",
"But to really mess things up...",
"One needs to know C!!"
};


int i;



for(i=0;i<3;i++)
xstrrev(s[i]);

for(i=0;i<3;i++)
printf("\n%s",s[i]);

}

xstrrev(char *m)
{
char *temp1;
char *temp2;
char *clear;

int i,len,j;
*clear='\0';
len=strlen(m)-1;

for(i=0,j=len;;i++,j--)
{
printf("\n b4 *(m+i) is %c",*(m+i));
*temp1=*(m+i);
*temp2=*(m+j);
*(m+i)=*clear;
*(m+j)=*clear;
*(m+i)=*temp2;
*(m+j)=*temp1;

/* printf("\n i is %d, j is %d",i,j); */
if((j-i)==1||j==i)
break;
printf("\n After *(m+i) is %c",*(m+i));


}

}

Chap9[F]b Arrange words alphabetically

Write a program to sort a set of names stored in an array in alphabetical order.

void main()
{
char words[10][20];
char temp[30];
char temp2[30];
char clear[1]={'\0'};

int i,j;

for(i=0;i<10;i++)
{
printf("\nKey in the %d) word",i+1);
scanf("%s",&words[i][0]);
}

for(i=0;i<9;i++)
{
for(j=0;words[i][j]!=0;j++)
{
if(words[i][j]>words[i+1][j])
{
strcpy(temp,&words[i][0]);
strcpy(temp2,&words[i+1][0]);
strcpy(&words[i][0],clear);
strcpy(&words[i+1][0],clear);
strcpy(&words[i][0],temp2);
strcpy(&words[i+1][0],temp);

i=-1;
}

else if (words[i][j]==words[i+1][j])
continue;

else
break;

}
}

for(i=0;i<10;i++)
{

printf("\n%s",&words[i][0]);
}
}

Note: This code only works for small letters.
If you want to use uppercase letters then create a function to convert all uppercase to lowercase first then do the main code then at the end convert back to uppercase and print.

Chap9[F]a Replacing words in sentences

Write a program that uses an array of pointers to strings str[ ]. Receive two strings str1 and str2 and check if str1 is embedded in any of the strings in str[ ]. If str1 is found, then replace it with str2.

char *str[ ] = { "We will teach you how to...",
"Move a mountain",
"Level a building",
"Erase the past",
"Make a million",
"...all through C!"
} ;

For example if str1 contains "mountain" and str2 contains "car", then the second string in str should get changed to "Move a car".





















Note: There is a limitation to this code
*** Except for the first sentence if the word you want to replace is longer than the original word the program doesn't work ideally.
So the replace function seem in the program works only on single line sentences(i.e One dimension char array).

The reason for this is that a longer word pushes the location of the last letter of the sentence into the next sentence.For example if a is replace with two in the mountain sentence then the last letter "n" of mountain gets pushed to a location at around "e" in "Level" in the next sentence. The code in replace only accounts for longer words in one sentence.

If you want to overcome this limitation then add a new string array.
"replace" function becomes replace(char *m,int j,char *n,char *new) where char *new is a blank array defined in main(). Then pass this blank array to char *new in replace function.

Chp9[D]f Removing two or more spaces in a string

Write a program that replaces two or more consecutive blanks in a string by a single blank. For example, if the input is






void main()
{
char sent[]="Grim return to the planet of apes!!";
int i;

for(i=0;sent[i]!=0;i++)
{

if(sent[i]==32&&sent[i+1]==32)

{

for(;sent[i+1]!=0;i++)
{
sent[i]=sent[i+1];
}

sent[i]='\0';


i=0;


}



}
printf("\n%s",sent);
}

Chap9[D]e Converting string digits to integers

Write a program that converts a string like "124" to an integer 124.

Chap 9[D]d Working with strings is fun

Write a program that extracts part of the given string from the specified position. For example, if the sting is "Working with strings is fun", then if from position 4, 4 characters are to be extracted then the program should return string as "king". Moreover, if the position from where the string is to be extracted is given and the number of characters to be extracted is 0 then the program should extract entire string from the specified position.


void main()
{
char stri[]="Working with string is fun";
char stri2[10];
int a,flag=0,i=0,b;

printf("\nEnter a position for sentence: Working with string is fun");
scanf("%d",&a);

while(flag==0)
{
if(i==(a-1))
{
if(stri[i]==32)
{
i++;
for(b=0;;b++,i++)
{

if(stri[i]==32||stri[i]=='\0')
{
stri2[b]='\0';
break;
}

stri2[b]=stri[i];
}
}

else

for(b=0;;b++,i++)
{

if(stri[i]==32||stri[i]=='\0')
{
stri2[b]='\0';
break;
}

stri2[b]=stri[i];
}
flag=1;
}

i++;
}
printf("\n%s",stri2);
}

Chap9[D]c Converting all lowercase to uppercase in string

Write a program that converts all lowercase characters in a given string to its equivalent uppercase character.

void main()
{
char word[30];
int i=0;

printf("\nType a word with capital and small letters");
scanf("%s",word);


while(word[i]!='\0')
{

if(word[i]>=97&&word[i]<=122)
word[i]-=32;

i++;
}

printf("\nThe edited word is %s",word);
}

Creating your own strcat()

Creating your own strcat()


void main()
{
char source[]="Folks!";
char target[30]="Hello";

scat(target,source);
printf("\nSource string = %s",source);
printf("\nTarget string = %s",target);
}

scat(char *m,char *n)
{
char *p;
p=m;
while(*n!='\0')
{
if(*m=='\0'||m>p+6)
{
*m=*n;
n++;
}

m++;
}

*m='\0';
}

Chap8[L]s Summation from first coordinate to last coordinate

The X and Y coordinates of 10 different points are entered through the keyboard. Write a program to find the distance of last point from the first point (sum of distance between consecutive points).

#include math.h(include arrows)
void main()
{
float dis(int,int);
int arr[10][2];
int i,j;
float sum;

for(i=0;i<10;i++)
{
for(j=0;j<2;j++)
{
printf("\nKey in the [%d][%d]) value",i+1,j+1);
scanf("%d",&arr[i][j]);
}
}

for(i=0;i<10;i++)
sum=sum+dis(arr[i][0],arr[i][1]);

printf("\nThe sum of the distance is %f",sum);
}

float dis(int a,int b)
{
float c;
c=sqrt((a*a)+(b*b));
return(c);
}

Chap8[L]r Computing straight line

For the following set of point given by (x, y) fit a straight line given by
y = a + bx
where,




















#include math.h (include arrows)

void main()
{
float arr[10][2]={
3.0,1.5,
4.5,2.0,
5.5,3.5,
6.5,5.0,
7.5,6.0,
8.5,7.5,
8.0,9.0,
9.0,10.5,
9.5,12.0,
10.0,14.0
};

int i,j;
float sx=0,sy=0,sx2=0,sxy=0,my,mx,a,b;

/* for(i=0;i<10;i++)
{
for(j=0;j<2;j++)
{
printf("\nKey in the [%d][%d] value",i+1,j+1);
scanf("%f",&arr[i][j]);
}
}
*/
/*calculating summation x*/

for(i=0;i<10;i++)
sx=sx+arr[i][0];

/*calculating summation y*/
for(i=0;i<10;i++)
sy=sy+arr[i][1];

/*calculating summation x2*/

for(i=0;i<10;i++)
sx2=sx2+(arr[i][0]*arr[i][0]);


/*calculating summation xy*/

for(i=0;i<10;i++)
sxy=sxy+(arr[i][0]*arr[i][1]);

my=sy/i;
mx=sx/i;

b=((i*sxy)-(sx*sy))/((i*sx2)-(sx*sx));
a=my-(b*mx);

printf("\nThe value of a is %f\nThe value of b is %f",a,b);
}

Chap8[L]q Computing correlation coefficient

For the following set of n data points (x, y), compute the correlation coefficient r, given by


















#include math.h (include arrows)

void main()
{
float arr[11][2]={
34.22,102.43,
39.87,100.93,
41.85,97.43,
43.23,97.81,
40.06,98.32,
53.29,98.32,
53.29,100.07,
54.14,97.08,
49.12,91.59,
40.71,94.85,
55.15,94.65
};
int i,j;
float sx=0,sy=0,sx2=0,sy2=0,sxy=0,b,r;


/*calculating summation x*/

for(i=0;i<11;i++)
sx=sx+arr[i][0];
printf("\nsummation x is %f",sx);
/*calculating summation y*/

for(i=0;i<11;i++)
sy=sy+arr[i][1];
printf("\nsummation y is %f",sy);
/*calculating summation x2*/

for(i=0;i<11;i++)
sx2=sx2+(arr[i][0]*arr[i][0]);
printf("\nsummation x2 is %f",sx2);
/*calculating summation y2*/

for(i=0;i<11;i++)
sy2=sy2+(arr[i][1]*arr[i][1]);
printf("\nsummation sy2 is %f",sy2);
/*calculating summation xy*/

for(i=0;i<11;i++)
sxy=sxy+(arr[i][0]*arr[i][1]);
printf("\nsummation sxy is %f",sxy);

/*calculating bottom part*/
b=(i*sx2-(sx*sx))*(i*sy2-(sy*sy));
printf("\nbottom is %f",b);

/*calculating coefficient r*/

r=(sxy-(sx*sy))/(sqrt(b));

printf("\n The correlation coefficient is %f",r);
}

Chap8[L]p Area of triangle and largest plot of land

The area of a triangle can be computed by the sine law when 2 sides of the triangle and the angle between them are known.
Area = (1 / 2 ) ab sin ( angle )
Given the following 6 triangular pieces of land, write a program to find their area and determine which is largest,











#include math.h (include arrows)
void main()
{
float arr[6][3];
int i,j,d;
float area,c=0;

for(i=0;i<6;i++)
{
for(j=0;j<3;j++)
{
printf("\nKey in the [%d][%d] value",i+1,j+1);
scanf("%f",&arr[i][j]);
}
}

for(i=0;i<6;i++)


{

area=(1.0/2.0)*arr[i][0]*arr[i][1]*sin(arr[i][2]);

if(area>c)
{ printf("\n1");
c=area;
d=i;
}
}

printf("\nThe biggest plot of land is plot no. %d with area %f",d+1,c);
}

Chap8[L]o Standard deviation and mean




Chap8[L]L Finding norm of matrix

Write a function to find the norm of a matrix. The norm is defined as the square root of the sum of squares of all elements in the matrix.

Chap8[L]d Creating grid puzzle


Very often in fairs we come across a puzzle that contains 15 numbered square pieces mounted on a frame. These pieces can be moved horizontally or vertically. A possible arrangement of these pieces is shown below:




As you can see there is a blank at bottom right corner. Implement the following procedure through a program:


Draw the boxes as shown above. Display the numbers in the above order. Allow the user to hit any of the arrow keys (up, down, left, or right). If user hits say, right arrow key then the piece with a number 5 should move to the right and blank should replace the original position of 5. Similarly, if down arrow key is hit, then 13 should move down and blank should replace the original position of 13. If left arrow key or up arrow key is hit then no action should be taken. The user would continue hitting the arrow keys till the numbers aren’t arranged in ascending order. Keep track of the number of moves in which the user manages to arrange the numbers in ascending order. The user who manages it in minimum number of moves is the one who wins. How do we tackle the arrow keys? We cannot receive them using scanf( ) function. Arrow keys are special keys which are identified by their ‘scan codes’. Use the following function in your program. It would return the scan code of the arrow key being hit. Don’t worry about how this function is written. We are going to deal with it later. The scan codes for the arrow keys are:

up arrow key – 72 down arrow key – 80 left arrow key – 75 right arrow key – 77
/* Returns scan code of the key that has been hit */
#include "dos.h"
getkey( )
{
union REGS i, o ;
while ( !kbhit( ) )
;
i.h.ah = 0 ;
int86 ( 22, &i, &o ) ;
return ( o.h.ah ) ;
}



ANS:

#include "dos.h"
void main()
{

void creategrid();
int g,c;
int arr[16]={1,4,15,7,8,10,2,11,14,3,6,13,12,9,5,0};
clrscr();
creategrid();
printarray(arr);

for(g=15,c=0;;)
{
int k,a,b,i;
k=getkey();

if(k==80)
{
if((g-4)<0) a="arr[g-4];" b="arr[g];" k="="72)">15)
continue;

a=arr[g+4];
b=arr[g];
arr[g+4]=b;
arr[g]=a;
go(g);
printf("%d",arr[g]);
go(g+4);
printf("%c%c",0,0);
go(g+4);
c++;
g+=4;
}

if(k==75)
{
if(g==3g==7g==11g==15)
continue;

a=arr[g+1];
b=arr[g];
arr[g+1]=b;
arr[g]=a;
go(g);
printf("%d",arr[g]);
go(g+1);
printf("%c%c",0,0);
go(g+1);
c++;
g+=1;
}

if(k==77)
{
if(g==0g==4g==8g==12)
continue;

a=arr[g-1];
b=arr[g];
arr[g-1]=b;
arr[g]=a;
go(g);
printf("%d",arr[g]);
go(g-1);
printf("%c%c",0,0);
go(g-1);
c++;
g-=1;
}

for(i=0;i<15;i++)
{
if(arr[i]!=i+1)
break;

if(arr[i]==(i+1)&&i==14)
{
gotoxy(6,24);
printf("\nNumber of moves to complete is %d",c);
exit();
}
}
}




}

go(int g)
{
switch(g)
{
case 0:
gotoxy(8,5);
break;
case 1:
gotoxy(12,5);
break;
case 2:
gotoxy(16,5);
break;
case 3:
gotoxy(20,5);
break;
case 4:
gotoxy(8,9);
break;
case 5:
gotoxy(12,9);
break;
case 6:
gotoxy(16,9);
break;
case 7:
gotoxy(20,9);
break;
case 8:
gotoxy(8,13);
break;
case 9:
gotoxy(12,13);
break;
case 10:
gotoxy(16,13);
break;
case 11:
gotoxy(20,13);
break;
case 12:
gotoxy(8,17);
break;
case 13:
gotoxy(12,17);
break;
case 14:
gotoxy(16,17);
break;
case 15:
gotoxy(20,17);
break;
}
}


getkey()
{
union REGS i,o;
while(!kbhit())
;
i.h.ah=0;
int86(22,&i,&o);
return(o.h.ah);
}

printarray(int *m)
{
int a,b,i,j;

for(a=5,i=0;a<=17;a+=4,i++)
{
for(b=8,j=0;b<=20;b+=4,j++)
{
gotoxy(b,a);
printf("%d",*(m+(i*4)+j));
}
}
gotoxy(20,17);
printf("%c",0);

}


void creategrid()
{
int a,b;

for(a=3;a<=19;a+=4)
{
for(b=6;b<=22;b++)
{
if(b==6(b-6)%4==0)
{
if(a==3)
{
if(b==6)
{
gotoxy(6,3);
printf("%c",218);
}

else if(b==22)
{
gotoxy(22,3);
printf("%c",191);
}

else
{
gotoxy(b,3);
printf("%c",194);
}
}

else if(a==19)
{
if(b==6)
{
gotoxy(6,19);
printf("%c",192);
}

else if(b==22)
{
gotoxy(22,19);
printf("%c",217);
}

else
{
gotoxy(b,19);
printf("%c",193);
}
}

else
{
if(b==6)
{
gotoxy(6,a);
printf("%c",195);
}

else if(b==22)
{
gotoxy(22,a);
printf("%c",180);
}

else
{
gotoxy(b,a);
printf("%c",197);
}
}
}

else
{
printf("%c",196);
}
}
}

for(b=6;b<=22;b+=4)
{
for(a=4;a<=18;a++)
{
if((a-3)%4==0)
continue;

else
{
gotoxy(b,a);
printf("%c",179);
}
}
}
}

Chap8[L]c Transpose 4X4 matrix

Write a program to obtain transpose of a 4 x 4 matrix. The transpose of a matrix is obtained by exchanging the elements of each row with the elements of the corresponding column.


void main()
{
int arr[4][4];
int i,j,a,b,f;
printf("\nInput numbers to 4*4 matrix");

for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("\nKey in the [%d][%d]) value",i+1,j+1);
scanf("%d",&arr[i][j]);
}
}

for(i=0;i<4;i++)
{
for(j=0,f=0;j<4;j++)
{
if(i!=j&&f==0)
continue;

a=arr[i][j];
b=arr[j][i];
arr[i][j]=b;
arr[j][i]=a;
f=1;
}
}

for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
printf("%d ",arr[i][j]);

printf("\n");
}
}

Chap8[L]b Pick largest number from matrix

Write a program to pick up the largest number from any 5 row by 5 column matrix.

Chap8[L]a Initialising 3D array

How will you initialize a three-dimensional array threed[3][2][3]? How will you refer the first and last element in this array?


void main()
{
int threed[3][2][3]={
{
1,2,3,
4,5,6
},

{
7,8,9,
10,11,12
},

{
13,14,15,
16,17,18
}
};

printf("\nFirst element of array is %d\nLast element of the array is %d",threed[0][0][0],threed[2][1][2]);
}

Chap8[I]d

Write a program which performs the following tasks:
− initialize an integer array of 10 elements in main( )
− pass the entire array to a function modify( )
− in modify( ) multiply each element of array by 3
− return the control to main( ) and print the new array elements in main( )


Chap8[I]c Finding smallest number in array using pointers

Find the smallest number in an array using pointers.

Chap8[I]b Check similar integers in array

If an array arr contains n elements, then write a program to check if arr[0] = arr[n-1], arr[1] = arr[n-2] and so on.

This program will have repeated results if the input contains more than 2 same integers



void main()
{
int arr[25];
int i,*j,k;
j=arr;

printf("\nInput 25 integers");

for(i=0;i<25;i++,j++)
{
printf("\nKey in the %d) value",i+1);
scanf("%d",&*j);
}

for(i=0;i<25;i++)
{
for(k=24;k>i;k--)
if(arr[i]==arr[k])
printf("\nArray [%d] = Array[%d]",i,k);
}
}

Chap8[I]a Reversing contents and copy to another array

Write a program to copy the contents of one array into another in the reverse order.

void main()
{
int arr1[5]={1,2,3,4,5};
int arr2[5];
int i,k;

for (i=4,k=0;i>=0;i--,k++)
arr2[k]=arr1[i];

for(i=0;i<5;i++)
printf("\nValue of arr2[%d] is %d",i,arr2[i]);

}


With Pointers


void main()
{
int arr1[5]={1,2,3,4,5};
int arr2[5];
int *m;
int i,*j,k,l=5;
j=arr1;
m=arr2;
func(j,m,l);
for(i=0;i<5;i++)
printf("\nValue of arr2[%d] is %d",i,arr2[i]);
}

func(int *j, int *m, int l)
{
int i;
for(j=j+4,i=0;i<5;i++,j--,m++)
*m=*j;
}

Chap8[D]d Sieve of Eratosthenes

Implement the following procedure to generate prime numbers from 1 to 100 into a program. This procedure is called sieve of Eratosthenes.
step 1 Fill an array num[100] with numbers from 1 to 100
step 2 Starting with the second entry in the array, set all its multiples to zero.

step 3 Proceed to the next non-zero element and set all its multiples to zero.
step 4
Repeat step 3 till you have set up the multiples of all the non-zero elements to zero
step 5 At the conclusion of step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers.


Chap8[D]b Finding +tive -tive zeros, odd and even numbers in array

Twenty-five numbers are entered from the keyboard into an array. Write a program to find out how many of them are positive, how many are negative, how many are even and how many odd.

void main()
{
int arr[25];
int a,b,c,d,e,i;
a=0;
b=0;
c=0;
d=0;
e=0;

for(i=0;i<25;i++)
{
printf("\nKey the %d) value",i);
scanf("%d",&arr[i]);
}

for(i=0;i<25;i++)
{
if(arr[i]>0)
a++;

if(arr[i]<0)
b++;

if(arr[i]==0)
c++;

if(arr[i]%2==0)
d++;
else
e++;
}

if(a>0)
printf("\nThere are %d positive integers",a);

if(b>0)
printf("\nThere are %d negative integers",b);

if(c>0)
printf("\nThere are %d zeros",c);

if(d>0)
printf("\nThere are %d even numbers",d);

if(e>0)
printf("\nThere are %d odd numbers",e);

}

Chap 8[D]a Search quantity of instances in Array

Twenty-five numbers are entered from the keyboard into an array. The number to be searched is entered through the keyboard by the user. Write a program to find if the number to be searched is present in the array and if it is present, display the number of times it appears in the array.
void main()
{
int arr[25];
int a,d,i;

for(i=0;i<25;i++)
{
printf("\nKey %d) value",i);
scanf("%d",&arr[i]);
}

printf("\n25 numbers stored, enter any integer again");
scanf("%d",&d);

for(i=0,a=0;i<25;i++)
{
if(arr[i]==d)
a++;
}

if(a>0)
printf("\nThe integer appeared %d times in the array",a);

else
printf("\nThe integer did not appear in the array");
}

Evaluating Sin(x) series

Write a C function to evaluate the sin series




void main()
{
float sin(float);
float d,e;
printf("\nInput x value into sin(x) to find its result");
scanf("%f",&d);
e=sin(d);
printf("\nThe result is %f",e);
}
float fact(float x)
{
int f;
if(x==1)
return(1);

else
f=x*fact(x-1);

return(f);
}

float power(float y,float z)
{
float w;
if(z==0)
return(1);
if(z==1)
return(y);
w=y*(power(y,z-1));
return(w);
}

float sin(float a)
{ float fact(float);
float b;
float power(float,float);
b=a-(power(a,3)/fact(3.0))+(power(a,5)/fact(5.0))-(power(a,7)/fact(7.0))+(power(a,9)/fact(9.0));
return(b);
}

Running sum of first 25 numbers

Write a recursive function to obtain the running sum of first 25 natural numbers.


void main()
{
int d,e;
d=25;
e=naturaln(d);
printf("\nThe sum of the first %d digits is %d",d,e);
}

naturaln(int x)
{
int a;
if(x==1)
return(1);
else
{
a=x+naturaln(x-1);
return(a);
}


}

Fibonacci Sequence

Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence: 1 1 2 3 5 8 13 21 34 55 89...

void main()
{ void Fib(float,float,float);
float e,d;
/* i put d=24 because the function will start off by printing 1 and starts counting its recursion only after the first digit so if i want 25 numbers its 25-1=24*/
d=24;
e=1;
printf("\Display Fibonacci sequence");
Fib(d,e,1.0);
}



void Fib(float x,float a,float b)
{
if(a==1)

printf("\n1");

if(x==0)
exit();
printf("\n%f",a);
if(x==1)
exit();
b=a+b;
printf("\n%f",b);
Fib(x-2,a+b,b);
}

Sum of 5 digits using recursion

A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number Using recursion

code obtained from: https://www.blogger.com/comment.g?blogID=20225658&postID=115134493576072577 -->comment by (rahul sahay)

void main()
{

int f,l;
printf("\nInput a 5 digit number");
scanf("%d",&f);
l=sum(f);
printf("\nThe sum of the digits is %d",l);
}

sum(int n)
{
if(n==0)
return 0;
else
return(n%10+sum(n/10));
}

Average and percentage 5[F]c

Write a function that receives marks received by a student in 3 subjects and returns the average and percentage of these marks. Call this function from main( ) and print the results in main( ).

void main()
{
int a,b,c,full;
float av,perc;
printf("\nEnter the marks received by the student in 3 subjects and the total possible marks for 1 paper");
scanf("%d%d%d%d",&a,&b,&c,&full);
calc(a,b,c,full,&av,&perc);
printf("\nThe average marks is %f.\nThe percentage is %f",av,perc);
}

calc(int i,int j,int k,int full,float *ave,float *perce)
{
*ave=(i+j+k)/3.0;
*perce=(*ave/full)*100.0;
}

Sum,Average Standard deviation 5[F]b

Write a function that receives 5 integers and returns the sum, average and standard deviation of these numbers. Call this function from main( ) and print the results in main( ).#include

void main()
{
float ave,sd;
int a,b,c,d,e,sum;
printf("\nInput 5 integers");
scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);
func(a,b,c,d,e,&sum,&ave,&sd);
printf("\nThe sum is %d\nThe average is %f\nThe standard deviation is %f",sum,ave,sd);
}

func(int a,int b,int c,int d,int e,int *su,float *av,float *std)
{
*su=a+b+c+d+e;
*av=*su/5;
*std=sqrt((((a-*av)*(a-*av))+((b-*av)*(b-*av))+((c-*av)*(c-*av)))/5.0);
}

Product of float and integer 5[F]a

Write a function which receives a float and an int from main( ), finds the product of these two and returns the product which is printed through main( ).

void main()
{
float product(float,int);
float a,p;
int b;
printf("\nEnter the two values to find the product");
scanf("%f%d",&a,&b);

p=product(a,b);
printf("The product is %f",p);
}

float product(float i,int j)
{
float pr;
pr=i*j;
return(pr);
}

Finding prime numbers

A positive integer is entered through the keyboard. Write a function to obtain the prime factors of this number. For example, prime factors of 24 are 2, 2, 2 and 3, whereas prime factors of 35 are 5 and 7.

Using recursion:

void main()
{
int x;
printf("\nInput an integer\n");
scanf("%d",&x);
prime(x);
}

prime(int x)
{
int a;
for(a=2;a<=x;a++)
{
if(x%a==0)
{
printf("%d ",a);
prime(x/a);
break;
}
}
}


without recursion


void main()
{
int x;
printf("\nInput an integer\n");
scanf("%d",&x);
prime(x);
}

prime(int x)
{
int a;

for(a=2;a<=x;a++)
{
if(x%a==0)
{
printf("%d ",a);
x/=a;
a--;
}
}
}

Checking for leap year

Any year is entered through the keyboard. Write a function to determine whether the year is a leap year or not.

void main()
{
int y;
printf("\nInput the year to check if its a leap year");
scanf("%d",&y);
leap(y);
}

leap(int year)
{
if((year%4==0&&year%100!=0)||year%400==0)
printf("\nIt is a leap year");

else
printf("\nIts not a leap year");
}

Power function

Write a function power ( a, b ), to calculate the value of a raised to b.



void main()
{
float power(float,float);
float x,y,z;
printf("\nInput the first value and second of which the first is raised to the power of the second value");
scanf("%f%f",&x,&y);
z=power(x,y);
printf("\nThe answer is %f",z);
}


float power(float a,float b)
{
float c;

if(b==0)
return(1);

if(b==1)
return(a);

else
c=a*power(a,b-1);

return(c);
}

Finding Factorial

Write a function to calculate the factorial value of any integer entered through the keyboard.

void main()
{
float fact(float);
float a,a1;
printf("\nInput a number to find the factorial");
scanf("%f",&a);
a1=fact(a);
printf("\nThe factorial of %f is %f",a,a1);
}

float fact(float x)
{
float f;

if(x==1)
return(1);

else
f=x*fact(x-1);

return(f);
}

Thursday, October 29, 2009

Converting to roman equivalent

Write a general-purpose function to convert any given year into its roman equivalent. The following table shows the roman equivalents of decimal numbers: Example: Roman equivalent of 1988 is mdcccclxxxviii Roman equivalent of 1525 is mdxxv



void main()
{
int a;
printf("\nInput the year to get it in Roman numerals");
scanf("%d",&a);
roman(a);
}

roman(int year)
{
if(year>=1000)
{
printf("m");
roman(year-1000);
}

else if(year>=500)
{
printf("d");
roman(year-500);
}

else if(year>=100)
{
printf("c");
roman(year-100);
}

else if(year>=50)
{
printf("l");
roman(year-50);
}

else if(year>=10)
{
printf("x");
roman(year-10);
}

else if(year>=5)
{
printf("v");
roman(year-5);
}

else if(year>=1)
{
printf("i");
roman(year-1);
}


}

Checking of point in triangle(Chap5[J](j))

Write a function to compute the distance between two points and use it to develop another function that will compute the area of the triangle whose vertices are A(x1, y1), B(x2, y2), and C(x3, y3). Use these functions to develop a function which returns a value 1 if the point (x, y) lines inside the triangle ABC, otherwise a value 0.


To check if point p inside triangle:













Calculate length AB,BC,AC
Then calculate area of triangle APB,APC,BPC
Point P is inside triangle if Area( APB + APC + BPC)=Area triangle ABC









#include maths.h (include the the two arrows)
float geodis(int,int,int,int);
float areat(float,float,float);
int pcheck(int,int,int,int,int,int,int,int,float);
void main()
{

float dis1,dis2,dis3,area;
int a,b,c,d,e,f,g,h,i=0;

printf("\nInput the 3 coordinates x1,y1,x2,y2,x3,y3");
scanf("%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f);
dis1=geodis(a,b,c,d);
dis2=geodis(a,b,e,f);
dis3=geodis(c,d,e,f);
area=areat(dis1,dis2,dis3);
printf("\nThe area of the triangle is %f",area);
printf("\nEnter a point(x,y) to check if it lies in the triangle");
scanf("%d%d",&g,&h);
i=pcheck(a,b,c,d,e,f,g,h,area);
printf("\nThe value of i now is %d",i);
if(i==1)
printf("\nThe point lies inside the triangle");
else
printf("\nThe point lies outside the triangle");


}




float geodis(int x1,int y1,int x2,int y2)
{
float distance,x3,y3;
x3=x2-x1;
y3=y2-y1;
distance=sqrt(pow(x3,2)+pow(y3,2));
return(distance);
}

float areat(float a,float b,float c)
{
float area,s;
s=(a+b+c)/2.0;
area=sqrt(s*(s-a)*(s-b)*(s-c));
return(area);
}

pcheck(int a,int b,int c,int d,int e,int f,int g,int h,float area)
{

float area1,area2,area3;
float dis1,dis2,dis3,dis4,dis5,dis6;
int total;
dis1=geodis(a,b,e,f);
dis2=geodis(c,d,e,f);
dis3=geodis(a,b,c,d);
dis4=geodis(a,b,g,h);
dis5=geodis(e,f,g,h);
dis6=geodis(c,d,g,h);
area1=areat(dis4,dis3,dis6);
area2=areat(dis2,dis5,dis6);
area3=areat(dis1,dis5,dis4);
printf("\nArea in pcheck is %f",area);
printf("\nArea 1,2,3 is %f",area1+area2+area3);
total=area1+area2+area3-area;
printf("\nTotal is %d",total);
if(total==0)
return(1);

else
return(0);
}

Area of Triangle

If the lengths of the sides of a triangle are denoted by a, b, and c, then area of triangle is given by
area = squareroot(S*(s-a)*(s-b)*(s-c))
where, S = ( a + b + c ) / 2


#include math.h (include 2 arrows)
void main()
{
float areat(float,float,float);
float x,y,z,t;
printf("\nInput the three sides of the triangle");
scanf("%f%f%f",&x,&y,&z);
t=areat(x,y,z);
printf("\nThe area of the triangle is %f",t);
}

float areat(float a,float b,float c)
{

float s,area;
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
return(area);
}

Circular shift

Given three variables x, y, z write a function to circularly shift their values to right. In other words if x = 5, y = 8, z = 10 after circular shift y = 5, z = 8, x =10 after circular shift y = 5, z = 8 and x = 10. Call the function with variables a, b, c to circularly shift values.

void main()
{
int d,e,f;
printf("\nInput 3 digits to circular shift it(x,y,z)");
scanf("%d%d%d",&d,&e,&f);
circs(&d,&e,&f);
printf("\The shifted values are x=%d, y=%d, z=%d",d,e,f);
}

circs(int *x, int *y, int *z)
{
int a,b,c;
a=*z;
b=*x;
c=*y;
*x=a;
*y=b;
*z=c;
}