Let Us C / Chapter 9 (Puppeting on Strings)


                             Exercise [D]



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

Solution:


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

char str[100];

gets(str);

printf("\n\n");

strupr(str);          /* 'strupr()' is a function to convert a lowercase 
puts(str);              string into uppercase */

getch();

}

-----------------------------------------------------------------------------------------------------------

(d) 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.

Solution:


#include<stdio.h>
#include<conio.h>

void main() {

char s[100];
int i=0,n,pos;
clrscr();

printf("enter the string: \n\n");
gets(s);

printf("\n\nenter the position to extract from: ");
scanf("%d",&pos);

printf("\nenter the number of characters to extract: ");
scanf("%d",&n);


printf("\n\n\nExtracted string: \n\n");

if(n==0) {

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

if(i>=pos-1) {

putch(s[i]);

}

i++;
}
}

else {

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

if(i>=pos-1 && i<=pos-1+(n-1)) {
printf("%c",s[i]);
}

i++;
}
}
getch();
}

--------------------------------------------------------------------------------------------------------------

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

Solution:


#include<stdio.h>
#include<conio.h>
#include<string.h>

void main() {

char str[100];
int i;
clrscr();

printf("Enter the string: \n\n");

gets(str);

i=atoi(str);  /* 'atoi' is a function to convert a string into an integer */

printf("%d",i);

getch();

}

---------------------------------------------------------------------------------------------------------------

(f) Write a program that replaces two or more consecutive blanks in a string by a single blank. For example, if the input is
Grim return to the planet of apes!!
the output should be
Grim return to the planet of apes!!

Solution:


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

char s[80];
int i=0;
clrscr();

printf("Enter the string:\n\n\n");
gets(s);


printf("\n\n\nOutput:\n\n\n");

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


if(s[i]==' ' && s[i+1]==' ') {

/* if there are two or more blanks, do nothing */

}

else  {

putch(s[i]);

}

i++;

}

getch();
}
_______________________________________________________________________

                          Exercise [F]


(a) 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".

Solution: 



#include<stdio.h>

#include<conio.h>

#include<string.h>


void replace();

void main() {

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

clrscr();

printf("\n\n");

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

printf("\t%s\n",*(str+i));

}

printf("\n\n");

printf("Enter the word to search: ");
gets(str1);

printf("\n\nEnter the word to replace: ");
gets(str2);

clrscr();

printf("\nBefore modification:\n\n");

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

printf("\t%s\n",*(str+i));

}

/*******************************************/
/* passing all strings to replace function */
/*******************************************/

printf("\nAfter modification:\n\n");

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

replace(*(str+i),str1,str2);

}

getch();

}

void replace(char *s, char s1[80], char s2[80]) {

int i=0,j=0,k=0;
char temp[100],temp2[100],main[100],*t=temp;


/* copying to temporary string */

while(*s!='\0') {

*t=*s;

t++;
s++;

}

*t='\0';

/**********************/
/* checking each word */
/**********************/


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

temp2[j]=temp[i];

if(temp[i]==' ') {

temp2[j]='\0';

if(strcmpi(temp2,s1)==0) {

strcpy(temp2,s2);

}

j=0;

while(temp2[j]!='\0') {

main[k]=temp2[j];

k++;
j++;
}

main[k]=' ';  /* adding space after each word is copied */

k++;     /* increment so that the next word won't replace the space */

j=-1;

}

i++;
j++;
}

temp2[j]='\0';              /* last word terminated */

if(strcmpi(temp2,s1)==0){    /* checking last word too */

strcpy(temp2,s2);

}

/***************************/
/* last word of the string */
/***************************/

j=0;

while(temp2[j]!='\0') {

main[k]=temp2[j];

k++;
j++;
}

main[k]='\0';   /* new string is completely ready */

printf("\t%s\n",main);       /* printing the new string */

}

------------------------------------------------------------------------------------------------------------

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

Solution:


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

char a[10][10];
char t1[10],t2[10];
int i,j;
clrscr();

printf("\nUnsorted list: \n\n");

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

scanf("%s",a[i]);

}

printf("\n\n");


/* sorting list */
/****************/

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

for(j=i+1;j<10;j++) {

if(a[i][0]>a[j][0]) {     /* testing only first alphabet of each name */

strcpy(t1,a[i]);         /* copying both in two temporary strings */
strcpy(t2,a[j]);

strcpy((a[i]),t2);       /* replacing both from temporary strings */
strcpy(a[j],t1);

}
}
}

/* sorted list */
/***************/

printf("\n\nSorted list: \n\n");

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

printf("\n%s\n",a[i]);

}

getch();

}

--------------------------------------------------------------------------------------------------------------

(c) 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.

Solution:


#include<stdio.h>
#include<conio.h>

void main() {

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

clrscr();


printf("REVERSED strings\n\n\n\n");
/* reversing and printing all strings */

xstrrev(*s);
printf("%s\n\n",*s);

xstrrev(*(s+1));
printf("%s\n\n",*(s+1));

xstrrev(*(s+2));
printf("%s\n\n",*(s+2));


getch();

}

xstrrev( char *s) {

int i=0;
char target[100],*t=target;

/* taking 'i' to the null position */

while(*s!='\0') {

i++;
s++;

}

/* reversing in temporary target string */

while(i>=0) {

s--;

*t=*s;

t++;
i--;

}

*t='\0';

/* reversing original string */

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

*s=target[i];

i++;
s++;

}


return *s;
}

-----------------------------------------------------------------------------------------------------------------

(d) 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.

Solution:


#include<stdio.h>
#include<conio.h>

void main() {


int x=49,y=9,i=1,lastday;
int month,year,a;
void box();

clrscr();

printf("Enter month: ");
scanf("%d",&month);

printf("\n\nEnter year: ");
scanf("%d",&year);

/***********************************************/
/*  starting the program with a condition      */
/***********************************************/


if(month<=12 && month>=1 && year>=1900 && year<=2045) {

x = dayfinder ( month, year );   /* finding the first day of month */

lastday=totaldays(month,year);   /* finding the total days of month */

clrscr();

box(month,year);       /* drawing boxes and headings of calender */


/*************************/
/* printing the calender */
/*************************/


while(i<=lastday) {

gotoxy(x,y);

printf("%2d",i);

i++;
x+=5;

if(x>52) {    /* if the position of 7 days is covered, again print from
 beginning from a new line */

x=22;
y+=2;

 }
}

}

else                /* exit message on wrong input */

printf("\n\nSorry! invalid input...");


gotoxy(1,1);  /* moving cursor out of the calender */

getch();

}

/*********************** main ends ************************/


/**********************************************************/
/* function to find first day of the given month and year */
/**********************************************************/

int dayfinder(int month, int year)

{

int a,day=1;

/* this is a general purpose formula to calculate first day */

a=(14-month)/12;
year=year-a;
month=month+12*a-2;

day=(day+year+(year/4)-(year/100)+(year/400)+((31*month)/12)) % 7;


/* determining the position to print the first day in the calender */

if(day==0)
day=22;

else if(day==1)
day=27;

else if(day==2)
day=32;

else if(day==3)
day=37;

else if(day==4)
day=42;

else if(day==5)
day=47;

else if(day==6)
day=52;

return (day);  /* return the position */

}

/********************************************************/
/* function to draw the boxes, headings of the calender */
/********************************************************/


void box(int m,int y) {


int i,j,k,l;

/*************/
/* inner box */
/*************/

/* corners of inner box */

gotoxy(20,3);
printf("%c",218);

gotoxy(55,3);
printf("%c",191);

gotoxy(55,21);
printf("%c",217);

gotoxy(20,21);
printf("%c",192);

/* boundries of inner box */

for(j=4;j<=20;j++) {

gotoxy(20,j);
printf("%c",179);

gotoxy(55,j);
printf("%c",179);

}


for(i=21;i<=54;i++) {

gotoxy(i,3);
printf("%c",196);

gotoxy(i,21);
printf("%c",196);

}

/*************/
/* outer box */
/*************/

/* corners of outer box */

gotoxy(17,1);
printf("%c",218);

gotoxy(17,23);
printf("%c",192);

gotoxy(58,1);
printf("%c",191);

gotoxy(58,23);
printf("%c",217);

/* boundries of outer box */

for(k=2;k<=22;k++) {

gotoxy(17,k);
printf("%c",179);

gotoxy(58,k);
printf("%c",179);

}


for(l=18;l<=57;l++) {

gotoxy(l,1);
printf("%c",196);

gotoxy(l,23);
printf("%c",196);

}

/********************************************/
/* writing heading on appropriate positions */
/********************************************/


gotoxy(22,6);
printf("Sun");

gotoxy(27,6);
printf("Mon");

gotoxy(32,6);
printf("Tue");

gotoxy(37,6);
printf("Wed");

gotoxy(42,6);
printf("Thu");

gotoxy(47,6);
printf("Fri");

gotoxy(52,6);
printf("Sat");


gotoxy(32,4);

if(m==1)
printf("January %d",y);

if(m==2)
printf("February %d",y);

if(m==3)
printf("March %d",y);

if(m==4)
printf("April %d",y);

if(m==5)
printf("May %d",y);

if(m==6)
printf("June %d",y);

if(m==7)
printf("July %d",y);

if(m==8)
printf("August %d",y);

if(m==9)
printf("September %d",y);

if(m==10)
printf("October %d",y);

if(m==11)
printf("November %d",y);

if(m==12)
printf("December %d",y);

}

/***************************************************/
/* function to determine total days of given month */
/***************************************************/

int totaldays(int m,int y) {

int days;

/* for january */

if(m==1)
days=31;

/* for february */

if(m==2) {

if(y%4==0)
days=29;

else
days=28;

}
/* for march */

if(m==3)
days=31;

/* for april */

if(m==4)
days=30;

/* for may */

if(m==5)
days=31;

/* for june */

if(m==6)
days=30;

/* for july */

if(m==7)
days=31;

/* for august */

if(m==8)
days=31;

/* for september */

if(m==9)
days=30;

/* for october */

if(m==10)
days=31;

/* for november */

if(m==11)
days=30;

/* for december */

if(m==12)
days=31;


return days;
}


----------------------------------------------------------------------------------------------------------------

(e) 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).

Solution:


#include<stdio.h>
#include<conio.h>
#include<dos.h>

/*********************************/
/* function to tackle arrow keys */
/*********************************/

getkey() {

union REGS i,o;

while(!kbhit());

i.h.ah=0;
int86 (22,&i,&o);

return (o.h.ah);

}

void main() {


int x,y,i,lastday,key;
int month,year,a;
void box();

clrscr();

printf("Enter month: ");
scanf("%d",&month);

printf("\n\nEnter year: ");
scanf("%d",&year);

/***********************************************/
/*   starting the program with a condition     */
/***********************************************/


if(month<=12 && month>=1 && year>=1900 && year<=2045)  {

do {


/* if up arrow key is hit */


if(key==72) {

if(year+1 > 2045) {
}
else {
year=year+1;  /* increment of year */
}

}


/* if down arrow key is hit */

if(key==80) {

if(year-1 < 1900) {
}
else {
year=year-1;  /* decrement of year */
}

}


/* if left arrow key is hit */

if(key==75) {

if(month-1 < 1){
}
else {
month=month-1;  /* decrement of month */
}

}


/* if right arrow key is hit */

if(key==77) {

if(month+1 > 12){
}

else {
month=month+1;   /* increment of month */
}

}

x=49,y=9,i=1;             /* calender printing objects */


x = dayfinder(month,year);    /* calculating first day of the month */

lastday = totaldays(month,year);    /* calculating total days of the month*/


clrscr();

box(month,year);       /* drawing boxes and headings of calender */


/*************************/
/* printing the calender */
/*************************/


while(i<=lastday) {

gotoxy(x,y);

printf("%2d",i);

i++;
x+=5;

if(x>52) {    /* if the position of 7 days is covered, again print from
 beginning from a new line */

x=22;
y+=2;

 }
}

gotoxy(1,1);  /* moving cursor away from calender */

key=getkey();     /* taking the arrow key input */

} while(key==72 || key==75 || key==77 || key==80);

}

else
printf("Error! invalid input\n");


getch();

}
/*********************** main ends ************************/


/**********************************************************/
/* function to find first day of the given month and year */
/**********************************************************/

int dayfinder(int month, int year)

{

int a,day=1;

/* this is a general purpose formula to calculate first day */

a=(14-month)/12;
year=year-a;
month=month+12*a-2;

day=(day+year+(year/4)-(year/100)+(year/400)+((31*month)/12)) % 7;


/* determining the position to print the first day in the calender */

if(day==0)
day=22;

else if(day==1)
day=27;

else if(day==2)
day=32;

else if(day==3)
day=37;

else if(day==4)
day=42;

else if(day==5)
day=47;

else if(day==6)
day=52;

return (day);  /* return the position */

}

/********************************************************/
/* function to draw the boxes, headings of the calender */
/********************************************************/


void box(int m,int y) {


int i,j,k,l;

/*************/
/* inner box */
/*************/

/* corners of inner box */

gotoxy(20,3);
printf("%c",218);

gotoxy(55,3);
printf("%c",191);

gotoxy(55,21);
printf("%c",217);

gotoxy(20,21);
printf("%c",192);

/* boundries of inner box */

for(j=4;j<=20;j++) {

gotoxy(20,j);
printf("%c",179);

gotoxy(55,j);
printf("%c",179);

}


for(i=21;i<=54;i++) {

gotoxy(i,3);
printf("%c",196);

gotoxy(i,21);
printf("%c",196);

}

/*************/
/* outer box */
/*************/

/* corners of outer box */

gotoxy(17,1);
printf("%c",218);

gotoxy(17,23);
printf("%c",192);

gotoxy(58,1);
printf("%c",191);

gotoxy(58,23);
printf("%c",217);

/* boundries of outer box */

for(k=2;k<=22;k++) {

gotoxy(17,k);
printf("%c",179);

gotoxy(58,k);
printf("%c",179);

}


for(l=18;l<=57;l++) {

gotoxy(l,1);
printf("%c",196);

gotoxy(l,23);
printf("%c",196);

}

/********************************************/
/* writing heading on appropriate positions */
/********************************************/


gotoxy(22,6);
printf("Sun");

gotoxy(27,6);
printf("Mon");

gotoxy(32,6);
printf("Tue");

gotoxy(37,6);
printf("Wed");

gotoxy(42,6);
printf("Thu");

gotoxy(47,6);
printf("Fri");

gotoxy(52,6);
printf("Sat");


gotoxy(32,4);

if(m==1)
printf("January %d",y);

if(m==2)
printf("February %d",y);

if(m==3)
printf("March %d",y);

if(m==4)
printf("April %d",y);

if(m==5)
printf("May %d",y);

if(m==6)
printf("June %d",y);

if(m==7)
printf("July %d",y);

if(m==8)
printf("August %d",y);

if(m==9)
printf("September %d",y);

if(m==10)
printf("October %d",y);

if(m==11)
printf("November %d",y);

if(m==12)
printf("December %d",y);


/*************************/
/* printing instructions */
/*************************/

gotoxy(60,16);
printf("%c : Next year",30);

gotoxy(60,18);
printf("%c : Previous year",31);

gotoxy(60,20);
printf("%c : Next month",16);

gotoxy(60,22);
printf("%c : Previous month",17);


}

/***************************************************/
/* function to determine total days of given month */
/***************************************************/

int totaldays(int m,int y) {

int days;

/* for january */

if(m==1)
days=31;

/* for february */

if(m==2) {

if(y%4==0)
days=29;

else
days=28;

}
/* for march */

if(m==3)
days=31;

/* for april */

if(m==4)
days=30;

/* for may */

if(m==5)
days=31;

/* for june */

if(m==6)
days=30;

/* for july */

if(m==7)
days=31;

/* for august */

if(m==8)
days=31;

/* for september */

if(m==9)
days=30;

/* for october */

if(m==10)
days=31;

/* for november */

if(m==11)
days=30;

/* for december */

if(m==12)
days=31;


return days;
}


--------------------------------------------------------------------------------------------------------------

(f) A factory has 3 division and stocks 4 categories of products. An inventory table is updated for each division and for each product as they are received. There are three independent suppliers of products to the factory:
(a) Design a data format to represent each transaction.
(b) Write a program to take a transaction and update the inventory.
(c) If the cost per item is also given write a program to calculate the total inventory values.

Solution:


-------------------------------------------------------------------------------------------------------------

(g) A dequeue is an ordered set of elements in which elements may be inserted or retrieved from either end. Using an array simulate a dequeue of characters and the operations retrieve left, retrieve right, insert left, insert right. Exceptional conditions such as dequeue full or empty should be indicated. Two pointers (namely, left and right) are needed in this simulation.

Solution:

NOTE: Topic not discussed in the book. I am learning from other resources.
---------------------------------------------------------------------------------------------------------------

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

Solution:


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

char s[80];
int i=0;

clrscr();

gets(s);

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

if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u') {
putch(' ');
}

else
putch(s[i]);
i++;
}

getch();
}

---------------------------------------------------------------------------------------------------------------

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

Solution:


#include<stdio.h>
#include<conio.h>
#include<string.h>

void replace();

void main() {

char str[80],str1[]="the";
clrscr();

gets(str);

replace(str,str1);

getch();

}
void replace(char *s, char s1[80]) {

int i=0,j=0,k=0;
char temp[100],temp2[100],main[100],*t=temp;


/* copying to temporary string */

while(*s!='\0') {

*t=*s;

t++;
s++;

}

*t='\0';

/**********************/
/* checking each word */
/**********************/


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

temp2[j]=temp[i];

if(temp[i]==' ') {

temp2[j]='\0';

if(strcmpi(temp2,s1)==0) {

}

else {
j=0;

while(temp2[j]!='\0') {

main[k]=temp2[j];

k++;j++;
}

main[k]=' ';  /* adding space after each word is copied */

k++;     /* increment so that the next word won't replace the space */
}
j=-1;

}

i++;
j++;
}

temp2[j]='\0';              /* last word terminated */

if(strcmpi(temp2,s1)==0){    /* checking last word too */

}

/***************************/
/* last word of the string */
/***************************/

else {

j=0;

while(temp2[j]!='\0') {

main[k]=temp2[j];

k++;
j++;
}

main[k]='\0';   /* new string is completely ready */

}
printf("%s\n",main);       /* printing the new string */

}

---------------------------------------------------------------------------------------------------------------

(j) 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.

Solution:

#include<stdio.h>
#include<conio.h>
#include<string.h>

void abbr();

void main() {

char s1[10][80];
int i=0;

clrscr();

printf("\tEnter 10 names: \n\n\n");

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

gets(s1[i]);    /* saving names in 2d string */

}

clrscr();

printf("\tAbbreviated names: \n\n");

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

abbr(s1[i]);            /* sending each name to function */

printf("\n\n");

}

getch();

}

void abbr( char s1[100]) {

char s2[30];
int i=0,j=0;

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

s2[j]=s1[i];

if(s1[i]==' ') {      /* if space is detected then it's not last name */

printf(" %c",toupper(s2[0]));  /* printing first character of name after
 converting to uppercase */
j=-1;

}

j++;
i++;
}
    /* printing the last name */
s2[j]='\0';
printf(" %s",s2);

}

--------------------------------------------------------------------------------------------------------------

(k) 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. 

Solution:


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

char a[10000],i=0,suc=0;
clrscr();

printf("enter the line of text (string): \n\n");

gets(a);


printf("\n\n\n\ntwo vowels in succesion are: \n\n");

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

if(a[i]=='a'|| a[i]=='e'|| a[i]=='i'|| a[i]=='o'||a[i]=='u' ) {

if(a[i+1]=='a'|| a[i+1]=='e'|| a[i+1]=='i'|| a[i+1]=='o'|| a[i+1]=='u') {

suc++;
printf("%c%c  ",a[i],a[i+1]);
}
}
i++;
}

printf("\n\n\noccurence of two vowels in succesion = %2d ",suc);


getch();
}

______________________________________________________________________

3 comments:

  1. Extracts parts of a strings very simple and easy way ::::

    #include
    #include
    #include
    main()
    {
    char st[100];
    int pos, ch,i;
    printf("\Enter the string\n\ ");
    gets(st);

    printf("\n\Enter the specific position\n");
    scanf("%d", &pos);

    printf("\n\n\Enter the characters that extracts\n");
    scanf("%d", &ch);

    if(ch == 0)
    {
    printf("%s",st);
    }
    else if ( ch != 0 )
    {
    printf("\nThe charachters extract is\n");
    for ( i=0; i<ch; i++)
    {
    if( i < pos)
    printf("\%c",st[pos+i] );
    }
    }
    }

    ReplyDelete

Let Us C / Chapter 7 (The C Pre-processor)

                               Exercise [C] (a) Write down macro definitions for the following: 1. To test whether a character ente...