let us c solutions ( by chetan )

822
Let us C solutions ( By Chetan ) http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM] will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here. Let us C solutions ( By Chetan ) Monday, 3 February 2014 Drawing a hut using graphics NOTE: please change the "initgraph" path of BGI directory according to your turbo C++ IDE's directory. #include<graphics.h> void main() { int gd=DETECT,gm; initgraph(&gd,&gm,"c:\\turboc3\\bgi"); line(200,100,170,200); line(200,100,250,200); line(200,100,400,100); line(400,100,450,200); line(450,200,250,200); line(178,176,178,277); line(245,190,245,300); line(440,200,440,300); line(440,300,245,300); line(245,300,178,277); line(210,288,210,215); line(190,280,190,215); line(190,215,210,215); rectangle(300,210,380,260); setfillstyle(5,RED); floodfill(399,101,WHITE); setfillstyle(SOLID_FILL,WHITE^23); floodfill(299,209,WHITE); Chetan Raikwar 2 have me in circles View all Add to circles Google+ Followers Chetan Raikwar Follow 2 This is Chetan Raikwar, Living in Jabalpur, M.P. India. View my complete profile About Me 2014 (16) January (14) February (2) Dynamic calender animated without graphics library... Drawing a hut using graphics Blog Archive More Next Blog» Create Blog Sign In

Upload: muhammad-shuaib

Post on 28-Dec-2015

489 views

Category:

Documents


12 download

DESCRIPTION

LEt us c solutions

TRANSCRIPT

Page 1: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Monday, 3 February 2014

Drawing a hut using graphics

NOTE: please change the "initgraph" path of BGI directory according to your turbo C++ IDE's directory.

#include<graphics.h>void main() {

int gd=DETECT,gm;

initgraph(&gd,&gm,"c:\\turboc3\\bgi");

line(200,100,170,200);line(200,100,250,200);line(200,100,400,100);line(400,100,450,200);line(450,200,250,200);line(178,176,178,277);line(245,190,245,300);line(440,200,440,300);line(440,300,245,300);line(245,300,178,277);line(210,288,210,215);line(190,280,190,215);line(190,215,210,215);

rectangle(300,210,380,260);

setfillstyle(5,RED);floodfill(399,101,WHITE);

setfillstyle(SOLID_FILL,WHITE^23);floodfill(299,209,WHITE);

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

► January (14)

▼ February (2)

Dynamic calender animated without graphics library...

Drawing a hut using graphics

Blog Archive

More Next Blog» Create Blog Sign In

Page 2: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

Posted by Chetan Raikwar at 11:11 No comments:

floodfill(179,275,WHITE);

setfillstyle(SOLID_FILL,BLACK^9);floodfill(191,216,WHITE);

floodfill(379,258,WHITE);

setcolor(BLACK);settextstyle(8,HORIZ_DIR,3);outtextxy(200,200,"Chetan Raikwar");

setcolor(BLUE);setfillstyle(CLOSE_DOT_FILL,BLUE);floodfill(0,0,WHITE);getch();closegraph();restorecrtmode();

}

+1 Recommend this on Google

Dynamic calender animated without graphics library

#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=2,year=2014,a;

Page 3: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

void box();

clrscr();

/***********************************************//* 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) {

sound(1400);delay(20);sound(750);delay(10);nosound();

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

}

/* if down arrow key is hit */

if(key==80) {

sound(1400);delay(20);sound(850);delay(10);nosound();

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

}

/* if left arrow key is hit */

if(key==75) {

sound(1600);delay(20);sound(1250);delay(10);nosound();

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

}

/* if right arrow key is hit */

if(key==77) {

sound(1600);

Page 4: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

delay(20);sound(1250);delay(10);

nosound();

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);

if(x==22)textcolor(RED);

elsetextcolor(YELLOW);

cprintf("%2d",i);

i++;x+=5;

if(x>52) { /* if the position of 7 days is covered, again print frombeginning 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);

}

elseprintf("Error! invalid input\n");

getch();

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

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

Page 5: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

/**********************************************************/

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 *//*************/

textcolor(BLUE);/* corners of inner box */

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

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

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

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

/* boundries of inner box */

Page 6: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

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

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

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

}

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

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

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

}

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

/* corners of outer box */

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

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

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

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

/* boundries of outer box */

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

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

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

}

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

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

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

}

textcolor(GREEN+BLINK);gotoxy(24,22);cprintf("%c%c%c%c %c%c %c%c%c%c%c%c%c%c%c%c%c%c%c",77,65,68,69,66,89,67,72,69,84,65,78,82,65,73,75,87,65,82);

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

Page 7: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

textcolor(RED);

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

textcolor(YELLOW);

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

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

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

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

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

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

textcolor(LIGHTGREEN);

gotoxy(32,4);

if(m==1)cprintf("January ");

if(m==2)cprintf("February ");

if(m==3)cprintf("March ");

if(m==4)cprintf("April ");

if(m==5)cprintf("May ");

if(m==6)cprintf("June ");

if(m==7)cprintf("July ");

if(m==8)cprintf("August ");

if(m==9)cprintf("September ");

if(m==10)cprintf("October ");

if(m==11)cprintf("November ");

if(m==12)cprintf("December ");

textcolor(CYAN);cprintf("%d",y);/*************************//* printing instructions *//*************************/

Page 8: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

textcolor(BROWN);

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

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

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

gotoxy(60,22);cprintf("%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;

elsedays=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 */

Page 9: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

Posted by Chetan Raikwar at 10:55 No comments:

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;}

+1 Recommend this on Google

Thursday, 30 January 2014

Let Us C / Chapter 14 (Operations on Bits)

(a) The information about colors is to be stored in bits of a char variable called color. The bit number 0 to 6, each represent 7 colors of a rainbow, i.e. bit 0 represents violet, 1 representsindigo, and so on. Write a program that asks the user to enter a number and based on this number it reports which colors in the rainbow does the number represents.

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

char color; int num;

clrscr();

printf("Please enter the number(0-6): "); scanf("%d",&num);

color=1<<num;

printf("\n\n");

if(num==0 && color==1) printf("Violet");

else if(num==1 && color==2) printf("Indigo");

else if(num==2 && color==4) printf("Blue");

Exercise [A]

Solution:

Page 10: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

else if(num==3 && color==8) printf("Green");

else if(num==4 && color==16) printf("Yellow");

else if(num==5 && color==32) printf("Orange");

else if(num==6 && color==64) printf("Red");

else printf("Wrong color number!");

getch();

}

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

(b) A company planning to launch a new newspaper in market conducts a survey. The various parameters considered in the survey were, the economic status (upper, middle, and lower class) the languages readers prefer (English, Hindi, Regional language) and category of paper (daily, supplement, tabloid). Write a program, which reads data of 10 respondents through keyboard, and stores the information in an array of integers. The bit-wise information to be stored in an integer is given below:Bit Number Information0 Upper class1 Middle class2 Lower class3 English4 Hindi5 Regional Language6 Daily7 Supplement8 TabloidAt the end give the statistical data for number of persons who read English daily, number of upper class people who read tabloid and number of regional language readers.

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

int arr[10][3],i,j; unsigned int infr; int eng=0,utab=0,rgl=0;

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

clrscr();

gotoxy(20,2); printf("Enter data of respondent %d:\n\n",i+1);

for(j=0;j<3;j++) {

Solution:

Page 11: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

if(j==0){ printf("Economic Status:\n\n"); printf("0: Upper class\t1: Middle class\t2: Lower class\n\n");

scanf("%d",&arr[i][j]); }

if(j==1){ printf("\n\nLanguage Preferred:\n\n"); printf("3: English\t4: Hindi\t5:Regional Language\n\n");

scanf("%d",&arr[i][j]); }

if(j==2){

printf("\n\nType of Paper:\n\n"); printf("6: Daily\t7: Supplement\t8: Tabloid\n\n");

scanf("%d",&arr[i][j]); }

} }

/***********************************************/ /* converting the whole array using left shift */ /***********************************************/

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

for(j=0;j<3;j++) {

arr[i][j]= 1 << arr[i][j]; /* conversion */

} }

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

if(arr[i][1]==8) /* english readers */ eng++;

if(arr[i][0]==1 && arr[i][2]==256) /* upper class,tabloid readers */ utab++;

if(arr[i][1]==32) /* regional language readers */ rgl++; }

clrscr();

gotoxy(20,2); printf("Reader's statistics:\n\n\n\n"); printf("\tEnglish Reader: %d\n",eng); printf("\tUpper class Tabloid Readers: %d\n",utab); printf("\tRegional Language readers: %d\n",rgl); getch();

}

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

(c) In an inter-college competition, various sports and games are played between different colleges like cricket, basketball, football,

Page 12: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

hockey, lawn tennis, table tennis, carom and chess. The information regarding the games won by a particular college is stored in bit numbers 0, 1, 2, 3, 4, 5, 6, 7 and 8 respectively of an integer variable called game. The college that wins in 5 or more than 5 games is awarded the Champion of Champions trophy. If a number is entered through the keyboard, then write a program to find out whether the college won the Champion of the Champions trophy or not, along with the names of the games won by the college.

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

int game; int i,won=0,name;

clrscr();

printf("Enter number: ");

scanf("%d",&name);

printf("\n\n");

for(i=1;i<=8;i++) {

game=i&name;

if(game==1) { printf("Cricket\n");

won++; }

if(game==2) { printf("Basketball\n");

won++; }

if(game==3) { printf("Football\n");

won++; }

if(game==4) { printf("Hockey\n");

won++; }

if(game==5) { printf("Lawn-tennis\n");

won++; }

if(game==6) { printf("Table-tennis\n");

won++; }

Solution:

Page 13: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

if(game==7) { printf("Carrom\n");

won++; }

if(game==8) { printf("Chess\n");

won++; }

}

if(won>=5) {

printf("\n\n\nCollege %d has won the champions trophy\n",name);

}

else {

printf("\n\n\nCollege %d didn't win the champions trophy\n",name);

}

getch(); }

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

(d) An animal could be either a canine (dog, wolf, fox, etc.), a feline (cat, lynx, jaguar, etc.), a cetacean (whale, narwhal, etc.) or a marsupial (koala, wombat, etc.). The information whether a particular animal is canine, feline, cetacean, or marsupial is stored in bit number 0, 1, 2 and 3 respectively of a integer variable called type. Bit number 4 of the variable type stores the information about whether the animal is Carnivore or Herbivore.For the following animal, complete the program to determine whether the animal is a herbivore or a carnivore. Also determine whether the animal is a canine, feline, cetacean or a marsupial.struct animal{char name[30] ;int type ;}struct animal a = { "OCELOT", 18 } ;

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

struct animal { char name[30]; int type; };

struct animal a={"OCELOT",18};

Solution:

Page 14: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

int t1,t2,typ1,typ2;

clrscr();

t1= a.type >> 3;

typ1= t1 & 2; /* checking the bit after shifting */

t2= t1 << 3;

typ2= t2 & 16; /* checking another bit after shifting */

/**********************************************************/ /* checking if ocelot is canine/feline/cetacean/marsupial */ /**********************************************************/

if(typ1==1) printf("\n\nOCELOT is Canine\n");

if(typ1==2) printf("\n\nOCELOT is Feline\n");

if(typ1==4) printf("\n\nOCELOT is Cetacean\n");

if(typ1==8) printf("\n\nOCELOT is Marsupial\n");

/************************************************/ /* checking if ocelot is carnivore or herbivore */ /************************************************/

if(typ2!=0) printf("\n\nOCELOT is Carnivore\n");

if(typ2==0) printf("\n\nOCELOT is Herbivore\n");

getch();

}

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

(e)The time field in the directory entry is 2 bytes long. Distribution of different bits which account for hours, minutes and seconds is given below. Write a function which would receive the two-byte time entry and return to the calling function, the hours, minutes and seconds. 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 H H H H H M M M M M M S S S S S

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

unsigned hr,mn,sc,input;

void timer();

Solution:

Page 15: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

clrscr();

printf("Enter the time entry: ");

scanf("%d",&input);

timer(input,&hr,&mn,&sc);

printf("\n\nTIME: %u : %u : %u\n",*(&hr),*(&mn),*(&sc));

getch();

}

void timer(unsigned time, unsigned *hr, unsigned *mn, unsigned *sc) {

*hr=time >> 11;

*mn=(time<<5) >> 10;

*sc=(time<<11) >> 11;

}

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

(f) In order to save disk space information about student is stored in an integer variable. If bit number 0 is on then it indicates Ist year student, bit number 1 to 3 stores IInd year, IIIrd year and IVth year student respectively. The bit number 4 to 7 stores stream Mechanical, Chemical, Electronics and IT. Rest of the bits store room number. Based on the given data, write a program that asks for the room number and displays the information about the student, if its data exists in the array. The contents of array are,int data[ ] = { 273, 548, 786, 1096 } ;

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

void main() {

unsigned int yr,br,data_yr,data_br; int i,j,k,rn,a,b,flag=0; int data[]={ 273,548,786,1096};

clrscr();

printf("Enter room number: "); scanf("%d",&rn);

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

/*********************/ /* checking for year */ /*********************/

for(i=1;i<=8;i=i*2) {

yr= rn & i;

Solution:

Page 16: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

if(yr==1) { printf("First year"); break; }

if(yr==2) { printf("Second year"); break; }

if(yr==4) { printf("Third year"); break; }

if(yr==8) { printf("Fourth year"); break; }

}

/***********************/ /* Checking for branch */ /***********************/

printf("\n\nBranch: ");

for(i=16;i<=128;i=i*2) {

br= rn & i;

if(br==16) { printf("Mechanical"); break; }

if(br==32) { printf("Chemical"); break; }

if(br==64) { printf("Electronics"); break; }

if(br==128) { printf("I.T."); break; }

}

/***********************************************/ /* checking if data matches with that of array */ /***********************************************/

for(i=1,j=16;i<=8,j<=128;i=i*2,j=j*2) {

yr=rn&i;

br=rn&j;

for(k=0,a=1,b=16;k<4,a<=8,b<=128;k++,a=a*2,b=b*2) {

data_yr=data[k] & a;

Page 17: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

Posted by Chetan Raikwar at 07:05 No comments:

data_br=data[k] & b;

if(yr==data_yr && br==data_br) {

flag+=1;

break;

}

}

}

if(flag==0) printf("\n\n\ndata doesn't matche with the array.\n");

else printf("\n\n\ndata matches with the array.\n");

getch(); }______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 13 (More Issues in Input Output)

(a) Write a program to carry out the following:(a) Read a text file provided at command prompt(b) Print each word in reverse orderFor example if the file containsINDIA IS MY COUNTRYOutput should beAIDNI SI YM YRTNUOC

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

void main(int argc, char *argv[]) {

FILE *fs;char ch,s[80];void rev();

if(argc!=2) {

printf("File name not supplied\n");

exit();

}

fs=fopen(argv[1],"r");

Exercise [B]

Solution:

Page 18: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

if(fs==NULL) {

printf("File not found!");

exit();}

while(fgets(s,79,fs)!=NULL)rev(s);

fclose(fs);

}

void rev(char s1[80]) {

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

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

s2[j]=s1[i];

if(s1[i]==' ' || s1[i]=='\0') {

s2[j]='\0';

strrev(s2);

printf("%s ",s2);

j=-1;

}

i++;j++;}

s2[j]='\0';

printf("%s",strrev(s2));

}

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

(b) Write a program using command line arguments to search for a word in a file and replace it with the specified word. The usage of the program is shown below.C> change <old word> <new word> <filename>

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

void replace();

void main ( int argc, char *argv[] ) {

FILE *fp,*ft;char str[80],str1[30],str2[30],nwstr[100];

clrscr();

if(argc!=4) {

Solution:

Page 19: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

puts("Improper argements passed!");exit();}

strcpy(str1,argv[1]);strcpy(str2,argv[2]);

fp=fopen(argv[3],"r");

if(fp==NULL) {

puts("cannot open source file!");exit();}

ft=fopen("NEW.TXT","w+");

if(ft==NULL) {

puts("cannot open target file!");exit();}

while(fgets(str,79,fp)!=NULL) {

replace(str,str1,str2,&nwstr);

fputs(nwstr,ft);}

fclose(fp);fclose(ft);

remove("FILE.TXT");rename("NEW.TXT","FILE.TXT");

printf("\n\nTask completed!\n\n");

getch();

}

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

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

/*******************************//* copying to temporary string *//*******************************/

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

*t=*s;

t++;s++;

}

*t='\0';

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

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

Page 20: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

temp2[j]=temp[i];

if(temp[i]==' ' || temp[i]==',' || 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 */

/******************************************************************//* preparing new string to return to main and printing it on file *//******************************************************************/

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

*n=*m;

n++;m++;}

Page 21: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

*n='\0';

}

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

(c) Write a program that can be used at command prompt as a calculating utility. The usage of the program is shown below.C> calc <switch> <n> <m>Where, n and m are two integer operands. switch can be any one of the arithmetic or comparison operators. If arithmetic operator is supplied, the output should be the result of the operation. If comparison operator is supplied then the output should be True or False.

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

void main(int argc, char *argv[]) {

int n,m,calc;

clrscr();

if(argc!=4)printf("Improper number of arguments");

/* converting both operands to integers */

n=atoi(argv[2]);

m=atoi(argv[3]);

printf("\n\nOutput: ");

/* comparing the operators passed at command prompt */

if(strcmp("+",argv[1])==0) {

printf("%d\n\n",n+m);

}

if(strcmp("-",argv[1])==0) {

printf("%d\n\n",n-m);

}

if(strcmp("*",argv[1])==0) {

printf("%d\n\n",n*m);

}

if(strcmp("/",argv[1])==0) {

printf("%d\n\n",n/m);

Solution:

Page 22: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

Posted by Chetan Raikwar at 07:05 No comments:

}

if(strcmp("%",argv[1])==0) {

printf("%d\n\n",n%m);

} /* IMPORTANT */

/* I have used dedicated variable for '<' and '>' comparison operators *//* because at command prompt, these are redirecting operators and cannot *//* be used simply for comparison. */

/* 1: "<" = "less" */ /* 2: ">" = "greater" */ /* type "less" for "<" and "greater" for ">" respectively if you want to perform comparison */

if(strcmp("greater",argv[1])==0) {

if(n>m)printf("True\n\n");

if(n<m)printf("False\n\n");

}

if(strcmp("less",argv[1])==0) {

if(n<m)printf("True\n\n");

if(n>m)printf("False\n\n");

}

if(strcmp("=",argv[1])==0) {

if(n==m)printf("True\n\n");

elseprintf("False\n\n");

}

}

_______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 11 (Console Input Output) Exercise [D]

Page 23: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

(a) Write down two functions xgets( ) and xputs( ) which work similar to the standard library functions gets( ) and puts( ).

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

void xgets();void xputs();

void main() {

char str[80];clrscr();

xgets(str);

printf("\n");

xputs(str);

getch();

}

void xgets( char *s) {

int i=0;char ch;

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

ch=getche();

if(ch=='\r') {

*s='\0';break;}

if(ch=='\b') {

printf("\b");

i-=2;s-=2;}

else {

*s=ch;s++;

}

}

}

void xputs( char *s) {

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

putch(*s);

Solution:

Page 24: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

Posted by Chetan Raikwar at 07:04 No comments:

s++;

}

}

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

(b) Write down a function getint( ), which would receive a numeric string from the keyboard, convert it to an integer number and return the integer to the calling function. A sample usage of getint( ) is shown below:main( ){int a ;a = getint( ) ;printf ( "you entered %d", a )}

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

int a; char s[80];

printf("Enter any numeric string: "); gets(s);

a=getint(s); /* converting and receiving string as integer */

printf("\n\nYou entered = %d\n",a);

getch();

}

int getint(char s1[80]) {

int digit;

digit=atoi(s1); /* converting string to integer */

return digit;

}

______________________________________________________________________

Solution:

Recommend this on Google

Let Us C / Chapter 10 (Structures)

(a) Create a structure to specify data on students given below:Roll number, Name, Department, Course, Year of joining

Exercise [D]

Page 25: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

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.

/* NOTE: since number of students to be assumed is too much ( about 450 )I have alloted full size (about 450) to it but array has been kept empty,if you have time then you can fill up all 450 names and can search throughthem.program has been tested by me and it works accurately. you can reducethe size of array of structure conveniently by changing the value of N */

#include<stdio.h>#include<conio.h>#define N 450

struct students { int rlnm; char name[25]; char dept[25]; /* structure defined outside of main(); */ char course[25]; int year; };

void main() { /* main() */

struct students s[N];int i,ch;

clrscr();

/* taking input of 450 students in an array of structure */

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

printf(" Enter data of student %d\t\t\t\ttotal students: %d\n",i+1,N);printf("****************************\n\n");

printf("enter rollnumber: ");scanf("%d",&s[i].rlnm);

printf("\n\nenter name: ");scanf(" %s",&s[i].name);

printf("\n\nenter department: ");scanf("%s",&s[i].dept);

printf("\n\nenter course: ");scanf("%s",&s[i].course);

printf("\n\nenter year of joining: ");scanf("%d",&s[i].year);

clrscr();

}

/* displaying a menu */

printf("\n\tenter your choice: \n");printf("\t**********************\n\n");

printf("1: enter year to search all students who took admission in that:\n\n");printf("2: enter roll number to see details of that student\n\n\n");

printf("your choice: "); /* taking input of your choice */

Solution:

Page 26: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

scanf("%d",&ch);

clrscr();

switch(ch) {

case 1: clrscr();

dispyr(&s); /* function call to display names of students who joined in\ a particular year */

break;

case 2: clrscr();

disprl(&s); /* function call to display information of a student \ whose roll number is given */

break;

default:

printf("\n\nerror! wrong choice");

}

getch();

}/******************* main() ends **************/

dispyr(struct students *a) { /* function for displaying names of students\ who took admission in a particular year */

int j,yr;

printf("\nenter year: ");scanf("%d",&yr);

printf("\n\nthese students joined in %d\n\n",yr);

for(j=0;j<N;j++) {

if(a[j].year==yr) {

printf("\n%s\n",a[j].name);}

}return 0;}

disprl(struct students *a) { /* function to print information of a\ student whose roll number has been \ given. */

int k,rl;

printf("\nenter roll number: ");scanf("%d",&rl);

for(k=0;k<N;k++) {

if(a[k].rlnm==rl) {

printf("\n\n\t Details of roll number: %d\n",a[k].rlnm);printf("\t***************************\n\n");printf(" Name: %s\n",a[k].name);

Page 27: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

printf(" Department: %s\n",a[k].dept);printf(" Course: %s\n",a[k].course);printf("Year of joining: %d",a[k].year);

break;}

else {printf("\nRoll number you entered does not exist\n\n");

break;}

}

return 0;}

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

(b) 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”.

/* NOTE: since number of customers to be assumed is too much ( about 200 ) I have alloted full size (about 200) to it but array has been kept empty, if you have time then you can fill up all 200 names and can search through them.program has been tested by me and it works accurately. you can reducethe size of array of structure conveniently by changing the value of N */

#include<stdio.h> #include<conio.h> #define N 200

struct bank { int acn; char name[20]; int bal; /* defined out of main() */ };

void main() {

struct bank b[N];

int i,ch,lw=100,ch2,ac,am;

clrscr();

for(i=0;i<N;i++) { /* inputting customer data */

printf("\tEnter information of customers \n"); printf("\t******************************\n\n");

Solution:

Page 28: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

printf("enter account no.: "); scanf("%d",&b[i].acn);

printf("\n\nenter customer name: "); scanf("%s",&b[i].name);

printf("\n\nenter balance: "); scanf("%d",&b[i].bal);

clrscr();

}

clrscr();

printf("\tEnter your choice\n"); /* further processing of transaction */ printf("\t*****************\n\n");

printf("1: to know whose balance is below 100.\n\n"); printf("2: to process request or withdrawl.\n\n\n");

scanf("%d",&ch);

switch(ch) {

case 1:

clrscr();

disp(&b); /* displaying whose balance is below 100 */

break;

case 2:

clrscr();

printf("enter your account number: "); scanf("%d",&ac);

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

if((b[i].acn)==ac) {

clrscr();

printf("\tHello %s\n",b[i].name); printf("\n\n");

printf("\n\nenter your choice\n"); printf("\n1: deposite:\n"); printf("\n0: withdrawl:\n\n"); scanf("%d",&ch2);

switch(ch2) {

case 0:

clrscr();

if(b[i].bal<lw) {

printf("\n\nsorry! account balance is too low for withdrawl.\n");

break; }

Page 29: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

else {

printf("\n\nenter amount for withdrawl: "); scanf("%d",&am);

}

if(b[i].bal<am) {

printf("\n\nyou don't have enough balance for withdrawl.\n");

}

else {

b[i].bal=b[i].bal+am;

printf("\n\nwithdrawl was successful.\n");

} break;

case 1:

clrscr();

printf("\n\nenter amount to deposite: "); scanf("%d",&am);

b[i].bal=b[i].bal+am;

printf("\n\ncash deposited successfully.\n\n");

break;

}

} } } getch(); }

disp(struct bank *a) {

int k;

printf("\tCustomers whose balance is below 100:\n"); printf("\t*************************************\n\n");

for(k=0;k<N;k++) {

if((a[k].bal)<100) {

printf("%2d\t%s\n",a[k].acn,a[k].name);

} } return 0;

}

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

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

Page 30: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

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.

#include<stdio.h> #include<conio.h> struct automob { char name[5]; int year; char mtr[10]; int qty; }; void main() {

struct automob a[54]={{"AA1",2009,"AAA",10}, {"AA2",2009,"AAA",10}, {"AA3",2009,"AAA",10}, {"AA4",2009,"AAA",10}, {"AA5",2009,"AAA",10}, {"AA6",2009,"AAA",10}, {"AA7",2009,"AAA",10}, {"AA8",2009,"AAA",10}, {"AA9",2009,"AAA",10}, {"BB1",2010,"BBB",11}, {"BB2",2010,"BBB",11}, {"BB3",2010,"BBB",11}, {"BB4",2010,"BBB",11}, {"BB5",2010,"BBB",11}, {"BB6",2010,"BBB",11}, {"BB7",2010,"BBB",11}, {"BB8",2010,"BBB",11}, {"BB9",2010,"BBB",11}, {"CC1",2011,"CCC",12}, {"CC2",2011,"CCC",12}, {"CC3",2011,"CCC",12}, {"CC4",2011,"CCC",12}, {"CC5",2011,"CCC",12}, {"CC6",2011,"CCC",12}, {"CC7",2011,"CCC",12}, {"CC8",2011,"CCC",12}, {"CC9",2011,"CCC",12}, {"DD1",2012,"DDD",13}, {"DD2",2012,"DDD",13}, {"DD3",2012,"DDD",13}, {"DD4",2012,"DDD",13}, {"DD5",2012,"DDD",13}, {"DD6",2012,"DDD",13}, {"DD7",2012,"DDD",13}, {"DD8",2012,"DDD",13}, {"DD9",2012,"DDD",13}, {"EE1",2013,"EEE",14}, {"EE2",2013,"EEE",14}, {"EE3",2013,"EEE",14}, {"EE4",2013,"EEE",14}, {"EE5",2013,"EEE",14}, {"EE6",2013,"EEE",14}, {"EE7",2013,"EEE",14}, {"EE8",2013,"EEE",14}, {"EE9",2013,"EEE",14}, {"FF1",2014,"FFF",15}, {"FF2",2014,"FFF",15}, {"FF3",2014,"FFF",15}, {"FF4",2014,"FFF",15},

Solution:

Page 31: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

{"FF5",2014,"FFF",15}, {"FF6",2014,"FFF",15}, {"FF7",2014,"FFF",15}, {"FF8",2014,"FFF",15}, {"FF9",2014,"FFF",15}};

int i,j,k;

clrscr();

printf("Information of parts between BB1 to CC6:\n\n");

printf("\n\nName\t\tyear(manu.)\t\tmaterial\tquantity\n\n\n");

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

if(i>=9 && i<=23) { printf("%3s\t\t%4d\t\t\t%5s\t\t%4d\n",a[i].name,a[i].year,a[i].mtr,a[i].qty);

} }

getch(); }

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

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

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

void main() {

struct cricketer { char name[50]; int age; int match; float avrn; }; struct cricketer c[20],temp; int i,j; clrscr();

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

printf("Enter data of cricketer %d\n\n\n",i+1);

fflush(stdin); printf("Name: "); gets(c[i].name);

Solution:

Page 32: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

printf("\n\nAge: "); scanf("%d",&c[i].age);

printf("\n\nMatches: "); scanf("%d",&c[i].match);

printf("\n\nAverage runs: "); scanf("%f",&c[i].avrn);

clrscr();

}

/*******************/ /* sorting records */ /*******************/

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

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

if(c[i].avrn > c[j].avrn) {

temp=c[i]; c[i]=c[j]; c[j]=temp; } } }

printf("Sorted records:\n\n");

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

printf("%d\t%s\t%d\t%d\t%f\n\n\n",i+1,c[i].name,c[i].age,c[i].match,c[i].avrn);

}

getch(); }

linkfloat() {

float a=0,*b;

b=&a; a=*b;

return 0; }

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

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

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

Solution:

Page 33: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

struct employee { int code; char name[20]; int dd,mm,yy; } e[N];

int d,m,y,i;clrscr();

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

printf("\tEnter employee data:\n");printf("\t*********************\n");

printf("\nEnter employee code: ");scanf("%d",&e[i].code);

printf("\n\nEnter employee name: ");scanf("%s",&e[i].name);

printf("\n\nEnter date of joining (dd mm yy): ");scanf("%d%d%d",&e[i].dd,&e[i].mm,&e[i].yy);

clrscr();

}

clrscr();

printf("\nenter current date(dd mm yy): \n\n");scanf("%d%d%d",&d,&m,&y);

clrscr();

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

if((y-(e[i].yy))>=3) {

printf("%s\n\N",e[i].name);

}

}

getch();}

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

(f) Write a menu driven program that depicts the working of a library. The menu options should be:1. Add book information2. Display book information3. List all books of given author4. List the title of specified book5. List the count of books in the library6. List the books in the order of accession number7. ExitCreate 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.

Solution:

Page 34: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

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

void main() {

struct library { int acn; char title[25]; char auth[25]; float price; int flag; };

struct library a[5]={ {2,"AAA","AAA",154.8,1}, {1,"BBB","BBB",124.6,0}, {5,"EEE","EEE",234.3,0}, {3,"CCC","CCC",232.3,1}, {4,"DDD","DDD",121.3,0} };

struct library temp; /* temporary structure to overwrite information / and for assistance in sorting the whole structure */

int i,ch,k,flag,j=0; char author[10];

clrscr();

while(1) { /* initialized an indefinite loop */

clrscr(); printf("\t1: Add book information\n"); printf("\t2: Display book information\n"); printf("\t3: List all books of given author\n"); printf("\t4: List the title of specified book\n"); printf("\t5: List the count of books in the library\n"); printf("\t6: List the books in order of accesion number\n"); printf("\t7: Exit\n\n\n");

printf("Choice: "); scanf("%d",&ch);

switch(ch) {

case 1: /* adding book information over current information */

clrscr();

printf("\t\t1: Add book information:\n\n\n");

printf("enter book information:\n\n");

printf("Accesion number of book to be modified: "); scanf("%d",&j); fflush(stdin);

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

if(j==a[i].acn) {

printf("\n\nenter new information:\n\n"); printf("accesion no.: "); scanf("%d",&temp.acn); fflush(stdin);

Page 35: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

printf("\n\ntitle: "); scanf("%s",&temp.title); fflush(stdin); printf("\n\nauthor: "); scanf("%s",&temp.auth); fflush(stdin); printf("\n\nprice: "); scanf("%f",&temp.auth); fflush(stdin); printf("\n\nflag(1/0): "); scanf("%d",&temp.flag); fflush(stdin);

} }

a[j]=temp; /* overwriting current information with new one */

clrscr();

printf("\n\nInformation added succesfully!\n\n");

delay(2000);

break;

case 2: /* displaying current book information */

clrscr();

printf("\t\t2: Display book information:\n\n\n");

printf("Enter accesion number: "); scanf("%d",&k);

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

if(k==a[i].acn) { clrscr(); printf("Book information: \n\n"); printf("\n\nAccesion Number: %d",a[i].acn); printf("\nTitle: %s",a[i].title); printf("\nAuthor: %s",a[i].auth); printf("\nPrice: %f",a[i].price);

if(a[i].flag==0) { printf("\nFlag: Not issued\n\n"); } else{ printf("\nFlag: Issued\n\n"); } } } delay(1000);

break;

case 3: /* listing all books of given author */

clrscr();

printf("\t\t3: List all books of given author:\n\n\n");

printf("Enter author name: "); scanf("%s",&author); fflush(stdin);

printf("\n\nbooks of %s\n\n",author); for(i=0;i<5;i++) {

k=strcmp(author,a[i].auth);

Page 36: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

if(k==0) { j=j+1; printf("%d.\t%s\n",j,a[i].title);

} } delay(2000); break;

case 4: /* displaying title of given book */

clrscr(); printf("\t\t4: Title of the specified book:\n\n\n");

printf("Enter the accesion number: "); scanf("%d",&k);

printf("\n\n");

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

if(k==a[i].acn) {

printf("Title: %s\n",a[i].title);

} } delay(2000); break;

case 5: /* counting total books in library */

clrscr(); printf("\t\t5: List the count of books in the library: \n\n\n");

for(i=0;i<5;i++) { j=j+1; } printf("\tTotal books: %2d",j);

delay(2000); break;

case 6: /* sorting the books by their accesion numbers */

clrscr(); printf("6: List the books in order of accesion number: \n\n\n");

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

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

if(a[i].acn>a[j].acn) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } }

printf("Access no.\tTitle\tAuthor\tFlag\n\n\n"); for(i=0;i<5;i++) {

printf("%4d\t\t%5s\t%5s\t",a[i].acn,a[i].title,a[i].auth);

Page 37: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

if(a[i].flag==0) printf("not issued\n\n");

else printf("issued\n\n"); }

delay(2000); break;

case 7: /* condition for going out */

exit();

} }

}

linkfloat() { /* special function to solve compilar error */ float a=0,*b; /* not used withing the program but still defined */ b=&a; a=*b; return 0; }

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

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

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

void main() {

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

int d,m,y,i;clrscr();

printf("enter the date to save in structure: \n\n");

printf("Enter the date: ");scanf("%d",&d1.date);

printf("\n\nEnter the month: ");scanf("%d",&d1.month);

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

clrscr();

printf("\nenter the date to compare with structure:\n\n");

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

Solution:

Page 38: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

printf("\n\nEnter the month: ");scanf("%d",&m);

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

if(d==d1.date && m==d1.month && y==d1.year) {

printf("\n\ndates are equal\n\n");

}

else {

printf("\n\ndates are unequal\n\n");

}

getch();

}

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

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

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

struct linklist { int data; linklist *link; };

void main() {

struct linklist *first, *temp;

char choice='y';

int count=0;

clrscr();

/* taking the input of first element */

printf("Enter element %d: ",++count);

Solution:

Page 39: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

first=(linklist *)malloc(sizeof(linklist));

scanf("%d",&first->data);

first->link=NULL;

printf("\n\nEnter another element(Y/N): ");

choice=getche();

tolower(choice); /* converting to lowercase to match the condition of switch */

switch(choice) {

case 'y':

clrscr();

while(choice=='y' || choice=='Y') {

printf("\nEnter element %d: ",++count);

temp=(linklist *)malloc(sizeof(linklist));

scanf("%d",&temp->data);

temp->link=first;

first=temp;

printf("\n\n\nEnter another elements(Y/N): ");choice=getche();

clrscr();

}

break;

case 'n':

break;

}

printf("\nTotal elements = %d\n\n",count);

/* printing all elements */

for(temp=first; temp!=NULL; temp=temp->link) {

printf("%d ",temp->data);

}

getch();

}

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

Page 40: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/[07-Apr-14 8:37:39 PM]

Older PostsHome

Subscribe to: Posts (Atom)

Posted by Chetan Raikwar at 07:04 No comments:

(i) A stack is a data structure in which addition of new element or deletion of existing element always takes place at the same end. This end is often known as ‘top’ of stack. This situation can be compared to a stack of plates in a cafeteria where every new plate taken off the stack is also from the ‘top’ of the stack. There are several application where stack can be put to use. For example, recursion, keeping track of function calls, evaluation of expressions, etc. Write a program to implement a stack using a linked list.

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

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

(j) Unlike a stack, in a queue the addition of new element takes place at the end (called ‘rear’ of queue) whereas deletion takes place at the other end (called ‘front’ of queue). Write a program to implement a queue using a linked list

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

Solution:

Solution:

Recommend this on Google

Simple template. Powered by Blogger.

Page 41: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Drawing a hut using graphics

http://letuscalllessons.blogspot.com/2014/02/drawing-hut-using-graphics.html[07-Apr-14 8:38:48 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Monday, 3 February 2014

Drawing a hut using graphics

NOTE: please change the "initgraph" path of BGI directory according to your turbo C++ IDE's directory.

#include<graphics.h>void main() {

int gd=DETECT,gm;

initgraph(&gd,&gm,"c:\\turboc3\\bgi");

line(200,100,170,200);line(200,100,250,200);line(200,100,400,100);line(400,100,450,200);line(450,200,250,200);line(178,176,178,277);line(245,190,245,300);line(440,200,440,300);line(440,300,245,300);line(245,300,178,277);line(210,288,210,215);line(190,280,190,215);line(190,215,210,215);

rectangle(300,210,380,260);

setfillstyle(5,RED);floodfill(399,101,WHITE);

setfillstyle(SOLID_FILL,WHITE^23);floodfill(299,209,WHITE);

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

► January (14)

▼ February (2)

Dynamic calender animated without graphics library...

Drawing a hut using graphics

Blog Archive

More Next Blog» Create Blog Sign In

Page 42: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Drawing a hut using graphics

http://letuscalllessons.blogspot.com/2014/02/drawing-hut-using-graphics.html[07-Apr-14 8:38:48 PM]

Older PostHome

Subscribe to: Post Comments (Atom)

Posted by Chetan Raikwar at 11:11

floodfill(179,275,WHITE);

setfillstyle(SOLID_FILL,BLACK^9);floodfill(191,216,WHITE);

floodfill(379,258,WHITE);

setcolor(BLACK);settextstyle(8,HORIZ_DIR,3);outtextxy(200,200,"Chetan Raikwar");

setcolor(BLUE);setfillstyle(CLOSE_DOT_FILL,BLUE);floodfill(0,0,WHITE);getch();closegraph();restorecrtmode();

}

+1 Recommend this on Google

Comment as: Google Account

No comments:

Post a Comment

Simple template. Powered by Blogger.

Page 43: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Monday, 3 February 2014

Drawing a hut using graphics

NOTE: please change the "initgraph" path of BGI directory according to your turbo C++ IDE's directory.

#include<graphics.h>void main() {

int gd=DETECT,gm;

initgraph(&gd,&gm,"c:\\turboc3\\bgi");

line(200,100,170,200);line(200,100,250,200);line(200,100,400,100);line(400,100,450,200);line(450,200,250,200);line(178,176,178,277);line(245,190,245,300);line(440,200,440,300);line(440,300,245,300);line(245,300,178,277);line(210,288,210,215);line(190,280,190,215);line(190,215,210,215);

rectangle(300,210,380,260);

setfillstyle(5,RED);floodfill(399,101,WHITE);

setfillstyle(SOLID_FILL,WHITE^23);floodfill(299,209,WHITE);

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

► January (14)

▼ February (2)

Dynamic calender animated without graphics library...

Drawing a hut using graphics

Blog Archive

More Next Blog» Create Blog Sign In

Page 44: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

Posted by Chetan Raikwar at 11:11 No comments:

floodfill(179,275,WHITE);

setfillstyle(SOLID_FILL,BLACK^9);floodfill(191,216,WHITE);

floodfill(379,258,WHITE);

setcolor(BLACK);settextstyle(8,HORIZ_DIR,3);outtextxy(200,200,"Chetan Raikwar");

setcolor(BLUE);setfillstyle(CLOSE_DOT_FILL,BLUE);floodfill(0,0,WHITE);getch();closegraph();restorecrtmode();

}

+1 Recommend this on Google

Dynamic calender animated without graphics library

#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=2,year=2014,a;

Page 45: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

void box();

clrscr();

/***********************************************//* 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) {

sound(1400);delay(20);sound(750);delay(10);nosound();

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

}

/* if down arrow key is hit */

if(key==80) {

sound(1400);delay(20);sound(850);delay(10);nosound();

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

}

/* if left arrow key is hit */

if(key==75) {

sound(1600);delay(20);sound(1250);delay(10);nosound();

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

}

/* if right arrow key is hit */

if(key==77) {

sound(1600);

Page 46: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

delay(20);sound(1250);delay(10);

nosound();

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);

if(x==22)textcolor(RED);

elsetextcolor(YELLOW);

cprintf("%2d",i);

i++;x+=5;

if(x>52) { /* if the position of 7 days is covered, again print frombeginning 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);

}

elseprintf("Error! invalid input\n");

getch();

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

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

Page 47: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

/**********************************************************/

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 *//*************/

textcolor(BLUE);/* corners of inner box */

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

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

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

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

/* boundries of inner box */

Page 48: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

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

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

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

}

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

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

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

}

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

/* corners of outer box */

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

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

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

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

/* boundries of outer box */

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

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

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

}

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

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

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

}

textcolor(GREEN+BLINK);gotoxy(24,22);cprintf("%c%c%c%c %c%c %c%c%c%c%c%c%c%c%c%c%c%c%c",77,65,68,69,66,89,67,72,69,84,65,78,82,65,73,75,87,65,82);

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

Page 49: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

textcolor(RED);

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

textcolor(YELLOW);

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

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

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

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

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

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

textcolor(LIGHTGREEN);

gotoxy(32,4);

if(m==1)cprintf("January ");

if(m==2)cprintf("February ");

if(m==3)cprintf("March ");

if(m==4)cprintf("April ");

if(m==5)cprintf("May ");

if(m==6)cprintf("June ");

if(m==7)cprintf("July ");

if(m==8)cprintf("August ");

if(m==9)cprintf("September ");

if(m==10)cprintf("October ");

if(m==11)cprintf("November ");

if(m==12)cprintf("December ");

textcolor(CYAN);cprintf("%d",y);/*************************//* printing instructions *//*************************/

Page 50: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

textcolor(BROWN);

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

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

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

gotoxy(60,22);cprintf("%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;

elsedays=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 */

Page 51: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

Posted by Chetan Raikwar at 10:55 No comments:

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;}

+1 Recommend this on Google

Thursday, 30 January 2014

Let Us C / Chapter 14 (Operations on Bits)

(a) The information about colors is to be stored in bits of a char variable called color. The bit number 0 to 6, each represent 7 colors of a rainbow, i.e. bit 0 represents violet, 1 representsindigo, and so on. Write a program that asks the user to enter a number and based on this number it reports which colors in the rainbow does the number represents.

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

char color; int num;

clrscr();

printf("Please enter the number(0-6): "); scanf("%d",&num);

color=1<<num;

printf("\n\n");

if(num==0 && color==1) printf("Violet");

else if(num==1 && color==2) printf("Indigo");

else if(num==2 && color==4) printf("Blue");

Exercise [A]

Solution:

Page 52: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

else if(num==3 && color==8) printf("Green");

else if(num==4 && color==16) printf("Yellow");

else if(num==5 && color==32) printf("Orange");

else if(num==6 && color==64) printf("Red");

else printf("Wrong color number!");

getch();

}

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

(b) A company planning to launch a new newspaper in market conducts a survey. The various parameters considered in the survey were, the economic status (upper, middle, and lower class) the languages readers prefer (English, Hindi, Regional language) and category of paper (daily, supplement, tabloid). Write a program, which reads data of 10 respondents through keyboard, and stores the information in an array of integers. The bit-wise information to be stored in an integer is given below:Bit Number Information0 Upper class1 Middle class2 Lower class3 English4 Hindi5 Regional Language6 Daily7 Supplement8 TabloidAt the end give the statistical data for number of persons who read English daily, number of upper class people who read tabloid and number of regional language readers.

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

int arr[10][3],i,j; unsigned int infr; int eng=0,utab=0,rgl=0;

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

clrscr();

gotoxy(20,2); printf("Enter data of respondent %d:\n\n",i+1);

for(j=0;j<3;j++) {

Solution:

Page 53: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

if(j==0){ printf("Economic Status:\n\n"); printf("0: Upper class\t1: Middle class\t2: Lower class\n\n");

scanf("%d",&arr[i][j]); }

if(j==1){ printf("\n\nLanguage Preferred:\n\n"); printf("3: English\t4: Hindi\t5:Regional Language\n\n");

scanf("%d",&arr[i][j]); }

if(j==2){

printf("\n\nType of Paper:\n\n"); printf("6: Daily\t7: Supplement\t8: Tabloid\n\n");

scanf("%d",&arr[i][j]); }

} }

/***********************************************/ /* converting the whole array using left shift */ /***********************************************/

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

for(j=0;j<3;j++) {

arr[i][j]= 1 << arr[i][j]; /* conversion */

} }

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

if(arr[i][1]==8) /* english readers */ eng++;

if(arr[i][0]==1 && arr[i][2]==256) /* upper class,tabloid readers */ utab++;

if(arr[i][1]==32) /* regional language readers */ rgl++; }

clrscr();

gotoxy(20,2); printf("Reader's statistics:\n\n\n\n"); printf("\tEnglish Reader: %d\n",eng); printf("\tUpper class Tabloid Readers: %d\n",utab); printf("\tRegional Language readers: %d\n",rgl); getch();

}

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

(c) In an inter-college competition, various sports and games are played between different colleges like cricket, basketball, football,

Page 54: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

hockey, lawn tennis, table tennis, carom and chess. The information regarding the games won by a particular college is stored in bit numbers 0, 1, 2, 3, 4, 5, 6, 7 and 8 respectively of an integer variable called game. The college that wins in 5 or more than 5 games is awarded the Champion of Champions trophy. If a number is entered through the keyboard, then write a program to find out whether the college won the Champion of the Champions trophy or not, along with the names of the games won by the college.

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

int game; int i,won=0,name;

clrscr();

printf("Enter number: ");

scanf("%d",&name);

printf("\n\n");

for(i=1;i<=8;i++) {

game=i&name;

if(game==1) { printf("Cricket\n");

won++; }

if(game==2) { printf("Basketball\n");

won++; }

if(game==3) { printf("Football\n");

won++; }

if(game==4) { printf("Hockey\n");

won++; }

if(game==5) { printf("Lawn-tennis\n");

won++; }

if(game==6) { printf("Table-tennis\n");

won++; }

Solution:

Page 55: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

if(game==7) { printf("Carrom\n");

won++; }

if(game==8) { printf("Chess\n");

won++; }

}

if(won>=5) {

printf("\n\n\nCollege %d has won the champions trophy\n",name);

}

else {

printf("\n\n\nCollege %d didn't win the champions trophy\n",name);

}

getch(); }

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

(d) An animal could be either a canine (dog, wolf, fox, etc.), a feline (cat, lynx, jaguar, etc.), a cetacean (whale, narwhal, etc.) or a marsupial (koala, wombat, etc.). The information whether a particular animal is canine, feline, cetacean, or marsupial is stored in bit number 0, 1, 2 and 3 respectively of a integer variable called type. Bit number 4 of the variable type stores the information about whether the animal is Carnivore or Herbivore.For the following animal, complete the program to determine whether the animal is a herbivore or a carnivore. Also determine whether the animal is a canine, feline, cetacean or a marsupial.struct animal{char name[30] ;int type ;}struct animal a = { "OCELOT", 18 } ;

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

struct animal { char name[30]; int type; };

struct animal a={"OCELOT",18};

Solution:

Page 56: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

int t1,t2,typ1,typ2;

clrscr();

t1= a.type >> 3;

typ1= t1 & 2; /* checking the bit after shifting */

t2= t1 << 3;

typ2= t2 & 16; /* checking another bit after shifting */

/**********************************************************/ /* checking if ocelot is canine/feline/cetacean/marsupial */ /**********************************************************/

if(typ1==1) printf("\n\nOCELOT is Canine\n");

if(typ1==2) printf("\n\nOCELOT is Feline\n");

if(typ1==4) printf("\n\nOCELOT is Cetacean\n");

if(typ1==8) printf("\n\nOCELOT is Marsupial\n");

/************************************************/ /* checking if ocelot is carnivore or herbivore */ /************************************************/

if(typ2!=0) printf("\n\nOCELOT is Carnivore\n");

if(typ2==0) printf("\n\nOCELOT is Herbivore\n");

getch();

}

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

(e)The time field in the directory entry is 2 bytes long. Distribution of different bits which account for hours, minutes and seconds is given below. Write a function which would receive the two-byte time entry and return to the calling function, the hours, minutes and seconds. 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 H H H H H M M M M M M S S S S S

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

unsigned hr,mn,sc,input;

void timer();

Solution:

Page 57: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

clrscr();

printf("Enter the time entry: ");

scanf("%d",&input);

timer(input,&hr,&mn,&sc);

printf("\n\nTIME: %u : %u : %u\n",*(&hr),*(&mn),*(&sc));

getch();

}

void timer(unsigned time, unsigned *hr, unsigned *mn, unsigned *sc) {

*hr=time >> 11;

*mn=(time<<5) >> 10;

*sc=(time<<11) >> 11;

}

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

(f) In order to save disk space information about student is stored in an integer variable. If bit number 0 is on then it indicates Ist year student, bit number 1 to 3 stores IInd year, IIIrd year and IVth year student respectively. The bit number 4 to 7 stores stream Mechanical, Chemical, Electronics and IT. Rest of the bits store room number. Based on the given data, write a program that asks for the room number and displays the information about the student, if its data exists in the array. The contents of array are,int data[ ] = { 273, 548, 786, 1096 } ;

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

void main() {

unsigned int yr,br,data_yr,data_br; int i,j,k,rn,a,b,flag=0; int data[]={ 273,548,786,1096};

clrscr();

printf("Enter room number: "); scanf("%d",&rn);

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

/*********************/ /* checking for year */ /*********************/

for(i=1;i<=8;i=i*2) {

yr= rn & i;

Solution:

Page 58: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

if(yr==1) { printf("First year"); break; }

if(yr==2) { printf("Second year"); break; }

if(yr==4) { printf("Third year"); break; }

if(yr==8) { printf("Fourth year"); break; }

}

/***********************/ /* Checking for branch */ /***********************/

printf("\n\nBranch: ");

for(i=16;i<=128;i=i*2) {

br= rn & i;

if(br==16) { printf("Mechanical"); break; }

if(br==32) { printf("Chemical"); break; }

if(br==64) { printf("Electronics"); break; }

if(br==128) { printf("I.T."); break; }

}

/***********************************************/ /* checking if data matches with that of array */ /***********************************************/

for(i=1,j=16;i<=8,j<=128;i=i*2,j=j*2) {

yr=rn&i;

br=rn&j;

for(k=0,a=1,b=16;k<4,a<=8,b<=128;k++,a=a*2,b=b*2) {

data_yr=data[k] & a;

Page 59: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

Posted by Chetan Raikwar at 07:05 No comments:

data_br=data[k] & b;

if(yr==data_yr && br==data_br) {

flag+=1;

break;

}

}

}

if(flag==0) printf("\n\n\ndata doesn't matche with the array.\n");

else printf("\n\n\ndata matches with the array.\n");

getch(); }______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 13 (More Issues in Input Output)

(a) Write a program to carry out the following:(a) Read a text file provided at command prompt(b) Print each word in reverse orderFor example if the file containsINDIA IS MY COUNTRYOutput should beAIDNI SI YM YRTNUOC

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

void main(int argc, char *argv[]) {

FILE *fs;char ch,s[80];void rev();

if(argc!=2) {

printf("File name not supplied\n");

exit();

}

fs=fopen(argv[1],"r");

Exercise [B]

Solution:

Page 60: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

if(fs==NULL) {

printf("File not found!");

exit();}

while(fgets(s,79,fs)!=NULL)rev(s);

fclose(fs);

}

void rev(char s1[80]) {

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

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

s2[j]=s1[i];

if(s1[i]==' ' || s1[i]=='\0') {

s2[j]='\0';

strrev(s2);

printf("%s ",s2);

j=-1;

}

i++;j++;}

s2[j]='\0';

printf("%s",strrev(s2));

}

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

(b) Write a program using command line arguments to search for a word in a file and replace it with the specified word. The usage of the program is shown below.C> change <old word> <new word> <filename>

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

void replace();

void main ( int argc, char *argv[] ) {

FILE *fp,*ft;char str[80],str1[30],str2[30],nwstr[100];

clrscr();

if(argc!=4) {

Solution:

Page 61: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

puts("Improper argements passed!");exit();}

strcpy(str1,argv[1]);strcpy(str2,argv[2]);

fp=fopen(argv[3],"r");

if(fp==NULL) {

puts("cannot open source file!");exit();}

ft=fopen("NEW.TXT","w+");

if(ft==NULL) {

puts("cannot open target file!");exit();}

while(fgets(str,79,fp)!=NULL) {

replace(str,str1,str2,&nwstr);

fputs(nwstr,ft);}

fclose(fp);fclose(ft);

remove("FILE.TXT");rename("NEW.TXT","FILE.TXT");

printf("\n\nTask completed!\n\n");

getch();

}

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

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

/*******************************//* copying to temporary string *//*******************************/

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

*t=*s;

t++;s++;

}

*t='\0';

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

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

Page 62: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

temp2[j]=temp[i];

if(temp[i]==' ' || temp[i]==',' || 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 */

/******************************************************************//* preparing new string to return to main and printing it on file *//******************************************************************/

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

*n=*m;

n++;m++;}

Page 63: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

*n='\0';

}

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

(c) Write a program that can be used at command prompt as a calculating utility. The usage of the program is shown below.C> calc <switch> <n> <m>Where, n and m are two integer operands. switch can be any one of the arithmetic or comparison operators. If arithmetic operator is supplied, the output should be the result of the operation. If comparison operator is supplied then the output should be True or False.

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

void main(int argc, char *argv[]) {

int n,m,calc;

clrscr();

if(argc!=4)printf("Improper number of arguments");

/* converting both operands to integers */

n=atoi(argv[2]);

m=atoi(argv[3]);

printf("\n\nOutput: ");

/* comparing the operators passed at command prompt */

if(strcmp("+",argv[1])==0) {

printf("%d\n\n",n+m);

}

if(strcmp("-",argv[1])==0) {

printf("%d\n\n",n-m);

}

if(strcmp("*",argv[1])==0) {

printf("%d\n\n",n*m);

}

if(strcmp("/",argv[1])==0) {

printf("%d\n\n",n/m);

Solution:

Page 64: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

Posted by Chetan Raikwar at 07:05 No comments:

}

if(strcmp("%",argv[1])==0) {

printf("%d\n\n",n%m);

} /* IMPORTANT */

/* I have used dedicated variable for '<' and '>' comparison operators *//* because at command prompt, these are redirecting operators and cannot *//* be used simply for comparison. */

/* 1: "<" = "less" */ /* 2: ">" = "greater" */ /* type "less" for "<" and "greater" for ">" respectively if you want to perform comparison */

if(strcmp("greater",argv[1])==0) {

if(n>m)printf("True\n\n");

if(n<m)printf("False\n\n");

}

if(strcmp("less",argv[1])==0) {

if(n<m)printf("True\n\n");

if(n>m)printf("False\n\n");

}

if(strcmp("=",argv[1])==0) {

if(n==m)printf("True\n\n");

elseprintf("False\n\n");

}

}

_______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 11 (Console Input Output) Exercise [D]

Page 65: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

(a) Write down two functions xgets( ) and xputs( ) which work similar to the standard library functions gets( ) and puts( ).

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

void xgets();void xputs();

void main() {

char str[80];clrscr();

xgets(str);

printf("\n");

xputs(str);

getch();

}

void xgets( char *s) {

int i=0;char ch;

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

ch=getche();

if(ch=='\r') {

*s='\0';break;}

if(ch=='\b') {

printf("\b");

i-=2;s-=2;}

else {

*s=ch;s++;

}

}

}

void xputs( char *s) {

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

putch(*s);

Solution:

Page 66: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

Posted by Chetan Raikwar at 07:04 No comments:

s++;

}

}

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

(b) Write down a function getint( ), which would receive a numeric string from the keyboard, convert it to an integer number and return the integer to the calling function. A sample usage of getint( ) is shown below:main( ){int a ;a = getint( ) ;printf ( "you entered %d", a )}

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

int a; char s[80];

printf("Enter any numeric string: "); gets(s);

a=getint(s); /* converting and receiving string as integer */

printf("\n\nYou entered = %d\n",a);

getch();

}

int getint(char s1[80]) {

int digit;

digit=atoi(s1); /* converting string to integer */

return digit;

}

______________________________________________________________________

Solution:

Recommend this on Google

Let Us C / Chapter 10 (Structures)

(a) Create a structure to specify data on students given below:Roll number, Name, Department, Course, Year of joining

Exercise [D]

Page 67: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

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.

/* NOTE: since number of students to be assumed is too much ( about 450 )I have alloted full size (about 450) to it but array has been kept empty,if you have time then you can fill up all 450 names and can search throughthem.program has been tested by me and it works accurately. you can reducethe size of array of structure conveniently by changing the value of N */

#include<stdio.h>#include<conio.h>#define N 450

struct students { int rlnm; char name[25]; char dept[25]; /* structure defined outside of main(); */ char course[25]; int year; };

void main() { /* main() */

struct students s[N];int i,ch;

clrscr();

/* taking input of 450 students in an array of structure */

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

printf(" Enter data of student %d\t\t\t\ttotal students: %d\n",i+1,N);printf("****************************\n\n");

printf("enter rollnumber: ");scanf("%d",&s[i].rlnm);

printf("\n\nenter name: ");scanf(" %s",&s[i].name);

printf("\n\nenter department: ");scanf("%s",&s[i].dept);

printf("\n\nenter course: ");scanf("%s",&s[i].course);

printf("\n\nenter year of joining: ");scanf("%d",&s[i].year);

clrscr();

}

/* displaying a menu */

printf("\n\tenter your choice: \n");printf("\t**********************\n\n");

printf("1: enter year to search all students who took admission in that:\n\n");printf("2: enter roll number to see details of that student\n\n\n");

printf("your choice: "); /* taking input of your choice */

Solution:

Page 68: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

scanf("%d",&ch);

clrscr();

switch(ch) {

case 1: clrscr();

dispyr(&s); /* function call to display names of students who joined in\ a particular year */

break;

case 2: clrscr();

disprl(&s); /* function call to display information of a student \ whose roll number is given */

break;

default:

printf("\n\nerror! wrong choice");

}

getch();

}/******************* main() ends **************/

dispyr(struct students *a) { /* function for displaying names of students\ who took admission in a particular year */

int j,yr;

printf("\nenter year: ");scanf("%d",&yr);

printf("\n\nthese students joined in %d\n\n",yr);

for(j=0;j<N;j++) {

if(a[j].year==yr) {

printf("\n%s\n",a[j].name);}

}return 0;}

disprl(struct students *a) { /* function to print information of a\ student whose roll number has been \ given. */

int k,rl;

printf("\nenter roll number: ");scanf("%d",&rl);

for(k=0;k<N;k++) {

if(a[k].rlnm==rl) {

printf("\n\n\t Details of roll number: %d\n",a[k].rlnm);printf("\t***************************\n\n");printf(" Name: %s\n",a[k].name);

Page 69: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

printf(" Department: %s\n",a[k].dept);printf(" Course: %s\n",a[k].course);printf("Year of joining: %d",a[k].year);

break;}

else {printf("\nRoll number you entered does not exist\n\n");

break;}

}

return 0;}

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

(b) 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”.

/* NOTE: since number of customers to be assumed is too much ( about 200 ) I have alloted full size (about 200) to it but array has been kept empty, if you have time then you can fill up all 200 names and can search through them.program has been tested by me and it works accurately. you can reducethe size of array of structure conveniently by changing the value of N */

#include<stdio.h> #include<conio.h> #define N 200

struct bank { int acn; char name[20]; int bal; /* defined out of main() */ };

void main() {

struct bank b[N];

int i,ch,lw=100,ch2,ac,am;

clrscr();

for(i=0;i<N;i++) { /* inputting customer data */

printf("\tEnter information of customers \n"); printf("\t******************************\n\n");

Solution:

Page 70: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

printf("enter account no.: "); scanf("%d",&b[i].acn);

printf("\n\nenter customer name: "); scanf("%s",&b[i].name);

printf("\n\nenter balance: "); scanf("%d",&b[i].bal);

clrscr();

}

clrscr();

printf("\tEnter your choice\n"); /* further processing of transaction */ printf("\t*****************\n\n");

printf("1: to know whose balance is below 100.\n\n"); printf("2: to process request or withdrawl.\n\n\n");

scanf("%d",&ch);

switch(ch) {

case 1:

clrscr();

disp(&b); /* displaying whose balance is below 100 */

break;

case 2:

clrscr();

printf("enter your account number: "); scanf("%d",&ac);

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

if((b[i].acn)==ac) {

clrscr();

printf("\tHello %s\n",b[i].name); printf("\n\n");

printf("\n\nenter your choice\n"); printf("\n1: deposite:\n"); printf("\n0: withdrawl:\n\n"); scanf("%d",&ch2);

switch(ch2) {

case 0:

clrscr();

if(b[i].bal<lw) {

printf("\n\nsorry! account balance is too low for withdrawl.\n");

break; }

Page 71: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

else {

printf("\n\nenter amount for withdrawl: "); scanf("%d",&am);

}

if(b[i].bal<am) {

printf("\n\nyou don't have enough balance for withdrawl.\n");

}

else {

b[i].bal=b[i].bal+am;

printf("\n\nwithdrawl was successful.\n");

} break;

case 1:

clrscr();

printf("\n\nenter amount to deposite: "); scanf("%d",&am);

b[i].bal=b[i].bal+am;

printf("\n\ncash deposited successfully.\n\n");

break;

}

} } } getch(); }

disp(struct bank *a) {

int k;

printf("\tCustomers whose balance is below 100:\n"); printf("\t*************************************\n\n");

for(k=0;k<N;k++) {

if((a[k].bal)<100) {

printf("%2d\t%s\n",a[k].acn,a[k].name);

} } return 0;

}

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

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

Page 72: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

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.

#include<stdio.h> #include<conio.h> struct automob { char name[5]; int year; char mtr[10]; int qty; }; void main() {

struct automob a[54]={{"AA1",2009,"AAA",10}, {"AA2",2009,"AAA",10}, {"AA3",2009,"AAA",10}, {"AA4",2009,"AAA",10}, {"AA5",2009,"AAA",10}, {"AA6",2009,"AAA",10}, {"AA7",2009,"AAA",10}, {"AA8",2009,"AAA",10}, {"AA9",2009,"AAA",10}, {"BB1",2010,"BBB",11}, {"BB2",2010,"BBB",11}, {"BB3",2010,"BBB",11}, {"BB4",2010,"BBB",11}, {"BB5",2010,"BBB",11}, {"BB6",2010,"BBB",11}, {"BB7",2010,"BBB",11}, {"BB8",2010,"BBB",11}, {"BB9",2010,"BBB",11}, {"CC1",2011,"CCC",12}, {"CC2",2011,"CCC",12}, {"CC3",2011,"CCC",12}, {"CC4",2011,"CCC",12}, {"CC5",2011,"CCC",12}, {"CC6",2011,"CCC",12}, {"CC7",2011,"CCC",12}, {"CC8",2011,"CCC",12}, {"CC9",2011,"CCC",12}, {"DD1",2012,"DDD",13}, {"DD2",2012,"DDD",13}, {"DD3",2012,"DDD",13}, {"DD4",2012,"DDD",13}, {"DD5",2012,"DDD",13}, {"DD6",2012,"DDD",13}, {"DD7",2012,"DDD",13}, {"DD8",2012,"DDD",13}, {"DD9",2012,"DDD",13}, {"EE1",2013,"EEE",14}, {"EE2",2013,"EEE",14}, {"EE3",2013,"EEE",14}, {"EE4",2013,"EEE",14}, {"EE5",2013,"EEE",14}, {"EE6",2013,"EEE",14}, {"EE7",2013,"EEE",14}, {"EE8",2013,"EEE",14}, {"EE9",2013,"EEE",14}, {"FF1",2014,"FFF",15}, {"FF2",2014,"FFF",15}, {"FF3",2014,"FFF",15}, {"FF4",2014,"FFF",15},

Solution:

Page 73: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

{"FF5",2014,"FFF",15}, {"FF6",2014,"FFF",15}, {"FF7",2014,"FFF",15}, {"FF8",2014,"FFF",15}, {"FF9",2014,"FFF",15}};

int i,j,k;

clrscr();

printf("Information of parts between BB1 to CC6:\n\n");

printf("\n\nName\t\tyear(manu.)\t\tmaterial\tquantity\n\n\n");

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

if(i>=9 && i<=23) { printf("%3s\t\t%4d\t\t\t%5s\t\t%4d\n",a[i].name,a[i].year,a[i].mtr,a[i].qty);

} }

getch(); }

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

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

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

void main() {

struct cricketer { char name[50]; int age; int match; float avrn; }; struct cricketer c[20],temp; int i,j; clrscr();

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

printf("Enter data of cricketer %d\n\n\n",i+1);

fflush(stdin); printf("Name: "); gets(c[i].name);

Solution:

Page 74: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

printf("\n\nAge: "); scanf("%d",&c[i].age);

printf("\n\nMatches: "); scanf("%d",&c[i].match);

printf("\n\nAverage runs: "); scanf("%f",&c[i].avrn);

clrscr();

}

/*******************/ /* sorting records */ /*******************/

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

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

if(c[i].avrn > c[j].avrn) {

temp=c[i]; c[i]=c[j]; c[j]=temp; } } }

printf("Sorted records:\n\n");

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

printf("%d\t%s\t%d\t%d\t%f\n\n\n",i+1,c[i].name,c[i].age,c[i].match,c[i].avrn);

}

getch(); }

linkfloat() {

float a=0,*b;

b=&a; a=*b;

return 0; }

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

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

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

Solution:

Page 75: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

struct employee { int code; char name[20]; int dd,mm,yy; } e[N];

int d,m,y,i;clrscr();

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

printf("\tEnter employee data:\n");printf("\t*********************\n");

printf("\nEnter employee code: ");scanf("%d",&e[i].code);

printf("\n\nEnter employee name: ");scanf("%s",&e[i].name);

printf("\n\nEnter date of joining (dd mm yy): ");scanf("%d%d%d",&e[i].dd,&e[i].mm,&e[i].yy);

clrscr();

}

clrscr();

printf("\nenter current date(dd mm yy): \n\n");scanf("%d%d%d",&d,&m,&y);

clrscr();

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

if((y-(e[i].yy))>=3) {

printf("%s\n\N",e[i].name);

}

}

getch();}

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

(f) Write a menu driven program that depicts the working of a library. The menu options should be:1. Add book information2. Display book information3. List all books of given author4. List the title of specified book5. List the count of books in the library6. List the books in the order of accession number7. ExitCreate 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.

Solution:

Page 76: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

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

void main() {

struct library { int acn; char title[25]; char auth[25]; float price; int flag; };

struct library a[5]={ {2,"AAA","AAA",154.8,1}, {1,"BBB","BBB",124.6,0}, {5,"EEE","EEE",234.3,0}, {3,"CCC","CCC",232.3,1}, {4,"DDD","DDD",121.3,0} };

struct library temp; /* temporary structure to overwrite information / and for assistance in sorting the whole structure */

int i,ch,k,flag,j=0; char author[10];

clrscr();

while(1) { /* initialized an indefinite loop */

clrscr(); printf("\t1: Add book information\n"); printf("\t2: Display book information\n"); printf("\t3: List all books of given author\n"); printf("\t4: List the title of specified book\n"); printf("\t5: List the count of books in the library\n"); printf("\t6: List the books in order of accesion number\n"); printf("\t7: Exit\n\n\n");

printf("Choice: "); scanf("%d",&ch);

switch(ch) {

case 1: /* adding book information over current information */

clrscr();

printf("\t\t1: Add book information:\n\n\n");

printf("enter book information:\n\n");

printf("Accesion number of book to be modified: "); scanf("%d",&j); fflush(stdin);

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

if(j==a[i].acn) {

printf("\n\nenter new information:\n\n"); printf("accesion no.: "); scanf("%d",&temp.acn); fflush(stdin);

Page 77: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

printf("\n\ntitle: "); scanf("%s",&temp.title); fflush(stdin); printf("\n\nauthor: "); scanf("%s",&temp.auth); fflush(stdin); printf("\n\nprice: "); scanf("%f",&temp.auth); fflush(stdin); printf("\n\nflag(1/0): "); scanf("%d",&temp.flag); fflush(stdin);

} }

a[j]=temp; /* overwriting current information with new one */

clrscr();

printf("\n\nInformation added succesfully!\n\n");

delay(2000);

break;

case 2: /* displaying current book information */

clrscr();

printf("\t\t2: Display book information:\n\n\n");

printf("Enter accesion number: "); scanf("%d",&k);

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

if(k==a[i].acn) { clrscr(); printf("Book information: \n\n"); printf("\n\nAccesion Number: %d",a[i].acn); printf("\nTitle: %s",a[i].title); printf("\nAuthor: %s",a[i].auth); printf("\nPrice: %f",a[i].price);

if(a[i].flag==0) { printf("\nFlag: Not issued\n\n"); } else{ printf("\nFlag: Issued\n\n"); } } } delay(1000);

break;

case 3: /* listing all books of given author */

clrscr();

printf("\t\t3: List all books of given author:\n\n\n");

printf("Enter author name: "); scanf("%s",&author); fflush(stdin);

printf("\n\nbooks of %s\n\n",author); for(i=0;i<5;i++) {

k=strcmp(author,a[i].auth);

Page 78: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

if(k==0) { j=j+1; printf("%d.\t%s\n",j,a[i].title);

} } delay(2000); break;

case 4: /* displaying title of given book */

clrscr(); printf("\t\t4: Title of the specified book:\n\n\n");

printf("Enter the accesion number: "); scanf("%d",&k);

printf("\n\n");

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

if(k==a[i].acn) {

printf("Title: %s\n",a[i].title);

} } delay(2000); break;

case 5: /* counting total books in library */

clrscr(); printf("\t\t5: List the count of books in the library: \n\n\n");

for(i=0;i<5;i++) { j=j+1; } printf("\tTotal books: %2d",j);

delay(2000); break;

case 6: /* sorting the books by their accesion numbers */

clrscr(); printf("6: List the books in order of accesion number: \n\n\n");

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

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

if(a[i].acn>a[j].acn) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } }

printf("Access no.\tTitle\tAuthor\tFlag\n\n\n"); for(i=0;i<5;i++) {

printf("%4d\t\t%5s\t%5s\t",a[i].acn,a[i].title,a[i].auth);

Page 79: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

if(a[i].flag==0) printf("not issued\n\n");

else printf("issued\n\n"); }

delay(2000); break;

case 7: /* condition for going out */

exit();

} }

}

linkfloat() { /* special function to solve compilar error */ float a=0,*b; /* not used withing the program but still defined */ b=&a; a=*b; return 0; }

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

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

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

void main() {

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

int d,m,y,i;clrscr();

printf("enter the date to save in structure: \n\n");

printf("Enter the date: ");scanf("%d",&d1.date);

printf("\n\nEnter the month: ");scanf("%d",&d1.month);

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

clrscr();

printf("\nenter the date to compare with structure:\n\n");

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

Solution:

Page 80: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

printf("\n\nEnter the month: ");scanf("%d",&m);

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

if(d==d1.date && m==d1.month && y==d1.year) {

printf("\n\ndates are equal\n\n");

}

else {

printf("\n\ndates are unequal\n\n");

}

getch();

}

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

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

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

struct linklist { int data; linklist *link; };

void main() {

struct linklist *first, *temp;

char choice='y';

int count=0;

clrscr();

/* taking the input of first element */

printf("Enter element %d: ",++count);

Solution:

Page 81: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

first=(linklist *)malloc(sizeof(linklist));

scanf("%d",&first->data);

first->link=NULL;

printf("\n\nEnter another element(Y/N): ");

choice=getche();

tolower(choice); /* converting to lowercase to match the condition of switch */

switch(choice) {

case 'y':

clrscr();

while(choice=='y' || choice=='Y') {

printf("\nEnter element %d: ",++count);

temp=(linklist *)malloc(sizeof(linklist));

scanf("%d",&temp->data);

temp->link=first;

first=temp;

printf("\n\n\nEnter another elements(Y/N): ");choice=getche();

clrscr();

}

break;

case 'n':

break;

}

printf("\nTotal elements = %d\n\n",count);

/* printing all elements */

for(temp=first; temp!=NULL; temp=temp->link) {

printf("%d ",temp->data);

}

getch();

}

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

Page 82: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2015-01-01T00:00:00-08:00&max-results=16[07-Apr-14 8:39:48 PM]

Newer Posts Older PostsHome

Subscribe to: Posts (Atom)

Posted by Chetan Raikwar at 07:04 No comments:

(i) A stack is a data structure in which addition of new element or deletion of existing element always takes place at the same end. This end is often known as ‘top’ of stack. This situation can be compared to a stack of plates in a cafeteria where every new plate taken off the stack is also from the ‘top’ of the stack. There are several application where stack can be put to use. For example, recursion, keeping track of function calls, evaluation of expressions, etc. Write a program to implement a stack using a linked list.

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

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

(j) Unlike a stack, in a queue the addition of new element takes place at the end (called ‘rear’ of queue) whereas deletion takes place at the other end (called ‘front’ of queue). Write a program to implement a queue using a linked list

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

Solution:

Solution:

Recommend this on Google

Simple template. Powered by Blogger.

Page 83: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 14 (Operations on Bits)

(a) The information about colors is to be stored in bits of a char variable called color. The bit number 0 to 6, each represent 7 colors of a rainbow, i.e. bit 0 represents violet, 1 representsindigo, and so on. Write a program that asks the user to enter a number and based on this number it reports which colors in the rainbow does the number represents.

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

char color; int num;

clrscr();

printf("Please enter the number(0-6): "); scanf("%d",&num);

color=1<<num;

printf("\n\n");

if(num==0 && color==1) printf("Violet");

else if(num==1 && color==2) printf("Indigo");

else if(num==2 && color==4) printf("Blue");

else if(num==3 && color==8) printf("Green");

else if(num==4 && color==16) printf("Yellow");

else if(num==5 && color==32) printf("Orange");

else if(num==6 && color==64)

Exercise [A]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 84: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

printf("Red");

else printf("Wrong color number!");

getch();

}

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

(b) A company planning to launch a new newspaper in market conducts a survey. The various parameters considered in the survey were, the economic status (upper, middle, and lower class) the languages readers prefer (English, Hindi, Regional language) and category of paper (daily, supplement, tabloid). Write a program, which reads data of 10 respondents through keyboard, and stores the information in an array of integers. The bit-wise information to be stored in an integer is given below:Bit Number Information0 Upper class1 Middle class2 Lower class3 English4 Hindi5 Regional Language6 Daily7 Supplement8 TabloidAt the end give the statistical data for number of persons who read English daily, number of upper class people who read tabloid and number of regional language readers.

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

int arr[10][3],i,j; unsigned int infr; int eng=0,utab=0,rgl=0;

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

clrscr();

gotoxy(20,2); printf("Enter data of respondent %d:\n\n",i+1);

for(j=0;j<3;j++) {

if(j==0){ printf("Economic Status:\n\n"); printf("0: Upper class\t1: Middle class\t2: Lower class\n\n");

scanf("%d",&arr[i][j]); }

if(j==1){ printf("\n\nLanguage Preferred:\n\n"); printf("3: English\t4: Hindi\t5:Regional Language\n\n");

Solution:

Page 85: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

scanf("%d",&arr[i][j]); }

if(j==2){

printf("\n\nType of Paper:\n\n"); printf("6: Daily\t7: Supplement\t8: Tabloid\n\n");

scanf("%d",&arr[i][j]); }

} }

/***********************************************/ /* converting the whole array using left shift */ /***********************************************/

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

for(j=0;j<3;j++) {

arr[i][j]= 1 << arr[i][j]; /* conversion */

} }

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

if(arr[i][1]==8) /* english readers */ eng++;

if(arr[i][0]==1 && arr[i][2]==256) /* upper class,tabloid readers */ utab++;

if(arr[i][1]==32) /* regional language readers */ rgl++; }

clrscr();

gotoxy(20,2); printf("Reader's statistics:\n\n\n\n"); printf("\tEnglish Reader: %d\n",eng); printf("\tUpper class Tabloid Readers: %d\n",utab); printf("\tRegional Language readers: %d\n",rgl); getch();

}

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

(c) In an inter-college competition, various sports and games are played between different colleges like cricket, basketball, football, hockey, lawn tennis, table tennis, carom and chess. The information regarding the games won by a particular college is stored in bit numbers 0, 1, 2, 3, 4, 5, 6, 7 and 8 respectively of an integer variable called game. The college that wins in 5 or more than 5 games is awarded the Champion of Champions trophy. If a number is entered through the keyboard, then write a program to find out whether the college won the Champion of the Champions trophy or not, along with the names of the games won by the college.

Page 86: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

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

int game; int i,won=0,name;

clrscr();

printf("Enter number: ");

scanf("%d",&name);

printf("\n\n");

for(i=1;i<=8;i++) {

game=i&name;

if(game==1) { printf("Cricket\n");

won++; }

if(game==2) { printf("Basketball\n");

won++; }

if(game==3) { printf("Football\n");

won++; }

if(game==4) { printf("Hockey\n");

won++; }

if(game==5) { printf("Lawn-tennis\n");

won++; }

if(game==6) { printf("Table-tennis\n");

won++; }

if(game==7) { printf("Carrom\n");

won++; }

if(game==8) { printf("Chess\n");

won++;

Solution:

Page 87: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

}

}

if(won>=5) {

printf("\n\n\nCollege %d has won the champions trophy\n",name);

}

else {

printf("\n\n\nCollege %d didn't win the champions trophy\n",name);

}

getch(); }

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

(d) An animal could be either a canine (dog, wolf, fox, etc.), a feline (cat, lynx, jaguar, etc.), a cetacean (whale, narwhal, etc.) or a marsupial (koala, wombat, etc.). The information whether a particular animal is canine, feline, cetacean, or marsupial is stored in bit number 0, 1, 2 and 3 respectively of a integer variable called type. Bit number 4 of the variable type stores the information about whether the animal is Carnivore or Herbivore.For the following animal, complete the program to determine whether the animal is a herbivore or a carnivore. Also determine whether the animal is a canine, feline, cetacean or a marsupial.struct animal{char name[30] ;int type ;}struct animal a = { "OCELOT", 18 } ;

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

struct animal { char name[30]; int type; };

struct animal a={"OCELOT",18};

int t1,t2,typ1,typ2;

clrscr();

t1= a.type >> 3;

typ1= t1 & 2; /* checking the bit after shifting */

t2= t1 << 3;

typ2= t2 & 16; /* checking another bit after shifting */

Solution:

Page 88: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

/**********************************************************/ /* checking if ocelot is canine/feline/cetacean/marsupial */ /**********************************************************/

if(typ1==1) printf("\n\nOCELOT is Canine\n");

if(typ1==2) printf("\n\nOCELOT is Feline\n");

if(typ1==4) printf("\n\nOCELOT is Cetacean\n");

if(typ1==8) printf("\n\nOCELOT is Marsupial\n");

/************************************************/ /* checking if ocelot is carnivore or herbivore */ /************************************************/

if(typ2!=0) printf("\n\nOCELOT is Carnivore\n");

if(typ2==0) printf("\n\nOCELOT is Herbivore\n");

getch();

}

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

(e)The time field in the directory entry is 2 bytes long. Distribution of different bits which account for hours, minutes and seconds is given below. Write a function which would receive the two-byte time entry and return to the calling function, the hours, minutes and seconds. 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 H H H H H M M M M M M S S S S S

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

unsigned hr,mn,sc,input;

void timer();

clrscr();

printf("Enter the time entry: ");

scanf("%d",&input);

timer(input,&hr,&mn,&sc);

printf("\n\nTIME: %u : %u : %u\n",*(&hr),*(&mn),*(&sc));

getch();

Solution:

Page 89: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

}

void timer(unsigned time, unsigned *hr, unsigned *mn, unsigned *sc) {

*hr=time >> 11;

*mn=(time<<5) >> 10;

*sc=(time<<11) >> 11;

}

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

(f) In order to save disk space information about student is stored in an integer variable. If bit number 0 is on then it indicates Ist year student, bit number 1 to 3 stores IInd year, IIIrd year and IVth year student respectively. The bit number 4 to 7 stores stream Mechanical, Chemical, Electronics and IT. Rest of the bits store room number. Based on the given data, write a program that asks for the room number and displays the information about the student, if its data exists in the array. The contents of array are,int data[ ] = { 273, 548, 786, 1096 } ;

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

void main() {

unsigned int yr,br,data_yr,data_br; int i,j,k,rn,a,b,flag=0; int data[]={ 273,548,786,1096};

clrscr();

printf("Enter room number: "); scanf("%d",&rn);

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

/*********************/ /* checking for year */ /*********************/

for(i=1;i<=8;i=i*2) {

yr= rn & i;

if(yr==1) { printf("First year"); break; }

if(yr==2) { printf("Second year"); break; }

if(yr==4) { printf("Third year");

Solution:

Page 90: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

break; }

if(yr==8) { printf("Fourth year"); break; }

}

/***********************/ /* Checking for branch */ /***********************/

printf("\n\nBranch: ");

for(i=16;i<=128;i=i*2) {

br= rn & i;

if(br==16) { printf("Mechanical"); break; }

if(br==32) { printf("Chemical"); break; }

if(br==64) { printf("Electronics"); break; }

if(br==128) { printf("I.T."); break; }

}

/***********************************************/ /* checking if data matches with that of array */ /***********************************************/

for(i=1,j=16;i<=8,j<=128;i=i*2,j=j*2) {

yr=rn&i;

br=rn&j;

for(k=0,a=1,b=16;k<4,a<=8,b<=128;k++,a=a*2,b=b*2) {

data_yr=data[k] & a;

data_br=data[k] & b;

if(yr==data_yr && br==data_br) {

flag+=1;

break;

}

}

Page 91: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

Posted by Chetan Raikwar at 07:05 No comments:

}

if(flag==0) printf("\n\n\ndata doesn't matche with the array.\n");

else printf("\n\n\ndata matches with the array.\n");

getch(); }______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 13 (More Issues in Input Output)

(a) Write a program to carry out the following:(a) Read a text file provided at command prompt(b) Print each word in reverse orderFor example if the file containsINDIA IS MY COUNTRYOutput should beAIDNI SI YM YRTNUOC

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

void main(int argc, char *argv[]) {

FILE *fs;char ch,s[80];void rev();

if(argc!=2) {

printf("File name not supplied\n");

exit();

}

fs=fopen(argv[1],"r");

if(fs==NULL) {

printf("File not found!");

exit();}

while(fgets(s,79,fs)!=NULL)rev(s);

fclose(fs);

Exercise [B]

Solution:

Page 92: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

}

void rev(char s1[80]) {

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

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

s2[j]=s1[i];

if(s1[i]==' ' || s1[i]=='\0') {

s2[j]='\0';

strrev(s2);

printf("%s ",s2);

j=-1;

}

i++;j++;}

s2[j]='\0';

printf("%s",strrev(s2));

}

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

(b) Write a program using command line arguments to search for a word in a file and replace it with the specified word. The usage of the program is shown below.C> change <old word> <new word> <filename>

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

void replace();

void main ( int argc, char *argv[] ) {

FILE *fp,*ft;char str[80],str1[30],str2[30],nwstr[100];

clrscr();

if(argc!=4) {

puts("Improper argements passed!");exit();}

strcpy(str1,argv[1]);strcpy(str2,argv[2]);

fp=fopen(argv[3],"r");

if(fp==NULL) {

Solution:

Page 93: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

puts("cannot open source file!");exit();}

ft=fopen("NEW.TXT","w+");

if(ft==NULL) {

puts("cannot open target file!");exit();}

while(fgets(str,79,fp)!=NULL) {

replace(str,str1,str2,&nwstr);

fputs(nwstr,ft);}

fclose(fp);fclose(ft);

remove("FILE.TXT");rename("NEW.TXT","FILE.TXT");

printf("\n\nTask completed!\n\n");

getch();

}

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

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

/*******************************//* 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]==' ' || temp[i]==',' || temp[i]=='.') {

temp2[j]='\0';

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

strcpy(temp2,s2);

}

Page 94: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

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 */

/******************************************************************//* preparing new string to return to main and printing it on file *//******************************************************************/

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

*n=*m;

n++;m++;}

*n='\0';

}

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

(c) Write a program that can be used at command prompt as a calculating utility. The usage of the program is shown below.C> calc <switch> <n> <m>

Page 95: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

Where, n and m are two integer operands. switch can be any one of the arithmetic or comparison operators. If arithmetic operator is supplied, the output should be the result of the operation. If comparison operator is supplied then the output should be True or False.

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

void main(int argc, char *argv[]) {

int n,m,calc;

clrscr();

if(argc!=4)printf("Improper number of arguments");

/* converting both operands to integers */

n=atoi(argv[2]);

m=atoi(argv[3]);

printf("\n\nOutput: ");

/* comparing the operators passed at command prompt */

if(strcmp("+",argv[1])==0) {

printf("%d\n\n",n+m);

}

if(strcmp("-",argv[1])==0) {

printf("%d\n\n",n-m);

}

if(strcmp("*",argv[1])==0) {

printf("%d\n\n",n*m);

}

if(strcmp("/",argv[1])==0) {

printf("%d\n\n",n/m);

}

if(strcmp("%",argv[1])==0) {

printf("%d\n\n",n%m);

} /* IMPORTANT */

Solution:

Page 96: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

Posted by Chetan Raikwar at 07:05 No comments:

/* I have used dedicated variable for '<' and '>' comparison operators *//* because at command prompt, these are redirecting operators and cannot *//* be used simply for comparison. */

/* 1: "<" = "less" */ /* 2: ">" = "greater" */ /* type "less" for "<" and "greater" for ">" respectively if you want to perform comparison */

if(strcmp("greater",argv[1])==0) {

if(n>m)printf("True\n\n");

if(n<m)printf("False\n\n");

}

if(strcmp("less",argv[1])==0) {

if(n<m)printf("True\n\n");

if(n>m)printf("False\n\n");

}

if(strcmp("=",argv[1])==0) {

if(n==m)printf("True\n\n");

elseprintf("False\n\n");

}

}

_______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 11 (Console Input Output)

(a) Write down two functions xgets( ) and xputs( ) which work similar to the standard library functions gets( ) and puts( ).

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

Exercise [D]

Solution:

Page 97: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

void xgets();void xputs();

void main() {

char str[80];clrscr();

xgets(str);

printf("\n");

xputs(str);

getch();

}

void xgets( char *s) {

int i=0;char ch;

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

ch=getche();

if(ch=='\r') {

*s='\0';break;}

if(ch=='\b') {

printf("\b");

i-=2;s-=2;}

else {

*s=ch;s++;

}

}

}

void xputs( char *s) {

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

putch(*s);

s++;

}

}

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

(b) Write down a function getint( ), which would receive a numeric string from the keyboard, convert it to an integer number and return

Page 98: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

Posted by Chetan Raikwar at 07:04 No comments:

the integer to the calling function. A sample usage of getint( ) is shown below:main( ){int a ;a = getint( ) ;printf ( "you entered %d", a )}

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

int a; char s[80];

printf("Enter any numeric string: "); gets(s);

a=getint(s); /* converting and receiving string as integer */

printf("\n\nYou entered = %d\n",a);

getch();

}

int getint(char s1[80]) {

int digit;

digit=atoi(s1); /* converting string to integer */

return digit;

}

______________________________________________________________________

Solution:

Recommend this on Google

Let Us C / Chapter 10 (Structures)

(a) Create a structure to specify data on students given below:Roll number, Name, Department, Course, Year of joiningAssume 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.

/* NOTE: since number of students to be assumed is too much ( about 450 )I have alloted full size (about 450) to it but array has been kept empty,

Exercise [D]

Solution:

Page 99: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

if you have time then you can fill up all 450 names and can search throughthem.program has been tested by me and it works accurately. you can reducethe size of array of structure conveniently by changing the value of N */

#include<stdio.h>#include<conio.h>#define N 450

struct students { int rlnm; char name[25]; char dept[25]; /* structure defined outside of main(); */ char course[25]; int year; };

void main() { /* main() */

struct students s[N];int i,ch;

clrscr();

/* taking input of 450 students in an array of structure */

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

printf(" Enter data of student %d\t\t\t\ttotal students: %d\n",i+1,N);printf("****************************\n\n");

printf("enter rollnumber: ");scanf("%d",&s[i].rlnm);

printf("\n\nenter name: ");scanf(" %s",&s[i].name);

printf("\n\nenter department: ");scanf("%s",&s[i].dept);

printf("\n\nenter course: ");scanf("%s",&s[i].course);

printf("\n\nenter year of joining: ");scanf("%d",&s[i].year);

clrscr();

}

/* displaying a menu */

printf("\n\tenter your choice: \n");printf("\t**********************\n\n");

printf("1: enter year to search all students who took admission in that:\n\n");printf("2: enter roll number to see details of that student\n\n\n");

printf("your choice: "); /* taking input of your choice */scanf("%d",&ch);

clrscr();

switch(ch) {

case 1: clrscr();

dispyr(&s); /* function call to display names of students who joined in\ a particular year */

Page 100: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

break;

case 2: clrscr();

disprl(&s); /* function call to display information of a student \ whose roll number is given */

break;

default:

printf("\n\nerror! wrong choice");

}

getch();

}/******************* main() ends **************/

dispyr(struct students *a) { /* function for displaying names of students\ who took admission in a particular year */

int j,yr;

printf("\nenter year: ");scanf("%d",&yr);

printf("\n\nthese students joined in %d\n\n",yr);

for(j=0;j<N;j++) {

if(a[j].year==yr) {

printf("\n%s\n",a[j].name);}

}return 0;}

disprl(struct students *a) { /* function to print information of a\ student whose roll number has been \ given. */

int k,rl;

printf("\nenter roll number: ");scanf("%d",&rl);

for(k=0;k<N;k++) {

if(a[k].rlnm==rl) {

printf("\n\n\t Details of roll number: %d\n",a[k].rlnm);printf("\t***************************\n\n");printf(" Name: %s\n",a[k].name);printf(" Department: %s\n",a[k].dept);printf(" Course: %s\n",a[k].course);printf("Year of joining: %d",a[k].year);

break;}

else {printf("\nRoll number you entered does not exist\n\n");

break;}

Page 101: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

}

return 0;}

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

(b) 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”.

/* NOTE: since number of customers to be assumed is too much ( about 200 ) I have alloted full size (about 200) to it but array has been kept empty, if you have time then you can fill up all 200 names and can search through them.program has been tested by me and it works accurately. you can reducethe size of array of structure conveniently by changing the value of N */

#include<stdio.h> #include<conio.h> #define N 200

struct bank { int acn; char name[20]; int bal; /* defined out of main() */ };

void main() {

struct bank b[N];

int i,ch,lw=100,ch2,ac,am;

clrscr();

for(i=0;i<N;i++) { /* inputting customer data */

printf("\tEnter information of customers \n"); printf("\t******************************\n\n");

printf("enter account no.: "); scanf("%d",&b[i].acn);

printf("\n\nenter customer name: "); scanf("%s",&b[i].name);

printf("\n\nenter balance: "); scanf("%d",&b[i].bal);

clrscr();

}

Solution:

Page 102: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

clrscr();

printf("\tEnter your choice\n"); /* further processing of transaction */ printf("\t*****************\n\n");

printf("1: to know whose balance is below 100.\n\n"); printf("2: to process request or withdrawl.\n\n\n");

scanf("%d",&ch);

switch(ch) {

case 1:

clrscr();

disp(&b); /* displaying whose balance is below 100 */

break;

case 2:

clrscr();

printf("enter your account number: "); scanf("%d",&ac);

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

if((b[i].acn)==ac) {

clrscr();

printf("\tHello %s\n",b[i].name); printf("\n\n");

printf("\n\nenter your choice\n"); printf("\n1: deposite:\n"); printf("\n0: withdrawl:\n\n"); scanf("%d",&ch2);

switch(ch2) {

case 0:

clrscr();

if(b[i].bal<lw) {

printf("\n\nsorry! account balance is too low for withdrawl.\n");

break; }

else {

printf("\n\nenter amount for withdrawl: "); scanf("%d",&am);

}

if(b[i].bal<am) {

printf("\n\nyou don't have enough balance for withdrawl.\n");

Page 103: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

}

else {

b[i].bal=b[i].bal+am;

printf("\n\nwithdrawl was successful.\n");

} break;

case 1:

clrscr();

printf("\n\nenter amount to deposite: "); scanf("%d",&am);

b[i].bal=b[i].bal+am;

printf("\n\ncash deposited successfully.\n\n");

break;

}

} } } getch(); }

disp(struct bank *a) {

int k;

printf("\tCustomers whose balance is below 100:\n"); printf("\t*************************************\n\n");

for(k=0;k<N;k++) {

if((a[k].bal)<100) {

printf("%2d\t%s\n",a[k].acn,a[k].name);

} } return 0;

}

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

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

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

Solution:

Page 104: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

struct automob { char name[5]; int year; char mtr[10]; int qty; }; void main() {

struct automob a[54]={{"AA1",2009,"AAA",10}, {"AA2",2009,"AAA",10}, {"AA3",2009,"AAA",10}, {"AA4",2009,"AAA",10}, {"AA5",2009,"AAA",10}, {"AA6",2009,"AAA",10}, {"AA7",2009,"AAA",10}, {"AA8",2009,"AAA",10}, {"AA9",2009,"AAA",10}, {"BB1",2010,"BBB",11}, {"BB2",2010,"BBB",11}, {"BB3",2010,"BBB",11}, {"BB4",2010,"BBB",11}, {"BB5",2010,"BBB",11}, {"BB6",2010,"BBB",11}, {"BB7",2010,"BBB",11}, {"BB8",2010,"BBB",11}, {"BB9",2010,"BBB",11}, {"CC1",2011,"CCC",12}, {"CC2",2011,"CCC",12}, {"CC3",2011,"CCC",12}, {"CC4",2011,"CCC",12}, {"CC5",2011,"CCC",12}, {"CC6",2011,"CCC",12}, {"CC7",2011,"CCC",12}, {"CC8",2011,"CCC",12}, {"CC9",2011,"CCC",12}, {"DD1",2012,"DDD",13}, {"DD2",2012,"DDD",13}, {"DD3",2012,"DDD",13}, {"DD4",2012,"DDD",13}, {"DD5",2012,"DDD",13}, {"DD6",2012,"DDD",13}, {"DD7",2012,"DDD",13}, {"DD8",2012,"DDD",13}, {"DD9",2012,"DDD",13}, {"EE1",2013,"EEE",14}, {"EE2",2013,"EEE",14}, {"EE3",2013,"EEE",14}, {"EE4",2013,"EEE",14}, {"EE5",2013,"EEE",14}, {"EE6",2013,"EEE",14}, {"EE7",2013,"EEE",14}, {"EE8",2013,"EEE",14}, {"EE9",2013,"EEE",14}, {"FF1",2014,"FFF",15}, {"FF2",2014,"FFF",15}, {"FF3",2014,"FFF",15}, {"FF4",2014,"FFF",15}, {"FF5",2014,"FFF",15}, {"FF6",2014,"FFF",15}, {"FF7",2014,"FFF",15}, {"FF8",2014,"FFF",15}, {"FF9",2014,"FFF",15}};

int i,j,k;

clrscr();

Page 105: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

printf("Information of parts between BB1 to CC6:\n\n");

printf("\n\nName\t\tyear(manu.)\t\tmaterial\tquantity\n\n\n");

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

if(i>=9 && i<=23) { printf("%3s\t\t%4d\t\t\t%5s\t\t%4d\n",a[i].name,a[i].year,a[i].mtr,a[i].qty);

} }

getch(); }

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

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

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

void main() {

struct cricketer { char name[50]; int age; int match; float avrn; }; struct cricketer c[20],temp; int i,j; clrscr();

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

printf("Enter data of cricketer %d\n\n\n",i+1);

fflush(stdin); printf("Name: "); gets(c[i].name);

printf("\n\nAge: "); scanf("%d",&c[i].age);

printf("\n\nMatches: "); scanf("%d",&c[i].match);

printf("\n\nAverage runs: "); scanf("%f",&c[i].avrn);

clrscr();

Solution:

Page 106: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

}

/*******************/ /* sorting records */ /*******************/

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

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

if(c[i].avrn > c[j].avrn) {

temp=c[i]; c[i]=c[j]; c[j]=temp; } } }

printf("Sorted records:\n\n");

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

printf("%d\t%s\t%d\t%d\t%f\n\n\n",i+1,c[i].name,c[i].age,c[i].match,c[i].avrn);

}

getch(); }

linkfloat() {

float a=0,*b;

b=&a; a=*b;

return 0; }

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

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

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

struct employee { int code; char name[20]; int dd,mm,yy; } e[N];

int d,m,y,i;clrscr();

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

printf("\tEnter employee data:\n");

Solution:

Page 107: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

printf("\t*********************\n");

printf("\nEnter employee code: ");scanf("%d",&e[i].code);

printf("\n\nEnter employee name: ");scanf("%s",&e[i].name);

printf("\n\nEnter date of joining (dd mm yy): ");scanf("%d%d%d",&e[i].dd,&e[i].mm,&e[i].yy);

clrscr();

}

clrscr();

printf("\nenter current date(dd mm yy): \n\n");scanf("%d%d%d",&d,&m,&y);

clrscr();

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

if((y-(e[i].yy))>=3) {

printf("%s\n\N",e[i].name);

}

}

getch();}

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

(f) Write a menu driven program that depicts the working of a library. The menu options should be:1. Add book information2. Display book information3. List all books of given author4. List the title of specified book5. List the count of books in the library6. List the books in the order of accession number7. ExitCreate 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.

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

void main() {

struct library { int acn;

Solution:

Page 108: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

char title[25]; char auth[25]; float price; int flag; };

struct library a[5]={ {2,"AAA","AAA",154.8,1}, {1,"BBB","BBB",124.6,0}, {5,"EEE","EEE",234.3,0}, {3,"CCC","CCC",232.3,1}, {4,"DDD","DDD",121.3,0} };

struct library temp; /* temporary structure to overwrite information / and for assistance in sorting the whole structure */

int i,ch,k,flag,j=0; char author[10];

clrscr();

while(1) { /* initialized an indefinite loop */

clrscr(); printf("\t1: Add book information\n"); printf("\t2: Display book information\n"); printf("\t3: List all books of given author\n"); printf("\t4: List the title of specified book\n"); printf("\t5: List the count of books in the library\n"); printf("\t6: List the books in order of accesion number\n"); printf("\t7: Exit\n\n\n");

printf("Choice: "); scanf("%d",&ch);

switch(ch) {

case 1: /* adding book information over current information */

clrscr();

printf("\t\t1: Add book information:\n\n\n");

printf("enter book information:\n\n");

printf("Accesion number of book to be modified: "); scanf("%d",&j); fflush(stdin);

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

if(j==a[i].acn) {

printf("\n\nenter new information:\n\n"); printf("accesion no.: "); scanf("%d",&temp.acn); fflush(stdin); printf("\n\ntitle: "); scanf("%s",&temp.title); fflush(stdin); printf("\n\nauthor: "); scanf("%s",&temp.auth); fflush(stdin); printf("\n\nprice: "); scanf("%f",&temp.auth); fflush(stdin); printf("\n\nflag(1/0): "); scanf("%d",&temp.flag); fflush(stdin);

} }

Page 109: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

a[j]=temp; /* overwriting current information with new one */

clrscr();

printf("\n\nInformation added succesfully!\n\n");

delay(2000);

break;

case 2: /* displaying current book information */

clrscr();

printf("\t\t2: Display book information:\n\n\n");

printf("Enter accesion number: "); scanf("%d",&k);

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

if(k==a[i].acn) { clrscr(); printf("Book information: \n\n"); printf("\n\nAccesion Number: %d",a[i].acn); printf("\nTitle: %s",a[i].title); printf("\nAuthor: %s",a[i].auth); printf("\nPrice: %f",a[i].price);

if(a[i].flag==0) { printf("\nFlag: Not issued\n\n"); } else{ printf("\nFlag: Issued\n\n"); } } } delay(1000);

break;

case 3: /* listing all books of given author */

clrscr();

printf("\t\t3: List all books of given author:\n\n\n");

printf("Enter author name: "); scanf("%s",&author); fflush(stdin);

printf("\n\nbooks of %s\n\n",author); for(i=0;i<5;i++) {

k=strcmp(author,a[i].auth);

if(k==0) { j=j+1; printf("%d.\t%s\n",j,a[i].title);

} } delay(2000); break;

case 4: /* displaying title of given book */

Page 110: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

clrscr(); printf("\t\t4: Title of the specified book:\n\n\n");

printf("Enter the accesion number: "); scanf("%d",&k);

printf("\n\n");

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

if(k==a[i].acn) {

printf("Title: %s\n",a[i].title);

} } delay(2000); break;

case 5: /* counting total books in library */

clrscr(); printf("\t\t5: List the count of books in the library: \n\n\n");

for(i=0;i<5;i++) { j=j+1; } printf("\tTotal books: %2d",j);

delay(2000); break;

case 6: /* sorting the books by their accesion numbers */

clrscr(); printf("6: List the books in order of accesion number: \n\n\n");

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

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

if(a[i].acn>a[j].acn) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } }

printf("Access no.\tTitle\tAuthor\tFlag\n\n\n"); for(i=0;i<5;i++) {

printf("%4d\t\t%5s\t%5s\t",a[i].acn,a[i].title,a[i].auth);

if(a[i].flag==0) printf("not issued\n\n");

else printf("issued\n\n"); }

delay(2000); break;

case 7: /* condition for going out */

Page 111: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

exit();

} }

}

linkfloat() { /* special function to solve compilar error */ float a=0,*b; /* not used withing the program but still defined */ b=&a; a=*b; return 0; }

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

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

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

void main() {

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

int d,m,y,i;clrscr();

printf("enter the date to save in structure: \n\n");

printf("Enter the date: ");scanf("%d",&d1.date);

printf("\n\nEnter the month: ");scanf("%d",&d1.month);

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

clrscr();

printf("\nenter the date to compare with structure:\n\n");

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

printf("\n\nEnter the month: ");scanf("%d",&m);

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

if(d==d1.date && m==d1.month && y==d1.year) {

printf("\n\ndates are equal\n\n");

}

else {

Solution:

Page 112: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

printf("\n\ndates are unequal\n\n");

}

getch();

}

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

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

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

struct linklist { int data; linklist *link; };

void main() {

struct linklist *first, *temp;

char choice='y';

int count=0;

clrscr();

/* taking the input of first element */

printf("Enter element %d: ",++count);

first=(linklist *)malloc(sizeof(linklist));

scanf("%d",&first->data);

first->link=NULL;

printf("\n\nEnter another element(Y/N): ");

choice=getche();

tolower(choice); /* converting to lowercase to match the condition of switch */

Solution:

Page 113: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

switch(choice) {

case 'y':

clrscr();

while(choice=='y' || choice=='Y') {

printf("\nEnter element %d: ",++count);

temp=(linklist *)malloc(sizeof(linklist));

scanf("%d",&temp->data);

temp->link=first;

first=temp;

printf("\n\n\nEnter another elements(Y/N): ");choice=getche();

clrscr();

}

break;

case 'n':

break;

}

printf("\nTotal elements = %d\n\n",count);

/* printing all elements */

for(temp=first; temp!=NULL; temp=temp->link) {

printf("%d ",temp->data);

}

getch();

}

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

(i) A stack is a data structure in which addition of new element or deletion of existing element always takes place at the same end. This end is often known as ‘top’ of stack. This situation can be compared to a stack of plates in a cafeteria where every new plate taken off the stack is also from the ‘top’ of the stack. There are several application where stack can be put to use. For example, recursion, keeping track of function calls, evaluation of expressions, etc. Write a program to implement a stack using a linked list.

Page 114: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): January 2014

http://letuscalllessons.blogspot.com/2014_01_01_archive.html[07-Apr-14 8:40:59 PM]

Newer Posts Older PostsHome

Subscribe to: Posts (Atom)

Posted by Chetan Raikwar at 07:04 No comments:

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

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

(j) Unlike a stack, in a queue the addition of new element takes place at the end (called ‘rear’ of queue) whereas deletion takes place at the other end (called ‘front’ of queue). Write a program to implement a queue using a linked list

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

Solution:

Solution:

Recommend this on Google

Simple template. Powered by Blogger.

Page 115: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): February 2014

http://letuscalllessons.blogspot.com/2014_02_01_archive.html[07-Apr-14 8:42:00 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Monday, 3 February 2014

Drawing a hut using graphics

NOTE: please change the "initgraph" path of BGI directory according to your turbo C++ IDE's directory.

#include<graphics.h>void main() {

int gd=DETECT,gm;

initgraph(&gd,&gm,"c:\\turboc3\\bgi");

line(200,100,170,200);line(200,100,250,200);line(200,100,400,100);line(400,100,450,200);line(450,200,250,200);line(178,176,178,277);line(245,190,245,300);line(440,200,440,300);line(440,300,245,300);line(245,300,178,277);line(210,288,210,215);line(190,280,190,215);line(190,215,210,215);

rectangle(300,210,380,260);

setfillstyle(5,RED);floodfill(399,101,WHITE);

setfillstyle(SOLID_FILL,WHITE^23);floodfill(299,209,WHITE);

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

► January (14)

▼ February (2)

Dynamic calender animated without graphics library...

Drawing a hut using graphics

Blog Archive

More Next Blog» Create Blog Sign In

Page 116: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): February 2014

http://letuscalllessons.blogspot.com/2014_02_01_archive.html[07-Apr-14 8:42:00 PM]

Posted by Chetan Raikwar at 11:11 No comments:

floodfill(179,275,WHITE);

setfillstyle(SOLID_FILL,BLACK^9);floodfill(191,216,WHITE);

floodfill(379,258,WHITE);

setcolor(BLACK);settextstyle(8,HORIZ_DIR,3);outtextxy(200,200,"Chetan Raikwar");

setcolor(BLUE);setfillstyle(CLOSE_DOT_FILL,BLUE);floodfill(0,0,WHITE);getch();closegraph();restorecrtmode();

}

+1 Recommend this on Google

Dynamic calender animated without graphics library

#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=2,year=2014,a;

Page 117: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): February 2014

http://letuscalllessons.blogspot.com/2014_02_01_archive.html[07-Apr-14 8:42:00 PM]

void box();

clrscr();

/***********************************************//* 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) {

sound(1400);delay(20);sound(750);delay(10);nosound();

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

}

/* if down arrow key is hit */

if(key==80) {

sound(1400);delay(20);sound(850);delay(10);nosound();

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

}

/* if left arrow key is hit */

if(key==75) {

sound(1600);delay(20);sound(1250);delay(10);nosound();

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

}

/* if right arrow key is hit */

if(key==77) {

sound(1600);

Page 118: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): February 2014

http://letuscalllessons.blogspot.com/2014_02_01_archive.html[07-Apr-14 8:42:00 PM]

delay(20);sound(1250);delay(10);

nosound();

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);

if(x==22)textcolor(RED);

elsetextcolor(YELLOW);

cprintf("%2d",i);

i++;x+=5;

if(x>52) { /* if the position of 7 days is covered, again print frombeginning 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);

}

elseprintf("Error! invalid input\n");

getch();

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

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

Page 119: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): February 2014

http://letuscalllessons.blogspot.com/2014_02_01_archive.html[07-Apr-14 8:42:00 PM]

/**********************************************************/

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 *//*************/

textcolor(BLUE);/* corners of inner box */

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

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

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

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

/* boundries of inner box */

Page 120: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): February 2014

http://letuscalllessons.blogspot.com/2014_02_01_archive.html[07-Apr-14 8:42:00 PM]

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

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

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

}

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

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

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

}

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

/* corners of outer box */

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

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

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

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

/* boundries of outer box */

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

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

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

}

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

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

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

}

textcolor(GREEN+BLINK);gotoxy(24,22);cprintf("%c%c%c%c %c%c %c%c%c%c%c%c%c%c%c%c%c%c%c",77,65,68,69,66,89,67,72,69,84,65,78,82,65,73,75,87,65,82);

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

Page 121: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): February 2014

http://letuscalllessons.blogspot.com/2014_02_01_archive.html[07-Apr-14 8:42:00 PM]

textcolor(RED);

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

textcolor(YELLOW);

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

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

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

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

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

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

textcolor(LIGHTGREEN);

gotoxy(32,4);

if(m==1)cprintf("January ");

if(m==2)cprintf("February ");

if(m==3)cprintf("March ");

if(m==4)cprintf("April ");

if(m==5)cprintf("May ");

if(m==6)cprintf("June ");

if(m==7)cprintf("July ");

if(m==8)cprintf("August ");

if(m==9)cprintf("September ");

if(m==10)cprintf("October ");

if(m==11)cprintf("November ");

if(m==12)cprintf("December ");

textcolor(CYAN);cprintf("%d",y);/*************************//* printing instructions *//*************************/

Page 122: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): February 2014

http://letuscalllessons.blogspot.com/2014_02_01_archive.html[07-Apr-14 8:42:00 PM]

textcolor(BROWN);

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

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

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

gotoxy(60,22);cprintf("%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;

elsedays=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 */

Page 124: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Dynamic calender animated without graphics library

http://letuscalllessons.blogspot.com/2014/02/dynamic-calender-animated-without.html[07-Apr-14 8:42:57 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Monday, 3 February 2014

Dynamic calender animated without graphics library

#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=2,year=2014,a;void box();

clrscr();

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

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

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

► January (14)

▼ February (2)

Dynamic calender animated without graphics library...

Drawing a hut using graphics

Blog Archive

More Next Blog» Create Blog Sign In

Page 125: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Dynamic calender animated without graphics library

http://letuscalllessons.blogspot.com/2014/02/dynamic-calender-animated-without.html[07-Apr-14 8:42:57 PM]

do {

/* if up arrow key is hit */

if(key==72) {

sound(1400);delay(20);sound(750);delay(10);nosound();

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

}

/* if down arrow key is hit */

if(key==80) {

sound(1400);delay(20);sound(850);delay(10);nosound();

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

}

/* if left arrow key is hit */

if(key==75) {

sound(1600);delay(20);sound(1250);delay(10);nosound();

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

}

/* if right arrow key is hit */

if(key==77) {

sound(1600);delay(20);sound(1250);delay(10);

nosound();

if(month+1 > 12){}

Page 126: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Dynamic calender animated without graphics library

http://letuscalllessons.blogspot.com/2014/02/dynamic-calender-animated-without.html[07-Apr-14 8:42:57 PM]

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);

if(x==22)textcolor(RED);

elsetextcolor(YELLOW);

cprintf("%2d",i);

i++;x+=5;

if(x>52) { /* if the position of 7 days is covered, again print frombeginning 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);

}

elseprintf("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 */

Page 127: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Dynamic calender animated without graphics library

http://letuscalllessons.blogspot.com/2014/02/dynamic-calender-animated-without.html[07-Apr-14 8:42:57 PM]

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 *//*************/

textcolor(BLUE);/* corners of inner box */

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

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

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

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

/* boundries of inner box */

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

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

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

Page 128: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Dynamic calender animated without graphics library

http://letuscalllessons.blogspot.com/2014/02/dynamic-calender-animated-without.html[07-Apr-14 8:42:57 PM]

}

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

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

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

}

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

/* corners of outer box */

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

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

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

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

/* boundries of outer box */

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

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

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

}

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

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

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

}

textcolor(GREEN+BLINK);gotoxy(24,22);cprintf("%c%c%c%c %c%c %c%c%c%c%c%c%c%c%c%c%c%c%c",77,65,68,69,66,89,67,72,69,84,65,78,82,65,73,75,87,65,82);

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

textcolor(RED);

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

textcolor(YELLOW);

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

Page 129: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Dynamic calender animated without graphics library

http://letuscalllessons.blogspot.com/2014/02/dynamic-calender-animated-without.html[07-Apr-14 8:42:57 PM]

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

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

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

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

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

textcolor(LIGHTGREEN);

gotoxy(32,4);

if(m==1)cprintf("January ");

if(m==2)cprintf("February ");

if(m==3)cprintf("March ");

if(m==4)cprintf("April ");

if(m==5)cprintf("May ");

if(m==6)cprintf("June ");

if(m==7)cprintf("July ");

if(m==8)cprintf("August ");

if(m==9)cprintf("September ");

if(m==10)cprintf("October ");

if(m==11)cprintf("November ");

if(m==12)cprintf("December ");

textcolor(CYAN);cprintf("%d",y);/*************************//* printing instructions *//*************************/

textcolor(BROWN);

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

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

gotoxy(60,20);

Page 130: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Dynamic calender animated without graphics library

http://letuscalllessons.blogspot.com/2014/02/dynamic-calender-animated-without.html[07-Apr-14 8:42:57 PM]

cprintf("%c : Next month",16);

gotoxy(60,22);cprintf("%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;

elsedays=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;

Page 132: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 14 (Operations on Bits)

http://letuscalllessons.blogspot.com/2014/01/chapter-14-operations-on-bits.html[07-Apr-14 8:43:44 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 14 (Operations on Bits)

(a) The information about colors is to be stored in bits of a char variable called color. The bit number 0 to 6, each represent 7 colors of a rainbow, i.e. bit 0 represents violet, 1 representsindigo, and so on. Write a program that asks the user to enter a number and based on this number it reports which colors in the rainbow does the number represents.

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

char color; int num;

clrscr();

printf("Please enter the number(0-6): "); scanf("%d",&num);

color=1<<num;

printf("\n\n");

if(num==0 && color==1) printf("Violet");

else if(num==1 && color==2) printf("Indigo");

else if(num==2 && color==4) printf("Blue");

else if(num==3 && color==8) printf("Green");

else if(num==4 && color==16) printf("Yellow");

else if(num==5 && color==32) printf("Orange");

else if(num==6 && color==64)

Exercise [A]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 133: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 14 (Operations on Bits)

http://letuscalllessons.blogspot.com/2014/01/chapter-14-operations-on-bits.html[07-Apr-14 8:43:44 PM]

printf("Red");

else printf("Wrong color number!");

getch();

}

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

(b) A company planning to launch a new newspaper in market conducts a survey. The various parameters considered in the survey were, the economic status (upper, middle, and lower class) the languages readers prefer (English, Hindi, Regional language) and category of paper (daily, supplement, tabloid). Write a program, which reads data of 10 respondents through keyboard, and stores the information in an array of integers. The bit-wise information to be stored in an integer is given below:Bit Number Information0 Upper class1 Middle class2 Lower class3 English4 Hindi5 Regional Language6 Daily7 Supplement8 TabloidAt the end give the statistical data for number of persons who read English daily, number of upper class people who read tabloid and number of regional language readers.

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

int arr[10][3],i,j; unsigned int infr; int eng=0,utab=0,rgl=0;

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

clrscr();

gotoxy(20,2); printf("Enter data of respondent %d:\n\n",i+1);

for(j=0;j<3;j++) {

if(j==0){ printf("Economic Status:\n\n"); printf("0: Upper class\t1: Middle class\t2: Lower class\n\n");

scanf("%d",&arr[i][j]); }

if(j==1){ printf("\n\nLanguage Preferred:\n\n"); printf("3: English\t4: Hindi\t5:Regional Language\n\n");

Solution:

Page 134: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 14 (Operations on Bits)

http://letuscalllessons.blogspot.com/2014/01/chapter-14-operations-on-bits.html[07-Apr-14 8:43:44 PM]

scanf("%d",&arr[i][j]); }

if(j==2){

printf("\n\nType of Paper:\n\n"); printf("6: Daily\t7: Supplement\t8: Tabloid\n\n");

scanf("%d",&arr[i][j]); }

} }

/***********************************************/ /* converting the whole array using left shift */ /***********************************************/

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

for(j=0;j<3;j++) {

arr[i][j]= 1 << arr[i][j]; /* conversion */

} }

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

if(arr[i][1]==8) /* english readers */ eng++;

if(arr[i][0]==1 && arr[i][2]==256) /* upper class,tabloid readers */ utab++;

if(arr[i][1]==32) /* regional language readers */ rgl++; }

clrscr();

gotoxy(20,2); printf("Reader's statistics:\n\n\n\n"); printf("\tEnglish Reader: %d\n",eng); printf("\tUpper class Tabloid Readers: %d\n",utab); printf("\tRegional Language readers: %d\n",rgl); getch();

}

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

(c) In an inter-college competition, various sports and games are played between different colleges like cricket, basketball, football, hockey, lawn tennis, table tennis, carom and chess. The information regarding the games won by a particular college is stored in bit numbers 0, 1, 2, 3, 4, 5, 6, 7 and 8 respectively of an integer variable called game. The college that wins in 5 or more than 5 games is awarded the Champion of Champions trophy. If a number is entered through the keyboard, then write a program to find out whether the college won the Champion of the Champions trophy or not, along with the names of the games won by the college.

Page 135: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 14 (Operations on Bits)

http://letuscalllessons.blogspot.com/2014/01/chapter-14-operations-on-bits.html[07-Apr-14 8:43:44 PM]

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

int game; int i,won=0,name;

clrscr();

printf("Enter number: ");

scanf("%d",&name);

printf("\n\n");

for(i=1;i<=8;i++) {

game=i&name;

if(game==1) { printf("Cricket\n");

won++; }

if(game==2) { printf("Basketball\n");

won++; }

if(game==3) { printf("Football\n");

won++; }

if(game==4) { printf("Hockey\n");

won++; }

if(game==5) { printf("Lawn-tennis\n");

won++; }

if(game==6) { printf("Table-tennis\n");

won++; }

if(game==7) { printf("Carrom\n");

won++; }

if(game==8) { printf("Chess\n");

won++;

Solution:

Page 136: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 14 (Operations on Bits)

http://letuscalllessons.blogspot.com/2014/01/chapter-14-operations-on-bits.html[07-Apr-14 8:43:44 PM]

}

}

if(won>=5) {

printf("\n\n\nCollege %d has won the champions trophy\n",name);

}

else {

printf("\n\n\nCollege %d didn't win the champions trophy\n",name);

}

getch(); }

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

(d) An animal could be either a canine (dog, wolf, fox, etc.), a feline (cat, lynx, jaguar, etc.), a cetacean (whale, narwhal, etc.) or a marsupial (koala, wombat, etc.). The information whether a particular animal is canine, feline, cetacean, or marsupial is stored in bit number 0, 1, 2 and 3 respectively of a integer variable called type. Bit number 4 of the variable type stores the information about whether the animal is Carnivore or Herbivore.For the following animal, complete the program to determine whether the animal is a herbivore or a carnivore. Also determine whether the animal is a canine, feline, cetacean or a marsupial.struct animal{char name[30] ;int type ;}struct animal a = { "OCELOT", 18 } ;

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

struct animal { char name[30]; int type; };

struct animal a={"OCELOT",18};

int t1,t2,typ1,typ2;

clrscr();

t1= a.type >> 3;

typ1= t1 & 2; /* checking the bit after shifting */

t2= t1 << 3;

typ2= t2 & 16; /* checking another bit after shifting */

Solution:

Page 137: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 14 (Operations on Bits)

http://letuscalllessons.blogspot.com/2014/01/chapter-14-operations-on-bits.html[07-Apr-14 8:43:44 PM]

/**********************************************************/ /* checking if ocelot is canine/feline/cetacean/marsupial */ /**********************************************************/

if(typ1==1) printf("\n\nOCELOT is Canine\n");

if(typ1==2) printf("\n\nOCELOT is Feline\n");

if(typ1==4) printf("\n\nOCELOT is Cetacean\n");

if(typ1==8) printf("\n\nOCELOT is Marsupial\n");

/************************************************/ /* checking if ocelot is carnivore or herbivore */ /************************************************/

if(typ2!=0) printf("\n\nOCELOT is Carnivore\n");

if(typ2==0) printf("\n\nOCELOT is Herbivore\n");

getch();

}

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

(e)The time field in the directory entry is 2 bytes long. Distribution of different bits which account for hours, minutes and seconds is given below. Write a function which would receive the two-byte time entry and return to the calling function, the hours, minutes and seconds. 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 H H H H H M M M M M M S S S S S

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

unsigned hr,mn,sc,input;

void timer();

clrscr();

printf("Enter the time entry: ");

scanf("%d",&input);

timer(input,&hr,&mn,&sc);

printf("\n\nTIME: %u : %u : %u\n",*(&hr),*(&mn),*(&sc));

getch();

Solution:

Page 138: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 14 (Operations on Bits)

http://letuscalllessons.blogspot.com/2014/01/chapter-14-operations-on-bits.html[07-Apr-14 8:43:44 PM]

}

void timer(unsigned time, unsigned *hr, unsigned *mn, unsigned *sc) {

*hr=time >> 11;

*mn=(time<<5) >> 10;

*sc=(time<<11) >> 11;

}

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

(f) In order to save disk space information about student is stored in an integer variable. If bit number 0 is on then it indicates Ist year student, bit number 1 to 3 stores IInd year, IIIrd year and IVth year student respectively. The bit number 4 to 7 stores stream Mechanical, Chemical, Electronics and IT. Rest of the bits store room number. Based on the given data, write a program that asks for the room number and displays the information about the student, if its data exists in the array. The contents of array are,int data[ ] = { 273, 548, 786, 1096 } ;

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

void main() {

unsigned int yr,br,data_yr,data_br; int i,j,k,rn,a,b,flag=0; int data[]={ 273,548,786,1096};

clrscr();

printf("Enter room number: "); scanf("%d",&rn);

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

/*********************/ /* checking for year */ /*********************/

for(i=1;i<=8;i=i*2) {

yr= rn & i;

if(yr==1) { printf("First year"); break; }

if(yr==2) { printf("Second year"); break; }

if(yr==4) { printf("Third year");

Solution:

Page 139: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 14 (Operations on Bits)

http://letuscalllessons.blogspot.com/2014/01/chapter-14-operations-on-bits.html[07-Apr-14 8:43:44 PM]

break; }

if(yr==8) { printf("Fourth year"); break; }

}

/***********************/ /* Checking for branch */ /***********************/

printf("\n\nBranch: ");

for(i=16;i<=128;i=i*2) {

br= rn & i;

if(br==16) { printf("Mechanical"); break; }

if(br==32) { printf("Chemical"); break; }

if(br==64) { printf("Electronics"); break; }

if(br==128) { printf("I.T."); break; }

}

/***********************************************/ /* checking if data matches with that of array */ /***********************************************/

for(i=1,j=16;i<=8,j<=128;i=i*2,j=j*2) {

yr=rn&i;

br=rn&j;

for(k=0,a=1,b=16;k<4,a<=8,b<=128;k++,a=a*2,b=b*2) {

data_yr=data[k] & a;

data_br=data[k] & b;

if(yr==data_yr && br==data_br) {

flag+=1;

break;

}

}

Page 140: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 14 (Operations on Bits)

http://letuscalllessons.blogspot.com/2014/01/chapter-14-operations-on-bits.html[07-Apr-14 8:43:44 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Posted by Chetan Raikwar at 07:05

}

if(flag==0) printf("\n\n\ndata doesn't matche with the array.\n");

else printf("\n\n\ndata matches with the array.\n");

getch(); }______________________________________________________________________

Recommend this on Google

Comment as: Google Account

No comments:

Post a Comment

Simple template. Powered by Blogger.

Page 141: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 13 (More Issues in Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-13-more-issues-in-input-output.html[07-Apr-14 8:44:36 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 13 (More Issues in Input Output)

(a) Write a program to carry out the following:(a) Read a text file provided at command prompt(b) Print each word in reverse orderFor example if the file containsINDIA IS MY COUNTRYOutput should beAIDNI SI YM YRTNUOC

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

void main(int argc, char *argv[]) {

FILE *fs;char ch,s[80];void rev();

if(argc!=2) {

printf("File name not supplied\n");

exit();

}

fs=fopen(argv[1],"r");

if(fs==NULL) {

printf("File not found!");

exit();}

while(fgets(s,79,fs)!=NULL)rev(s);

fclose(fs);

}

Exercise [B]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 142: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 13 (More Issues in Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-13-more-issues-in-input-output.html[07-Apr-14 8:44:36 PM]

void rev(char s1[80]) {

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

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

s2[j]=s1[i];

if(s1[i]==' ' || s1[i]=='\0') {

s2[j]='\0';

strrev(s2);

printf("%s ",s2);

j=-1;

}

i++;j++;}

s2[j]='\0';

printf("%s",strrev(s2));

}

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

(b) Write a program using command line arguments to search for a word in a file and replace it with the specified word. The usage of the program is shown below.C> change <old word> <new word> <filename>

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

void replace();

void main ( int argc, char *argv[] ) {

FILE *fp,*ft;char str[80],str1[30],str2[30],nwstr[100];

clrscr();

if(argc!=4) {

puts("Improper argements passed!");exit();}

strcpy(str1,argv[1]);strcpy(str2,argv[2]);

fp=fopen(argv[3],"r");

if(fp==NULL) {

puts("cannot open source file!");

Solution:

Page 143: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 13 (More Issues in Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-13-more-issues-in-input-output.html[07-Apr-14 8:44:36 PM]

exit();}

ft=fopen("NEW.TXT","w+");

if(ft==NULL) {

puts("cannot open target file!");exit();}

while(fgets(str,79,fp)!=NULL) {

replace(str,str1,str2,&nwstr);

fputs(nwstr,ft);}

fclose(fp);fclose(ft);

remove("FILE.TXT");rename("NEW.TXT","FILE.TXT");

printf("\n\nTask completed!\n\n");

getch();

}

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

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

/*******************************//* 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]==' ' || temp[i]==',' || temp[i]=='.') {

temp2[j]='\0';

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

strcpy(temp2,s2);

}

Page 144: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 13 (More Issues in Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-13-more-issues-in-input-output.html[07-Apr-14 8:44:36 PM]

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 */

/******************************************************************//* preparing new string to return to main and printing it on file *//******************************************************************/

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

*n=*m;

n++;m++;}

*n='\0';

}

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

(c) Write a program that can be used at command prompt as a calculating utility. The usage of the program is shown below.C> calc <switch> <n> <m>

Page 145: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 13 (More Issues in Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-13-more-issues-in-input-output.html[07-Apr-14 8:44:36 PM]

Where, n and m are two integer operands. switch can be any one of the arithmetic or comparison operators. If arithmetic operator is supplied, the output should be the result of the operation. If comparison operator is supplied then the output should be True or False.

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

void main(int argc, char *argv[]) {

int n,m,calc;

clrscr();

if(argc!=4)printf("Improper number of arguments");

/* converting both operands to integers */

n=atoi(argv[2]);

m=atoi(argv[3]);

printf("\n\nOutput: ");

/* comparing the operators passed at command prompt */

if(strcmp("+",argv[1])==0) {

printf("%d\n\n",n+m);

}

if(strcmp("-",argv[1])==0) {

printf("%d\n\n",n-m);

}

if(strcmp("*",argv[1])==0) {

printf("%d\n\n",n*m);

}

if(strcmp("/",argv[1])==0) {

printf("%d\n\n",n/m);

}

if(strcmp("%",argv[1])==0) {

printf("%d\n\n",n%m);

} /* IMPORTANT */

Solution:

Page 146: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 13 (More Issues in Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-13-more-issues-in-input-output.html[07-Apr-14 8:44:36 PM]

Posted by Chetan Raikwar at 07:05

/* I have used dedicated variable for '<' and '>' comparison operators *//* because at command prompt, these are redirecting operators and cannot *//* be used simply for comparison. */

/* 1: "<" = "less" */ /* 2: ">" = "greater" */ /* type "less" for "<" and "greater" for ">" respectively if you want to perform comparison */

if(strcmp("greater",argv[1])==0) {

if(n>m)printf("True\n\n");

if(n<m)printf("False\n\n");

}

if(strcmp("less",argv[1])==0) {

if(n<m)printf("True\n\n");

if(n>m)printf("False\n\n");

}

if(strcmp("=",argv[1])==0) {

if(n==m)printf("True\n\n");

elseprintf("False\n\n");

}

}

_______________________________________________________________________

Recommend this on Google

Google Account

No comments:

Post a Comment

Page 147: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 13 (More Issues in Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-13-more-issues-in-input-output.html[07-Apr-14 8:44:36 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Comment as:

Simple template. Powered by Blogger.

Page 148: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 11 (Console Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-11-console-input-output.html[07-Apr-14 8:45:28 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 11 (Console Input Output)

(a) Write down two functions xgets( ) and xputs( ) which work similar to the standard library functions gets( ) and puts( ).

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

void xgets();void xputs();

void main() {

char str[80];clrscr();

xgets(str);

printf("\n");

xputs(str);

getch();

}

void xgets( char *s) {

int i=0;char ch;

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

ch=getche();

if(ch=='\r') {

*s='\0';break;}

if(ch=='\b') {

printf("\b");

Exercise [D]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 149: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 11 (Console Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-11-console-input-output.html[07-Apr-14 8:45:28 PM]

i-=2;s-=2;}

else {

*s=ch;s++;

}

}

}

void xputs( char *s) {

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

putch(*s);

s++;

}

}

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

(b) Write down a function getint( ), which would receive a numeric string from the keyboard, convert it to an integer number and return the integer to the calling function. A sample usage of getint( ) is shown below:main( ){int a ;a = getint( ) ;printf ( "you entered %d", a )}

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

int a; char s[80];

printf("Enter any numeric string: "); gets(s);

a=getint(s); /* converting and receiving string as integer */

printf("\n\nYou entered = %d\n",a);

getch();

}

int getint(char s1[80]) {

int digit;

Solution:

Page 151: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 10 (Structures)

(a) Create a structure to specify data on students given below:Roll number, Name, Department, Course, Year of joiningAssume 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.

/* NOTE: since number of students to be assumed is too much ( about 450 )I have alloted full size (about 450) to it but array has been kept empty,if you have time then you can fill up all 450 names and can search throughthem.program has been tested by me and it works accurately. you can reducethe size of array of structure conveniently by changing the value of N */

#include<stdio.h>#include<conio.h>#define N 450

struct students { int rlnm; char name[25]; char dept[25]; /* structure defined outside of main(); */ char course[25]; int year; };

void main() { /* main() */

struct students s[N];int i,ch;

clrscr();

/* taking input of 450 students in an array of structure */

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

printf(" Enter data of student %d\t\t\t\ttotal students: %d\n",i+1,N);printf("****************************\n\n");

printf("enter rollnumber: ");scanf("%d",&s[i].rlnm);

Exercise [D]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 152: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

printf("\n\nenter name: ");scanf(" %s",&s[i].name);

printf("\n\nenter department: ");scanf("%s",&s[i].dept);

printf("\n\nenter course: ");scanf("%s",&s[i].course);

printf("\n\nenter year of joining: ");scanf("%d",&s[i].year);

clrscr();

}

/* displaying a menu */

printf("\n\tenter your choice: \n");printf("\t**********************\n\n");

printf("1: enter year to search all students who took admission in that:\n\n");printf("2: enter roll number to see details of that student\n\n\n");

printf("your choice: "); /* taking input of your choice */scanf("%d",&ch);

clrscr();

switch(ch) {

case 1: clrscr();

dispyr(&s); /* function call to display names of students who joined in\ a particular year */

break;

case 2: clrscr();

disprl(&s); /* function call to display information of a student \ whose roll number is given */

break;

default:

printf("\n\nerror! wrong choice");

}

getch();

}/******************* main() ends **************/

dispyr(struct students *a) { /* function for displaying names of students\ who took admission in a particular year */

int j,yr;

printf("\nenter year: ");scanf("%d",&yr);

printf("\n\nthese students joined in %d\n\n",yr);

for(j=0;j<N;j++) {

Page 153: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

if(a[j].year==yr) {

printf("\n%s\n",a[j].name);}

}return 0;}

disprl(struct students *a) { /* function to print information of a\ student whose roll number has been \ given. */

int k,rl;

printf("\nenter roll number: ");scanf("%d",&rl);

for(k=0;k<N;k++) {

if(a[k].rlnm==rl) {

printf("\n\n\t Details of roll number: %d\n",a[k].rlnm);printf("\t***************************\n\n");printf(" Name: %s\n",a[k].name);printf(" Department: %s\n",a[k].dept);printf(" Course: %s\n",a[k].course);printf("Year of joining: %d",a[k].year);

break;}

else {printf("\nRoll number you entered does not exist\n\n");

break;}

}

return 0;}

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

(b) 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”.

/* NOTE: since number of customers to be assumed is too much ( about 200 ) I have alloted full size (about 200) to it but array has been kept empty, if you have time then you can fill up all 200 names and can search through

Solution:

Page 154: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

them.program has been tested by me and it works accurately. you can reducethe size of array of structure conveniently by changing the value of N */

#include<stdio.h> #include<conio.h> #define N 200

struct bank { int acn; char name[20]; int bal; /* defined out of main() */ };

void main() {

struct bank b[N];

int i,ch,lw=100,ch2,ac,am;

clrscr();

for(i=0;i<N;i++) { /* inputting customer data */

printf("\tEnter information of customers \n"); printf("\t******************************\n\n");

printf("enter account no.: "); scanf("%d",&b[i].acn);

printf("\n\nenter customer name: "); scanf("%s",&b[i].name);

printf("\n\nenter balance: "); scanf("%d",&b[i].bal);

clrscr();

}

clrscr();

printf("\tEnter your choice\n"); /* further processing of transaction */ printf("\t*****************\n\n");

printf("1: to know whose balance is below 100.\n\n"); printf("2: to process request or withdrawl.\n\n\n");

scanf("%d",&ch);

switch(ch) {

case 1:

clrscr();

disp(&b); /* displaying whose balance is below 100 */

break;

case 2:

clrscr();

printf("enter your account number: "); scanf("%d",&ac);

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

Page 155: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

if((b[i].acn)==ac) {

clrscr();

printf("\tHello %s\n",b[i].name); printf("\n\n");

printf("\n\nenter your choice\n"); printf("\n1: deposite:\n"); printf("\n0: withdrawl:\n\n"); scanf("%d",&ch2);

switch(ch2) {

case 0:

clrscr();

if(b[i].bal<lw) {

printf("\n\nsorry! account balance is too low for withdrawl.\n");

break; }

else {

printf("\n\nenter amount for withdrawl: "); scanf("%d",&am);

}

if(b[i].bal<am) {

printf("\n\nyou don't have enough balance for withdrawl.\n");

}

else {

b[i].bal=b[i].bal+am;

printf("\n\nwithdrawl was successful.\n");

} break;

case 1:

clrscr();

printf("\n\nenter amount to deposite: "); scanf("%d",&am);

b[i].bal=b[i].bal+am;

printf("\n\ncash deposited successfully.\n\n");

break;

}

} } } getch(); }

Page 156: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

disp(struct bank *a) {

int k;

printf("\tCustomers whose balance is below 100:\n"); printf("\t*************************************\n\n");

for(k=0;k<N;k++) {

if((a[k].bal)<100) {

printf("%2d\t%s\n",a[k].acn,a[k].name);

} } return 0;

}

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

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

#include<stdio.h> #include<conio.h> struct automob { char name[5]; int year; char mtr[10]; int qty; }; void main() {

struct automob a[54]={{"AA1",2009,"AAA",10}, {"AA2",2009,"AAA",10}, {"AA3",2009,"AAA",10}, {"AA4",2009,"AAA",10}, {"AA5",2009,"AAA",10}, {"AA6",2009,"AAA",10}, {"AA7",2009,"AAA",10}, {"AA8",2009,"AAA",10}, {"AA9",2009,"AAA",10}, {"BB1",2010,"BBB",11}, {"BB2",2010,"BBB",11}, {"BB3",2010,"BBB",11}, {"BB4",2010,"BBB",11}, {"BB5",2010,"BBB",11}, {"BB6",2010,"BBB",11}, {"BB7",2010,"BBB",11}, {"BB8",2010,"BBB",11}, {"BB9",2010,"BBB",11}, {"CC1",2011,"CCC",12}, {"CC2",2011,"CCC",12}, {"CC3",2011,"CCC",12}, {"CC4",2011,"CCC",12}, {"CC5",2011,"CCC",12},

Solution:

Page 157: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

{"CC6",2011,"CCC",12}, {"CC7",2011,"CCC",12}, {"CC8",2011,"CCC",12}, {"CC9",2011,"CCC",12}, {"DD1",2012,"DDD",13}, {"DD2",2012,"DDD",13}, {"DD3",2012,"DDD",13}, {"DD4",2012,"DDD",13}, {"DD5",2012,"DDD",13}, {"DD6",2012,"DDD",13}, {"DD7",2012,"DDD",13}, {"DD8",2012,"DDD",13}, {"DD9",2012,"DDD",13}, {"EE1",2013,"EEE",14}, {"EE2",2013,"EEE",14}, {"EE3",2013,"EEE",14}, {"EE4",2013,"EEE",14}, {"EE5",2013,"EEE",14}, {"EE6",2013,"EEE",14}, {"EE7",2013,"EEE",14}, {"EE8",2013,"EEE",14}, {"EE9",2013,"EEE",14}, {"FF1",2014,"FFF",15}, {"FF2",2014,"FFF",15}, {"FF3",2014,"FFF",15}, {"FF4",2014,"FFF",15}, {"FF5",2014,"FFF",15}, {"FF6",2014,"FFF",15}, {"FF7",2014,"FFF",15}, {"FF8",2014,"FFF",15}, {"FF9",2014,"FFF",15}};

int i,j,k;

clrscr();

printf("Information of parts between BB1 to CC6:\n\n");

printf("\n\nName\t\tyear(manu.)\t\tmaterial\tquantity\n\n\n");

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

if(i>=9 && i<=23) { printf("%3s\t\t%4d\t\t\t%5s\t\t%4d\n",a[i].name,a[i].year,a[i].mtr,a[i].qty);

} }

getch(); }

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

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

Solution:

Page 158: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

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

void main() {

struct cricketer { char name[50]; int age; int match; float avrn; }; struct cricketer c[20],temp; int i,j; clrscr();

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

printf("Enter data of cricketer %d\n\n\n",i+1);

fflush(stdin); printf("Name: "); gets(c[i].name);

printf("\n\nAge: "); scanf("%d",&c[i].age);

printf("\n\nMatches: "); scanf("%d",&c[i].match);

printf("\n\nAverage runs: "); scanf("%f",&c[i].avrn);

clrscr();

}

/*******************/ /* sorting records */ /*******************/

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

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

if(c[i].avrn > c[j].avrn) {

temp=c[i]; c[i]=c[j]; c[j]=temp; } } }

printf("Sorted records:\n\n");

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

printf("%d\t%s\t%d\t%d\t%f\n\n\n",i+1,c[i].name,c[i].age,c[i].match,c[i].avrn);

}

getch(); }

linkfloat() {

Page 159: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

float a=0,*b;

b=&a; a=*b;

return 0; }

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

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

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

struct employee { int code; char name[20]; int dd,mm,yy; } e[N];

int d,m,y,i;clrscr();

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

printf("\tEnter employee data:\n");printf("\t*********************\n");

printf("\nEnter employee code: ");scanf("%d",&e[i].code);

printf("\n\nEnter employee name: ");scanf("%s",&e[i].name);

printf("\n\nEnter date of joining (dd mm yy): ");scanf("%d%d%d",&e[i].dd,&e[i].mm,&e[i].yy);

clrscr();

}

clrscr();

printf("\nenter current date(dd mm yy): \n\n");scanf("%d%d%d",&d,&m,&y);

clrscr();

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

if((y-(e[i].yy))>=3) {

printf("%s\n\N",e[i].name);

}

}

Solution:

Page 160: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

getch();}

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

(f) Write a menu driven program that depicts the working of a library. The menu options should be:1. Add book information2. Display book information3. List all books of given author4. List the title of specified book5. List the count of books in the library6. List the books in the order of accession number7. ExitCreate 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.

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

void main() {

struct library { int acn; char title[25]; char auth[25]; float price; int flag; };

struct library a[5]={ {2,"AAA","AAA",154.8,1}, {1,"BBB","BBB",124.6,0}, {5,"EEE","EEE",234.3,0}, {3,"CCC","CCC",232.3,1}, {4,"DDD","DDD",121.3,0} };

struct library temp; /* temporary structure to overwrite information / and for assistance in sorting the whole structure */

int i,ch,k,flag,j=0; char author[10];

clrscr();

while(1) { /* initialized an indefinite loop */

clrscr(); printf("\t1: Add book information\n"); printf("\t2: Display book information\n"); printf("\t3: List all books of given author\n"); printf("\t4: List the title of specified book\n"); printf("\t5: List the count of books in the library\n");

Solution:

Page 161: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

printf("\t6: List the books in order of accesion number\n"); printf("\t7: Exit\n\n\n");

printf("Choice: "); scanf("%d",&ch);

switch(ch) {

case 1: /* adding book information over current information */

clrscr();

printf("\t\t1: Add book information:\n\n\n");

printf("enter book information:\n\n");

printf("Accesion number of book to be modified: "); scanf("%d",&j); fflush(stdin);

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

if(j==a[i].acn) {

printf("\n\nenter new information:\n\n"); printf("accesion no.: "); scanf("%d",&temp.acn); fflush(stdin); printf("\n\ntitle: "); scanf("%s",&temp.title); fflush(stdin); printf("\n\nauthor: "); scanf("%s",&temp.auth); fflush(stdin); printf("\n\nprice: "); scanf("%f",&temp.auth); fflush(stdin); printf("\n\nflag(1/0): "); scanf("%d",&temp.flag); fflush(stdin);

} }

a[j]=temp; /* overwriting current information with new one */

clrscr();

printf("\n\nInformation added succesfully!\n\n");

delay(2000);

break;

case 2: /* displaying current book information */

clrscr();

printf("\t\t2: Display book information:\n\n\n");

printf("Enter accesion number: "); scanf("%d",&k);

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

if(k==a[i].acn) { clrscr(); printf("Book information: \n\n"); printf("\n\nAccesion Number: %d",a[i].acn); printf("\nTitle: %s",a[i].title); printf("\nAuthor: %s",a[i].auth); printf("\nPrice: %f",a[i].price);

if(a[i].flag==0) { printf("\nFlag: Not issued\n\n");

Page 162: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

} else{ printf("\nFlag: Issued\n\n"); } } } delay(1000);

break;

case 3: /* listing all books of given author */

clrscr();

printf("\t\t3: List all books of given author:\n\n\n");

printf("Enter author name: "); scanf("%s",&author); fflush(stdin);

printf("\n\nbooks of %s\n\n",author); for(i=0;i<5;i++) {

k=strcmp(author,a[i].auth);

if(k==0) { j=j+1; printf("%d.\t%s\n",j,a[i].title);

} } delay(2000); break;

case 4: /* displaying title of given book */

clrscr(); printf("\t\t4: Title of the specified book:\n\n\n");

printf("Enter the accesion number: "); scanf("%d",&k);

printf("\n\n");

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

if(k==a[i].acn) {

printf("Title: %s\n",a[i].title);

} } delay(2000); break;

case 5: /* counting total books in library */

clrscr(); printf("\t\t5: List the count of books in the library: \n\n\n");

for(i=0;i<5;i++) { j=j+1; } printf("\tTotal books: %2d",j);

delay(2000);

Page 163: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

break;

case 6: /* sorting the books by their accesion numbers */

clrscr(); printf("6: List the books in order of accesion number: \n\n\n");

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

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

if(a[i].acn>a[j].acn) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } }

printf("Access no.\tTitle\tAuthor\tFlag\n\n\n"); for(i=0;i<5;i++) {

printf("%4d\t\t%5s\t%5s\t",a[i].acn,a[i].title,a[i].auth);

if(a[i].flag==0) printf("not issued\n\n");

else printf("issued\n\n"); }

delay(2000); break;

case 7: /* condition for going out */

exit();

} }

}

linkfloat() { /* special function to solve compilar error */ float a=0,*b; /* not used withing the program but still defined */ b=&a; a=*b; return 0; }

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

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

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

void main() {

struct date {

Solution:

Page 164: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

int date; int month; int year; }d1;

int d,m,y,i;clrscr();

printf("enter the date to save in structure: \n\n");

printf("Enter the date: ");scanf("%d",&d1.date);

printf("\n\nEnter the month: ");scanf("%d",&d1.month);

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

clrscr();

printf("\nenter the date to compare with structure:\n\n");

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

printf("\n\nEnter the month: ");scanf("%d",&m);

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

if(d==d1.date && m==d1.month && y==d1.year) {

printf("\n\ndates are equal\n\n");

}

else {

printf("\n\ndates are unequal\n\n");

}

getch();

}

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

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

Solution:

Page 165: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

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

struct linklist { int data; linklist *link; };

void main() {

struct linklist *first, *temp;

char choice='y';

int count=0;

clrscr();

/* taking the input of first element */

printf("Enter element %d: ",++count);

first=(linklist *)malloc(sizeof(linklist));

scanf("%d",&first->data);

first->link=NULL;

printf("\n\nEnter another element(Y/N): ");

choice=getche();

tolower(choice); /* converting to lowercase to match the condition of switch */

switch(choice) {

case 'y':

clrscr();

while(choice=='y' || choice=='Y') {

printf("\nEnter element %d: ",++count);

temp=(linklist *)malloc(sizeof(linklist));

scanf("%d",&temp->data);

temp->link=first;

first=temp;

printf("\n\n\nEnter another elements(Y/N): ");choice=getche();

clrscr();

}

break;

case 'n':

Page 166: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

Posted by Chetan Raikwar at 07:04

break;

}

printf("\nTotal elements = %d\n\n",count);

/* printing all elements */

for(temp=first; temp!=NULL; temp=temp->link) {

printf("%d ",temp->data);

}

getch();

}

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

(i) A stack is a data structure in which addition of new element or deletion of existing element always takes place at the same end. This end is often known as ‘top’ of stack. This situation can be compared to a stack of plates in a cafeteria where every new plate taken off the stack is also from the ‘top’ of the stack. There are several application where stack can be put to use. For example, recursion, keeping track of function calls, evaluation of expressions, etc. Write a program to implement a stack using a linked list.

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

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

(j) Unlike a stack, in a queue the addition of new element takes place at the end (called ‘rear’ of queue) whereas deletion takes place at the other end (called ‘front’ of queue). Write a program to implement a queue using a linked list

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

Solution:

Solution:

Recommend this on Google

No comments:

Post a Comment

Page 167: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 10 (Structures)

http://letuscalllessons.blogspot.com/2014/01/chapter-10-structures.html[07-Apr-14 8:46:18 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Comment as: Google Account

Simple template. Powered by Blogger.

Page 168: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 9 (Puppeting on Strings)

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

#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.

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

void main() {

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

Exercise [D]

Solution:

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 169: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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.

#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();

}

Solution:

Page 170: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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

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

#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();}_______________________________________________________________________

(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:

Exercise [F]

Page 171: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

#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]) {

Solution:

Page 172: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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;

Page 173: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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.

#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");

Solution:

Page 174: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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.

#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;

Solution:

Page 175: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

/* 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.

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

void main() {

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

clrscr();

Solution:

Page 176: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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;

Page 177: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

/* 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);

Page 178: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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");

Page 179: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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)

Page 180: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

days=29;

elsedays=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

Page 181: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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<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) {

Solution:

Page 182: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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);

Page 183: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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);

}

elseprintf("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;

Page 184: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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);

Page 185: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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);

Page 186: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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;

elsedays=28;

}/* for march */

if(m==3)days=31;

Page 187: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

/* 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.

Page 188: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

(c) If the cost per item is also given write a program to calculate the total inventory values.

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

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

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.

#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(' ');}

elseputch(s[i]);i++;}

getch();}

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

Solution:

Solution:

Solution:

Page 189: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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

#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];

Solution:

Page 190: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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.

#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");

Solution:

Page 191: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

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.

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

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

Solution:

Page 192: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7[07-Apr-14 8:47:07 PM]

Newer Posts Older PostsHome

Subscribe to: Posts (Atom)

Posted by Chetan Raikwar at 07:03 No comments:

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();}

______________________________________________________________________

Recommend this on Google

Simple template. Powered by Blogger.

Page 193: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 9 (Puppeting on Strings)

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

#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.

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

void main() {

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

Exercise [D]

Solution:

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 194: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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.

#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();

}

Solution:

Page 195: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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

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

#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();}_______________________________________________________________________

(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:

Exercise [F]

Page 196: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

#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]) {

Solution:

Page 197: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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;

Page 198: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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.

#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");

Solution:

Page 199: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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.

#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;

Solution:

Page 200: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

/* 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.

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

void main() {

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

clrscr();

Solution:

Page 201: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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;

Page 202: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

/* 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);

Page 203: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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");

Page 204: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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)

Page 205: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

days=29;

elsedays=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

Page 206: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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<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) {

Solution:

Page 207: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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);

Page 208: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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);

}

elseprintf("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;

Page 209: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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);

Page 210: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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);

Page 211: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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;

elsedays=28;

}/* for march */

if(m==3)days=31;

Page 212: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

/* 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.

Page 213: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

(c) If the cost per item is also given write a program to calculate the total inventory values.

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

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

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.

#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(' ');}

elseputch(s[i]);i++;}

getch();}

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

Solution:

Solution:

Solution:

Page 214: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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

#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];

Solution:

Page 215: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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.

#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");

Solution:

Page 216: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

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.

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

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

Solution:

Page 217: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:04:00-08:00&max-results=16&start=6&by-date=false[07-Apr-14 8:48:00 PM]

Newer Posts Older PostsHome

Subscribe to: Posts (Atom)

Posted by Chetan Raikwar at 07:03 No comments:

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();}

______________________________________________________________________

Recommend this on Google

Simple template. Powered by Blogger.

Page 218: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 2 (The Decision Control Structure)

(a) If cost price and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss he incurred.

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

int cp,sp,rslt;clrscr();

printf("Please enter the cost price of the item: \n");scanf("%d",&cp);

printf("Please enter the selling price of the item: \n");scanf("%d",&sp);

if(cp>sp) {rslt=cp-sp;printf("\nSeller has incurred LOSS of %d rupees.\n",rslt);}

if(cp<sp){rslt=sp-cp;printf("\nSeller has made PROFIT of %d rupees.\n",rslt);}

getch();return 0;

}

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

(b) Any integer is input through the keyboard. Write a program to find out whether it is an odd number or even number.

#include<stdio.h>

Exercise [C]

Solution:

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 219: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

#include<conio.h>

main() {

int i;clrscr();

printf("Please enter the number: \n");scanf("%d",&i);

if(i%2==0)printf("\nThe number is EVEN.\n");

elseprintf("\nThe number is ODD.\n");

getch();return 0;

}

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

(c) Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not.(Hint: Use the % (modulus) operator)

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

main() {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4==0)printf("\nThe year is a LEAP YEAR.\n");

elseprintf("\nThe Year is NOT A LEAP YEAR.\n");

getch();return 0;

}

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

(d) According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input through the keyboard write a program to find out what is the day on 1st January of this year.

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

main() {

int month=1,year,a,day=1;

clrscr();

printf("Enter year: ");

Solution:

Solution:

Page 220: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

scanf("%d",&year);

/* 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 */

printf("\n\nFirst day is ");

if(day==0)printf("Sunday");

else if(day==1)printf("Monday");

else if(day==2)printf("Tuesday");

else if(day==3)printf("Wednesday");

else if(day==4)printf("Thursday");

else if(day==5)printf("Friday");

else if(day==6)printf("Saturday");

getch();return 0;

}

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

(e) A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.

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

main() {

long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();

printf("Please enter a five digit number: \n");scanf("%ld",&i);

d1=i/10000;a=i%10000;

d2=a/1000;b=a%1000;

d3=b/100;

Solution:

Page 221: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

c=b%100;

d4=c/10;d=c%10;

d5=d/1;

n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);

printf("\nThe REVERSED NUMBER is %ld \n",n_num);

if(n_num==i){printf("\nboth numbers are SAME.\n");}else {printf("\nboth number are NOT SAME.\n");}

getch();return 0;

}

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

(f) If the ages of Ram, Shyam and Ajay are input through the keyboard, write a program to determine the youngest of the three.

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

main() {

int ram,shyam,ajay;clrscr();

printf("Please enter the age of RAM: ");scanf("%d",&ram);

printf("\nPlease enter the age of SHYAM: ");scanf("%d",&shyam);

printf("\nPlease enter the age or AJAY: ");scanf("%d",&ajay);

if(ram<shyam){if(ram<ajay) {printf("\nRam is the YOUNGEST.\n");} } if(shyam<ram){if(shyam<ajay) {printf("\nShyam is the YOUNGEST.\n");} }

if(ajay<ram) {if(ajay<shyam) {printf("\nAjay is the YOUNGEST.\n");} }

getch();

Solution:

Page 222: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

return 0;

}

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

(g)Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.

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

int a1,a2,a3;clrscr();

printf("Please enter the first angle: \n");scanf("%d",&a1);

printf("\nPlease enter the second angle: \n");scanf("%d",&a2);

printf("\nPlease enter the third angle: \n");scanf("%d",&a3);

if(a1+a2+a3==180) {printf("\nThe triangle is VALID.\n");}

else {printf("\nThe triangle is NOT VALID.\n");}

getch();return 0;

}

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

(h) Find the absolute value of a number entered through the keyboard.

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

int i,av;clrscr();

printf("Please enter any number: ");scanf("%d",&i);

av=abs(i);

/* abs(); is a standard function to calculate absolute value.\this function has been defined in <stdlib.h> library. */

printf("Absolute value = %d",av);

getch();

Solution:

Solution:

Page 223: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

return 0;

}

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

(i) Given the length and breadth of a rectangle, write a program to find whether the area of the rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and breadth = 4 is greater than its perimeter.

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

int l,b,area,peri;clrscr();

printf("Please enter the length and bredth of a rectangle: \n");scanf("%d%d",&l,&b);

area=l*b;peri=2*(l+b);

if(area>peri) {printf("\nThe Area of Rectangle is GREATER then it's perimeter.\n");}

else {printf("\nThe area of Rectangle is NOT GREATER then it's perimeter.\n");}

getch();return 0;

}

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

(j) Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

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

int x1,y1,x2,y2,x3,y3,curve1,curve2;clrscr();

printf("Please enter the values of Three points: ");printf("\n(x1,y1):\n");scanf("%d%d",&x1,&y1);printf("\n(x2,y2):\n");scanf("%d%d",&x2,&y2);printf("\n(x3,y3):\n");scanf("%d%d",&x3,&y3);

curve1=(x2-x1)/(y2-y1);curve2=(x3-x2)/(y3-y2);

if(curve1==curve2)printf("\nAll three points fall on one straight line.\n");else

Solution:

Solution:

Page 224: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

printf("\nThese three points do not fall on one straight line.\n");

getch();return 0;

}

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

(k) Given the coordinates (x, y) of a center of a circle and it’s radius, write a program which will determine whether a point lies inside the circle, on the circle or outside the circle.(Hint: Use sqrt( ) and pow( ) functions)

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

int x,y,x_,y_,r,point;clrscr();

printf("Please enter the coordinates of center: \n");printf("(x,y): ");scanf("%d%d",&x,&y);printf("\nPlease enter the radius of circle: \n");scanf("%d",&r);printf("\nPlease enter the point to check: \n");printf("(x`,y`): ");scanf("%d%d",&x_,&y_);

point=pow(x_,2)+pow(y_,2)+pow(x,2)+pow(y,2)-(2*x_*x)-(2*y_*y)-pow(r,2);

if(point<0)printf("\nThe point lies inside the circle.\n");

if(point>0)printf("\nThe point lies outside the circle.\n");

if(point==0)printf("\nThe point lies on the circle.\n");

getch();return 0;

}

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

(l) Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis or at the origin, viz. (0, 0).

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

int x,y;clrscr();

printf("Please enter points\n");printf("(x,y): \n");scanf("%d%d",&x,&y);

Solution:

Solution:

Page 225: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

if(x==0&&y!=0) {printf("\nThe point lies on Y AXIS.\n");}

else if(x!=0&&y==0) {printf("\nThe point lies on X AXIS.\n");}

else if(x==0&&y==0) {printf("\nThe point lies at the origin.\n");}

else {printf("\nThe point doesn't lie on any axis or at origin.\n");}

getch();return 0;

}

___________________________________________________________________

(a) Any year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators && and ||.

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

int yr;clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

if(yr%4==0 || !((yr%4)>0) )printf("\nThe is a LEAP YEAR.\n");

elseprintf("\nThis is NOT A LEAP YEAR.\n");

getch();return 0;

}

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

(b) Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol.The following table shows the range of ASCII values for various characters.

The following table shows the range of ASCII values for various characters.

Exercise [F]

Solution:

Page 226: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

Characters

Characters ASCII values

A – Z 65 - 90a – z 97 - 1220 – 9 48 - 57special symbols 0 - 47, 58 - 64, 91 - 96, 123 - 127

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

char ch;clrscr();

printf("Please enter any character:");scanf("%c",&ch);

if(ch>=65&&ch<=90)printf("\nThe character you entered is a CAPITAL LETTER.\n");

if(ch>=97&&ch<=122)printf("\nThe character you entered is a SMALL LETTER.\n");

if(ch>=48&&ch<=57)printf("\nThe character you entered is a DIGIT.\n");

if(ch>=0&&ch<=47 || ch>=58&&ch<=64 || ch>=91&&ch<=96 || ch>=123&&ch<=127)printf("\nThe character you entered is a SPECIAL SYMBOL.\n");

getch();

return 0;

}

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

(c) An Insurance company follows following rules to calculate premium.(1) If a person’s health is excellent and the person is between 25 and 35 years of age and lives in a city and is a male then the premium is Rs. 4 per thousand and his policy amount cannot exceed Rs. 2 lakhs.(2) If a person satisfies all the above conditions except that the sex is female then the premium is Rs. 3 per thousand and her policy amount cannot exceed Rs. 1 lakh.(3) If a person’s health is poor and the person is between 25 and 35 years of age and lives in a village and is a male then the premium is Rs. 6 per thousand and his policy cannot exceed Rs. 10,000.(4) In all other cases the person is not insured.

Write a program to output whether the person should be insured or not, his/her premium rate and maximum amount for which he/she can be insured.

Solution:

Solution:

Page 227: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

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

int age,premium,p_a,hlt,rsdnc,sex;long amount;clrscr();

printf("Please tell the HEALTH of the person\n(1 for excellent or 2 for poor) :\n");scanf("%d",&hlt);

printf("Please tell the AGE of the person: \n");scanf("%d",&age);

printf("Please tell the residence\n(1 for city or 2 for village) : \n");scanf("%d",&rsdnc);

printf("Please tell you sex\n(1 for male or 2 for female) : \n");scanf("%d",&sex);

if(hlt==1 && age>=25&&age<=35 && rsdnc==1 && sex==1) {premium=4;amount=200000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==1||hlt==2 && age>=25&&age<=35 && rsdnc==1||rsdnc==2 && sex==2) {premium=3;amount=100000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==2 && age>=25&&age<=35 && rsdnc==2 && sex==1) {premium=6;amount=10000;

printf("\nThis person is insured.\n");printf("Premium rate is = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else {printf("\nThis person cannot be insured.\n");}

getch();return 0;

}

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

(d) A certain grade of steel is graded according to the following conditions:(i) Hardness must be greater than 50(ii) Carbon content must be less than 0.7(iii) Tensile strength must be greater than 5600

The grades are as follows:

Page 228: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

Grade is 10 if all three conditions are metGrade is 9 if conditions (i) and (ii) are metGrade is 8 if conditions (ii) and (iii) are metGrade is 7 if conditions (i) and (iii) are metGrade is 6 if only one condition is metGrade is 5 if none of the conditions are met

Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and output the grade of the steel.

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

int hdn,tnsl,hardness=50,tensile_strength=5600;

float c,carbon_content=0.7;

clrscr();

printf("Please enter the Hardness: \n");scanf("%d",&hdn);

printf("\nPlease enter the Carbon content: \n");scanf("%f",&c);

printf("\nPlease enter the Tensile Strength: \n");scanf("%d",&tnsl);

if(hdn>hardness && c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 10.\n");

else if(hdn>hardness && c<carbon_content)printf("\nThe steel has been Graded 9.\n");

else if(c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 8.\n");

else if(hdn>hardness && tnsl>tensile_strength)printf("\nThe steel has been Graded 7.\n");

else if(hdn>hardness || c<carbon_content || tnsl>tensile_strength)printf("\nThe steel has been Graded 6.\n");

elseprintf("\nThe steel has been Graded 5.\n");

getch();

return 0;

}

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

(e) A library charges a fine for every book returned late. For first 5 days the fine is 50 paise, for 6-10 days fine is one rupee and above 10 days fine is 5 rupees. If you return the book after 30 days your membership will be cancelled. Write a program to accept the number of days the

Solution:

Page 229: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

member is late to return the book and display the fine or the appropriate message.

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

printf("Please enter the days of being late in returning the book:\n");scanf("%d",&days);

if(days<=5)printf("\nYou have been fined for 50 paise.\n");

if(days>=6&&days<=10)printf("\nYou have been fined for 1 rupee.\n");

if(days>10&&days<30)printf("\nYou have been fined for 5 rupee.\n");

if(days>=30)printf("\nYour membership has been cancelled.\n");

getch();return 0;

}

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

(f) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.

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

int s1,s2,s3,ls,ss1,ss2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d%d%d",&s1,&s2,&s3);

if(s1>s2&&s1>s3){ls=s1;ss1=s2;ss2=s3;}if(s2>s1&&s2>s3) {ls=s2;ss1=s1;ss2=s3;}if(s3>s1&&s3>s2) {ls=s3;ss1=s1;ss2=s2;}

Solution:

Solution:

Page 230: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

if((ss1+ss2)>ls) {printf("\nThe Triangle is VALID.\n");}else {printf("The triangle is NOT VALID.\n");}

getch();return 0;

}

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

(g) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.

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

main() {

int s1,s2,s3,largest,s_1,s_2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d %d %d",&s1,&s2,&s3);

if(s1==s2&&s1!=s3||s1==s3&&s1!=s2 || s2==s3&&s2!=s1||s2==s1&&s2!=s3 ||s3==s1&&s3!=s2||s3==s2&&s3!=s1){printf("The Triangle is ISOSCELES.\n");}

if(s1==s2&&s2==s3 || s2==s1&&s2==s3 || s3==s1&&s3==s2){printf("The Triangle is EQUILATERAL.\n");}

if(s1!=s2&&s2!=s3 || s2!=s1&&s1!=s3 || s3!=s1&&s1!=s2){printf("The Triangle is SCALENE.\n");}

if(s1>s2&&s1>s3){largest=s1;s_1=s2;s2=s3;}

if(s2>s1&&s2>s3){largest=s2;s_1=s1;s_2=s3;}

if(s3>s1&&s3>s2){largest=s3;s_1=s1;s_2=s2;}

if(pow(largest,2)==pow(s_1,2)+pow(s_2,2))printf("The Triangle is RIGHT ANGLED.\n");

getch();return 0;}

Solution:

Page 231: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

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

(h) In a company, worker efficiency is determined on the basis of the time required for a worker to complete a particular job. If the time taken by the worker is between 2 – 3 hours, then the worker is said to be highly efficient. If the time required by the worker is between 3 – 4 hours, then the worker is ordered to improve speed. If the time taken is between 4 – 5 hours, the worker is given training to improve his speed, and if the time taken by the worker is more than 5 hours, then the worker has to leave the company. If the time taken by the worker is input through the keyboard, find the efficiency of the worker.

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

int hrs;clrscr();

printf("Please enter the hours of completing job: ");scanf("%d",&hrs);

if(hrs>=2 && hrs<=3)printf("\nThe worker is HIGHLY EFFICIENT.\n");

if(hrs>=3 && hrs<=4)printf("\nThe worker is ordered to IMPROVE SPEED.\n");

if(hrs>=4 && hrs<= 5)printf("\nThe worker should be given TRAINING TO IMPROVE SPEED.\n");

if(hrs>5)printf("\nThe worker should be asked to leave the company.\n");

elseprintf("The worker is HIGHLY EFFICIENT.\n");

getch();return 0;

}

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

(i) A university has the following rules for a student to qualify for a degree with A as the main subject and B as the subsidiary subject: (a) He should get 55 percent or more in A and 45 percent or more in B. (b) If he gets than 55 percent in A he should get 55 percent or more in B. However, he should get at least 45 percent in A. (c) If he gets less than 45 percent in B and 65 percent or more in A he is allowed to reappear in an examination in B to qualify. (d) In all other cases he is declared to have failed.

Write a program to receive marks in A and B and Output whether the student has passed, failed or is allowed to reappear in B.

#include<stdio.h>

Solution:

Solution:

Page 232: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

#include<conio.h>main() {

int a,b;clrscr();

printf("Please enter the marks in subject A: \n");scanf("%d",&a);

printf("\nPlease enter the marks in subject B: \n");scanf("%d",&b);

if(a>=55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a==55 && b>=55 || a==55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a>=65 && b<45) {printf("Student is allowed to reappear in the exam of B to qualify.\n"); }

else {printf("Student has failed.\n"); }

getch();return 0;

}

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

(j) The policy followed by a company to process customer orders is given by the following rules:

(a) If a customer order is less than or equal to that in stock and has credit is OK, supply has requirement.(b) If has credit is not OK do not supply. Send him intimation.(c) If has credit is Ok but the item in stock is less than has order, supply what is in stock. Intimate to him data the balance will be shipped.

Write a C program to implement the company policy.

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

int stock,credit,order;clrscr();

printf("Please enter the stock available: ");scanf("%d",&stock);printf("\nPlease enter the order: ");scanf("%d",&order);printf("\nPlease enter the credit: ");scanf("%d",&credit);

if(credit!=0&&order<=stock) {

Solution:

Page 233: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

printf("\nSupply\n");}

else if(credit!=0&&order>stock) {printf("\nAvailable items will be supplied.\n");}

else {printf("\nNo supply.\n");}

getch();return 0;

}______________________________________________________________________

(a) Using conditional operators determine: (1) Whether the character entered through the keyboard is a lower case alphabet or not.(2) Whether a character entered through the keyboard is a special symbol or not.

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

char main() {

char ch;clrscr();

printf("Please enter a character: \n");scanf("%c",&ch);

if(ch>=97 && ch<=122) {printf("\n[A] This character is a SMALL CASE alphabet.\n");}

else {printf("\n[A] This character is NOT A SMALL CASE alphabet.\n");}

if(ch>=0&&ch<=47||ch>=58&&ch<=64||ch>=91&&ch<=96||ch>=123&&ch<=127){printf("\n[B] This character is a SPECIAL SYMBOL.\n");}

else{printf("\n[B] This character is NOT A SPECIAL SYMBOL.\n");}

getch();return 0;

}

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

Exercise [J]

Solution:

Page 234: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 2 (The Decision Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-2-decision-control-structure.html[07-Apr-14 8:48:59 PM]

(b) Write a program using conditional operators to determine whether a year entered through the keyboard is a leap year or not.

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

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4!=0)printf("\nThis is NOT A LEAP YEAR.\n");

elseprintf("\nThis is a LEAP YEAR.\n");

getch();return 0;}

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

(c) Write a program to find the greatest of the three numbers entered through the keyboard using conditional operators.

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

main() {

int n1,n2,n3;clrscr();

printf("\nPlease enter 3 numbers: \n");scanf("%d %d %d",&n1,&n2,&n3);

if(n1>n2 && n1>n3) {printf("\n%d is the greatest number of the three numbers.\n",n1);}

else if(n2>n1 && n2>n3) {printf("\n%d is the greatest number of the three numbers.\n",n2);}

else if(n3>n2 && n3>n1) {printf("\n%d is the greatest number of the three numbers.\n",n3);}

else {printf("\nwrong input!\n");}

getch();return 0;

}

_______________________________________________________________________

Solution:

Solution:

Page 236: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 12 (File Input Output)

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

NOTE: Make a file as "DATA.TXT" in bin directory and write/paste some text in it, then run the program.

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

FILE *fp;char i;int line=1;

clrscr();

fp=fopen("DATA.TXT","r");

if(fp==NULL) {

printf("\n\nCannot open file!");

delay(1000);exit();}

printf("%2d. ",line); /* we already print 1st for the first line */

while(i!=EOF) {

i=fgetc(fp);

printf("%c",i);

/* if the character is newline,the line number will be\printed after it */

if(i=='\n') {line++;printf("%2d. ",line);}

}

Exercise [C]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 237: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

fclose(fp);getch();}

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

(b) Write a program to find the size of a text file without traversing it character by character.

NOTE: Make a file as "DATA.TXT" in bin directory and write/paste some text in it, then run the program.

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

void main() {

FILE *fp;char s[80],ch;int len=0;

clrscr();

fp=fopen("data.txt","r");

while(fgets(s,79,fp)!=NULL)

len=len+strlen(s); /* length of each string */ /* spaces and newlines are also counted */

fclose(fp);

printf("length of file = %d",len);

getch();}

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

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

NOTE: Make two file as "FILE1.TXT" and "FILE2.TXT" in bin directory and then run the program. The contents of FILE1.TXT will be appended to FILE2.TXT.

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

FILE *f1,*f2;char ch;

clrscr();

f1=fopen("FILE1.TXT","r"); /* file to append */f2=fopen("FILE2.TXT","a+"); /* file to be appended */

Solution:

Solution:

Page 238: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

if(f1==NULL || f2==NULL) {printf("\ncannot open one of files!");

exit();}

while(1) {

ch=fgetc(f1);

if(ch==EOF) {break;}

fputc(ch,f2);

}

fclose(f1);fclose(f2);

printf("\ntask completed successfully!");

getch();

}

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

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

#include<stdio.h>#include<conio.h>#define N 100struct student { char name[30]; int age; };

void main() {

struct student std;struct student s[N]; /* size of array of structure defined globally for convenience */

FILE *fp;int flag=0,ch,i=0,count=0;long recsize;char another='y';void srt_print(); /* funtion to sort and print */

clrscr();

recsize=sizeof(std);

fp=fopen("STUDENT.DAT","rb+");if(fp==NULL) {fp=fopen("STUDENT.DAT","wb+");if(fp==NULL)exit();}

while(1) {

Solution:

Page 239: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

clrscr();

printf("\t\t\tStudent database\n");printf("\t\t\t****************\n\n\n");printf("\t\t\n1: Add student data\n");printf("\t\t\n2: List student data\n");printf("\t\t\n0: Exit");

gotoxy(2,24);printf("Your choice: ");scanf("%d",&ch);

switch(ch) {

case 1:

clrscr();

while(another=='y' || another=='Y') {

clrscr();

printf("\t\tAdd student data\n");printf("\t\t****************\n\n");printf("\nEnter student name: ");scanf("%s",&std.name);printf("\n\naEnter student age: ");scanf("%d",&std.age);

fseek(fp,0,SEEK_END);fwrite(&std,recsize,1,fp);

gotoxy(2,24);printf("Add another information(Y/N): ");fflush(stdin);another=getche();

}break;

case 2:

clrscr();

printf("\t\tList student data\n");printf("\t\t*****************\n\n");rewind(fp);while(fread(&std,recsize,1,fp)==1) {s[i]=std;flag=1;i++;count++;}

srt_print(&s,count); /* function to print names */

if(flag==0) {

printf("\n\n\nNo data found!\n");

}printf("\n\n\npress any key to return...");getch();

break;

case 0:

fclose(fp);exit();

Page 240: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

default:

printf("wrong input!\n");exit();

}

}

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

/**** sorting and printing function ****/void srt_print(struct student *ss, int n) {

struct student temp;int i,j;

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

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

/* checking first alphabets of both names */

if(ss[i].name[0] > ss[j].name[0]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;}

/* if first alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1] > ss[j].name[1]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;

}

/* if first 2 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2] > ss[j].name[2]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;}}

/* if first 3 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2]==ss[i].name[2]) {

if(ss[i].name[3] > ss[j].name[3]) {

Page 241: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

temp=ss[i];ss[i]=ss[j];ss[j]=ss[i];}}}

/* if first four 4 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2]==ss[j].name[2] && ss[i].name[2]==ss[j].name[2]) {

if(ss[i].name[3]==ss[j].name[3]) {

if(ss[i].name[4] > ss[j].name[4]) {

temp=ss[i];ss[i]=ss[j];ss[j]=ss[i];

} } } }

}}

/* printing sorted list */

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

printf("\n%10s\t\t%2d\n",ss[i].name,ss[i].age);

}

}

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

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

NOTE: Make a file as "FILE.TXT" in bin directory and write/paste some text in it. then run the program and you will receive another file as "RESULT.TXT" with uppercase letters.

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

void main() {

FILE *fr,*fw;char a[1000];char ch,upr;clrscr();

fr=fopen("SOURCE.TXT","r");

if(fr==NULL) {printf("cannot open source file!\n");

}

Solution:

Page 242: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

fw=fopen("RESULT.TXT","w");

if(fw==NULL) {printf("cannot open target file!\n");

}

while(1) {

ch=fgetc(fr);

if(ch==EOF)break;

else {

if(ch>=97 && ch<=122) {

ch=ch-32;

}

fputc(ch,fw);}

}fclose(fr);fclose(fw);

printf("Task completed!");getch();}

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

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

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

(g) 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 cornerco-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.

#include<stdio.h>#include<conio.h>#include<string.h>#include<types.h>#include<stat.h>#include<fcntl.h>

Solution:

Solution:

Page 243: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

void box();void print();

void main() {

int inhandle,bytes,pg=1;FILE *fp;char source[80],buffer[1400];

clrscr();

printf("Enter file name: ");gets(source);

inhandle=open(source, O_RDONLY);

if(inhandle==-1) {

printf("cannot open file!");exit();

}

clrscr();

while(1) {

bytes=read(inhandle,buffer,1387);

if(bytes>0) {

gotoxy(32,1); /* showing filename */printf("%s",strupr(source));

gotoxy(70,1);printf("Pg: %3d",pg); /* showing page number */

box(); /* passing the heading and page number to the function */

print(buffer); /* passing the buffer to the function */

}

else {

gotoxy(70,1);printf("Pg: %3d",pg);break;}

++pg;}

close(inhandle);

getch();}

/********************************//* function to print the buffer *//********************************/

void print(char s[1400]) {

int x=4,y=3,i=0;

Page 244: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

while(s[i]!=EOF) {

gotoxy(x,y);printf("%c",s[i]);

if(x>74) {

x=4;y+=1;

}

if(y>21) {

gotoxy(2,24);printf("press any key to go to next page...");

x=4;y=3;

getch();

clrscr();box();}

x++;i++;

}

}

/****************************//* function to draw the box *//****************************/

void box() {

int i,j;

for(i=2;i<=77;i++) {

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

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

}

for(j=3;j<=22;j++) {

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

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

}

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

gotoxy(77,2);printf("%c",191);

Page 245: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

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

gotoxy(2,2);printf("%c",218);

}

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

(h) Write a program to encrypt/decrypt a file using:(1) 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.(2) A substitution cipher: In this each character read from the source file is substituted by a corresponding predetermined character and this character is written to the target file.For example, if character ‘A’ is read from the source file, and if we have decided that every ‘A’ is to be substituted by ‘!’, then a ‘!’ would be written to the target file in place of every ‘A’ Similarly, every ‘B’ would be substituted by ‘5’ and so on.

Offset cipher Encryption:

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

void main() { /* offset cipher encryption */

/* every character has been added to 128 and the new value has beenwritten */

FILE *fp,*ft;char ch;

clrscr();

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

ch=ch+128; /* offset cipher encryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

Solution:

Page 246: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();}

Offset cipher Decryption:

#include<stdio.h>#include<conio.h>void main() { /* offset cipher decryption */

FILE *fp,*ft;char ch;

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");

exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

ch=ch-128; /* decryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();

}

Substitution cipher encryption:

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

void main() { /* substitution cipher encryption */

/* all vowels have been exchanged with first five ascii characters and every space has been converted to 6th ascii character */

FILE *fp,*ft;char ch;

Page 247: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

clrscr();

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

encrypt(&ch); /* function for encryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();}encrypt(char *c) {

if(*c=='a') {*c='!';}

if(*c=='e') {*c='@';}

if(*c=='i') {*c='#';}

if(*c=='o') {*c='$';}

if(*c=='u') {*c='%';}

if(*c==' ') {*c='^';}

return *c;}

Substitution cipher Decryption:

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

/* substitution cipher's decryption */

Page 248: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

FILE *fp,*ft;char ch;

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");

exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

decrypt(&ch); /* function for decryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();

}

decrypt(char *c) {

if(*c=='!')*c='a';

if(*c=='@')*c='e';

if(*c=='#')*c='i';

if(*c=='$')*c='o';

if(*c=='%')*c='u';

if(*c=='^')*c=' ';

return *c;

}----------------------------------------------------------------------------------------------------------------

(i) In the file ‘CUSTOMER.DAT’ there are 100 records with the following structure:struct customer{

Page 249: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

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.

NOTE: If on withdrawal, the balance subtracts to less than 100. The withdrawal will not be performed.

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

struct customer { int accno; char name[30]; float balance; }cust;struct trans { int accno; char trans_type; float amount; }tra;FILE *fp,*ft,*ftemp;int flag=0;long recsize,retsize;char another,ch;clrscr();

fp=fopen("CUSTOMER.DAT","rb+");

if(fp==NULL) {

fp=fopen("CUSTOMER.DAT","wb+");

if(fp==NULL)

printf("cannot open customer data file!\n");

exit();

}

ft=fopen("TRANSACTIONS.DAT","rb+");

if(ft==NULL) {

Solution:

Page 250: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

ft=fopen("TRANSACTIONS.DAT","wb+");

if(ft==NULL)

printf("cannot open transactions file!\n");

exit();

}

recsize=sizeof(cust);retsize=sizeof(tra);

while(1) {

clrscr();

printf("\t\tCutomer Transactions:\n");printf("\t\t*********************\n\n\n");printf("\t1: Add customer information:\n\n");printf("\t2: Add transaction information:\n\n");printf("\t3: List customer information:\n\n");printf("\t4: List transaction information:\n\n");printf("\t5: Perform transaction:\n\n");printf("\t0: Exit:\n\n\n");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd customer information:\n");printf("\t\t*************************\n\n");printf("\nEnter account number: ");scanf("%d",&cust.accno);printf("\n\nEnter name: ");scanf("%s",cust.name);printf("\n\nEnter balance: ");fflush(stdin);scanf("%f",&cust.balance);

fwrite(&cust,recsize,1,fp);

gotoxy(2,24);printf("Add another customer information(Y/N): ");another=getche();

clrscr();

}break;

case '2':

clrscr();

fseek(ft,0,SEEK_END);

Page 251: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd transaction information:\n");printf("\t\t****************************\n\n\n");printf("Enter existing customer account number: ");scanf("%d",&tra.accno);printf("\n\nEnter transaction type(D/W): ");fflush(stdin);scanf("%c",&tra.trans_type);printf("\n\nEnter amount for transaction: ");fflush(stdin);scanf("%f",&tra.amount);

fwrite(&tra,retsize,1,ft);

gotoxy(2,24);printf("Enter another information(Y/N): ");another=getche();

clrscr();}break;

case '3':

clrscr();

printf("\t\tList customer information:\n");printf("\t\t**************************\n\n");

rewind(fp);while(fread(&cust,recsize,1,fp)==1) {printf("\n%5d\t%-8s\t%5.2f\n",cust.accno,cust.name,cust.balance);flag=1;}

if(flag==0) {gotoxy(2,12);printf("No customer information found!\n");}printf("\n\npress any key to go back...");getch();

break;

case '4':

clrscr();

printf("\t\tList transaction information:\n");printf("\t\t*****************************\n\n");

rewind(ft);while(fread(&tra,retsize,1,ft)==1) {printf("\n%5d\t%c\t%6.2f\n",tra.accno,tra.trans_type,tra.amount);flag=1;}

if(flag==0) {gotoxy(2,12);printf("No transaction information found!\n");}

printf("\n\npress any key to go back...");getch();

break;

Page 252: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

case '5':

clrscr();

printf("\t\tPerform transactions\n");printf("\t\t********************\n\n");

rewind(fp);

while(fread(&cust,recsize,1,fp)==1) {

rewind(ft);

while(fread(&tra,retsize,1,ft)==1) {

if(cust.accno==tra.accno) {

flag=1;

if(tra.trans_type=='D' || tra.trans_type=='d') {

cust.balance+=tra.amount;

fseek(fp,-recsize,SEEK_CUR);fwrite(&cust,recsize,1,fp);

}

else if(tra.trans_type=='W' || tra.trans_type=='w') {

if((cust.balance-tra.amount)>=100) {

cust.balance-=tra.amount;

fseek(fp,-recsize,SEEK_CUR);fwrite(&cust,recsize,1,fp);

}

}

}}}

fclose(ft);

ftemp=fopen("TEMP.DAT","rb+");

if(ftemp==NULL) {

ftemp=fopen("TEMP.DAT","wb+");

}

remove("TRANSACTIONS.DAT");rename("TEMP.DAT","TRANSACTIONS.DAT");

ft=fopen("TRANSACTIONS.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTIONS.DAT","wb+");

}

if(flag==0) {

gotoxy(2,12);printf("No active transactions\n");

Page 253: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

}

else if(flag>0) {

gotoxy(2,12);printf("Transactions performed seccussfully!\n");gotoxy(2,14);printf("NOTE: withdrawl for low balance accounts has not been performed\n");

}gotoxy(2,24);printf("press any key to return...");getch();

break;

case '0':

fclose(fp);fclose(ft);exit();

}}

}

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

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

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

(k) A hospital keeps a file of blood donors in which each record has the format:Name: 20 ColumnsAddress: 40 ColumnAge: 2 ColumnsBlood Type: 1 Column (Type 1, 2, 3 or 4)Write a program to read the file and print a list of all blood donors whose age is below 25 and blood is type 2.

Solution:

Solution:Program to creat record file of blood donors

Page 254: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

/* This program will make a file of blood donors and save information in it */

/* Writing program */

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

FILE *fp;char another='y';

struct blood { char name[50]; char adr[50]; int age; int bld; } b;

clrscr();

fp=fopen("BLOODBANK.DAT","wb");

if(fp==NULL) {printf("cannot open target file!\n");exit();}

while(another=='Y' || another=='y') {

clrscr();printf("\t\tInformation of Blood donor\n");printf("\t\t**************************\n\n\n");printf("Enter the name: ");scanf("%s",b.name);printf("\n\nenter the address: ");scanf("%s",b.adr);printf("\n\nenter the age: ");scanf("%d",&b.age);printf("\n\nenter the blood group(1/2/3/4): ");scanf("%d",&b.bld);

fprintf(fp,"%s\t%s\t%d\t%d",b.name,b.adr,b.age,b.bld);

printf("\n\n\nenter more information(Y/N): ");fflush(stdin);

another=getch();

}

fclose(fp);

}

/* This program will read the information from the file made by writing program */

/* Reading Program */

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

FILE *fp;

Program to read record file for specifications

Page 255: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

char ch;

struct blood { char name[50]; char adr[50]; int age; int bld; }b;clrscr();

fp=fopen("BLOODBANK.DAT","rb");

if(fp==NULL) {printf("cannot open source file!\n\n");exit();}

while(fscanf(fp,"%s\t%s\t%d\t%d",&b.name,&b.adr,&b.age,&b.bld)!=EOF)if(b.age<25 && b.bld==2) {printf("\n%s\t %s\t%2d\t %d",b.name,b.adr,b.age,b.bld);}fclose(fp);

getch();}

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

(l) Given a list of names of students in a class, write a program to store the names in a file on disk. Make a provision to display the nth name in the list (n is data to be read) and to display all names starting with S.

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

struct name { int sn; char name[30]; }s;int i,num,flag=0;long recsize;char another,ch;FILE *fp;clrscr();

fp=fopen("NAMES.DAT","rb+");

if(fp==NULL) {

fp=fopen("NAMES.DAT","wb+");

if(fp==NULL)

printf("cannot open file! \n");exit();}

recsize=sizeof(s);

while(1) {

clrscr();printf("\t\tStudent Names:\n");printf("\t\t**************\n\n\n");printf("\t1: Add names of students:\n\n");printf("\t2: Search a student name:\n\n");printf("\t3: List all student names:\n\n");

Solution:

Page 256: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

printf("\t4: List all names starting with 'S':\n\n");printf("\t0: Exit\n\n");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd names of students:\n");printf("\t\t**********************\n\n");printf("Enter student number: ");scanf("%d",&s.sn);printf("\n\nEnter student name: ");scanf("%s",s.name);

fwrite(&s,recsize,1,fp);

gotoxy(2,24);printf("Enter another name(Y/N): ");fflush(stdin);another=getche();

clrscr();}break;

case '2':

clrscr();

printf("\t\tSearch a student name:\n");printf("\t\t**********************\n\n");printf("Enter student number: ");scanf("%d",&num);

rewind(fp);

while(fread(&s,recsize,1,fp)==1) {

if(s.sn==num) {

printf("\n\nStudent Number: %5d\n\n",s.sn);printf("Student name: %s\n\n",s.name);

flag=1;break;} }

if(flag==0) {printf("\n\n\nNo such name found!\n");}gotoxy(2,24);printf("press any key to return...\n");getch();

Page 257: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

break;

case '3':

clrscr();

printf("\t\tList all student names\n");printf("\t\t**********************\n\n\n");

rewind(fp);

while(fread(&s,recsize,1,fp)==1) {printf("\n%5d\t%-10s\n",s.sn,s.name);flag=1;}

if(flag==0) {printf("\n\n\nNo name found!\n");}

printf("\n\n\npress any key to return...\n");getch();break;

case '4':

clrscr();

printf("\t\tAll name starting with 'S':\n");printf("\t\t***************************\n\n\n");

rewind(fp);while(fread(&s,recsize,1,fp)==1) {

if(strncmp('s',s.name[0])==0) { /* comparing only first character of \ name if it is "s" */printf("\n%5d\t%-10s\n",s.sn,s.name);flag=1;}}

if(flag==0) {printf("\n\n\nNo name starting with \'S\' found!\n");}

printf("\n\n\npress any key to return...\n");getch();break;

case '0':

fclose(fp);exit();

} }

}

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

(m) Assume that a Master file contains two fields, Roll no. and name of the student. At the end of the year, a set of students join the class and another set leaves. A Transaction file contains the roll numbers and an appropriate code to add or delete a student.Write a program to create another file that contains the updated list of names and roll numbers. Assume that the Master file and the

Page 258: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

Transaction file are arranged in ascending order by roll numbers. The updated file should also be in ascending order by roll numbers.

Note:- This program ( all the 3 ) are ideally for single. After you have ran it once, check the results and delete the updated list file before running it again. Assign roll number in ascending orders by roll numbers. And process data according to ascending nature.

1- first program will let you save data in masterfile.2- second program will let you add or delete data and will generate an updated list in text mode.3- obtain the updated list and check it ( assuming you have processed data as instructed).

1. program to creat master file.

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

void main() {

FILE *fp;struct student { int rl; char name[50]; }s;char ch,another;clrscr();

fp=fopen("MASTERFILE.DAT","rb+");

if(fp==NULL) {

fp=fopen("MASTERFILE.DAT","wb+");

if(fp==NULL)puts("cannot open master file!");exit();}

while(1) {

clrscr();

gotoxy(30,2);printf("Masterfile\n");gotoxy(30,3);printf("**********\n\n\n");gotoxy(20,6);printf("1: Enter student data: ");gotoxy(20,8);printf("2: Read student data: ");gotoxy(20,10);printf("0: Exit: ");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

Solution:

Page 259: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

clrscr();

gotoxy(2,24);printf("NOTE: assign roll numbers in ascending order");gotoxy(20,5);printf("Enter roll number: ");scanf("%d",&s.rl);

gotoxy(20,7);printf("Enter name: ");fflush(stdin);gets(s.name);

fwrite(&s,sizeof(s),1,fp);

gotoxy(20,10);printf("Add more data(Y/N): ");fflush(stdin);

another=getche();

}

break;

case '2':

clrscr();

gotoxy(30,2);printf("Student data");gotoxy(30,3);printf("************\n\n");

rewind(fp);

while(fread(&s,sizeof(s),1,fp)==1) {

printf("\n%d\t%s\n",s.rl,s.name);

}

printf("\n\npress any key to return...");getch();

break;

case '0':

fclose(fp);exit();

}}

}

2. program to creat transaction file and generate

Page 260: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

updated list

#include<stdio.h>#include<conio.h>#include<string.h>#define N 100

void main() {

FILE *ft,*fu,*fm,*ftemp;

struct student { int rl; char name[50]; }s,ss[N],temp;

struct transaction { char stats; int rl; char name[50]; }t;

int flag=0;char ch,another;clrscr();

fm=fopen("MASTERFILE.DAT","rb+");

if(fm==NULL) {

printf("Masterfile doesn't exist!");

}

ft=fopen("TRANSACTION.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTION.DAT","wb+");

if(ft==NULL)puts("cannot open transactions file!");exit();}

fu=fopen("UPDATELIST.TXT","w+");

if(fu==NULL) {

puts("cannot open target file!");exit();}

while(1) {

clrscr();

gotoxy(30,2);printf("Transaction-File\n");gotoxy(30,3);printf("****************\n\n\n");gotoxy(20,6);printf("1: ADD/DELETE student data from master list: ");gotoxy(20,8);printf("2: Read transaction data: ");gotoxy(20,10);printf("3: Creat updated list: ");gotoxy(20,12);

Page 261: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

printf("0: Exit:");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(ft,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

clrscr();

gotoxy(2,23);printf("NOTE: data to be deleted should match master list");gotoxy(2,24);printf("NOTE: data to be added should follow the ascending nature of master list");gotoxy(20,5);printf("ADD/DELETE student(A/D): ");scanf("%c",&t.stats);gotoxy(20,7);printf("Enter roll number: ");scanf("%d",&t.rl);gotoxy(20,9);printf("Enter name: ");fflush(stdin);gets(t.name);

fwrite(&t,sizeof(t),1,ft);

gotoxy(20,12);printf("Add more data(Y/N): ");fflush(stdin);

another=getche();

}

break;

case '2':

clrscr();

gotoxy(30,2);printf("Student data");gotoxy(30,3);printf("************\n\n");

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

printf("\n");

if(t.stats=='a' || t.stats=='A') {printf("ADD");}

else {printf("DELETE");}

Page 262: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

printf("\t%d\t%s\n",t.rl,t.name);

}

printf("\n\npress any key to return...");getch();

break;

case '3':

clrscr();

gotoxy(30,2);printf("make updated list");gotoxy(30,3);printf("*****************\n\n");

rewind(fm);

while(fread(&s,sizeof(s),1,fm)==1) {

flag=0;

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

if(t.rl==s.rl ) {

if(t.stats=='d' || t.stats=='D') {flag=1;}

}

}

if(flag==0)

fprintf(fu,"\n%d\t%-s\n",s.rl,s.name);

}

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

if(t.stats=='a' || t.stats=='A') {

fprintf(fu,"\n%d\t%-s\n",t.rl,t.name);

}

}

ftemp=fopen("TEMP.DAT","wb+");

fclose(ftemp);fclose(ft);

remove("TRANSACTION.DAT");rename("TEMP.DAT","TRANSACTION.DAT");

ft=fopen("TRANSACTION.DAT","rb+");

gotoxy(2,24);printf("press any key to continue...");

Page 263: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

getch();

break;case '0':

fclose(fm);fclose(ft);fclose(fu);exit();

}}

}

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

(n) In a small firm employee numbers are given in serial numerical order, that is 1, 2, 3, etc.− Create a file of employee data with following information: employee number, name, sex, gross salary.− If more employees join, append their data to the file.− If an employee with serial number 25 (say) leaves, delete the record by making gross salary 0.− If some employee’s gross salary increases, retrieve the record and update the salary.Write a program to implement the above operations.

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

struct emp { int empno; char name[30]; char sex; float gs; } e;FILE *fp,*ft;int long recsize;int empn,flag=0;float new_sal;char another,ch;clrscr();

recsize=sizeof(e);

fp=fopen("EMP.DAT","rb+");

if(fp==NULL) {

fp=fopen("EMP.DAT","wb+");if(fp==NULL)

exit();

}

while(1) {

clrscr();

printf("\t\tEmployee database management\n");

Solution:

Page 264: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

printf("\t\t****************************\n");printf("\n\n\t1: Add another employee: ");printf("\n\n\t2: Add salary information of employee: ");printf("\n\n\t3: List all records: ");printf("\n\n\t4: Delete employee with 0 salary: ");printf("\n\n\t0: Exit:");

gotoxy(2,24);printf("your choice: ");fflush(stdin);ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END); /* seeking cursor to reach at the end of file */

another='Y';

while(another=='Y' || another=='y') {

printf("\n\tEnter new employee information\n");printf("\t******************************\n\n\n");

printf("\nEnter employee number: ");scanf("%d",&e.empno);

printf("\n\nEnter employee name: ");scanf("%s",e.name);

printf("\n\nEnter sex(M/F/O): ");scanf(" %c",&e.sex);

printf("\n\nEnter gross salary: ");scanf("%f",&e.gs);

/* writing new information at the end of file */

fwrite(&e,recsize,1,fp);

printf("\n\n\n\nAdd another employee(Y/N): ");fflush(stdin);another=getche();

clrscr();

}

break;

case '2':

clrscr();

another='Y';

while(another=='Y' || another=='y') {

printf("\n\tEnter salary information\n");printf("\t************************\n\n");

gotoxy(2,23); /* showing message at the bottom of the screen */

printf("NOTE: to delete an employee, mark his/her salary 0\n");printf(" then use option 4 from main menu.");

gotoxy(3,5); /* returning cursor back from the bottom */

Page 265: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

printf("Enter employee number: ");scanf("%d",&empn); /* asking for employee number to search */

rewind(fp);

while(fread(&e,recsize,1,fp)==1) {

if(e.empno-empn==0) { /* if employee number matches with structure */

flag=1; /* condition indicator for printing further messages */

printf("\n\nEnter new salary for employee: ");

scanf("%f",&e.gs);

e.empno=e.empno; /* rest information should be same except only\ salary */e.sex=e.sex;

e.name[30]=e.name[30];

fseek(fp,-recsize,SEEK_CUR); /* seeking the correct location of data within\ structure in the file */fwrite(&e,recsize,1,fp); /* writing data at correct position */

break;

}}

if(flag==0) /* conditional indicator used above */printf("\n\n\n\tinformation does not exist!\n");

printf("\n\nenter another information(Y/N): ");another=getche();

clrscr();

}

break;

case '4':

clrscr();

printf("\n\n\tDelete employee\n");printf("\t***************\n\n");

ft=fopen("TEMP.DAT","w"); /* opening new temporary file */

rewind(fp); /* taking cursor back to the very beginning of file */

while(fread(&e,recsize,1,fp)==1) { /* matching each salary */

if(e.gs!=0.0 || e.gs!=0) { /* if salary is not 0 then data will be written to new file */

flag=1;

fwrite(&e,recsize,1,ft);

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

remove("EMP.DAT"); /* removing original file with 0 salary and renaming\ temporary without 0 salary as the original file */

Page 266: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

rename("TEMP.DAT","EMP.DAT");

fp=fopen("EMP.DAT","rt+"); /* opening the new file, it opens because it has not been opened before */ /* a file cannot be opened twice during execution as you know */

if(flag>0) {printf("\n\n\nall records with 0 gross salary have been deleted. \n");}

gotoxy(2,24);printf("\n\n\npress any key to return...");getch();

break;

case '0':

fclose(fp);exit();

case '3':

clrscr();

printf("\t\tList all employees\n");printf("\t\t******************\n\n\n");

rewind(fp);

while(fread(&e,recsize,1,fp)==1) {

flag=1;

printf("%2d\t%6s\t%c\t%.2f\n\n",e.empno,e.name,e.sex,e.gs);

}

if(flag==0)

printf("\n\n\tNo records exist!\n\n");

printf("\n\npress any key to return... ");

getch(); /* this is very important place, if we don't stop screen here \ after reading and printing the list,we won't be able to see it and it will disappear and will return to main menu because of "break" statement. */break;

} }

}linkfloat() { /* function to avoid possible errors because of floats */float a=0,*b;b=&a;a=*b;return 0;}

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

(o) Given a text file, write a program to create another text file deleting the words “a”, “the”, “an” and replacing each one of them with a blank space.

Page 267: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

NOTE: Make a file "FILE.TXT" in bin directory and write/paste something in it, then run the program, you will get another file as "NEW.TXT" as result of the program.

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

void replace();

void main() {

FILE *fp,*ft; char str[80],target[80]; clrscr();

fp=fopen("FILE.TXT","r");

if(fp==NULL) {

puts("cannot open source file!"); exit(); }

ft=fopen("NEW.TXT","w");

if(ft==NULL) {

puts("cannot open target file!"); exit(); }

while(fgets(str,79,fp)!=NULL) {

replace(str,&target);

fputs(target,ft);

}

fclose(fp); fclose(ft);

printf("\nTask completed!"); getch();

}

void replace(char *s, char *s1) {

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

/* copying to temporary string */

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

*t=*s;

t++; s++;

Solution:

Page 268: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

}

*t='\0';

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

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

temp2[j]=temp[i];

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

temp2[j]='\0';

if(strcmpi(temp2,"the")==0) {

strcpy(temp2," "); }

else if(strcmpi(temp2,"an")==0) {

strcpy(temp2," ");

}

else if(strcmpi(temp2,"a")==0) {

strcpy(temp2," ");

}

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,"the")==0){ /* checking last word too */

strcpy(temp2," "); }

else if(strcmpi(temp2,"an")==0) {

strcpy(temp2," "); }

else if(strcmpi(temp2,"a")==0) {

Page 269: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

strcpy(temp2," "); }

/***************************/ /* 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 */

}

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

*s1=*m;

s1++; m++;

}

*s1='\0';

}

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

(p) You are given a data file EMPLOYEE.DAT with the following record structure:struct employee {int empno ;char name[30] ;int basic, grade ;} ;Every employee has a unique empno and there are supposed to be no gaps between employee numbers. Records are entered into the data file in ascending order of employee number, empno. It is intended to check whether there are missing employee numbers. Write a program segment to read the data file records sequentially and display the list of missing employee numbers.

NOTE: assign employee numbers in ascending order only.

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

struct employee {

Solution:

Page 270: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

int empno; char name[30]; int basic,grade; }e; FILE *fp; int num=0; long recsize; char another,ch; clrscr();

fp=fopen("EMPLOYEE.DAT","rb+"); if(fp==NULL) { fp=fopen("EMPLOYEE.DAT","wb+");

if(fp==NULL) exit(); }

recsize=sizeof(e);

while(1) {

clrscr();

printf("\t\tEmployee number database:\n"); printf("\t\t*************************\n\n"); printf("\n\t1: Add employee information:\n"); printf("\n\t2: List employee information:\n"); printf("\n\t3: Check missing employee numbers:\n"); printf("\n\t0: Exit:\n\n");

gotoxy(2,24); printf("your choice: "); fflush(stdin); ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd employee information:\n"); printf("\t\t*************************\n\n");

printf("Note: employee numbers should be given in ascending order\n\n");

printf("\nEnter employee number: "); scanf("%d",&e.empno); printf("\n\nEnter employee name: "); scanf("%s",e.name); printf("\n\nEnter employee basic salary: "); scanf("%d",&e.basic); printf("\n\nEnter employee grade(1/2/3): "); scanf("%d",&e.grade);

fwrite(&e,recsize,1,fp);

gotoxy(2,24); printf("Add another employee information(Y/N): "); fflush(stdin); another=getche();

clrscr();

Page 271: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

}

break;

case '2':

clrscr();

printf("\t\tList employee information:\n"); printf("\t\t**************************\n\n\n");

rewind(fp); while(fread(&e,recsize,1,fp)==1) {

printf("\n%3d\t%8s\t%5d\t%d\n",e.empno,e.name,e.basic,e.grade);

}

printf("\n\npress any key to return...\n"); getch();

break;

case '3':

clrscr();

printf("\t\tMissing employee numbers:\n"); printf("\t\t*************************\n\n");

rewind(fp); while(fread(&e,recsize,1,fp)==1) { num=e.empno; /* assigning the value of first employee number */ break; }

rewind(fp); /* again rewinding the file to read from beginning */

while(fread(&e,recsize,1,fp)==1) {

if(num!=e.empno) { /* if assigned number is smaller than employee number we will print all the number between them */ while(num<e.empno) {

printf("%4d ",num);

num++; } num=e.empno+1;

}

/* we will assign greater value than employee number to make sure that both don't match until another greater employee number is found */

else

num=e.empno+1;

}

printf("\n\n press any key to return..."); getch();

break;

case '0':

fclose(fp);

Page 272: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

exit();

} } }

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

(q) Write a program to carry out the following:− To read a text file “TRIAL.TXT” consisting of a maximum of 50 lines of text, each line with a maximum of 80 characters.− Count and display the number of words contained in the file.− Display the total number of four letter words in the text file.Assume that the end of a word may be a space, comma or a full-stop followed by one or more spaces or a newline character.

NOTE: Make a file "TRIAL.TXT" in bin directory and write something in it ,then run the program.

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

FILE *fp; char s[80]; int twd,fwd,tw=0,fw=0;void word(); clrscr();

fp=fopen("TRIAL.TXT","r"); if(fp==NULL) {

exit(); }

while(fgets(s,79,fp)!=NULL) { word(s,&twd,&fwd); tw=tw+twd; fw=fw+fwd; }

fclose(fp);

printf("\nTotal number of words in text file = %d\n",tw); printf("\n\nTotal number of 4 letter words = %d\n",fw);

getch(); }

void word(char ss[80],int *tw, int *fw) {

int i=0,tot_wd=0,tot_4_wd=0;

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

/************************/ /* to cound total words */ /************************/

if(ss[i]>=65 && ss[i]<=90 || ss[i]>=97 && ss[i]<=122) {

Solution:

Page 273: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

if(ss[i+1]==' ' || ss[i+1]=='.' || ss[i+1]==',' || ss[i+1]=='\n' ) {

tot_wd++; } }

/*********************************/ /* to count total 4 letter words */ /*********************************/

if(ss[i]==' ' || ss[i]==',' || ss[i]=='.') {

if(ss[i+1]>=65 && ss[i+1]<=90 || ss[i+1]>=97 && ss[i+1]<=122) {

if(ss[i+2]>=65 && ss[i+2]<=90 || ss[i+2]>=97 && ss[i+2]<=122) {

if(ss[i+3]>=65 && ss[i+3]<=90 || ss[i+3]>=97 && ss[i+3]<=122) {

if(ss[i+4]>=65 && ss[i+4]<=90 || ss[i+4]>=97 && ss[i+4]<=122) {

if(ss[i+5]==' ' || ss[i+5]==',' || ss[i+5]=='.' || ss[i+5]=='\n') {

tot_4_wd++; } } } } } }

if(ss[i]>=65 && ss[i]<=90 || ss[i]>=97 && ss[i]<=122) {

if(ss[i+1]>=65 && ss[i+1]<=90 || ss[i+1]>=97 && ss[i+1]<=122) {

if(ss[i+2]>=65 && ss[i+2]<=90 || ss[i+2]>=97 && ss[i+2]<=122) {

if(ss[i+3]>=65 && ss[i+3]<=90 || ss[i+3]>=97 && ss[i+3]<=122) {

if(ss[i+4]==' ' || ss[i+4]==',' || ss[i+4]=='.' || ss[i+4]=='\n') {

} } } } }

i++;

}

*tw=tot_wd; *fw=tot_4_wd;

}

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

(r) Write a program to read a list of words, sort the words in alphabetical order and display them one word per line. Also give the total number of words in the list. Output format should be:Total Number of words in the list is _______Alphabetical listing of words is:-----------

Page 274: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

Assume the end of the list is indicated by ZZZZZZ and there are maximum in 25 words in the Text file.

NOTE: Make a file as "trial.txt" in bin directory and write some words in it. Words should be in the form of a list. One below another,then run the program.

#include<stdio.h>#include<conio.h>#define N 100

/* make a list of words, every words should be written under previous one to make sure it's a list of words. */

/* upper case letters will be arranged before small case letter, so it is recommended to use the list of either Capital letter or small case letters but not both together. */struct word { char wrd [30]; };

void main() {

struct word w[N];

FILE *fp;char s1[30];int i=0,count=0;void srt_wrd(); /* function to sort and print list */

clrscr();

fp=fopen("TRIAL.TXT","rb+");

while(fgets(s1,30,fp)!=NULL) {strcpy(w[i].wrd,s1); /* copying each word in array of structure */i++;count++; /* count of all the words */}

printf("Total words if file = %3d\n",count);

printf("\t\tList in alphabetical order:\n");srt_wrd(&w,count); /* function for sorting and printing list */

fclose(fp);getch();

}

void srt_wrd( struct word *w, int n) {

int i,j,k=0;struct word temp;

/***************************************//* sorting words in alphabetical order *//***************************************/

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

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

/* testing the first alphabets of two words */

Solution:

Page 275: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

if(w[i].wrd[0] > w[j].wrd[0]) {

temp=w[i];w[i]=w[j];w[j]=temp;}

/* testing the first two alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1] > w[j].wrd[1]) {

temp=w[i];w[i]=w[j];w[j]=temp;}

/* testing first three alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]>w[j].wrd[2]) {

temp=w[i];w[i]=w[j];w[j]=temp;}}

/* testing first four alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]==w[j].wrd[2] && w[i].wrd[3]>w[j].wrd[2]) {

temp=w[i];w[i]=w[j];w[j]=temp;}}

}}

/*****************************//* printing the sorted words *//*****************************/

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

printf("%-s\n",w[i].wrd);

k++;

if(k==10) {

printf("\n\npress any key to go to next page...");getch();

k=1;clrscr();}}

}

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

Page 276: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

(s) Write a program to carry out the following:(a) Read a text file ‘INPUT.TXT’(b) Print each word in reverse orderExample,Input: INDIA IS MY COUNTRYOutput: AIDNI SI YM YRTNUOCAssume that each word length is maximum of 10 characters and each word is separated by newline/blank characters.

NOTE: Make a file "INPUT.TXT" in bin directory and write something in it, then run the program.

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

void main() {

FILE *fs;char s[80];void rev();

clrscr();

fs=fopen("INPUT.TXT","r");

if(fs==NULL) {

printf("cannot open file!");exit();}

while(fgets(s,79,fs)!=NULL)rev(s);

fclose(fs);

getch();

}

void rev(char s1[80]) {

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

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

s2[j]=s1[i];

if(s1[i]==' ' || s1[i]=='\0') {

s2[j]='\0';

strrev(s2);

printf("%s ",s2);

j=-1;

}

i++;j++;

Solution:

Page 277: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

}

s2[j]='\0';

printf("%s",strrev(s2));

}

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

(s) Write a C program to read a large text file ‘NOTES.TXT’ and print it on the printer in cut-sheets, introducing page breaks at the end of every 50 lines and a pause message on the screen at the end of every page for the user to change the paper.

NOTE: Make a file as "NOTES.TXT" in bin directory and write/paste some text in it, then run the program.

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

void print();

void main() {

FILE *fp;

char s[80]; int x=4,y=4,c=0,pg=0; clrscr();

fp=fopen("NOTES.TXT","r");

if(fp==NULL) {

puts("cannot open file!"); exit(); }

while(fgets(s,74,fp)!=NULL) {

gotoxy(30,1); /* printing page number */ printf("Page No: %3d",pg);

print(s,x,y,c); /* function to print */

c++; y++;

if(c>51) { /* checking for page end */

pg++;

c=0; gotoxy(2,24); printf("press any key to change paper..."); getch();

clrscr();

Solution:

Page 278: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 12 (File Input Output)

http://letuscalllessons.blogspot.com/2014/01/chapter-12-file-input-output.html[07-Apr-14 8:49:48 PM]

}

if(y>22) { /* checking for total lines */

gotoxy(2,24); printf("press any key to go to next page..."); getch(); y=5; clrscr(); }

}

fclose(fp); }

void print(char *s,int x, int y, int c) {

/* page border */

int i,bdr,bdr2;

gotoxy(1,2); printf("%c",218); for(bdr=3;bdr<23;bdr++) {

gotoxy(1,bdr); printf("%c",179);

gotoxy(79,bdr); printf("%c",179);

}

gotoxy(79,2); printf("%c",191);

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

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

for(bdr2=2;bdr2<=78;bdr2++) {

gotoxy(bdr2,2); printf("%c",196);

}

gotoxy(x,y);

puts(s);

if(c>50) {

for(i=2;i<79;i+=2) {

gotoxy(i,23);

printf("-"); } } }

____________________________________________________

Page 280: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 1 (Getting started)

http://letuscalllessons.blogspot.com/2014/01/chapter-1-getting-started.html[07-Apr-14 8:50:41 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 1 (Getting started)

(a) Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.

Solution:

(b) The distance between two cities (in km.) is input through the keyboard. Write a program to convert and print this distance in meters, feet, inches and centimeters.

#include<stdio.h>#include<conio.h>main() {long km,m,ft,inc,cm;clrscr();printf("Please enter the distance(in km):\n");scanf("%ld",&km);m=km*1000;ft=m*3;inc=ft*12;cm=ft*30;printf("\nDistance in kilometer = %ld\n",km);printf("\nDistance in meter = %ld\n",m);printf("\nDistance in feet = %ld\n",ft);printf("\nDistance in inches = %ld\n",inc);printf("\nDistance in centimeters = %ld\n",cm);getch();

Exercise [H]

#include<stdio.h>#include<conio.h>main() {long bs,da,hra,gs;clrscr();printf("Please enter Ramesh's Basic Salary: \n");scanf("%ld",&bs);gs=(40*bs/100)+(20*bs/100)+bs;printf("Ramesh's GROSS SALARY = %ld\n",gs);getch();return 0;} ------------------------------------------------------------------------------------------------------------

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 281: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 1 (Getting started)

http://letuscalllessons.blogspot.com/2014/01/chapter-1-getting-started.html[07-Apr-14 8:50:41 PM]

return 0;}

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

(c) If the marks obtained by a student in five different subjects are input through the keyboard, find out the aggregate marks and percentage marks obtained by the student. Assume that the maximum marks that can be obtained by a student in each subject is 100.

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

(d) Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this temperature into Centigrade degrees.

#include<stdio.h>#include<conio.h>main() {float fh,cn;clrscr();printf("Please enter the temperature in fahrenheit:\n");scanf("%f",&fh);cn=5*(fh-32)/9;printf("Centigrade Temperature = %f \n",cn);getch();return 0;}

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

(e) The length & breadth of a rectangle and radius of a circle are input through the keyboard. Write a program to calculate the area & perimeter of the rectangle, and the area & circumference of the circle.

Solution:

#include<stdio.h>#include<conio.h>main() {int m1,m2,m3,m4,m5,ttl;float prcnt;clrscr();printf("Please enter the marks of the student:\n");scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);ttl=m1+m2+m3+m4+m5;prcnt=ttl/5;printf("AGGREGATE MARKS = %d\nPERCENTAGE MARKS = %f%\n",ttl,prcnt);getch();return 0;}

Solution:

Solution:

#include<stdio.h>#include<conio.h>main() {float l,b,area,peri,ca,cr,r;clrscr();printf("Please enter the length of rectangle:");scanf("%f",&l);printf("\nPlease enter the breadth of rectangle:");scanf("%f",&b);area=l*b;peri=2*(l+b);

Page 282: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 1 (Getting started)

http://letuscalllessons.blogspot.com/2014/01/chapter-1-getting-started.html[07-Apr-14 8:50:41 PM]

(f) Two numbers are input through the keyboard into two locations C and D. Write a program to interchange the contents of C and D.

#include<stdio.h>#include<conio.h>main() {int c,d,t;clrscr();printf("Enter value of C: ");scanf("%d",&c);printf("\n\nEnter value of D: ");scanf("%d",&d);t=c;c=d;d=t;printf("\n\nC = %d\nD = %d\n",c,d);getch();}

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

(g) If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits.(Hint: Use the modulus operator ‘%’)

#include<stdio.h>#include<conio.h>main() {long i,d1,d2,d3,d4,d5,a,b,c,d,sum;clrscr();printf("Please enter the five digit number: \n");scanf("%ld",&i);d1=i/10000;a=i%10000;d2=a/1000;b=a%1000;d3=b/100;c=b%100;d4=c/10;d=c%10;d5=d/1;sum=d1+d2+d3+d4+d5;printf("Sum of the digits is %ld\n",sum);getch();return 0;}

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

(h) If a five-digit number is input through the keyboard, write a program to reverse the number.

printf("\n\nAREA = %f square cm.\t PERIMETER = %f cm.\n",area,peri);printf("\n\nPlease enter the radius of the circle:");scanf("%f",&r);ca=3.14*r*r;cr=2*3.14*r;printf("\n\nAREA = %f square cm.\t CIRCUMFERENCE = %f cm.\n",ca,cr);getch();return 0;}

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

Solution:

Solution:

Page 283: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 1 (Getting started)

http://letuscalllessons.blogspot.com/2014/01/chapter-1-getting-started.html[07-Apr-14 8:50:41 PM]

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

(i) If a four-digit number is input through the keyboard, write a program to obtain the sum of the first and last digit of this number.

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

(j) In a town, the percentage of men is 52. The percentage of total literacy is 48. If total percentage of literate men is 35 of the total population, write a program to find the total number of illiterate men and women if the population of the town is 80,000.

#include<stdio.h>#include<conio.h>main() {int i,d1,d4,a,b,c,sum;clrscr();printf("Please enter the four digit number: \n");scanf("%d",&i);d1=i/1000;

Solution:

#include<stdio.h>#include<conio.h>main() {long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();printf("Please enter the five digit number: \n");scanf("%ld",&i);d1=i/10000;a=i%10000;d2=a/1000;b=a%1000;d3=b/100;c=b%100;d4=c/10;d=c%10;d5=d/1;n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);printf("reversed number = %ld \n",n_num);getch();return 0;}

Solution:

#include<stdio.h>#include<conio.h>main() {int i,d1,d4,a,b,c,sum;clrscr();printf("Please enter the four digit number: \n");scanf("%d",&i);d1=i/1000;a=i%1000;b=a%100;c=b%10;d4=c/1;sum=d1+d4;

printf("The sum of first and last digit is %d\n",sum);getch();return 0;}

Solution:

Page 284: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 1 (Getting started)

http://letuscalllessons.blogspot.com/2014/01/chapter-1-getting-started.html[07-Apr-14 8:50:41 PM]

a=i%1000;b=a%100;c=b%10;d4=c/1;sum=d1+d4;printf("The sum of first and last digit is %d\n",sum);getch();return 0;}

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

(k) A cashier has currency notes of denominations 10, 50 and 100. If the amount to be withdrawn is input through the keyboard in hundreds, find the total number of currency notes of each denomination the cashier will have to give to the withdrawer.

#include<stdio.h>#include<conio.h>main() {int a,t_10,f_50,h_100,b,c;clrscr();printf("Please enter the amount to be withdrawn: \n");scanf("%d",&a);h_100=a/100;b=a%100;f_50=b/50;c=b%50;t_10=c/10;

printf("\nCurrency notes of 100 should be = %d\n",h_100);printf("\nCurrency notes of 50 should be = %d\n",f_50);printf("\nCurrency notes of 10 should be = %d\n",t_10);getch();return 0;}

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

(l) If the total selling price of 15 items and the total profit earned on them is input through the keyboard, write a program to find the cost price of one item.

#include<stdio.h>#include<conio.h>main() {int sp,p,cp;clrscr();

printf("Please enter the selling price of 15 items: \n");scanf("%d",&sp);printf("\nPlease enter the total profit of 15 items: \n");scanf("%d",&p);cp=(sp-p)/15;printf("Cost price of one item is %d\n",cp);getch();return 0;}

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

(m) If a five-digit number is input through the keyboard, write a program

Solution:

Solution:

Page 285: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 1 (Getting started)

http://letuscalllessons.blogspot.com/2014/01/chapter-1-getting-started.html[07-Apr-14 8:50:41 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Posted by Chetan Raikwar at 07:01

to print a new number by adding one to each of its digits. For example if the number that is input is 12391 then the output should be displayed as 23502.

#include<stdio.h>#include<conio.h>main() {long i,add;clrscr();printf("Please enter a five digit number: \n");scanf("%ld",&i);add=i+11111;printf("addition = %ld\n",add);getch();return 0;}

______________________________________________________________________

Solution:

Recommend this on Google

Comment as: Google Account

No comments:

Post a Comment

Simple template. Powered by Blogger.

Page 286: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 3 (The Loop Control Structure)

(a) Write a program to calculate overtime pay of 10 employees. Overtime is paid at the rate of Rs. 12.00 per hour for every hour worked above 40 hours. Assume that employees do not work for fractional part of an hour.

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

main() {

int wrkh,hr,emp,pay,r=12;clrscr();

printf("Please enter working hours of 10 employees: \n\n");

emp=1;

while(emp<=10) {

printf("\n\nEnter working hours of employee: ",emp);

scanf("%d",&wrkh);

if(wrkh>40) {

hr=wrkh-40;pay=hr*r;

printf("\n%d\tOver-time pay %d rs\n",emp,pay);

}

else {

printf("\n%d\tNo over time pay\n",emp);

}

emp++;

}

Exercise [B]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 287: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

getch();return 0;

}

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

(b) Write a program to find the factorial value of any number entered through the keyboard.

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

main() {

long i,j,fact=1;clrscr();

printf("Please enter any number: ");scanf("%ld",&i);

for(j=i;j>=1;j--) {

fact=fact*j;

}

printf("Factorial value = %ld ",fact);

getch();return 0;

}

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

(c) Two numbers are entered through the keyboard. Write a program to find the value of one number raised to the power of another.

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

main() {

int num1,num2,i,rslt=1;clrscr();

printf("Enter two numbers: \n");scanf("%d%d",&num1,&num2);

for(i=1;i<=num2;i++) {rslt=rslt*num1;

if(i==num2) {break;}

}

Solution:

Solution:

Page 288: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

printf("\n\nvalue of %d raised to the power of %d is = %d\n",num1,num2,rslt);

getch();return 0;

}

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

(d) Write a program to print all the ASCII values and their equivalent characters using a while loop. The ASCII values vary from 0 to 255.

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

int i=0;clrscr();

while(i<=255) {

printf(" %d %c \n",i,i);i++;

}

getch();return 0;

}

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

(e) Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number. For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 )

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

main() {

int i,a,b,c,d,e;clrscr();

printf("All Armstrong Numbers between 1-500 are: \n\n");

for(i=1;i<=500;i++) {

if(i<9) { /* for one digit numbers */a=i/1;

if((a*a*a)==(a*1)) {printf(" %d ",i);

} }

if(i>9 && i<100) { /* for two digit numbers */

a=i/10;b=i%10;

Solution:

Solution:

Page 289: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

c=b/1;

if(((a*a*a)+(c*c*c))==((a*10)+(c*1))) {printf(" %d ",i);

}}

if(i>99) { /* for three digit numbers */

a=i/100;b=i%100;c=b/10;d=b%10;e=d/1;

if(((a*a*a)+(c*c*c)+(e*e*e))==((a*100)+(c*10)+(e*1))){

printf(" %d ",i);

} }

}

getch();return 0;

}

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

(f) Write a program for a matchstick game being played between the computer and a user. Your program should ensure that the computer always wins. Rules for the game are as follows:− There are 21 matchsticks.− The computer asks the player to pick 1, 2, 3, or 4 matchsticks.− After the person picks, the computer does its picking.− Whoever is forced to pick up the last matchstick loses the game.

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

main() {

int tms=21,lms=0,user,cpu,pms=0;char another;

clrscr();

do {

printf("\nPick up 1,2,3 or 4 matchsticks: ");scanf("%d",&user); /* Matchsticks picked by you */

cpu=user; /* Matchsticks picked by computer */

if(pms<20) {printf("\nyou picked = %d\tcomputer picked = %d\n",user,cpu);}else {printf("\nyou picked =%d\n",user);}

pms=pms+(cpu+user); /* Total picked Matchsticks */

Solution:

Page 290: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

lms=tms-pms; /* Total left matchsticks */

if(pms<=21) {printf("\nleft matchsticks = %d\n",lms);}else {break;}

printf("\nPick again Y/N: ");scanf(" %c",&another);

}while(another=='y');

printf("\n\n\n");printf("\n==============\n");printf("\nComputer wins!\n");printf("\n==============\n");

getch();return 0;

}

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

(g) Write a program to enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros entered.

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

main() {

int num,tnum=0,tp=0,tn=0,tz=0;char another;

clrscr();

do {printf("\nEnter any number: ");scanf("%d",&num);

tnum=tnum+1; /* count of total numbers entered by you */

if(num==0) /* count of total zeros */tz=tz+1;

if(num>0) /* count of total positive numbers */tp=tp+1;

if(num<0) /* count of total negative number */tn=tn+1;

printf("\nEnter another number Y/N: ");scanf(" %c",&another);

}while(another=='y');

clrscr();

printf("\n\n\nTotal numbers entered = %d\n",tnum);

Solution:

Page 291: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

printf("\nTotal zeros = %d\n",tz);printf("\nTotal positive numbers = %d\n",tp);printf("\nTotal negative numbers = %d\n",tn);

getch();return 0;

}

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

(h) Write a program to find the octal equivalent of the entered number.

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

long num,n;clrscr();

printf("Please enter the number: ");scanf("%ld",&num);printf("\n\nOctal equivalent: ");

while(num!=0) {

n=num%8;

printf("%ld",n);

num=num/8; /* devision by 8 */

}

gotoxy(20,6);printf("<%c%c%c%c%c read from right to left",196,196,196,196,196);

getch();return 0;}

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

(i) Write a program to find the range of a set of numbers. Range is the difference between the smallest and biggest number in the list

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

int min,max,num,range,flag=0;char ch;

clrscr();

do {

printf("\nEnter number: ");scanf("%d",&num);

if(flag==0) {

min=num;max=num;}

Solution:

Solution:

Page 292: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

flag++; /* counting total numbers */

if(min>num) {min=num;}

if(max<num)max=num;

printf("\n\nEnter another number(Y/N): ");scanf(" %c",&ch);

clrscr();}while(ch=='Y' || ch=='y');

range=max-min;

printf("\nTotal number = %d\n",flag);printf("\nLargest number = %d\n",max);printf("\nSmallest number = %d\n",min);printf("\nRange = %d\n",range);

getch();return 0;}______________________________________________________________________

(a) Write a program to print all prime numbers from 1 to 300. (Hint: Use nested loops, break and continue)

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

int i=1,j;

clrscr();

printf("\nPrime numbers between 1 to 300 are:\n\n");

while(i!=300) {

j=2;

while(j<i) {

if(i%j==0) {break;}

j++;

}

if(j==i) {

printf(" %d",i);

}

i++;}

Exercise [E]

Solution:

Page 293: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

getch();return 0;

}

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

(b) Write a program to fill the entire screen with a smiling face. The smiling face has an ASCII value 1.

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

int i;clrscr();

for(i=1;i<=10000;i++) {printf("%c",1);}

getch();return 0;

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

(c) Write a program to add first seven terms of the following series using a for loop:

1/1! + 2/2! + 3/3! + .............

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

main() {

float i,j,k,fact=1,factsum,numsum;clrscr();

printf("\tTerm\t\tFactorial\n\n");

for(i=1;i<=7;i++) {

for(j=i;j>=2;j--) {

fact=fact*j;factsum=factsum+fact;break;}numsum=numsum+i;printf("\t%.0f\t\t%.0f\n",i,fact);}

k=numsum/factsum;

printf("\n\nsum of 7 terms = %.0f ",numsum);printf("\nsum of all factorials = %.0f",factsum);printf("\n\naddition of all terms / sum of factorials: %f",k);

getch();return 0;

Solution:

Solution:

Page 294: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

}

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

(d) Write a program to generate all combinations of 1, 2 and 3 using for loop.

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

int i,j,k;clrscr();

printf("All combinations of 1,2,3 are:\n\n");for(i=1;i<=3;i++) {for(j=1;j<=3;j++) {for(k=1;k<=3;k++) {printf(" %d%d%d ",i,j,k);} } }

getch();return 0;}

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

(e) According to a study, the approximate level of intelligence of a person can be calculated using the following formula:i = 2 + ( y + 0.5 x )Write a program, which will produce a table of values of i, y and x, where y varies from 1 to 6, and, for each value of y, x varies from 5.5 to 12.5 in steps of 0.5.

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

float i=1,x,y;clrscr();

for(y=1.0;y<=6.0;y++) {

for(x=5.5;x<=12.5;x+=0.5) {

i=2+(y+(0.5*0.5));

printf("%.2f\t%.2f\t%.2f\n",i,y,x);

}

}

getch();return 0;

}

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

Solution:

Solution:

Page 295: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

(f) Write a program to produce the following output:

A B C D E F G F E D C B AA B C D E F F E D C B AA B C D E E D C B AA B C D D C B AA B C C B AA B B AA A

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

int i,j,k,l;clrscr();

for(i=71;i>=65;i--) {

/* loop for printing ascending letters */

for(j=65;j<=i;j++) {

printf("%c ",j);

}

/* loop for making a space between patterns */

for(k=i+1;k<=71;k++) {

if(k==71)printf(" ");

if(k<71)printf(" ");}

/* loop to print descending letters */

for(l=i;l>=65;l--) {

if(l==71) { /* to skip printing 'G' twice */continue;}

printf("%c ",l);

}printf("\n");}

getch();

return 0;}

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

(g) Write a program to fill the entire screen with diamond and heart alternatively. The ASCII value for heart is 3 and that of diamond is 4.

Solution:

Solution:

Page 296: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

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

int i,j;clrscr();

for(i=j=1;i<=10000,j<=10000;i++,j++) {printf("%c%c",4,3);}

getch();return 0;

}

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

(h) Write a program to print the multiplication table of the number entered by the user. The table should get displayed in the following form.29 * 1 = 2929 * 2 = 58…

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

int i,j,k;clrscr();

printf("Please enter the number:\n");scanf("%d",&i);

for(j=1;j<=10;j++) {k=i*j;printf("\n%d*%d = %d\n",i,j,k);}

getch();return 0;

}

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

(i) Write a program to produce the following output: 1 2 3 4 5 67 8 9 10

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

int i,num=0,k,j;clrscr();

Solution:

Solution:

Page 297: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

for(i=1;i<=4;i++) {

for(j=4;j>=i;j--) { /* loop for making a space from left corner */

printf(" ");

}

for(k=1;k<=i;k++) {

num=num+1; /* incrementing external number for printing */

printf(" %d ",num);

}

printf("\n\n");}

getch();

}

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

(j) Write a program to produce the following output:

1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

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

int i,j,k;clrscr();

printf(" 1\n\n\n");

for(i=1;i<=4;i++) {

for(k=5;k>=i;k--) {printf(" ");}printf("1 ");

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

if(i==4 && j==3) {printf("%d ",i+j-1);continue;}

if(j>1)printf("%d ",i);

}

printf("1\n\n\n");

}

Solution:

Page 298: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

getch();return 0;

}

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

(k) A machine is purchased which will produce earning of Rs. 1000 per year while it lasts. The machine costs Rs. 6000 and will have a salvage of Rs. 2000 when it is condemned. If 12 percent per annum can be earned on alternate investments what would be the minimum life of the machine to make it a more attractive investment compared to alternative investment?

#include <stdio.h>#include <conio.h>int main(){int year=0,inv,altn;

while(altn>inv) {

year+=1;altn=120*year;inv=(1000*year)-(6000-2000);

}

printf("Minimum life of the machine would be = %d",year); getch(); return 0;}------------------------------------------------------------------------------------------------------------

(l) When interest compounds q times per year at an annual rate of r % for n years, the principle p compounds to an amount a as per the following formulaa = p ( 1 + r / q ) nqWrite a program to read 10 sets of p, r, n & q and calculate the corresponding as.

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

int i,p,r,n,q,j,pw;float a;

clrscr();

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

printf("Set number %d:\n\n\n\n",i+1);

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

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

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

Solution:

Solution:

Page 299: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

Posted by Chetan Raikwar at 07:02

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

pw=n*q;

for(j=0;j<pw;j++) {

a = a + p *(1+r/1);

}printf("\n\n\nA = %f\n",a);

printf("\n\n\n\npress any key to proceed...");getch();

clrscr();}

getch();return 0;}

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

(m) The natural logarithm can be approximated by the following series.x-1/x + 1/2(x-1/x)2 + 1/2(x-1/x)3 + 1/2(x-1/x)4 + --------If x is input through the keyboard, write a program to calculate the sum of first seven terms of this series.

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

float x,nl,x_1,t1;int i;

clrscr();

printf("\n\nEnter the value of X: ");scanf("%f",&x);

t1 = (x-1)/x; /* fist term */

for(i=2;i<=7;i++) {

nl = (1.0/2.0) * pow((x_1),i); /* terms from 2 to 7 */

}

nl = nl + t1; /* adding all the terms */

printf("\n\nApproximated natural log = %f\n",nl);

getch();return 0;}___________________________________________________________________

Solution:

Recommend this on Google

Page 300: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 3 (The Loop Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-3-loop-control-structure.html[07-Apr-14 8:51:29 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Comment as: Google Account

No comments:

Post a Comment

Simple template. Powered by Blogger.

Page 301: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 4 (The Case Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-4-case-control-structure.html[07-Apr-14 8:52:22 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 4 (The Case Control Structure)

Write a menu driven program which has following options:

1. Factorial of a number.2. Prime or not3. Odd or even4. Exit

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

int num,i,j=0,k=0,choice,fact=1;clrscr();

printf("Please enter any number: ");scanf("%d",&num);

while(1){printf("\n\n1. Factorial");printf("\n2. Prime");printf("\n3. Odd/Even");printf("\n4. Exit");printf("\n\nPlease enter your choice: ");scanf("%d",&choice);

switch(choice){

case 1:

for(i=num;i>=1;i--) { fact=fact*i; } printf("\nFactorial = %d ",fact); break;

case 2:

for(i=2;i<num;i++) { j=num%i; if(j==0){ k=1;

Exercise [C]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 302: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 4 (The Case Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-4-case-control-structure.html[07-Apr-14 8:52:22 PM]

break; } } if(k==0) { printf("\nPrime Number"); } else { printf("\nNot a Prime Number"); } break;

case 3:

if((num%2)==0) printf("\nEven Number"); else printf("\nOdd Number"); break;

case 4:

exit();

} }

}

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

Write a program which to find the grace marks for a student using switch. The user should enter the class obtained by the student and the number of subjects he has failed in.

− If the student gets first class and the number of subjects he failed in is greater than 3, then he does not get any grace. If the number of subjects he failed in is less than or equal to 3 then the grace is of 5 marks per subject.

− If the student gets second class and the number of subjects he failed in is greater than 2, then he does not get any grace. If the number of subjects he failed in is less than or equal to 2 then the grace is of 4 marks per subject.

− If the student gets third class and the number of subjects he failed in is greater than 1, then he does not get any grace. If the number of subjects he failed in is equal to 1 then the grace is of 5 marks per subject

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

int _class,f_sub;clrscr();

printf("\nPlease enter the class obtained\n1=first 2=second 3=third: ");scanf("%d",&_class);printf("\n\nPlease enter the number of failed subjects: ");

Exercise [D]

Solution:

Page 303: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 4 (The Case Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-4-case-control-structure.html[07-Apr-14 8:52:22 PM]

Posted by Chetan Raikwar at 07:02

scanf("%d",&f_sub);

switch(_class) {

case 1: if(f_sub<=3) { printf("\nGrace marks = 5 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

case 2: if(f_sub<=2) { printf("\nGrace marks = 4 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

case 3: if(f_sub==1) { printf("\nGrace marks = 5 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

default: printf("Error! wrong input.\n"); break; }

getch(); return 0;

}_____________________________________________________________________

Recommend this on Google

Comment as: Google Account

No comments:

Post a Comment

Page 304: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 4 (The Case Control Structure)

http://letuscalllessons.blogspot.com/2014/01/chapter-4-case-control-structure.html[07-Apr-14 8:52:22 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Simple template. Powered by Blogger.

Page 305: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 5 (Functions & Pointers)

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

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

void main() {

int num;void func();

clrscr();

printf("Please enter any number: ");scanf("%d",&num);

func(num);

getch();

}

void func(int n) {

int fact=1;

for(;n>=1;n--) {

fact=fact*n;

}

printf("\n\nFactorial value = %d \n",fact);

}

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

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

Exercise [D]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 306: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

b.

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

void main() {

int num1,num2 ;clrscr();

printf("Please enter the value of a: ");scanf("%d",&num1);

printf("\n\nPlease enter the value of b: ");scanf("%d",&num2);

power(num1,num2);

getch();

}

power(int a , int b) {

int c=1,i;

for(i=1;i<=b;i++) {c=c*a;

if(i==b) {break;}

}

printf("\n\n\nValue of %d raised to the power of %d is = %d\n",a,b,c);

return 0; }

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

(c) Write a general-purpose function to convert any given year into its roman equivalent. The following table shows the roman equivalents of decimal numbers:

Decimal Roman

1 i5 v10 x50 l100 c500 d1000 m

Example:Roman equivalent of 1988 is mdcccclxxxviiiRoman equivalent of 1525 is mdxxv

Solution:

Page 307: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

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

void main() {

int yr;void func();

clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

printf("\n\nRoman Equivalent = ");func(yr);

getch();

}void func(int y) {

int d1,d2,d3,d4,d5,d6,d7,a,b,c,d,e,f;

char thsnd='m',hndr_5='d',hndr='c',ffty='l',tn='x',fv='v',one='i';

/******* Roman Convertion ********/

/* To find all thousands */

d1=y/1000;a=y%1000;

for(;d1>=1;d1--) {printf("%c",thsnd);

if(a==0)break;}

/* To find all five-hundreds */

d2=a/500;b=a%500;

for(;d2>=1;d2--) {printf("%c",hndr_5);

if(b==0)break;}

/* To find all hundreds */

d3=b/100;c=b%100;

for(;d3>=1;d3--) {printf("%c",hndr);

if(c==0)break;}

/* To find all fifties *//***********************/

Solution:

Page 308: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

d4=c/50;d=c%50;

for(;d4>=1;d4--) {printf("%c",ffty);

if(d==0)break;}

/* To find all tens *//********************/

d5=d/10;e=d%10;

for(;d5>=1;d5--) {printf("%c",tn);

if(e==0)break;

}

/* To find all fives */

d6=e/5;f=e%5;

for(;d6>=1;d6--) {printf("%c",fv);

if(f==0)break;}

/* To find all ones */

for(d7=f;d7>=1;d7--) {printf("%c",one);

}

}

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

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

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

int yr;void func();clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

func(yr);

Solution:

Page 309: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

getch();

}void func(int y) {

if((y%4)==0)

printf("\nThis is a LEAP YEAR.\n");

else

printf("\nThis is NOT A LEAP YEAR.\n");

}

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

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

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

void main() {

int i,j,k;clrscr();

printf("enter the number: ");

scanf("%d",&j);

printf("\n\nprime factors:");

for(i=2;i<=j;) {

if(j%i==0) { /* divide only if remainder is supposed to be 0 */

j=j/i;

printf(" %d ",i); /* print the divisor */

}

else /* if divisor cannot divide completely */

i=i+1; /* increase it's value and try again */

}

getch();

}

________________________________________________________________________

(a) Write a function which receives a float and an int from main( ), finds

Solution:

Exercise [F]

Page 310: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

the product of these two and returns the product which is printed through main( ).

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

void main() {

int i;float j,k,product();clrscr();

printf("Please enter an integer number: ");scanf("%d",&i);

printf("\nPlease enter a decimal number: ");scanf("%f",&j);

k=product(&i,&j);

printf("\nProduct = %.1f\n",k);

getch();

}

float product(int *a,float *b) {

float *c;

*c=(*a)*(*b);

return *c;

}

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

(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<stdio.h>#include<conio.h>#include<math.h>

void main() {

int d1,d2,d3,d4,d5,i,sum,avg;float sd;

clrscr();

printf("enter five digits: \n\n");scanf("%d%d%d%d%d",&d1,&d2,&d3,&d4,&d5);

func(d1,d2,d3,d4,d5,&sum,&avg,&sd);

printf("\tsum = %d\n\taverage = %d\n\tstandard deviation = %f ",sum,avg,sd);

getch();

Solution:

Solution:

Page 311: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

}func(int a, int b, int c, int d, int e, int *s, int *av, float *ssd) {

float temp;

*s=a+b+c+d+e; /* sum of digits */*av=(a+b+c+d+e)/5; /* average */

a=a-(*av);b=b-(*av);c=c-(*av);d=d-(*av);e=e-(*av);

temp=((a*a)+(b*b)+(c*c)+(d*d)+(e*e))/4; /* standard deviation */*ssd=sqrt(temp);

return 0;

}

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

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

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

int s1,s2,s3,*avg,*prcnt;void func();clrscr();

printf("Please enter the marks of 3 subjects: \n");scanf("%d%d%d",&s1,&s2,&s3);

func(s1,s2,s3,&avg,&prcnt);

printf(" Average = %d\nPercentage = %d%\n",avg,prcnt);

getch();

}void func(int a, int b, int c, int *d, int *f) {

*d=(a+b+c)/3;*f=(a+b+c)/3;

}_____________________________________________________________________

a) A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:(1) Without using recursion(2) Using recursion

Solution:

Exercise [J]

Solution:

Page 312: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

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

long num,s=0,ch;clrscr();

printf("Enter any number: ");scanf("%ld",&num);

printf("\n\nChoose: 1: obtain sum of digits non-recursively\n\n");printf(" 2: obtain sum of digits recursively\n\n\n");

printf("Your choice: ");ch=getche();

switch(ch) {

case '1':

while(num!=0) {

s=s+(num%10);

num=num/10;

}

printf("\n\n\nsum of digits = %d\n",s);

break;

case '2':

s=sum(num);

printf("\n\n\nSum of digits = %d\n",s);break;}

getch();

}

sum(long n) {

static s=0;

if(n==0)return s;

else {

s=s+n%10;n=sum(n/10);

return n;

}

}

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

(b) A positive integer is entered through the keyboard, write a program to obtain the prime factors of the number. Modify the function suitably to obtain the prime factors recursively.

Page 313: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

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

int d,ch,b=2;clrscr();

printf("Enter the number: ");

scanf("%d",&d);

printf("\n\nObtain prime factors:\n\n");printf("1: non-recursively\n\n");printf("2: recursively\n\n");

printf("your choice: ");scanf("%d",&ch);

switch(ch) {

case 1:

printf("\n\n\nPrime factors: ");while(d!=1) {

if(d%b==0) { /* non recursive method */d=d/b;printf("%d ",b);}elseb++;}break;

case 2:

printf("\n\n\nPrime factors: ");

factors(d);

break;

default:

printf("\n\nwrong input!");

break;}

getch();

}

int factors (int n) {

int b=2;

if(n==1)return 1;

else {

while(n!=1) {

if((n%b)==0) {

Solution:

Page 314: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

n=factors(n/b); /* recursive function */

printf("%d ",b);}

elseb++;

}return n;}

}

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

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

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

unsigned i,num=25,c=1;clrscr();

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

printf("%u ",fib(c));

c++;}

getch();}

fib(unsigned n) {

if(n==0)return 0;

if(n==1)return 1;

else

return fib(n-1)+fib(n-2);

}

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

(d) A positive integer is entered through the keyboard, write a function to find the binary equivalent of this number using recursion.

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

int num;

Solution:

Solution:

Page 315: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

clrscr();

printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,7);printf("<%c%c%c%c%c read right to left",196,196,196,196,196);

getch();

}

binary(int n) {

if(n==0)return 0;

else {

printf("%d",n%2);

n= binary( n/2 ); /* recursive function */

return n;

}

}------------------------------------------------------------------------------------------------------------

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

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

int i=25,j;clrscr();

j=recsum(i);

printf("Addition of 25 natural numbers = %d",j);

getch();

}

int recsum(int n) {

if(n==1)return 1;

else

n = n + recsum(n-1); /* recursive addition */

return n;

}

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

(f) Write a C function to evaluate the series

Solution:

Page 316: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

sin(x) = x - (x3/3!) + ( x5/5!) - (x7/7!) + ........to five significant digits.

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

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

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

int x,y,z;char choice;void func();clrscr();

printf("Please enter values of X,Y,Z\n");scanf("%d",&x);scanf("%d",&y);scanf("%d",&z);

printf("\n\nBefore shift: X=%d Y=%d Z=%d\n",x,y,z);

func(&x,&y,&z); /* Call by reference */

printf("\n\nAfter shift: X=%d Y=%d Z=%d\n\n",x,y,z);

/* Circular Shifting continuously */

do {

printf("\nShift again(Y/N): ");scanf(" %c",&choice);

clrscr();

func(&x,&y,&z);printf("\nAfter another shift: X=%d Y=%d Z=%d\n\n",x,y,z);

}while(choice=='y');

}

void func(int *a,int *b,int *c) {

int d,e,f;

d=*a;e=*b;f=*c;*a=f;*b=d;*c=e;

}

Solution:

Solution:

Page 317: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

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

(h) Write a function to find the binary equivalent of a given decimal integer and display it.

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

int num;void binary();

clrscr();

printf("\t\tDecimal Integer to Binary conversion\n\n\n");printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,10);printf("<%c%c%c%c%c",196,196,196,196,196);printf(" read right to left");

getch();}

void binary(int n) {

while(n!=0) {

printf("%d",n%2);

n=n/2;

}

}

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

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

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

int s1,s2,s3,s;int area;clrscr();

printf("enter 3 sides of triangle: \n\n");scanf("%d%d%d",&s1,&s2,&s3);

s=s1+s2+s3/2;

area=func(s1,s2,s3,s);

Solution:

Solution:

Page 318: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

printf("\narea = %d",area);

getch();

}func(int i, int j, int k, int h) {

int ar,area;

ar=sqrt(h*((h-i)*(h-j)*(h-k)));

return (ar);

}

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

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

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

(k) Write a function to compute the greatest common divisor given by Euclid’s algorithm, exemplified for J = 1980, K = 1617 as follows:1980 / 1617 = 11980 – 1 * 1617 = 3631617 / 363 = 41617 – 4 * 363 = 165363 / 165 = 2363 – 2 * 165 = 335 / 33 = 5165 – 5 * 33 = 0Thus, the greatest common divisor is 33.

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

int a,b,r,d1,d2,temp;clrscr();

printf("Enter first number: ");scanf("%d",&a);

printf("\n\nEnter second number: ");scanf("%d",&b);

while(b!=0) {

r=a%b;

a=b;b=r;

Solution:

Solution:

Page 319: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Posted by Chetan Raikwar at 07:02

}

d1=a; /* devisor of first number */

temp=a;a=b;b=temp;

while(b!=0) {

r=a%b;a=b;b=r;

}

d2=a; /* devisor of second number */

printf("\n\n\nGreatest common devisor: ");

if(d1==d2) {

printf("%d",d1);

}

getch();

}______________________________________________________________________

Recommend this on Google

Comment as: Google Account

No comments:

Post a Comment

Page 320: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 5 (Functions & Pointers)

http://letuscalllessons.blogspot.com/2014/01/chapter-5-functions-pointers.html[07-Apr-14 8:53:09 PM]

Simple template. Powered by Blogger.

Page 321: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 6 (Data Types Revisited)

http://letuscalllessons.blogspot.com/2014/01/chapter-6-data-types-revisited.html[07-Apr-14 8:53:56 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 6 (Data Types Revisited)

Following program calculates the sum of digits of the number 12345. Go through it and find out why is it necessary to declare the storage class of the variable sum as static.main( ){int a ;a = sumdig ( 12345 ) ;printf ( "\n%d", a ) ;}sumdig ( int num ){static int sum ;int a, b ;a = num % 10 ;b = ( num - a ) / 10 ;sum = sum + a ;if ( b != 0 )sumdig ( b ) ;elsereturn ( sum ) ;}

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

void main() {

int a;

clrscr();

a=sumdig ( 12345 ) ;

printf("\n %d ",a) ;

getch();

Exercise [D]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 322: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 6 (Data Types Revisited)

http://letuscalllessons.blogspot.com/2014/01/chapter-6-data-types-revisited.html[07-Apr-14 8:53:56 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Posted by Chetan Raikwar at 07:03

}sumdig(int num){

static int sum;

/*

It is necessary to declare the storage class of sum as static because it is withina recursive funtion. It is necessary to keep the value of 'num' same for all releventrecursions of it. And to obtain running sum of all of them.

*/

int a,b;

a=num%10;b=(num-a)/10;sum=sum+a;

if(b!=0)sumdig(b);

elsereturn(sum);

}______________________________________________________________________

Recommend this on Google

Comment as: Google Account

No comments:

Post a Comment

Simple template. Powered by Blogger.

Page 323: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 7 (The C Pre-processor)

http://letuscalllessons.blogspot.com/2014/01/chapter-7-c-pre-processor.html[07-Apr-14 8:54:48 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

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

(a) Write down macro definitions for the following:1. To test whether a character entered is a small case letter or not.2. To test whether a character entered is a upper case letter or not.3. To test whether a character is an alphabet or not. Make use of the macros you defined in (1) and (2) above.4. To obtain the bigger of two numbers.

#include<stdio.h>#include<conio.h>#define UPPER(x) (x>=65 && x<=90)#define SMALL(y) (y>=97 && y<=123)#define ALPHABET(z) (z>=65 && z<=90 || z>=97 && z<=123)#define BIGGER(a,b) (a>b)

void main() {

int i,d1,d2;char ch,ch1;clrscr();

printf("\t enter your choice: \n");printf("\t===================\n\n");

printf("1: to test if character is small case letter or not\n\n");printf("2: to test if character is upper case letter or not\n\n");printf("3: to test if character is an alphabet or not\n\n");printf("4: to find bigger of two number\n\n\n");

printf("choice: ");scanf("%d",&i);

switch (i) {

case 1:

clrscr();

printf("enter any character\n\n");

scanf(" %c",&ch);

if SMALL(ch)printf("\n\n it is a small case letter.\n");

Exercise [C]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 324: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 7 (The C Pre-processor)

http://letuscalllessons.blogspot.com/2014/01/chapter-7-c-pre-processor.html[07-Apr-14 8:54:48 PM]

elseprintf("\n\nit is not a small case letter.\n");

break;

case 2:

clrscr();

printf("enter any character\n\n");

scanf(" %c",&ch);

if UPPER(ch)printf("\n\nit is an upper case letter.\n");elseprintf("\n\nit is not an upper case letter.\n");

break;

case 3:

clrscr();

printf("enter any character\n\n");

scanf(" %c",&ch);

if ALPHABET(ch)printf("\n\nit is an alphabet.\n");

elseprintf("\n\nit is not an alphabet.\n");

break;

case 4:

clrscr();

printf("enter two numbers\n\n");

scanf("%d%d",&d1,&d2);

if BIGGER(d1,d2)

printf("\n\n%d is bigger\n",d1);

elseprintf("\n\n%d is bigger \n",d2);

break;

default:

printf("\n\n\nwrong choice entered\n");

}

getch();}

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

(b) Write macro definitions with arguments for calculation of area and perimeter of a triangle, a square and a circle. Store these macro definitions in a file called “areaperi.h”. Include this file in your program,

Page 325: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 7 (The C Pre-processor)

http://letuscalllessons.blogspot.com/2014/01/chapter-7-c-pre-processor.html[07-Apr-14 8:54:48 PM]

and call the macro definitions for calculating area and perimeter for different squares, triangles and circles.

#define TP(a,b,c) (a+b+c) /* perimeter of triangle */#define TA(a,b,c,d) (d*((d-a)*(d-b)*(d-c))) /* area of triangle *#define PS(x) (4*x) /* perimeter of square */#define SA(x) (x*x) /* area of square */#define CP(x) (2*3.14*r) /* perimeter of circle */#define CA(x) (3.14*r*r) /* area of circle */

#include"areaperi.h" /* inclusion of custom header file */#include<stdio.h>#include<conio.h>#include<math.h>void main() {

float t1,t2,t3,hpt; /* sides of triangle,half of perimeter */float ss,r; /* side of square, radius of circle */int ch; float tp,ta,ta1,sp,sa,cp,ca; /* perimeter & area of triangle,square,circle */

clrscr();

printf("\tFind area and perimeter of: \n");printf(" *****************************\n\n");

printf("1: triangle\n\n");printf("2: square\n\n");printf("3: circle\n\n\n\n\n");

printf("enter your choice: ");scanf("%d",&ch);

switch(ch)

{

case 1:

/* triangle */

clrscr(); printf("enter side 1 of triangle: "); scanf("%f",&t1);

printf("\n\nenter side 2 of triangle: "); scanf("%f",&t2);

printf("\n\nenter side 3 of triangle: "); scanf("%f",&t3);

hpt=t1+t2+t3/2;

tp=TP(t1,t2,t3); ta=TA(t1,t2,t3,hpt);

ta1=sqrt(ta);

printf("\n\n\tperimeter of triangle = %f",tp); printf("\n\tarea of triangle = %f",ta1);

Note: write these macro definitions in a new file and save it as "areaperi.h", compile it and then you can include it during inclusion of libraries as - include"areaperi.h".

Solution:

Page 326: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 7 (The C Pre-processor)

http://letuscalllessons.blogspot.com/2014/01/chapter-7-c-pre-processor.html[07-Apr-14 8:54:48 PM]

break;

case 2:

/* square */

clrscr();

printf("\n\nenter side of a square: "); scanf("%f",&ss);

sp=PS(ss); sa=SA(ss);

printf("\n\n\tperimeter of square = %f",sp); printf("\n\tarea of square = %f",sa);

break;

case 3:

/* circle */

clrscr();

printf("\n\nenter radius of circle: "); scanf("%f",&r);

cp=CP(r); ca=CA(r);

printf("\n\n\tperimeter of circle = %f",cp); printf("\n\tarea of circle = %f",ca);

break;

default:

exit();}

getch();

}

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

(c) Write down macro definitions for the following:1. To find arithmetic mean of two numbers.2. To find absolute value of a number.3. To convert a uppercase alphabet to lowercase.4. To obtain the bigger of two numbers.

#include<stdio.h>#include<conio.h> #define AM(x,y) ((x+y)/2) #define ABS(x,y) (x<y) #define LOWER(x)(122-(90-x)) #define BIG(x,y) (x>y)

Solution:

Page 327: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 7 (The C Pre-processor)

http://letuscalllessons.blogspot.com/2014/01/chapter-7-c-pre-processor.html[07-Apr-14 8:54:48 PM]

void main() {

char ch,ch1; int choice,a,b,abs,c=0; float am;

clrscr();

printf("\tMacro Definitions to:\n"); printf(" ***************************\n\n");

printf("\n1: Find airthmetic mean of two numbers: \n\n"); printf("2: find absolute value of a number: \n\n"); printf("3: convert an uppercase character to lowercase: \n\n"); printf("4: obtain the bigger of two numbers: \n\n\n\n\n\n\n\n\n\n");

printf("enter your choice: "); scanf("%d",&choice);

switch(choice) {

case 1:

/* finding arithmetic mean of two numbers */

clrscr();

printf("\nenter two numbers:\n "); scanf("%d%d",&a,&b); am=AM(a,b); /* airthmetic mean */ printf("\nairthmetic mean = %f ",am); break;

case 2:

/* finding the absolute value of a number */

clrscr();

printf("\nenter a number: "); scanf("%d",&a);

if ABS(a,c)

abs=a*(-1);

else abs=a;

printf("\nabsolute value = %d",abs); break;

case 3:

/* converting an uppercase character to equivalent lowercase */

clrscr();

printf("\nenter an uppercase character: "); scanf(" %c",&ch);

ch1=LOWER(ch);

printf("\nequivalent lowercase character = %c",ch1); break;

case 4:

Page 328: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 7 (The C Pre-processor)

http://letuscalllessons.blogspot.com/2014/01/chapter-7-c-pre-processor.html[07-Apr-14 8:54:48 PM]

/* finding the bigger of two numbers */

clrscr();

printf("\nenter two numbers:\n "); scanf("%d%d",&a,&b);

if BIG(a,b) printf("\n\n%d is bigger.\n",a);

else printf("\n\n%d is bigger.\n",b);

break;

default:

exit(); }

getch();

}

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

(d) Write macro definitions with arguments for calculation of Simple Interest and Amount. Store these macro definitions in a file called “interest.h”. Include this file in your program, and use the macro definitions for calculating simple interest and amount.

#define INTEREST(x,y,z) (x*y*z/100)#define AMOUNT(x,y) (x+y)

#include<stdio.h>#include<conio.h> #include"interest.h" /* inclusion of custom header file */

void main() {

int p,r,t,a; float si;

clrscr();

printf("enter the principle: "); scanf("%d",&p);

printf("\n\nenter the rate: "); scanf("%d",&r);

printf("\n\nenter the time: "); scanf("%d",&t);

si=INTEREST(p,r,t);

Note: write these macro definitions in a new file and save it as

"interest.h", compile it and then you can include it during

inclusion of libraries as - include"interest.h".

Solution:

Page 329: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 7 (The C Pre-processor)

http://letuscalllessons.blogspot.com/2014/01/chapter-7-c-pre-processor.html[07-Apr-14 8:54:48 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Posted by Chetan Raikwar at 07:03

a=AMOUNT(p,si);

printf("\n\n\n\n\t\tsimple interest = %f\n\n\t\tamount = %d",si,a);

getch(); }

_______________________________________________________________________

Recommend this on Google

Comment as: Google Account

No comments:

Post a Comment

Simple template. Powered by Blogger.

Page 330: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 8 (Arrays)

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

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

void main() {

int i,arr[25],prsnt=0,num; clrscr();

printf("Please enter 25 numbers: \n");

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

printf("\n\nPlease enter the number to be searched: "); scanf("%d",&num);

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

if(num==arr[i]) prsnt=prsnt+1;

}

if(prsnt==0) { printf("\n\nNumber does not present in the array.\n"); }

else { printf("\n\nNumber presents in the array.\n"); printf("\nNumber of times it appears = %d.\n",prsnt); }

Exercise [D]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 331: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

getch();

}

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

b) 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.

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

void main() {

int i,arr[25],tz=0,tp=0,tn=0;clrscr();

printf("Enter numbers in the array: \n");

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

if(arr[i]<0){tn=tn+1;}

if(arr[i]==0){tz=tz+1;}

if(arr[i]>0){tp=tp+1;}

}

printf("\n\n\nTotal zeros = %d\n",tz);printf("Total positive numbers = %d\n",tp);printf("Total negative numbers = %d\n",tn);

getch();

}

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

(c) Implement the Selection Sort, Bubble Sort and Insertion sort algorithms on a set of 25 numbers. (Refer Figure 8.11 for the logic of the algorithms)− Selection sort− Bubble Sort− Insertion Sort

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

(d) Implement the following procedure to generate prime numbers from

Solution:

Solution:

Page 332: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

1 to 100 into a program. This procedure is called sieve of Eratosthenes.step 1Fill an array num[100] with numbers from 1 to 100step 2Starting with the second entry in the array, set all its multiples to zero.step 3Proceed to the next non-zero element and set all its multiples to zero.step 4Repeat step 3 till you have set up the multiples of all the non-zero elements to zerostep 5At the conclusion of step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers.

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

void main() {

int i,j,a[100];clrscr();

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

a[i]=i+1;

}

printf("\n100 numbers in the array:\n\n");

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

printf("%3d ",a[i]);

}

printf("\n\nafter implementing eratothene's sieve:\n\n");

for(i=2;i<100;i++) {

for(j=2;j<a[i];j++) {

if(a[i]%j==0)a[i]=0;}}

i=a[0];for(;i<100;i++) {

printf("%3d ",a[i]);

}

printf("\n\nprime numbers are: \n\n");

for(i=a[0];i<100;i++) {

if(a[i]!=0)

printf("%3d ",a[i]);

Solution:

Page 333: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

}

getch();}

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

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

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

int i,j,k,a1[5],a2[5]; clrscr();

for(i=1;i<=5;i++) { scanf("%d",&a1[i]); }

printf("\n\nThe elements you enterd are:\n");

for(i=1;i<=5;i++) { printf(" %d",a1[i]); }

printf("\n\nElements in reversed order:\n");

for(i=5,j=1;i>=1,j<=5;i--,j++) {

k=a1[i]; a2[j]=k;

printf(" %d",a2[j]); }

getch(); }

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

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

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

int arr[100];int n,i,f=0;clrscr();

printf("enter total elements of array(n): ");scanf("%d",&n);

printf("\n\nenter \"n\" elements of array: \n\n");

Exercise [I]

Solution:

Solution:

Page 334: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

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

scanf("%d",&arr[i]);

}

clrscr();

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

if(arr[i]==arr[n-(i+1)]) { /* if element is equal, according to the problem, it will be printed */f=f+1;

printf("element no: %d = %d ",i,arr[i]);}

}

if(f==0)printf("\n\nNo such element found.\n");

getch();

}

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

(c) Find the smallest number in an array using pointers.

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

int i,n,*p,*s,a[100]; clrscr();

printf("enter how many numbers you want to save in array: "); scanf("%d",&n);

printf("\n\nenter %d number in array:\n",n);

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

scanf("%d",&a[i]);

}

clrscr();

printf("array you entered: \n\n");

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

printf("%2d ",a[i]);

}

printf("\n\n");

p=&a[0]; /* first pointer points 0th element */

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

s=&a[i]; /* second pointer points every element one by one */

Solution:

Page 335: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

if(*p>*s) /* if first is bigger than second */ *p=*s; /* first becomes second */

s++; /* second is incremented to check with other elements */

}

printf("smallest digit in array is %d\n",*p);

getch(); }

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

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

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

int i,j,a[10]={1,2,3,4,5,6,7,8,9,10}; modify(); clrscr();

printf("array before modification: \n\n");

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

printf(" %d ",a[i]);

}

modify(a); /* passing only the name of array */

printf("\n\n\narray after modification:\n\n");

for(i=0;i<10;i++) { /* printing the array in main(); */

printf(" %d ",a[i]);

}

getch();

}

modify(int b[10]) {

int c;

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

b[c]=b[c]*3; /* multiplying each element with 3 */

} return b[c]; /* returning the whole array to main(); */

Solution:

Page 336: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

}

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

(e) The screen is divided into 25 rows and 80 columns. The characters that are displayed on the screen are stored in a special memory called VDU memory (not to be confused with ordinary memory). Each character displayed on the screen occupies two bytes in VDU memory. The first of these bytes contains the ASCII value of the character being displayed, whereas, the second byte contains the colour in which the character is displayed.For example, the ASCII value of the character present on zeroth row and zeroth column on the screen is stored at location number 0xB8000000. Therefore the colour of this character would be present at location number 0xB8000000 + 1. Similarly ASCII value of character in row 0, col 1 will be at location 0xB8000000 + 2, and its colour at 0xB8000000 + 3.With this knowledge write a program which when executed would keep converting every capital letter on the screen to small case letter and every small case letter to capital letter. The procedure should stop the moment the user hits a key from the keyboard.This is an activity of a rampant Virus called Dancing Dolls. (For monochrome adapter, use 0xB0000000 instead of 0xB8000000).

_______________________________________________________________________

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

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

/* initialization of a 3 dimensional array */

int threed[3][2][3]={ { {100,2,3}, {1,2,3} }, { {8,5,6}, {4,5,6} }, { {7,8,9}, {7,8,200} } };int *f,*l;clrscr();

f=&threed[0][0][0]; /* reference to first element */

Solution:

Exercise [L]

Solution:

Page 337: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

l=&threed[2][1][2]; /* reference to second element */

printf("\n\nfirst element = %d",*f);printf("\n\nlast element = %d",*l);

getch();

}

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

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

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

void main() {

int i,j,a[5][5];clrscr();

printf("\nType the numbers to in matrix:\n");

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

for(j=0;j<5;j++) {

scanf("%d",&a[i][j]);

} }

clrscr();

printf("matrix you entered is:\n\n");

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

for(j=0;j<5;j++) {

printf(" %2d ",a[i][j]);

}

printf("\n");

}

/* finding the largest number */

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

for(j=0;j<5;j++) {

if(a[0][0]<a[i][j]) /* if number is larger than first element */

a[0][0]=a[i][j]; /* larger number is placed as the first element */

}

}

Solution:

Page 338: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

printf("\n\nThe largest number in matrix is: %d",a[0][0]);

getch();

}

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

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

#include<stdio.h>#include<conio.h>#define MAX 4

void main() {

int i,j,a[4][4],b[4][4];clrscr();

printf("\nenter numbers in 5x5 matrix: \n\n");

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

for(j=0;j<MAX;j++) {

scanf("%d",&a[i][j]);

}

}

clrscr();

printf("\nmatrix you entered is: \n\n");

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

for(j=0;j<MAX;j++) {

printf("%2d ",a[i][j]);

}printf("\n");}

/* transpose of matrix */

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

for(j=0;j<MAX;j++) {

b[j][i]=a[i][j];

}}

printf("\n\n");

/* printing the transpose */

printf("Transpose of matrix is: \n\n");

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

Solution:

Page 339: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

for(j=0;j<MAX;j++) {

printf("%2d ",b[i][j]);

}printf("\n");}

getch();}

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

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

1 4 15 7 8 10 2 1114 3 6 1312 9 5

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( ) ) ;

Page 340: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

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

Solution:

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

/* returns scan code of the key that has been hit */getkey(){union REGS i,o;while(!kbhit() );i.h.ah=0;int86(22,&i,&o);return(o.h.ah);}

void main() {

int i,j,a[16]={1,4,15,7,8,10,2,11,14,3,6,13,12,9,5,0};int temp,h,moves=0,won=0;

clrscr();

/****************************************************/

do { /**************/ /* to move up */ /**************/

if(h==72) {

for(i=0;i<16;i++) {if(a[i]==0){if(a[0]==0 || a[1]==0 || a[2]==0 || a[3]==0) {break;}temp=a[i];a[i]=a[i-4];a[i-4]=temp;moves=moves+1;break;}} } /****************/ /* to move left */ /****************/

if(h==75) {

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

if(a[i]==0){if(a[0]==0 || a[4]==0 || a[8]==0 || a[12]==0) {break;}

Page 341: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

temp=a[i];a[i]=a[i-1];a[i-1]=temp;moves=moves+1;break;}} }

/****************/ /* to move down */ /****************/

if(h==80) {for(i=0;i<16;i++) {if(a[i]==0){if(a[12]==0 || a[13]==0 || a[14]==0 || a[15]==0) {break;}temp=a[i];a[i]=a[i+4];a[i+4]=temp;moves=moves+1;break;}} } /*****************/ /* to move right */ /*****************/

if(h==77) {

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

if(a[i]==0) {

if(a[3]==0 || a[7]==0 || a[11]==0 || a[15]==0 ) {break;}

temp=a[i];a[i]=a[i+1];a[i+1]=temp;moves=moves+1;break;} } }

/***********************************************************/

/**********************************/ /* printing the puzzle with boxes */ /**********************************/

printf("\n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n",218,196,196,196,194,196,196,196,194,196,196,196,194,196,196,196,191);for(i=0;i<=15;i++) {

printf("%c",179);

if(a[i]==0) {printf("%c ",32); /* printing a blank space in the puzzle */}if(a[i]!=0)

printf(" %2d",a[i]);

if(a[i]==a[3] || a[i]==a[7] || a[i]==a[11] || a[i]==a[15])printf("%c",179);

Page 342: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

if(i==3||i==7||i==11)printf("\n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n",195,196,196,196,197,196,196,196,197,196,196,196,197,196,196,196,180);

if(a[0]==1 && a[1]==2 && a[2]==3 && a[3]==4 && a[4]==5 && a[5]==6&&a[6]==7 && a[7]==8 && a[8]==9 && a[9]==10 && a[11]==12 && a[12]==13&& a[13]==14 && a[14]==15 && a[15]==0 ) {

won=1;}

}printf("\n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n",192,196,196,196,193,196,196,196,193,196,196,196,193,196,196,196,217);

/***************************************************/if(won==1) {printf("\n\n\tCongratulations! you have won.");break;} /**********************************/ /* to print instructions for user */ /**********************************/

printf("\n\n\n\n\n\n Total Moves: %d\t\t\t\t Use arrow keys to move blank:\n\n",moves);printf("\t\t\t\t\t\t %c to move up\n",30);printf("\t\t\t\t\t\t %c to move down\n",31);printf("\t\t\t\t\t\t %c to move left\n",17);printf("\t\t\t\t\t\t %c to move right\n",16);

/****************************************************/

/**********************/ /* to take user input */ /**********************/

h=getkey();clrscr();

/****************************************************/

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

getch();

}

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

(e) Those readers who are from an Engineering/Science background may try writing programs for following problems.(1) Write a program to add two 6 x 6 matrices.(2) Write a program to multiply any two 3 x 3 matrices.(3) Write a program to sort all the elements of a 4 x 4 matrix.(4) Write a program to obtain the determinant value of a 5 x 5 matrix.

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

(j) Write a program that interchanges the odd and even components of an array.

Solution:

Page 343: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

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

void main() {

int i,j,a[6],even,temp; clrscr();

printf("enter the numbers: \n\n");

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

scanf("%d",&a[i]);

}

clrscr();

printf("\narray without exchanging even and odd numbers:\n\n");

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

printf("%2d ",a[i]);

}

printf("\n\narray after exchanging even and odd numbers: \n\n");

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

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

/* if one element is even and another after that is odd \ ,they will be exchanged */

if((a[i]%2)!=0 && (a[j]%2)==0) {

temp=a[j]; a[j]=a[i]; a[i]=temp; } } }

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

printf("%2d ",a[i]);

}

getch(); }

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

(k) Write a program to find if a square matrix is symmetric.

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

void main() {

int i,j,r,c,sym;

Solution:

Solution:

Page 344: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

int a[100][100],b[100][100];

clrscr();

printf(" enter number of rows of matrix: ");scanf("%d",&r);

printf("\n\nenter number of columns of matrix: ");scanf("%d",&c);

clrscr();

printf("enter the elements in matrix: \n");

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

for(j=0;j<c;j++) {

scanf("%d",&a[i][j]);}

}

clrscr();

printf("\nmatrix you entered is\n\n");

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

for(j=0;j<c;j++) {

printf("%d ",a[i][j]);

}printf("\n");}

printf("\n\ntranspose of matrix is \n\n");

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

for(j=0;j<c;j++) {

b[j][i]=a[i][j];

}}

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

for(j=0;j<c;j++) {

printf("%d ",b[i][j]);

}printf("\n");}

/* finding if square matrix is equal to it's transpose to be symmetric */

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

for(j=0;j<c;j++) {

if(a[i][j]!=b[i][j])

sym=1;

}

Page 345: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

}

if(sym==1)printf("\nSquare matrix is not symmetric.\n");

elseprintf("\nSquare matrix is symmetric.\n");

getch();

}

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

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

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

void main() {

int i,j,r,c,a[100][100];int norm=0,sum=0;

clrscr();

printf("\nEnter the number of rows: ");scanf("%d",&r);

printf("\n\nEnter the number of coloumns: ");scanf("%d",&c);

clrscr();

printf("Enter elements of %d x %d array: \n\n",r,c);

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

for(j=0;j<c;j++) {

scanf("%d",&a[i][j]);

}}

clrscr();

printf("\nmatrix you entered is: \n\n");

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

for(j=0;j<c;j++) {

printf("%2d ",a[i][j]);

}printf("\n");}

/* norm of the matrix */

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

for(j=0;j<c;j++) {

Solution:

Page 346: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

sum=sum+(a[i][j]*a[i][j]);

}

}

norm=sqrt(sum);

printf("\nNorm of matrix = %d",norm);

getch();}

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

(m) Given an array p[5], write a function to shift it circularly left by two positions. Thus, if p[0] = 15, p[1]= 30, p[2] = 28, p[3]= 19 and p[4] = 61 then after the shift p[0] = 28, p[1] = 19, p[2] = 61, p[3] = 15 and p[4] = 30. Call this function for a (4 x 5 ) matrix and get its rows left shifted.

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

void main() {

int i,j,p[]={15,30,28,19,61}; int a[4][5];

clrscr();

printf("Array before shift:\n\n"); for(i=0;i<5;i++) {

printf("%2d ",p[i]);

}

func(p);

printf("\n\nArray after shift:\n\n");

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

printf("%2d ",p[i]);

}

printf("\n\n\nenter the elements of 4x5 matrix: \n\n");

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

for(j=0;j<5;j++) {

scanf("%d",&a[i][j]);

}

}

clrscr();

printf("matrix you enterd before shift: \n\n");

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

Solution:

Page 347: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

for(j=0;j<5;j++) {

printf("%2d ",a[i][j]);

}

printf("\n"); }

printf("\n\nafter shift:\n\n");

/* shift the rows of matrix */

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

func(a[i]);

}

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

for(j=0;j<5;j++) {

printf("%2d ",a[i][j]);

}

printf("\n");

}

getch();

}

func(int q[5]) {

int a,t1,t2,t3;

t1=q[0]; t2=q[1];

q[0]=q[2]; q[1]=q[3]; q[2]=q[4]; q[3]=t1; q[4]=t2;

return q[5];

}----------------------------------------------------------------------------------------------------------

(n) A 6 x 6 matrix is entered through the keyboard and stored in a 2-dimensional array mat[7][7]. Write a program to obtain the Determinant values of this matrix.

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

(o) For the following set of sample data, compute the standard deviation and the mean.-6, -12, 8, 13, 11, 6, 7, 2, -6, -9, -10, 11, 10, 9, 2

Solution:

Page 348: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

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

void main() {

int a[15]={-6,-12,8,13,11,6,7,2,-6,-9,-10,11,10,9,2}; int i,j; float temp,sd,sum=0,mean,x;

clrscr();

printf("\ndata set: \n\n");

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

printf(" %3d ",a[i]);

}

printf("\n");

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

sum=sum+a[i]; /* adding all the numbers */

}

mean=sum/15; /* calculating the mean */

/* computing standard deviation */

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

a[i]=pow((a[i]-mean),2); x=x+a[i]; }

temp=x/15; sd=sqrt(temp);

printf("\n\n\t\tmean= %f\n\t\tstandard deviation = %f\n",mean,sd);

getch(); }

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

(p) 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,Plot No. a b angle

137.4 80.9 0.78

Solution:

Page 349: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

155.2 92.62 0.89

149.3 97.93 1.35160.0 100.25 9.00

155.6 68.95 1.25

149.7 120.0 1.75

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

float a[6][3]={ {137.4, 80.9, 0.78}, {155.2, 92.62, 0.89}, {149.3, 97.93, 1.35}, {160.0, 100.25, 9.00}, {155.6, 68.95, 1.25}, {149.7, 120.0, 1.75} };

float big=0,area; int sr=0,i; clrscr();

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

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

if(area>big) { big=area; sr=i; }

}

printf("\n\nPlot no. %d is the biggest.\n",sr); printf("\nArea of plot no. %d = %f\n",sr,big);

getch();

}

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

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

x y34.22 102.4339.87 100.93

41.85 97.43

Solution:

Page 350: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

43.23 97.8140.06 98.3253.29 98.3253.29 100.0754.14 97.0849.12 91.5940.71 94.8555.15 94.65

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

void main() {

float a[][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,n=0; float x2,y2,x,y,x_y,n_x2,n_y2,r; clrscr();

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

x2= x2 + ( a[i][0] * a[i][0] ); /* computing square of x */

y2= y2 + ( a[i][1] * a[i][1] ); /* computing square of y */

x= x + a[i][0]; /* computing total of x */

y= y + a[i][1]; /* computing total of y */

x_y= x_y + ( a[i][0] * a[i][1] ); /* computing total of x * y */

n++;

}

n_x2= n * x2;

n_y2= n * y2;

r= ( x_y - x*y )/sqrt((n_x2-x2) * (n_y2-y2));

Solution:

Page 351: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

printf(" sum of square of x = %f\n\n",x2); printf(" sum of square of y = %f\n\n",y2); printf(" sum of x = %f\n\n",x); printf(" sum of y = %f\n\n",y); printf(" sum of x * y = %f\n\n",x_y); printf(" sum of n*x2 = %f\n\n",n_x2); printf(" sum of n*y2 = %f\n\n",n_y2);

printf("\n\n\nCorrelation cofficient = %f\n",r);

getch();

} -------------------------------------------------------------------------------------------------------------

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

x y 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

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

Solution:

Page 352: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

void main() {

float data[][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,n=0;float sx,sy,x2,y2,xy,a,b,Y;

clrscr();

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

sx = sx + data[i][0];

sy = sy + data[i][1];

x2= x2 + ( data[i][0] * data[i][0] );

y2= y2 + ( data[i][1] * data[i][1] );

xy = xy + ( data[i][0] * data[i][1] );

n++;

}

printf(" sum of x = %f\n",sx);printf(" sum of y = %f\n",sy);printf(" sum of x2 = %f\n",x2);printf(" sum of y2 = %f\n",y2);printf(" sum of x*y = %f\n",xy);printf(" total number = %d\n",n);

b = ( (n*xy) - (sx*sy) ) / ( n*x2 - (sx*sx) );

a = (sy/n) - b*(sx/n);

Y= a + b*sx ;

printf("\n\nvalue of a = %f\n\n",a);

printf("value of b = %f\n\n",b);

printf(" Y = %f \n\n",Y);

getch();

}

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

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

Page 353: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

Posted by Chetan Raikwar at 07:03

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

float a[10][2],sx,sy; int i;

clrscr();

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

printf("Enter coordinates of point number %d:\n\n",i+1);

printf("Value of X coordinate: "); scanf("%f",&a[i][0]);

printf("\nValue of Y coordinate: "); scanf("%f",&a[i][1]);

clrscr(); }

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

if(i>0 && i<10-1) {

sx = sx + a[i][0];

sy = sy = a[i][1];

} }

printf(" First coordinate: X = %f\tY = %f\n\n",a[0][0],a[0][1]);

printf(" Last coordinate: X = %f\tY = %f\n\n",a[9][0],a[9][1]);

printf("\nDistance between them: X = %f\tY = %f\n",sx,sy);

getch(); } ______________________________________________________________________

Solution:

Recommend this on Google

Comment as: Google Account

No comments:

Post a Comment

Page 354: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 8 (Arrays)

http://letuscalllessons.blogspot.com/2014/01/chapter-8-arrays.html[07-Apr-14 8:56:03 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Simple template. Powered by Blogger.

Page 355: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 9 (Puppeting on Strings)

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

#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.

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

void main() {

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

Exercise [D]

Solution:

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

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

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 356: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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.

#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();

}

Solution:

Page 357: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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

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

#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();}_______________________________________________________________________

(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:

Exercise [F]

Page 358: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

#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]) {

Solution:

Page 359: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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;

Page 360: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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.

#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");

Solution:

Page 361: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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.

#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;

Solution:

Page 362: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

/* 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.

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

void main() {

int x=49,y=9,i=1,lastday;int month,year,a;void box();

clrscr();

Solution:

Page 363: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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;

Page 364: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

/* 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);

Page 365: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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");

Page 366: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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)

Page 367: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

days=29;

elsedays=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

Page 368: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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<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) {

Solution:

Page 369: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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);

Page 370: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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);

}

elseprintf("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;

Page 371: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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);

Page 372: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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);

Page 373: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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;

elsedays=28;

}/* for march */

if(m==3)days=31;

Page 374: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

/* 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.

Page 375: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

(c) If the cost per item is also given write a program to calculate the total inventory values.

-------------------------------------------------------------------------------------------------------------

(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.

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.

#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(' ');}

elseputch(s[i]);i++;}

getch();}

---------------------------------------------------------------------------------------------------------------

Solution:

Solution:

Solution:

Page 376: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

(i) Write a program that will read a line and delete from it all occurrences of the word ‘the’.

#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];

Solution:

Page 377: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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.

#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");

Solution:

Page 378: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

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.

#include<stdio.h>#include<conio.h>void main() {

char a[10000],i=0,suc=0;clrscr();

Solution:

Page 379: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan ): Let Us C / Chapter 9 (Puppeting on Strings)

http://letuscalllessons.blogspot.com/2014/01/chapter-9-puppeting-on-strings.html[07-Apr-14 8:57:15 PM]

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Posted by Chetan Raikwar at 07:03

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();}

______________________________________________________________________

Recommend this on Google

Comment as: Google Account

No comments:

Post a Comment

Simple template. Powered by Blogger.

Page 380: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 14 (Operations on Bits)

(a) The information about colors is to be stored in bits of a char variable called color. The bit number 0 to 6, each represent 7 colors of a rainbow, i.e. bit 0 represents violet, 1 representsindigo, and so on. Write a program that asks the user to enter a number and based on this number it reports which colors in the rainbow does the number represents.

#include<stdio.h> #include<conio.h> void main() {

char color; int num;

clrscr();

printf("Please enter the number(0-6): "); scanf("%d",&num);

color=1<<num;

printf("\n\n");

if(num==0 && color==1) printf("Violet");

else if(num==1 && color==2) printf("Indigo");

else if(num==2 && color==4) printf("Blue");

else if(num==3 && color==8) printf("Green");

else if(num==4 && color==16) printf("Yellow");

else if(num==5 && color==32) printf("Orange");

else if(num==6 && color==64)

Exercise [A]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 381: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

printf("Red");

else printf("Wrong color number!");

getch();

}

----------------------------------------------------------------------------------------------------------------

(b) A company planning to launch a new newspaper in market conducts a survey. The various parameters considered in the survey were, the economic status (upper, middle, and lower class) the languages readers prefer (English, Hindi, Regional language) and category of paper (daily, supplement, tabloid). Write a program, which reads data of 10 respondents through keyboard, and stores the information in an array of integers. The bit-wise information to be stored in an integer is given below:Bit Number Information0 Upper class1 Middle class2 Lower class3 English4 Hindi5 Regional Language6 Daily7 Supplement8 TabloidAt the end give the statistical data for number of persons who read English daily, number of upper class people who read tabloid and number of regional language readers.

#include<stdio.h> #include<conio.h> void main() {

int arr[10][3],i,j; unsigned int infr; int eng=0,utab=0,rgl=0;

for(i=0;i<10;i++) {

clrscr();

gotoxy(20,2); printf("Enter data of respondent %d:\n\n",i+1);

for(j=0;j<3;j++) {

if(j==0){ printf("Economic Status:\n\n"); printf("0: Upper class\t1: Middle class\t2: Lower class\n\n");

scanf("%d",&arr[i][j]); }

if(j==1){ printf("\n\nLanguage Preferred:\n\n"); printf("3: English\t4: Hindi\t5:Regional Language\n\n");

Solution:

Page 382: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

scanf("%d",&arr[i][j]); }

if(j==2){

printf("\n\nType of Paper:\n\n"); printf("6: Daily\t7: Supplement\t8: Tabloid\n\n");

scanf("%d",&arr[i][j]); }

} }

/***********************************************/ /* converting the whole array using left shift */ /***********************************************/

for(i=0;i<10;i++) {

for(j=0;j<3;j++) {

arr[i][j]= 1 << arr[i][j]; /* conversion */

} }

for(i=0;i<10;i++) {

if(arr[i][1]==8) /* english readers */ eng++;

if(arr[i][0]==1 && arr[i][2]==256) /* upper class,tabloid readers */ utab++;

if(arr[i][1]==32) /* regional language readers */ rgl++; }

clrscr();

gotoxy(20,2); printf("Reader's statistics:\n\n\n\n"); printf("\tEnglish Reader: %d\n",eng); printf("\tUpper class Tabloid Readers: %d\n",utab); printf("\tRegional Language readers: %d\n",rgl); getch();

}

----------------------------------------------------------------------------------------------------------------

(c) In an inter-college competition, various sports and games are played between different colleges like cricket, basketball, football, hockey, lawn tennis, table tennis, carom and chess. The information regarding the games won by a particular college is stored in bit numbers 0, 1, 2, 3, 4, 5, 6, 7 and 8 respectively of an integer variable called game. The college that wins in 5 or more than 5 games is awarded the Champion of Champions trophy. If a number is entered through the keyboard, then write a program to find out whether the college won the Champion of the Champions trophy or not, along with the names of the games won by the college.

Page 383: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

#include<stdio.h> #include<conio.h> void main() {

int game; int i,won=0,name;

clrscr();

printf("Enter number: ");

scanf("%d",&name);

printf("\n\n");

for(i=1;i<=8;i++) {

game=i&name;

if(game==1) { printf("Cricket\n");

won++; }

if(game==2) { printf("Basketball\n");

won++; }

if(game==3) { printf("Football\n");

won++; }

if(game==4) { printf("Hockey\n");

won++; }

if(game==5) { printf("Lawn-tennis\n");

won++; }

if(game==6) { printf("Table-tennis\n");

won++; }

if(game==7) { printf("Carrom\n");

won++; }

if(game==8) { printf("Chess\n");

won++;

Solution:

Page 384: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

}

}

if(won>=5) {

printf("\n\n\nCollege %d has won the champions trophy\n",name);

}

else {

printf("\n\n\nCollege %d didn't win the champions trophy\n",name);

}

getch(); }

-----------------------------------------------------------------------------------------------------------------

(d) An animal could be either a canine (dog, wolf, fox, etc.), a feline (cat, lynx, jaguar, etc.), a cetacean (whale, narwhal, etc.) or a marsupial (koala, wombat, etc.). The information whether a particular animal is canine, feline, cetacean, or marsupial is stored in bit number 0, 1, 2 and 3 respectively of a integer variable called type. Bit number 4 of the variable type stores the information about whether the animal is Carnivore or Herbivore.For the following animal, complete the program to determine whether the animal is a herbivore or a carnivore. Also determine whether the animal is a canine, feline, cetacean or a marsupial.struct animal{char name[30] ;int type ;}struct animal a = { "OCELOT", 18 } ;

#include<stdio.h> #include<conio.h> void main() {

struct animal { char name[30]; int type; };

struct animal a={"OCELOT",18};

int t1,t2,typ1,typ2;

clrscr();

t1= a.type >> 3;

typ1= t1 & 2; /* checking the bit after shifting */

t2= t1 << 3;

typ2= t2 & 16; /* checking another bit after shifting */

Solution:

Page 385: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

/**********************************************************/ /* checking if ocelot is canine/feline/cetacean/marsupial */ /**********************************************************/

if(typ1==1) printf("\n\nOCELOT is Canine\n");

if(typ1==2) printf("\n\nOCELOT is Feline\n");

if(typ1==4) printf("\n\nOCELOT is Cetacean\n");

if(typ1==8) printf("\n\nOCELOT is Marsupial\n");

/************************************************/ /* checking if ocelot is carnivore or herbivore */ /************************************************/

if(typ2!=0) printf("\n\nOCELOT is Carnivore\n");

if(typ2==0) printf("\n\nOCELOT is Herbivore\n");

getch();

}

-----------------------------------------------------------------------------------------------------------------

(e)The time field in the directory entry is 2 bytes long. Distribution of different bits which account for hours, minutes and seconds is given below. Write a function which would receive the two-byte time entry and return to the calling function, the hours, minutes and seconds. 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 H H H H H M M M M M M S S S S S

#include<stdio.h> #include<conio.h> void main() {

unsigned hr,mn,sc,input;

void timer();

clrscr();

printf("Enter the time entry: ");

scanf("%d",&input);

timer(input,&hr,&mn,&sc);

printf("\n\nTIME: %u : %u : %u\n",*(&hr),*(&mn),*(&sc));

getch();

Solution:

Page 386: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

}

void timer(unsigned time, unsigned *hr, unsigned *mn, unsigned *sc) {

*hr=time >> 11;

*mn=(time<<5) >> 10;

*sc=(time<<11) >> 11;

}

-----------------------------------------------------------------------------------------------------------------

(f) In order to save disk space information about student is stored in an integer variable. If bit number 0 is on then it indicates Ist year student, bit number 1 to 3 stores IInd year, IIIrd year and IVth year student respectively. The bit number 4 to 7 stores stream Mechanical, Chemical, Electronics and IT. Rest of the bits store room number. Based on the given data, write a program that asks for the room number and displays the information about the student, if its data exists in the array. The contents of array are,int data[ ] = { 273, 548, 786, 1096 } ;

#include<stdio.h> #include<conio.h>

void main() {

unsigned int yr,br,data_yr,data_br; int i,j,k,rn,a,b,flag=0; int data[]={ 273,548,786,1096};

clrscr();

printf("Enter room number: "); scanf("%d",&rn);

printf("\n\n\n Year: ");

/*********************/ /* checking for year */ /*********************/

for(i=1;i<=8;i=i*2) {

yr= rn & i;

if(yr==1) { printf("First year"); break; }

if(yr==2) { printf("Second year"); break; }

if(yr==4) { printf("Third year");

Solution:

Page 387: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

break; }

if(yr==8) { printf("Fourth year"); break; }

}

/***********************/ /* Checking for branch */ /***********************/

printf("\n\nBranch: ");

for(i=16;i<=128;i=i*2) {

br= rn & i;

if(br==16) { printf("Mechanical"); break; }

if(br==32) { printf("Chemical"); break; }

if(br==64) { printf("Electronics"); break; }

if(br==128) { printf("I.T."); break; }

}

/***********************************************/ /* checking if data matches with that of array */ /***********************************************/

for(i=1,j=16;i<=8,j<=128;i=i*2,j=j*2) {

yr=rn&i;

br=rn&j;

for(k=0,a=1,b=16;k<4,a<=8,b<=128;k++,a=a*2,b=b*2) {

data_yr=data[k] & a;

data_br=data[k] & b;

if(yr==data_yr && br==data_br) {

flag+=1;

break;

}

}

Page 388: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

Posted by Chetan Raikwar at 07:05 No comments:

}

if(flag==0) printf("\n\n\ndata doesn't matche with the array.\n");

else printf("\n\n\ndata matches with the array.\n");

getch(); }______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 13 (More Issues in Input Output)

(a) Write a program to carry out the following:(a) Read a text file provided at command prompt(b) Print each word in reverse orderFor example if the file containsINDIA IS MY COUNTRYOutput should beAIDNI SI YM YRTNUOC

#include"stdio.h"<+>#include<conio.h>#include<string.h>

void main(int argc, char *argv[]) {

FILE *fs;char ch,s[80];void rev();

if(argc!=2) {

printf("File name not supplied\n");

exit();

}

fs=fopen(argv[1],"r");

if(fs==NULL) {

printf("File not found!");

exit();}

while(fgets(s,79,fs)!=NULL)rev(s);

fclose(fs);

Exercise [B]

Solution:

Page 389: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

}

void rev(char s1[80]) {

char s2[80];int i=0,j=0;

while(s1[i]!='\0') {

s2[j]=s1[i];

if(s1[i]==' ' || s1[i]=='\0') {

s2[j]='\0';

strrev(s2);

printf("%s ",s2);

j=-1;

}

i++;j++;}

s2[j]='\0';

printf("%s",strrev(s2));

}

-----------------------------------------------------------------------------------------------------------------

(b) Write a program using command line arguments to search for a word in a file and replace it with the specified word. The usage of the program is shown below.C> change <old word> <new word> <filename>

#include<stdio.h>#include<conio.h>#include<string.h>

void replace();

void main ( int argc, char *argv[] ) {

FILE *fp,*ft;char str[80],str1[30],str2[30],nwstr[100];

clrscr();

if(argc!=4) {

puts("Improper argements passed!");exit();}

strcpy(str1,argv[1]);strcpy(str2,argv[2]);

fp=fopen(argv[3],"r");

if(fp==NULL) {

Solution:

Page 390: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

puts("cannot open source file!");exit();}

ft=fopen("NEW.TXT","w+");

if(ft==NULL) {

puts("cannot open target file!");exit();}

while(fgets(str,79,fp)!=NULL) {

replace(str,str1,str2,&nwstr);

fputs(nwstr,ft);}

fclose(fp);fclose(ft);

remove("FILE.TXT");rename("NEW.TXT","FILE.TXT");

printf("\n\nTask completed!\n\n");

getch();

}

void replace(char *s, char s1[80], char s2[80], char *n) {

int i=0,j=0,k=0;char temp[100],temp2[100],main[100],*t=temp,*m=main;

/*******************************//* 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]==' ' || temp[i]==',' || temp[i]=='.') {

temp2[j]='\0';

if(strcmpi(temp2,s1)==0) {

strcpy(temp2,s2);

}

Page 391: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

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 */

/******************************************************************//* preparing new string to return to main and printing it on file *//******************************************************************/

while(*m!='\0') {

*n=*m;

n++;m++;}

*n='\0';

}

----------------------------------------------------------------------------------------------------------------

(c) Write a program that can be used at command prompt as a calculating utility. The usage of the program is shown below.C> calc <switch> <n> <m>

Page 392: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

Where, n and m are two integer operands. switch can be any one of the arithmetic or comparison operators. If arithmetic operator is supplied, the output should be the result of the operation. If comparison operator is supplied then the output should be True or False.

#include<stdio.h>#include<conio.h>#include<string.h>

void main(int argc, char *argv[]) {

int n,m,calc;

clrscr();

if(argc!=4)printf("Improper number of arguments");

/* converting both operands to integers */

n=atoi(argv[2]);

m=atoi(argv[3]);

printf("\n\nOutput: ");

/* comparing the operators passed at command prompt */

if(strcmp("+",argv[1])==0) {

printf("%d\n\n",n+m);

}

if(strcmp("-",argv[1])==0) {

printf("%d\n\n",n-m);

}

if(strcmp("*",argv[1])==0) {

printf("%d\n\n",n*m);

}

if(strcmp("/",argv[1])==0) {

printf("%d\n\n",n/m);

}

if(strcmp("%",argv[1])==0) {

printf("%d\n\n",n%m);

} /* IMPORTANT */

Solution:

Page 393: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

Posted by Chetan Raikwar at 07:05 No comments:

/* I have used dedicated variable for '<' and '>' comparison operators *//* because at command prompt, these are redirecting operators and cannot *//* be used simply for comparison. */

/* 1: "<" = "less" */ /* 2: ">" = "greater" */ /* type "less" for "<" and "greater" for ">" respectively if you want to perform comparison */

if(strcmp("greater",argv[1])==0) {

if(n>m)printf("True\n\n");

if(n<m)printf("False\n\n");

}

if(strcmp("less",argv[1])==0) {

if(n<m)printf("True\n\n");

if(n>m)printf("False\n\n");

}

if(strcmp("=",argv[1])==0) {

if(n==m)printf("True\n\n");

elseprintf("False\n\n");

}

}

_______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 11 (Console Input Output)

(a) Write down two functions xgets( ) and xputs( ) which work similar to the standard library functions gets( ) and puts( ).

#include<stdio.h>#include<conio.h>

Exercise [D]

Solution:

Page 394: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

void xgets();void xputs();

void main() {

char str[80];clrscr();

xgets(str);

printf("\n");

xputs(str);

getch();

}

void xgets( char *s) {

int i=0;char ch;

for(i=0;i<=79;i++) {

ch=getche();

if(ch=='\r') {

*s='\0';break;}

if(ch=='\b') {

printf("\b");

i-=2;s-=2;}

else {

*s=ch;s++;

}

}

}

void xputs( char *s) {

while(*s!='\0') {

putch(*s);

s++;

}

}

---------------------------------------------------------------------------------------------------------------

(b) Write down a function getint( ), which would receive a numeric string from the keyboard, convert it to an integer number and return

Page 395: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

Posted by Chetan Raikwar at 07:04 No comments:

the integer to the calling function. A sample usage of getint( ) is shown below:main( ){int a ;a = getint( ) ;printf ( "you entered %d", a )}

#include<stdio.h>#include<conio.h> void main() {

int a; char s[80];

printf("Enter any numeric string: "); gets(s);

a=getint(s); /* converting and receiving string as integer */

printf("\n\nYou entered = %d\n",a);

getch();

}

int getint(char s1[80]) {

int digit;

digit=atoi(s1); /* converting string to integer */

return digit;

}

______________________________________________________________________

Solution:

Recommend this on Google

Let Us C / Chapter 10 (Structures)

(a) Create a structure to specify data on students given below:Roll number, Name, Department, Course, Year of joiningAssume 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.

/* NOTE: since number of students to be assumed is too much ( about 450 )I have alloted full size (about 450) to it but array has been kept empty,

Exercise [D]

Solution:

Page 396: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

if you have time then you can fill up all 450 names and can search throughthem.program has been tested by me and it works accurately. you can reducethe size of array of structure conveniently by changing the value of N */

#include<stdio.h>#include<conio.h>#define N 450

struct students { int rlnm; char name[25]; char dept[25]; /* structure defined outside of main(); */ char course[25]; int year; };

void main() { /* main() */

struct students s[N];int i,ch;

clrscr();

/* taking input of 450 students in an array of structure */

for(i=0;i<N;i++) {

printf(" Enter data of student %d\t\t\t\ttotal students: %d\n",i+1,N);printf("****************************\n\n");

printf("enter rollnumber: ");scanf("%d",&s[i].rlnm);

printf("\n\nenter name: ");scanf(" %s",&s[i].name);

printf("\n\nenter department: ");scanf("%s",&s[i].dept);

printf("\n\nenter course: ");scanf("%s",&s[i].course);

printf("\n\nenter year of joining: ");scanf("%d",&s[i].year);

clrscr();

}

/* displaying a menu */

printf("\n\tenter your choice: \n");printf("\t**********************\n\n");

printf("1: enter year to search all students who took admission in that:\n\n");printf("2: enter roll number to see details of that student\n\n\n");

printf("your choice: "); /* taking input of your choice */scanf("%d",&ch);

clrscr();

switch(ch) {

case 1: clrscr();

dispyr(&s); /* function call to display names of students who joined in\ a particular year */

Page 397: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

break;

case 2: clrscr();

disprl(&s); /* function call to display information of a student \ whose roll number is given */

break;

default:

printf("\n\nerror! wrong choice");

}

getch();

}/******************* main() ends **************/

dispyr(struct students *a) { /* function for displaying names of students\ who took admission in a particular year */

int j,yr;

printf("\nenter year: ");scanf("%d",&yr);

printf("\n\nthese students joined in %d\n\n",yr);

for(j=0;j<N;j++) {

if(a[j].year==yr) {

printf("\n%s\n",a[j].name);}

}return 0;}

disprl(struct students *a) { /* function to print information of a\ student whose roll number has been \ given. */

int k,rl;

printf("\nenter roll number: ");scanf("%d",&rl);

for(k=0;k<N;k++) {

if(a[k].rlnm==rl) {

printf("\n\n\t Details of roll number: %d\n",a[k].rlnm);printf("\t***************************\n\n");printf(" Name: %s\n",a[k].name);printf(" Department: %s\n",a[k].dept);printf(" Course: %s\n",a[k].course);printf("Year of joining: %d",a[k].year);

break;}

else {printf("\nRoll number you entered does not exist\n\n");

break;}

Page 398: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

}

return 0;}

--------------------------------------------------------------------------------------------------------------

(b) 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”.

/* NOTE: since number of customers to be assumed is too much ( about 200 ) I have alloted full size (about 200) to it but array has been kept empty, if you have time then you can fill up all 200 names and can search through them.program has been tested by me and it works accurately. you can reducethe size of array of structure conveniently by changing the value of N */

#include<stdio.h> #include<conio.h> #define N 200

struct bank { int acn; char name[20]; int bal; /* defined out of main() */ };

void main() {

struct bank b[N];

int i,ch,lw=100,ch2,ac,am;

clrscr();

for(i=0;i<N;i++) { /* inputting customer data */

printf("\tEnter information of customers \n"); printf("\t******************************\n\n");

printf("enter account no.: "); scanf("%d",&b[i].acn);

printf("\n\nenter customer name: "); scanf("%s",&b[i].name);

printf("\n\nenter balance: "); scanf("%d",&b[i].bal);

clrscr();

}

Solution:

Page 399: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

clrscr();

printf("\tEnter your choice\n"); /* further processing of transaction */ printf("\t*****************\n\n");

printf("1: to know whose balance is below 100.\n\n"); printf("2: to process request or withdrawl.\n\n\n");

scanf("%d",&ch);

switch(ch) {

case 1:

clrscr();

disp(&b); /* displaying whose balance is below 100 */

break;

case 2:

clrscr();

printf("enter your account number: "); scanf("%d",&ac);

for(i=0;i<N;i++) {

if((b[i].acn)==ac) {

clrscr();

printf("\tHello %s\n",b[i].name); printf("\n\n");

printf("\n\nenter your choice\n"); printf("\n1: deposite:\n"); printf("\n0: withdrawl:\n\n"); scanf("%d",&ch2);

switch(ch2) {

case 0:

clrscr();

if(b[i].bal<lw) {

printf("\n\nsorry! account balance is too low for withdrawl.\n");

break; }

else {

printf("\n\nenter amount for withdrawl: "); scanf("%d",&am);

}

if(b[i].bal<am) {

printf("\n\nyou don't have enough balance for withdrawl.\n");

Page 400: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

}

else {

b[i].bal=b[i].bal+am;

printf("\n\nwithdrawl was successful.\n");

} break;

case 1:

clrscr();

printf("\n\nenter amount to deposite: "); scanf("%d",&am);

b[i].bal=b[i].bal+am;

printf("\n\ncash deposited successfully.\n\n");

break;

}

} } } getch(); }

disp(struct bank *a) {

int k;

printf("\tCustomers whose balance is below 100:\n"); printf("\t*************************************\n\n");

for(k=0;k<N;k++) {

if((a[k].bal)<100) {

printf("%2d\t%s\n",a[k].acn,a[k].name);

} } return 0;

}

-----------------------------------------------------------------------------------------------------------------

(c) 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.

#include<stdio.h> #include<conio.h>

Solution:

Page 401: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

struct automob { char name[5]; int year; char mtr[10]; int qty; }; void main() {

struct automob a[54]={{"AA1",2009,"AAA",10}, {"AA2",2009,"AAA",10}, {"AA3",2009,"AAA",10}, {"AA4",2009,"AAA",10}, {"AA5",2009,"AAA",10}, {"AA6",2009,"AAA",10}, {"AA7",2009,"AAA",10}, {"AA8",2009,"AAA",10}, {"AA9",2009,"AAA",10}, {"BB1",2010,"BBB",11}, {"BB2",2010,"BBB",11}, {"BB3",2010,"BBB",11}, {"BB4",2010,"BBB",11}, {"BB5",2010,"BBB",11}, {"BB6",2010,"BBB",11}, {"BB7",2010,"BBB",11}, {"BB8",2010,"BBB",11}, {"BB9",2010,"BBB",11}, {"CC1",2011,"CCC",12}, {"CC2",2011,"CCC",12}, {"CC3",2011,"CCC",12}, {"CC4",2011,"CCC",12}, {"CC5",2011,"CCC",12}, {"CC6",2011,"CCC",12}, {"CC7",2011,"CCC",12}, {"CC8",2011,"CCC",12}, {"CC9",2011,"CCC",12}, {"DD1",2012,"DDD",13}, {"DD2",2012,"DDD",13}, {"DD3",2012,"DDD",13}, {"DD4",2012,"DDD",13}, {"DD5",2012,"DDD",13}, {"DD6",2012,"DDD",13}, {"DD7",2012,"DDD",13}, {"DD8",2012,"DDD",13}, {"DD9",2012,"DDD",13}, {"EE1",2013,"EEE",14}, {"EE2",2013,"EEE",14}, {"EE3",2013,"EEE",14}, {"EE4",2013,"EEE",14}, {"EE5",2013,"EEE",14}, {"EE6",2013,"EEE",14}, {"EE7",2013,"EEE",14}, {"EE8",2013,"EEE",14}, {"EE9",2013,"EEE",14}, {"FF1",2014,"FFF",15}, {"FF2",2014,"FFF",15}, {"FF3",2014,"FFF",15}, {"FF4",2014,"FFF",15}, {"FF5",2014,"FFF",15}, {"FF6",2014,"FFF",15}, {"FF7",2014,"FFF",15}, {"FF8",2014,"FFF",15}, {"FF9",2014,"FFF",15}};

int i,j,k;

clrscr();

Page 402: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

printf("Information of parts between BB1 to CC6:\n\n");

printf("\n\nName\t\tyear(manu.)\t\tmaterial\tquantity\n\n\n");

for(i=0;i<54;i++) {

if(i>=9 && i<=23) { printf("%3s\t\t%4d\t\t\t%5s\t\t%4d\n",a[i].name,a[i].year,a[i].mtr,a[i].qty);

} }

getch(); }

-----------------------------------------------------------------------------------------------------------------

(d) 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.

#include<stdio.h> #include<conio.h> #include<string.h>

void main() {

struct cricketer { char name[50]; int age; int match; float avrn; }; struct cricketer c[20],temp; int i,j; clrscr();

for(i=0;i<20;i++) {

printf("Enter data of cricketer %d\n\n\n",i+1);

fflush(stdin); printf("Name: "); gets(c[i].name);

printf("\n\nAge: "); scanf("%d",&c[i].age);

printf("\n\nMatches: "); scanf("%d",&c[i].match);

printf("\n\nAverage runs: "); scanf("%f",&c[i].avrn);

clrscr();

Solution:

Page 403: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

}

/*******************/ /* sorting records */ /*******************/

for(i=0;i<20;i++) {

for(j=i+1;j<20;j++) {

if(c[i].avrn > c[j].avrn) {

temp=c[i]; c[i]=c[j]; c[j]=temp; } } }

printf("Sorted records:\n\n");

for(i=0;i<20;i++) {

printf("%d\t%s\t%d\t%d\t%f\n\n\n",i+1,c[i].name,c[i].age,c[i].match,c[i].avrn);

}

getch(); }

linkfloat() {

float a=0,*b;

b=&a; a=*b;

return 0; }

-----------------------------------------------------------------------------------------------------------------

(e) 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.

#include<stdio.h>#include<conio.h>#define N 3void main() {

struct employee { int code; char name[20]; int dd,mm,yy; } e[N];

int d,m,y,i;clrscr();

for(i=0;i<N;i++) {

printf("\tEnter employee data:\n");

Solution:

Page 404: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

printf("\t*********************\n");

printf("\nEnter employee code: ");scanf("%d",&e[i].code);

printf("\n\nEnter employee name: ");scanf("%s",&e[i].name);

printf("\n\nEnter date of joining (dd mm yy): ");scanf("%d%d%d",&e[i].dd,&e[i].mm,&e[i].yy);

clrscr();

}

clrscr();

printf("\nenter current date(dd mm yy): \n\n");scanf("%d%d%d",&d,&m,&y);

clrscr();

for(i=0;i<N;i++) {

if((y-(e[i].yy))>=3) {

printf("%s\n\N",e[i].name);

}

}

getch();}

-----------------------------------------------------------------------------------------------------------------

(f) Write a menu driven program that depicts the working of a library. The menu options should be:1. Add book information2. Display book information3. List all books of given author4. List the title of specified book5. List the count of books in the library6. List the books in the order of accession number7. ExitCreate 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.

#include<stdio.h> #include<conio.h> #include<dos.h>

void main() {

struct library { int acn;

Solution:

Page 405: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

char title[25]; char auth[25]; float price; int flag; };

struct library a[5]={ {2,"AAA","AAA",154.8,1}, {1,"BBB","BBB",124.6,0}, {5,"EEE","EEE",234.3,0}, {3,"CCC","CCC",232.3,1}, {4,"DDD","DDD",121.3,0} };

struct library temp; /* temporary structure to overwrite information / and for assistance in sorting the whole structure */

int i,ch,k,flag,j=0; char author[10];

clrscr();

while(1) { /* initialized an indefinite loop */

clrscr(); printf("\t1: Add book information\n"); printf("\t2: Display book information\n"); printf("\t3: List all books of given author\n"); printf("\t4: List the title of specified book\n"); printf("\t5: List the count of books in the library\n"); printf("\t6: List the books in order of accesion number\n"); printf("\t7: Exit\n\n\n");

printf("Choice: "); scanf("%d",&ch);

switch(ch) {

case 1: /* adding book information over current information */

clrscr();

printf("\t\t1: Add book information:\n\n\n");

printf("enter book information:\n\n");

printf("Accesion number of book to be modified: "); scanf("%d",&j); fflush(stdin);

for(i=0;i<5;i++) {

if(j==a[i].acn) {

printf("\n\nenter new information:\n\n"); printf("accesion no.: "); scanf("%d",&temp.acn); fflush(stdin); printf("\n\ntitle: "); scanf("%s",&temp.title); fflush(stdin); printf("\n\nauthor: "); scanf("%s",&temp.auth); fflush(stdin); printf("\n\nprice: "); scanf("%f",&temp.auth); fflush(stdin); printf("\n\nflag(1/0): "); scanf("%d",&temp.flag); fflush(stdin);

} }

Page 406: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

a[j]=temp; /* overwriting current information with new one */

clrscr();

printf("\n\nInformation added succesfully!\n\n");

delay(2000);

break;

case 2: /* displaying current book information */

clrscr();

printf("\t\t2: Display book information:\n\n\n");

printf("Enter accesion number: "); scanf("%d",&k);

for(i=0;i<5;i++) {

if(k==a[i].acn) { clrscr(); printf("Book information: \n\n"); printf("\n\nAccesion Number: %d",a[i].acn); printf("\nTitle: %s",a[i].title); printf("\nAuthor: %s",a[i].auth); printf("\nPrice: %f",a[i].price);

if(a[i].flag==0) { printf("\nFlag: Not issued\n\n"); } else{ printf("\nFlag: Issued\n\n"); } } } delay(1000);

break;

case 3: /* listing all books of given author */

clrscr();

printf("\t\t3: List all books of given author:\n\n\n");

printf("Enter author name: "); scanf("%s",&author); fflush(stdin);

printf("\n\nbooks of %s\n\n",author); for(i=0;i<5;i++) {

k=strcmp(author,a[i].auth);

if(k==0) { j=j+1; printf("%d.\t%s\n",j,a[i].title);

} } delay(2000); break;

case 4: /* displaying title of given book */

Page 407: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

clrscr(); printf("\t\t4: Title of the specified book:\n\n\n");

printf("Enter the accesion number: "); scanf("%d",&k);

printf("\n\n");

for(i=0;i<5;i++) {

if(k==a[i].acn) {

printf("Title: %s\n",a[i].title);

} } delay(2000); break;

case 5: /* counting total books in library */

clrscr(); printf("\t\t5: List the count of books in the library: \n\n\n");

for(i=0;i<5;i++) { j=j+1; } printf("\tTotal books: %2d",j);

delay(2000); break;

case 6: /* sorting the books by their accesion numbers */

clrscr(); printf("6: List the books in order of accesion number: \n\n\n");

for(i=0;i<5;i++) {

for(j=i+1;j<4;j++) {

if(a[i].acn>a[j].acn) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } }

printf("Access no.\tTitle\tAuthor\tFlag\n\n\n"); for(i=0;i<5;i++) {

printf("%4d\t\t%5s\t%5s\t",a[i].acn,a[i].title,a[i].auth);

if(a[i].flag==0) printf("not issued\n\n");

else printf("issued\n\n"); }

delay(2000); break;

case 7: /* condition for going out */

Page 408: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

exit();

} }

}

linkfloat() { /* special function to solve compilar error */ float a=0,*b; /* not used withing the program but still defined */ b=&a; a=*b; return 0; }

------------------------------------------------------------------------------------------------------------------

(g) 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".

#include<stdio.h>#include<conio.h>

void main() {

struct date { int date; int month; int year; }d1;

int d,m,y,i;clrscr();

printf("enter the date to save in structure: \n\n");

printf("Enter the date: ");scanf("%d",&d1.date);

printf("\n\nEnter the month: ");scanf("%d",&d1.month);

printf("\n\nEnter the year: ");scanf("%d",&d1.year);

clrscr();

printf("\nenter the date to compare with structure:\n\n");

printf("Enter the date: ");scanf("%d",&d);

printf("\n\nEnter the month: ");scanf("%d",&m);

printf("\n\nEnter the year: ");scanf("%d",&y);

if(d==d1.date && m==d1.month && y==d1.year) {

printf("\n\ndates are equal\n\n");

}

else {

Solution:

Page 409: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

printf("\n\ndates are unequal\n\n");

}

getch();

}

-----------------------------------------------------------------------------------------------------------------

(h) 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.

#include<stdio.h>#include<conio.h>#include<alloc.h>#include<ctype.h>

struct linklist { int data; linklist *link; };

void main() {

struct linklist *first, *temp;

char choice='y';

int count=0;

clrscr();

/* taking the input of first element */

printf("Enter element %d: ",++count);

first=(linklist *)malloc(sizeof(linklist));

scanf("%d",&first->data);

first->link=NULL;

printf("\n\nEnter another element(Y/N): ");

choice=getche();

tolower(choice); /* converting to lowercase to match the condition of switch */

Solution:

Page 410: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

switch(choice) {

case 'y':

clrscr();

while(choice=='y' || choice=='Y') {

printf("\nEnter element %d: ",++count);

temp=(linklist *)malloc(sizeof(linklist));

scanf("%d",&temp->data);

temp->link=first;

first=temp;

printf("\n\n\nEnter another elements(Y/N): ");choice=getche();

clrscr();

}

break;

case 'n':

break;

}

printf("\nTotal elements = %d\n\n",count);

/* printing all elements */

for(temp=first; temp!=NULL; temp=temp->link) {

printf("%d ",temp->data);

}

getch();

}

-----------------------------------------------------------------------------------------------------------------

(i) A stack is a data structure in which addition of new element or deletion of existing element always takes place at the same end. This end is often known as ‘top’ of stack. This situation can be compared to a stack of plates in a cafeteria where every new plate taken off the stack is also from the ‘top’ of the stack. There are several application where stack can be put to use. For example, recursion, keeping track of function calls, evaluation of expressions, etc. Write a program to implement a stack using a linked list.

Page 411: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T10:55:00-08:00&max-results=7[07-Apr-14 8:58:21 PM]

Newer Posts Older PostsHome

Subscribe to: Posts (Atom)

Posted by Chetan Raikwar at 07:04 No comments:

NOTE: Topic not discussed in the book. I am learning from other resources.

-----------------------------------------------------------------------------------------------------------------

(j) Unlike a stack, in a queue the addition of new element takes place at the end (called ‘rear’ of queue) whereas deletion takes place at the other end (called ‘front’ of queue). Write a program to implement a queue using a linked list

NOTE: Topic not discussed in the book. I am learning from other resources._______________________________________________________________________

Solution:

Solution:

Recommend this on Google

Simple template. Powered by Blogger.

Page 412: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 5 (Functions & Pointers)

(a) Write a function to calculate the factorial value of any integer entered through the keyboard.

#include<stdio.h>#include<conio.h>

void main() {

int num;void func();

clrscr();

printf("Please enter any number: ");scanf("%d",&num);

func(num);

getch();

}

void func(int n) {

int fact=1;

for(;n>=1;n--) {

fact=fact*n;

}

printf("\n\nFactorial value = %d \n",fact);

}

------------------------------------------------------------------------------------------------------------

(b) Write a function power ( a, b ), to calculate the value of a raised to

Exercise [D]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 413: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

b.

#include<stdio.h>#include<conio.h>

void main() {

int num1,num2 ;clrscr();

printf("Please enter the value of a: ");scanf("%d",&num1);

printf("\n\nPlease enter the value of b: ");scanf("%d",&num2);

power(num1,num2);

getch();

}

power(int a , int b) {

int c=1,i;

for(i=1;i<=b;i++) {c=c*a;

if(i==b) {break;}

}

printf("\n\n\nValue of %d raised to the power of %d is = %d\n",a,b,c);

return 0; }

------------------------------------------------------------------------------------------------------------

(c) Write a general-purpose function to convert any given year into its roman equivalent. The following table shows the roman equivalents of decimal numbers:

Decimal Roman

1 i5 v10 x50 l100 c500 d1000 m

Example:Roman equivalent of 1988 is mdcccclxxxviiiRoman equivalent of 1525 is mdxxv

Solution:

Page 414: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

#include<stdio.h>#include<conio.h>

void main() {

int yr;void func();

clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

printf("\n\nRoman Equivalent = ");func(yr);

getch();

}void func(int y) {

int d1,d2,d3,d4,d5,d6,d7,a,b,c,d,e,f;

char thsnd='m',hndr_5='d',hndr='c',ffty='l',tn='x',fv='v',one='i';

/******* Roman Convertion ********/

/* To find all thousands */

d1=y/1000;a=y%1000;

for(;d1>=1;d1--) {printf("%c",thsnd);

if(a==0)break;}

/* To find all five-hundreds */

d2=a/500;b=a%500;

for(;d2>=1;d2--) {printf("%c",hndr_5);

if(b==0)break;}

/* To find all hundreds */

d3=b/100;c=b%100;

for(;d3>=1;d3--) {printf("%c",hndr);

if(c==0)break;}

/* To find all fifties *//***********************/

Solution:

Page 415: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

d4=c/50;d=c%50;

for(;d4>=1;d4--) {printf("%c",ffty);

if(d==0)break;}

/* To find all tens *//********************/

d5=d/10;e=d%10;

for(;d5>=1;d5--) {printf("%c",tn);

if(e==0)break;

}

/* To find all fives */

d6=e/5;f=e%5;

for(;d6>=1;d6--) {printf("%c",fv);

if(f==0)break;}

/* To find all ones */

for(d7=f;d7>=1;d7--) {printf("%c",one);

}

}

------------------------------------------------------------------------------------------------------------

(d) Any year is entered through the keyboard. Write a function to determine whether the year is a leap year or not.

#include<stdio.h>#include<conio.h>void main() {

int yr;void func();clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

func(yr);

Solution:

Page 416: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

getch();

}void func(int y) {

if((y%4)==0)

printf("\nThis is a LEAP YEAR.\n");

else

printf("\nThis is NOT A LEAP YEAR.\n");

}

------------------------------------------------------------------------------------------------------------

(e) 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.

#include<stdio.h>#include<conio.h>

void main() {

int i,j,k;clrscr();

printf("enter the number: ");

scanf("%d",&j);

printf("\n\nprime factors:");

for(i=2;i<=j;) {

if(j%i==0) { /* divide only if remainder is supposed to be 0 */

j=j/i;

printf(" %d ",i); /* print the divisor */

}

else /* if divisor cannot divide completely */

i=i+1; /* increase it's value and try again */

}

getch();

}

________________________________________________________________________

(a) Write a function which receives a float and an int from main( ), finds

Solution:

Exercise [F]

Page 417: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

the product of these two and returns the product which is printed through main( ).

#include<stdio.h>#include<conio.h>

void main() {

int i;float j,k,product();clrscr();

printf("Please enter an integer number: ");scanf("%d",&i);

printf("\nPlease enter a decimal number: ");scanf("%f",&j);

k=product(&i,&j);

printf("\nProduct = %.1f\n",k);

getch();

}

float product(int *a,float *b) {

float *c;

*c=(*a)*(*b);

return *c;

}

------------------------------------------------------------------------------------------------------------

(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<stdio.h>#include<conio.h>#include<math.h>

void main() {

int d1,d2,d3,d4,d5,i,sum,avg;float sd;

clrscr();

printf("enter five digits: \n\n");scanf("%d%d%d%d%d",&d1,&d2,&d3,&d4,&d5);

func(d1,d2,d3,d4,d5,&sum,&avg,&sd);

printf("\tsum = %d\n\taverage = %d\n\tstandard deviation = %f ",sum,avg,sd);

getch();

Solution:

Solution:

Page 418: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

}func(int a, int b, int c, int d, int e, int *s, int *av, float *ssd) {

float temp;

*s=a+b+c+d+e; /* sum of digits */*av=(a+b+c+d+e)/5; /* average */

a=a-(*av);b=b-(*av);c=c-(*av);d=d-(*av);e=e-(*av);

temp=((a*a)+(b*b)+(c*c)+(d*d)+(e*e))/4; /* standard deviation */*ssd=sqrt(temp);

return 0;

}

------------------------------------------------------------------------------------------------------------

(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( ).

#include<stdio.h>#include<conio.h>void main() {

int s1,s2,s3,*avg,*prcnt;void func();clrscr();

printf("Please enter the marks of 3 subjects: \n");scanf("%d%d%d",&s1,&s2,&s3);

func(s1,s2,s3,&avg,&prcnt);

printf(" Average = %d\nPercentage = %d%\n",avg,prcnt);

getch();

}void func(int a, int b, int c, int *d, int *f) {

*d=(a+b+c)/3;*f=(a+b+c)/3;

}_____________________________________________________________________

a) A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:(1) Without using recursion(2) Using recursion

Solution:

Exercise [J]

Solution:

Page 419: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

#include<stdio.h>#include<conio.h>void main() {

long num,s=0,ch;clrscr();

printf("Enter any number: ");scanf("%ld",&num);

printf("\n\nChoose: 1: obtain sum of digits non-recursively\n\n");printf(" 2: obtain sum of digits recursively\n\n\n");

printf("Your choice: ");ch=getche();

switch(ch) {

case '1':

while(num!=0) {

s=s+(num%10);

num=num/10;

}

printf("\n\n\nsum of digits = %d\n",s);

break;

case '2':

s=sum(num);

printf("\n\n\nSum of digits = %d\n",s);break;}

getch();

}

sum(long n) {

static s=0;

if(n==0)return s;

else {

s=s+n%10;n=sum(n/10);

return n;

}

}

-----------------------------------------------------------------------------------------------------------

(b) A positive integer is entered through the keyboard, write a program to obtain the prime factors of the number. Modify the function suitably to obtain the prime factors recursively.

Page 420: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

#include<stdio.h>#include<conio.h>void main() {

int d,ch,b=2;clrscr();

printf("Enter the number: ");

scanf("%d",&d);

printf("\n\nObtain prime factors:\n\n");printf("1: non-recursively\n\n");printf("2: recursively\n\n");

printf("your choice: ");scanf("%d",&ch);

switch(ch) {

case 1:

printf("\n\n\nPrime factors: ");while(d!=1) {

if(d%b==0) { /* non recursive method */d=d/b;printf("%d ",b);}elseb++;}break;

case 2:

printf("\n\n\nPrime factors: ");

factors(d);

break;

default:

printf("\n\nwrong input!");

break;}

getch();

}

int factors (int n) {

int b=2;

if(n==1)return 1;

else {

while(n!=1) {

if((n%b)==0) {

Solution:

Page 421: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

n=factors(n/b); /* recursive function */

printf("%d ",b);}

elseb++;

}return n;}

}

------------------------------------------------------------------------------------------------------------

(c) 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...

#include<stdio.h>#include<conio.h>void main() {

unsigned i,num=25,c=1;clrscr();

for(i=0;i<num;i++) {

printf("%u ",fib(c));

c++;}

getch();}

fib(unsigned n) {

if(n==0)return 0;

if(n==1)return 1;

else

return fib(n-1)+fib(n-2);

}

------------------------------------------------------------------------------------------------------------

(d) A positive integer is entered through the keyboard, write a function to find the binary equivalent of this number using recursion.

#include<stdio.h>#include<conio.h>void main() {

int num;

Solution:

Solution:

Page 422: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

clrscr();

printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,7);printf("<%c%c%c%c%c read right to left",196,196,196,196,196);

getch();

}

binary(int n) {

if(n==0)return 0;

else {

printf("%d",n%2);

n= binary( n/2 ); /* recursive function */

return n;

}

}------------------------------------------------------------------------------------------------------------

(e) Write a recursive function to obtain the running sum of first 25 natural numbers.

#include<stdio.h>#include<conio.h>void main() {

int i=25,j;clrscr();

j=recsum(i);

printf("Addition of 25 natural numbers = %d",j);

getch();

}

int recsum(int n) {

if(n==1)return 1;

else

n = n + recsum(n-1); /* recursive addition */

return n;

}

------------------------------------------------------------------------------------------------------------

(f) Write a C function to evaluate the series

Solution:

Page 423: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

sin(x) = x - (x3/3!) + ( x5/5!) - (x7/7!) + ........to five significant digits.

------------------------------------------------------------------------------------------------------------

(g) 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.

#include<stdio.h>#include<conio.h>void main() {

int x,y,z;char choice;void func();clrscr();

printf("Please enter values of X,Y,Z\n");scanf("%d",&x);scanf("%d",&y);scanf("%d",&z);

printf("\n\nBefore shift: X=%d Y=%d Z=%d\n",x,y,z);

func(&x,&y,&z); /* Call by reference */

printf("\n\nAfter shift: X=%d Y=%d Z=%d\n\n",x,y,z);

/* Circular Shifting continuously */

do {

printf("\nShift again(Y/N): ");scanf(" %c",&choice);

clrscr();

func(&x,&y,&z);printf("\nAfter another shift: X=%d Y=%d Z=%d\n\n",x,y,z);

}while(choice=='y');

}

void func(int *a,int *b,int *c) {

int d,e,f;

d=*a;e=*b;f=*c;*a=f;*b=d;*c=e;

}

Solution:

Solution:

Page 424: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

------------------------------------------------------------------------------------------------------------

(h) Write a function to find the binary equivalent of a given decimal integer and display it.

#include<stdio.h>#include<conio.h>void main() {

int num;void binary();

clrscr();

printf("\t\tDecimal Integer to Binary conversion\n\n\n");printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,10);printf("<%c%c%c%c%c",196,196,196,196,196);printf(" read right to left");

getch();}

void binary(int n) {

while(n!=0) {

printf("%d",n%2);

n=n/2;

}

}

------------------------------------------------------------------------------------------------------------

(i) If the lengths of the sides of a triangle are denoted by a, b, and c, then area of triangle is given byrootover ( S * (S-a) * (S-b) * (S-c))where, S = ( a + b + c ) / 2

#include<stdio.h>#include<conio.h>#include<math.h>void main() {

int s1,s2,s3,s;int area;clrscr();

printf("enter 3 sides of triangle: \n\n");scanf("%d%d%d",&s1,&s2,&s3);

s=s1+s2+s3/2;

area=func(s1,s2,s3,s);

Solution:

Solution:

Page 425: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

printf("\narea = %d",area);

getch();

}func(int i, int j, int k, int h) {

int ar,area;

ar=sqrt(h*((h-i)*(h-j)*(h-k)));

return (ar);

}

------------------------------------------------------------------------------------------------------------

(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.

------------------------------------------------------------------------------------------------------------

(k) Write a function to compute the greatest common divisor given by Euclid’s algorithm, exemplified for J = 1980, K = 1617 as follows:1980 / 1617 = 11980 – 1 * 1617 = 3631617 / 363 = 41617 – 4 * 363 = 165363 / 165 = 2363 – 2 * 165 = 335 / 33 = 5165 – 5 * 33 = 0Thus, the greatest common divisor is 33.

#include<stdio.h>#include<conio.h>void main() {

int a,b,r,d1,d2,temp;clrscr();

printf("Enter first number: ");scanf("%d",&a);

printf("\n\nEnter second number: ");scanf("%d",&b);

while(b!=0) {

r=a%b;

a=b;b=r;

Solution:

Solution:

Page 426: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

Posted by Chetan Raikwar at 07:02 No comments:

}

d1=a; /* devisor of first number */

temp=a;a=b;b=temp;

while(b!=0) {

r=a%b;a=b;b=r;

}

d2=a; /* devisor of second number */

printf("\n\n\nGreatest common devisor: ");

if(d1==d2) {

printf("%d",d1);

}

getch();

}______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 4 (The Case Control Structure)

Write a menu driven program which has following options:

1. Factorial of a number.2. Prime or not3. Odd or even4. Exit

#include<stdio.h>#include<conio.h>main() {

int num,i,j=0,k=0,choice,fact=1;clrscr();

printf("Please enter any number: ");scanf("%d",&num);

while(1){printf("\n\n1. Factorial");

Exercise [C]

Solution:

Page 427: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

printf("\n2. Prime");printf("\n3. Odd/Even");printf("\n4. Exit");printf("\n\nPlease enter your choice: ");scanf("%d",&choice);

switch(choice){

case 1:

for(i=num;i>=1;i--) { fact=fact*i; } printf("\nFactorial = %d ",fact); break;

case 2:

for(i=2;i<num;i++) { j=num%i; if(j==0){ k=1; break; } } if(k==0) { printf("\nPrime Number"); } else { printf("\nNot a Prime Number"); } break;

case 3:

if((num%2)==0) printf("\nEven Number"); else printf("\nOdd Number"); break;

case 4:

exit();

} }

}

------------------------------------------------------------------------------------------------------------

Write a program which to find the grace marks for a student using switch. The user should enter the class obtained by the student and the number of subjects he has failed in.

− If the student gets first class and the number of subjects he failed in is greater than 3, then he does not get any grace. If the number of subjects he failed in is less than or equal to 3 then the grace is of 5 marks per subject.

− If the student gets second class and the number of subjects he failed in is greater than 2, then he does not get any grace. If the number of

Exercise [D]

Page 428: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

Newer Posts Older PostsHome

Posted by Chetan Raikwar at 07:02 No comments:

subjects he failed in is less than or equal to 2 then the grace is of 4 marks per subject.

− If the student gets third class and the number of subjects he failed in is greater than 1, then he does not get any grace. If the number of subjects he failed in is equal to 1 then the grace is of 5 marks per subject

#include<stdio.h>#include<conio.h>main() {

int _class,f_sub;clrscr();

printf("\nPlease enter the class obtained\n1=first 2=second 3=third: ");scanf("%d",&_class);printf("\n\nPlease enter the number of failed subjects: ");scanf("%d",&f_sub);

switch(_class) {

case 1: if(f_sub<=3) { printf("\nGrace marks = 5 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

case 2: if(f_sub<=2) { printf("\nGrace marks = 4 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

case 3: if(f_sub==1) { printf("\nGrace marks = 5 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

default: printf("Error! wrong input.\n"); break; }

getch(); return 0;

}_____________________________________________________________________

Solution:

Recommend this on Google

Page 429: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=1&by-date=false[07-Apr-14 8:59:28 PM]

Subscribe to: Posts (Atom)

Simple template. Powered by Blogger.

Page 430: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 5 (Functions & Pointers)

(a) Write a function to calculate the factorial value of any integer entered through the keyboard.

#include<stdio.h>#include<conio.h>

void main() {

int num;void func();

clrscr();

printf("Please enter any number: ");scanf("%d",&num);

func(num);

getch();

}

void func(int n) {

int fact=1;

for(;n>=1;n--) {

fact=fact*n;

}

printf("\n\nFactorial value = %d \n",fact);

}

------------------------------------------------------------------------------------------------------------

(b) Write a function power ( a, b ), to calculate the value of a raised to

Exercise [D]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 431: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

b.

#include<stdio.h>#include<conio.h>

void main() {

int num1,num2 ;clrscr();

printf("Please enter the value of a: ");scanf("%d",&num1);

printf("\n\nPlease enter the value of b: ");scanf("%d",&num2);

power(num1,num2);

getch();

}

power(int a , int b) {

int c=1,i;

for(i=1;i<=b;i++) {c=c*a;

if(i==b) {break;}

}

printf("\n\n\nValue of %d raised to the power of %d is = %d\n",a,b,c);

return 0; }

------------------------------------------------------------------------------------------------------------

(c) Write a general-purpose function to convert any given year into its roman equivalent. The following table shows the roman equivalents of decimal numbers:

Decimal Roman

1 i5 v10 x50 l100 c500 d1000 m

Example:Roman equivalent of 1988 is mdcccclxxxviiiRoman equivalent of 1525 is mdxxv

Solution:

Page 432: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

#include<stdio.h>#include<conio.h>

void main() {

int yr;void func();

clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

printf("\n\nRoman Equivalent = ");func(yr);

getch();

}void func(int y) {

int d1,d2,d3,d4,d5,d6,d7,a,b,c,d,e,f;

char thsnd='m',hndr_5='d',hndr='c',ffty='l',tn='x',fv='v',one='i';

/******* Roman Convertion ********/

/* To find all thousands */

d1=y/1000;a=y%1000;

for(;d1>=1;d1--) {printf("%c",thsnd);

if(a==0)break;}

/* To find all five-hundreds */

d2=a/500;b=a%500;

for(;d2>=1;d2--) {printf("%c",hndr_5);

if(b==0)break;}

/* To find all hundreds */

d3=b/100;c=b%100;

for(;d3>=1;d3--) {printf("%c",hndr);

if(c==0)break;}

/* To find all fifties *//***********************/

Solution:

Page 433: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

d4=c/50;d=c%50;

for(;d4>=1;d4--) {printf("%c",ffty);

if(d==0)break;}

/* To find all tens *//********************/

d5=d/10;e=d%10;

for(;d5>=1;d5--) {printf("%c",tn);

if(e==0)break;

}

/* To find all fives */

d6=e/5;f=e%5;

for(;d6>=1;d6--) {printf("%c",fv);

if(f==0)break;}

/* To find all ones */

for(d7=f;d7>=1;d7--) {printf("%c",one);

}

}

------------------------------------------------------------------------------------------------------------

(d) Any year is entered through the keyboard. Write a function to determine whether the year is a leap year or not.

#include<stdio.h>#include<conio.h>void main() {

int yr;void func();clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

func(yr);

Solution:

Page 434: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

getch();

}void func(int y) {

if((y%4)==0)

printf("\nThis is a LEAP YEAR.\n");

else

printf("\nThis is NOT A LEAP YEAR.\n");

}

------------------------------------------------------------------------------------------------------------

(e) 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.

#include<stdio.h>#include<conio.h>

void main() {

int i,j,k;clrscr();

printf("enter the number: ");

scanf("%d",&j);

printf("\n\nprime factors:");

for(i=2;i<=j;) {

if(j%i==0) { /* divide only if remainder is supposed to be 0 */

j=j/i;

printf(" %d ",i); /* print the divisor */

}

else /* if divisor cannot divide completely */

i=i+1; /* increase it's value and try again */

}

getch();

}

________________________________________________________________________

(a) Write a function which receives a float and an int from main( ), finds

Solution:

Exercise [F]

Page 435: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

the product of these two and returns the product which is printed through main( ).

#include<stdio.h>#include<conio.h>

void main() {

int i;float j,k,product();clrscr();

printf("Please enter an integer number: ");scanf("%d",&i);

printf("\nPlease enter a decimal number: ");scanf("%f",&j);

k=product(&i,&j);

printf("\nProduct = %.1f\n",k);

getch();

}

float product(int *a,float *b) {

float *c;

*c=(*a)*(*b);

return *c;

}

------------------------------------------------------------------------------------------------------------

(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<stdio.h>#include<conio.h>#include<math.h>

void main() {

int d1,d2,d3,d4,d5,i,sum,avg;float sd;

clrscr();

printf("enter five digits: \n\n");scanf("%d%d%d%d%d",&d1,&d2,&d3,&d4,&d5);

func(d1,d2,d3,d4,d5,&sum,&avg,&sd);

printf("\tsum = %d\n\taverage = %d\n\tstandard deviation = %f ",sum,avg,sd);

getch();

Solution:

Solution:

Page 436: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

}func(int a, int b, int c, int d, int e, int *s, int *av, float *ssd) {

float temp;

*s=a+b+c+d+e; /* sum of digits */*av=(a+b+c+d+e)/5; /* average */

a=a-(*av);b=b-(*av);c=c-(*av);d=d-(*av);e=e-(*av);

temp=((a*a)+(b*b)+(c*c)+(d*d)+(e*e))/4; /* standard deviation */*ssd=sqrt(temp);

return 0;

}

------------------------------------------------------------------------------------------------------------

(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( ).

#include<stdio.h>#include<conio.h>void main() {

int s1,s2,s3,*avg,*prcnt;void func();clrscr();

printf("Please enter the marks of 3 subjects: \n");scanf("%d%d%d",&s1,&s2,&s3);

func(s1,s2,s3,&avg,&prcnt);

printf(" Average = %d\nPercentage = %d%\n",avg,prcnt);

getch();

}void func(int a, int b, int c, int *d, int *f) {

*d=(a+b+c)/3;*f=(a+b+c)/3;

}_____________________________________________________________________

a) A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:(1) Without using recursion(2) Using recursion

Solution:

Exercise [J]

Solution:

Page 437: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

#include<stdio.h>#include<conio.h>void main() {

long num,s=0,ch;clrscr();

printf("Enter any number: ");scanf("%ld",&num);

printf("\n\nChoose: 1: obtain sum of digits non-recursively\n\n");printf(" 2: obtain sum of digits recursively\n\n\n");

printf("Your choice: ");ch=getche();

switch(ch) {

case '1':

while(num!=0) {

s=s+(num%10);

num=num/10;

}

printf("\n\n\nsum of digits = %d\n",s);

break;

case '2':

s=sum(num);

printf("\n\n\nSum of digits = %d\n",s);break;}

getch();

}

sum(long n) {

static s=0;

if(n==0)return s;

else {

s=s+n%10;n=sum(n/10);

return n;

}

}

-----------------------------------------------------------------------------------------------------------

(b) A positive integer is entered through the keyboard, write a program to obtain the prime factors of the number. Modify the function suitably to obtain the prime factors recursively.

Page 438: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

#include<stdio.h>#include<conio.h>void main() {

int d,ch,b=2;clrscr();

printf("Enter the number: ");

scanf("%d",&d);

printf("\n\nObtain prime factors:\n\n");printf("1: non-recursively\n\n");printf("2: recursively\n\n");

printf("your choice: ");scanf("%d",&ch);

switch(ch) {

case 1:

printf("\n\n\nPrime factors: ");while(d!=1) {

if(d%b==0) { /* non recursive method */d=d/b;printf("%d ",b);}elseb++;}break;

case 2:

printf("\n\n\nPrime factors: ");

factors(d);

break;

default:

printf("\n\nwrong input!");

break;}

getch();

}

int factors (int n) {

int b=2;

if(n==1)return 1;

else {

while(n!=1) {

if((n%b)==0) {

Solution:

Page 439: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

n=factors(n/b); /* recursive function */

printf("%d ",b);}

elseb++;

}return n;}

}

------------------------------------------------------------------------------------------------------------

(c) 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...

#include<stdio.h>#include<conio.h>void main() {

unsigned i,num=25,c=1;clrscr();

for(i=0;i<num;i++) {

printf("%u ",fib(c));

c++;}

getch();}

fib(unsigned n) {

if(n==0)return 0;

if(n==1)return 1;

else

return fib(n-1)+fib(n-2);

}

------------------------------------------------------------------------------------------------------------

(d) A positive integer is entered through the keyboard, write a function to find the binary equivalent of this number using recursion.

#include<stdio.h>#include<conio.h>void main() {

int num;

Solution:

Solution:

Page 440: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

clrscr();

printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,7);printf("<%c%c%c%c%c read right to left",196,196,196,196,196);

getch();

}

binary(int n) {

if(n==0)return 0;

else {

printf("%d",n%2);

n= binary( n/2 ); /* recursive function */

return n;

}

}------------------------------------------------------------------------------------------------------------

(e) Write a recursive function to obtain the running sum of first 25 natural numbers.

#include<stdio.h>#include<conio.h>void main() {

int i=25,j;clrscr();

j=recsum(i);

printf("Addition of 25 natural numbers = %d",j);

getch();

}

int recsum(int n) {

if(n==1)return 1;

else

n = n + recsum(n-1); /* recursive addition */

return n;

}

------------------------------------------------------------------------------------------------------------

(f) Write a C function to evaluate the series

Solution:

Page 441: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

sin(x) = x - (x3/3!) + ( x5/5!) - (x7/7!) + ........to five significant digits.

------------------------------------------------------------------------------------------------------------

(g) 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.

#include<stdio.h>#include<conio.h>void main() {

int x,y,z;char choice;void func();clrscr();

printf("Please enter values of X,Y,Z\n");scanf("%d",&x);scanf("%d",&y);scanf("%d",&z);

printf("\n\nBefore shift: X=%d Y=%d Z=%d\n",x,y,z);

func(&x,&y,&z); /* Call by reference */

printf("\n\nAfter shift: X=%d Y=%d Z=%d\n\n",x,y,z);

/* Circular Shifting continuously */

do {

printf("\nShift again(Y/N): ");scanf(" %c",&choice);

clrscr();

func(&x,&y,&z);printf("\nAfter another shift: X=%d Y=%d Z=%d\n\n",x,y,z);

}while(choice=='y');

}

void func(int *a,int *b,int *c) {

int d,e,f;

d=*a;e=*b;f=*c;*a=f;*b=d;*c=e;

}

Solution:

Solution:

Page 442: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

------------------------------------------------------------------------------------------------------------

(h) Write a function to find the binary equivalent of a given decimal integer and display it.

#include<stdio.h>#include<conio.h>void main() {

int num;void binary();

clrscr();

printf("\t\tDecimal Integer to Binary conversion\n\n\n");printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,10);printf("<%c%c%c%c%c",196,196,196,196,196);printf(" read right to left");

getch();}

void binary(int n) {

while(n!=0) {

printf("%d",n%2);

n=n/2;

}

}

------------------------------------------------------------------------------------------------------------

(i) If the lengths of the sides of a triangle are denoted by a, b, and c, then area of triangle is given byrootover ( S * (S-a) * (S-b) * (S-c))where, S = ( a + b + c ) / 2

#include<stdio.h>#include<conio.h>#include<math.h>void main() {

int s1,s2,s3,s;int area;clrscr();

printf("enter 3 sides of triangle: \n\n");scanf("%d%d%d",&s1,&s2,&s3);

s=s1+s2+s3/2;

area=func(s1,s2,s3,s);

Solution:

Solution:

Page 443: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

printf("\narea = %d",area);

getch();

}func(int i, int j, int k, int h) {

int ar,area;

ar=sqrt(h*((h-i)*(h-j)*(h-k)));

return (ar);

}

------------------------------------------------------------------------------------------------------------

(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.

------------------------------------------------------------------------------------------------------------

(k) Write a function to compute the greatest common divisor given by Euclid’s algorithm, exemplified for J = 1980, K = 1617 as follows:1980 / 1617 = 11980 – 1 * 1617 = 3631617 / 363 = 41617 – 4 * 363 = 165363 / 165 = 2363 – 2 * 165 = 335 / 33 = 5165 – 5 * 33 = 0Thus, the greatest common divisor is 33.

#include<stdio.h>#include<conio.h>void main() {

int a,b,r,d1,d2,temp;clrscr();

printf("Enter first number: ");scanf("%d",&a);

printf("\n\nEnter second number: ");scanf("%d",&b);

while(b!=0) {

r=a%b;

a=b;b=r;

Solution:

Solution:

Page 444: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

Posted by Chetan Raikwar at 07:02 No comments:

}

d1=a; /* devisor of first number */

temp=a;a=b;b=temp;

while(b!=0) {

r=a%b;a=b;b=r;

}

d2=a; /* devisor of second number */

printf("\n\n\nGreatest common devisor: ");

if(d1==d2) {

printf("%d",d1);

}

getch();

}______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 4 (The Case Control Structure)

Write a menu driven program which has following options:

1. Factorial of a number.2. Prime or not3. Odd or even4. Exit

#include<stdio.h>#include<conio.h>main() {

int num,i,j=0,k=0,choice,fact=1;clrscr();

printf("Please enter any number: ");scanf("%d",&num);

while(1){printf("\n\n1. Factorial");

Exercise [C]

Solution:

Page 445: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

printf("\n2. Prime");printf("\n3. Odd/Even");printf("\n4. Exit");printf("\n\nPlease enter your choice: ");scanf("%d",&choice);

switch(choice){

case 1:

for(i=num;i>=1;i--) { fact=fact*i; } printf("\nFactorial = %d ",fact); break;

case 2:

for(i=2;i<num;i++) { j=num%i; if(j==0){ k=1; break; } } if(k==0) { printf("\nPrime Number"); } else { printf("\nNot a Prime Number"); } break;

case 3:

if((num%2)==0) printf("\nEven Number"); else printf("\nOdd Number"); break;

case 4:

exit();

} }

}

------------------------------------------------------------------------------------------------------------

Write a program which to find the grace marks for a student using switch. The user should enter the class obtained by the student and the number of subjects he has failed in.

− If the student gets first class and the number of subjects he failed in is greater than 3, then he does not get any grace. If the number of subjects he failed in is less than or equal to 3 then the grace is of 5 marks per subject.

− If the student gets second class and the number of subjects he failed in is greater than 2, then he does not get any grace. If the number of

Exercise [D]

Page 446: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

Newer Posts Older PostsHome

Posted by Chetan Raikwar at 07:02 No comments:

subjects he failed in is less than or equal to 2 then the grace is of 4 marks per subject.

− If the student gets third class and the number of subjects he failed in is greater than 1, then he does not get any grace. If the number of subjects he failed in is equal to 1 then the grace is of 5 marks per subject

#include<stdio.h>#include<conio.h>main() {

int _class,f_sub;clrscr();

printf("\nPlease enter the class obtained\n1=first 2=second 3=third: ");scanf("%d",&_class);printf("\n\nPlease enter the number of failed subjects: ");scanf("%d",&f_sub);

switch(_class) {

case 1: if(f_sub<=3) { printf("\nGrace marks = 5 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

case 2: if(f_sub<=2) { printf("\nGrace marks = 4 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

case 3: if(f_sub==1) { printf("\nGrace marks = 5 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

default: printf("Error! wrong input.\n"); break; }

getch(); return 0;

}_____________________________________________________________________

Solution:

Recommend this on Google

Page 447: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:03:00-08:00&max-results=16&start=7&by-date=false[07-Apr-14 9:00:25 PM]

Subscribe to: Posts (Atom)

Simple template. Powered by Blogger.

Page 448: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 9 (Puppeting on Strings)

(c) Write a program that converts all lowercase characters in a given string to its equivalent uppercase character.

#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.

#include<stdio.h>#include<conio.h>

void main() {

char s[100];int i=0,n,pos;

Exercise [D]

Solution:

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 449: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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.

#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();

}

Solution:

Page 450: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

---------------------------------------------------------------------------------------------------------------

(f) Write a program that replaces two or more consecutive blanks in a string by a single blank. For example, if the input isGrim return to the planet of apes!!the output should beGrim return to the planet of apes!!

#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();}_______________________________________________________________________

(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:

Exercise [F]

Page 451: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

#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]) {

Solution:

Page 452: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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;

Page 453: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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.

#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");

Solution:

Page 454: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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.

#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;

Solution:

Page 455: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

/* 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.

#include<stdio.h>#include<conio.h>

void main() {

int x=49,y=9,i=1,lastday;int month,year,a;void box();

clrscr();

Solution:

Page 456: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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;

Page 457: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

/* 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);

Page 458: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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");

Page 459: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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)

Page 460: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

days=29;

elsedays=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

Page 461: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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<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) {

Solution:

Page 462: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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);

Page 463: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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);

}

elseprintf("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;

Page 464: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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);

Page 465: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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);

Page 466: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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;

elsedays=28;

}/* for march */

if(m==3)days=31;

Page 467: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

/* 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.

Page 468: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

(c) If the cost per item is also given write a program to calculate the total inventory values.

-------------------------------------------------------------------------------------------------------------

(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.

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.

#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(' ');}

elseputch(s[i]);i++;}

getch();}

---------------------------------------------------------------------------------------------------------------

Solution:

Solution:

Solution:

Page 469: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

(i) Write a program that will read a line and delete from it all occurrences of the word ‘the’.

#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];

Solution:

Page 470: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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.

#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");

Solution:

Page 471: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

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.

#include<stdio.h>#include<conio.h>void main() {

char a[10000],i=0,suc=0;clrscr();

Solution:

Page 472: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&start=4&by-date=false[07-Apr-14 9:01:46 PM]

Newer Posts Older PostsHome

Subscribe to: Posts (Atom)

Posted by Chetan Raikwar at 07:03 No comments:

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();}

______________________________________________________________________

Recommend this on Google

Simple template. Powered by Blogger.

Page 473: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 7 (The C Pre-processor)

(a) Write down macro definitions for the following:1. To test whether a character entered is a small case letter or not.2. To test whether a character entered is a upper case letter or not.3. To test whether a character is an alphabet or not. Make use of the macros you defined in (1) and (2) above.4. To obtain the bigger of two numbers.

#include<stdio.h>#include<conio.h>#define UPPER(x) (x>=65 && x<=90)#define SMALL(y) (y>=97 && y<=123)#define ALPHABET(z) (z>=65 && z<=90 || z>=97 && z<=123)#define BIGGER(a,b) (a>b)

void main() {

int i,d1,d2;char ch,ch1;clrscr();

printf("\t enter your choice: \n");printf("\t===================\n\n");

printf("1: to test if character is small case letter or not\n\n");printf("2: to test if character is upper case letter or not\n\n");printf("3: to test if character is an alphabet or not\n\n");printf("4: to find bigger of two number\n\n\n");

printf("choice: ");scanf("%d",&i);

switch (i) {

case 1:

clrscr();

printf("enter any character\n\n");

scanf(" %c",&ch);

if SMALL(ch)printf("\n\n it is a small case letter.\n");

Exercise [C]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 474: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

elseprintf("\n\nit is not a small case letter.\n");

break;

case 2:

clrscr();

printf("enter any character\n\n");

scanf(" %c",&ch);

if UPPER(ch)printf("\n\nit is an upper case letter.\n");elseprintf("\n\nit is not an upper case letter.\n");

break;

case 3:

clrscr();

printf("enter any character\n\n");

scanf(" %c",&ch);

if ALPHABET(ch)printf("\n\nit is an alphabet.\n");

elseprintf("\n\nit is not an alphabet.\n");

break;

case 4:

clrscr();

printf("enter two numbers\n\n");

scanf("%d%d",&d1,&d2);

if BIGGER(d1,d2)

printf("\n\n%d is bigger\n",d1);

elseprintf("\n\n%d is bigger \n",d2);

break;

default:

printf("\n\n\nwrong choice entered\n");

}

getch();}

--------------------------------------------------------------------

(b) Write macro definitions with arguments for calculation of area and perimeter of a triangle, a square and a circle. Store these macro definitions in a file called “areaperi.h”. Include this file in your program,

Page 475: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

and call the macro definitions for calculating area and perimeter for different squares, triangles and circles.

#define TP(a,b,c) (a+b+c) /* perimeter of triangle */#define TA(a,b,c,d) (d*((d-a)*(d-b)*(d-c))) /* area of triangle *#define PS(x) (4*x) /* perimeter of square */#define SA(x) (x*x) /* area of square */#define CP(x) (2*3.14*r) /* perimeter of circle */#define CA(x) (3.14*r*r) /* area of circle */

#include"areaperi.h" /* inclusion of custom header file */#include<stdio.h>#include<conio.h>#include<math.h>void main() {

float t1,t2,t3,hpt; /* sides of triangle,half of perimeter */float ss,r; /* side of square, radius of circle */int ch; float tp,ta,ta1,sp,sa,cp,ca; /* perimeter & area of triangle,square,circle */

clrscr();

printf("\tFind area and perimeter of: \n");printf(" *****************************\n\n");

printf("1: triangle\n\n");printf("2: square\n\n");printf("3: circle\n\n\n\n\n");

printf("enter your choice: ");scanf("%d",&ch);

switch(ch)

{

case 1:

/* triangle */

clrscr(); printf("enter side 1 of triangle: "); scanf("%f",&t1);

printf("\n\nenter side 2 of triangle: "); scanf("%f",&t2);

printf("\n\nenter side 3 of triangle: "); scanf("%f",&t3);

hpt=t1+t2+t3/2;

tp=TP(t1,t2,t3); ta=TA(t1,t2,t3,hpt);

ta1=sqrt(ta);

printf("\n\n\tperimeter of triangle = %f",tp); printf("\n\tarea of triangle = %f",ta1);

Note: write these macro definitions in a new file and save it as "areaperi.h", compile it and then you can include it during inclusion of libraries as - include"areaperi.h".

Solution:

Page 476: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

break;

case 2:

/* square */

clrscr();

printf("\n\nenter side of a square: "); scanf("%f",&ss);

sp=PS(ss); sa=SA(ss);

printf("\n\n\tperimeter of square = %f",sp); printf("\n\tarea of square = %f",sa);

break;

case 3:

/* circle */

clrscr();

printf("\n\nenter radius of circle: "); scanf("%f",&r);

cp=CP(r); ca=CA(r);

printf("\n\n\tperimeter of circle = %f",cp); printf("\n\tarea of circle = %f",ca);

break;

default:

exit();}

getch();

}

-----------------------------------------------------------------------

(c) Write down macro definitions for the following:1. To find arithmetic mean of two numbers.2. To find absolute value of a number.3. To convert a uppercase alphabet to lowercase.4. To obtain the bigger of two numbers.

#include<stdio.h>#include<conio.h> #define AM(x,y) ((x+y)/2) #define ABS(x,y) (x<y) #define LOWER(x)(122-(90-x)) #define BIG(x,y) (x>y)

Solution:

Page 477: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

void main() {

char ch,ch1; int choice,a,b,abs,c=0; float am;

clrscr();

printf("\tMacro Definitions to:\n"); printf(" ***************************\n\n");

printf("\n1: Find airthmetic mean of two numbers: \n\n"); printf("2: find absolute value of a number: \n\n"); printf("3: convert an uppercase character to lowercase: \n\n"); printf("4: obtain the bigger of two numbers: \n\n\n\n\n\n\n\n\n\n");

printf("enter your choice: "); scanf("%d",&choice);

switch(choice) {

case 1:

/* finding arithmetic mean of two numbers */

clrscr();

printf("\nenter two numbers:\n "); scanf("%d%d",&a,&b); am=AM(a,b); /* airthmetic mean */ printf("\nairthmetic mean = %f ",am); break;

case 2:

/* finding the absolute value of a number */

clrscr();

printf("\nenter a number: "); scanf("%d",&a);

if ABS(a,c)

abs=a*(-1);

else abs=a;

printf("\nabsolute value = %d",abs); break;

case 3:

/* converting an uppercase character to equivalent lowercase */

clrscr();

printf("\nenter an uppercase character: "); scanf(" %c",&ch);

ch1=LOWER(ch);

printf("\nequivalent lowercase character = %c",ch1); break;

case 4:

Page 478: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

/* finding the bigger of two numbers */

clrscr();

printf("\nenter two numbers:\n "); scanf("%d%d",&a,&b);

if BIG(a,b) printf("\n\n%d is bigger.\n",a);

else printf("\n\n%d is bigger.\n",b);

break;

default:

exit(); }

getch();

}

-----------------------------------------------------------------------

(d) Write macro definitions with arguments for calculation of Simple Interest and Amount. Store these macro definitions in a file called “interest.h”. Include this file in your program, and use the macro definitions for calculating simple interest and amount.

#define INTEREST(x,y,z) (x*y*z/100)#define AMOUNT(x,y) (x+y)

#include<stdio.h>#include<conio.h> #include"interest.h" /* inclusion of custom header file */

void main() {

int p,r,t,a; float si;

clrscr();

printf("enter the principle: "); scanf("%d",&p);

printf("\n\nenter the rate: "); scanf("%d",&r);

printf("\n\nenter the time: "); scanf("%d",&t);

si=INTEREST(p,r,t);

Note: write these macro definitions in a new file and save it as

"interest.h", compile it and then you can include it during

inclusion of libraries as - include"interest.h".

Solution:

Page 479: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

Posted by Chetan Raikwar at 07:03 No comments:

a=AMOUNT(p,si);

printf("\n\n\n\n\t\tsimple interest = %f\n\n\t\tamount = %d",si,a);

getch(); }

_______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 6 (Data Types Revisited)

Following program calculates the sum of digits of the number 12345. Go through it and find out why is it necessary to declare the storage class of the variable sum as static.main( ){int a ;a = sumdig ( 12345 ) ;printf ( "\n%d", a ) ;}sumdig ( int num ){static int sum ;int a, b ;a = num % 10 ;b = ( num - a ) / 10 ;sum = sum + a ;if ( b != 0 )sumdig ( b ) ;elsereturn ( sum ) ;}

#include<stdio.h>#include<conio.h>

void main() {

int a;

clrscr();

a=sumdig ( 12345 ) ;

printf("\n %d ",a) ;

getch();

}sumdig(int num){

Exercise [D]

Solution:

Page 480: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

Posted by Chetan Raikwar at 07:03 No comments:

static int sum;

/*

It is necessary to declare the storage class of sum as static because it is withina recursive funtion. It is necessary to keep the value of 'num' same for all releventrecursions of it. And to obtain running sum of all of them.

*/

int a,b;

a=num%10;b=(num-a)/10;sum=sum+a;

if(b!=0)sumdig(b);

elsereturn(sum);

}______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 5 (Functions & Pointers)

(a) Write a function to calculate the factorial value of any integer entered through the keyboard.

#include<stdio.h>#include<conio.h>

void main() {

int num;void func();

clrscr();

printf("Please enter any number: ");scanf("%d",&num);

func(num);

getch();

}

void func(int n) {

int fact=1;

Exercise [D]

Solution:

Page 481: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

for(;n>=1;n--) {

fact=fact*n;

}

printf("\n\nFactorial value = %d \n",fact);

}

------------------------------------------------------------------------------------------------------------

(b) Write a function power ( a, b ), to calculate the value of a raised to b.

#include<stdio.h>#include<conio.h>

void main() {

int num1,num2 ;clrscr();

printf("Please enter the value of a: ");scanf("%d",&num1);

printf("\n\nPlease enter the value of b: ");scanf("%d",&num2);

power(num1,num2);

getch();

}

power(int a , int b) {

int c=1,i;

for(i=1;i<=b;i++) {c=c*a;

if(i==b) {break;}

}

printf("\n\n\nValue of %d raised to the power of %d is = %d\n",a,b,c);

return 0; }

------------------------------------------------------------------------------------------------------------

(c) Write a general-purpose function to convert any given year into its roman equivalent. The following table shows the roman equivalents of decimal numbers:

Decimal Roman

1 i5 v

Solution:

Page 482: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

10 x50 l100 c500 d1000 m

Example:Roman equivalent of 1988 is mdcccclxxxviiiRoman equivalent of 1525 is mdxxv

#include<stdio.h>#include<conio.h>

void main() {

int yr;void func();

clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

printf("\n\nRoman Equivalent = ");func(yr);

getch();

}void func(int y) {

int d1,d2,d3,d4,d5,d6,d7,a,b,c,d,e,f;

char thsnd='m',hndr_5='d',hndr='c',ffty='l',tn='x',fv='v',one='i';

/******* Roman Convertion ********/

/* To find all thousands */

d1=y/1000;a=y%1000;

for(;d1>=1;d1--) {printf("%c",thsnd);

if(a==0)break;}

/* To find all five-hundreds */

d2=a/500;b=a%500;

for(;d2>=1;d2--) {printf("%c",hndr_5);

if(b==0)break;}

/* To find all hundreds */

Solution:

Page 483: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

d3=b/100;c=b%100;

for(;d3>=1;d3--) {printf("%c",hndr);

if(c==0)break;}

/* To find all fifties *//***********************/

d4=c/50;d=c%50;

for(;d4>=1;d4--) {printf("%c",ffty);

if(d==0)break;}

/* To find all tens *//********************/

d5=d/10;e=d%10;

for(;d5>=1;d5--) {printf("%c",tn);

if(e==0)break;

}

/* To find all fives */

d6=e/5;f=e%5;

for(;d6>=1;d6--) {printf("%c",fv);

if(f==0)break;}

/* To find all ones */

for(d7=f;d7>=1;d7--) {printf("%c",one);

}

}

------------------------------------------------------------------------------------------------------------

(d) Any year is entered through the keyboard. Write a function to determine whether the year is a leap year or not.

Solution:

Page 484: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

#include<stdio.h>#include<conio.h>void main() {

int yr;void func();clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

func(yr);

getch();

}void func(int y) {

if((y%4)==0)

printf("\nThis is a LEAP YEAR.\n");

else

printf("\nThis is NOT A LEAP YEAR.\n");

}

------------------------------------------------------------------------------------------------------------

(e) 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.

#include<stdio.h>#include<conio.h>

void main() {

int i,j,k;clrscr();

printf("enter the number: ");

scanf("%d",&j);

printf("\n\nprime factors:");

for(i=2;i<=j;) {

if(j%i==0) { /* divide only if remainder is supposed to be 0 */

j=j/i;

printf(" %d ",i); /* print the divisor */

}

else /* if divisor cannot divide completely */

i=i+1; /* increase it's value and try again */

Solution:

Page 485: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

}

getch();

}

________________________________________________________________________

(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( ).

#include<stdio.h>#include<conio.h>

void main() {

int i;float j,k,product();clrscr();

printf("Please enter an integer number: ");scanf("%d",&i);

printf("\nPlease enter a decimal number: ");scanf("%f",&j);

k=product(&i,&j);

printf("\nProduct = %.1f\n",k);

getch();

}

float product(int *a,float *b) {

float *c;

*c=(*a)*(*b);

return *c;

}

------------------------------------------------------------------------------------------------------------

(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<stdio.h>#include<conio.h>#include<math.h>

void main() {

Exercise [F]

Solution:

Solution:

Page 486: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

int d1,d2,d3,d4,d5,i,sum,avg;float sd;

clrscr();

printf("enter five digits: \n\n");scanf("%d%d%d%d%d",&d1,&d2,&d3,&d4,&d5);

func(d1,d2,d3,d4,d5,&sum,&avg,&sd);

printf("\tsum = %d\n\taverage = %d\n\tstandard deviation = %f ",sum,avg,sd);

getch();

}func(int a, int b, int c, int d, int e, int *s, int *av, float *ssd) {

float temp;

*s=a+b+c+d+e; /* sum of digits */*av=(a+b+c+d+e)/5; /* average */

a=a-(*av);b=b-(*av);c=c-(*av);d=d-(*av);e=e-(*av);

temp=((a*a)+(b*b)+(c*c)+(d*d)+(e*e))/4; /* standard deviation */*ssd=sqrt(temp);

return 0;

}

------------------------------------------------------------------------------------------------------------

(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( ).

#include<stdio.h>#include<conio.h>void main() {

int s1,s2,s3,*avg,*prcnt;void func();clrscr();

printf("Please enter the marks of 3 subjects: \n");scanf("%d%d%d",&s1,&s2,&s3);

func(s1,s2,s3,&avg,&prcnt);

printf(" Average = %d\nPercentage = %d%\n",avg,prcnt);

getch();

}void func(int a, int b, int c, int *d, int *f) {

*d=(a+b+c)/3;*f=(a+b+c)/3;

}_____________________________________________________________________

Solution:

Page 487: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

a) A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:(1) Without using recursion(2) Using recursion

#include<stdio.h>#include<conio.h>void main() {

long num,s=0,ch;clrscr();

printf("Enter any number: ");scanf("%ld",&num);

printf("\n\nChoose: 1: obtain sum of digits non-recursively\n\n");printf(" 2: obtain sum of digits recursively\n\n\n");

printf("Your choice: ");ch=getche();

switch(ch) {

case '1':

while(num!=0) {

s=s+(num%10);

num=num/10;

}

printf("\n\n\nsum of digits = %d\n",s);

break;

case '2':

s=sum(num);

printf("\n\n\nSum of digits = %d\n",s);break;}

getch();

}

sum(long n) {

static s=0;

if(n==0)return s;

else {

s=s+n%10;n=sum(n/10);

Exercise [J]

Solution:

Page 488: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

return n;

}

}

-----------------------------------------------------------------------------------------------------------

(b) A positive integer is entered through the keyboard, write a program to obtain the prime factors of the number. Modify the function suitably to obtain the prime factors recursively.

#include<stdio.h>#include<conio.h>void main() {

int d,ch,b=2;clrscr();

printf("Enter the number: ");

scanf("%d",&d);

printf("\n\nObtain prime factors:\n\n");printf("1: non-recursively\n\n");printf("2: recursively\n\n");

printf("your choice: ");scanf("%d",&ch);

switch(ch) {

case 1:

printf("\n\n\nPrime factors: ");while(d!=1) {

if(d%b==0) { /* non recursive method */d=d/b;printf("%d ",b);}elseb++;}break;

case 2:

printf("\n\n\nPrime factors: ");

factors(d);

break;

default:

printf("\n\nwrong input!");

break;}

getch();

}

int factors (int n) {

Solution:

Page 489: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

int b=2;

if(n==1)return 1;

else {

while(n!=1) {

if((n%b)==0) {

n=factors(n/b); /* recursive function */

printf("%d ",b);}

elseb++;

}return n;}

}

------------------------------------------------------------------------------------------------------------

(c) 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...

#include<stdio.h>#include<conio.h>void main() {

unsigned i,num=25,c=1;clrscr();

for(i=0;i<num;i++) {

printf("%u ",fib(c));

c++;}

getch();}

fib(unsigned n) {

if(n==0)return 0;

if(n==1)return 1;

else

return fib(n-1)+fib(n-2);

}

------------------------------------------------------------------------------------------------------------

Solution:

Page 490: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

(d) A positive integer is entered through the keyboard, write a function to find the binary equivalent of this number using recursion.

#include<stdio.h>#include<conio.h>void main() {

int num;clrscr();

printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,7);printf("<%c%c%c%c%c read right to left",196,196,196,196,196);

getch();

}

binary(int n) {

if(n==0)return 0;

else {

printf("%d",n%2);

n= binary( n/2 ); /* recursive function */

return n;

}

}------------------------------------------------------------------------------------------------------------

(e) Write a recursive function to obtain the running sum of first 25 natural numbers.

#include<stdio.h>#include<conio.h>void main() {

int i=25,j;clrscr();

j=recsum(i);

printf("Addition of 25 natural numbers = %d",j);

getch();

}

int recsum(int n) {

if(n==1)return 1;

Solution:

Solution:

Page 491: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

else

n = n + recsum(n-1); /* recursive addition */

return n;

}

------------------------------------------------------------------------------------------------------------

(f) Write a C function to evaluate the seriessin(x) = x - (x3/3!) + ( x5/5!) - (x7/7!) + ........to five significant digits.

------------------------------------------------------------------------------------------------------------

(g) 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.

#include<stdio.h>#include<conio.h>void main() {

int x,y,z;char choice;void func();clrscr();

printf("Please enter values of X,Y,Z\n");scanf("%d",&x);scanf("%d",&y);scanf("%d",&z);

printf("\n\nBefore shift: X=%d Y=%d Z=%d\n",x,y,z);

func(&x,&y,&z); /* Call by reference */

printf("\n\nAfter shift: X=%d Y=%d Z=%d\n\n",x,y,z);

/* Circular Shifting continuously */

do {

printf("\nShift again(Y/N): ");scanf(" %c",&choice);

clrscr();

func(&x,&y,&z);printf("\nAfter another shift: X=%d Y=%d Z=%d\n\n",x,y,z);

}while(choice=='y');

}

void func(int *a,int *b,int *c) {

Solution:

Solution:

Page 492: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

int d,e,f;

d=*a;e=*b;f=*c;*a=f;*b=d;*c=e;

}

------------------------------------------------------------------------------------------------------------

(h) Write a function to find the binary equivalent of a given decimal integer and display it.

#include<stdio.h>#include<conio.h>void main() {

int num;void binary();

clrscr();

printf("\t\tDecimal Integer to Binary conversion\n\n\n");printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,10);printf("<%c%c%c%c%c",196,196,196,196,196);printf(" read right to left");

getch();}

void binary(int n) {

while(n!=0) {

printf("%d",n%2);

n=n/2;

}

}

------------------------------------------------------------------------------------------------------------

(i) If the lengths of the sides of a triangle are denoted by a, b, and c, then area of triangle is given byrootover ( S * (S-a) * (S-b) * (S-c))where, S = ( a + b + c ) / 2

#include<stdio.h>#include<conio.h>#include<math.h>void main() {

Solution:

Solution:

Page 493: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

int s1,s2,s3,s;int area;clrscr();

printf("enter 3 sides of triangle: \n\n");scanf("%d%d%d",&s1,&s2,&s3);

s=s1+s2+s3/2;

area=func(s1,s2,s3,s);

printf("\narea = %d",area);

getch();

}func(int i, int j, int k, int h) {

int ar,area;

ar=sqrt(h*((h-i)*(h-j)*(h-k)));

return (ar);

}

------------------------------------------------------------------------------------------------------------

(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.

------------------------------------------------------------------------------------------------------------

(k) Write a function to compute the greatest common divisor given by Euclid’s algorithm, exemplified for J = 1980, K = 1617 as follows:1980 / 1617 = 11980 – 1 * 1617 = 3631617 / 363 = 41617 – 4 * 363 = 165363 / 165 = 2363 – 2 * 165 = 335 / 33 = 5165 – 5 * 33 = 0Thus, the greatest common divisor is 33.

#include<stdio.h>#include<conio.h>void main() {

int a,b,r,d1,d2,temp;clrscr();

Solution:

Solution:

Page 494: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:05:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:02:50 PM]

Newer Posts Older PostsHome

Subscribe to: Posts (Atom)

Posted by Chetan Raikwar at 07:02 No comments:

printf("Enter first number: ");scanf("%d",&a);

printf("\n\nEnter second number: ");scanf("%d",&b);

while(b!=0) {

r=a%b;

a=b;b=r;

}

d1=a; /* devisor of first number */

temp=a;a=b;b=temp;

while(b!=0) {

r=a%b;a=b;b=r;

}

d2=a; /* devisor of second number */

printf("\n\n\nGreatest common devisor: ");

if(d1==d2) {

printf("%d",d1);

}

getch();

}______________________________________________________________________

Recommend this on Google

Simple template. Powered by Blogger.

Page 495: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 1 (Getting started)

(a) Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.

Solution:

(b) The distance between two cities (in km.) is input through the keyboard. Write a program to convert and print this distance in meters, feet, inches and centimeters.

#include<stdio.h>#include<conio.h>main() {long km,m,ft,inc,cm;clrscr();printf("Please enter the distance(in km):\n");scanf("%ld",&km);m=km*1000;ft=m*3;inc=ft*12;cm=ft*30;printf("\nDistance in kilometer = %ld\n",km);printf("\nDistance in meter = %ld\n",m);printf("\nDistance in feet = %ld\n",ft);printf("\nDistance in inches = %ld\n",inc);printf("\nDistance in centimeters = %ld\n",cm);getch();

Exercise [H]

#include<stdio.h>#include<conio.h>main() {long bs,da,hra,gs;clrscr();printf("Please enter Ramesh's Basic Salary: \n");scanf("%ld",&bs);gs=(40*bs/100)+(20*bs/100)+bs;printf("Ramesh's GROSS SALARY = %ld\n",gs);getch();return 0;} ------------------------------------------------------------------------------------------------------------

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 496: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

return 0;}

------------------------------------------------------------------------------------------------------------

(c) If the marks obtained by a student in five different subjects are input through the keyboard, find out the aggregate marks and percentage marks obtained by the student. Assume that the maximum marks that can be obtained by a student in each subject is 100.

------------------------------------------------------------------------------------------------------------

(d) Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this temperature into Centigrade degrees.

#include<stdio.h>#include<conio.h>main() {float fh,cn;clrscr();printf("Please enter the temperature in fahrenheit:\n");scanf("%f",&fh);cn=5*(fh-32)/9;printf("Centigrade Temperature = %f \n",cn);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(e) The length & breadth of a rectangle and radius of a circle are input through the keyboard. Write a program to calculate the area & perimeter of the rectangle, and the area & circumference of the circle.

Solution:

#include<stdio.h>#include<conio.h>main() {int m1,m2,m3,m4,m5,ttl;float prcnt;clrscr();printf("Please enter the marks of the student:\n");scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);ttl=m1+m2+m3+m4+m5;prcnt=ttl/5;printf("AGGREGATE MARKS = %d\nPERCENTAGE MARKS = %f%\n",ttl,prcnt);getch();return 0;}

Solution:

Solution:

#include<stdio.h>#include<conio.h>main() {float l,b,area,peri,ca,cr,r;clrscr();printf("Please enter the length of rectangle:");scanf("%f",&l);printf("\nPlease enter the breadth of rectangle:");scanf("%f",&b);area=l*b;peri=2*(l+b);

Page 497: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

(f) Two numbers are input through the keyboard into two locations C and D. Write a program to interchange the contents of C and D.

#include<stdio.h>#include<conio.h>main() {int c,d,t;clrscr();printf("Enter value of C: ");scanf("%d",&c);printf("\n\nEnter value of D: ");scanf("%d",&d);t=c;c=d;d=t;printf("\n\nC = %d\nD = %d\n",c,d);getch();}

------------------------------------------------------------------------------------------------------------

(g) If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits.(Hint: Use the modulus operator ‘%’)

#include<stdio.h>#include<conio.h>main() {long i,d1,d2,d3,d4,d5,a,b,c,d,sum;clrscr();printf("Please enter the five digit number: \n");scanf("%ld",&i);d1=i/10000;a=i%10000;d2=a/1000;b=a%1000;d3=b/100;c=b%100;d4=c/10;d=c%10;d5=d/1;sum=d1+d2+d3+d4+d5;printf("Sum of the digits is %ld\n",sum);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(h) If a five-digit number is input through the keyboard, write a program to reverse the number.

printf("\n\nAREA = %f square cm.\t PERIMETER = %f cm.\n",area,peri);printf("\n\nPlease enter the radius of the circle:");scanf("%f",&r);ca=3.14*r*r;cr=2*3.14*r;printf("\n\nAREA = %f square cm.\t CIRCUMFERENCE = %f cm.\n",ca,cr);getch();return 0;}

------------------------------------------------------------------------------------------------------------

Solution:

Solution:

Page 498: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

------------------------------------------------------------------------------------------------------------

(i) If a four-digit number is input through the keyboard, write a program to obtain the sum of the first and last digit of this number.

------------------------------------------------------------------------------------------------------------

(j) In a town, the percentage of men is 52. The percentage of total literacy is 48. If total percentage of literate men is 35 of the total population, write a program to find the total number of illiterate men and women if the population of the town is 80,000.

#include<stdio.h>#include<conio.h>main() {int i,d1,d4,a,b,c,sum;clrscr();printf("Please enter the four digit number: \n");scanf("%d",&i);d1=i/1000;

Solution:

#include<stdio.h>#include<conio.h>main() {long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();printf("Please enter the five digit number: \n");scanf("%ld",&i);d1=i/10000;a=i%10000;d2=a/1000;b=a%1000;d3=b/100;c=b%100;d4=c/10;d=c%10;d5=d/1;n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);printf("reversed number = %ld \n",n_num);getch();return 0;}

Solution:

#include<stdio.h>#include<conio.h>main() {int i,d1,d4,a,b,c,sum;clrscr();printf("Please enter the four digit number: \n");scanf("%d",&i);d1=i/1000;a=i%1000;b=a%100;c=b%10;d4=c/1;sum=d1+d4;

printf("The sum of first and last digit is %d\n",sum);getch();return 0;}

Solution:

Page 499: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

a=i%1000;b=a%100;c=b%10;d4=c/1;sum=d1+d4;printf("The sum of first and last digit is %d\n",sum);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(k) A cashier has currency notes of denominations 10, 50 and 100. If the amount to be withdrawn is input through the keyboard in hundreds, find the total number of currency notes of each denomination the cashier will have to give to the withdrawer.

#include<stdio.h>#include<conio.h>main() {int a,t_10,f_50,h_100,b,c;clrscr();printf("Please enter the amount to be withdrawn: \n");scanf("%d",&a);h_100=a/100;b=a%100;f_50=b/50;c=b%50;t_10=c/10;

printf("\nCurrency notes of 100 should be = %d\n",h_100);printf("\nCurrency notes of 50 should be = %d\n",f_50);printf("\nCurrency notes of 10 should be = %d\n",t_10);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(l) If the total selling price of 15 items and the total profit earned on them is input through the keyboard, write a program to find the cost price of one item.

#include<stdio.h>#include<conio.h>main() {int sp,p,cp;clrscr();

printf("Please enter the selling price of 15 items: \n");scanf("%d",&sp);printf("\nPlease enter the total profit of 15 items: \n");scanf("%d",&p);cp=(sp-p)/15;printf("Cost price of one item is %d\n",cp);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(m) If a five-digit number is input through the keyboard, write a program

Solution:

Solution:

Page 500: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

Posted by Chetan Raikwar at 07:01 No comments:

to print a new number by adding one to each of its digits. For example if the number that is input is 12391 then the output should be displayed as 23502.

#include<stdio.h>#include<conio.h>main() {long i,add;clrscr();printf("Please enter a five digit number: \n");scanf("%ld",&i);add=i+11111;printf("addition = %ld\n",add);getch();return 0;}

______________________________________________________________________

Solution:

Recommend this on Google

Let Us C / Chapter 12 (File Input Output)

(a) Write a program to read a file and display contents with its line numbers.

NOTE: Make a file as "DATA.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h>#include<conio.h>void main() {

FILE *fp;char i;int line=1;

clrscr();

fp=fopen("DATA.TXT","r");

if(fp==NULL) {

printf("\n\nCannot open file!");

delay(1000);exit();}

printf("%2d. ",line); /* we already print 1st for the first line */

while(i!=EOF) {

i=fgetc(fp);

printf("%c",i);

Exercise [C]

Solution:

Page 501: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

/* if the character is newline,the line number will be\printed after it */

if(i=='\n') {line++;printf("%2d. ",line);}

}

fclose(fp);getch();}

---------------------------------------------------------------------------------------------------------------

(b) Write a program to find the size of a text file without traversing it character by character.

NOTE: Make a file as "DATA.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h>#include<conio.h>#include<string.h>

void main() {

FILE *fp;char s[80],ch;int len=0;

clrscr();

fp=fopen("data.txt","r");

while(fgets(s,79,fp)!=NULL)

len=len+strlen(s); /* length of each string */ /* spaces and newlines are also counted */

fclose(fp);

printf("length of file = %d",len);

getch();}

----------------------------------------------------------------------------------------------------------------

(c) Write a program to add the contents of one file at the end of another.

NOTE: Make two file as "FILE1.TXT" and "FILE2.TXT" in bin directory and then run the program. The contents of FILE1.TXT will be appended to FILE2.TXT.

Solution:

Solution:

Page 502: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

#include<stdio.h>#include<conio.h>void main() {

FILE *f1,*f2;char ch;

clrscr();

f1=fopen("FILE1.TXT","r"); /* file to append */f2=fopen("FILE2.TXT","a+"); /* file to be appended */

if(f1==NULL || f2==NULL) {printf("\ncannot open one of files!");

exit();}

while(1) {

ch=fgetc(f1);

if(ch==EOF) {break;}

fputc(ch,f2);

}

fclose(f1);fclose(f2);

printf("\ntask completed successfully!");

getch();

}

---------------------------------------------------------------------------------------------------------------

(d) 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.

#include<stdio.h>#include<conio.h>#define N 100struct student { char name[30]; int age; };

void main() {

struct student std;struct student s[N]; /* size of array of structure defined globally for convenience */

FILE *fp;int flag=0,ch,i=0,count=0;long recsize;char another='y';void srt_print(); /* funtion to sort and print */

Solution:

Page 503: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

clrscr();

recsize=sizeof(std);

fp=fopen("STUDENT.DAT","rb+");if(fp==NULL) {fp=fopen("STUDENT.DAT","wb+");if(fp==NULL)exit();}

while(1) {

clrscr();

printf("\t\t\tStudent database\n");printf("\t\t\t****************\n\n\n");printf("\t\t\n1: Add student data\n");printf("\t\t\n2: List student data\n");printf("\t\t\n0: Exit");

gotoxy(2,24);printf("Your choice: ");scanf("%d",&ch);

switch(ch) {

case 1:

clrscr();

while(another=='y' || another=='Y') {

clrscr();

printf("\t\tAdd student data\n");printf("\t\t****************\n\n");printf("\nEnter student name: ");scanf("%s",&std.name);printf("\n\naEnter student age: ");scanf("%d",&std.age);

fseek(fp,0,SEEK_END);fwrite(&std,recsize,1,fp);

gotoxy(2,24);printf("Add another information(Y/N): ");fflush(stdin);another=getche();

}break;

case 2:

clrscr();

printf("\t\tList student data\n");printf("\t\t*****************\n\n");rewind(fp);while(fread(&std,recsize,1,fp)==1) {s[i]=std;flag=1;i++;count++;}

srt_print(&s,count); /* function to print names */

if(flag==0) {

Page 504: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

printf("\n\n\nNo data found!\n");

}printf("\n\n\npress any key to return...");getch();

break;

case 0:

fclose(fp);exit();

default:

printf("wrong input!\n");exit();

}

}

}/******** main ends ************/

/**** sorting and printing function ****/void srt_print(struct student *ss, int n) {

struct student temp;int i,j;

for(i=0;i<=n;i++) {

for(j=i+1;j<n;j++) {

/* checking first alphabets of both names */

if(ss[i].name[0] > ss[j].name[0]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;}

/* if first alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1] > ss[j].name[1]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;

}

/* if first 2 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2] > ss[j].name[2]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;

Page 505: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

}}

/* if first 3 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2]==ss[i].name[2]) {

if(ss[i].name[3] > ss[j].name[3]) {

temp=ss[i];ss[i]=ss[j];ss[j]=ss[i];}}}

/* if first four 4 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2]==ss[j].name[2] && ss[i].name[2]==ss[j].name[2]) {

if(ss[i].name[3]==ss[j].name[3]) {

if(ss[i].name[4] > ss[j].name[4]) {

temp=ss[i];ss[i]=ss[j];ss[j]=ss[i];

} } } }

}}

/* printing sorted list */

for(i=0;i<n;i++) {

printf("\n%10s\t\t%2d\n",ss[i].name,ss[i].age);

}

}

--------------------------------------------------------------------------------------------------------------

(e) Write a program to copy one file to another. While doing so replace all lowercase characters to their equivalent uppercase characters.

NOTE: Make a file as "FILE.TXT" in bin directory and write/paste some text in it. then run the program and you will receive another file as "RESULT.TXT" with uppercase letters.

#include<stdio.h>#include<conio.h>

Solution:

Page 506: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

void main() {

FILE *fr,*fw;char a[1000];char ch,upr;clrscr();

fr=fopen("SOURCE.TXT","r");

if(fr==NULL) {printf("cannot open source file!\n");

}

fw=fopen("RESULT.TXT","w");

if(fw==NULL) {printf("cannot open target file!\n");

}

while(1) {

ch=fgetc(fr);

if(ch==EOF)break;

else {

if(ch>=97 && ch<=122) {

ch=ch-32;

}

fputc(ch,fw);}

}fclose(fr);fclose(fw);

printf("Task completed!");getch();}

----------------------------------------------------------------------------------------------------------------

(f) 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.

----------------------------------------------------------------------------------------------------------------

(g) 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 cornerco-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

Solution:

Page 507: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

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.

#include<stdio.h>#include<conio.h>#include<string.h>#include<types.h>#include<stat.h>#include<fcntl.h>

void box();void print();

void main() {

int inhandle,bytes,pg=1;FILE *fp;char source[80],buffer[1400];

clrscr();

printf("Enter file name: ");gets(source);

inhandle=open(source, O_RDONLY);

if(inhandle==-1) {

printf("cannot open file!");exit();

}

clrscr();

while(1) {

bytes=read(inhandle,buffer,1387);

if(bytes>0) {

gotoxy(32,1); /* showing filename */printf("%s",strupr(source));

gotoxy(70,1);printf("Pg: %3d",pg); /* showing page number */

box(); /* passing the heading and page number to the function */

print(buffer); /* passing the buffer to the function */

}

else {

gotoxy(70,1);printf("Pg: %3d",pg);break;}

++pg;}

close(inhandle);

Solution:

Page 508: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

getch();}

/********************************//* function to print the buffer *//********************************/

void print(char s[1400]) {

int x=4,y=3,i=0;

while(s[i]!=EOF) {

gotoxy(x,y);printf("%c",s[i]);

if(x>74) {

x=4;y+=1;

}

if(y>21) {

gotoxy(2,24);printf("press any key to go to next page...");

x=4;y=3;

getch();

clrscr();box();}

x++;i++;

}

}

/****************************//* function to draw the box *//****************************/

void box() {

int i,j;

for(i=2;i<=77;i++) {

gotoxy(i,2);printf("%c",196);

gotoxy(i,23);printf("%c",196);

}

for(j=3;j<=22;j++) {

gotoxy(2,j);

Page 509: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

printf("%c",179);

gotoxy(77,j);printf("%c",179);

}

gotoxy(77,23);printf("%c",217);

gotoxy(77,2);printf("%c",191);

gotoxy(2,23);printf("%c",192);

gotoxy(2,2);printf("%c",218);

}

----------------------------------------------------------------------------------------------------------------

(h) Write a program to encrypt/decrypt a file using:(1) 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.(2) A substitution cipher: In this each character read from the source file is substituted by a corresponding predetermined character and this character is written to the target file.For example, if character ‘A’ is read from the source file, and if we have decided that every ‘A’ is to be substituted by ‘!’, then a ‘!’ would be written to the target file in place of every ‘A’ Similarly, every ‘B’ would be substituted by ‘5’ and so on.

Offset cipher Encryption:

#include<stdio.h>#include<conio.h>

void main() { /* offset cipher encryption */

/* every character has been added to 128 and the new value has beenwritten */

FILE *fp,*ft;char ch;

clrscr();

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");exit();}

while(1) {

ch=fgetc(fp);

Solution:

Page 510: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

if(ch==EOF)break;

ch=ch+128; /* offset cipher encryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();}

Offset cipher Decryption:

#include<stdio.h>#include<conio.h>void main() { /* offset cipher decryption */

FILE *fp,*ft;char ch;

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");

exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

ch=ch-128; /* decryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();

}

Substitution cipher encryption:

Page 511: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

#include<stdio.h>#include<conio.h>

void main() { /* substitution cipher encryption */

/* all vowels have been exchanged with first five ascii characters and every space has been converted to 6th ascii character */

FILE *fp,*ft;char ch;

clrscr();

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

encrypt(&ch); /* function for encryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();}encrypt(char *c) {

if(*c=='a') {*c='!';}

if(*c=='e') {*c='@';}

if(*c=='i') {*c='#';}

if(*c=='o') {*c='$';}

if(*c=='u') {*c='%';}

if(*c==' ') {*c='^';}

Page 512: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

return *c;}

Substitution cipher Decryption:

#include<stdio.h>#include<conio.h>void main() {

/* substitution cipher's decryption */

FILE *fp,*ft;char ch;

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");

exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

decrypt(&ch); /* function for decryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();

}

decrypt(char *c) {

if(*c=='!')*c='a';

if(*c=='@')*c='e';

if(*c=='#')*c='i';

if(*c=='$')*c='o';

if(*c=='%')*c='u';

if(*c=='^')*c=' ';

Page 513: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

return *c;

}----------------------------------------------------------------------------------------------------------------

(i) 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.

NOTE: If on withdrawal, the balance subtracts to less than 100. The withdrawal will not be performed.

#include<stdio.h>#include<conio.h>void main() {

struct customer { int accno; char name[30]; float balance; }cust;struct trans { int accno; char trans_type; float amount; }tra;FILE *fp,*ft,*ftemp;int flag=0;long recsize,retsize;char another,ch;clrscr();

fp=fopen("CUSTOMER.DAT","rb+");

if(fp==NULL) {

fp=fopen("CUSTOMER.DAT","wb+");

if(fp==NULL)

Solution:

Page 514: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

printf("cannot open customer data file!\n");

exit();

}

ft=fopen("TRANSACTIONS.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTIONS.DAT","wb+");

if(ft==NULL)

printf("cannot open transactions file!\n");

exit();

}

recsize=sizeof(cust);retsize=sizeof(tra);

while(1) {

clrscr();

printf("\t\tCutomer Transactions:\n");printf("\t\t*********************\n\n\n");printf("\t1: Add customer information:\n\n");printf("\t2: Add transaction information:\n\n");printf("\t3: List customer information:\n\n");printf("\t4: List transaction information:\n\n");printf("\t5: Perform transaction:\n\n");printf("\t0: Exit:\n\n\n");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd customer information:\n");printf("\t\t*************************\n\n");printf("\nEnter account number: ");scanf("%d",&cust.accno);printf("\n\nEnter name: ");scanf("%s",cust.name);printf("\n\nEnter balance: ");fflush(stdin);scanf("%f",&cust.balance);

fwrite(&cust,recsize,1,fp);

gotoxy(2,24);printf("Add another customer information(Y/N): ");another=getche();

Page 515: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

clrscr();

}break;

case '2':

clrscr();

fseek(ft,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd transaction information:\n");printf("\t\t****************************\n\n\n");printf("Enter existing customer account number: ");scanf("%d",&tra.accno);printf("\n\nEnter transaction type(D/W): ");fflush(stdin);scanf("%c",&tra.trans_type);printf("\n\nEnter amount for transaction: ");fflush(stdin);scanf("%f",&tra.amount);

fwrite(&tra,retsize,1,ft);

gotoxy(2,24);printf("Enter another information(Y/N): ");another=getche();

clrscr();}break;

case '3':

clrscr();

printf("\t\tList customer information:\n");printf("\t\t**************************\n\n");

rewind(fp);while(fread(&cust,recsize,1,fp)==1) {printf("\n%5d\t%-8s\t%5.2f\n",cust.accno,cust.name,cust.balance);flag=1;}

if(flag==0) {gotoxy(2,12);printf("No customer information found!\n");}printf("\n\npress any key to go back...");getch();

break;

case '4':

clrscr();

printf("\t\tList transaction information:\n");printf("\t\t*****************************\n\n");

rewind(ft);while(fread(&tra,retsize,1,ft)==1) {printf("\n%5d\t%c\t%6.2f\n",tra.accno,tra.trans_type,tra.amount);flag=1;}

Page 516: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

if(flag==0) {gotoxy(2,12);printf("No transaction information found!\n");}

printf("\n\npress any key to go back...");getch();

break;

case '5':

clrscr();

printf("\t\tPerform transactions\n");printf("\t\t********************\n\n");

rewind(fp);

while(fread(&cust,recsize,1,fp)==1) {

rewind(ft);

while(fread(&tra,retsize,1,ft)==1) {

if(cust.accno==tra.accno) {

flag=1;

if(tra.trans_type=='D' || tra.trans_type=='d') {

cust.balance+=tra.amount;

fseek(fp,-recsize,SEEK_CUR);fwrite(&cust,recsize,1,fp);

}

else if(tra.trans_type=='W' || tra.trans_type=='w') {

if((cust.balance-tra.amount)>=100) {

cust.balance-=tra.amount;

fseek(fp,-recsize,SEEK_CUR);fwrite(&cust,recsize,1,fp);

}

}

}}}

fclose(ft);

ftemp=fopen("TEMP.DAT","rb+");

if(ftemp==NULL) {

ftemp=fopen("TEMP.DAT","wb+");

}

remove("TRANSACTIONS.DAT");rename("TEMP.DAT","TRANSACTIONS.DAT");

ft=fopen("TRANSACTIONS.DAT","rb+");

Page 517: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

if(ft==NULL) {

ft=fopen("TRANSACTIONS.DAT","wb+");

}

if(flag==0) {

gotoxy(2,12);printf("No active transactions\n");

}

else if(flag>0) {

gotoxy(2,12);printf("Transactions performed seccussfully!\n");gotoxy(2,14);printf("NOTE: withdrawl for low balance accounts has not been performed\n");

}gotoxy(2,24);printf("press any key to return...");getch();

break;

case '0':

fclose(fp);fclose(ft);exit();

}}

}

---------------------------------------------------------------------------------------------------------------

(j) 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.

----------------------------------------------------------------------------------------------------------------

(k) A hospital keeps a file of blood donors in which each record has the format:Name: 20 Columns

Solution:

Page 518: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

Address: 40 ColumnAge: 2 ColumnsBlood Type: 1 Column (Type 1, 2, 3 or 4)Write a program to read the file and print a list of all blood donors whose age is below 25 and blood is type 2.

/* This program will make a file of blood donors and save information in it */

/* Writing program */

#include<stdio.h>#include<conio.h>void main() {

FILE *fp;char another='y';

struct blood { char name[50]; char adr[50]; int age; int bld; } b;

clrscr();

fp=fopen("BLOODBANK.DAT","wb");

if(fp==NULL) {printf("cannot open target file!\n");exit();}

while(another=='Y' || another=='y') {

clrscr();printf("\t\tInformation of Blood donor\n");printf("\t\t**************************\n\n\n");printf("Enter the name: ");scanf("%s",b.name);printf("\n\nenter the address: ");scanf("%s",b.adr);printf("\n\nenter the age: ");scanf("%d",&b.age);printf("\n\nenter the blood group(1/2/3/4): ");scanf("%d",&b.bld);

fprintf(fp,"%s\t%s\t%d\t%d",b.name,b.adr,b.age,b.bld);

printf("\n\n\nenter more information(Y/N): ");fflush(stdin);

another=getch();

}

fclose(fp);

}

Solution:Program to creat record file of blood donors

Program to read record file for specifications

Page 519: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

/* This program will read the information from the file made by writing program */

/* Reading Program */

#include<stdio.h>#include<conio.h>void main() {

FILE *fp;char ch;

struct blood { char name[50]; char adr[50]; int age; int bld; }b;clrscr();

fp=fopen("BLOODBANK.DAT","rb");

if(fp==NULL) {printf("cannot open source file!\n\n");exit();}

while(fscanf(fp,"%s\t%s\t%d\t%d",&b.name,&b.adr,&b.age,&b.bld)!=EOF)if(b.age<25 && b.bld==2) {printf("\n%s\t %s\t%2d\t %d",b.name,b.adr,b.age,b.bld);}fclose(fp);

getch();}

----------------------------------------------------------------------------------------------------------------

(l) Given a list of names of students in a class, write a program to store the names in a file on disk. Make a provision to display the nth name in the list (n is data to be read) and to display all names starting with S.

#include<stdio.h>#include<conio.h>void main() {

struct name { int sn; char name[30]; }s;int i,num,flag=0;long recsize;char another,ch;FILE *fp;clrscr();

fp=fopen("NAMES.DAT","rb+");

if(fp==NULL) {

fp=fopen("NAMES.DAT","wb+");

if(fp==NULL)

printf("cannot open file! \n");exit();}

Solution:

Page 520: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

recsize=sizeof(s);

while(1) {

clrscr();printf("\t\tStudent Names:\n");printf("\t\t**************\n\n\n");printf("\t1: Add names of students:\n\n");printf("\t2: Search a student name:\n\n");printf("\t3: List all student names:\n\n");printf("\t4: List all names starting with 'S':\n\n");printf("\t0: Exit\n\n");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd names of students:\n");printf("\t\t**********************\n\n");printf("Enter student number: ");scanf("%d",&s.sn);printf("\n\nEnter student name: ");scanf("%s",s.name);

fwrite(&s,recsize,1,fp);

gotoxy(2,24);printf("Enter another name(Y/N): ");fflush(stdin);another=getche();

clrscr();}break;

case '2':

clrscr();

printf("\t\tSearch a student name:\n");printf("\t\t**********************\n\n");printf("Enter student number: ");scanf("%d",&num);

rewind(fp);

while(fread(&s,recsize,1,fp)==1) {

if(s.sn==num) {

printf("\n\nStudent Number: %5d\n\n",s.sn);printf("Student name: %s\n\n",s.name);

flag=1;

Page 521: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

break;} }

if(flag==0) {printf("\n\n\nNo such name found!\n");}gotoxy(2,24);printf("press any key to return...\n");getch();

break;

case '3':

clrscr();

printf("\t\tList all student names\n");printf("\t\t**********************\n\n\n");

rewind(fp);

while(fread(&s,recsize,1,fp)==1) {printf("\n%5d\t%-10s\n",s.sn,s.name);flag=1;}

if(flag==0) {printf("\n\n\nNo name found!\n");}

printf("\n\n\npress any key to return...\n");getch();break;

case '4':

clrscr();

printf("\t\tAll name starting with 'S':\n");printf("\t\t***************************\n\n\n");

rewind(fp);while(fread(&s,recsize,1,fp)==1) {

if(strncmp('s',s.name[0])==0) { /* comparing only first character of \ name if it is "s" */printf("\n%5d\t%-10s\n",s.sn,s.name);flag=1;}}

if(flag==0) {printf("\n\n\nNo name starting with \'S\' found!\n");}

printf("\n\n\npress any key to return...\n");getch();break;

case '0':

fclose(fp);exit();

} }

}

Page 522: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

----------------------------------------------------------------------------------------------------------------

(m) Assume that a Master file contains two fields, Roll no. and name of the student. At the end of the year, a set of students join the class and another set leaves. A Transaction file contains the roll numbers and an appropriate code to add or delete a student.Write a program to create another file that contains the updated list of names and roll numbers. Assume that the Master file and the Transaction file are arranged in ascending order by roll numbers. The updated file should also be in ascending order by roll numbers.

Note:- This program ( all the 3 ) are ideally for single. After you have ran it once, check the results and delete the updated list file before running it again. Assign roll number in ascending orders by roll numbers. And process data according to ascending nature.

1- first program will let you save data in masterfile.2- second program will let you add or delete data and will generate an updated list in text mode.3- obtain the updated list and check it ( assuming you have processed data as instructed).

1. program to creat master file.

#include<stdio.h>#include<conio.h>#include<string.h>

void main() {

FILE *fp;struct student { int rl; char name[50]; }s;char ch,another;clrscr();

fp=fopen("MASTERFILE.DAT","rb+");

if(fp==NULL) {

fp=fopen("MASTERFILE.DAT","wb+");

if(fp==NULL)puts("cannot open master file!");exit();}

while(1) {

clrscr();

gotoxy(30,2);printf("Masterfile\n");gotoxy(30,3);printf("**********\n\n\n");gotoxy(20,6);printf("1: Enter student data: ");gotoxy(20,8);printf("2: Read student data: ");gotoxy(20,10);printf("0: Exit: ");

Solution:

Page 523: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

clrscr();

gotoxy(2,24);printf("NOTE: assign roll numbers in ascending order");gotoxy(20,5);printf("Enter roll number: ");scanf("%d",&s.rl);

gotoxy(20,7);printf("Enter name: ");fflush(stdin);gets(s.name);

fwrite(&s,sizeof(s),1,fp);

gotoxy(20,10);printf("Add more data(Y/N): ");fflush(stdin);

another=getche();

}

break;

case '2':

clrscr();

gotoxy(30,2);printf("Student data");gotoxy(30,3);printf("************\n\n");

rewind(fp);

while(fread(&s,sizeof(s),1,fp)==1) {

printf("\n%d\t%s\n",s.rl,s.name);

}

printf("\n\npress any key to return...");getch();

break;

case '0':

fclose(fp);exit();

Page 524: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

}}

}

2. program to creat transaction file and generate updated list

#include<stdio.h>#include<conio.h>#include<string.h>#define N 100

void main() {

FILE *ft,*fu,*fm,*ftemp;

struct student { int rl; char name[50]; }s,ss[N],temp;

struct transaction { char stats; int rl; char name[50]; }t;

int flag=0;char ch,another;clrscr();

fm=fopen("MASTERFILE.DAT","rb+");

if(fm==NULL) {

printf("Masterfile doesn't exist!");

}

ft=fopen("TRANSACTION.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTION.DAT","wb+");

if(ft==NULL)puts("cannot open transactions file!");exit();}

fu=fopen("UPDATELIST.TXT","w+");

if(fu==NULL) {

puts("cannot open target file!");exit();}

while(1) {

clrscr();

gotoxy(30,2);printf("Transaction-File\n");

Page 525: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

gotoxy(30,3);printf("****************\n\n\n");gotoxy(20,6);printf("1: ADD/DELETE student data from master list: ");gotoxy(20,8);printf("2: Read transaction data: ");gotoxy(20,10);printf("3: Creat updated list: ");gotoxy(20,12);printf("0: Exit:");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(ft,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

clrscr();

gotoxy(2,23);printf("NOTE: data to be deleted should match master list");gotoxy(2,24);printf("NOTE: data to be added should follow the ascending nature of master list");gotoxy(20,5);printf("ADD/DELETE student(A/D): ");scanf("%c",&t.stats);gotoxy(20,7);printf("Enter roll number: ");scanf("%d",&t.rl);gotoxy(20,9);printf("Enter name: ");fflush(stdin);gets(t.name);

fwrite(&t,sizeof(t),1,ft);

gotoxy(20,12);printf("Add more data(Y/N): ");fflush(stdin);

another=getche();

}

break;

case '2':

clrscr();

gotoxy(30,2);printf("Student data");gotoxy(30,3);printf("************\n\n");

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

Page 526: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

printf("\n");

if(t.stats=='a' || t.stats=='A') {printf("ADD");}

else {printf("DELETE");}printf("\t%d\t%s\n",t.rl,t.name);

}

printf("\n\npress any key to return...");getch();

break;

case '3':

clrscr();

gotoxy(30,2);printf("make updated list");gotoxy(30,3);printf("*****************\n\n");

rewind(fm);

while(fread(&s,sizeof(s),1,fm)==1) {

flag=0;

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

if(t.rl==s.rl ) {

if(t.stats=='d' || t.stats=='D') {flag=1;}

}

}

if(flag==0)

fprintf(fu,"\n%d\t%-s\n",s.rl,s.name);

}

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

if(t.stats=='a' || t.stats=='A') {

fprintf(fu,"\n%d\t%-s\n",t.rl,t.name);

}

}

ftemp=fopen("TEMP.DAT","wb+");

fclose(ftemp);

Page 527: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

fclose(ft);

remove("TRANSACTION.DAT");rename("TEMP.DAT","TRANSACTION.DAT");

ft=fopen("TRANSACTION.DAT","rb+");

gotoxy(2,24);printf("press any key to continue...");getch();

break;case '0':

fclose(fm);fclose(ft);fclose(fu);exit();

}}

}

-----------------------------------------------------------------------------------------------------------------

(n) In a small firm employee numbers are given in serial numerical order, that is 1, 2, 3, etc.− Create a file of employee data with following information: employee number, name, sex, gross salary.− If more employees join, append their data to the file.− If an employee with serial number 25 (say) leaves, delete the record by making gross salary 0.− If some employee’s gross salary increases, retrieve the record and update the salary.Write a program to implement the above operations.

#include<stdio.h>#include<conio.h>void main() {

struct emp { int empno; char name[30]; char sex; float gs; } e;FILE *fp,*ft;int long recsize;int empn,flag=0;float new_sal;char another,ch;clrscr();

recsize=sizeof(e);

fp=fopen("EMP.DAT","rb+");

if(fp==NULL) {

fp=fopen("EMP.DAT","wb+");if(fp==NULL)

Solution:

Page 528: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

exit();

}

while(1) {

clrscr();

printf("\t\tEmployee database management\n");printf("\t\t****************************\n");printf("\n\n\t1: Add another employee: ");printf("\n\n\t2: Add salary information of employee: ");printf("\n\n\t3: List all records: ");printf("\n\n\t4: Delete employee with 0 salary: ");printf("\n\n\t0: Exit:");

gotoxy(2,24);printf("your choice: ");fflush(stdin);ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END); /* seeking cursor to reach at the end of file */

another='Y';

while(another=='Y' || another=='y') {

printf("\n\tEnter new employee information\n");printf("\t******************************\n\n\n");

printf("\nEnter employee number: ");scanf("%d",&e.empno);

printf("\n\nEnter employee name: ");scanf("%s",e.name);

printf("\n\nEnter sex(M/F/O): ");scanf(" %c",&e.sex);

printf("\n\nEnter gross salary: ");scanf("%f",&e.gs);

/* writing new information at the end of file */

fwrite(&e,recsize,1,fp);

printf("\n\n\n\nAdd another employee(Y/N): ");fflush(stdin);another=getche();

clrscr();

}

break;

case '2':

clrscr();

another='Y';

while(another=='Y' || another=='y') {

printf("\n\tEnter salary information\n");

Page 529: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

printf("\t************************\n\n");

gotoxy(2,23); /* showing message at the bottom of the screen */

printf("NOTE: to delete an employee, mark his/her salary 0\n");printf(" then use option 4 from main menu.");

gotoxy(3,5); /* returning cursor back from the bottom */printf("Enter employee number: ");scanf("%d",&empn); /* asking for employee number to search */

rewind(fp);

while(fread(&e,recsize,1,fp)==1) {

if(e.empno-empn==0) { /* if employee number matches with structure */

flag=1; /* condition indicator for printing further messages */

printf("\n\nEnter new salary for employee: ");

scanf("%f",&e.gs);

e.empno=e.empno; /* rest information should be same except only\ salary */e.sex=e.sex;

e.name[30]=e.name[30];

fseek(fp,-recsize,SEEK_CUR); /* seeking the correct location of data within\ structure in the file */fwrite(&e,recsize,1,fp); /* writing data at correct position */

break;

}}

if(flag==0) /* conditional indicator used above */printf("\n\n\n\tinformation does not exist!\n");

printf("\n\nenter another information(Y/N): ");another=getche();

clrscr();

}

break;

case '4':

clrscr();

printf("\n\n\tDelete employee\n");printf("\t***************\n\n");

ft=fopen("TEMP.DAT","w"); /* opening new temporary file */

rewind(fp); /* taking cursor back to the very beginning of file */

while(fread(&e,recsize,1,fp)==1) { /* matching each salary */

if(e.gs!=0.0 || e.gs!=0) { /* if salary is not 0 then data will be written to new file */

flag=1;

Page 530: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

fwrite(&e,recsize,1,ft);

}}fclose(fp);fclose(ft);

remove("EMP.DAT"); /* removing original file with 0 salary and renaming\ temporary without 0 salary as the original file */

rename("TEMP.DAT","EMP.DAT");

fp=fopen("EMP.DAT","rt+"); /* opening the new file, it opens because it has not been opened before */ /* a file cannot be opened twice during execution as you know */

if(flag>0) {printf("\n\n\nall records with 0 gross salary have been deleted. \n");}

gotoxy(2,24);printf("\n\n\npress any key to return...");getch();

break;

case '0':

fclose(fp);exit();

case '3':

clrscr();

printf("\t\tList all employees\n");printf("\t\t******************\n\n\n");

rewind(fp);

while(fread(&e,recsize,1,fp)==1) {

flag=1;

printf("%2d\t%6s\t%c\t%.2f\n\n",e.empno,e.name,e.sex,e.gs);

}

if(flag==0)

printf("\n\n\tNo records exist!\n\n");

printf("\n\npress any key to return... ");

getch(); /* this is very important place, if we don't stop screen here \ after reading and printing the list,we won't be able to see it and it will disappear and will return to main menu because of "break" statement. */break;

} }

}linkfloat() { /* function to avoid possible errors because of floats */float a=0,*b;b=&a;a=*b;

Page 531: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

return 0;}

-----------------------------------------------------------------------------------------------------------------

(o) Given a text file, write a program to create another text file deleting the words “a”, “the”, “an” and replacing each one of them with a blank space.

NOTE: Make a file "FILE.TXT" in bin directory and write/paste something in it, then run the program, you will get another file as "NEW.TXT" as result of the program.

#include<stdio.h> #include<conio.h> #include<string.h>

void replace();

void main() {

FILE *fp,*ft; char str[80],target[80]; clrscr();

fp=fopen("FILE.TXT","r");

if(fp==NULL) {

puts("cannot open source file!"); exit(); }

ft=fopen("NEW.TXT","w");

if(ft==NULL) {

puts("cannot open target file!"); exit(); }

while(fgets(str,79,fp)!=NULL) {

replace(str,&target);

fputs(target,ft);

}

fclose(fp); fclose(ft);

printf("\nTask completed!"); getch();

}

void replace(char *s, char *s1) {

int i=0,j=0,k=0; char temp[100],temp2[100],main[100],*t=temp,*m=main;

Solution:

Page 532: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

/* 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,"the")==0) {

strcpy(temp2," "); }

else if(strcmpi(temp2,"an")==0) {

strcpy(temp2," ");

}

else if(strcmpi(temp2,"a")==0) {

strcpy(temp2," ");

}

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,"the")==0){ /* checking last word too */

Page 533: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

strcpy(temp2," "); }

else if(strcmpi(temp2,"an")==0) {

strcpy(temp2," "); }

else if(strcmpi(temp2,"a")==0) {

strcpy(temp2," "); }

/***************************/ /* 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 */

}

while(*m!='\0') {

*s1=*m;

s1++; m++;

}

*s1='\0';

}

-----------------------------------------------------------------------------------------------------------------

(p) You are given a data file EMPLOYEE.DAT with the following record structure:struct employee {int empno ;char name[30] ;int basic, grade ;} ;Every employee has a unique empno and there are supposed to be no gaps between employee numbers. Records are entered into the data file in ascending order of employee number, empno. It is intended to check whether there are missing employee numbers. Write a program segment to read the data file records sequentially and display the list of missing employee numbers.

NOTE: assign employee numbers in ascending order only.Solution:

Page 534: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

#include<stdio.h> #include<conio.h> void main() {

struct employee { int empno; char name[30]; int basic,grade; }e; FILE *fp; int num=0; long recsize; char another,ch; clrscr();

fp=fopen("EMPLOYEE.DAT","rb+"); if(fp==NULL) { fp=fopen("EMPLOYEE.DAT","wb+");

if(fp==NULL) exit(); }

recsize=sizeof(e);

while(1) {

clrscr();

printf("\t\tEmployee number database:\n"); printf("\t\t*************************\n\n"); printf("\n\t1: Add employee information:\n"); printf("\n\t2: List employee information:\n"); printf("\n\t3: Check missing employee numbers:\n"); printf("\n\t0: Exit:\n\n");

gotoxy(2,24); printf("your choice: "); fflush(stdin); ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd employee information:\n"); printf("\t\t*************************\n\n");

printf("Note: employee numbers should be given in ascending order\n\n");

printf("\nEnter employee number: "); scanf("%d",&e.empno); printf("\n\nEnter employee name: "); scanf("%s",e.name); printf("\n\nEnter employee basic salary: "); scanf("%d",&e.basic); printf("\n\nEnter employee grade(1/2/3): ");

Page 535: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

scanf("%d",&e.grade);

fwrite(&e,recsize,1,fp);

gotoxy(2,24); printf("Add another employee information(Y/N): "); fflush(stdin); another=getche();

clrscr();

}

break;

case '2':

clrscr();

printf("\t\tList employee information:\n"); printf("\t\t**************************\n\n\n");

rewind(fp); while(fread(&e,recsize,1,fp)==1) {

printf("\n%3d\t%8s\t%5d\t%d\n",e.empno,e.name,e.basic,e.grade);

}

printf("\n\npress any key to return...\n"); getch();

break;

case '3':

clrscr();

printf("\t\tMissing employee numbers:\n"); printf("\t\t*************************\n\n");

rewind(fp); while(fread(&e,recsize,1,fp)==1) { num=e.empno; /* assigning the value of first employee number */ break; }

rewind(fp); /* again rewinding the file to read from beginning */

while(fread(&e,recsize,1,fp)==1) {

if(num!=e.empno) { /* if assigned number is smaller than employee number we will print all the number between them */ while(num<e.empno) {

printf("%4d ",num);

num++; } num=e.empno+1;

}

/* we will assign greater value than employee number to make sure that both don't match until another greater employee number is found */

else

num=e.empno+1;

Page 536: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

}

printf("\n\n press any key to return..."); getch();

break;

case '0':

fclose(fp); exit();

} } }

-----------------------------------------------------------------------------------------------------------------

(q) Write a program to carry out the following:− To read a text file “TRIAL.TXT” consisting of a maximum of 50 lines of text, each line with a maximum of 80 characters.− Count and display the number of words contained in the file.− Display the total number of four letter words in the text file.Assume that the end of a word may be a space, comma or a full-stop followed by one or more spaces or a newline character.

NOTE: Make a file "TRIAL.TXT" in bin directory and write something in it ,then run the program.

#include<stdio.h> #include<conio.h> void main() {

FILE *fp; char s[80]; int twd,fwd,tw=0,fw=0;void word(); clrscr();

fp=fopen("TRIAL.TXT","r"); if(fp==NULL) {

exit(); }

while(fgets(s,79,fp)!=NULL) { word(s,&twd,&fwd); tw=tw+twd; fw=fw+fwd; }

fclose(fp);

printf("\nTotal number of words in text file = %d\n",tw); printf("\n\nTotal number of 4 letter words = %d\n",fw);

getch(); }

void word(char ss[80],int *tw, int *fw) {

Solution:

Page 537: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

int i=0,tot_wd=0,tot_4_wd=0;

while(ss[i]!='\0') {

/************************/ /* to cound total words */ /************************/

if(ss[i]>=65 && ss[i]<=90 || ss[i]>=97 && ss[i]<=122) {

if(ss[i+1]==' ' || ss[i+1]=='.' || ss[i+1]==',' || ss[i+1]=='\n' ) {

tot_wd++; } }

/*********************************/ /* to count total 4 letter words */ /*********************************/

if(ss[i]==' ' || ss[i]==',' || ss[i]=='.') {

if(ss[i+1]>=65 && ss[i+1]<=90 || ss[i+1]>=97 && ss[i+1]<=122) {

if(ss[i+2]>=65 && ss[i+2]<=90 || ss[i+2]>=97 && ss[i+2]<=122) {

if(ss[i+3]>=65 && ss[i+3]<=90 || ss[i+3]>=97 && ss[i+3]<=122) {

if(ss[i+4]>=65 && ss[i+4]<=90 || ss[i+4]>=97 && ss[i+4]<=122) {

if(ss[i+5]==' ' || ss[i+5]==',' || ss[i+5]=='.' || ss[i+5]=='\n') {

tot_4_wd++; } } } } } }

if(ss[i]>=65 && ss[i]<=90 || ss[i]>=97 && ss[i]<=122) {

if(ss[i+1]>=65 && ss[i+1]<=90 || ss[i+1]>=97 && ss[i+1]<=122) {

if(ss[i+2]>=65 && ss[i+2]<=90 || ss[i+2]>=97 && ss[i+2]<=122) {

if(ss[i+3]>=65 && ss[i+3]<=90 || ss[i+3]>=97 && ss[i+3]<=122) {

if(ss[i+4]==' ' || ss[i+4]==',' || ss[i+4]=='.' || ss[i+4]=='\n') {

} } } } }

i++;

}

*tw=tot_wd; *fw=tot_4_wd;

}

-----------------------------------------------------------------------------------------------------------------

Page 538: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

(r) Write a program to read a list of words, sort the words in alphabetical order and display them one word per line. Also give the total number of words in the list. Output format should be:Total Number of words in the list is _______Alphabetical listing of words is:-----------Assume the end of the list is indicated by ZZZZZZ and there are maximum in 25 words in the Text file.

NOTE: Make a file as "trial.txt" in bin directory and write some words in it. Words should be in the form of a list. One below another,then run the program.

#include<stdio.h>#include<conio.h>#define N 100

/* make a list of words, every words should be written under previous one to make sure it's a list of words. */

/* upper case letters will be arranged before small case letter, so it is recommended to use the list of either Capital letter or small case letters but not both together. */struct word { char wrd [30]; };

void main() {

struct word w[N];

FILE *fp;char s1[30];int i=0,count=0;void srt_wrd(); /* function to sort and print list */

clrscr();

fp=fopen("TRIAL.TXT","rb+");

while(fgets(s1,30,fp)!=NULL) {strcpy(w[i].wrd,s1); /* copying each word in array of structure */i++;count++; /* count of all the words */}

printf("Total words if file = %3d\n",count);

printf("\t\tList in alphabetical order:\n");srt_wrd(&w,count); /* function for sorting and printing list */

fclose(fp);getch();

}

void srt_wrd( struct word *w, int n) {

int i,j,k=0;struct word temp;

Solution:

Page 539: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

/***************************************//* sorting words in alphabetical order *//***************************************/

for(i=0;i<=n;i++) {

for(j=i+1;j<n;j++) {

/* testing the first alphabets of two words */

if(w[i].wrd[0] > w[j].wrd[0]) {

temp=w[i];w[i]=w[j];w[j]=temp;}

/* testing the first two alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1] > w[j].wrd[1]) {

temp=w[i];w[i]=w[j];w[j]=temp;}

/* testing first three alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]>w[j].wrd[2]) {

temp=w[i];w[i]=w[j];w[j]=temp;}}

/* testing first four alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]==w[j].wrd[2] && w[i].wrd[3]>w[j].wrd[2]) {

temp=w[i];w[i]=w[j];w[j]=temp;}}

}}

/*****************************//* printing the sorted words *//*****************************/

for(i=0;i<n;i++) {

printf("%-s\n",w[i].wrd);

k++;

if(k==10) {

printf("\n\npress any key to go to next page...");getch();

Page 540: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

k=1;clrscr();}}

}

--------------------------------------------------------------------------------------------------------------

(s) Write a program to carry out the following:(a) Read a text file ‘INPUT.TXT’(b) Print each word in reverse orderExample,Input: INDIA IS MY COUNTRYOutput: AIDNI SI YM YRTNUOCAssume that each word length is maximum of 10 characters and each word is separated by newline/blank characters.

NOTE: Make a file "INPUT.TXT" in bin directory and write something in it, then run the program.

#include<stdio.h>#include<conio.h>#include<string.h>

void main() {

FILE *fs;char s[80];void rev();

clrscr();

fs=fopen("INPUT.TXT","r");

if(fs==NULL) {

printf("cannot open file!");exit();}

while(fgets(s,79,fs)!=NULL)rev(s);

fclose(fs);

getch();

}

void rev(char s1[80]) {

char s2[80];int i=0,j=0;

while(s1[i]!='\0') {

s2[j]=s1[i];

if(s1[i]==' ' || s1[i]=='\0') {

s2[j]='\0';

Solution:

Page 541: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

strrev(s2);

printf("%s ",s2);

j=-1;

}

i++;j++;}

s2[j]='\0';

printf("%s",strrev(s2));

}

-----------------------------------------------------------------------------------------------------------------

(s) Write a C program to read a large text file ‘NOTES.TXT’ and print it on the printer in cut-sheets, introducing page breaks at the end of every 50 lines and a pause message on the screen at the end of every page for the user to change the paper.

NOTE: Make a file as "NOTES.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h> #include<conio.h> #include<string.h>

void print();

void main() {

FILE *fp;

char s[80]; int x=4,y=4,c=0,pg=0; clrscr();

fp=fopen("NOTES.TXT","r");

if(fp==NULL) {

puts("cannot open file!"); exit(); }

while(fgets(s,74,fp)!=NULL) {

gotoxy(30,1); /* printing page number */ printf("Page No: %3d",pg);

print(s,x,y,c); /* function to print */

c++; y++;

Solution:

Page 542: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=3&by-date=false[07-Apr-14 9:03:45 PM]

if(c>51) { /* checking for page end */

pg++;

c=0; gotoxy(2,24); printf("press any key to change paper..."); getch();

clrscr();

}

if(y>22) { /* checking for total lines */

gotoxy(2,24); printf("press any key to go to next page..."); getch(); y=5; clrscr(); }

}

fclose(fp); }

void print(char *s,int x, int y, int c) {

/* page border */

int i,bdr,bdr2;

gotoxy(1,2); printf("%c",218); for(bdr=3;bdr<23;bdr++) {

gotoxy(1,bdr); printf("%c",179);

gotoxy(79,bdr); printf("%c",179);

}

gotoxy(79,2); printf("%c",191);

gotoxy(79,23); printf("%c",217);

gotoxy(1,23); printf("%c",192);

for(bdr2=2;bdr2<=78;bdr2++) {

gotoxy(bdr2,2); printf("%c",196);

}

gotoxy(x,y);

puts(s);

if(c>50) {

for(i=2;i<79;i+=2) {

Page 544: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 1 (Getting started)

(a) Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.

Solution:

(b) The distance between two cities (in km.) is input through the keyboard. Write a program to convert and print this distance in meters, feet, inches and centimeters.

#include<stdio.h>#include<conio.h>main() {long km,m,ft,inc,cm;clrscr();printf("Please enter the distance(in km):\n");scanf("%ld",&km);m=km*1000;ft=m*3;inc=ft*12;cm=ft*30;printf("\nDistance in kilometer = %ld\n",km);printf("\nDistance in meter = %ld\n",m);printf("\nDistance in feet = %ld\n",ft);printf("\nDistance in inches = %ld\n",inc);printf("\nDistance in centimeters = %ld\n",cm);getch();

Exercise [H]

#include<stdio.h>#include<conio.h>main() {long bs,da,hra,gs;clrscr();printf("Please enter Ramesh's Basic Salary: \n");scanf("%ld",&bs);gs=(40*bs/100)+(20*bs/100)+bs;printf("Ramesh's GROSS SALARY = %ld\n",gs);getch();return 0;} ------------------------------------------------------------------------------------------------------------

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 545: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

return 0;}

------------------------------------------------------------------------------------------------------------

(c) If the marks obtained by a student in five different subjects are input through the keyboard, find out the aggregate marks and percentage marks obtained by the student. Assume that the maximum marks that can be obtained by a student in each subject is 100.

------------------------------------------------------------------------------------------------------------

(d) Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this temperature into Centigrade degrees.

#include<stdio.h>#include<conio.h>main() {float fh,cn;clrscr();printf("Please enter the temperature in fahrenheit:\n");scanf("%f",&fh);cn=5*(fh-32)/9;printf("Centigrade Temperature = %f \n",cn);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(e) The length & breadth of a rectangle and radius of a circle are input through the keyboard. Write a program to calculate the area & perimeter of the rectangle, and the area & circumference of the circle.

Solution:

#include<stdio.h>#include<conio.h>main() {int m1,m2,m3,m4,m5,ttl;float prcnt;clrscr();printf("Please enter the marks of the student:\n");scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);ttl=m1+m2+m3+m4+m5;prcnt=ttl/5;printf("AGGREGATE MARKS = %d\nPERCENTAGE MARKS = %f%\n",ttl,prcnt);getch();return 0;}

Solution:

Solution:

#include<stdio.h>#include<conio.h>main() {float l,b,area,peri,ca,cr,r;clrscr();printf("Please enter the length of rectangle:");scanf("%f",&l);printf("\nPlease enter the breadth of rectangle:");scanf("%f",&b);area=l*b;peri=2*(l+b);

Page 546: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

(f) Two numbers are input through the keyboard into two locations C and D. Write a program to interchange the contents of C and D.

#include<stdio.h>#include<conio.h>main() {int c,d,t;clrscr();printf("Enter value of C: ");scanf("%d",&c);printf("\n\nEnter value of D: ");scanf("%d",&d);t=c;c=d;d=t;printf("\n\nC = %d\nD = %d\n",c,d);getch();}

------------------------------------------------------------------------------------------------------------

(g) If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits.(Hint: Use the modulus operator ‘%’)

#include<stdio.h>#include<conio.h>main() {long i,d1,d2,d3,d4,d5,a,b,c,d,sum;clrscr();printf("Please enter the five digit number: \n");scanf("%ld",&i);d1=i/10000;a=i%10000;d2=a/1000;b=a%1000;d3=b/100;c=b%100;d4=c/10;d=c%10;d5=d/1;sum=d1+d2+d3+d4+d5;printf("Sum of the digits is %ld\n",sum);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(h) If a five-digit number is input through the keyboard, write a program to reverse the number.

printf("\n\nAREA = %f square cm.\t PERIMETER = %f cm.\n",area,peri);printf("\n\nPlease enter the radius of the circle:");scanf("%f",&r);ca=3.14*r*r;cr=2*3.14*r;printf("\n\nAREA = %f square cm.\t CIRCUMFERENCE = %f cm.\n",ca,cr);getch();return 0;}

------------------------------------------------------------------------------------------------------------

Solution:

Solution:

Page 547: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

------------------------------------------------------------------------------------------------------------

(i) If a four-digit number is input through the keyboard, write a program to obtain the sum of the first and last digit of this number.

------------------------------------------------------------------------------------------------------------

(j) In a town, the percentage of men is 52. The percentage of total literacy is 48. If total percentage of literate men is 35 of the total population, write a program to find the total number of illiterate men and women if the population of the town is 80,000.

#include<stdio.h>#include<conio.h>main() {int i,d1,d4,a,b,c,sum;clrscr();printf("Please enter the four digit number: \n");scanf("%d",&i);d1=i/1000;

Solution:

#include<stdio.h>#include<conio.h>main() {long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();printf("Please enter the five digit number: \n");scanf("%ld",&i);d1=i/10000;a=i%10000;d2=a/1000;b=a%1000;d3=b/100;c=b%100;d4=c/10;d=c%10;d5=d/1;n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);printf("reversed number = %ld \n",n_num);getch();return 0;}

Solution:

#include<stdio.h>#include<conio.h>main() {int i,d1,d4,a,b,c,sum;clrscr();printf("Please enter the four digit number: \n");scanf("%d",&i);d1=i/1000;a=i%1000;b=a%100;c=b%10;d4=c/1;sum=d1+d4;

printf("The sum of first and last digit is %d\n",sum);getch();return 0;}

Solution:

Page 548: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

a=i%1000;b=a%100;c=b%10;d4=c/1;sum=d1+d4;printf("The sum of first and last digit is %d\n",sum);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(k) A cashier has currency notes of denominations 10, 50 and 100. If the amount to be withdrawn is input through the keyboard in hundreds, find the total number of currency notes of each denomination the cashier will have to give to the withdrawer.

#include<stdio.h>#include<conio.h>main() {int a,t_10,f_50,h_100,b,c;clrscr();printf("Please enter the amount to be withdrawn: \n");scanf("%d",&a);h_100=a/100;b=a%100;f_50=b/50;c=b%50;t_10=c/10;

printf("\nCurrency notes of 100 should be = %d\n",h_100);printf("\nCurrency notes of 50 should be = %d\n",f_50);printf("\nCurrency notes of 10 should be = %d\n",t_10);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(l) If the total selling price of 15 items and the total profit earned on them is input through the keyboard, write a program to find the cost price of one item.

#include<stdio.h>#include<conio.h>main() {int sp,p,cp;clrscr();

printf("Please enter the selling price of 15 items: \n");scanf("%d",&sp);printf("\nPlease enter the total profit of 15 items: \n");scanf("%d",&p);cp=(sp-p)/15;printf("Cost price of one item is %d\n",cp);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(m) If a five-digit number is input through the keyboard, write a program

Solution:

Solution:

Page 549: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

Posted by Chetan Raikwar at 07:01 No comments:

to print a new number by adding one to each of its digits. For example if the number that is input is 12391 then the output should be displayed as 23502.

#include<stdio.h>#include<conio.h>main() {long i,add;clrscr();printf("Please enter a five digit number: \n");scanf("%ld",&i);add=i+11111;printf("addition = %ld\n",add);getch();return 0;}

______________________________________________________________________

Solution:

Recommend this on Google

Let Us C / Chapter 12 (File Input Output)

(a) Write a program to read a file and display contents with its line numbers.

NOTE: Make a file as "DATA.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h>#include<conio.h>void main() {

FILE *fp;char i;int line=1;

clrscr();

fp=fopen("DATA.TXT","r");

if(fp==NULL) {

printf("\n\nCannot open file!");

delay(1000);exit();}

printf("%2d. ",line); /* we already print 1st for the first line */

while(i!=EOF) {

i=fgetc(fp);

printf("%c",i);

Exercise [C]

Solution:

Page 550: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

/* if the character is newline,the line number will be\printed after it */

if(i=='\n') {line++;printf("%2d. ",line);}

}

fclose(fp);getch();}

---------------------------------------------------------------------------------------------------------------

(b) Write a program to find the size of a text file without traversing it character by character.

NOTE: Make a file as "DATA.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h>#include<conio.h>#include<string.h>

void main() {

FILE *fp;char s[80],ch;int len=0;

clrscr();

fp=fopen("data.txt","r");

while(fgets(s,79,fp)!=NULL)

len=len+strlen(s); /* length of each string */ /* spaces and newlines are also counted */

fclose(fp);

printf("length of file = %d",len);

getch();}

----------------------------------------------------------------------------------------------------------------

(c) Write a program to add the contents of one file at the end of another.

NOTE: Make two file as "FILE1.TXT" and "FILE2.TXT" in bin directory and then run the program. The contents of FILE1.TXT will be appended to FILE2.TXT.

Solution:

Solution:

Page 551: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

#include<stdio.h>#include<conio.h>void main() {

FILE *f1,*f2;char ch;

clrscr();

f1=fopen("FILE1.TXT","r"); /* file to append */f2=fopen("FILE2.TXT","a+"); /* file to be appended */

if(f1==NULL || f2==NULL) {printf("\ncannot open one of files!");

exit();}

while(1) {

ch=fgetc(f1);

if(ch==EOF) {break;}

fputc(ch,f2);

}

fclose(f1);fclose(f2);

printf("\ntask completed successfully!");

getch();

}

---------------------------------------------------------------------------------------------------------------

(d) 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.

#include<stdio.h>#include<conio.h>#define N 100struct student { char name[30]; int age; };

void main() {

struct student std;struct student s[N]; /* size of array of structure defined globally for convenience */

FILE *fp;int flag=0,ch,i=0,count=0;long recsize;char another='y';void srt_print(); /* funtion to sort and print */

Solution:

Page 552: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

clrscr();

recsize=sizeof(std);

fp=fopen("STUDENT.DAT","rb+");if(fp==NULL) {fp=fopen("STUDENT.DAT","wb+");if(fp==NULL)exit();}

while(1) {

clrscr();

printf("\t\t\tStudent database\n");printf("\t\t\t****************\n\n\n");printf("\t\t\n1: Add student data\n");printf("\t\t\n2: List student data\n");printf("\t\t\n0: Exit");

gotoxy(2,24);printf("Your choice: ");scanf("%d",&ch);

switch(ch) {

case 1:

clrscr();

while(another=='y' || another=='Y') {

clrscr();

printf("\t\tAdd student data\n");printf("\t\t****************\n\n");printf("\nEnter student name: ");scanf("%s",&std.name);printf("\n\naEnter student age: ");scanf("%d",&std.age);

fseek(fp,0,SEEK_END);fwrite(&std,recsize,1,fp);

gotoxy(2,24);printf("Add another information(Y/N): ");fflush(stdin);another=getche();

}break;

case 2:

clrscr();

printf("\t\tList student data\n");printf("\t\t*****************\n\n");rewind(fp);while(fread(&std,recsize,1,fp)==1) {s[i]=std;flag=1;i++;count++;}

srt_print(&s,count); /* function to print names */

if(flag==0) {

Page 553: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

printf("\n\n\nNo data found!\n");

}printf("\n\n\npress any key to return...");getch();

break;

case 0:

fclose(fp);exit();

default:

printf("wrong input!\n");exit();

}

}

}/******** main ends ************/

/**** sorting and printing function ****/void srt_print(struct student *ss, int n) {

struct student temp;int i,j;

for(i=0;i<=n;i++) {

for(j=i+1;j<n;j++) {

/* checking first alphabets of both names */

if(ss[i].name[0] > ss[j].name[0]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;}

/* if first alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1] > ss[j].name[1]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;

}

/* if first 2 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2] > ss[j].name[2]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;

Page 554: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

}}

/* if first 3 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2]==ss[i].name[2]) {

if(ss[i].name[3] > ss[j].name[3]) {

temp=ss[i];ss[i]=ss[j];ss[j]=ss[i];}}}

/* if first four 4 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2]==ss[j].name[2] && ss[i].name[2]==ss[j].name[2]) {

if(ss[i].name[3]==ss[j].name[3]) {

if(ss[i].name[4] > ss[j].name[4]) {

temp=ss[i];ss[i]=ss[j];ss[j]=ss[i];

} } } }

}}

/* printing sorted list */

for(i=0;i<n;i++) {

printf("\n%10s\t\t%2d\n",ss[i].name,ss[i].age);

}

}

--------------------------------------------------------------------------------------------------------------

(e) Write a program to copy one file to another. While doing so replace all lowercase characters to their equivalent uppercase characters.

NOTE: Make a file as "FILE.TXT" in bin directory and write/paste some text in it. then run the program and you will receive another file as "RESULT.TXT" with uppercase letters.

#include<stdio.h>#include<conio.h>

Solution:

Page 555: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

void main() {

FILE *fr,*fw;char a[1000];char ch,upr;clrscr();

fr=fopen("SOURCE.TXT","r");

if(fr==NULL) {printf("cannot open source file!\n");

}

fw=fopen("RESULT.TXT","w");

if(fw==NULL) {printf("cannot open target file!\n");

}

while(1) {

ch=fgetc(fr);

if(ch==EOF)break;

else {

if(ch>=97 && ch<=122) {

ch=ch-32;

}

fputc(ch,fw);}

}fclose(fr);fclose(fw);

printf("Task completed!");getch();}

----------------------------------------------------------------------------------------------------------------

(f) 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.

----------------------------------------------------------------------------------------------------------------

(g) 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 cornerco-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

Solution:

Page 556: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

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.

#include<stdio.h>#include<conio.h>#include<string.h>#include<types.h>#include<stat.h>#include<fcntl.h>

void box();void print();

void main() {

int inhandle,bytes,pg=1;FILE *fp;char source[80],buffer[1400];

clrscr();

printf("Enter file name: ");gets(source);

inhandle=open(source, O_RDONLY);

if(inhandle==-1) {

printf("cannot open file!");exit();

}

clrscr();

while(1) {

bytes=read(inhandle,buffer,1387);

if(bytes>0) {

gotoxy(32,1); /* showing filename */printf("%s",strupr(source));

gotoxy(70,1);printf("Pg: %3d",pg); /* showing page number */

box(); /* passing the heading and page number to the function */

print(buffer); /* passing the buffer to the function */

}

else {

gotoxy(70,1);printf("Pg: %3d",pg);break;}

++pg;}

close(inhandle);

Solution:

Page 557: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

getch();}

/********************************//* function to print the buffer *//********************************/

void print(char s[1400]) {

int x=4,y=3,i=0;

while(s[i]!=EOF) {

gotoxy(x,y);printf("%c",s[i]);

if(x>74) {

x=4;y+=1;

}

if(y>21) {

gotoxy(2,24);printf("press any key to go to next page...");

x=4;y=3;

getch();

clrscr();box();}

x++;i++;

}

}

/****************************//* function to draw the box *//****************************/

void box() {

int i,j;

for(i=2;i<=77;i++) {

gotoxy(i,2);printf("%c",196);

gotoxy(i,23);printf("%c",196);

}

for(j=3;j<=22;j++) {

gotoxy(2,j);

Page 558: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

printf("%c",179);

gotoxy(77,j);printf("%c",179);

}

gotoxy(77,23);printf("%c",217);

gotoxy(77,2);printf("%c",191);

gotoxy(2,23);printf("%c",192);

gotoxy(2,2);printf("%c",218);

}

----------------------------------------------------------------------------------------------------------------

(h) Write a program to encrypt/decrypt a file using:(1) 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.(2) A substitution cipher: In this each character read from the source file is substituted by a corresponding predetermined character and this character is written to the target file.For example, if character ‘A’ is read from the source file, and if we have decided that every ‘A’ is to be substituted by ‘!’, then a ‘!’ would be written to the target file in place of every ‘A’ Similarly, every ‘B’ would be substituted by ‘5’ and so on.

Offset cipher Encryption:

#include<stdio.h>#include<conio.h>

void main() { /* offset cipher encryption */

/* every character has been added to 128 and the new value has beenwritten */

FILE *fp,*ft;char ch;

clrscr();

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");exit();}

while(1) {

ch=fgetc(fp);

Solution:

Page 559: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

if(ch==EOF)break;

ch=ch+128; /* offset cipher encryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();}

Offset cipher Decryption:

#include<stdio.h>#include<conio.h>void main() { /* offset cipher decryption */

FILE *fp,*ft;char ch;

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");

exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

ch=ch-128; /* decryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();

}

Substitution cipher encryption:

Page 560: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

#include<stdio.h>#include<conio.h>

void main() { /* substitution cipher encryption */

/* all vowels have been exchanged with first five ascii characters and every space has been converted to 6th ascii character */

FILE *fp,*ft;char ch;

clrscr();

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

encrypt(&ch); /* function for encryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();}encrypt(char *c) {

if(*c=='a') {*c='!';}

if(*c=='e') {*c='@';}

if(*c=='i') {*c='#';}

if(*c=='o') {*c='$';}

if(*c=='u') {*c='%';}

if(*c==' ') {*c='^';}

Page 561: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

return *c;}

Substitution cipher Decryption:

#include<stdio.h>#include<conio.h>void main() {

/* substitution cipher's decryption */

FILE *fp,*ft;char ch;

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");

exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

decrypt(&ch); /* function for decryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();

}

decrypt(char *c) {

if(*c=='!')*c='a';

if(*c=='@')*c='e';

if(*c=='#')*c='i';

if(*c=='$')*c='o';

if(*c=='%')*c='u';

if(*c=='^')*c=' ';

Page 562: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

return *c;

}----------------------------------------------------------------------------------------------------------------

(i) 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.

NOTE: If on withdrawal, the balance subtracts to less than 100. The withdrawal will not be performed.

#include<stdio.h>#include<conio.h>void main() {

struct customer { int accno; char name[30]; float balance; }cust;struct trans { int accno; char trans_type; float amount; }tra;FILE *fp,*ft,*ftemp;int flag=0;long recsize,retsize;char another,ch;clrscr();

fp=fopen("CUSTOMER.DAT","rb+");

if(fp==NULL) {

fp=fopen("CUSTOMER.DAT","wb+");

if(fp==NULL)

Solution:

Page 563: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

printf("cannot open customer data file!\n");

exit();

}

ft=fopen("TRANSACTIONS.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTIONS.DAT","wb+");

if(ft==NULL)

printf("cannot open transactions file!\n");

exit();

}

recsize=sizeof(cust);retsize=sizeof(tra);

while(1) {

clrscr();

printf("\t\tCutomer Transactions:\n");printf("\t\t*********************\n\n\n");printf("\t1: Add customer information:\n\n");printf("\t2: Add transaction information:\n\n");printf("\t3: List customer information:\n\n");printf("\t4: List transaction information:\n\n");printf("\t5: Perform transaction:\n\n");printf("\t0: Exit:\n\n\n");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd customer information:\n");printf("\t\t*************************\n\n");printf("\nEnter account number: ");scanf("%d",&cust.accno);printf("\n\nEnter name: ");scanf("%s",cust.name);printf("\n\nEnter balance: ");fflush(stdin);scanf("%f",&cust.balance);

fwrite(&cust,recsize,1,fp);

gotoxy(2,24);printf("Add another customer information(Y/N): ");another=getche();

Page 564: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

clrscr();

}break;

case '2':

clrscr();

fseek(ft,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd transaction information:\n");printf("\t\t****************************\n\n\n");printf("Enter existing customer account number: ");scanf("%d",&tra.accno);printf("\n\nEnter transaction type(D/W): ");fflush(stdin);scanf("%c",&tra.trans_type);printf("\n\nEnter amount for transaction: ");fflush(stdin);scanf("%f",&tra.amount);

fwrite(&tra,retsize,1,ft);

gotoxy(2,24);printf("Enter another information(Y/N): ");another=getche();

clrscr();}break;

case '3':

clrscr();

printf("\t\tList customer information:\n");printf("\t\t**************************\n\n");

rewind(fp);while(fread(&cust,recsize,1,fp)==1) {printf("\n%5d\t%-8s\t%5.2f\n",cust.accno,cust.name,cust.balance);flag=1;}

if(flag==0) {gotoxy(2,12);printf("No customer information found!\n");}printf("\n\npress any key to go back...");getch();

break;

case '4':

clrscr();

printf("\t\tList transaction information:\n");printf("\t\t*****************************\n\n");

rewind(ft);while(fread(&tra,retsize,1,ft)==1) {printf("\n%5d\t%c\t%6.2f\n",tra.accno,tra.trans_type,tra.amount);flag=1;}

Page 565: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

if(flag==0) {gotoxy(2,12);printf("No transaction information found!\n");}

printf("\n\npress any key to go back...");getch();

break;

case '5':

clrscr();

printf("\t\tPerform transactions\n");printf("\t\t********************\n\n");

rewind(fp);

while(fread(&cust,recsize,1,fp)==1) {

rewind(ft);

while(fread(&tra,retsize,1,ft)==1) {

if(cust.accno==tra.accno) {

flag=1;

if(tra.trans_type=='D' || tra.trans_type=='d') {

cust.balance+=tra.amount;

fseek(fp,-recsize,SEEK_CUR);fwrite(&cust,recsize,1,fp);

}

else if(tra.trans_type=='W' || tra.trans_type=='w') {

if((cust.balance-tra.amount)>=100) {

cust.balance-=tra.amount;

fseek(fp,-recsize,SEEK_CUR);fwrite(&cust,recsize,1,fp);

}

}

}}}

fclose(ft);

ftemp=fopen("TEMP.DAT","rb+");

if(ftemp==NULL) {

ftemp=fopen("TEMP.DAT","wb+");

}

remove("TRANSACTIONS.DAT");rename("TEMP.DAT","TRANSACTIONS.DAT");

ft=fopen("TRANSACTIONS.DAT","rb+");

Page 566: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

if(ft==NULL) {

ft=fopen("TRANSACTIONS.DAT","wb+");

}

if(flag==0) {

gotoxy(2,12);printf("No active transactions\n");

}

else if(flag>0) {

gotoxy(2,12);printf("Transactions performed seccussfully!\n");gotoxy(2,14);printf("NOTE: withdrawl for low balance accounts has not been performed\n");

}gotoxy(2,24);printf("press any key to return...");getch();

break;

case '0':

fclose(fp);fclose(ft);exit();

}}

}

---------------------------------------------------------------------------------------------------------------

(j) 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.

----------------------------------------------------------------------------------------------------------------

(k) A hospital keeps a file of blood donors in which each record has the format:Name: 20 Columns

Solution:

Page 567: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

Address: 40 ColumnAge: 2 ColumnsBlood Type: 1 Column (Type 1, 2, 3 or 4)Write a program to read the file and print a list of all blood donors whose age is below 25 and blood is type 2.

/* This program will make a file of blood donors and save information in it */

/* Writing program */

#include<stdio.h>#include<conio.h>void main() {

FILE *fp;char another='y';

struct blood { char name[50]; char adr[50]; int age; int bld; } b;

clrscr();

fp=fopen("BLOODBANK.DAT","wb");

if(fp==NULL) {printf("cannot open target file!\n");exit();}

while(another=='Y' || another=='y') {

clrscr();printf("\t\tInformation of Blood donor\n");printf("\t\t**************************\n\n\n");printf("Enter the name: ");scanf("%s",b.name);printf("\n\nenter the address: ");scanf("%s",b.adr);printf("\n\nenter the age: ");scanf("%d",&b.age);printf("\n\nenter the blood group(1/2/3/4): ");scanf("%d",&b.bld);

fprintf(fp,"%s\t%s\t%d\t%d",b.name,b.adr,b.age,b.bld);

printf("\n\n\nenter more information(Y/N): ");fflush(stdin);

another=getch();

}

fclose(fp);

}

Solution:Program to creat record file of blood donors

Program to read record file for specifications

Page 568: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

/* This program will read the information from the file made by writing program */

/* Reading Program */

#include<stdio.h>#include<conio.h>void main() {

FILE *fp;char ch;

struct blood { char name[50]; char adr[50]; int age; int bld; }b;clrscr();

fp=fopen("BLOODBANK.DAT","rb");

if(fp==NULL) {printf("cannot open source file!\n\n");exit();}

while(fscanf(fp,"%s\t%s\t%d\t%d",&b.name,&b.adr,&b.age,&b.bld)!=EOF)if(b.age<25 && b.bld==2) {printf("\n%s\t %s\t%2d\t %d",b.name,b.adr,b.age,b.bld);}fclose(fp);

getch();}

----------------------------------------------------------------------------------------------------------------

(l) Given a list of names of students in a class, write a program to store the names in a file on disk. Make a provision to display the nth name in the list (n is data to be read) and to display all names starting with S.

#include<stdio.h>#include<conio.h>void main() {

struct name { int sn; char name[30]; }s;int i,num,flag=0;long recsize;char another,ch;FILE *fp;clrscr();

fp=fopen("NAMES.DAT","rb+");

if(fp==NULL) {

fp=fopen("NAMES.DAT","wb+");

if(fp==NULL)

printf("cannot open file! \n");exit();}

Solution:

Page 569: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

recsize=sizeof(s);

while(1) {

clrscr();printf("\t\tStudent Names:\n");printf("\t\t**************\n\n\n");printf("\t1: Add names of students:\n\n");printf("\t2: Search a student name:\n\n");printf("\t3: List all student names:\n\n");printf("\t4: List all names starting with 'S':\n\n");printf("\t0: Exit\n\n");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd names of students:\n");printf("\t\t**********************\n\n");printf("Enter student number: ");scanf("%d",&s.sn);printf("\n\nEnter student name: ");scanf("%s",s.name);

fwrite(&s,recsize,1,fp);

gotoxy(2,24);printf("Enter another name(Y/N): ");fflush(stdin);another=getche();

clrscr();}break;

case '2':

clrscr();

printf("\t\tSearch a student name:\n");printf("\t\t**********************\n\n");printf("Enter student number: ");scanf("%d",&num);

rewind(fp);

while(fread(&s,recsize,1,fp)==1) {

if(s.sn==num) {

printf("\n\nStudent Number: %5d\n\n",s.sn);printf("Student name: %s\n\n",s.name);

flag=1;

Page 570: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

break;} }

if(flag==0) {printf("\n\n\nNo such name found!\n");}gotoxy(2,24);printf("press any key to return...\n");getch();

break;

case '3':

clrscr();

printf("\t\tList all student names\n");printf("\t\t**********************\n\n\n");

rewind(fp);

while(fread(&s,recsize,1,fp)==1) {printf("\n%5d\t%-10s\n",s.sn,s.name);flag=1;}

if(flag==0) {printf("\n\n\nNo name found!\n");}

printf("\n\n\npress any key to return...\n");getch();break;

case '4':

clrscr();

printf("\t\tAll name starting with 'S':\n");printf("\t\t***************************\n\n\n");

rewind(fp);while(fread(&s,recsize,1,fp)==1) {

if(strncmp('s',s.name[0])==0) { /* comparing only first character of \ name if it is "s" */printf("\n%5d\t%-10s\n",s.sn,s.name);flag=1;}}

if(flag==0) {printf("\n\n\nNo name starting with \'S\' found!\n");}

printf("\n\n\npress any key to return...\n");getch();break;

case '0':

fclose(fp);exit();

} }

}

Page 571: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

----------------------------------------------------------------------------------------------------------------

(m) Assume that a Master file contains two fields, Roll no. and name of the student. At the end of the year, a set of students join the class and another set leaves. A Transaction file contains the roll numbers and an appropriate code to add or delete a student.Write a program to create another file that contains the updated list of names and roll numbers. Assume that the Master file and the Transaction file are arranged in ascending order by roll numbers. The updated file should also be in ascending order by roll numbers.

Note:- This program ( all the 3 ) are ideally for single. After you have ran it once, check the results and delete the updated list file before running it again. Assign roll number in ascending orders by roll numbers. And process data according to ascending nature.

1- first program will let you save data in masterfile.2- second program will let you add or delete data and will generate an updated list in text mode.3- obtain the updated list and check it ( assuming you have processed data as instructed).

1. program to creat master file.

#include<stdio.h>#include<conio.h>#include<string.h>

void main() {

FILE *fp;struct student { int rl; char name[50]; }s;char ch,another;clrscr();

fp=fopen("MASTERFILE.DAT","rb+");

if(fp==NULL) {

fp=fopen("MASTERFILE.DAT","wb+");

if(fp==NULL)puts("cannot open master file!");exit();}

while(1) {

clrscr();

gotoxy(30,2);printf("Masterfile\n");gotoxy(30,3);printf("**********\n\n\n");gotoxy(20,6);printf("1: Enter student data: ");gotoxy(20,8);printf("2: Read student data: ");gotoxy(20,10);printf("0: Exit: ");

Solution:

Page 572: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

clrscr();

gotoxy(2,24);printf("NOTE: assign roll numbers in ascending order");gotoxy(20,5);printf("Enter roll number: ");scanf("%d",&s.rl);

gotoxy(20,7);printf("Enter name: ");fflush(stdin);gets(s.name);

fwrite(&s,sizeof(s),1,fp);

gotoxy(20,10);printf("Add more data(Y/N): ");fflush(stdin);

another=getche();

}

break;

case '2':

clrscr();

gotoxy(30,2);printf("Student data");gotoxy(30,3);printf("************\n\n");

rewind(fp);

while(fread(&s,sizeof(s),1,fp)==1) {

printf("\n%d\t%s\n",s.rl,s.name);

}

printf("\n\npress any key to return...");getch();

break;

case '0':

fclose(fp);exit();

Page 573: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

}}

}

2. program to creat transaction file and generate updated list

#include<stdio.h>#include<conio.h>#include<string.h>#define N 100

void main() {

FILE *ft,*fu,*fm,*ftemp;

struct student { int rl; char name[50]; }s,ss[N],temp;

struct transaction { char stats; int rl; char name[50]; }t;

int flag=0;char ch,another;clrscr();

fm=fopen("MASTERFILE.DAT","rb+");

if(fm==NULL) {

printf("Masterfile doesn't exist!");

}

ft=fopen("TRANSACTION.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTION.DAT","wb+");

if(ft==NULL)puts("cannot open transactions file!");exit();}

fu=fopen("UPDATELIST.TXT","w+");

if(fu==NULL) {

puts("cannot open target file!");exit();}

while(1) {

clrscr();

gotoxy(30,2);printf("Transaction-File\n");

Page 574: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

gotoxy(30,3);printf("****************\n\n\n");gotoxy(20,6);printf("1: ADD/DELETE student data from master list: ");gotoxy(20,8);printf("2: Read transaction data: ");gotoxy(20,10);printf("3: Creat updated list: ");gotoxy(20,12);printf("0: Exit:");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(ft,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

clrscr();

gotoxy(2,23);printf("NOTE: data to be deleted should match master list");gotoxy(2,24);printf("NOTE: data to be added should follow the ascending nature of master list");gotoxy(20,5);printf("ADD/DELETE student(A/D): ");scanf("%c",&t.stats);gotoxy(20,7);printf("Enter roll number: ");scanf("%d",&t.rl);gotoxy(20,9);printf("Enter name: ");fflush(stdin);gets(t.name);

fwrite(&t,sizeof(t),1,ft);

gotoxy(20,12);printf("Add more data(Y/N): ");fflush(stdin);

another=getche();

}

break;

case '2':

clrscr();

gotoxy(30,2);printf("Student data");gotoxy(30,3);printf("************\n\n");

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

Page 575: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

printf("\n");

if(t.stats=='a' || t.stats=='A') {printf("ADD");}

else {printf("DELETE");}printf("\t%d\t%s\n",t.rl,t.name);

}

printf("\n\npress any key to return...");getch();

break;

case '3':

clrscr();

gotoxy(30,2);printf("make updated list");gotoxy(30,3);printf("*****************\n\n");

rewind(fm);

while(fread(&s,sizeof(s),1,fm)==1) {

flag=0;

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

if(t.rl==s.rl ) {

if(t.stats=='d' || t.stats=='D') {flag=1;}

}

}

if(flag==0)

fprintf(fu,"\n%d\t%-s\n",s.rl,s.name);

}

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

if(t.stats=='a' || t.stats=='A') {

fprintf(fu,"\n%d\t%-s\n",t.rl,t.name);

}

}

ftemp=fopen("TEMP.DAT","wb+");

fclose(ftemp);

Page 576: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

fclose(ft);

remove("TRANSACTION.DAT");rename("TEMP.DAT","TRANSACTION.DAT");

ft=fopen("TRANSACTION.DAT","rb+");

gotoxy(2,24);printf("press any key to continue...");getch();

break;case '0':

fclose(fm);fclose(ft);fclose(fu);exit();

}}

}

-----------------------------------------------------------------------------------------------------------------

(n) In a small firm employee numbers are given in serial numerical order, that is 1, 2, 3, etc.− Create a file of employee data with following information: employee number, name, sex, gross salary.− If more employees join, append their data to the file.− If an employee with serial number 25 (say) leaves, delete the record by making gross salary 0.− If some employee’s gross salary increases, retrieve the record and update the salary.Write a program to implement the above operations.

#include<stdio.h>#include<conio.h>void main() {

struct emp { int empno; char name[30]; char sex; float gs; } e;FILE *fp,*ft;int long recsize;int empn,flag=0;float new_sal;char another,ch;clrscr();

recsize=sizeof(e);

fp=fopen("EMP.DAT","rb+");

if(fp==NULL) {

fp=fopen("EMP.DAT","wb+");if(fp==NULL)

Solution:

Page 577: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

exit();

}

while(1) {

clrscr();

printf("\t\tEmployee database management\n");printf("\t\t****************************\n");printf("\n\n\t1: Add another employee: ");printf("\n\n\t2: Add salary information of employee: ");printf("\n\n\t3: List all records: ");printf("\n\n\t4: Delete employee with 0 salary: ");printf("\n\n\t0: Exit:");

gotoxy(2,24);printf("your choice: ");fflush(stdin);ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END); /* seeking cursor to reach at the end of file */

another='Y';

while(another=='Y' || another=='y') {

printf("\n\tEnter new employee information\n");printf("\t******************************\n\n\n");

printf("\nEnter employee number: ");scanf("%d",&e.empno);

printf("\n\nEnter employee name: ");scanf("%s",e.name);

printf("\n\nEnter sex(M/F/O): ");scanf(" %c",&e.sex);

printf("\n\nEnter gross salary: ");scanf("%f",&e.gs);

/* writing new information at the end of file */

fwrite(&e,recsize,1,fp);

printf("\n\n\n\nAdd another employee(Y/N): ");fflush(stdin);another=getche();

clrscr();

}

break;

case '2':

clrscr();

another='Y';

while(another=='Y' || another=='y') {

printf("\n\tEnter salary information\n");

Page 578: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

printf("\t************************\n\n");

gotoxy(2,23); /* showing message at the bottom of the screen */

printf("NOTE: to delete an employee, mark his/her salary 0\n");printf(" then use option 4 from main menu.");

gotoxy(3,5); /* returning cursor back from the bottom */printf("Enter employee number: ");scanf("%d",&empn); /* asking for employee number to search */

rewind(fp);

while(fread(&e,recsize,1,fp)==1) {

if(e.empno-empn==0) { /* if employee number matches with structure */

flag=1; /* condition indicator for printing further messages */

printf("\n\nEnter new salary for employee: ");

scanf("%f",&e.gs);

e.empno=e.empno; /* rest information should be same except only\ salary */e.sex=e.sex;

e.name[30]=e.name[30];

fseek(fp,-recsize,SEEK_CUR); /* seeking the correct location of data within\ structure in the file */fwrite(&e,recsize,1,fp); /* writing data at correct position */

break;

}}

if(flag==0) /* conditional indicator used above */printf("\n\n\n\tinformation does not exist!\n");

printf("\n\nenter another information(Y/N): ");another=getche();

clrscr();

}

break;

case '4':

clrscr();

printf("\n\n\tDelete employee\n");printf("\t***************\n\n");

ft=fopen("TEMP.DAT","w"); /* opening new temporary file */

rewind(fp); /* taking cursor back to the very beginning of file */

while(fread(&e,recsize,1,fp)==1) { /* matching each salary */

if(e.gs!=0.0 || e.gs!=0) { /* if salary is not 0 then data will be written to new file */

flag=1;

Page 579: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

fwrite(&e,recsize,1,ft);

}}fclose(fp);fclose(ft);

remove("EMP.DAT"); /* removing original file with 0 salary and renaming\ temporary without 0 salary as the original file */

rename("TEMP.DAT","EMP.DAT");

fp=fopen("EMP.DAT","rt+"); /* opening the new file, it opens because it has not been opened before */ /* a file cannot be opened twice during execution as you know */

if(flag>0) {printf("\n\n\nall records with 0 gross salary have been deleted. \n");}

gotoxy(2,24);printf("\n\n\npress any key to return...");getch();

break;

case '0':

fclose(fp);exit();

case '3':

clrscr();

printf("\t\tList all employees\n");printf("\t\t******************\n\n\n");

rewind(fp);

while(fread(&e,recsize,1,fp)==1) {

flag=1;

printf("%2d\t%6s\t%c\t%.2f\n\n",e.empno,e.name,e.sex,e.gs);

}

if(flag==0)

printf("\n\n\tNo records exist!\n\n");

printf("\n\npress any key to return... ");

getch(); /* this is very important place, if we don't stop screen here \ after reading and printing the list,we won't be able to see it and it will disappear and will return to main menu because of "break" statement. */break;

} }

}linkfloat() { /* function to avoid possible errors because of floats */float a=0,*b;b=&a;a=*b;

Page 580: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

return 0;}

-----------------------------------------------------------------------------------------------------------------

(o) Given a text file, write a program to create another text file deleting the words “a”, “the”, “an” and replacing each one of them with a blank space.

NOTE: Make a file "FILE.TXT" in bin directory and write/paste something in it, then run the program, you will get another file as "NEW.TXT" as result of the program.

#include<stdio.h> #include<conio.h> #include<string.h>

void replace();

void main() {

FILE *fp,*ft; char str[80],target[80]; clrscr();

fp=fopen("FILE.TXT","r");

if(fp==NULL) {

puts("cannot open source file!"); exit(); }

ft=fopen("NEW.TXT","w");

if(ft==NULL) {

puts("cannot open target file!"); exit(); }

while(fgets(str,79,fp)!=NULL) {

replace(str,&target);

fputs(target,ft);

}

fclose(fp); fclose(ft);

printf("\nTask completed!"); getch();

}

void replace(char *s, char *s1) {

int i=0,j=0,k=0; char temp[100],temp2[100],main[100],*t=temp,*m=main;

Solution:

Page 581: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

/* 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,"the")==0) {

strcpy(temp2," "); }

else if(strcmpi(temp2,"an")==0) {

strcpy(temp2," ");

}

else if(strcmpi(temp2,"a")==0) {

strcpy(temp2," ");

}

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,"the")==0){ /* checking last word too */

Page 582: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

strcpy(temp2," "); }

else if(strcmpi(temp2,"an")==0) {

strcpy(temp2," "); }

else if(strcmpi(temp2,"a")==0) {

strcpy(temp2," "); }

/***************************/ /* 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 */

}

while(*m!='\0') {

*s1=*m;

s1++; m++;

}

*s1='\0';

}

-----------------------------------------------------------------------------------------------------------------

(p) You are given a data file EMPLOYEE.DAT with the following record structure:struct employee {int empno ;char name[30] ;int basic, grade ;} ;Every employee has a unique empno and there are supposed to be no gaps between employee numbers. Records are entered into the data file in ascending order of employee number, empno. It is intended to check whether there are missing employee numbers. Write a program segment to read the data file records sequentially and display the list of missing employee numbers.

NOTE: assign employee numbers in ascending order only.Solution:

Page 583: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

#include<stdio.h> #include<conio.h> void main() {

struct employee { int empno; char name[30]; int basic,grade; }e; FILE *fp; int num=0; long recsize; char another,ch; clrscr();

fp=fopen("EMPLOYEE.DAT","rb+"); if(fp==NULL) { fp=fopen("EMPLOYEE.DAT","wb+");

if(fp==NULL) exit(); }

recsize=sizeof(e);

while(1) {

clrscr();

printf("\t\tEmployee number database:\n"); printf("\t\t*************************\n\n"); printf("\n\t1: Add employee information:\n"); printf("\n\t2: List employee information:\n"); printf("\n\t3: Check missing employee numbers:\n"); printf("\n\t0: Exit:\n\n");

gotoxy(2,24); printf("your choice: "); fflush(stdin); ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd employee information:\n"); printf("\t\t*************************\n\n");

printf("Note: employee numbers should be given in ascending order\n\n");

printf("\nEnter employee number: "); scanf("%d",&e.empno); printf("\n\nEnter employee name: "); scanf("%s",e.name); printf("\n\nEnter employee basic salary: "); scanf("%d",&e.basic); printf("\n\nEnter employee grade(1/2/3): ");

Page 584: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

scanf("%d",&e.grade);

fwrite(&e,recsize,1,fp);

gotoxy(2,24); printf("Add another employee information(Y/N): "); fflush(stdin); another=getche();

clrscr();

}

break;

case '2':

clrscr();

printf("\t\tList employee information:\n"); printf("\t\t**************************\n\n\n");

rewind(fp); while(fread(&e,recsize,1,fp)==1) {

printf("\n%3d\t%8s\t%5d\t%d\n",e.empno,e.name,e.basic,e.grade);

}

printf("\n\npress any key to return...\n"); getch();

break;

case '3':

clrscr();

printf("\t\tMissing employee numbers:\n"); printf("\t\t*************************\n\n");

rewind(fp); while(fread(&e,recsize,1,fp)==1) { num=e.empno; /* assigning the value of first employee number */ break; }

rewind(fp); /* again rewinding the file to read from beginning */

while(fread(&e,recsize,1,fp)==1) {

if(num!=e.empno) { /* if assigned number is smaller than employee number we will print all the number between them */ while(num<e.empno) {

printf("%4d ",num);

num++; } num=e.empno+1;

}

/* we will assign greater value than employee number to make sure that both don't match until another greater employee number is found */

else

num=e.empno+1;

Page 585: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

}

printf("\n\n press any key to return..."); getch();

break;

case '0':

fclose(fp); exit();

} } }

-----------------------------------------------------------------------------------------------------------------

(q) Write a program to carry out the following:− To read a text file “TRIAL.TXT” consisting of a maximum of 50 lines of text, each line with a maximum of 80 characters.− Count and display the number of words contained in the file.− Display the total number of four letter words in the text file.Assume that the end of a word may be a space, comma or a full-stop followed by one or more spaces or a newline character.

NOTE: Make a file "TRIAL.TXT" in bin directory and write something in it ,then run the program.

#include<stdio.h> #include<conio.h> void main() {

FILE *fp; char s[80]; int twd,fwd,tw=0,fw=0;void word(); clrscr();

fp=fopen("TRIAL.TXT","r"); if(fp==NULL) {

exit(); }

while(fgets(s,79,fp)!=NULL) { word(s,&twd,&fwd); tw=tw+twd; fw=fw+fwd; }

fclose(fp);

printf("\nTotal number of words in text file = %d\n",tw); printf("\n\nTotal number of 4 letter words = %d\n",fw);

getch(); }

void word(char ss[80],int *tw, int *fw) {

Solution:

Page 586: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

int i=0,tot_wd=0,tot_4_wd=0;

while(ss[i]!='\0') {

/************************/ /* to cound total words */ /************************/

if(ss[i]>=65 && ss[i]<=90 || ss[i]>=97 && ss[i]<=122) {

if(ss[i+1]==' ' || ss[i+1]=='.' || ss[i+1]==',' || ss[i+1]=='\n' ) {

tot_wd++; } }

/*********************************/ /* to count total 4 letter words */ /*********************************/

if(ss[i]==' ' || ss[i]==',' || ss[i]=='.') {

if(ss[i+1]>=65 && ss[i+1]<=90 || ss[i+1]>=97 && ss[i+1]<=122) {

if(ss[i+2]>=65 && ss[i+2]<=90 || ss[i+2]>=97 && ss[i+2]<=122) {

if(ss[i+3]>=65 && ss[i+3]<=90 || ss[i+3]>=97 && ss[i+3]<=122) {

if(ss[i+4]>=65 && ss[i+4]<=90 || ss[i+4]>=97 && ss[i+4]<=122) {

if(ss[i+5]==' ' || ss[i+5]==',' || ss[i+5]=='.' || ss[i+5]=='\n') {

tot_4_wd++; } } } } } }

if(ss[i]>=65 && ss[i]<=90 || ss[i]>=97 && ss[i]<=122) {

if(ss[i+1]>=65 && ss[i+1]<=90 || ss[i+1]>=97 && ss[i+1]<=122) {

if(ss[i+2]>=65 && ss[i+2]<=90 || ss[i+2]>=97 && ss[i+2]<=122) {

if(ss[i+3]>=65 && ss[i+3]<=90 || ss[i+3]>=97 && ss[i+3]<=122) {

if(ss[i+4]==' ' || ss[i+4]==',' || ss[i+4]=='.' || ss[i+4]=='\n') {

} } } } }

i++;

}

*tw=tot_wd; *fw=tot_4_wd;

}

-----------------------------------------------------------------------------------------------------------------

Page 587: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

(r) Write a program to read a list of words, sort the words in alphabetical order and display them one word per line. Also give the total number of words in the list. Output format should be:Total Number of words in the list is _______Alphabetical listing of words is:-----------Assume the end of the list is indicated by ZZZZZZ and there are maximum in 25 words in the Text file.

NOTE: Make a file as "trial.txt" in bin directory and write some words in it. Words should be in the form of a list. One below another,then run the program.

#include<stdio.h>#include<conio.h>#define N 100

/* make a list of words, every words should be written under previous one to make sure it's a list of words. */

/* upper case letters will be arranged before small case letter, so it is recommended to use the list of either Capital letter or small case letters but not both together. */struct word { char wrd [30]; };

void main() {

struct word w[N];

FILE *fp;char s1[30];int i=0,count=0;void srt_wrd(); /* function to sort and print list */

clrscr();

fp=fopen("TRIAL.TXT","rb+");

while(fgets(s1,30,fp)!=NULL) {strcpy(w[i].wrd,s1); /* copying each word in array of structure */i++;count++; /* count of all the words */}

printf("Total words if file = %3d\n",count);

printf("\t\tList in alphabetical order:\n");srt_wrd(&w,count); /* function for sorting and printing list */

fclose(fp);getch();

}

void srt_wrd( struct word *w, int n) {

int i,j,k=0;struct word temp;

Solution:

Page 588: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

/***************************************//* sorting words in alphabetical order *//***************************************/

for(i=0;i<=n;i++) {

for(j=i+1;j<n;j++) {

/* testing the first alphabets of two words */

if(w[i].wrd[0] > w[j].wrd[0]) {

temp=w[i];w[i]=w[j];w[j]=temp;}

/* testing the first two alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1] > w[j].wrd[1]) {

temp=w[i];w[i]=w[j];w[j]=temp;}

/* testing first three alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]>w[j].wrd[2]) {

temp=w[i];w[i]=w[j];w[j]=temp;}}

/* testing first four alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]==w[j].wrd[2] && w[i].wrd[3]>w[j].wrd[2]) {

temp=w[i];w[i]=w[j];w[j]=temp;}}

}}

/*****************************//* printing the sorted words *//*****************************/

for(i=0;i<n;i++) {

printf("%-s\n",w[i].wrd);

k++;

if(k==10) {

printf("\n\npress any key to go to next page...");getch();

Page 589: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

k=1;clrscr();}}

}

--------------------------------------------------------------------------------------------------------------

(s) Write a program to carry out the following:(a) Read a text file ‘INPUT.TXT’(b) Print each word in reverse orderExample,Input: INDIA IS MY COUNTRYOutput: AIDNI SI YM YRTNUOCAssume that each word length is maximum of 10 characters and each word is separated by newline/blank characters.

NOTE: Make a file "INPUT.TXT" in bin directory and write something in it, then run the program.

#include<stdio.h>#include<conio.h>#include<string.h>

void main() {

FILE *fs;char s[80];void rev();

clrscr();

fs=fopen("INPUT.TXT","r");

if(fs==NULL) {

printf("cannot open file!");exit();}

while(fgets(s,79,fs)!=NULL)rev(s);

fclose(fs);

getch();

}

void rev(char s1[80]) {

char s2[80];int i=0,j=0;

while(s1[i]!='\0') {

s2[j]=s1[i];

if(s1[i]==' ' || s1[i]=='\0') {

s2[j]='\0';

Solution:

Page 590: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

strrev(s2);

printf("%s ",s2);

j=-1;

}

i++;j++;}

s2[j]='\0';

printf("%s",strrev(s2));

}

-----------------------------------------------------------------------------------------------------------------

(s) Write a C program to read a large text file ‘NOTES.TXT’ and print it on the printer in cut-sheets, introducing page breaks at the end of every 50 lines and a pause message on the screen at the end of every page for the user to change the paper.

NOTE: Make a file as "NOTES.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h> #include<conio.h> #include<string.h>

void print();

void main() {

FILE *fp;

char s[80]; int x=4,y=4,c=0,pg=0; clrscr();

fp=fopen("NOTES.TXT","r");

if(fp==NULL) {

puts("cannot open file!"); exit(); }

while(fgets(s,74,fp)!=NULL) {

gotoxy(30,1); /* printing page number */ printf("Page No: %3d",pg);

print(s,x,y,c); /* function to print */

c++; y++;

Solution:

Page 591: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

if(c>51) { /* checking for page end */

pg++;

c=0; gotoxy(2,24); printf("press any key to change paper..."); getch();

clrscr();

}

if(y>22) { /* checking for total lines */

gotoxy(2,24); printf("press any key to go to next page..."); getch(); y=5; clrscr(); }

}

fclose(fp); }

void print(char *s,int x, int y, int c) {

/* page border */

int i,bdr,bdr2;

gotoxy(1,2); printf("%c",218); for(bdr=3;bdr<23;bdr++) {

gotoxy(1,bdr); printf("%c",179);

gotoxy(79,bdr); printf("%c",179);

}

gotoxy(79,2); printf("%c",191);

gotoxy(79,23); printf("%c",217);

gotoxy(1,23); printf("%c",192);

for(bdr2=2;bdr2<=78;bdr2++) {

gotoxy(bdr2,2); printf("%c",196);

}

gotoxy(x,y);

puts(s);

if(c>50) {

for(i=2;i<79;i+=2) {

Page 592: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T07:02:00-08:00&max-results=16&start=9&by-date=false[07-Apr-14 9:04:49 PM]

Newer Posts Older PostsHome

Subscribe to: Posts (Atom)

Posted by Chetan Raikwar at 06:51 No comments:

gotoxy(i,23);

printf("-"); } } }

____________________________________________________

+1 Recommend this on Google

Simple template. Powered by Blogger.

Page 593: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 5 (Functions & Pointers)

(a) Write a function to calculate the factorial value of any integer entered through the keyboard.

#include<stdio.h>#include<conio.h>

void main() {

int num;void func();

clrscr();

printf("Please enter any number: ");scanf("%d",&num);

func(num);

getch();

}

void func(int n) {

int fact=1;

for(;n>=1;n--) {

fact=fact*n;

}

printf("\n\nFactorial value = %d \n",fact);

}

------------------------------------------------------------------------------------------------------------

(b) Write a function power ( a, b ), to calculate the value of a raised to

Exercise [D]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

Page 594: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

b.

#include<stdio.h>#include<conio.h>

void main() {

int num1,num2 ;clrscr();

printf("Please enter the value of a: ");scanf("%d",&num1);

printf("\n\nPlease enter the value of b: ");scanf("%d",&num2);

power(num1,num2);

getch();

}

power(int a , int b) {

int c=1,i;

for(i=1;i<=b;i++) {c=c*a;

if(i==b) {break;}

}

printf("\n\n\nValue of %d raised to the power of %d is = %d\n",a,b,c);

return 0; }

------------------------------------------------------------------------------------------------------------

(c) Write a general-purpose function to convert any given year into its roman equivalent. The following table shows the roman equivalents of decimal numbers:

Decimal Roman

1 i5 v10 x50 l100 c500 d1000 m

Example:Roman equivalent of 1988 is mdcccclxxxviiiRoman equivalent of 1525 is mdxxv

Solution:

Page 595: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

#include<stdio.h>#include<conio.h>

void main() {

int yr;void func();

clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

printf("\n\nRoman Equivalent = ");func(yr);

getch();

}void func(int y) {

int d1,d2,d3,d4,d5,d6,d7,a,b,c,d,e,f;

char thsnd='m',hndr_5='d',hndr='c',ffty='l',tn='x',fv='v',one='i';

/******* Roman Convertion ********/

/* To find all thousands */

d1=y/1000;a=y%1000;

for(;d1>=1;d1--) {printf("%c",thsnd);

if(a==0)break;}

/* To find all five-hundreds */

d2=a/500;b=a%500;

for(;d2>=1;d2--) {printf("%c",hndr_5);

if(b==0)break;}

/* To find all hundreds */

d3=b/100;c=b%100;

for(;d3>=1;d3--) {printf("%c",hndr);

if(c==0)break;}

/* To find all fifties *//***********************/

Solution:

Page 596: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

d4=c/50;d=c%50;

for(;d4>=1;d4--) {printf("%c",ffty);

if(d==0)break;}

/* To find all tens *//********************/

d5=d/10;e=d%10;

for(;d5>=1;d5--) {printf("%c",tn);

if(e==0)break;

}

/* To find all fives */

d6=e/5;f=e%5;

for(;d6>=1;d6--) {printf("%c",fv);

if(f==0)break;}

/* To find all ones */

for(d7=f;d7>=1;d7--) {printf("%c",one);

}

}

------------------------------------------------------------------------------------------------------------

(d) Any year is entered through the keyboard. Write a function to determine whether the year is a leap year or not.

#include<stdio.h>#include<conio.h>void main() {

int yr;void func();clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

func(yr);

Solution:

Page 597: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

getch();

}void func(int y) {

if((y%4)==0)

printf("\nThis is a LEAP YEAR.\n");

else

printf("\nThis is NOT A LEAP YEAR.\n");

}

------------------------------------------------------------------------------------------------------------

(e) 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.

#include<stdio.h>#include<conio.h>

void main() {

int i,j,k;clrscr();

printf("enter the number: ");

scanf("%d",&j);

printf("\n\nprime factors:");

for(i=2;i<=j;) {

if(j%i==0) { /* divide only if remainder is supposed to be 0 */

j=j/i;

printf(" %d ",i); /* print the divisor */

}

else /* if divisor cannot divide completely */

i=i+1; /* increase it's value and try again */

}

getch();

}

________________________________________________________________________

(a) Write a function which receives a float and an int from main( ), finds

Solution:

Exercise [F]

Page 598: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

the product of these two and returns the product which is printed through main( ).

#include<stdio.h>#include<conio.h>

void main() {

int i;float j,k,product();clrscr();

printf("Please enter an integer number: ");scanf("%d",&i);

printf("\nPlease enter a decimal number: ");scanf("%f",&j);

k=product(&i,&j);

printf("\nProduct = %.1f\n",k);

getch();

}

float product(int *a,float *b) {

float *c;

*c=(*a)*(*b);

return *c;

}

------------------------------------------------------------------------------------------------------------

(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<stdio.h>#include<conio.h>#include<math.h>

void main() {

int d1,d2,d3,d4,d5,i,sum,avg;float sd;

clrscr();

printf("enter five digits: \n\n");scanf("%d%d%d%d%d",&d1,&d2,&d3,&d4,&d5);

func(d1,d2,d3,d4,d5,&sum,&avg,&sd);

printf("\tsum = %d\n\taverage = %d\n\tstandard deviation = %f ",sum,avg,sd);

getch();

Solution:

Solution:

Page 599: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

}func(int a, int b, int c, int d, int e, int *s, int *av, float *ssd) {

float temp;

*s=a+b+c+d+e; /* sum of digits */*av=(a+b+c+d+e)/5; /* average */

a=a-(*av);b=b-(*av);c=c-(*av);d=d-(*av);e=e-(*av);

temp=((a*a)+(b*b)+(c*c)+(d*d)+(e*e))/4; /* standard deviation */*ssd=sqrt(temp);

return 0;

}

------------------------------------------------------------------------------------------------------------

(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( ).

#include<stdio.h>#include<conio.h>void main() {

int s1,s2,s3,*avg,*prcnt;void func();clrscr();

printf("Please enter the marks of 3 subjects: \n");scanf("%d%d%d",&s1,&s2,&s3);

func(s1,s2,s3,&avg,&prcnt);

printf(" Average = %d\nPercentage = %d%\n",avg,prcnt);

getch();

}void func(int a, int b, int c, int *d, int *f) {

*d=(a+b+c)/3;*f=(a+b+c)/3;

}_____________________________________________________________________

a) A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:(1) Without using recursion(2) Using recursion

Solution:

Exercise [J]

Solution:

Page 600: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

#include<stdio.h>#include<conio.h>void main() {

long num,s=0,ch;clrscr();

printf("Enter any number: ");scanf("%ld",&num);

printf("\n\nChoose: 1: obtain sum of digits non-recursively\n\n");printf(" 2: obtain sum of digits recursively\n\n\n");

printf("Your choice: ");ch=getche();

switch(ch) {

case '1':

while(num!=0) {

s=s+(num%10);

num=num/10;

}

printf("\n\n\nsum of digits = %d\n",s);

break;

case '2':

s=sum(num);

printf("\n\n\nSum of digits = %d\n",s);break;}

getch();

}

sum(long n) {

static s=0;

if(n==0)return s;

else {

s=s+n%10;n=sum(n/10);

return n;

}

}

-----------------------------------------------------------------------------------------------------------

(b) A positive integer is entered through the keyboard, write a program to obtain the prime factors of the number. Modify the function suitably to obtain the prime factors recursively.

Page 601: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

#include<stdio.h>#include<conio.h>void main() {

int d,ch,b=2;clrscr();

printf("Enter the number: ");

scanf("%d",&d);

printf("\n\nObtain prime factors:\n\n");printf("1: non-recursively\n\n");printf("2: recursively\n\n");

printf("your choice: ");scanf("%d",&ch);

switch(ch) {

case 1:

printf("\n\n\nPrime factors: ");while(d!=1) {

if(d%b==0) { /* non recursive method */d=d/b;printf("%d ",b);}elseb++;}break;

case 2:

printf("\n\n\nPrime factors: ");

factors(d);

break;

default:

printf("\n\nwrong input!");

break;}

getch();

}

int factors (int n) {

int b=2;

if(n==1)return 1;

else {

while(n!=1) {

if((n%b)==0) {

Solution:

Page 602: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

n=factors(n/b); /* recursive function */

printf("%d ",b);}

elseb++;

}return n;}

}

------------------------------------------------------------------------------------------------------------

(c) 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...

#include<stdio.h>#include<conio.h>void main() {

unsigned i,num=25,c=1;clrscr();

for(i=0;i<num;i++) {

printf("%u ",fib(c));

c++;}

getch();}

fib(unsigned n) {

if(n==0)return 0;

if(n==1)return 1;

else

return fib(n-1)+fib(n-2);

}

------------------------------------------------------------------------------------------------------------

(d) A positive integer is entered through the keyboard, write a function to find the binary equivalent of this number using recursion.

#include<stdio.h>#include<conio.h>void main() {

int num;

Solution:

Solution:

Page 603: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

clrscr();

printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,7);printf("<%c%c%c%c%c read right to left",196,196,196,196,196);

getch();

}

binary(int n) {

if(n==0)return 0;

else {

printf("%d",n%2);

n= binary( n/2 ); /* recursive function */

return n;

}

}------------------------------------------------------------------------------------------------------------

(e) Write a recursive function to obtain the running sum of first 25 natural numbers.

#include<stdio.h>#include<conio.h>void main() {

int i=25,j;clrscr();

j=recsum(i);

printf("Addition of 25 natural numbers = %d",j);

getch();

}

int recsum(int n) {

if(n==1)return 1;

else

n = n + recsum(n-1); /* recursive addition */

return n;

}

------------------------------------------------------------------------------------------------------------

(f) Write a C function to evaluate the series

Solution:

Page 604: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

sin(x) = x - (x3/3!) + ( x5/5!) - (x7/7!) + ........to five significant digits.

------------------------------------------------------------------------------------------------------------

(g) 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.

#include<stdio.h>#include<conio.h>void main() {

int x,y,z;char choice;void func();clrscr();

printf("Please enter values of X,Y,Z\n");scanf("%d",&x);scanf("%d",&y);scanf("%d",&z);

printf("\n\nBefore shift: X=%d Y=%d Z=%d\n",x,y,z);

func(&x,&y,&z); /* Call by reference */

printf("\n\nAfter shift: X=%d Y=%d Z=%d\n\n",x,y,z);

/* Circular Shifting continuously */

do {

printf("\nShift again(Y/N): ");scanf(" %c",&choice);

clrscr();

func(&x,&y,&z);printf("\nAfter another shift: X=%d Y=%d Z=%d\n\n",x,y,z);

}while(choice=='y');

}

void func(int *a,int *b,int *c) {

int d,e,f;

d=*a;e=*b;f=*c;*a=f;*b=d;*c=e;

}

Solution:

Solution:

Page 605: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

------------------------------------------------------------------------------------------------------------

(h) Write a function to find the binary equivalent of a given decimal integer and display it.

#include<stdio.h>#include<conio.h>void main() {

int num;void binary();

clrscr();

printf("\t\tDecimal Integer to Binary conversion\n\n\n");printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,10);printf("<%c%c%c%c%c",196,196,196,196,196);printf(" read right to left");

getch();}

void binary(int n) {

while(n!=0) {

printf("%d",n%2);

n=n/2;

}

}

------------------------------------------------------------------------------------------------------------

(i) If the lengths of the sides of a triangle are denoted by a, b, and c, then area of triangle is given byrootover ( S * (S-a) * (S-b) * (S-c))where, S = ( a + b + c ) / 2

#include<stdio.h>#include<conio.h>#include<math.h>void main() {

int s1,s2,s3,s;int area;clrscr();

printf("enter 3 sides of triangle: \n\n");scanf("%d%d%d",&s1,&s2,&s3);

s=s1+s2+s3/2;

area=func(s1,s2,s3,s);

Solution:

Solution:

Page 606: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

printf("\narea = %d",area);

getch();

}func(int i, int j, int k, int h) {

int ar,area;

ar=sqrt(h*((h-i)*(h-j)*(h-k)));

return (ar);

}

------------------------------------------------------------------------------------------------------------

(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.

------------------------------------------------------------------------------------------------------------

(k) Write a function to compute the greatest common divisor given by Euclid’s algorithm, exemplified for J = 1980, K = 1617 as follows:1980 / 1617 = 11980 – 1 * 1617 = 3631617 / 363 = 41617 – 4 * 363 = 165363 / 165 = 2363 – 2 * 165 = 335 / 33 = 5165 – 5 * 33 = 0Thus, the greatest common divisor is 33.

#include<stdio.h>#include<conio.h>void main() {

int a,b,r,d1,d2,temp;clrscr();

printf("Enter first number: ");scanf("%d",&a);

printf("\n\nEnter second number: ");scanf("%d",&b);

while(b!=0) {

r=a%b;

a=b;b=r;

Solution:

Solution:

Page 607: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

Posted by Chetan Raikwar at 07:02 No comments:

}

d1=a; /* devisor of first number */

temp=a;a=b;b=temp;

while(b!=0) {

r=a%b;a=b;b=r;

}

d2=a; /* devisor of second number */

printf("\n\n\nGreatest common devisor: ");

if(d1==d2) {

printf("%d",d1);

}

getch();

}______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 4 (The Case Control Structure)

Write a menu driven program which has following options:

1. Factorial of a number.2. Prime or not3. Odd or even4. Exit

#include<stdio.h>#include<conio.h>main() {

int num,i,j=0,k=0,choice,fact=1;clrscr();

printf("Please enter any number: ");scanf("%d",&num);

while(1){printf("\n\n1. Factorial");

Exercise [C]

Solution:

Page 608: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

printf("\n2. Prime");printf("\n3. Odd/Even");printf("\n4. Exit");printf("\n\nPlease enter your choice: ");scanf("%d",&choice);

switch(choice){

case 1:

for(i=num;i>=1;i--) { fact=fact*i; } printf("\nFactorial = %d ",fact); break;

case 2:

for(i=2;i<num;i++) { j=num%i; if(j==0){ k=1; break; } } if(k==0) { printf("\nPrime Number"); } else { printf("\nNot a Prime Number"); } break;

case 3:

if((num%2)==0) printf("\nEven Number"); else printf("\nOdd Number"); break;

case 4:

exit();

} }

}

------------------------------------------------------------------------------------------------------------

Write a program which to find the grace marks for a student using switch. The user should enter the class obtained by the student and the number of subjects he has failed in.

− If the student gets first class and the number of subjects he failed in is greater than 3, then he does not get any grace. If the number of subjects he failed in is less than or equal to 3 then the grace is of 5 marks per subject.

− If the student gets second class and the number of subjects he failed in is greater than 2, then he does not get any grace. If the number of

Exercise [D]

Page 609: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

Newer Posts Older PostsHome

Posted by Chetan Raikwar at 07:02 No comments:

subjects he failed in is less than or equal to 2 then the grace is of 4 marks per subject.

− If the student gets third class and the number of subjects he failed in is greater than 1, then he does not get any grace. If the number of subjects he failed in is equal to 1 then the grace is of 5 marks per subject

#include<stdio.h>#include<conio.h>main() {

int _class,f_sub;clrscr();

printf("\nPlease enter the class obtained\n1=first 2=second 3=third: ");scanf("%d",&_class);printf("\n\nPlease enter the number of failed subjects: ");scanf("%d",&f_sub);

switch(_class) {

case 1: if(f_sub<=3) { printf("\nGrace marks = 5 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

case 2: if(f_sub<=2) { printf("\nGrace marks = 4 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

case 3: if(f_sub==1) { printf("\nGrace marks = 5 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

default: printf("Error! wrong input.\n"); break; }

getch(); return 0;

}_____________________________________________________________________

Solution:

Recommend this on Google

Page 610: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:06:08 PM]

Subscribe to: Posts (Atom)

Simple template. Powered by Blogger.

Page 611: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

More Next Blog» Create Blog Sign In

Let us C solutions ( By Chetan )

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Thursday, 30 January 2014

Let Us C / Chapter 8 (Arrays)

Exercise [D]

(a) 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.

Solution:

#include<stdio.h> #include<conio.h>

void main() {

int i,arr[25],prsnt=0,num; clrscr();

printf("Please enter 25 numbers: \n");

for(i=0;i<25;i++) { scanf("%d",&arr[i]); }

printf("\n\nPlease enter the number to be searched: "); scanf("%d",&num);

for(i=0;i<25;i++) {

if(num==arr[i]) prsnt=prsnt+1;

}

Page 612: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

if(prsnt==0) { printf("\n\nNumber does not present in the array.\n"); }

else { printf("\n\nNumber presents in the array.\n"); printf("\nNumber of times it appears = %d.\n",prsnt); }

getch();

}

---------------------------------------------------------------------------------------------------------------

b) 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.

Solution:

#include<stdio.h>#include<conio.h>

void main() {

int i,arr[25],tz=0,tp=0,tn=0;clrscr();

printf("Enter numbers in the array: \n");

for(i=0;i<25;i++) {scanf("%d",&arr[i]);

if(arr[i]<0){tn=tn+1;}

if(arr[i]==0){tz=tz+1;}

if(arr[i]>0){tp=tp+1;}

}

printf("\n\n\nTotal zeros = %d\n",tz);printf("Total positive numbers = %d\n",tp);printf("Total negative numbers = %d\n",tn);

getch();

}

----------------------------------------------------------------------------------------------------------------

(c) Implement the Selection Sort, Bubble Sort and Insertion sort algorithms on a set of 25 numbers. (Refer Figure 8.11 for the logic of the algorithms)− Selection sort− Bubble Sort− Insertion Sort

Page 613: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

Solution:

----------------------------------------------------------------------------------------------------------------

(d) Implement the following procedure to generate prime numbers from 1 to 100 into a program. This procedure is called sieve of Eratosthenes.step 1Fill an array num[100] with numbers from 1 to 100step 2Starting with the second entry in the array, set all its multiples to zero.step 3Proceed to the next non-zero element and set all its multiples to zero.step 4Repeat step 3 till you have set up the multiples of all the non-zero elements to zerostep 5At the conclusion of step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers.

Solution:

#include<stdio.h>#include<conio.h>

void main() {

int i,j,a[100];clrscr();

for(i=0;i<100;i++) {

a[i]=i+1;

}

printf("\n100 numbers in the array:\n\n");

for(i=0;i<100;i++) {

printf("%3d ",a[i]);

}

printf("\n\nafter implementing eratothene's sieve:\n\n");

for(i=2;i<100;i++) {

for(j=2;j<a[i];j++) {

if(a[i]%j==0)a[i]=0;}}

i=a[0];for(;i<100;i++) {

printf("%3d ",a[i]);

}

printf("\n\nprime numbers are: \n\n");

Page 614: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

for(i=a[0];i<100;i++) {

if(a[i]!=0)

printf("%3d ",a[i]);

}

getch();}

---------------------------------------------------------------------------------------------------------------

Exercise [I]

(a) Write a program to copy the contents of one array into another in the reverse order.

Solution:

#include<stdio.h> #include<conio.h> void main() {

int i,j,k,a1[5],a2[5]; clrscr();

for(i=1;i<=5;i++) { scanf("%d",&a1[i]); }

printf("\n\nThe elements you enterd are:\n");

for(i=1;i<=5;i++) { printf(" %d",a1[i]); }

printf("\n\nElements in reversed order:\n");

for(i=5,j=1;i>=1,j<=5;i--,j++) {

k=a1[i]; a2[j]=k;

printf(" %d",a2[j]); }

getch(); }

---------------------------------------------------------------------------------------------------------------

(b) 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.

Solution:

#include<stdio.h>#include<conio.h>void main() {

int arr[100];int n,i,f=0;clrscr();

Page 615: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

printf("enter total elements of array(n): ");scanf("%d",&n);

printf("\n\nenter \"n\" elements of array: \n\n");

for(i=0;i<n;i++) {

scanf("%d",&arr[i]);

}

clrscr();

for(i=0;i<n;i++) {

if(arr[i]==arr[n-(i+1)]) { /* if element is equal, according to the problem, it will be printed */f=f+1;

printf("element no: %d = %d ",i,arr[i]);}

}

if(f==0)printf("\n\nNo such element found.\n");

getch();

}

---------------------------------------------------------------------------------------------------------------

(c) Find the smallest number in an array using pointers.

Solution:

#include<stdio.h> #include<conio.h> void main() {

int i,n,*p,*s,a[100]; clrscr();

printf("enter how many numbers you want to save in array: "); scanf("%d",&n);

printf("\n\nenter %d number in array:\n",n);

for(i=0;i<n;i++) {

scanf("%d",&a[i]);

}

clrscr();

printf("array you entered: \n\n");

for(i=0;i<n;i++) {

printf("%2d ",a[i]);

}

printf("\n\n");

p=&a[0]; /* first pointer points 0th element */

for(i=0;i<n;i++) {

Page 616: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

s=&a[i]; /* second pointer points every element one by one */

if(*p>*s) /* if first is bigger than second */ *p=*s; /* first becomes second */

s++; /* second is incremented to check with other elements */

}

printf("smallest digit in array is %d\n",*p);

getch(); }

----------------------------------------------------------------------------------------------------------------

(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( )

Solution:

#include<stdio.h> #include<conio.h> void main() {

int i,j,a[10]={1,2,3,4,5,6,7,8,9,10}; modify(); clrscr();

printf("array before modification: \n\n");

for(i=0;i<10;i++) {

printf(" %d ",a[i]);

}

modify(a); /* passing only the name of array */

printf("\n\n\narray after modification:\n\n");

for(i=0;i<10;i++) { /* printing the array in main(); */

printf(" %d ",a[i]);

}

getch();

}

modify(int b[10]) {

int c;

for(c=0;c<10;c++) {

b[c]=b[c]*3; /* multiplying each element with 3 */

} return b[c]; /* returning the whole array to main(); */

Page 617: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

}

----------------------------------------------------------------------------------------------------------

(e) The screen is divided into 25 rows and 80 columns. The characters that are displayed on the screen are stored in a special memory called VDU memory (not to be confused with ordinary memory). Each character displayed on the screen occupies two bytes in VDU memory. The first of these bytes contains the ASCII value of the character being displayed, whereas, the second byte contains the colour in which the character is displayed.For example, the ASCII value of the character present on zeroth row and zeroth column on the screen is stored at location number 0xB8000000. Therefore the colour of this character would be present at location number 0xB8000000 + 1. Similarly ASCII value of character in row 0, col 1 will be at location 0xB8000000 + 2, and its colour at 0xB8000000 + 3.With this knowledge write a program which when executed would keep converting every capital letter on the screen to small case letter and every small case letter to capital letter. The procedure should stop the moment the user hits a key from the keyboard.This is an activity of a rampant Virus called Dancing Dolls. (For monochrome adapter, use 0xB0000000 instead of 0xB8000000).

Solution:

_______________________________________________________________________

Exercise [L]

(a) How will you initialize a three-dimensional array threed[3][2][3]? How will you refer the first and last element in this array?

Solution:

#include<stdio.h>#include<conio.h>void main() {

/* initialization of a 3 dimensional array */

int threed[3][2][3]={ { {100,2,3}, {1,2,3} }, { {8,5,6}, {4,5,6} }, { {7,8,9}, {7,8,200} } };int *f,*l;clrscr();

f=&threed[0][0][0]; /* reference to first element */

Page 618: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

l=&threed[2][1][2]; /* reference to second element */

printf("\n\nfirst element = %d",*f);printf("\n\nlast element = %d",*l);

getch();

}

---------------------------------------------------------------------------------------------------------------

(b) Write a program to pick up the largest number from any 5 row by 5 column matrix.

Solution:

#include<stdio.h>#include<conio.h>

void main() {

int i,j,a[5][5];clrscr();

printf("\nType the numbers to in matrix:\n");

for(i=0;i<5;i++) {

for(j=0;j<5;j++) {

scanf("%d",&a[i][j]);

} }

clrscr();

printf("matrix you entered is:\n\n");

for(i=0;i<5;i++) {

for(j=0;j<5;j++) {

printf(" %2d ",a[i][j]);

}

printf("\n");

}

/* finding the largest number */

for(i=0;i<5;i++) {

for(j=0;j<5;j++) {

if(a[0][0]<a[i][j]) /* if number is larger than first element */

a[0][0]=a[i][j]; /* larger number is placed as the first element */

}

}

printf("\n\nThe largest number in matrix is: %d",a[0][0]);

Page 619: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

getch();

}

---------------------------------------------------------------------------------------------------------------

(c) 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.

Solution:

#include<stdio.h>#include<conio.h>#define MAX 4

void main() {

int i,j,a[4][4],b[4][4];clrscr();

printf("\nenter numbers in 5x5 matrix: \n\n");

for(i=0;i<MAX;i++) {

for(j=0;j<MAX;j++) {

scanf("%d",&a[i][j]);

}

}

clrscr();

printf("\nmatrix you entered is: \n\n");

for(i=0;i<MAX;i++) {

for(j=0;j<MAX;j++) {

printf("%2d ",a[i][j]);

}printf("\n");}

/* transpose of matrix */

for(i=0;i<MAX;i++) {

for(j=0;j<MAX;j++) {

b[j][i]=a[i][j];

}}

printf("\n\n");

/* printing the transpose */

printf("Transpose of matrix is: \n\n");

for(i=0;i<MAX;i++) {

for(j=0;j<MAX;j++) {

printf("%2d ",b[i][j]);

Page 620: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

}printf("\n");}

getch();}

----------------------------------------------------------------------------------------------------------------

(d) 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:

1 4 15 7 8 10 2 1114 3 6 1312 9 5

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 ) ; }

Solution:

Page 621: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

#include<stdio.h>#include<conio.h>#include<dos.h>

/* returns scan code of the key that has been hit */getkey(){union REGS i,o;while(!kbhit() );i.h.ah=0;int86(22,&i,&o);return(o.h.ah);}

void main() {

int i,j,a[16]={1,4,15,7,8,10,2,11,14,3,6,13,12,9,5,0};int temp,h,moves=0,won=0;

clrscr();

/****************************************************/

do { /**************/ /* to move up */ /**************/

if(h==72) {

for(i=0;i<16;i++) {if(a[i]==0){if(a[0]==0 || a[1]==0 || a[2]==0 || a[3]==0) {break;}temp=a[i];a[i]=a[i-4];a[i-4]=temp;moves=moves+1;break;}} } /****************/ /* to move left */ /****************/

if(h==75) {

for(i=0;i<16;i++) {

if(a[i]==0){if(a[0]==0 || a[4]==0 || a[8]==0 || a[12]==0) {break;}temp=a[i];a[i]=a[i-1];a[i-1]=temp;moves=moves+1;break;}} }

/****************/ /* to move down */ /****************/

Page 622: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

if(h==80) {for(i=0;i<16;i++) {if(a[i]==0){if(a[12]==0 || a[13]==0 || a[14]==0 || a[15]==0) {break;}temp=a[i];a[i]=a[i+4];a[i+4]=temp;moves=moves+1;break;}} } /*****************/ /* to move right */ /*****************/

if(h==77) {

for(i=0;i<16;i++) {

if(a[i]==0) {

if(a[3]==0 || a[7]==0 || a[11]==0 || a[15]==0 ) {break;}

temp=a[i];a[i]=a[i+1];a[i+1]=temp;moves=moves+1;break;} } }

/***********************************************************/

/**********************************/ /* printing the puzzle with boxes */ /**********************************/

printf("\n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n",218,196,196,196,194,196,196,196,194,196,196,196,194,196,196,196,191);for(i=0;i<=15;i++) {

printf("%c",179);

if(a[i]==0) {printf("%c ",32); /* printing a blank space in the puzzle */}if(a[i]!=0)

printf(" %2d",a[i]);

if(a[i]==a[3] || a[i]==a[7] || a[i]==a[11] || a[i]==a[15])printf("%c",179);

if(i==3||i==7||i==11)printf("\n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n",195,196,196,196,197,196,196,196,197,196,196,196,197,196,196,196,180);

if(a[0]==1 && a[1]==2 && a[2]==3 && a[3]==4 && a[4]==5 && a[5]==6&&a[6]==7 && a[7]==8 && a[8]==9 && a[9]==10 && a[11]==12 && a[12]==13&& a[13]==14 && a[14]==15 && a[15]==0 ) {

won=1;}

}printf("\n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n",192,196,196,196,193,196,196,196,193,196,196,196,193,196,196,196,217);

/***************************************************/if(won==1) {printf("\n\n\tCongratulations! you have won.");break;

Page 623: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

} /**********************************/ /* to print instructions for user */ /**********************************/

printf("\n\n\n\n\n\n Total Moves: %d\t\t\t\t Use arrow keys to move blank:\n\n",moves);printf("\t\t\t\t\t\t %c to move up\n",30);printf("\t\t\t\t\t\t %c to move down\n",31);printf("\t\t\t\t\t\t %c to move left\n",17);printf("\t\t\t\t\t\t %c to move right\n",16);

/****************************************************/

/**********************/ /* to take user input */ /**********************/

h=getkey();clrscr();

/****************************************************/

}while(h==72 || h==75 || h==77 ||h==80);

getch();

}

-----------------------------------------------------------------------------------------------------------------

(e) Those readers who are from an Engineering/Science background may try writing programs for following problems.(1) Write a program to add two 6 x 6 matrices.(2) Write a program to multiply any two 3 x 3 matrices.(3) Write a program to sort all the elements of a 4 x 4 matrix.(4) Write a program to obtain the determinant value of a 5 x 5 matrix.

Solution:

--------------------------------------------------------------------------------------------------------------

(j) Write a program that interchanges the odd and even components of an array.

Solution:

#include<stdio.h> #include<conio.h>

void main() {

int i,j,a[6],even,temp; clrscr();

printf("enter the numbers: \n\n");

for(i=0;i<6;i++) {

scanf("%d",&a[i]);

}

clrscr();

Page 624: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

printf("\narray without exchanging even and odd numbers:\n\n");

for(i=0;i<6;i++) {

printf("%2d ",a[i]);

}

printf("\n\narray after exchanging even and odd numbers: \n\n");

for(i=0;i<6;i++) {

for(j=i+1;j<6;j++) {

/* if one element is even and another after that is odd \ ,they will be exchanged */

if((a[i]%2)!=0 && (a[j]%2)==0) {

temp=a[j]; a[j]=a[i]; a[i]=temp; } } }

for(i=0;i<6;i++) {

printf("%2d ",a[i]);

}

getch(); }

--------------------------------------------------------------------------------------------------------------

(k) Write a program to find if a square matrix is symmetric.

Solution:

#include<stdio.h>#include<conio.h>

void main() {

int i,j,r,c,sym;int a[100][100],b[100][100];

clrscr();

printf(" enter number of rows of matrix: ");scanf("%d",&r);

printf("\n\nenter number of columns of matrix: ");scanf("%d",&c);

clrscr();

printf("enter the elements in matrix: \n");

for(i=0;i<r;i++) {

for(j=0;j<c;j++) {

scanf("%d",&a[i][j]);}

}

Page 625: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

clrscr();

printf("\nmatrix you entered is\n\n");

for(i=0;i<r;i++) {

for(j=0;j<c;j++) {

printf("%d ",a[i][j]);

}printf("\n");}

printf("\n\ntranspose of matrix is \n\n");

for(i=0;i<r;i++) {

for(j=0;j<c;j++) {

b[j][i]=a[i][j];

}}

for(i=0;i<r;i++) {

for(j=0;j<c;j++) {

printf("%d ",b[i][j]);

}printf("\n");}

/* finding if square matrix is equal to it's transpose to be symmetric */

for(i=0;i<r;i++) {

for(j=0;j<c;j++) {

if(a[i][j]!=b[i][j])

sym=1;

}

}

if(sym==1)printf("\nSquare matrix is not symmetric.\n");

elseprintf("\nSquare matrix is symmetric.\n");

getch();

}

----------------------------------------------------------------------------------------------------------------

(l) 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.

Solution:

#include<stdio.h>#include<conio.h>#include<math.h>

Page 626: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

void main() {

int i,j,r,c,a[100][100];int norm=0,sum=0;

clrscr();

printf("\nEnter the number of rows: ");scanf("%d",&r);

printf("\n\nEnter the number of coloumns: ");scanf("%d",&c);

clrscr();

printf("Enter elements of %d x %d array: \n\n",r,c);

for(i=0;i<r;i++) {

for(j=0;j<c;j++) {

scanf("%d",&a[i][j]);

}}

clrscr();

printf("\nmatrix you entered is: \n\n");

for(i=0;i<r;i++) {

for(j=0;j<c;j++) {

printf("%2d ",a[i][j]);

}printf("\n");}

/* norm of the matrix */

for(i=0;i<r;i++) {

for(j=0;j<c;j++) {

sum=sum+(a[i][j]*a[i][j]);

}

}

norm=sqrt(sum);

printf("\nNorm of matrix = %d",norm);

getch();}

----------------------------------------------------------------------------------------------------------------

(m) Given an array p[5], write a function to shift it circularly left by two positions. Thus, if p[0] = 15, p[1]= 30, p[2] = 28, p[3]= 19 and p[4] = 61 then after the shift p[0] = 28, p[1] = 19, p[2] = 61, p[3] = 15 and p[4] = 30. Call this function for a (4 x 5 ) matrix and get its rows left shifted.

Solution:

#include<stdio.h> #include<conio.h>

Page 627: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

void main() {

int i,j,p[]={15,30,28,19,61}; int a[4][5];

clrscr();

printf("Array before shift:\n\n"); for(i=0;i<5;i++) {

printf("%2d ",p[i]);

}

func(p);

printf("\n\nArray after shift:\n\n");

for(i=0;i<5;i++) {

printf("%2d ",p[i]);

}

printf("\n\n\nenter the elements of 4x5 matrix: \n\n");

for(i=0;i<4;i++) {

for(j=0;j<5;j++) {

scanf("%d",&a[i][j]);

}

}

clrscr();

printf("matrix you enterd before shift: \n\n");

for(i=0;i<4;i++) {

for(j=0;j<5;j++) {

printf("%2d ",a[i][j]);

}

printf("\n"); }

printf("\n\nafter shift:\n\n");

/* shift the rows of matrix */

for(i=0;i<4;i++) {

func(a[i]);

}

for(i=0;i<4;i++) {

for(j=0;j<5;j++) {

printf("%2d ",a[i][j]);

}

printf("\n");

}

Page 628: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

getch();

}

func(int q[5]) {

int a,t1,t2,t3;

t1=q[0]; t2=q[1];

q[0]=q[2]; q[1]=q[3]; q[2]=q[4]; q[3]=t1; q[4]=t2;

return q[5];

}----------------------------------------------------------------------------------------------------------

(n) A 6 x 6 matrix is entered through the keyboard and stored in a 2-dimensional array mat[7][7]. Write a program to obtain the Determinant values of this matrix.

Solution:

------------------------------------------------------------------------------

(o) For the following set of sample data, compute the standard deviation and the mean.-6, -12, 8, 13, 11, 6, 7, 2, -6, -9, -10, 11, 10, 9, 2

Solution:

#include<stdio.h> #include<conio.h> #include<math.h>

void main() {

int a[15]={-6,-12,8,13,11,6,7,2,-6,-9,-10,11,10,9,2}; int i,j; float temp,sd,sum=0,mean,x;

clrscr();

printf("\ndata set: \n\n");

for(i=0;i<15;i++) {

printf(" %3d ",a[i]);

}

printf("\n");

for(i=0;i<15;i++) {

sum=sum+a[i]; /* adding all the numbers */

}

mean=sum/15; /* calculating the mean */

Page 629: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

/* computing standard deviation */

for(i=0;i<15;i++) {

a[i]=pow((a[i]-mean),2); x=x+a[i]; }

temp=x/15; sd=sqrt(temp);

printf("\n\n\t\tmean= %f\n\t\tstandard deviation = %f\n",mean,sd);

getch(); }

--------------------------------------------------------------------------------------------------------------

(p) 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,Plot No. a b angle

137.4 80.9 0.78

155.2 92.62 0.89

149.3 97.93 1.35160.0 100.25 9.00

155.6 68.95 1.25

149.7 120.0 1.75

Solution:

#include<stdio.h> #include<conio.h> #include<math.h> void main() {

float a[6][3]={ {137.4, 80.9, 0.78}, {155.2, 92.62, 0.89}, {149.3, 97.93, 1.35}, {160.0, 100.25, 9.00}, {155.6, 68.95, 1.25}, {149.7, 120.0, 1.75} };

float big=0,area; int sr=0,i; clrscr();

for(i=0;i<6;i++) {

area=(1.0/2.0)*a[i][0]*a[i][1]*sin(a[i][2]);

Page 630: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

if(area>big) { big=area; sr=i; }

}

printf("\n\nPlot no. %d is the biggest.\n",sr); printf("\nArea of plot no. %d = %f\n",sr,big);

getch();

}

- ------------------------------------------------------------------------------------------------------------

(q) For the following set of n data points (x, y), compute the correlation coefficient r,

x y34.22 102.4339.87 100.93

41.85 97.4343.23 97.8140.06 98.3253.29 98.3253.29 100.0754.14 97.0849.12 91.5940.71 94.8555.15 94.65

Solution:

#include<stdio.h> #include<conio.h> #include<math.h>

void main() {

float a[][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},

Page 631: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

{53.29,100.07}, {54.14,97.08}, {49.12,91.59}, {40.71,94.85}, {55.15,94.65} };

int i,n=0; float x2,y2,x,y,x_y,n_x2,n_y2,r; clrscr();

for(i=0;i<11;i++) {

x2= x2 + ( a[i][0] * a[i][0] ); /* computing square of x */

y2= y2 + ( a[i][1] * a[i][1] ); /* computing square of y */

x= x + a[i][0]; /* computing total of x */

y= y + a[i][1]; /* computing total of y */

x_y= x_y + ( a[i][0] * a[i][1] ); /* computing total of x * y */

n++;

}

n_x2= n * x2;

n_y2= n * y2;

r= ( x_y - x*y )/sqrt((n_x2-x2) * (n_y2-y2));

printf(" sum of square of x = %f\n\n",x2); printf(" sum of square of y = %f\n\n",y2); printf(" sum of x = %f\n\n",x); printf(" sum of y = %f\n\n",y); printf(" sum of x * y = %f\n\n",x_y); printf(" sum of n*x2 = %f\n\n",n_x2); printf(" sum of n*y2 = %f\n\n",n_y2);

printf("\n\n\nCorrelation cofficient = %f\n",r);

getch();

} -------------------------------------------------------------------------------------------------------------

(r) For the following set of point given by (x, y) fit a straight line given by y = a + bx

x y 3.0 1.5 4.5 2.0 5.5 3.5 6.5 5.0

Page 632: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

7.5 6.0 8.5 7.5 8.0 9.0 9.0 10.5 9.5 12.0 10.0 14.0

Solution:

#include<stdio.h>#include<conio.h>#include<math.h>

void main() {

float data[][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,n=0;float sx,sy,x2,y2,xy,a,b,Y;

clrscr();

for(i=0;i<10;i++) {

sx = sx + data[i][0];

sy = sy + data[i][1];

x2= x2 + ( data[i][0] * data[i][0] );

y2= y2 + ( data[i][1] * data[i][1] );

xy = xy + ( data[i][0] * data[i][1] );

n++;

}

printf(" sum of x = %f\n",sx);printf(" sum of y = %f\n",sy);printf(" sum of x2 = %f\n",x2);printf(" sum of y2 = %f\n",y2);printf(" sum of x*y = %f\n",xy);printf(" total number = %d\n",n);

b = ( (n*xy) - (sx*sy) ) / ( n*x2 - (sx*sx) );

Page 633: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

a = (sy/n) - b*(sx/n);

Y= a + b*sx ;

printf("\n\nvalue of a = %f\n\n",a);

printf("value of b = %f\n\n",b);

printf(" Y = %f \n\n",Y);

getch();

}

-------------------------------------------------------------------------------------------------------------

(s) 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).

Solution:

#include<stdio.h> #include<conio.h> void main() {

float a[10][2],sx,sy; int i;

clrscr();

for(i=0;i<10;i++) {

printf("Enter coordinates of point number %d:\n\n",i+1);

printf("Value of X coordinate: "); scanf("%f",&a[i][0]);

printf("\nValue of Y coordinate: "); scanf("%f",&a[i][1]);

clrscr(); }

for(i=0;i<10;i++) {

if(i>0 && i<10-1) {

sx = sx + a[i][0];

sy = sy = a[i][1];

} }

printf(" First coordinate: X = %f\tY = %f\n\n",a[0][0],a[0][1]);

printf(" Last coordinate: X = %f\tY = %f\n\n",a[9][0],a[9][1]);

printf("\nDistance between them: X = %f\tY = %f\n",sx,sy);

getch(); } ______________________________________________________________________

Page 634: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-02-03T11:11:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:07:28 PM]

Posted by Chetan Raikwar at 07:03 No comments: Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest

Recommend this on Google

Newer Posts Older Posts Home Subscribe to: Posts (Atom)

Google+ Followers

Chetan Raikwar

2 have me in circles View all

Add to circles

About Me

Chetan Raikwar Follow

2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

Blog Archive

▼ 2014 (16)▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...Let Us C / Chapter 12 (File Input Output)Let Us C / Chapter 1 (Getting started)Let Us C / Chapter 3 (The Loop Control Structure)Let Us C / Chapter 4 (The Case Control Structure)Let Us C / Chapter 5 (Functions & Pointers)Let Us C / Chapter 6 (Data Types Revisited)Let Us C / Chapter 7 (The C Pre-processor)Let Us C / Chapter 8 (Arrays)Let Us C / Chapter 9 (Puppeting on Strings)Let Us C / Chapter 10 (Structures)Let Us C / Chapter 11 (Console Input Output)Let Us C / Chapter 13 (More Issues in Input Output...Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Simple template. Powered by Blogger.

Page 635: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

More Next Blog» Create Blog Sign In

Let us C solutions ( By Chetan )

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Thursday, 30 January 2014

Let Us C / Chapter 2 (The Decision Control Structure) Exercise [C]

(a) If cost price and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss he incurred.

Solution:

#include<stdio.h>#include<conio.h>main() {

int cp,sp,rslt;clrscr();

printf("Please enter the cost price of the item: \n");scanf("%d",&cp);

printf("Please enter the selling price of the item: \n");scanf("%d",&sp);

if(cp>sp) {rslt=cp-sp;printf("\nSeller has incurred LOSS of %d rupees.\n",rslt);}

if(cp<sp){rslt=sp-cp;printf("\nSeller has made PROFIT of %d rupees.\n",rslt);}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

Page 636: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

(b) Any integer is input through the keyboard. Write a program to find out whether it is an odd number or even number.

Solution:

#include<stdio.h>#include<conio.h>

main() {

int i;clrscr();

printf("Please enter the number: \n");scanf("%d",&i);

if(i%2==0)printf("\nThe number is EVEN.\n");

elseprintf("\nThe number is ODD.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(c) Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not.(Hint: Use the % (modulus) operator)

Solution:

#include<stdio.h>#include<conio.h>

main() {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4==0)printf("\nThe year is a LEAP YEAR.\n");

elseprintf("\nThe Year is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input through the keyboard write a program to find out what is the day on 1st January of this year.

Solution:

#include<stdio.h>

Page 637: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

#include<conio.h>

main() {

int month=1,year,a,day=1;

clrscr();

printf("Enter year: ");scanf("%d",&year);

/* 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 */

printf("\n\nFirst day is ");

if(day==0)printf("Sunday");

else if(day==1)printf("Monday");

else if(day==2)printf("Tuesday");

else if(day==3)printf("Wednesday");

else if(day==4)printf("Thursday");

else if(day==5)printf("Friday");

else if(day==6)printf("Saturday");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.

Solution:

#include<stdio.h>#include<conio.h>

main() {

long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();

printf("Please enter a five digit number: \n");scanf("%ld",&i);

Page 638: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

d1=i/10000;a=i%10000;

d2=a/1000;b=a%1000;

d3=b/100;c=b%100;

d4=c/10;d=c%10;

d5=d/1;

n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);

printf("\nThe REVERSED NUMBER is %ld \n",n_num);

if(n_num==i){printf("\nboth numbers are SAME.\n");}else {printf("\nboth number are NOT SAME.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the ages of Ram, Shyam and Ajay are input through the keyboard, write a program to determine the youngest of the three.

Solution:

#include<stdio.h>#include<conio.h>

main() {

int ram,shyam,ajay;clrscr();

printf("Please enter the age of RAM: ");scanf("%d",&ram);

printf("\nPlease enter the age of SHYAM: ");scanf("%d",&shyam);

printf("\nPlease enter the age or AJAY: ");scanf("%d",&ajay);

if(ram<shyam){if(ram<ajay) {printf("\nRam is the YOUNGEST.\n");} } if(shyam<ram){if(shyam<ajay) {printf("\nShyam is the YOUNGEST.\n");} }

if(ajay<ram) {if(ajay<shyam) {printf("\nAjay is the YOUNGEST.\n");

Page 639: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

} }

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(g)Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.

Solution:

#include<stdio.h>#include<conio.h>main() {

int a1,a2,a3;clrscr();

printf("Please enter the first angle: \n");scanf("%d",&a1);

printf("\nPlease enter the second angle: \n");scanf("%d",&a2);

printf("\nPlease enter the third angle: \n");scanf("%d",&a3);

if(a1+a2+a3==180) {printf("\nThe triangle is VALID.\n");}

else {printf("\nThe triangle is NOT VALID.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(h) Find the absolute value of a number entered through the keyboard.

Solution:

#include<stdio.h>#include<conio.h>#include<stdlib.h>main() {

int i,av;clrscr();

printf("Please enter any number: ");scanf("%d",&i);

av=abs(i);

/* abs(); is a standard function to calculate absolute value.\this function has been defined in <stdlib.h> library. */

Page 640: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

printf("Absolute value = %d",av);

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(i) Given the length and breadth of a rectangle, write a program to find whether the area of the rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and breadth = 4 is greater than its perimeter.

Solution:

#include<stdio.h>#include<conio.h>main() {

int l,b,area,peri;clrscr();

printf("Please enter the length and bredth of a rectangle: \n");scanf("%d%d",&l,&b);

area=l*b;peri=2*(l+b);

if(area>peri) {printf("\nThe Area of Rectangle is GREATER then it's perimeter.\n");}

else {printf("\nThe area of Rectangle is NOT GREATER then it's perimeter.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

Solution:

#include<stdio.h>#include<conio.h>main() {

int x1,y1,x2,y2,x3,y3,curve1,curve2;clrscr();

printf("Please enter the values of Three points: ");printf("\n(x1,y1):\n");scanf("%d%d",&x1,&y1);printf("\n(x2,y2):\n");scanf("%d%d",&x2,&y2);printf("\n(x3,y3):\n");scanf("%d%d",&x3,&y3);

curve1=(x2-x1)/(y2-y1);curve2=(x3-x2)/(y3-y2);

Page 641: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

if(curve1==curve2)printf("\nAll three points fall on one straight line.\n");elseprintf("\nThese three points do not fall on one straight line.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(k) Given the coordinates (x, y) of a center of a circle and it’s radius, write a program which will determine whether a point lies inside the circle, on the circle or outside the circle.(Hint: Use sqrt( ) and pow( ) functions)

Solution:

#include<stdio.h>#include<conio.h>#include<math.h>main() {

int x,y,x_,y_,r,point;clrscr();

printf("Please enter the coordinates of center: \n");printf("(x,y): ");scanf("%d%d",&x,&y);printf("\nPlease enter the radius of circle: \n");scanf("%d",&r);printf("\nPlease enter the point to check: \n");printf("(x`,y`): ");scanf("%d%d",&x_,&y_);

point=pow(x_,2)+pow(y_,2)+pow(x,2)+pow(y,2)-(2*x_*x)-(2*y_*y)-pow(r,2);

if(point<0)printf("\nThe point lies inside the circle.\n");

if(point>0)printf("\nThe point lies outside the circle.\n");

if(point==0)printf("\nThe point lies on the circle.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(l) Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis or at the origin, viz. (0, 0).

Solution:

#include<stdio.h>#include<conio.h>main() {

int x,y;clrscr();

Page 642: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

printf("Please enter points\n");printf("(x,y): \n");scanf("%d%d",&x,&y);

if(x==0&&y!=0) {printf("\nThe point lies on Y AXIS.\n");}

else if(x!=0&&y==0) {printf("\nThe point lies on X AXIS.\n");}

else if(x==0&&y==0) {printf("\nThe point lies at the origin.\n");}

else {printf("\nThe point doesn't lie on any axis or at origin.\n");}

getch();return 0;

}

___________________________________________________________________

Exercise [F]

(a) Any year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators && and ||.

Solution:

#include<stdio.h>#include<conio.h>main() {

int yr;clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

if(yr%4==0 || !((yr%4)>0) )printf("\nThe is a LEAP YEAR.\n");

elseprintf("\nThis is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol.The following table shows the range of ASCII values for various characters.

The following table shows the range of ASCII values for various

Page 643: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

characters.Characters

Characters ASCII values

A – Z 65 - 90a – z 97 - 1220 – 9 48 - 57special symbols 0 - 47, 58 - 64, 91 - 96, 123 - 127

Solution:

#include<stdio.h>#include<conio.h>main() {

char ch;clrscr();

printf("Please enter any character:");scanf("%c",&ch);

if(ch>=65&&ch<=90)printf("\nThe character you entered is a CAPITAL LETTER.\n");

if(ch>=97&&ch<=122)printf("\nThe character you entered is a SMALL LETTER.\n");

if(ch>=48&&ch<=57)printf("\nThe character you entered is a DIGIT.\n");

if(ch>=0&&ch<=47 || ch>=58&&ch<=64 || ch>=91&&ch<=96 || ch>=123&&ch<=127)printf("\nThe character you entered is a SPECIAL SYMBOL.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(c) An Insurance company follows following rules to calculate premium.(1) If a person’s health is excellent and the person is between 25 and 35 years of age and lives in a city and is a male then the premium is Rs. 4 per thousand and his policy amount cannot exceed Rs. 2 lakhs.(2) If a person satisfies all the above conditions except that the sex is female then the premium is Rs. 3 per thousand and her policy amount cannot exceed Rs. 1 lakh.(3) If a person’s health is poor and the person is between 25 and 35 years of age and lives in a village and is a male then the premium is Rs. 6 per thousand and his policy cannot exceed Rs. 10,000.(4) In all other cases the person is not insured.

Write a program to output whether the person should be insured or not, his/her premium rate and maximum amount for which he/she can be insured.

Solution:

Page 644: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

#include<stdio.h>#include<conio.h>main() {

int age,premium,p_a,hlt,rsdnc,sex;long amount;clrscr();

printf("Please tell the HEALTH of the person\n(1 for excellent or 2 for poor) :\n");scanf("%d",&hlt);

printf("Please tell the AGE of the person: \n");scanf("%d",&age);

printf("Please tell the residence\n(1 for city or 2 for village) : \n");scanf("%d",&rsdnc);

printf("Please tell you sex\n(1 for male or 2 for female) : \n");scanf("%d",&sex);

if(hlt==1 && age>=25&&age<=35 && rsdnc==1 && sex==1) {premium=4;amount=200000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==1||hlt==2 && age>=25&&age<=35 && rsdnc==1||rsdnc==2 && sex==2) {premium=3;amount=100000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==2 && age>=25&&age<=35 && rsdnc==2 && sex==1) {premium=6;amount=10000;

printf("\nThis person is insured.\n");printf("Premium rate is = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else {printf("\nThis person cannot be insured.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) A certain grade of steel is graded according to the following conditions:(i) Hardness must be greater than 50(ii) Carbon content must be less than 0.7(iii) Tensile strength must be greater than 5600

The grades are as follows:

Grade is 10 if all three conditions are metGrade is 9 if conditions (i) and (ii) are met

Page 645: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

Grade is 8 if conditions (ii) and (iii) are metGrade is 7 if conditions (i) and (iii) are metGrade is 6 if only one condition is metGrade is 5 if none of the conditions are met

Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and output the grade of the steel.

Solution:

#include<stdio.h>#include<conio.h>main() {

int hdn,tnsl,hardness=50,tensile_strength=5600;

float c,carbon_content=0.7;

clrscr();

printf("Please enter the Hardness: \n");scanf("%d",&hdn);

printf("\nPlease enter the Carbon content: \n");scanf("%f",&c);

printf("\nPlease enter the Tensile Strength: \n");scanf("%d",&tnsl);

if(hdn>hardness && c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 10.\n");

else if(hdn>hardness && c<carbon_content)printf("\nThe steel has been Graded 9.\n");

else if(c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 8.\n");

else if(hdn>hardness && tnsl>tensile_strength)printf("\nThe steel has been Graded 7.\n");

else if(hdn>hardness || c<carbon_content || tnsl>tensile_strength)printf("\nThe steel has been Graded 6.\n");

elseprintf("\nThe steel has been Graded 5.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A library charges a fine for every book returned late. For first 5 days the fine is 50 paise, for 6-10 days fine is one rupee and above 10 days fine is 5 rupees. If you return the book after 30 days your membership will be cancelled. Write a program to accept the number of days the member is late to return the book and display the fine or the appropriate message.

Solution:

Page 646: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

#include<stdio.h>#include<conio.h>main() {int days;clrscr();

printf("Please enter the days of being late in returning the book:\n");scanf("%d",&days);

if(days<=5)printf("\nYou have been fined for 50 paise.\n");

if(days>=6&&days<=10)printf("\nYou have been fined for 1 rupee.\n");

if(days>10&&days<30)printf("\nYou have been fined for 5 rupee.\n");

if(days>=30)printf("\nYour membership has been cancelled.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.

Solution:

#include<stdio.h>#include<conio.h>main() {

int s1,s2,s3,ls,ss1,ss2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d%d%d",&s1,&s2,&s3);

if(s1>s2&&s1>s3){ls=s1;ss1=s2;ss2=s3;}if(s2>s1&&s2>s3) {ls=s2;ss1=s1;ss2=s3;}if(s3>s1&&s3>s2) {ls=s3;ss1=s1;ss2=s2;}

if((ss1+ss2)>ls) {printf("\nThe Triangle is VALID.\n");}else {printf("The triangle is NOT VALID.\n");}

Page 647: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(g) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.

Solution:

#include<stdio.h>#include<conio.h>

main() {

int s1,s2,s3,largest,s_1,s_2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d %d %d",&s1,&s2,&s3);

if(s1==s2&&s1!=s3||s1==s3&&s1!=s2 || s2==s3&&s2!=s1||s2==s1&&s2!=s3 ||s3==s1&&s3!=s2||s3==s2&&s3!=s1){printf("The Triangle is ISOSCELES.\n");}

if(s1==s2&&s2==s3 || s2==s1&&s2==s3 || s3==s1&&s3==s2){printf("The Triangle is EQUILATERAL.\n");}

if(s1!=s2&&s2!=s3 || s2!=s1&&s1!=s3 || s3!=s1&&s1!=s2){printf("The Triangle is SCALENE.\n");}

if(s1>s2&&s1>s3){largest=s1;s_1=s2;s2=s3;}

if(s2>s1&&s2>s3){largest=s2;s_1=s1;s_2=s3;}

if(s3>s1&&s3>s2){largest=s3;s_1=s1;s_2=s2;}

if(pow(largest,2)==pow(s_1,2)+pow(s_2,2))printf("The Triangle is RIGHT ANGLED.\n");

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(h) In a company, worker efficiency is determined on the basis of the time required for a worker to complete a particular job. If the time taken by the worker is between 2 – 3 hours, then the worker is said to be highly efficient. If the time required by the worker is between 3 – 4

Page 648: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

hours, then the worker is ordered to improve speed. If the time taken is between 4 – 5 hours, the worker is given training to improve his speed, and if the time taken by the worker is more than 5 hours, then the worker has to leave the company. If the time taken by the worker is input through the keyboard, find the efficiency of the worker.

Solution:

#include<stdio.h>#include<conio.h>main() {

int hrs;clrscr();

printf("Please enter the hours of completing job: ");scanf("%d",&hrs);

if(hrs>=2 && hrs<=3)printf("\nThe worker is HIGHLY EFFICIENT.\n");

if(hrs>=3 && hrs<=4)printf("\nThe worker is ordered to IMPROVE SPEED.\n");

if(hrs>=4 && hrs<= 5)printf("\nThe worker should be given TRAINING TO IMPROVE SPEED.\n");

if(hrs>5)printf("\nThe worker should be asked to leave the company.\n");

elseprintf("The worker is HIGHLY EFFICIENT.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(i) A university has the following rules for a student to qualify for a degree with A as the main subject and B as the subsidiary subject: (a) He should get 55 percent or more in A and 45 percent or more in B. (b) If he gets than 55 percent in A he should get 55 percent or more in B. However, he should get at least 45 percent in A. (c) If he gets less than 45 percent in B and 65 percent or more in A he is allowed to reappear in an examination in B to qualify. (d) In all other cases he is declared to have failed.

Write a program to receive marks in A and B and Output whether the student has passed, failed or is allowed to reappear in B.

Solution:

#include<stdio.h>#include<conio.h>main() {

int a,b;clrscr();

printf("Please enter the marks in subject A: \n");scanf("%d",&a);

Page 649: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

printf("\nPlease enter the marks in subject B: \n");scanf("%d",&b);

if(a>=55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a==55 && b>=55 || a==55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a>=65 && b<45) {printf("Student is allowed to reappear in the exam of B to qualify.\n"); }

else {printf("Student has failed.\n"); }

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) The policy followed by a company to process customer orders is given by the following rules:

(a) If a customer order is less than or equal to that in stock and has credit is OK, supply has requirement.(b) If has credit is not OK do not supply. Send him intimation.(c) If has credit is Ok but the item in stock is less than has order, supply what is in stock. Intimate to him data the balance will be shipped.

Write a C program to implement the company policy.

Solution:

#include<stdio.h>#include<conio.h>main() {

int stock,credit,order;clrscr();

printf("Please enter the stock available: ");scanf("%d",&stock);printf("\nPlease enter the order: ");scanf("%d",&order);printf("\nPlease enter the credit: ");scanf("%d",&credit);

if(credit!=0&&order<=stock) {printf("\nSupply\n");}

else if(credit!=0&&order>stock) {printf("\nAvailable items will be supplied.\n");}

else {printf("\nNo supply.\n");}

Page 650: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

getch();return 0;

}______________________________________________________________________ Exercise [J]

(a) Using conditional operators determine: (1) Whether the character entered through the keyboard is a lower case alphabet or not.(2) Whether a character entered through the keyboard is a special symbol or not.

Solution:

#include<stdio.h>#include<conio.h>

char main() {

char ch;clrscr();

printf("Please enter a character: \n");scanf("%c",&ch);

if(ch>=97 && ch<=122) {printf("\n[A] This character is a SMALL CASE alphabet.\n");}

else {printf("\n[A] This character is NOT A SMALL CASE alphabet.\n");}

if(ch>=0&&ch<=47||ch>=58&&ch<=64||ch>=91&&ch<=96||ch>=123&&ch<=127){printf("\n[B] This character is a SPECIAL SYMBOL.\n");}

else{printf("\n[B] This character is NOT A SPECIAL SYMBOL.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Write a program using conditional operators to determine whether a year entered through the keyboard is a leap year or not.

Solution:

#include<stdio.h>#include<conio.h>main () {

int yr;clrscr();

Page 651: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

Posted by Chetan Raikwar at 06:42 No comments: Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest

Recommend this on Google

Newer Posts Home Subscribe to: Posts (Atom)

Google+ Followers

Chetan Raikwar

Add to circles

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4!=0)printf("\nThis is NOT A LEAP YEAR.\n");

elseprintf("\nThis is a LEAP YEAR.\n");

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(c) Write a program to find the greatest of the three numbers entered through the keyboard using conditional operators.

Solution:

#include<stdio.h>#include<conio.h>

main() {

int n1,n2,n3;clrscr();

printf("\nPlease enter 3 numbers: \n");scanf("%d %d %d",&n1,&n2,&n3);

if(n1>n2 && n1>n3) {printf("\n%d is the greatest number of the three numbers.\n",n1);}

else if(n2>n1 && n2>n3) {printf("\n%d is the greatest number of the three numbers.\n",n2);}

else if(n3>n2 && n3>n1) {printf("\n%d is the greatest number of the three numbers.\n",n3);}

else {printf("\nwrong input!\n");}

getch();return 0;

}

_______________________________________________________________________

Page 652: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&reverse-paginate=true&start=3&by-date=false[07-Apr-14 9:08:38 PM]

2 have me in circles View all

About Me

Chetan Raikwar Follow

2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

Blog Archive

▼ 2014 (16)▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...Let Us C / Chapter 12 (File Input Output)Let Us C / Chapter 1 (Getting started)Let Us C / Chapter 3 (The Loop Control Structure)Let Us C / Chapter 4 (The Case Control Structure)Let Us C / Chapter 5 (Functions & Pointers)Let Us C / Chapter 6 (Data Types Revisited)Let Us C / Chapter 7 (The C Pre-processor)Let Us C / Chapter 8 (Arrays)Let Us C / Chapter 9 (Puppeting on Strings)Let Us C / Chapter 10 (Structures)Let Us C / Chapter 11 (Console Input Output)Let Us C / Chapter 13 (More Issues in Input Output...Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Simple template. Powered by Blogger.

Page 653: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 5 (Functions & Pointers)

(a) Write a function to calculate the factorial value of any integer entered through the keyboard.

#include<stdio.h>#include<conio.h>

void main() {

int num;void func();

clrscr();

printf("Please enter any number: ");scanf("%d",&num);

func(num);

getch();

}

void func(int n) {

int fact=1;

for(;n>=1;n--) {

fact=fact*n;

}

printf("\n\nFactorial value = %d \n",fact);

}

------------------------------------------------------------------------------------------------------------

(b) Write a function power ( a, b ), to calculate the value of a raised to

Exercise [D]

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 654: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

b.

#include<stdio.h>#include<conio.h>

void main() {

int num1,num2 ;clrscr();

printf("Please enter the value of a: ");scanf("%d",&num1);

printf("\n\nPlease enter the value of b: ");scanf("%d",&num2);

power(num1,num2);

getch();

}

power(int a , int b) {

int c=1,i;

for(i=1;i<=b;i++) {c=c*a;

if(i==b) {break;}

}

printf("\n\n\nValue of %d raised to the power of %d is = %d\n",a,b,c);

return 0; }

------------------------------------------------------------------------------------------------------------

(c) Write a general-purpose function to convert any given year into its roman equivalent. The following table shows the roman equivalents of decimal numbers:

Decimal Roman

1 i5 v10 x50 l100 c500 d1000 m

Example:Roman equivalent of 1988 is mdcccclxxxviiiRoman equivalent of 1525 is mdxxv

Solution:

Page 655: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

#include<stdio.h>#include<conio.h>

void main() {

int yr;void func();

clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

printf("\n\nRoman Equivalent = ");func(yr);

getch();

}void func(int y) {

int d1,d2,d3,d4,d5,d6,d7,a,b,c,d,e,f;

char thsnd='m',hndr_5='d',hndr='c',ffty='l',tn='x',fv='v',one='i';

/******* Roman Convertion ********/

/* To find all thousands */

d1=y/1000;a=y%1000;

for(;d1>=1;d1--) {printf("%c",thsnd);

if(a==0)break;}

/* To find all five-hundreds */

d2=a/500;b=a%500;

for(;d2>=1;d2--) {printf("%c",hndr_5);

if(b==0)break;}

/* To find all hundreds */

d3=b/100;c=b%100;

for(;d3>=1;d3--) {printf("%c",hndr);

if(c==0)break;}

/* To find all fifties *//***********************/

Solution:

Page 656: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

d4=c/50;d=c%50;

for(;d4>=1;d4--) {printf("%c",ffty);

if(d==0)break;}

/* To find all tens *//********************/

d5=d/10;e=d%10;

for(;d5>=1;d5--) {printf("%c",tn);

if(e==0)break;

}

/* To find all fives */

d6=e/5;f=e%5;

for(;d6>=1;d6--) {printf("%c",fv);

if(f==0)break;}

/* To find all ones */

for(d7=f;d7>=1;d7--) {printf("%c",one);

}

}

------------------------------------------------------------------------------------------------------------

(d) Any year is entered through the keyboard. Write a function to determine whether the year is a leap year or not.

#include<stdio.h>#include<conio.h>void main() {

int yr;void func();clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

func(yr);

Solution:

Page 657: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

getch();

}void func(int y) {

if((y%4)==0)

printf("\nThis is a LEAP YEAR.\n");

else

printf("\nThis is NOT A LEAP YEAR.\n");

}

------------------------------------------------------------------------------------------------------------

(e) 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.

#include<stdio.h>#include<conio.h>

void main() {

int i,j,k;clrscr();

printf("enter the number: ");

scanf("%d",&j);

printf("\n\nprime factors:");

for(i=2;i<=j;) {

if(j%i==0) { /* divide only if remainder is supposed to be 0 */

j=j/i;

printf(" %d ",i); /* print the divisor */

}

else /* if divisor cannot divide completely */

i=i+1; /* increase it's value and try again */

}

getch();

}

________________________________________________________________________

(a) Write a function which receives a float and an int from main( ), finds

Solution:

Exercise [F]

Page 658: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

the product of these two and returns the product which is printed through main( ).

#include<stdio.h>#include<conio.h>

void main() {

int i;float j,k,product();clrscr();

printf("Please enter an integer number: ");scanf("%d",&i);

printf("\nPlease enter a decimal number: ");scanf("%f",&j);

k=product(&i,&j);

printf("\nProduct = %.1f\n",k);

getch();

}

float product(int *a,float *b) {

float *c;

*c=(*a)*(*b);

return *c;

}

------------------------------------------------------------------------------------------------------------

(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<stdio.h>#include<conio.h>#include<math.h>

void main() {

int d1,d2,d3,d4,d5,i,sum,avg;float sd;

clrscr();

printf("enter five digits: \n\n");scanf("%d%d%d%d%d",&d1,&d2,&d3,&d4,&d5);

func(d1,d2,d3,d4,d5,&sum,&avg,&sd);

printf("\tsum = %d\n\taverage = %d\n\tstandard deviation = %f ",sum,avg,sd);

getch();

Solution:

Solution:

Page 659: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

}func(int a, int b, int c, int d, int e, int *s, int *av, float *ssd) {

float temp;

*s=a+b+c+d+e; /* sum of digits */*av=(a+b+c+d+e)/5; /* average */

a=a-(*av);b=b-(*av);c=c-(*av);d=d-(*av);e=e-(*av);

temp=((a*a)+(b*b)+(c*c)+(d*d)+(e*e))/4; /* standard deviation */*ssd=sqrt(temp);

return 0;

}

------------------------------------------------------------------------------------------------------------

(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( ).

#include<stdio.h>#include<conio.h>void main() {

int s1,s2,s3,*avg,*prcnt;void func();clrscr();

printf("Please enter the marks of 3 subjects: \n");scanf("%d%d%d",&s1,&s2,&s3);

func(s1,s2,s3,&avg,&prcnt);

printf(" Average = %d\nPercentage = %d%\n",avg,prcnt);

getch();

}void func(int a, int b, int c, int *d, int *f) {

*d=(a+b+c)/3;*f=(a+b+c)/3;

}_____________________________________________________________________

a) A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:(1) Without using recursion(2) Using recursion

Solution:

Exercise [J]

Solution:

Page 660: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

#include<stdio.h>#include<conio.h>void main() {

long num,s=0,ch;clrscr();

printf("Enter any number: ");scanf("%ld",&num);

printf("\n\nChoose: 1: obtain sum of digits non-recursively\n\n");printf(" 2: obtain sum of digits recursively\n\n\n");

printf("Your choice: ");ch=getche();

switch(ch) {

case '1':

while(num!=0) {

s=s+(num%10);

num=num/10;

}

printf("\n\n\nsum of digits = %d\n",s);

break;

case '2':

s=sum(num);

printf("\n\n\nSum of digits = %d\n",s);break;}

getch();

}

sum(long n) {

static s=0;

if(n==0)return s;

else {

s=s+n%10;n=sum(n/10);

return n;

}

}

-----------------------------------------------------------------------------------------------------------

(b) A positive integer is entered through the keyboard, write a program to obtain the prime factors of the number. Modify the function suitably to obtain the prime factors recursively.

Page 661: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

#include<stdio.h>#include<conio.h>void main() {

int d,ch,b=2;clrscr();

printf("Enter the number: ");

scanf("%d",&d);

printf("\n\nObtain prime factors:\n\n");printf("1: non-recursively\n\n");printf("2: recursively\n\n");

printf("your choice: ");scanf("%d",&ch);

switch(ch) {

case 1:

printf("\n\n\nPrime factors: ");while(d!=1) {

if(d%b==0) { /* non recursive method */d=d/b;printf("%d ",b);}elseb++;}break;

case 2:

printf("\n\n\nPrime factors: ");

factors(d);

break;

default:

printf("\n\nwrong input!");

break;}

getch();

}

int factors (int n) {

int b=2;

if(n==1)return 1;

else {

while(n!=1) {

if((n%b)==0) {

Solution:

Page 662: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

n=factors(n/b); /* recursive function */

printf("%d ",b);}

elseb++;

}return n;}

}

------------------------------------------------------------------------------------------------------------

(c) 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...

#include<stdio.h>#include<conio.h>void main() {

unsigned i,num=25,c=1;clrscr();

for(i=0;i<num;i++) {

printf("%u ",fib(c));

c++;}

getch();}

fib(unsigned n) {

if(n==0)return 0;

if(n==1)return 1;

else

return fib(n-1)+fib(n-2);

}

------------------------------------------------------------------------------------------------------------

(d) A positive integer is entered through the keyboard, write a function to find the binary equivalent of this number using recursion.

#include<stdio.h>#include<conio.h>void main() {

int num;

Solution:

Solution:

Page 663: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

clrscr();

printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,7);printf("<%c%c%c%c%c read right to left",196,196,196,196,196);

getch();

}

binary(int n) {

if(n==0)return 0;

else {

printf("%d",n%2);

n= binary( n/2 ); /* recursive function */

return n;

}

}------------------------------------------------------------------------------------------------------------

(e) Write a recursive function to obtain the running sum of first 25 natural numbers.

#include<stdio.h>#include<conio.h>void main() {

int i=25,j;clrscr();

j=recsum(i);

printf("Addition of 25 natural numbers = %d",j);

getch();

}

int recsum(int n) {

if(n==1)return 1;

else

n = n + recsum(n-1); /* recursive addition */

return n;

}

------------------------------------------------------------------------------------------------------------

(f) Write a C function to evaluate the series

Solution:

Page 664: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

sin(x) = x - (x3/3!) + ( x5/5!) - (x7/7!) + ........to five significant digits.

------------------------------------------------------------------------------------------------------------

(g) 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.

#include<stdio.h>#include<conio.h>void main() {

int x,y,z;char choice;void func();clrscr();

printf("Please enter values of X,Y,Z\n");scanf("%d",&x);scanf("%d",&y);scanf("%d",&z);

printf("\n\nBefore shift: X=%d Y=%d Z=%d\n",x,y,z);

func(&x,&y,&z); /* Call by reference */

printf("\n\nAfter shift: X=%d Y=%d Z=%d\n\n",x,y,z);

/* Circular Shifting continuously */

do {

printf("\nShift again(Y/N): ");scanf(" %c",&choice);

clrscr();

func(&x,&y,&z);printf("\nAfter another shift: X=%d Y=%d Z=%d\n\n",x,y,z);

}while(choice=='y');

}

void func(int *a,int *b,int *c) {

int d,e,f;

d=*a;e=*b;f=*c;*a=f;*b=d;*c=e;

}

Solution:

Solution:

Page 665: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

------------------------------------------------------------------------------------------------------------

(h) Write a function to find the binary equivalent of a given decimal integer and display it.

#include<stdio.h>#include<conio.h>void main() {

int num;void binary();

clrscr();

printf("\t\tDecimal Integer to Binary conversion\n\n\n");printf("Enter the number: ");scanf("%d",&num);

printf("\n\n\nBinary equivalent: ");

binary(num);

gotoxy(20,10);printf("<%c%c%c%c%c",196,196,196,196,196);printf(" read right to left");

getch();}

void binary(int n) {

while(n!=0) {

printf("%d",n%2);

n=n/2;

}

}

------------------------------------------------------------------------------------------------------------

(i) If the lengths of the sides of a triangle are denoted by a, b, and c, then area of triangle is given byrootover ( S * (S-a) * (S-b) * (S-c))where, S = ( a + b + c ) / 2

#include<stdio.h>#include<conio.h>#include<math.h>void main() {

int s1,s2,s3,s;int area;clrscr();

printf("enter 3 sides of triangle: \n\n");scanf("%d%d%d",&s1,&s2,&s3);

s=s1+s2+s3/2;

area=func(s1,s2,s3,s);

Solution:

Solution:

Page 666: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

printf("\narea = %d",area);

getch();

}func(int i, int j, int k, int h) {

int ar,area;

ar=sqrt(h*((h-i)*(h-j)*(h-k)));

return (ar);

}

------------------------------------------------------------------------------------------------------------

(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.

------------------------------------------------------------------------------------------------------------

(k) Write a function to compute the greatest common divisor given by Euclid’s algorithm, exemplified for J = 1980, K = 1617 as follows:1980 / 1617 = 11980 – 1 * 1617 = 3631617 / 363 = 41617 – 4 * 363 = 165363 / 165 = 2363 – 2 * 165 = 335 / 33 = 5165 – 5 * 33 = 0Thus, the greatest common divisor is 33.

#include<stdio.h>#include<conio.h>void main() {

int a,b,r,d1,d2,temp;clrscr();

printf("Enter first number: ");scanf("%d",&a);

printf("\n\nEnter second number: ");scanf("%d",&b);

while(b!=0) {

r=a%b;

a=b;b=r;

Solution:

Solution:

Page 667: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

Posted by Chetan Raikwar at 07:02 No comments:

}

d1=a; /* devisor of first number */

temp=a;a=b;b=temp;

while(b!=0) {

r=a%b;a=b;b=r;

}

d2=a; /* devisor of second number */

printf("\n\n\nGreatest common devisor: ");

if(d1==d2) {

printf("%d",d1);

}

getch();

}______________________________________________________________________

Recommend this on Google

Let Us C / Chapter 4 (The Case Control Structure)

Write a menu driven program which has following options:

1. Factorial of a number.2. Prime or not3. Odd or even4. Exit

#include<stdio.h>#include<conio.h>main() {

int num,i,j=0,k=0,choice,fact=1;clrscr();

printf("Please enter any number: ");scanf("%d",&num);

while(1){printf("\n\n1. Factorial");

Exercise [C]

Solution:

Page 668: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

printf("\n2. Prime");printf("\n3. Odd/Even");printf("\n4. Exit");printf("\n\nPlease enter your choice: ");scanf("%d",&choice);

switch(choice){

case 1:

for(i=num;i>=1;i--) { fact=fact*i; } printf("\nFactorial = %d ",fact); break;

case 2:

for(i=2;i<num;i++) { j=num%i; if(j==0){ k=1; break; } } if(k==0) { printf("\nPrime Number"); } else { printf("\nNot a Prime Number"); } break;

case 3:

if((num%2)==0) printf("\nEven Number"); else printf("\nOdd Number"); break;

case 4:

exit();

} }

}

------------------------------------------------------------------------------------------------------------

Write a program which to find the grace marks for a student using switch. The user should enter the class obtained by the student and the number of subjects he has failed in.

− If the student gets first class and the number of subjects he failed in is greater than 3, then he does not get any grace. If the number of subjects he failed in is less than or equal to 3 then the grace is of 5 marks per subject.

− If the student gets second class and the number of subjects he failed in is greater than 2, then he does not get any grace. If the number of

Exercise [D]

Page 669: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

Posted by Chetan Raikwar at 07:02 No comments:

subjects he failed in is less than or equal to 2 then the grace is of 4 marks per subject.

− If the student gets third class and the number of subjects he failed in is greater than 1, then he does not get any grace. If the number of subjects he failed in is equal to 1 then the grace is of 5 marks per subject

#include<stdio.h>#include<conio.h>main() {

int _class,f_sub;clrscr();

printf("\nPlease enter the class obtained\n1=first 2=second 3=third: ");scanf("%d",&_class);printf("\n\nPlease enter the number of failed subjects: ");scanf("%d",&f_sub);

switch(_class) {

case 1: if(f_sub<=3) { printf("\nGrace marks = 5 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

case 2: if(f_sub<=2) { printf("\nGrace marks = 4 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

case 3: if(f_sub==1) { printf("\nGrace marks = 5 marks per subject.\n"); } else { printf("\nNo Grace marks.\n"); } break;

default: printf("Error! wrong input.\n"); break; }

getch(); return 0;

}_____________________________________________________________________

Solution:

Recommend this on Google

Page 670: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

Let Us C / Chapter 3 (The Loop Control Structure)

(a) Write a program to calculate overtime pay of 10 employees. Overtime is paid at the rate of Rs. 12.00 per hour for every hour worked above 40 hours. Assume that employees do not work for fractional part of an hour.

#include<stdio.h>#include<conio.h>

main() {

int wrkh,hr,emp,pay,r=12;clrscr();

printf("Please enter working hours of 10 employees: \n\n");

emp=1;

while(emp<=10) {

printf("\n\nEnter working hours of employee: ",emp);

scanf("%d",&wrkh);

if(wrkh>40) {

hr=wrkh-40;pay=hr*r;

printf("\n%d\tOver-time pay %d rs\n",emp,pay);

}

else {

printf("\n%d\tNo over time pay\n",emp);

}

emp++;

}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Write a program to find the factorial value of any number entered through the keyboard.

#include<stdio.h>#include<conio.h>

main() {

Exercise [B]

Solution:

Solution:

Page 671: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

long i,j,fact=1;clrscr();

printf("Please enter any number: ");scanf("%ld",&i);

for(j=i;j>=1;j--) {

fact=fact*j;

}

printf("Factorial value = %ld ",fact);

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(c) Two numbers are entered through the keyboard. Write a program to find the value of one number raised to the power of another.

#include<stdio.h>#include<conio.h>

main() {

int num1,num2,i,rslt=1;clrscr();

printf("Enter two numbers: \n");scanf("%d%d",&num1,&num2);

for(i=1;i<=num2;i++) {rslt=rslt*num1;

if(i==num2) {break;}

}

printf("\n\nvalue of %d raised to the power of %d is = %d\n",num1,num2,rslt);

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) Write a program to print all the ASCII values and their equivalent characters using a while loop. The ASCII values vary from 0 to 255.

#include<stdio.h>#include<conio.h>main() {

Solution:

Solution:

Page 672: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

int i=0;clrscr();

while(i<=255) {

printf(" %d %c \n",i,i);i++;

}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(e) Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number. For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 )

#include<stdio.h>#include<conio.h>

main() {

int i,a,b,c,d,e;clrscr();

printf("All Armstrong Numbers between 1-500 are: \n\n");

for(i=1;i<=500;i++) {

if(i<9) { /* for one digit numbers */a=i/1;

if((a*a*a)==(a*1)) {printf(" %d ",i);

} }

if(i>9 && i<100) { /* for two digit numbers */

a=i/10;b=i%10;c=b/1;

if(((a*a*a)+(c*c*c))==((a*10)+(c*1))) {printf(" %d ",i);

}}

if(i>99) { /* for three digit numbers */

a=i/100;b=i%100;c=b/10;d=b%10;e=d/1;

if(((a*a*a)+(c*c*c)+(e*e*e))==((a*100)+(c*10)+(e*1))){

printf(" %d ",i);

Solution:

Page 673: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

} }

}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) Write a program for a matchstick game being played between the computer and a user. Your program should ensure that the computer always wins. Rules for the game are as follows:− There are 21 matchsticks.− The computer asks the player to pick 1, 2, 3, or 4 matchsticks.− After the person picks, the computer does its picking.− Whoever is forced to pick up the last matchstick loses the game.

#include<stdio.h>#include<conio.h>

main() {

int tms=21,lms=0,user,cpu,pms=0;char another;

clrscr();

do {

printf("\nPick up 1,2,3 or 4 matchsticks: ");scanf("%d",&user); /* Matchsticks picked by you */

cpu=user; /* Matchsticks picked by computer */

if(pms<20) {printf("\nyou picked = %d\tcomputer picked = %d\n",user,cpu);}else {printf("\nyou picked =%d\n",user);}

pms=pms+(cpu+user); /* Total picked Matchsticks */

lms=tms-pms; /* Total left matchsticks */

if(pms<=21) {printf("\nleft matchsticks = %d\n",lms);}else {break;}

printf("\nPick again Y/N: ");scanf(" %c",&another);

}while(another=='y');

printf("\n\n\n");printf("\n==============\n");

Solution:

Page 674: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

printf("\nComputer wins!\n");printf("\n==============\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(g) Write a program to enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros entered.

#include<stdio.h>#include<conio.h>

main() {

int num,tnum=0,tp=0,tn=0,tz=0;char another;

clrscr();

do {printf("\nEnter any number: ");scanf("%d",&num);

tnum=tnum+1; /* count of total numbers entered by you */

if(num==0) /* count of total zeros */tz=tz+1;

if(num>0) /* count of total positive numbers */tp=tp+1;

if(num<0) /* count of total negative number */tn=tn+1;

printf("\nEnter another number Y/N: ");scanf(" %c",&another);

}while(another=='y');

clrscr();

printf("\n\n\nTotal numbers entered = %d\n",tnum);printf("\nTotal zeros = %d\n",tz);printf("\nTotal positive numbers = %d\n",tp);printf("\nTotal negative numbers = %d\n",tn);

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(h) Write a program to find the octal equivalent of the entered number.

#include<stdio.h>#include<conio.h>main() {

Solution:

Solution:

Page 675: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

long num,n;clrscr();

printf("Please enter the number: ");scanf("%ld",&num);printf("\n\nOctal equivalent: ");

while(num!=0) {

n=num%8;

printf("%ld",n);

num=num/8; /* devision by 8 */

}

gotoxy(20,6);printf("<%c%c%c%c%c read from right to left",196,196,196,196,196);

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(i) Write a program to find the range of a set of numbers. Range is the difference between the smallest and biggest number in the list

#include<stdio.h>#include<conio.h>main() {

int min,max,num,range,flag=0;char ch;

clrscr();

do {

printf("\nEnter number: ");scanf("%d",&num);

if(flag==0) {

min=num;max=num;}

flag++; /* counting total numbers */

if(min>num) {min=num;}

if(max<num)max=num;

printf("\n\nEnter another number(Y/N): ");scanf(" %c",&ch);

clrscr();}while(ch=='Y' || ch=='y');

range=max-min;

printf("\nTotal number = %d\n",flag);

Solution:

Page 676: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

printf("\nLargest number = %d\n",max);printf("\nSmallest number = %d\n",min);printf("\nRange = %d\n",range);

getch();return 0;}______________________________________________________________________

(a) Write a program to print all prime numbers from 1 to 300. (Hint: Use nested loops, break and continue)

#include<stdio.h>#include<conio.h>main() {

int i=1,j;

clrscr();

printf("\nPrime numbers between 1 to 300 are:\n\n");

while(i!=300) {

j=2;

while(j<i) {

if(i%j==0) {break;}

j++;

}

if(j==i) {

printf(" %d",i);

}

i++;}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Write a program to fill the entire screen with a smiling face. The smiling face has an ASCII value 1.

#include<stdio.h>#include<conio.h>main() {

int i;clrscr();

Exercise [E]

Solution:

Solution:

Page 677: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

for(i=1;i<=10000;i++) {printf("%c",1);}

getch();return 0;

------------------------------------------------------------------------------------------------------------

(c) Write a program to add first seven terms of the following series using a for loop:

1/1! + 2/2! + 3/3! + .............

#include<stdio.h>#include<conio.h>

main() {

float i,j,k,fact=1,factsum,numsum;clrscr();

printf("\tTerm\t\tFactorial\n\n");

for(i=1;i<=7;i++) {

for(j=i;j>=2;j--) {

fact=fact*j;factsum=factsum+fact;break;}numsum=numsum+i;printf("\t%.0f\t\t%.0f\n",i,fact);}

k=numsum/factsum;

printf("\n\nsum of 7 terms = %.0f ",numsum);printf("\nsum of all factorials = %.0f",factsum);printf("\n\naddition of all terms / sum of factorials: %f",k);

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(d) Write a program to generate all combinations of 1, 2 and 3 using for loop.

#include<stdio.h>#include<conio.h>main() {

int i,j,k;clrscr();

printf("All combinations of 1,2,3 are:\n\n");for(i=1;i<=3;i++) {for(j=1;j<=3;j++) {

Solution:

Solution:

Page 678: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

for(k=1;k<=3;k++) {printf(" %d%d%d ",i,j,k);} } }

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(e) According to a study, the approximate level of intelligence of a person can be calculated using the following formula:i = 2 + ( y + 0.5 x )Write a program, which will produce a table of values of i, y and x, where y varies from 1 to 6, and, for each value of y, x varies from 5.5 to 12.5 in steps of 0.5.

#include<stdio.h>#include<conio.h>main() {

float i=1,x,y;clrscr();

for(y=1.0;y<=6.0;y++) {

for(x=5.5;x<=12.5;x+=0.5) {

i=2+(y+(0.5*0.5));

printf("%.2f\t%.2f\t%.2f\n",i,y,x);

}

}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) Write a program to produce the following output:

A B C D E F G F E D C B AA B C D E F F E D C B AA B C D E E D C B AA B C D D C B AA B C C B AA B B AA A

#include<stdio.h>#include<conio.h>main() {

Solution:

Solution:

Page 679: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

int i,j,k,l;clrscr();

for(i=71;i>=65;i--) {

/* loop for printing ascending letters */

for(j=65;j<=i;j++) {

printf("%c ",j);

}

/* loop for making a space between patterns */

for(k=i+1;k<=71;k++) {

if(k==71)printf(" ");

if(k<71)printf(" ");}

/* loop to print descending letters */

for(l=i;l>=65;l--) {

if(l==71) { /* to skip printing 'G' twice */continue;}

printf("%c ",l);

}printf("\n");}

getch();

return 0;}

------------------------------------------------------------------------------------------------------------

(g) Write a program to fill the entire screen with diamond and heart alternatively. The ASCII value for heart is 3 and that of diamond is 4.

#include<stdio.h>#include<conio.h>main() {

int i,j;clrscr();

for(i=j=1;i<=10000,j<=10000;i++,j++) {printf("%c%c",4,3);}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(h) Write a program to print the multiplication table of the number

Solution:

Page 680: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

entered by the user. The table should get displayed in the following form.29 * 1 = 2929 * 2 = 58…

#include<stdio.h>#include<conio.h>main() {

int i,j,k;clrscr();

printf("Please enter the number:\n");scanf("%d",&i);

for(j=1;j<=10;j++) {k=i*j;printf("\n%d*%d = %d\n",i,j,k);}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(i) Write a program to produce the following output: 1 2 3 4 5 67 8 9 10

#include<stdio.h>#include<conio.h>void main() {

int i,num=0,k,j;clrscr();

for(i=1;i<=4;i++) {

for(j=4;j>=i;j--) { /* loop for making a space from left corner */

printf(" ");

}

for(k=1;k<=i;k++) {

num=num+1; /* incrementing external number for printing */

printf(" %d ",num);

}

printf("\n\n");}

Solution:

Solution:

Page 681: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

getch();

}

-----------------------------------------------------------------------------------------------------------

(j) Write a program to produce the following output:

1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

#include<stdio.h>#include<conio.h>main() {

int i,j,k;clrscr();

printf(" 1\n\n\n");

for(i=1;i<=4;i++) {

for(k=5;k>=i;k--) {printf(" ");}printf("1 ");

for(j=1;j<=i;j++) {

if(i==4 && j==3) {printf("%d ",i+j-1);continue;}

if(j>1)printf("%d ",i);

}

printf("1\n\n\n");

}

getch();return 0;

}

-----------------------------------------------------------------------------------------------------------

(k) A machine is purchased which will produce earning of Rs. 1000 per year while it lasts. The machine costs Rs. 6000 and will have a salvage of Rs. 2000 when it is condemned. If 12 percent per annum can be earned on alternate investments what would be the minimum life of the machine to make it a more attractive investment compared to alternative investment?

#include <stdio.h>

Solution:

Solution:

Page 682: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

#include <conio.h>int main(){int year=0,inv,altn;

while(altn>inv) {

year+=1;altn=120*year;inv=(1000*year)-(6000-2000);

}

printf("Minimum life of the machine would be = %d",year); getch(); return 0;}------------------------------------------------------------------------------------------------------------

(l) When interest compounds q times per year at an annual rate of r % for n years, the principle p compounds to an amount a as per the following formulaa = p ( 1 + r / q ) nqWrite a program to read 10 sets of p, r, n & q and calculate the corresponding as.

#include<stdio.h>#include<conio.h>main() {

int i,p,r,n,q,j,pw;float a;

clrscr();

for(i=0;i<10;i++) {

printf("Set number %d:\n\n\n\n",i+1);

printf("Enter p: ");scanf("%d",&p);

printf("\n\nEnter r: ");scanf("%d",&r);

printf("\n\nEnter n: ");scanf("%d",&n);

printf("\n\nEnter q: ");scanf("%d",&q);

pw=n*q;

for(j=0;j<pw;j++) {

a = a + p *(1+r/1);

}printf("\n\n\nA = %f\n",a);

printf("\n\n\n\npress any key to proceed...");getch();

clrscr();}

Solution:

Page 683: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:04:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:09:35 PM]

Newer Posts Older PostsHome

Subscribe to: Posts (Atom)

Posted by Chetan Raikwar at 07:02 No comments:

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(m) The natural logarithm can be approximated by the following series.x-1/x + 1/2(x-1/x)2 + 1/2(x-1/x)3 + 1/2(x-1/x)4 + --------If x is input through the keyboard, write a program to calculate the sum of first seven terms of this series.

#include<stdio.h>#include<conio.h>#include<math.h>main() {

float x,nl,x_1,t1;int i;

clrscr();

printf("\n\nEnter the value of X: ");scanf("%f",&x);

t1 = (x-1)/x; /* fist term */

for(i=2;i<=7;i++) {

nl = (1.0/2.0) * pow((x_1),i); /* terms from 2 to 7 */

}

nl = nl + t1; /* adding all the terms */

printf("\n\nApproximated natural log = %f\n",nl);

getch();return 0;}___________________________________________________________________

Solution:

Recommend this on Google

Simple template. Powered by Blogger.

Page 684: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

More Next Blog» Create Blog Sign In

Let us C solutions ( By Chetan )

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Thursday, 30 January 2014

Let Us C / Chapter 2 (The Decision Control Structure) Exercise [C]

(a) If cost price and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss he incurred.

Solution:

#include<stdio.h>#include<conio.h>main() {

int cp,sp,rslt;clrscr();

printf("Please enter the cost price of the item: \n");scanf("%d",&cp);

printf("Please enter the selling price of the item: \n");scanf("%d",&sp);

if(cp>sp) {rslt=cp-sp;printf("\nSeller has incurred LOSS of %d rupees.\n",rslt);}

if(cp<sp){rslt=sp-cp;printf("\nSeller has made PROFIT of %d rupees.\n",rslt);}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

Page 685: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

(b) Any integer is input through the keyboard. Write a program to find out whether it is an odd number or even number.

Solution:

#include<stdio.h>#include<conio.h>

main() {

int i;clrscr();

printf("Please enter the number: \n");scanf("%d",&i);

if(i%2==0)printf("\nThe number is EVEN.\n");

elseprintf("\nThe number is ODD.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(c) Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not.(Hint: Use the % (modulus) operator)

Solution:

#include<stdio.h>#include<conio.h>

main() {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4==0)printf("\nThe year is a LEAP YEAR.\n");

elseprintf("\nThe Year is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input through the keyboard write a program to find out what is the day on 1st January of this year.

Solution:

#include<stdio.h>

Page 686: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

#include<conio.h>

main() {

int month=1,year,a,day=1;

clrscr();

printf("Enter year: ");scanf("%d",&year);

/* 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 */

printf("\n\nFirst day is ");

if(day==0)printf("Sunday");

else if(day==1)printf("Monday");

else if(day==2)printf("Tuesday");

else if(day==3)printf("Wednesday");

else if(day==4)printf("Thursday");

else if(day==5)printf("Friday");

else if(day==6)printf("Saturday");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.

Solution:

#include<stdio.h>#include<conio.h>

main() {

long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();

printf("Please enter a five digit number: \n");scanf("%ld",&i);

Page 687: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

d1=i/10000;a=i%10000;

d2=a/1000;b=a%1000;

d3=b/100;c=b%100;

d4=c/10;d=c%10;

d5=d/1;

n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);

printf("\nThe REVERSED NUMBER is %ld \n",n_num);

if(n_num==i){printf("\nboth numbers are SAME.\n");}else {printf("\nboth number are NOT SAME.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the ages of Ram, Shyam and Ajay are input through the keyboard, write a program to determine the youngest of the three.

Solution:

#include<stdio.h>#include<conio.h>

main() {

int ram,shyam,ajay;clrscr();

printf("Please enter the age of RAM: ");scanf("%d",&ram);

printf("\nPlease enter the age of SHYAM: ");scanf("%d",&shyam);

printf("\nPlease enter the age or AJAY: ");scanf("%d",&ajay);

if(ram<shyam){if(ram<ajay) {printf("\nRam is the YOUNGEST.\n");} } if(shyam<ram){if(shyam<ajay) {printf("\nShyam is the YOUNGEST.\n");} }

if(ajay<ram) {if(ajay<shyam) {printf("\nAjay is the YOUNGEST.\n");

Page 688: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

} }

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(g)Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.

Solution:

#include<stdio.h>#include<conio.h>main() {

int a1,a2,a3;clrscr();

printf("Please enter the first angle: \n");scanf("%d",&a1);

printf("\nPlease enter the second angle: \n");scanf("%d",&a2);

printf("\nPlease enter the third angle: \n");scanf("%d",&a3);

if(a1+a2+a3==180) {printf("\nThe triangle is VALID.\n");}

else {printf("\nThe triangle is NOT VALID.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(h) Find the absolute value of a number entered through the keyboard.

Solution:

#include<stdio.h>#include<conio.h>#include<stdlib.h>main() {

int i,av;clrscr();

printf("Please enter any number: ");scanf("%d",&i);

av=abs(i);

/* abs(); is a standard function to calculate absolute value.\this function has been defined in <stdlib.h> library. */

Page 689: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

printf("Absolute value = %d",av);

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(i) Given the length and breadth of a rectangle, write a program to find whether the area of the rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and breadth = 4 is greater than its perimeter.

Solution:

#include<stdio.h>#include<conio.h>main() {

int l,b,area,peri;clrscr();

printf("Please enter the length and bredth of a rectangle: \n");scanf("%d%d",&l,&b);

area=l*b;peri=2*(l+b);

if(area>peri) {printf("\nThe Area of Rectangle is GREATER then it's perimeter.\n");}

else {printf("\nThe area of Rectangle is NOT GREATER then it's perimeter.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

Solution:

#include<stdio.h>#include<conio.h>main() {

int x1,y1,x2,y2,x3,y3,curve1,curve2;clrscr();

printf("Please enter the values of Three points: ");printf("\n(x1,y1):\n");scanf("%d%d",&x1,&y1);printf("\n(x2,y2):\n");scanf("%d%d",&x2,&y2);printf("\n(x3,y3):\n");scanf("%d%d",&x3,&y3);

curve1=(x2-x1)/(y2-y1);curve2=(x3-x2)/(y3-y2);

Page 690: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

if(curve1==curve2)printf("\nAll three points fall on one straight line.\n");elseprintf("\nThese three points do not fall on one straight line.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(k) Given the coordinates (x, y) of a center of a circle and it’s radius, write a program which will determine whether a point lies inside the circle, on the circle or outside the circle.(Hint: Use sqrt( ) and pow( ) functions)

Solution:

#include<stdio.h>#include<conio.h>#include<math.h>main() {

int x,y,x_,y_,r,point;clrscr();

printf("Please enter the coordinates of center: \n");printf("(x,y): ");scanf("%d%d",&x,&y);printf("\nPlease enter the radius of circle: \n");scanf("%d",&r);printf("\nPlease enter the point to check: \n");printf("(x`,y`): ");scanf("%d%d",&x_,&y_);

point=pow(x_,2)+pow(y_,2)+pow(x,2)+pow(y,2)-(2*x_*x)-(2*y_*y)-pow(r,2);

if(point<0)printf("\nThe point lies inside the circle.\n");

if(point>0)printf("\nThe point lies outside the circle.\n");

if(point==0)printf("\nThe point lies on the circle.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(l) Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis or at the origin, viz. (0, 0).

Solution:

#include<stdio.h>#include<conio.h>main() {

int x,y;clrscr();

Page 691: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

printf("Please enter points\n");printf("(x,y): \n");scanf("%d%d",&x,&y);

if(x==0&&y!=0) {printf("\nThe point lies on Y AXIS.\n");}

else if(x!=0&&y==0) {printf("\nThe point lies on X AXIS.\n");}

else if(x==0&&y==0) {printf("\nThe point lies at the origin.\n");}

else {printf("\nThe point doesn't lie on any axis or at origin.\n");}

getch();return 0;

}

___________________________________________________________________

Exercise [F]

(a) Any year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators && and ||.

Solution:

#include<stdio.h>#include<conio.h>main() {

int yr;clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

if(yr%4==0 || !((yr%4)>0) )printf("\nThe is a LEAP YEAR.\n");

elseprintf("\nThis is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol.The following table shows the range of ASCII values for various characters.

The following table shows the range of ASCII values for various

Page 692: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

characters.Characters

Characters ASCII values

A – Z 65 - 90a – z 97 - 1220 – 9 48 - 57special symbols 0 - 47, 58 - 64, 91 - 96, 123 - 127

Solution:

#include<stdio.h>#include<conio.h>main() {

char ch;clrscr();

printf("Please enter any character:");scanf("%c",&ch);

if(ch>=65&&ch<=90)printf("\nThe character you entered is a CAPITAL LETTER.\n");

if(ch>=97&&ch<=122)printf("\nThe character you entered is a SMALL LETTER.\n");

if(ch>=48&&ch<=57)printf("\nThe character you entered is a DIGIT.\n");

if(ch>=0&&ch<=47 || ch>=58&&ch<=64 || ch>=91&&ch<=96 || ch>=123&&ch<=127)printf("\nThe character you entered is a SPECIAL SYMBOL.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(c) An Insurance company follows following rules to calculate premium.(1) If a person’s health is excellent and the person is between 25 and 35 years of age and lives in a city and is a male then the premium is Rs. 4 per thousand and his policy amount cannot exceed Rs. 2 lakhs.(2) If a person satisfies all the above conditions except that the sex is female then the premium is Rs. 3 per thousand and her policy amount cannot exceed Rs. 1 lakh.(3) If a person’s health is poor and the person is between 25 and 35 years of age and lives in a village and is a male then the premium is Rs. 6 per thousand and his policy cannot exceed Rs. 10,000.(4) In all other cases the person is not insured.

Write a program to output whether the person should be insured or not, his/her premium rate and maximum amount for which he/she can be insured.

Solution:

Page 693: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

#include<stdio.h>#include<conio.h>main() {

int age,premium,p_a,hlt,rsdnc,sex;long amount;clrscr();

printf("Please tell the HEALTH of the person\n(1 for excellent or 2 for poor) :\n");scanf("%d",&hlt);

printf("Please tell the AGE of the person: \n");scanf("%d",&age);

printf("Please tell the residence\n(1 for city or 2 for village) : \n");scanf("%d",&rsdnc);

printf("Please tell you sex\n(1 for male or 2 for female) : \n");scanf("%d",&sex);

if(hlt==1 && age>=25&&age<=35 && rsdnc==1 && sex==1) {premium=4;amount=200000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==1||hlt==2 && age>=25&&age<=35 && rsdnc==1||rsdnc==2 && sex==2) {premium=3;amount=100000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==2 && age>=25&&age<=35 && rsdnc==2 && sex==1) {premium=6;amount=10000;

printf("\nThis person is insured.\n");printf("Premium rate is = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else {printf("\nThis person cannot be insured.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) A certain grade of steel is graded according to the following conditions:(i) Hardness must be greater than 50(ii) Carbon content must be less than 0.7(iii) Tensile strength must be greater than 5600

The grades are as follows:

Grade is 10 if all three conditions are metGrade is 9 if conditions (i) and (ii) are met

Page 694: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

Grade is 8 if conditions (ii) and (iii) are metGrade is 7 if conditions (i) and (iii) are metGrade is 6 if only one condition is metGrade is 5 if none of the conditions are met

Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and output the grade of the steel.

Solution:

#include<stdio.h>#include<conio.h>main() {

int hdn,tnsl,hardness=50,tensile_strength=5600;

float c,carbon_content=0.7;

clrscr();

printf("Please enter the Hardness: \n");scanf("%d",&hdn);

printf("\nPlease enter the Carbon content: \n");scanf("%f",&c);

printf("\nPlease enter the Tensile Strength: \n");scanf("%d",&tnsl);

if(hdn>hardness && c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 10.\n");

else if(hdn>hardness && c<carbon_content)printf("\nThe steel has been Graded 9.\n");

else if(c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 8.\n");

else if(hdn>hardness && tnsl>tensile_strength)printf("\nThe steel has been Graded 7.\n");

else if(hdn>hardness || c<carbon_content || tnsl>tensile_strength)printf("\nThe steel has been Graded 6.\n");

elseprintf("\nThe steel has been Graded 5.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A library charges a fine for every book returned late. For first 5 days the fine is 50 paise, for 6-10 days fine is one rupee and above 10 days fine is 5 rupees. If you return the book after 30 days your membership will be cancelled. Write a program to accept the number of days the member is late to return the book and display the fine or the appropriate message.

Solution:

Page 695: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

#include<stdio.h>#include<conio.h>main() {int days;clrscr();

printf("Please enter the days of being late in returning the book:\n");scanf("%d",&days);

if(days<=5)printf("\nYou have been fined for 50 paise.\n");

if(days>=6&&days<=10)printf("\nYou have been fined for 1 rupee.\n");

if(days>10&&days<30)printf("\nYou have been fined for 5 rupee.\n");

if(days>=30)printf("\nYour membership has been cancelled.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.

Solution:

#include<stdio.h>#include<conio.h>main() {

int s1,s2,s3,ls,ss1,ss2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d%d%d",&s1,&s2,&s3);

if(s1>s2&&s1>s3){ls=s1;ss1=s2;ss2=s3;}if(s2>s1&&s2>s3) {ls=s2;ss1=s1;ss2=s3;}if(s3>s1&&s3>s2) {ls=s3;ss1=s1;ss2=s2;}

if((ss1+ss2)>ls) {printf("\nThe Triangle is VALID.\n");}else {printf("The triangle is NOT VALID.\n");}

Page 696: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(g) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.

Solution:

#include<stdio.h>#include<conio.h>

main() {

int s1,s2,s3,largest,s_1,s_2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d %d %d",&s1,&s2,&s3);

if(s1==s2&&s1!=s3||s1==s3&&s1!=s2 || s2==s3&&s2!=s1||s2==s1&&s2!=s3 ||s3==s1&&s3!=s2||s3==s2&&s3!=s1){printf("The Triangle is ISOSCELES.\n");}

if(s1==s2&&s2==s3 || s2==s1&&s2==s3 || s3==s1&&s3==s2){printf("The Triangle is EQUILATERAL.\n");}

if(s1!=s2&&s2!=s3 || s2!=s1&&s1!=s3 || s3!=s1&&s1!=s2){printf("The Triangle is SCALENE.\n");}

if(s1>s2&&s1>s3){largest=s1;s_1=s2;s2=s3;}

if(s2>s1&&s2>s3){largest=s2;s_1=s1;s_2=s3;}

if(s3>s1&&s3>s2){largest=s3;s_1=s1;s_2=s2;}

if(pow(largest,2)==pow(s_1,2)+pow(s_2,2))printf("The Triangle is RIGHT ANGLED.\n");

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(h) In a company, worker efficiency is determined on the basis of the time required for a worker to complete a particular job. If the time taken by the worker is between 2 – 3 hours, then the worker is said to be highly efficient. If the time required by the worker is between 3 – 4

Page 697: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

hours, then the worker is ordered to improve speed. If the time taken is between 4 – 5 hours, the worker is given training to improve his speed, and if the time taken by the worker is more than 5 hours, then the worker has to leave the company. If the time taken by the worker is input through the keyboard, find the efficiency of the worker.

Solution:

#include<stdio.h>#include<conio.h>main() {

int hrs;clrscr();

printf("Please enter the hours of completing job: ");scanf("%d",&hrs);

if(hrs>=2 && hrs<=3)printf("\nThe worker is HIGHLY EFFICIENT.\n");

if(hrs>=3 && hrs<=4)printf("\nThe worker is ordered to IMPROVE SPEED.\n");

if(hrs>=4 && hrs<= 5)printf("\nThe worker should be given TRAINING TO IMPROVE SPEED.\n");

if(hrs>5)printf("\nThe worker should be asked to leave the company.\n");

elseprintf("The worker is HIGHLY EFFICIENT.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(i) A university has the following rules for a student to qualify for a degree with A as the main subject and B as the subsidiary subject: (a) He should get 55 percent or more in A and 45 percent or more in B. (b) If he gets than 55 percent in A he should get 55 percent or more in B. However, he should get at least 45 percent in A. (c) If he gets less than 45 percent in B and 65 percent or more in A he is allowed to reappear in an examination in B to qualify. (d) In all other cases he is declared to have failed.

Write a program to receive marks in A and B and Output whether the student has passed, failed or is allowed to reappear in B.

Solution:

#include<stdio.h>#include<conio.h>main() {

int a,b;clrscr();

printf("Please enter the marks in subject A: \n");scanf("%d",&a);

Page 698: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

printf("\nPlease enter the marks in subject B: \n");scanf("%d",&b);

if(a>=55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a==55 && b>=55 || a==55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a>=65 && b<45) {printf("Student is allowed to reappear in the exam of B to qualify.\n"); }

else {printf("Student has failed.\n"); }

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) The policy followed by a company to process customer orders is given by the following rules:

(a) If a customer order is less than or equal to that in stock and has credit is OK, supply has requirement.(b) If has credit is not OK do not supply. Send him intimation.(c) If has credit is Ok but the item in stock is less than has order, supply what is in stock. Intimate to him data the balance will be shipped.

Write a C program to implement the company policy.

Solution:

#include<stdio.h>#include<conio.h>main() {

int stock,credit,order;clrscr();

printf("Please enter the stock available: ");scanf("%d",&stock);printf("\nPlease enter the order: ");scanf("%d",&order);printf("\nPlease enter the credit: ");scanf("%d",&credit);

if(credit!=0&&order<=stock) {printf("\nSupply\n");}

else if(credit!=0&&order>stock) {printf("\nAvailable items will be supplied.\n");}

else {printf("\nNo supply.\n");}

Page 699: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

getch();return 0;

}______________________________________________________________________ Exercise [J]

(a) Using conditional operators determine: (1) Whether the character entered through the keyboard is a lower case alphabet or not.(2) Whether a character entered through the keyboard is a special symbol or not.

Solution:

#include<stdio.h>#include<conio.h>

char main() {

char ch;clrscr();

printf("Please enter a character: \n");scanf("%c",&ch);

if(ch>=97 && ch<=122) {printf("\n[A] This character is a SMALL CASE alphabet.\n");}

else {printf("\n[A] This character is NOT A SMALL CASE alphabet.\n");}

if(ch>=0&&ch<=47||ch>=58&&ch<=64||ch>=91&&ch<=96||ch>=123&&ch<=127){printf("\n[B] This character is a SPECIAL SYMBOL.\n");}

else{printf("\n[B] This character is NOT A SPECIAL SYMBOL.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Write a program using conditional operators to determine whether a year entered through the keyboard is a leap year or not.

Solution:

#include<stdio.h>#include<conio.h>main () {

int yr;clrscr();

Page 700: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

Posted by Chetan Raikwar at 06:42 No comments: Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest

Recommend this on Google

Newer Posts Home Subscribe to: Posts (Atom)

Google+ Followers

Chetan Raikwar

Add to circles

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4!=0)printf("\nThis is NOT A LEAP YEAR.\n");

elseprintf("\nThis is a LEAP YEAR.\n");

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(c) Write a program to find the greatest of the three numbers entered through the keyboard using conditional operators.

Solution:

#include<stdio.h>#include<conio.h>

main() {

int n1,n2,n3;clrscr();

printf("\nPlease enter 3 numbers: \n");scanf("%d %d %d",&n1,&n2,&n3);

if(n1>n2 && n1>n3) {printf("\n%d is the greatest number of the three numbers.\n",n1);}

else if(n2>n1 && n2>n3) {printf("\n%d is the greatest number of the three numbers.\n",n2);}

else if(n3>n2 && n3>n1) {printf("\n%d is the greatest number of the three numbers.\n",n3);}

else {printf("\nwrong input!\n");}

getch();return 0;

}

_______________________________________________________________________

Page 701: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=5&by-date=false[07-Apr-14 9:10:30 PM]

2 have me in circles View all

About Me

Chetan Raikwar Follow

2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

Blog Archive

▼ 2014 (16)▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...Let Us C / Chapter 12 (File Input Output)Let Us C / Chapter 1 (Getting started)Let Us C / Chapter 3 (The Loop Control Structure)Let Us C / Chapter 4 (The Case Control Structure)Let Us C / Chapter 5 (Functions & Pointers)Let Us C / Chapter 6 (Data Types Revisited)Let Us C / Chapter 7 (The C Pre-processor)Let Us C / Chapter 8 (Arrays)Let Us C / Chapter 9 (Puppeting on Strings)Let Us C / Chapter 10 (Structures)Let Us C / Chapter 11 (Console Input Output)Let Us C / Chapter 13 (More Issues in Input Output...Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Simple template. Powered by Blogger.

Page 702: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 2 (The Decision Control Structure)

(a) If cost price and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss he incurred.

#include<stdio.h>#include<conio.h>main() {

int cp,sp,rslt;clrscr();

printf("Please enter the cost price of the item: \n");scanf("%d",&cp);

printf("Please enter the selling price of the item: \n");scanf("%d",&sp);

if(cp>sp) {rslt=cp-sp;printf("\nSeller has incurred LOSS of %d rupees.\n",rslt);}

if(cp<sp){rslt=sp-cp;printf("\nSeller has made PROFIT of %d rupees.\n",rslt);}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Any integer is input through the keyboard. Write a program to find out whether it is an odd number or even number.

#include<stdio.h>

Exercise [C]

Solution:

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 703: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

#include<conio.h>

main() {

int i;clrscr();

printf("Please enter the number: \n");scanf("%d",&i);

if(i%2==0)printf("\nThe number is EVEN.\n");

elseprintf("\nThe number is ODD.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(c) Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not.(Hint: Use the % (modulus) operator)

#include<stdio.h>#include<conio.h>

main() {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4==0)printf("\nThe year is a LEAP YEAR.\n");

elseprintf("\nThe Year is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input through the keyboard write a program to find out what is the day on 1st January of this year.

#include<stdio.h>#include<conio.h>

main() {

int month=1,year,a,day=1;

clrscr();

printf("Enter year: ");

Solution:

Solution:

Page 704: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

scanf("%d",&year);

/* 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 */

printf("\n\nFirst day is ");

if(day==0)printf("Sunday");

else if(day==1)printf("Monday");

else if(day==2)printf("Tuesday");

else if(day==3)printf("Wednesday");

else if(day==4)printf("Thursday");

else if(day==5)printf("Friday");

else if(day==6)printf("Saturday");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.

#include<stdio.h>#include<conio.h>

main() {

long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();

printf("Please enter a five digit number: \n");scanf("%ld",&i);

d1=i/10000;a=i%10000;

d2=a/1000;b=a%1000;

d3=b/100;

Solution:

Page 705: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

c=b%100;

d4=c/10;d=c%10;

d5=d/1;

n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);

printf("\nThe REVERSED NUMBER is %ld \n",n_num);

if(n_num==i){printf("\nboth numbers are SAME.\n");}else {printf("\nboth number are NOT SAME.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the ages of Ram, Shyam and Ajay are input through the keyboard, write a program to determine the youngest of the three.

#include<stdio.h>#include<conio.h>

main() {

int ram,shyam,ajay;clrscr();

printf("Please enter the age of RAM: ");scanf("%d",&ram);

printf("\nPlease enter the age of SHYAM: ");scanf("%d",&shyam);

printf("\nPlease enter the age or AJAY: ");scanf("%d",&ajay);

if(ram<shyam){if(ram<ajay) {printf("\nRam is the YOUNGEST.\n");} } if(shyam<ram){if(shyam<ajay) {printf("\nShyam is the YOUNGEST.\n");} }

if(ajay<ram) {if(ajay<shyam) {printf("\nAjay is the YOUNGEST.\n");} }

getch();

Solution:

Page 706: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

return 0;

}

------------------------------------------------------------------------------------------------------------

(g)Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.

#include<stdio.h>#include<conio.h>main() {

int a1,a2,a3;clrscr();

printf("Please enter the first angle: \n");scanf("%d",&a1);

printf("\nPlease enter the second angle: \n");scanf("%d",&a2);

printf("\nPlease enter the third angle: \n");scanf("%d",&a3);

if(a1+a2+a3==180) {printf("\nThe triangle is VALID.\n");}

else {printf("\nThe triangle is NOT VALID.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(h) Find the absolute value of a number entered through the keyboard.

#include<stdio.h>#include<conio.h>#include<stdlib.h>main() {

int i,av;clrscr();

printf("Please enter any number: ");scanf("%d",&i);

av=abs(i);

/* abs(); is a standard function to calculate absolute value.\this function has been defined in <stdlib.h> library. */

printf("Absolute value = %d",av);

getch();

Solution:

Solution:

Page 707: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

return 0;

}

------------------------------------------------------------------------------------------------------------

(i) Given the length and breadth of a rectangle, write a program to find whether the area of the rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and breadth = 4 is greater than its perimeter.

#include<stdio.h>#include<conio.h>main() {

int l,b,area,peri;clrscr();

printf("Please enter the length and bredth of a rectangle: \n");scanf("%d%d",&l,&b);

area=l*b;peri=2*(l+b);

if(area>peri) {printf("\nThe Area of Rectangle is GREATER then it's perimeter.\n");}

else {printf("\nThe area of Rectangle is NOT GREATER then it's perimeter.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

#include<stdio.h>#include<conio.h>main() {

int x1,y1,x2,y2,x3,y3,curve1,curve2;clrscr();

printf("Please enter the values of Three points: ");printf("\n(x1,y1):\n");scanf("%d%d",&x1,&y1);printf("\n(x2,y2):\n");scanf("%d%d",&x2,&y2);printf("\n(x3,y3):\n");scanf("%d%d",&x3,&y3);

curve1=(x2-x1)/(y2-y1);curve2=(x3-x2)/(y3-y2);

if(curve1==curve2)printf("\nAll three points fall on one straight line.\n");else

Solution:

Solution:

Page 708: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

printf("\nThese three points do not fall on one straight line.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(k) Given the coordinates (x, y) of a center of a circle and it’s radius, write a program which will determine whether a point lies inside the circle, on the circle or outside the circle.(Hint: Use sqrt( ) and pow( ) functions)

#include<stdio.h>#include<conio.h>#include<math.h>main() {

int x,y,x_,y_,r,point;clrscr();

printf("Please enter the coordinates of center: \n");printf("(x,y): ");scanf("%d%d",&x,&y);printf("\nPlease enter the radius of circle: \n");scanf("%d",&r);printf("\nPlease enter the point to check: \n");printf("(x`,y`): ");scanf("%d%d",&x_,&y_);

point=pow(x_,2)+pow(y_,2)+pow(x,2)+pow(y,2)-(2*x_*x)-(2*y_*y)-pow(r,2);

if(point<0)printf("\nThe point lies inside the circle.\n");

if(point>0)printf("\nThe point lies outside the circle.\n");

if(point==0)printf("\nThe point lies on the circle.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(l) Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis or at the origin, viz. (0, 0).

#include<stdio.h>#include<conio.h>main() {

int x,y;clrscr();

printf("Please enter points\n");printf("(x,y): \n");scanf("%d%d",&x,&y);

Solution:

Solution:

Page 709: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

if(x==0&&y!=0) {printf("\nThe point lies on Y AXIS.\n");}

else if(x!=0&&y==0) {printf("\nThe point lies on X AXIS.\n");}

else if(x==0&&y==0) {printf("\nThe point lies at the origin.\n");}

else {printf("\nThe point doesn't lie on any axis or at origin.\n");}

getch();return 0;

}

___________________________________________________________________

(a) Any year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators && and ||.

#include<stdio.h>#include<conio.h>main() {

int yr;clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

if(yr%4==0 || !((yr%4)>0) )printf("\nThe is a LEAP YEAR.\n");

elseprintf("\nThis is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol.The following table shows the range of ASCII values for various characters.

The following table shows the range of ASCII values for various characters.

Exercise [F]

Solution:

Page 710: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

Characters

Characters ASCII values

A – Z 65 - 90a – z 97 - 1220 – 9 48 - 57special symbols 0 - 47, 58 - 64, 91 - 96, 123 - 127

#include<stdio.h>#include<conio.h>main() {

char ch;clrscr();

printf("Please enter any character:");scanf("%c",&ch);

if(ch>=65&&ch<=90)printf("\nThe character you entered is a CAPITAL LETTER.\n");

if(ch>=97&&ch<=122)printf("\nThe character you entered is a SMALL LETTER.\n");

if(ch>=48&&ch<=57)printf("\nThe character you entered is a DIGIT.\n");

if(ch>=0&&ch<=47 || ch>=58&&ch<=64 || ch>=91&&ch<=96 || ch>=123&&ch<=127)printf("\nThe character you entered is a SPECIAL SYMBOL.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(c) An Insurance company follows following rules to calculate premium.(1) If a person’s health is excellent and the person is between 25 and 35 years of age and lives in a city and is a male then the premium is Rs. 4 per thousand and his policy amount cannot exceed Rs. 2 lakhs.(2) If a person satisfies all the above conditions except that the sex is female then the premium is Rs. 3 per thousand and her policy amount cannot exceed Rs. 1 lakh.(3) If a person’s health is poor and the person is between 25 and 35 years of age and lives in a village and is a male then the premium is Rs. 6 per thousand and his policy cannot exceed Rs. 10,000.(4) In all other cases the person is not insured.

Write a program to output whether the person should be insured or not, his/her premium rate and maximum amount for which he/she can be insured.

Solution:

Solution:

Page 711: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

#include<stdio.h>#include<conio.h>main() {

int age,premium,p_a,hlt,rsdnc,sex;long amount;clrscr();

printf("Please tell the HEALTH of the person\n(1 for excellent or 2 for poor) :\n");scanf("%d",&hlt);

printf("Please tell the AGE of the person: \n");scanf("%d",&age);

printf("Please tell the residence\n(1 for city or 2 for village) : \n");scanf("%d",&rsdnc);

printf("Please tell you sex\n(1 for male or 2 for female) : \n");scanf("%d",&sex);

if(hlt==1 && age>=25&&age<=35 && rsdnc==1 && sex==1) {premium=4;amount=200000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==1||hlt==2 && age>=25&&age<=35 && rsdnc==1||rsdnc==2 && sex==2) {premium=3;amount=100000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==2 && age>=25&&age<=35 && rsdnc==2 && sex==1) {premium=6;amount=10000;

printf("\nThis person is insured.\n");printf("Premium rate is = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else {printf("\nThis person cannot be insured.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) A certain grade of steel is graded according to the following conditions:(i) Hardness must be greater than 50(ii) Carbon content must be less than 0.7(iii) Tensile strength must be greater than 5600

The grades are as follows:

Page 712: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

Grade is 10 if all three conditions are metGrade is 9 if conditions (i) and (ii) are metGrade is 8 if conditions (ii) and (iii) are metGrade is 7 if conditions (i) and (iii) are metGrade is 6 if only one condition is metGrade is 5 if none of the conditions are met

Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and output the grade of the steel.

#include<stdio.h>#include<conio.h>main() {

int hdn,tnsl,hardness=50,tensile_strength=5600;

float c,carbon_content=0.7;

clrscr();

printf("Please enter the Hardness: \n");scanf("%d",&hdn);

printf("\nPlease enter the Carbon content: \n");scanf("%f",&c);

printf("\nPlease enter the Tensile Strength: \n");scanf("%d",&tnsl);

if(hdn>hardness && c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 10.\n");

else if(hdn>hardness && c<carbon_content)printf("\nThe steel has been Graded 9.\n");

else if(c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 8.\n");

else if(hdn>hardness && tnsl>tensile_strength)printf("\nThe steel has been Graded 7.\n");

else if(hdn>hardness || c<carbon_content || tnsl>tensile_strength)printf("\nThe steel has been Graded 6.\n");

elseprintf("\nThe steel has been Graded 5.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A library charges a fine for every book returned late. For first 5 days the fine is 50 paise, for 6-10 days fine is one rupee and above 10 days fine is 5 rupees. If you return the book after 30 days your membership will be cancelled. Write a program to accept the number of days the

Solution:

Page 713: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

member is late to return the book and display the fine or the appropriate message.

#include<stdio.h>#include<conio.h>main() {int days;clrscr();

printf("Please enter the days of being late in returning the book:\n");scanf("%d",&days);

if(days<=5)printf("\nYou have been fined for 50 paise.\n");

if(days>=6&&days<=10)printf("\nYou have been fined for 1 rupee.\n");

if(days>10&&days<30)printf("\nYou have been fined for 5 rupee.\n");

if(days>=30)printf("\nYour membership has been cancelled.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.

#include<stdio.h>#include<conio.h>main() {

int s1,s2,s3,ls,ss1,ss2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d%d%d",&s1,&s2,&s3);

if(s1>s2&&s1>s3){ls=s1;ss1=s2;ss2=s3;}if(s2>s1&&s2>s3) {ls=s2;ss1=s1;ss2=s3;}if(s3>s1&&s3>s2) {ls=s3;ss1=s1;ss2=s2;}

Solution:

Solution:

Page 714: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

if((ss1+ss2)>ls) {printf("\nThe Triangle is VALID.\n");}else {printf("The triangle is NOT VALID.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(g) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.

#include<stdio.h>#include<conio.h>

main() {

int s1,s2,s3,largest,s_1,s_2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d %d %d",&s1,&s2,&s3);

if(s1==s2&&s1!=s3||s1==s3&&s1!=s2 || s2==s3&&s2!=s1||s2==s1&&s2!=s3 ||s3==s1&&s3!=s2||s3==s2&&s3!=s1){printf("The Triangle is ISOSCELES.\n");}

if(s1==s2&&s2==s3 || s2==s1&&s2==s3 || s3==s1&&s3==s2){printf("The Triangle is EQUILATERAL.\n");}

if(s1!=s2&&s2!=s3 || s2!=s1&&s1!=s3 || s3!=s1&&s1!=s2){printf("The Triangle is SCALENE.\n");}

if(s1>s2&&s1>s3){largest=s1;s_1=s2;s2=s3;}

if(s2>s1&&s2>s3){largest=s2;s_1=s1;s_2=s3;}

if(s3>s1&&s3>s2){largest=s3;s_1=s1;s_2=s2;}

if(pow(largest,2)==pow(s_1,2)+pow(s_2,2))printf("The Triangle is RIGHT ANGLED.\n");

getch();return 0;}

Solution:

Page 715: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

------------------------------------------------------------------------------------------------------------

(h) In a company, worker efficiency is determined on the basis of the time required for a worker to complete a particular job. If the time taken by the worker is between 2 – 3 hours, then the worker is said to be highly efficient. If the time required by the worker is between 3 – 4 hours, then the worker is ordered to improve speed. If the time taken is between 4 – 5 hours, the worker is given training to improve his speed, and if the time taken by the worker is more than 5 hours, then the worker has to leave the company. If the time taken by the worker is input through the keyboard, find the efficiency of the worker.

#include<stdio.h>#include<conio.h>main() {

int hrs;clrscr();

printf("Please enter the hours of completing job: ");scanf("%d",&hrs);

if(hrs>=2 && hrs<=3)printf("\nThe worker is HIGHLY EFFICIENT.\n");

if(hrs>=3 && hrs<=4)printf("\nThe worker is ordered to IMPROVE SPEED.\n");

if(hrs>=4 && hrs<= 5)printf("\nThe worker should be given TRAINING TO IMPROVE SPEED.\n");

if(hrs>5)printf("\nThe worker should be asked to leave the company.\n");

elseprintf("The worker is HIGHLY EFFICIENT.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(i) A university has the following rules for a student to qualify for a degree with A as the main subject and B as the subsidiary subject: (a) He should get 55 percent or more in A and 45 percent or more in B. (b) If he gets than 55 percent in A he should get 55 percent or more in B. However, he should get at least 45 percent in A. (c) If he gets less than 45 percent in B and 65 percent or more in A he is allowed to reappear in an examination in B to qualify. (d) In all other cases he is declared to have failed.

Write a program to receive marks in A and B and Output whether the student has passed, failed or is allowed to reappear in B.

#include<stdio.h>

Solution:

Solution:

Page 716: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

#include<conio.h>main() {

int a,b;clrscr();

printf("Please enter the marks in subject A: \n");scanf("%d",&a);

printf("\nPlease enter the marks in subject B: \n");scanf("%d",&b);

if(a>=55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a==55 && b>=55 || a==55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a>=65 && b<45) {printf("Student is allowed to reappear in the exam of B to qualify.\n"); }

else {printf("Student has failed.\n"); }

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) The policy followed by a company to process customer orders is given by the following rules:

(a) If a customer order is less than or equal to that in stock and has credit is OK, supply has requirement.(b) If has credit is not OK do not supply. Send him intimation.(c) If has credit is Ok but the item in stock is less than has order, supply what is in stock. Intimate to him data the balance will be shipped.

Write a C program to implement the company policy.

#include<stdio.h>#include<conio.h>main() {

int stock,credit,order;clrscr();

printf("Please enter the stock available: ");scanf("%d",&stock);printf("\nPlease enter the order: ");scanf("%d",&order);printf("\nPlease enter the credit: ");scanf("%d",&credit);

if(credit!=0&&order<=stock) {

Solution:

Page 717: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

printf("\nSupply\n");}

else if(credit!=0&&order>stock) {printf("\nAvailable items will be supplied.\n");}

else {printf("\nNo supply.\n");}

getch();return 0;

}______________________________________________________________________

(a) Using conditional operators determine: (1) Whether the character entered through the keyboard is a lower case alphabet or not.(2) Whether a character entered through the keyboard is a special symbol or not.

#include<stdio.h>#include<conio.h>

char main() {

char ch;clrscr();

printf("Please enter a character: \n");scanf("%c",&ch);

if(ch>=97 && ch<=122) {printf("\n[A] This character is a SMALL CASE alphabet.\n");}

else {printf("\n[A] This character is NOT A SMALL CASE alphabet.\n");}

if(ch>=0&&ch<=47||ch>=58&&ch<=64||ch>=91&&ch<=96||ch>=123&&ch<=127){printf("\n[B] This character is a SPECIAL SYMBOL.\n");}

else{printf("\n[B] This character is NOT A SPECIAL SYMBOL.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

Exercise [J]

Solution:

Page 718: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-min=2014-01-01T00:00:00-08:00&updated-max=2014-01-30T06:51:00-08:00&max-results=16&start=11&by-date=false[07-Apr-14 9:11:34 PM]

(b) Write a program using conditional operators to determine whether a year entered through the keyboard is a leap year or not.

#include<stdio.h>#include<conio.h>main () {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4!=0)printf("\nThis is NOT A LEAP YEAR.\n");

elseprintf("\nThis is a LEAP YEAR.\n");

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(c) Write a program to find the greatest of the three numbers entered through the keyboard using conditional operators.

#include<stdio.h>#include<conio.h>

main() {

int n1,n2,n3;clrscr();

printf("\nPlease enter 3 numbers: \n");scanf("%d %d %d",&n1,&n2,&n3);

if(n1>n2 && n1>n3) {printf("\n%d is the greatest number of the three numbers.\n",n1);}

else if(n2>n1 && n2>n3) {printf("\n%d is the greatest number of the three numbers.\n",n2);}

else if(n3>n2 && n3>n1) {printf("\n%d is the greatest number of the three numbers.\n",n3);}

else {printf("\nwrong input!\n");}

getch();return 0;

}

_______________________________________________________________________

Solution:

Solution:

Page 720: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 1 (Getting started)

(a) Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.

Solution:

(b) The distance between two cities (in km.) is input through the keyboard. Write a program to convert and print this distance in meters, feet, inches and centimeters.

#include<stdio.h>#include<conio.h>main() {long km,m,ft,inc,cm;clrscr();printf("Please enter the distance(in km):\n");scanf("%ld",&km);m=km*1000;ft=m*3;inc=ft*12;cm=ft*30;printf("\nDistance in kilometer = %ld\n",km);printf("\nDistance in meter = %ld\n",m);printf("\nDistance in feet = %ld\n",ft);printf("\nDistance in inches = %ld\n",inc);printf("\nDistance in centimeters = %ld\n",cm);getch();

Exercise [H]

#include<stdio.h>#include<conio.h>main() {long bs,da,hra,gs;clrscr();printf("Please enter Ramesh's Basic Salary: \n");scanf("%ld",&bs);gs=(40*bs/100)+(20*bs/100)+bs;printf("Ramesh's GROSS SALARY = %ld\n",gs);getch();return 0;} ------------------------------------------------------------------------------------------------------------

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 721: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

return 0;}

------------------------------------------------------------------------------------------------------------

(c) If the marks obtained by a student in five different subjects are input through the keyboard, find out the aggregate marks and percentage marks obtained by the student. Assume that the maximum marks that can be obtained by a student in each subject is 100.

------------------------------------------------------------------------------------------------------------

(d) Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this temperature into Centigrade degrees.

#include<stdio.h>#include<conio.h>main() {float fh,cn;clrscr();printf("Please enter the temperature in fahrenheit:\n");scanf("%f",&fh);cn=5*(fh-32)/9;printf("Centigrade Temperature = %f \n",cn);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(e) The length & breadth of a rectangle and radius of a circle are input through the keyboard. Write a program to calculate the area & perimeter of the rectangle, and the area & circumference of the circle.

Solution:

#include<stdio.h>#include<conio.h>main() {int m1,m2,m3,m4,m5,ttl;float prcnt;clrscr();printf("Please enter the marks of the student:\n");scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);ttl=m1+m2+m3+m4+m5;prcnt=ttl/5;printf("AGGREGATE MARKS = %d\nPERCENTAGE MARKS = %f%\n",ttl,prcnt);getch();return 0;}

Solution:

Solution:

#include<stdio.h>#include<conio.h>main() {float l,b,area,peri,ca,cr,r;clrscr();printf("Please enter the length of rectangle:");scanf("%f",&l);printf("\nPlease enter the breadth of rectangle:");scanf("%f",&b);area=l*b;peri=2*(l+b);

Page 722: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

(f) Two numbers are input through the keyboard into two locations C and D. Write a program to interchange the contents of C and D.

#include<stdio.h>#include<conio.h>main() {int c,d,t;clrscr();printf("Enter value of C: ");scanf("%d",&c);printf("\n\nEnter value of D: ");scanf("%d",&d);t=c;c=d;d=t;printf("\n\nC = %d\nD = %d\n",c,d);getch();}

------------------------------------------------------------------------------------------------------------

(g) If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits.(Hint: Use the modulus operator ‘%’)

#include<stdio.h>#include<conio.h>main() {long i,d1,d2,d3,d4,d5,a,b,c,d,sum;clrscr();printf("Please enter the five digit number: \n");scanf("%ld",&i);d1=i/10000;a=i%10000;d2=a/1000;b=a%1000;d3=b/100;c=b%100;d4=c/10;d=c%10;d5=d/1;sum=d1+d2+d3+d4+d5;printf("Sum of the digits is %ld\n",sum);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(h) If a five-digit number is input through the keyboard, write a program to reverse the number.

printf("\n\nAREA = %f square cm.\t PERIMETER = %f cm.\n",area,peri);printf("\n\nPlease enter the radius of the circle:");scanf("%f",&r);ca=3.14*r*r;cr=2*3.14*r;printf("\n\nAREA = %f square cm.\t CIRCUMFERENCE = %f cm.\n",ca,cr);getch();return 0;}

------------------------------------------------------------------------------------------------------------

Solution:

Solution:

Page 723: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

------------------------------------------------------------------------------------------------------------

(i) If a four-digit number is input through the keyboard, write a program to obtain the sum of the first and last digit of this number.

------------------------------------------------------------------------------------------------------------

(j) In a town, the percentage of men is 52. The percentage of total literacy is 48. If total percentage of literate men is 35 of the total population, write a program to find the total number of illiterate men and women if the population of the town is 80,000.

#include<stdio.h>#include<conio.h>main() {int i,d1,d4,a,b,c,sum;clrscr();printf("Please enter the four digit number: \n");scanf("%d",&i);d1=i/1000;

Solution:

#include<stdio.h>#include<conio.h>main() {long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();printf("Please enter the five digit number: \n");scanf("%ld",&i);d1=i/10000;a=i%10000;d2=a/1000;b=a%1000;d3=b/100;c=b%100;d4=c/10;d=c%10;d5=d/1;n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);printf("reversed number = %ld \n",n_num);getch();return 0;}

Solution:

#include<stdio.h>#include<conio.h>main() {int i,d1,d4,a,b,c,sum;clrscr();printf("Please enter the four digit number: \n");scanf("%d",&i);d1=i/1000;a=i%1000;b=a%100;c=b%10;d4=c/1;sum=d1+d4;

printf("The sum of first and last digit is %d\n",sum);getch();return 0;}

Solution:

Page 724: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

a=i%1000;b=a%100;c=b%10;d4=c/1;sum=d1+d4;printf("The sum of first and last digit is %d\n",sum);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(k) A cashier has currency notes of denominations 10, 50 and 100. If the amount to be withdrawn is input through the keyboard in hundreds, find the total number of currency notes of each denomination the cashier will have to give to the withdrawer.

#include<stdio.h>#include<conio.h>main() {int a,t_10,f_50,h_100,b,c;clrscr();printf("Please enter the amount to be withdrawn: \n");scanf("%d",&a);h_100=a/100;b=a%100;f_50=b/50;c=b%50;t_10=c/10;

printf("\nCurrency notes of 100 should be = %d\n",h_100);printf("\nCurrency notes of 50 should be = %d\n",f_50);printf("\nCurrency notes of 10 should be = %d\n",t_10);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(l) If the total selling price of 15 items and the total profit earned on them is input through the keyboard, write a program to find the cost price of one item.

#include<stdio.h>#include<conio.h>main() {int sp,p,cp;clrscr();

printf("Please enter the selling price of 15 items: \n");scanf("%d",&sp);printf("\nPlease enter the total profit of 15 items: \n");scanf("%d",&p);cp=(sp-p)/15;printf("Cost price of one item is %d\n",cp);getch();return 0;}

------------------------------------------------------------------------------------------------------------

(m) If a five-digit number is input through the keyboard, write a program

Solution:

Solution:

Page 725: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

Posted by Chetan Raikwar at 07:01 No comments:

to print a new number by adding one to each of its digits. For example if the number that is input is 12391 then the output should be displayed as 23502.

#include<stdio.h>#include<conio.h>main() {long i,add;clrscr();printf("Please enter a five digit number: \n");scanf("%ld",&i);add=i+11111;printf("addition = %ld\n",add);getch();return 0;}

______________________________________________________________________

Solution:

Recommend this on Google

Let Us C / Chapter 12 (File Input Output)

(a) Write a program to read a file and display contents with its line numbers.

NOTE: Make a file as "DATA.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h>#include<conio.h>void main() {

FILE *fp;char i;int line=1;

clrscr();

fp=fopen("DATA.TXT","r");

if(fp==NULL) {

printf("\n\nCannot open file!");

delay(1000);exit();}

printf("%2d. ",line); /* we already print 1st for the first line */

while(i!=EOF) {

i=fgetc(fp);

printf("%c",i);

Exercise [C]

Solution:

Page 726: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

/* if the character is newline,the line number will be\printed after it */

if(i=='\n') {line++;printf("%2d. ",line);}

}

fclose(fp);getch();}

---------------------------------------------------------------------------------------------------------------

(b) Write a program to find the size of a text file without traversing it character by character.

NOTE: Make a file as "DATA.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h>#include<conio.h>#include<string.h>

void main() {

FILE *fp;char s[80],ch;int len=0;

clrscr();

fp=fopen("data.txt","r");

while(fgets(s,79,fp)!=NULL)

len=len+strlen(s); /* length of each string */ /* spaces and newlines are also counted */

fclose(fp);

printf("length of file = %d",len);

getch();}

----------------------------------------------------------------------------------------------------------------

(c) Write a program to add the contents of one file at the end of another.

NOTE: Make two file as "FILE1.TXT" and "FILE2.TXT" in bin directory and then run the program. The contents of FILE1.TXT will be appended to FILE2.TXT.

Solution:

Solution:

Page 727: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

#include<stdio.h>#include<conio.h>void main() {

FILE *f1,*f2;char ch;

clrscr();

f1=fopen("FILE1.TXT","r"); /* file to append */f2=fopen("FILE2.TXT","a+"); /* file to be appended */

if(f1==NULL || f2==NULL) {printf("\ncannot open one of files!");

exit();}

while(1) {

ch=fgetc(f1);

if(ch==EOF) {break;}

fputc(ch,f2);

}

fclose(f1);fclose(f2);

printf("\ntask completed successfully!");

getch();

}

---------------------------------------------------------------------------------------------------------------

(d) 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.

#include<stdio.h>#include<conio.h>#define N 100struct student { char name[30]; int age; };

void main() {

struct student std;struct student s[N]; /* size of array of structure defined globally for convenience */

FILE *fp;int flag=0,ch,i=0,count=0;long recsize;char another='y';void srt_print(); /* funtion to sort and print */

Solution:

Page 728: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

clrscr();

recsize=sizeof(std);

fp=fopen("STUDENT.DAT","rb+");if(fp==NULL) {fp=fopen("STUDENT.DAT","wb+");if(fp==NULL)exit();}

while(1) {

clrscr();

printf("\t\t\tStudent database\n");printf("\t\t\t****************\n\n\n");printf("\t\t\n1: Add student data\n");printf("\t\t\n2: List student data\n");printf("\t\t\n0: Exit");

gotoxy(2,24);printf("Your choice: ");scanf("%d",&ch);

switch(ch) {

case 1:

clrscr();

while(another=='y' || another=='Y') {

clrscr();

printf("\t\tAdd student data\n");printf("\t\t****************\n\n");printf("\nEnter student name: ");scanf("%s",&std.name);printf("\n\naEnter student age: ");scanf("%d",&std.age);

fseek(fp,0,SEEK_END);fwrite(&std,recsize,1,fp);

gotoxy(2,24);printf("Add another information(Y/N): ");fflush(stdin);another=getche();

}break;

case 2:

clrscr();

printf("\t\tList student data\n");printf("\t\t*****************\n\n");rewind(fp);while(fread(&std,recsize,1,fp)==1) {s[i]=std;flag=1;i++;count++;}

srt_print(&s,count); /* function to print names */

if(flag==0) {

Page 729: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

printf("\n\n\nNo data found!\n");

}printf("\n\n\npress any key to return...");getch();

break;

case 0:

fclose(fp);exit();

default:

printf("wrong input!\n");exit();

}

}

}/******** main ends ************/

/**** sorting and printing function ****/void srt_print(struct student *ss, int n) {

struct student temp;int i,j;

for(i=0;i<=n;i++) {

for(j=i+1;j<n;j++) {

/* checking first alphabets of both names */

if(ss[i].name[0] > ss[j].name[0]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;}

/* if first alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1] > ss[j].name[1]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;

}

/* if first 2 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2] > ss[j].name[2]) {

temp=ss[i];ss[i]=ss[j];ss[j]=temp;

Page 730: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

}}

/* if first 3 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2]==ss[i].name[2]) {

if(ss[i].name[3] > ss[j].name[3]) {

temp=ss[i];ss[i]=ss[j];ss[j]=ss[i];}}}

/* if first four 4 alphabets are same */

else if(ss[i].name[0]==ss[j].name[0] && ss[i].name[1]==ss[j].name[1]) {

if(ss[i].name[2]==ss[j].name[2] && ss[i].name[2]==ss[j].name[2]) {

if(ss[i].name[3]==ss[j].name[3]) {

if(ss[i].name[4] > ss[j].name[4]) {

temp=ss[i];ss[i]=ss[j];ss[j]=ss[i];

} } } }

}}

/* printing sorted list */

for(i=0;i<n;i++) {

printf("\n%10s\t\t%2d\n",ss[i].name,ss[i].age);

}

}

--------------------------------------------------------------------------------------------------------------

(e) Write a program to copy one file to another. While doing so replace all lowercase characters to their equivalent uppercase characters.

NOTE: Make a file as "FILE.TXT" in bin directory and write/paste some text in it. then run the program and you will receive another file as "RESULT.TXT" with uppercase letters.

#include<stdio.h>#include<conio.h>

Solution:

Page 731: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

void main() {

FILE *fr,*fw;char a[1000];char ch,upr;clrscr();

fr=fopen("SOURCE.TXT","r");

if(fr==NULL) {printf("cannot open source file!\n");

}

fw=fopen("RESULT.TXT","w");

if(fw==NULL) {printf("cannot open target file!\n");

}

while(1) {

ch=fgetc(fr);

if(ch==EOF)break;

else {

if(ch>=97 && ch<=122) {

ch=ch-32;

}

fputc(ch,fw);}

}fclose(fr);fclose(fw);

printf("Task completed!");getch();}

----------------------------------------------------------------------------------------------------------------

(f) 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.

----------------------------------------------------------------------------------------------------------------

(g) 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 cornerco-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

Solution:

Page 732: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

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.

#include<stdio.h>#include<conio.h>#include<string.h>#include<types.h>#include<stat.h>#include<fcntl.h>

void box();void print();

void main() {

int inhandle,bytes,pg=1;FILE *fp;char source[80],buffer[1400];

clrscr();

printf("Enter file name: ");gets(source);

inhandle=open(source, O_RDONLY);

if(inhandle==-1) {

printf("cannot open file!");exit();

}

clrscr();

while(1) {

bytes=read(inhandle,buffer,1387);

if(bytes>0) {

gotoxy(32,1); /* showing filename */printf("%s",strupr(source));

gotoxy(70,1);printf("Pg: %3d",pg); /* showing page number */

box(); /* passing the heading and page number to the function */

print(buffer); /* passing the buffer to the function */

}

else {

gotoxy(70,1);printf("Pg: %3d",pg);break;}

++pg;}

close(inhandle);

Solution:

Page 733: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

getch();}

/********************************//* function to print the buffer *//********************************/

void print(char s[1400]) {

int x=4,y=3,i=0;

while(s[i]!=EOF) {

gotoxy(x,y);printf("%c",s[i]);

if(x>74) {

x=4;y+=1;

}

if(y>21) {

gotoxy(2,24);printf("press any key to go to next page...");

x=4;y=3;

getch();

clrscr();box();}

x++;i++;

}

}

/****************************//* function to draw the box *//****************************/

void box() {

int i,j;

for(i=2;i<=77;i++) {

gotoxy(i,2);printf("%c",196);

gotoxy(i,23);printf("%c",196);

}

for(j=3;j<=22;j++) {

gotoxy(2,j);

Page 734: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

printf("%c",179);

gotoxy(77,j);printf("%c",179);

}

gotoxy(77,23);printf("%c",217);

gotoxy(77,2);printf("%c",191);

gotoxy(2,23);printf("%c",192);

gotoxy(2,2);printf("%c",218);

}

----------------------------------------------------------------------------------------------------------------

(h) Write a program to encrypt/decrypt a file using:(1) 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.(2) A substitution cipher: In this each character read from the source file is substituted by a corresponding predetermined character and this character is written to the target file.For example, if character ‘A’ is read from the source file, and if we have decided that every ‘A’ is to be substituted by ‘!’, then a ‘!’ would be written to the target file in place of every ‘A’ Similarly, every ‘B’ would be substituted by ‘5’ and so on.

Offset cipher Encryption:

#include<stdio.h>#include<conio.h>

void main() { /* offset cipher encryption */

/* every character has been added to 128 and the new value has beenwritten */

FILE *fp,*ft;char ch;

clrscr();

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");exit();}

while(1) {

ch=fgetc(fp);

Solution:

Page 735: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

if(ch==EOF)break;

ch=ch+128; /* offset cipher encryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();}

Offset cipher Decryption:

#include<stdio.h>#include<conio.h>void main() { /* offset cipher decryption */

FILE *fp,*ft;char ch;

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");

exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

ch=ch-128; /* decryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();

}

Substitution cipher encryption:

Page 736: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

#include<stdio.h>#include<conio.h>

void main() { /* substitution cipher encryption */

/* all vowels have been exchanged with first five ascii characters and every space has been converted to 6th ascii character */

FILE *fp,*ft;char ch;

clrscr();

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

encrypt(&ch); /* function for encryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();}encrypt(char *c) {

if(*c=='a') {*c='!';}

if(*c=='e') {*c='@';}

if(*c=='i') {*c='#';}

if(*c=='o') {*c='$';}

if(*c=='u') {*c='%';}

if(*c==' ') {*c='^';}

Page 737: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

return *c;}

Substitution cipher Decryption:

#include<stdio.h>#include<conio.h>void main() {

/* substitution cipher's decryption */

FILE *fp,*ft;char ch;

fp=fopen("data.txt","r");ft=fopen("temp.txt","w");

if(fp==NULL) {printf("cannot open one of files!");

exit();}

while(1) {

ch=fgetc(fp);

if(ch==EOF)break;

decrypt(&ch); /* function for decryption */

fputc(ch,ft);

}

fclose(fp);fclose(ft);

remove("data.txt");rename("temp.txt","data.txt");

printf("task completed!");getch();

}

decrypt(char *c) {

if(*c=='!')*c='a';

if(*c=='@')*c='e';

if(*c=='#')*c='i';

if(*c=='$')*c='o';

if(*c=='%')*c='u';

if(*c=='^')*c=' ';

Page 738: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

return *c;

}----------------------------------------------------------------------------------------------------------------

(i) 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.

NOTE: If on withdrawal, the balance subtracts to less than 100. The withdrawal will not be performed.

#include<stdio.h>#include<conio.h>void main() {

struct customer { int accno; char name[30]; float balance; }cust;struct trans { int accno; char trans_type; float amount; }tra;FILE *fp,*ft,*ftemp;int flag=0;long recsize,retsize;char another,ch;clrscr();

fp=fopen("CUSTOMER.DAT","rb+");

if(fp==NULL) {

fp=fopen("CUSTOMER.DAT","wb+");

if(fp==NULL)

Solution:

Page 739: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

printf("cannot open customer data file!\n");

exit();

}

ft=fopen("TRANSACTIONS.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTIONS.DAT","wb+");

if(ft==NULL)

printf("cannot open transactions file!\n");

exit();

}

recsize=sizeof(cust);retsize=sizeof(tra);

while(1) {

clrscr();

printf("\t\tCutomer Transactions:\n");printf("\t\t*********************\n\n\n");printf("\t1: Add customer information:\n\n");printf("\t2: Add transaction information:\n\n");printf("\t3: List customer information:\n\n");printf("\t4: List transaction information:\n\n");printf("\t5: Perform transaction:\n\n");printf("\t0: Exit:\n\n\n");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd customer information:\n");printf("\t\t*************************\n\n");printf("\nEnter account number: ");scanf("%d",&cust.accno);printf("\n\nEnter name: ");scanf("%s",cust.name);printf("\n\nEnter balance: ");fflush(stdin);scanf("%f",&cust.balance);

fwrite(&cust,recsize,1,fp);

gotoxy(2,24);printf("Add another customer information(Y/N): ");another=getche();

Page 740: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

clrscr();

}break;

case '2':

clrscr();

fseek(ft,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd transaction information:\n");printf("\t\t****************************\n\n\n");printf("Enter existing customer account number: ");scanf("%d",&tra.accno);printf("\n\nEnter transaction type(D/W): ");fflush(stdin);scanf("%c",&tra.trans_type);printf("\n\nEnter amount for transaction: ");fflush(stdin);scanf("%f",&tra.amount);

fwrite(&tra,retsize,1,ft);

gotoxy(2,24);printf("Enter another information(Y/N): ");another=getche();

clrscr();}break;

case '3':

clrscr();

printf("\t\tList customer information:\n");printf("\t\t**************************\n\n");

rewind(fp);while(fread(&cust,recsize,1,fp)==1) {printf("\n%5d\t%-8s\t%5.2f\n",cust.accno,cust.name,cust.balance);flag=1;}

if(flag==0) {gotoxy(2,12);printf("No customer information found!\n");}printf("\n\npress any key to go back...");getch();

break;

case '4':

clrscr();

printf("\t\tList transaction information:\n");printf("\t\t*****************************\n\n");

rewind(ft);while(fread(&tra,retsize,1,ft)==1) {printf("\n%5d\t%c\t%6.2f\n",tra.accno,tra.trans_type,tra.amount);flag=1;}

Page 741: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

if(flag==0) {gotoxy(2,12);printf("No transaction information found!\n");}

printf("\n\npress any key to go back...");getch();

break;

case '5':

clrscr();

printf("\t\tPerform transactions\n");printf("\t\t********************\n\n");

rewind(fp);

while(fread(&cust,recsize,1,fp)==1) {

rewind(ft);

while(fread(&tra,retsize,1,ft)==1) {

if(cust.accno==tra.accno) {

flag=1;

if(tra.trans_type=='D' || tra.trans_type=='d') {

cust.balance+=tra.amount;

fseek(fp,-recsize,SEEK_CUR);fwrite(&cust,recsize,1,fp);

}

else if(tra.trans_type=='W' || tra.trans_type=='w') {

if((cust.balance-tra.amount)>=100) {

cust.balance-=tra.amount;

fseek(fp,-recsize,SEEK_CUR);fwrite(&cust,recsize,1,fp);

}

}

}}}

fclose(ft);

ftemp=fopen("TEMP.DAT","rb+");

if(ftemp==NULL) {

ftemp=fopen("TEMP.DAT","wb+");

}

remove("TRANSACTIONS.DAT");rename("TEMP.DAT","TRANSACTIONS.DAT");

ft=fopen("TRANSACTIONS.DAT","rb+");

Page 742: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

if(ft==NULL) {

ft=fopen("TRANSACTIONS.DAT","wb+");

}

if(flag==0) {

gotoxy(2,12);printf("No active transactions\n");

}

else if(flag>0) {

gotoxy(2,12);printf("Transactions performed seccussfully!\n");gotoxy(2,14);printf("NOTE: withdrawl for low balance accounts has not been performed\n");

}gotoxy(2,24);printf("press any key to return...");getch();

break;

case '0':

fclose(fp);fclose(ft);exit();

}}

}

---------------------------------------------------------------------------------------------------------------

(j) 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.

----------------------------------------------------------------------------------------------------------------

(k) A hospital keeps a file of blood donors in which each record has the format:Name: 20 Columns

Solution:

Page 743: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

Address: 40 ColumnAge: 2 ColumnsBlood Type: 1 Column (Type 1, 2, 3 or 4)Write a program to read the file and print a list of all blood donors whose age is below 25 and blood is type 2.

/* This program will make a file of blood donors and save information in it */

/* Writing program */

#include<stdio.h>#include<conio.h>void main() {

FILE *fp;char another='y';

struct blood { char name[50]; char adr[50]; int age; int bld; } b;

clrscr();

fp=fopen("BLOODBANK.DAT","wb");

if(fp==NULL) {printf("cannot open target file!\n");exit();}

while(another=='Y' || another=='y') {

clrscr();printf("\t\tInformation of Blood donor\n");printf("\t\t**************************\n\n\n");printf("Enter the name: ");scanf("%s",b.name);printf("\n\nenter the address: ");scanf("%s",b.adr);printf("\n\nenter the age: ");scanf("%d",&b.age);printf("\n\nenter the blood group(1/2/3/4): ");scanf("%d",&b.bld);

fprintf(fp,"%s\t%s\t%d\t%d",b.name,b.adr,b.age,b.bld);

printf("\n\n\nenter more information(Y/N): ");fflush(stdin);

another=getch();

}

fclose(fp);

}

Solution:Program to creat record file of blood donors

Program to read record file for specifications

Page 744: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

/* This program will read the information from the file made by writing program */

/* Reading Program */

#include<stdio.h>#include<conio.h>void main() {

FILE *fp;char ch;

struct blood { char name[50]; char adr[50]; int age; int bld; }b;clrscr();

fp=fopen("BLOODBANK.DAT","rb");

if(fp==NULL) {printf("cannot open source file!\n\n");exit();}

while(fscanf(fp,"%s\t%s\t%d\t%d",&b.name,&b.adr,&b.age,&b.bld)!=EOF)if(b.age<25 && b.bld==2) {printf("\n%s\t %s\t%2d\t %d",b.name,b.adr,b.age,b.bld);}fclose(fp);

getch();}

----------------------------------------------------------------------------------------------------------------

(l) Given a list of names of students in a class, write a program to store the names in a file on disk. Make a provision to display the nth name in the list (n is data to be read) and to display all names starting with S.

#include<stdio.h>#include<conio.h>void main() {

struct name { int sn; char name[30]; }s;int i,num,flag=0;long recsize;char another,ch;FILE *fp;clrscr();

fp=fopen("NAMES.DAT","rb+");

if(fp==NULL) {

fp=fopen("NAMES.DAT","wb+");

if(fp==NULL)

printf("cannot open file! \n");exit();}

Solution:

Page 745: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

recsize=sizeof(s);

while(1) {

clrscr();printf("\t\tStudent Names:\n");printf("\t\t**************\n\n\n");printf("\t1: Add names of students:\n\n");printf("\t2: Search a student name:\n\n");printf("\t3: List all student names:\n\n");printf("\t4: List all names starting with 'S':\n\n");printf("\t0: Exit\n\n");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd names of students:\n");printf("\t\t**********************\n\n");printf("Enter student number: ");scanf("%d",&s.sn);printf("\n\nEnter student name: ");scanf("%s",s.name);

fwrite(&s,recsize,1,fp);

gotoxy(2,24);printf("Enter another name(Y/N): ");fflush(stdin);another=getche();

clrscr();}break;

case '2':

clrscr();

printf("\t\tSearch a student name:\n");printf("\t\t**********************\n\n");printf("Enter student number: ");scanf("%d",&num);

rewind(fp);

while(fread(&s,recsize,1,fp)==1) {

if(s.sn==num) {

printf("\n\nStudent Number: %5d\n\n",s.sn);printf("Student name: %s\n\n",s.name);

flag=1;

Page 746: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

break;} }

if(flag==0) {printf("\n\n\nNo such name found!\n");}gotoxy(2,24);printf("press any key to return...\n");getch();

break;

case '3':

clrscr();

printf("\t\tList all student names\n");printf("\t\t**********************\n\n\n");

rewind(fp);

while(fread(&s,recsize,1,fp)==1) {printf("\n%5d\t%-10s\n",s.sn,s.name);flag=1;}

if(flag==0) {printf("\n\n\nNo name found!\n");}

printf("\n\n\npress any key to return...\n");getch();break;

case '4':

clrscr();

printf("\t\tAll name starting with 'S':\n");printf("\t\t***************************\n\n\n");

rewind(fp);while(fread(&s,recsize,1,fp)==1) {

if(strncmp('s',s.name[0])==0) { /* comparing only first character of \ name if it is "s" */printf("\n%5d\t%-10s\n",s.sn,s.name);flag=1;}}

if(flag==0) {printf("\n\n\nNo name starting with \'S\' found!\n");}

printf("\n\n\npress any key to return...\n");getch();break;

case '0':

fclose(fp);exit();

} }

}

Page 747: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

----------------------------------------------------------------------------------------------------------------

(m) Assume that a Master file contains two fields, Roll no. and name of the student. At the end of the year, a set of students join the class and another set leaves. A Transaction file contains the roll numbers and an appropriate code to add or delete a student.Write a program to create another file that contains the updated list of names and roll numbers. Assume that the Master file and the Transaction file are arranged in ascending order by roll numbers. The updated file should also be in ascending order by roll numbers.

Note:- This program ( all the 3 ) are ideally for single. After you have ran it once, check the results and delete the updated list file before running it again. Assign roll number in ascending orders by roll numbers. And process data according to ascending nature.

1- first program will let you save data in masterfile.2- second program will let you add or delete data and will generate an updated list in text mode.3- obtain the updated list and check it ( assuming you have processed data as instructed).

1. program to creat master file.

#include<stdio.h>#include<conio.h>#include<string.h>

void main() {

FILE *fp;struct student { int rl; char name[50]; }s;char ch,another;clrscr();

fp=fopen("MASTERFILE.DAT","rb+");

if(fp==NULL) {

fp=fopen("MASTERFILE.DAT","wb+");

if(fp==NULL)puts("cannot open master file!");exit();}

while(1) {

clrscr();

gotoxy(30,2);printf("Masterfile\n");gotoxy(30,3);printf("**********\n\n\n");gotoxy(20,6);printf("1: Enter student data: ");gotoxy(20,8);printf("2: Read student data: ");gotoxy(20,10);printf("0: Exit: ");

Solution:

Page 748: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

clrscr();

gotoxy(2,24);printf("NOTE: assign roll numbers in ascending order");gotoxy(20,5);printf("Enter roll number: ");scanf("%d",&s.rl);

gotoxy(20,7);printf("Enter name: ");fflush(stdin);gets(s.name);

fwrite(&s,sizeof(s),1,fp);

gotoxy(20,10);printf("Add more data(Y/N): ");fflush(stdin);

another=getche();

}

break;

case '2':

clrscr();

gotoxy(30,2);printf("Student data");gotoxy(30,3);printf("************\n\n");

rewind(fp);

while(fread(&s,sizeof(s),1,fp)==1) {

printf("\n%d\t%s\n",s.rl,s.name);

}

printf("\n\npress any key to return...");getch();

break;

case '0':

fclose(fp);exit();

Page 749: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

}}

}

2. program to creat transaction file and generate updated list

#include<stdio.h>#include<conio.h>#include<string.h>#define N 100

void main() {

FILE *ft,*fu,*fm,*ftemp;

struct student { int rl; char name[50]; }s,ss[N],temp;

struct transaction { char stats; int rl; char name[50]; }t;

int flag=0;char ch,another;clrscr();

fm=fopen("MASTERFILE.DAT","rb+");

if(fm==NULL) {

printf("Masterfile doesn't exist!");

}

ft=fopen("TRANSACTION.DAT","rb+");

if(ft==NULL) {

ft=fopen("TRANSACTION.DAT","wb+");

if(ft==NULL)puts("cannot open transactions file!");exit();}

fu=fopen("UPDATELIST.TXT","w+");

if(fu==NULL) {

puts("cannot open target file!");exit();}

while(1) {

clrscr();

gotoxy(30,2);printf("Transaction-File\n");

Page 750: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

gotoxy(30,3);printf("****************\n\n\n");gotoxy(20,6);printf("1: ADD/DELETE student data from master list: ");gotoxy(20,8);printf("2: Read transaction data: ");gotoxy(20,10);printf("3: Creat updated list: ");gotoxy(20,12);printf("0: Exit:");

gotoxy(2,24);printf("Your choice: ");fflush(stdin);

ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(ft,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

clrscr();

gotoxy(2,23);printf("NOTE: data to be deleted should match master list");gotoxy(2,24);printf("NOTE: data to be added should follow the ascending nature of master list");gotoxy(20,5);printf("ADD/DELETE student(A/D): ");scanf("%c",&t.stats);gotoxy(20,7);printf("Enter roll number: ");scanf("%d",&t.rl);gotoxy(20,9);printf("Enter name: ");fflush(stdin);gets(t.name);

fwrite(&t,sizeof(t),1,ft);

gotoxy(20,12);printf("Add more data(Y/N): ");fflush(stdin);

another=getche();

}

break;

case '2':

clrscr();

gotoxy(30,2);printf("Student data");gotoxy(30,3);printf("************\n\n");

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

Page 751: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

printf("\n");

if(t.stats=='a' || t.stats=='A') {printf("ADD");}

else {printf("DELETE");}printf("\t%d\t%s\n",t.rl,t.name);

}

printf("\n\npress any key to return...");getch();

break;

case '3':

clrscr();

gotoxy(30,2);printf("make updated list");gotoxy(30,3);printf("*****************\n\n");

rewind(fm);

while(fread(&s,sizeof(s),1,fm)==1) {

flag=0;

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

if(t.rl==s.rl ) {

if(t.stats=='d' || t.stats=='D') {flag=1;}

}

}

if(flag==0)

fprintf(fu,"\n%d\t%-s\n",s.rl,s.name);

}

rewind(ft);

while(fread(&t,sizeof(t),1,ft)==1) {

if(t.stats=='a' || t.stats=='A') {

fprintf(fu,"\n%d\t%-s\n",t.rl,t.name);

}

}

ftemp=fopen("TEMP.DAT","wb+");

fclose(ftemp);

Page 752: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

fclose(ft);

remove("TRANSACTION.DAT");rename("TEMP.DAT","TRANSACTION.DAT");

ft=fopen("TRANSACTION.DAT","rb+");

gotoxy(2,24);printf("press any key to continue...");getch();

break;case '0':

fclose(fm);fclose(ft);fclose(fu);exit();

}}

}

-----------------------------------------------------------------------------------------------------------------

(n) In a small firm employee numbers are given in serial numerical order, that is 1, 2, 3, etc.− Create a file of employee data with following information: employee number, name, sex, gross salary.− If more employees join, append their data to the file.− If an employee with serial number 25 (say) leaves, delete the record by making gross salary 0.− If some employee’s gross salary increases, retrieve the record and update the salary.Write a program to implement the above operations.

#include<stdio.h>#include<conio.h>void main() {

struct emp { int empno; char name[30]; char sex; float gs; } e;FILE *fp,*ft;int long recsize;int empn,flag=0;float new_sal;char another,ch;clrscr();

recsize=sizeof(e);

fp=fopen("EMP.DAT","rb+");

if(fp==NULL) {

fp=fopen("EMP.DAT","wb+");if(fp==NULL)

Solution:

Page 753: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

exit();

}

while(1) {

clrscr();

printf("\t\tEmployee database management\n");printf("\t\t****************************\n");printf("\n\n\t1: Add another employee: ");printf("\n\n\t2: Add salary information of employee: ");printf("\n\n\t3: List all records: ");printf("\n\n\t4: Delete employee with 0 salary: ");printf("\n\n\t0: Exit:");

gotoxy(2,24);printf("your choice: ");fflush(stdin);ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END); /* seeking cursor to reach at the end of file */

another='Y';

while(another=='Y' || another=='y') {

printf("\n\tEnter new employee information\n");printf("\t******************************\n\n\n");

printf("\nEnter employee number: ");scanf("%d",&e.empno);

printf("\n\nEnter employee name: ");scanf("%s",e.name);

printf("\n\nEnter sex(M/F/O): ");scanf(" %c",&e.sex);

printf("\n\nEnter gross salary: ");scanf("%f",&e.gs);

/* writing new information at the end of file */

fwrite(&e,recsize,1,fp);

printf("\n\n\n\nAdd another employee(Y/N): ");fflush(stdin);another=getche();

clrscr();

}

break;

case '2':

clrscr();

another='Y';

while(another=='Y' || another=='y') {

printf("\n\tEnter salary information\n");

Page 754: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

printf("\t************************\n\n");

gotoxy(2,23); /* showing message at the bottom of the screen */

printf("NOTE: to delete an employee, mark his/her salary 0\n");printf(" then use option 4 from main menu.");

gotoxy(3,5); /* returning cursor back from the bottom */printf("Enter employee number: ");scanf("%d",&empn); /* asking for employee number to search */

rewind(fp);

while(fread(&e,recsize,1,fp)==1) {

if(e.empno-empn==0) { /* if employee number matches with structure */

flag=1; /* condition indicator for printing further messages */

printf("\n\nEnter new salary for employee: ");

scanf("%f",&e.gs);

e.empno=e.empno; /* rest information should be same except only\ salary */e.sex=e.sex;

e.name[30]=e.name[30];

fseek(fp,-recsize,SEEK_CUR); /* seeking the correct location of data within\ structure in the file */fwrite(&e,recsize,1,fp); /* writing data at correct position */

break;

}}

if(flag==0) /* conditional indicator used above */printf("\n\n\n\tinformation does not exist!\n");

printf("\n\nenter another information(Y/N): ");another=getche();

clrscr();

}

break;

case '4':

clrscr();

printf("\n\n\tDelete employee\n");printf("\t***************\n\n");

ft=fopen("TEMP.DAT","w"); /* opening new temporary file */

rewind(fp); /* taking cursor back to the very beginning of file */

while(fread(&e,recsize,1,fp)==1) { /* matching each salary */

if(e.gs!=0.0 || e.gs!=0) { /* if salary is not 0 then data will be written to new file */

flag=1;

Page 755: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

fwrite(&e,recsize,1,ft);

}}fclose(fp);fclose(ft);

remove("EMP.DAT"); /* removing original file with 0 salary and renaming\ temporary without 0 salary as the original file */

rename("TEMP.DAT","EMP.DAT");

fp=fopen("EMP.DAT","rt+"); /* opening the new file, it opens because it has not been opened before */ /* a file cannot be opened twice during execution as you know */

if(flag>0) {printf("\n\n\nall records with 0 gross salary have been deleted. \n");}

gotoxy(2,24);printf("\n\n\npress any key to return...");getch();

break;

case '0':

fclose(fp);exit();

case '3':

clrscr();

printf("\t\tList all employees\n");printf("\t\t******************\n\n\n");

rewind(fp);

while(fread(&e,recsize,1,fp)==1) {

flag=1;

printf("%2d\t%6s\t%c\t%.2f\n\n",e.empno,e.name,e.sex,e.gs);

}

if(flag==0)

printf("\n\n\tNo records exist!\n\n");

printf("\n\npress any key to return... ");

getch(); /* this is very important place, if we don't stop screen here \ after reading and printing the list,we won't be able to see it and it will disappear and will return to main menu because of "break" statement. */break;

} }

}linkfloat() { /* function to avoid possible errors because of floats */float a=0,*b;b=&a;a=*b;

Page 756: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

return 0;}

-----------------------------------------------------------------------------------------------------------------

(o) Given a text file, write a program to create another text file deleting the words “a”, “the”, “an” and replacing each one of them with a blank space.

NOTE: Make a file "FILE.TXT" in bin directory and write/paste something in it, then run the program, you will get another file as "NEW.TXT" as result of the program.

#include<stdio.h> #include<conio.h> #include<string.h>

void replace();

void main() {

FILE *fp,*ft; char str[80],target[80]; clrscr();

fp=fopen("FILE.TXT","r");

if(fp==NULL) {

puts("cannot open source file!"); exit(); }

ft=fopen("NEW.TXT","w");

if(ft==NULL) {

puts("cannot open target file!"); exit(); }

while(fgets(str,79,fp)!=NULL) {

replace(str,&target);

fputs(target,ft);

}

fclose(fp); fclose(ft);

printf("\nTask completed!"); getch();

}

void replace(char *s, char *s1) {

int i=0,j=0,k=0; char temp[100],temp2[100],main[100],*t=temp,*m=main;

Solution:

Page 757: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

/* 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,"the")==0) {

strcpy(temp2," "); }

else if(strcmpi(temp2,"an")==0) {

strcpy(temp2," ");

}

else if(strcmpi(temp2,"a")==0) {

strcpy(temp2," ");

}

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,"the")==0){ /* checking last word too */

Page 758: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

strcpy(temp2," "); }

else if(strcmpi(temp2,"an")==0) {

strcpy(temp2," "); }

else if(strcmpi(temp2,"a")==0) {

strcpy(temp2," "); }

/***************************/ /* 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 */

}

while(*m!='\0') {

*s1=*m;

s1++; m++;

}

*s1='\0';

}

-----------------------------------------------------------------------------------------------------------------

(p) You are given a data file EMPLOYEE.DAT with the following record structure:struct employee {int empno ;char name[30] ;int basic, grade ;} ;Every employee has a unique empno and there are supposed to be no gaps between employee numbers. Records are entered into the data file in ascending order of employee number, empno. It is intended to check whether there are missing employee numbers. Write a program segment to read the data file records sequentially and display the list of missing employee numbers.

NOTE: assign employee numbers in ascending order only.Solution:

Page 759: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

#include<stdio.h> #include<conio.h> void main() {

struct employee { int empno; char name[30]; int basic,grade; }e; FILE *fp; int num=0; long recsize; char another,ch; clrscr();

fp=fopen("EMPLOYEE.DAT","rb+"); if(fp==NULL) { fp=fopen("EMPLOYEE.DAT","wb+");

if(fp==NULL) exit(); }

recsize=sizeof(e);

while(1) {

clrscr();

printf("\t\tEmployee number database:\n"); printf("\t\t*************************\n\n"); printf("\n\t1: Add employee information:\n"); printf("\n\t2: List employee information:\n"); printf("\n\t3: Check missing employee numbers:\n"); printf("\n\t0: Exit:\n\n");

gotoxy(2,24); printf("your choice: "); fflush(stdin); ch=getche();

switch(ch) {

case '1':

clrscr();

fseek(fp,0,SEEK_END);

another='y';

while(another=='y' || another=='Y') {

printf("\t\tAdd employee information:\n"); printf("\t\t*************************\n\n");

printf("Note: employee numbers should be given in ascending order\n\n");

printf("\nEnter employee number: "); scanf("%d",&e.empno); printf("\n\nEnter employee name: "); scanf("%s",e.name); printf("\n\nEnter employee basic salary: "); scanf("%d",&e.basic); printf("\n\nEnter employee grade(1/2/3): ");

Page 760: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

scanf("%d",&e.grade);

fwrite(&e,recsize,1,fp);

gotoxy(2,24); printf("Add another employee information(Y/N): "); fflush(stdin); another=getche();

clrscr();

}

break;

case '2':

clrscr();

printf("\t\tList employee information:\n"); printf("\t\t**************************\n\n\n");

rewind(fp); while(fread(&e,recsize,1,fp)==1) {

printf("\n%3d\t%8s\t%5d\t%d\n",e.empno,e.name,e.basic,e.grade);

}

printf("\n\npress any key to return...\n"); getch();

break;

case '3':

clrscr();

printf("\t\tMissing employee numbers:\n"); printf("\t\t*************************\n\n");

rewind(fp); while(fread(&e,recsize,1,fp)==1) { num=e.empno; /* assigning the value of first employee number */ break; }

rewind(fp); /* again rewinding the file to read from beginning */

while(fread(&e,recsize,1,fp)==1) {

if(num!=e.empno) { /* if assigned number is smaller than employee number we will print all the number between them */ while(num<e.empno) {

printf("%4d ",num);

num++; } num=e.empno+1;

}

/* we will assign greater value than employee number to make sure that both don't match until another greater employee number is found */

else

num=e.empno+1;

Page 761: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

}

printf("\n\n press any key to return..."); getch();

break;

case '0':

fclose(fp); exit();

} } }

-----------------------------------------------------------------------------------------------------------------

(q) Write a program to carry out the following:− To read a text file “TRIAL.TXT” consisting of a maximum of 50 lines of text, each line with a maximum of 80 characters.− Count and display the number of words contained in the file.− Display the total number of four letter words in the text file.Assume that the end of a word may be a space, comma or a full-stop followed by one or more spaces or a newline character.

NOTE: Make a file "TRIAL.TXT" in bin directory and write something in it ,then run the program.

#include<stdio.h> #include<conio.h> void main() {

FILE *fp; char s[80]; int twd,fwd,tw=0,fw=0;void word(); clrscr();

fp=fopen("TRIAL.TXT","r"); if(fp==NULL) {

exit(); }

while(fgets(s,79,fp)!=NULL) { word(s,&twd,&fwd); tw=tw+twd; fw=fw+fwd; }

fclose(fp);

printf("\nTotal number of words in text file = %d\n",tw); printf("\n\nTotal number of 4 letter words = %d\n",fw);

getch(); }

void word(char ss[80],int *tw, int *fw) {

Solution:

Page 762: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

int i=0,tot_wd=0,tot_4_wd=0;

while(ss[i]!='\0') {

/************************/ /* to cound total words */ /************************/

if(ss[i]>=65 && ss[i]<=90 || ss[i]>=97 && ss[i]<=122) {

if(ss[i+1]==' ' || ss[i+1]=='.' || ss[i+1]==',' || ss[i+1]=='\n' ) {

tot_wd++; } }

/*********************************/ /* to count total 4 letter words */ /*********************************/

if(ss[i]==' ' || ss[i]==',' || ss[i]=='.') {

if(ss[i+1]>=65 && ss[i+1]<=90 || ss[i+1]>=97 && ss[i+1]<=122) {

if(ss[i+2]>=65 && ss[i+2]<=90 || ss[i+2]>=97 && ss[i+2]<=122) {

if(ss[i+3]>=65 && ss[i+3]<=90 || ss[i+3]>=97 && ss[i+3]<=122) {

if(ss[i+4]>=65 && ss[i+4]<=90 || ss[i+4]>=97 && ss[i+4]<=122) {

if(ss[i+5]==' ' || ss[i+5]==',' || ss[i+5]=='.' || ss[i+5]=='\n') {

tot_4_wd++; } } } } } }

if(ss[i]>=65 && ss[i]<=90 || ss[i]>=97 && ss[i]<=122) {

if(ss[i+1]>=65 && ss[i+1]<=90 || ss[i+1]>=97 && ss[i+1]<=122) {

if(ss[i+2]>=65 && ss[i+2]<=90 || ss[i+2]>=97 && ss[i+2]<=122) {

if(ss[i+3]>=65 && ss[i+3]<=90 || ss[i+3]>=97 && ss[i+3]<=122) {

if(ss[i+4]==' ' || ss[i+4]==',' || ss[i+4]=='.' || ss[i+4]=='\n') {

} } } } }

i++;

}

*tw=tot_wd; *fw=tot_4_wd;

}

-----------------------------------------------------------------------------------------------------------------

Page 763: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

(r) Write a program to read a list of words, sort the words in alphabetical order and display them one word per line. Also give the total number of words in the list. Output format should be:Total Number of words in the list is _______Alphabetical listing of words is:-----------Assume the end of the list is indicated by ZZZZZZ and there are maximum in 25 words in the Text file.

NOTE: Make a file as "trial.txt" in bin directory and write some words in it. Words should be in the form of a list. One below another,then run the program.

#include<stdio.h>#include<conio.h>#define N 100

/* make a list of words, every words should be written under previous one to make sure it's a list of words. */

/* upper case letters will be arranged before small case letter, so it is recommended to use the list of either Capital letter or small case letters but not both together. */struct word { char wrd [30]; };

void main() {

struct word w[N];

FILE *fp;char s1[30];int i=0,count=0;void srt_wrd(); /* function to sort and print list */

clrscr();

fp=fopen("TRIAL.TXT","rb+");

while(fgets(s1,30,fp)!=NULL) {strcpy(w[i].wrd,s1); /* copying each word in array of structure */i++;count++; /* count of all the words */}

printf("Total words if file = %3d\n",count);

printf("\t\tList in alphabetical order:\n");srt_wrd(&w,count); /* function for sorting and printing list */

fclose(fp);getch();

}

void srt_wrd( struct word *w, int n) {

int i,j,k=0;struct word temp;

Solution:

Page 764: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

/***************************************//* sorting words in alphabetical order *//***************************************/

for(i=0;i<=n;i++) {

for(j=i+1;j<n;j++) {

/* testing the first alphabets of two words */

if(w[i].wrd[0] > w[j].wrd[0]) {

temp=w[i];w[i]=w[j];w[j]=temp;}

/* testing the first two alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1] > w[j].wrd[1]) {

temp=w[i];w[i]=w[j];w[j]=temp;}

/* testing first three alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]>w[j].wrd[2]) {

temp=w[i];w[i]=w[j];w[j]=temp;}}

/* testing first four alphabets of two words */

else if(w[i].wrd[0]==w[j].wrd[0] && w[i].wrd[1]==w[j].wrd[1]) {

if(w[i].wrd[2]==w[j].wrd[2] && w[i].wrd[3]>w[j].wrd[2]) {

temp=w[i];w[i]=w[j];w[j]=temp;}}

}}

/*****************************//* printing the sorted words *//*****************************/

for(i=0;i<n;i++) {

printf("%-s\n",w[i].wrd);

k++;

if(k==10) {

printf("\n\npress any key to go to next page...");getch();

Page 765: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

k=1;clrscr();}}

}

--------------------------------------------------------------------------------------------------------------

(s) Write a program to carry out the following:(a) Read a text file ‘INPUT.TXT’(b) Print each word in reverse orderExample,Input: INDIA IS MY COUNTRYOutput: AIDNI SI YM YRTNUOCAssume that each word length is maximum of 10 characters and each word is separated by newline/blank characters.

NOTE: Make a file "INPUT.TXT" in bin directory and write something in it, then run the program.

#include<stdio.h>#include<conio.h>#include<string.h>

void main() {

FILE *fs;char s[80];void rev();

clrscr();

fs=fopen("INPUT.TXT","r");

if(fs==NULL) {

printf("cannot open file!");exit();}

while(fgets(s,79,fs)!=NULL)rev(s);

fclose(fs);

getch();

}

void rev(char s1[80]) {

char s2[80];int i=0,j=0;

while(s1[i]!='\0') {

s2[j]=s1[i];

if(s1[i]==' ' || s1[i]=='\0') {

s2[j]='\0';

Solution:

Page 766: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

strrev(s2);

printf("%s ",s2);

j=-1;

}

i++;j++;}

s2[j]='\0';

printf("%s",strrev(s2));

}

-----------------------------------------------------------------------------------------------------------------

(s) Write a C program to read a large text file ‘NOTES.TXT’ and print it on the printer in cut-sheets, introducing page breaks at the end of every 50 lines and a pause message on the screen at the end of every page for the user to change the paper.

NOTE: Make a file as "NOTES.TXT" in bin directory and write/paste some text in it, then run the program.

#include<stdio.h> #include<conio.h> #include<string.h>

void print();

void main() {

FILE *fp;

char s[80]; int x=4,y=4,c=0,pg=0; clrscr();

fp=fopen("NOTES.TXT","r");

if(fp==NULL) {

puts("cannot open file!"); exit(); }

while(fgets(s,74,fp)!=NULL) {

gotoxy(30,1); /* printing page number */ printf("Page No: %3d",pg);

print(s,x,y,c); /* function to print */

c++; y++;

Solution:

Page 767: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:02:00-08:00&max-results=7&start=7&by-date=false[07-Apr-14 9:12:55 PM]

if(c>51) { /* checking for page end */

pg++;

c=0; gotoxy(2,24); printf("press any key to change paper..."); getch();

clrscr();

}

if(y>22) { /* checking for total lines */

gotoxy(2,24); printf("press any key to go to next page..."); getch(); y=5; clrscr(); }

}

fclose(fp); }

void print(char *s,int x, int y, int c) {

/* page border */

int i,bdr,bdr2;

gotoxy(1,2); printf("%c",218); for(bdr=3;bdr<23;bdr++) {

gotoxy(1,bdr); printf("%c",179);

gotoxy(79,bdr); printf("%c",179);

}

gotoxy(79,2); printf("%c",191);

gotoxy(79,23); printf("%c",217);

gotoxy(1,23); printf("%c",192);

for(bdr2=2;bdr2<=78;bdr2++) {

gotoxy(bdr2,2); printf("%c",196);

}

gotoxy(x,y);

puts(s);

if(c>50) {

for(i=2;i<79;i+=2) {

Page 769: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 2 (The Decision Control Structure)

(a) If cost price and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss he incurred.

#include<stdio.h>#include<conio.h>main() {

int cp,sp,rslt;clrscr();

printf("Please enter the cost price of the item: \n");scanf("%d",&cp);

printf("Please enter the selling price of the item: \n");scanf("%d",&sp);

if(cp>sp) {rslt=cp-sp;printf("\nSeller has incurred LOSS of %d rupees.\n",rslt);}

if(cp<sp){rslt=sp-cp;printf("\nSeller has made PROFIT of %d rupees.\n",rslt);}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Any integer is input through the keyboard. Write a program to find out whether it is an odd number or even number.

#include<stdio.h>

Exercise [C]

Solution:

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 770: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

#include<conio.h>

main() {

int i;clrscr();

printf("Please enter the number: \n");scanf("%d",&i);

if(i%2==0)printf("\nThe number is EVEN.\n");

elseprintf("\nThe number is ODD.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(c) Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not.(Hint: Use the % (modulus) operator)

#include<stdio.h>#include<conio.h>

main() {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4==0)printf("\nThe year is a LEAP YEAR.\n");

elseprintf("\nThe Year is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input through the keyboard write a program to find out what is the day on 1st January of this year.

#include<stdio.h>#include<conio.h>

main() {

int month=1,year,a,day=1;

clrscr();

printf("Enter year: ");

Solution:

Solution:

Page 771: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

scanf("%d",&year);

/* 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 */

printf("\n\nFirst day is ");

if(day==0)printf("Sunday");

else if(day==1)printf("Monday");

else if(day==2)printf("Tuesday");

else if(day==3)printf("Wednesday");

else if(day==4)printf("Thursday");

else if(day==5)printf("Friday");

else if(day==6)printf("Saturday");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.

#include<stdio.h>#include<conio.h>

main() {

long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();

printf("Please enter a five digit number: \n");scanf("%ld",&i);

d1=i/10000;a=i%10000;

d2=a/1000;b=a%1000;

d3=b/100;

Solution:

Page 772: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

c=b%100;

d4=c/10;d=c%10;

d5=d/1;

n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);

printf("\nThe REVERSED NUMBER is %ld \n",n_num);

if(n_num==i){printf("\nboth numbers are SAME.\n");}else {printf("\nboth number are NOT SAME.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the ages of Ram, Shyam and Ajay are input through the keyboard, write a program to determine the youngest of the three.

#include<stdio.h>#include<conio.h>

main() {

int ram,shyam,ajay;clrscr();

printf("Please enter the age of RAM: ");scanf("%d",&ram);

printf("\nPlease enter the age of SHYAM: ");scanf("%d",&shyam);

printf("\nPlease enter the age or AJAY: ");scanf("%d",&ajay);

if(ram<shyam){if(ram<ajay) {printf("\nRam is the YOUNGEST.\n");} } if(shyam<ram){if(shyam<ajay) {printf("\nShyam is the YOUNGEST.\n");} }

if(ajay<ram) {if(ajay<shyam) {printf("\nAjay is the YOUNGEST.\n");} }

getch();

Solution:

Page 773: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

return 0;

}

------------------------------------------------------------------------------------------------------------

(g)Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.

#include<stdio.h>#include<conio.h>main() {

int a1,a2,a3;clrscr();

printf("Please enter the first angle: \n");scanf("%d",&a1);

printf("\nPlease enter the second angle: \n");scanf("%d",&a2);

printf("\nPlease enter the third angle: \n");scanf("%d",&a3);

if(a1+a2+a3==180) {printf("\nThe triangle is VALID.\n");}

else {printf("\nThe triangle is NOT VALID.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(h) Find the absolute value of a number entered through the keyboard.

#include<stdio.h>#include<conio.h>#include<stdlib.h>main() {

int i,av;clrscr();

printf("Please enter any number: ");scanf("%d",&i);

av=abs(i);

/* abs(); is a standard function to calculate absolute value.\this function has been defined in <stdlib.h> library. */

printf("Absolute value = %d",av);

getch();

Solution:

Solution:

Page 774: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

return 0;

}

------------------------------------------------------------------------------------------------------------

(i) Given the length and breadth of a rectangle, write a program to find whether the area of the rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and breadth = 4 is greater than its perimeter.

#include<stdio.h>#include<conio.h>main() {

int l,b,area,peri;clrscr();

printf("Please enter the length and bredth of a rectangle: \n");scanf("%d%d",&l,&b);

area=l*b;peri=2*(l+b);

if(area>peri) {printf("\nThe Area of Rectangle is GREATER then it's perimeter.\n");}

else {printf("\nThe area of Rectangle is NOT GREATER then it's perimeter.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

#include<stdio.h>#include<conio.h>main() {

int x1,y1,x2,y2,x3,y3,curve1,curve2;clrscr();

printf("Please enter the values of Three points: ");printf("\n(x1,y1):\n");scanf("%d%d",&x1,&y1);printf("\n(x2,y2):\n");scanf("%d%d",&x2,&y2);printf("\n(x3,y3):\n");scanf("%d%d",&x3,&y3);

curve1=(x2-x1)/(y2-y1);curve2=(x3-x2)/(y3-y2);

if(curve1==curve2)printf("\nAll three points fall on one straight line.\n");else

Solution:

Solution:

Page 775: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

printf("\nThese three points do not fall on one straight line.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(k) Given the coordinates (x, y) of a center of a circle and it’s radius, write a program which will determine whether a point lies inside the circle, on the circle or outside the circle.(Hint: Use sqrt( ) and pow( ) functions)

#include<stdio.h>#include<conio.h>#include<math.h>main() {

int x,y,x_,y_,r,point;clrscr();

printf("Please enter the coordinates of center: \n");printf("(x,y): ");scanf("%d%d",&x,&y);printf("\nPlease enter the radius of circle: \n");scanf("%d",&r);printf("\nPlease enter the point to check: \n");printf("(x`,y`): ");scanf("%d%d",&x_,&y_);

point=pow(x_,2)+pow(y_,2)+pow(x,2)+pow(y,2)-(2*x_*x)-(2*y_*y)-pow(r,2);

if(point<0)printf("\nThe point lies inside the circle.\n");

if(point>0)printf("\nThe point lies outside the circle.\n");

if(point==0)printf("\nThe point lies on the circle.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(l) Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis or at the origin, viz. (0, 0).

#include<stdio.h>#include<conio.h>main() {

int x,y;clrscr();

printf("Please enter points\n");printf("(x,y): \n");scanf("%d%d",&x,&y);

Solution:

Solution:

Page 776: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

if(x==0&&y!=0) {printf("\nThe point lies on Y AXIS.\n");}

else if(x!=0&&y==0) {printf("\nThe point lies on X AXIS.\n");}

else if(x==0&&y==0) {printf("\nThe point lies at the origin.\n");}

else {printf("\nThe point doesn't lie on any axis or at origin.\n");}

getch();return 0;

}

___________________________________________________________________

(a) Any year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators && and ||.

#include<stdio.h>#include<conio.h>main() {

int yr;clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

if(yr%4==0 || !((yr%4)>0) )printf("\nThe is a LEAP YEAR.\n");

elseprintf("\nThis is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol.The following table shows the range of ASCII values for various characters.

The following table shows the range of ASCII values for various characters.

Exercise [F]

Solution:

Page 777: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

Characters

Characters ASCII values

A – Z 65 - 90a – z 97 - 1220 – 9 48 - 57special symbols 0 - 47, 58 - 64, 91 - 96, 123 - 127

#include<stdio.h>#include<conio.h>main() {

char ch;clrscr();

printf("Please enter any character:");scanf("%c",&ch);

if(ch>=65&&ch<=90)printf("\nThe character you entered is a CAPITAL LETTER.\n");

if(ch>=97&&ch<=122)printf("\nThe character you entered is a SMALL LETTER.\n");

if(ch>=48&&ch<=57)printf("\nThe character you entered is a DIGIT.\n");

if(ch>=0&&ch<=47 || ch>=58&&ch<=64 || ch>=91&&ch<=96 || ch>=123&&ch<=127)printf("\nThe character you entered is a SPECIAL SYMBOL.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(c) An Insurance company follows following rules to calculate premium.(1) If a person’s health is excellent and the person is between 25 and 35 years of age and lives in a city and is a male then the premium is Rs. 4 per thousand and his policy amount cannot exceed Rs. 2 lakhs.(2) If a person satisfies all the above conditions except that the sex is female then the premium is Rs. 3 per thousand and her policy amount cannot exceed Rs. 1 lakh.(3) If a person’s health is poor and the person is between 25 and 35 years of age and lives in a village and is a male then the premium is Rs. 6 per thousand and his policy cannot exceed Rs. 10,000.(4) In all other cases the person is not insured.

Write a program to output whether the person should be insured or not, his/her premium rate and maximum amount for which he/she can be insured.

Solution:

Solution:

Page 778: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

#include<stdio.h>#include<conio.h>main() {

int age,premium,p_a,hlt,rsdnc,sex;long amount;clrscr();

printf("Please tell the HEALTH of the person\n(1 for excellent or 2 for poor) :\n");scanf("%d",&hlt);

printf("Please tell the AGE of the person: \n");scanf("%d",&age);

printf("Please tell the residence\n(1 for city or 2 for village) : \n");scanf("%d",&rsdnc);

printf("Please tell you sex\n(1 for male or 2 for female) : \n");scanf("%d",&sex);

if(hlt==1 && age>=25&&age<=35 && rsdnc==1 && sex==1) {premium=4;amount=200000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==1||hlt==2 && age>=25&&age<=35 && rsdnc==1||rsdnc==2 && sex==2) {premium=3;amount=100000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==2 && age>=25&&age<=35 && rsdnc==2 && sex==1) {premium=6;amount=10000;

printf("\nThis person is insured.\n");printf("Premium rate is = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else {printf("\nThis person cannot be insured.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) A certain grade of steel is graded according to the following conditions:(i) Hardness must be greater than 50(ii) Carbon content must be less than 0.7(iii) Tensile strength must be greater than 5600

The grades are as follows:

Page 779: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

Grade is 10 if all three conditions are metGrade is 9 if conditions (i) and (ii) are metGrade is 8 if conditions (ii) and (iii) are metGrade is 7 if conditions (i) and (iii) are metGrade is 6 if only one condition is metGrade is 5 if none of the conditions are met

Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and output the grade of the steel.

#include<stdio.h>#include<conio.h>main() {

int hdn,tnsl,hardness=50,tensile_strength=5600;

float c,carbon_content=0.7;

clrscr();

printf("Please enter the Hardness: \n");scanf("%d",&hdn);

printf("\nPlease enter the Carbon content: \n");scanf("%f",&c);

printf("\nPlease enter the Tensile Strength: \n");scanf("%d",&tnsl);

if(hdn>hardness && c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 10.\n");

else if(hdn>hardness && c<carbon_content)printf("\nThe steel has been Graded 9.\n");

else if(c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 8.\n");

else if(hdn>hardness && tnsl>tensile_strength)printf("\nThe steel has been Graded 7.\n");

else if(hdn>hardness || c<carbon_content || tnsl>tensile_strength)printf("\nThe steel has been Graded 6.\n");

elseprintf("\nThe steel has been Graded 5.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A library charges a fine for every book returned late. For first 5 days the fine is 50 paise, for 6-10 days fine is one rupee and above 10 days fine is 5 rupees. If you return the book after 30 days your membership will be cancelled. Write a program to accept the number of days the

Solution:

Page 780: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

member is late to return the book and display the fine or the appropriate message.

#include<stdio.h>#include<conio.h>main() {int days;clrscr();

printf("Please enter the days of being late in returning the book:\n");scanf("%d",&days);

if(days<=5)printf("\nYou have been fined for 50 paise.\n");

if(days>=6&&days<=10)printf("\nYou have been fined for 1 rupee.\n");

if(days>10&&days<30)printf("\nYou have been fined for 5 rupee.\n");

if(days>=30)printf("\nYour membership has been cancelled.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.

#include<stdio.h>#include<conio.h>main() {

int s1,s2,s3,ls,ss1,ss2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d%d%d",&s1,&s2,&s3);

if(s1>s2&&s1>s3){ls=s1;ss1=s2;ss2=s3;}if(s2>s1&&s2>s3) {ls=s2;ss1=s1;ss2=s3;}if(s3>s1&&s3>s2) {ls=s3;ss1=s1;ss2=s2;}

Solution:

Solution:

Page 781: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

if((ss1+ss2)>ls) {printf("\nThe Triangle is VALID.\n");}else {printf("The triangle is NOT VALID.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(g) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.

#include<stdio.h>#include<conio.h>

main() {

int s1,s2,s3,largest,s_1,s_2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d %d %d",&s1,&s2,&s3);

if(s1==s2&&s1!=s3||s1==s3&&s1!=s2 || s2==s3&&s2!=s1||s2==s1&&s2!=s3 ||s3==s1&&s3!=s2||s3==s2&&s3!=s1){printf("The Triangle is ISOSCELES.\n");}

if(s1==s2&&s2==s3 || s2==s1&&s2==s3 || s3==s1&&s3==s2){printf("The Triangle is EQUILATERAL.\n");}

if(s1!=s2&&s2!=s3 || s2!=s1&&s1!=s3 || s3!=s1&&s1!=s2){printf("The Triangle is SCALENE.\n");}

if(s1>s2&&s1>s3){largest=s1;s_1=s2;s2=s3;}

if(s2>s1&&s2>s3){largest=s2;s_1=s1;s_2=s3;}

if(s3>s1&&s3>s2){largest=s3;s_1=s1;s_2=s2;}

if(pow(largest,2)==pow(s_1,2)+pow(s_2,2))printf("The Triangle is RIGHT ANGLED.\n");

getch();return 0;}

Solution:

Page 782: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

------------------------------------------------------------------------------------------------------------

(h) In a company, worker efficiency is determined on the basis of the time required for a worker to complete a particular job. If the time taken by the worker is between 2 – 3 hours, then the worker is said to be highly efficient. If the time required by the worker is between 3 – 4 hours, then the worker is ordered to improve speed. If the time taken is between 4 – 5 hours, the worker is given training to improve his speed, and if the time taken by the worker is more than 5 hours, then the worker has to leave the company. If the time taken by the worker is input through the keyboard, find the efficiency of the worker.

#include<stdio.h>#include<conio.h>main() {

int hrs;clrscr();

printf("Please enter the hours of completing job: ");scanf("%d",&hrs);

if(hrs>=2 && hrs<=3)printf("\nThe worker is HIGHLY EFFICIENT.\n");

if(hrs>=3 && hrs<=4)printf("\nThe worker is ordered to IMPROVE SPEED.\n");

if(hrs>=4 && hrs<= 5)printf("\nThe worker should be given TRAINING TO IMPROVE SPEED.\n");

if(hrs>5)printf("\nThe worker should be asked to leave the company.\n");

elseprintf("The worker is HIGHLY EFFICIENT.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(i) A university has the following rules for a student to qualify for a degree with A as the main subject and B as the subsidiary subject: (a) He should get 55 percent or more in A and 45 percent or more in B. (b) If he gets than 55 percent in A he should get 55 percent or more in B. However, he should get at least 45 percent in A. (c) If he gets less than 45 percent in B and 65 percent or more in A he is allowed to reappear in an examination in B to qualify. (d) In all other cases he is declared to have failed.

Write a program to receive marks in A and B and Output whether the student has passed, failed or is allowed to reappear in B.

#include<stdio.h>

Solution:

Solution:

Page 783: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

#include<conio.h>main() {

int a,b;clrscr();

printf("Please enter the marks in subject A: \n");scanf("%d",&a);

printf("\nPlease enter the marks in subject B: \n");scanf("%d",&b);

if(a>=55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a==55 && b>=55 || a==55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a>=65 && b<45) {printf("Student is allowed to reappear in the exam of B to qualify.\n"); }

else {printf("Student has failed.\n"); }

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) The policy followed by a company to process customer orders is given by the following rules:

(a) If a customer order is less than or equal to that in stock and has credit is OK, supply has requirement.(b) If has credit is not OK do not supply. Send him intimation.(c) If has credit is Ok but the item in stock is less than has order, supply what is in stock. Intimate to him data the balance will be shipped.

Write a C program to implement the company policy.

#include<stdio.h>#include<conio.h>main() {

int stock,credit,order;clrscr();

printf("Please enter the stock available: ");scanf("%d",&stock);printf("\nPlease enter the order: ");scanf("%d",&order);printf("\nPlease enter the credit: ");scanf("%d",&credit);

if(credit!=0&&order<=stock) {

Solution:

Page 784: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

printf("\nSupply\n");}

else if(credit!=0&&order>stock) {printf("\nAvailable items will be supplied.\n");}

else {printf("\nNo supply.\n");}

getch();return 0;

}______________________________________________________________________

(a) Using conditional operators determine: (1) Whether the character entered through the keyboard is a lower case alphabet or not.(2) Whether a character entered through the keyboard is a special symbol or not.

#include<stdio.h>#include<conio.h>

char main() {

char ch;clrscr();

printf("Please enter a character: \n");scanf("%c",&ch);

if(ch>=97 && ch<=122) {printf("\n[A] This character is a SMALL CASE alphabet.\n");}

else {printf("\n[A] This character is NOT A SMALL CASE alphabet.\n");}

if(ch>=0&&ch<=47||ch>=58&&ch<=64||ch>=91&&ch<=96||ch>=123&&ch<=127){printf("\n[B] This character is a SPECIAL SYMBOL.\n");}

else{printf("\n[B] This character is NOT A SPECIAL SYMBOL.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

Exercise [J]

Solution:

Page 785: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true&start=1&by-date=false[07-Apr-14 9:14:09 PM]

(b) Write a program using conditional operators to determine whether a year entered through the keyboard is a leap year or not.

#include<stdio.h>#include<conio.h>main () {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4!=0)printf("\nThis is NOT A LEAP YEAR.\n");

elseprintf("\nThis is a LEAP YEAR.\n");

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(c) Write a program to find the greatest of the three numbers entered through the keyboard using conditional operators.

#include<stdio.h>#include<conio.h>

main() {

int n1,n2,n3;clrscr();

printf("\nPlease enter 3 numbers: \n");scanf("%d %d %d",&n1,&n2,&n3);

if(n1>n2 && n1>n3) {printf("\n%d is the greatest number of the three numbers.\n",n1);}

else if(n2>n1 && n2>n3) {printf("\n%d is the greatest number of the three numbers.\n",n2);}

else if(n3>n2 && n3>n1) {printf("\n%d is the greatest number of the three numbers.\n",n3);}

else {printf("\nwrong input!\n");}

getch();return 0;

}

_______________________________________________________________________

Solution:

Solution:

Page 787: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 2 (The Decision Control Structure)

(a) If cost price and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss he incurred.

#include<stdio.h>#include<conio.h>main() {

int cp,sp,rslt;clrscr();

printf("Please enter the cost price of the item: \n");scanf("%d",&cp);

printf("Please enter the selling price of the item: \n");scanf("%d",&sp);

if(cp>sp) {rslt=cp-sp;printf("\nSeller has incurred LOSS of %d rupees.\n",rslt);}

if(cp<sp){rslt=sp-cp;printf("\nSeller has made PROFIT of %d rupees.\n",rslt);}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Any integer is input through the keyboard. Write a program to find out whether it is an odd number or even number.

#include<stdio.h>

Exercise [C]

Solution:

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 788: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

#include<conio.h>

main() {

int i;clrscr();

printf("Please enter the number: \n");scanf("%d",&i);

if(i%2==0)printf("\nThe number is EVEN.\n");

elseprintf("\nThe number is ODD.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(c) Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not.(Hint: Use the % (modulus) operator)

#include<stdio.h>#include<conio.h>

main() {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4==0)printf("\nThe year is a LEAP YEAR.\n");

elseprintf("\nThe Year is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input through the keyboard write a program to find out what is the day on 1st January of this year.

#include<stdio.h>#include<conio.h>

main() {

int month=1,year,a,day=1;

clrscr();

printf("Enter year: ");

Solution:

Solution:

Page 789: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

scanf("%d",&year);

/* 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 */

printf("\n\nFirst day is ");

if(day==0)printf("Sunday");

else if(day==1)printf("Monday");

else if(day==2)printf("Tuesday");

else if(day==3)printf("Wednesday");

else if(day==4)printf("Thursday");

else if(day==5)printf("Friday");

else if(day==6)printf("Saturday");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.

#include<stdio.h>#include<conio.h>

main() {

long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();

printf("Please enter a five digit number: \n");scanf("%ld",&i);

d1=i/10000;a=i%10000;

d2=a/1000;b=a%1000;

d3=b/100;

Solution:

Page 790: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

c=b%100;

d4=c/10;d=c%10;

d5=d/1;

n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);

printf("\nThe REVERSED NUMBER is %ld \n",n_num);

if(n_num==i){printf("\nboth numbers are SAME.\n");}else {printf("\nboth number are NOT SAME.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the ages of Ram, Shyam and Ajay are input through the keyboard, write a program to determine the youngest of the three.

#include<stdio.h>#include<conio.h>

main() {

int ram,shyam,ajay;clrscr();

printf("Please enter the age of RAM: ");scanf("%d",&ram);

printf("\nPlease enter the age of SHYAM: ");scanf("%d",&shyam);

printf("\nPlease enter the age or AJAY: ");scanf("%d",&ajay);

if(ram<shyam){if(ram<ajay) {printf("\nRam is the YOUNGEST.\n");} } if(shyam<ram){if(shyam<ajay) {printf("\nShyam is the YOUNGEST.\n");} }

if(ajay<ram) {if(ajay<shyam) {printf("\nAjay is the YOUNGEST.\n");} }

getch();

Solution:

Page 791: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

return 0;

}

------------------------------------------------------------------------------------------------------------

(g)Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.

#include<stdio.h>#include<conio.h>main() {

int a1,a2,a3;clrscr();

printf("Please enter the first angle: \n");scanf("%d",&a1);

printf("\nPlease enter the second angle: \n");scanf("%d",&a2);

printf("\nPlease enter the third angle: \n");scanf("%d",&a3);

if(a1+a2+a3==180) {printf("\nThe triangle is VALID.\n");}

else {printf("\nThe triangle is NOT VALID.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(h) Find the absolute value of a number entered through the keyboard.

#include<stdio.h>#include<conio.h>#include<stdlib.h>main() {

int i,av;clrscr();

printf("Please enter any number: ");scanf("%d",&i);

av=abs(i);

/* abs(); is a standard function to calculate absolute value.\this function has been defined in <stdlib.h> library. */

printf("Absolute value = %d",av);

getch();

Solution:

Solution:

Page 792: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

return 0;

}

------------------------------------------------------------------------------------------------------------

(i) Given the length and breadth of a rectangle, write a program to find whether the area of the rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and breadth = 4 is greater than its perimeter.

#include<stdio.h>#include<conio.h>main() {

int l,b,area,peri;clrscr();

printf("Please enter the length and bredth of a rectangle: \n");scanf("%d%d",&l,&b);

area=l*b;peri=2*(l+b);

if(area>peri) {printf("\nThe Area of Rectangle is GREATER then it's perimeter.\n");}

else {printf("\nThe area of Rectangle is NOT GREATER then it's perimeter.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

#include<stdio.h>#include<conio.h>main() {

int x1,y1,x2,y2,x3,y3,curve1,curve2;clrscr();

printf("Please enter the values of Three points: ");printf("\n(x1,y1):\n");scanf("%d%d",&x1,&y1);printf("\n(x2,y2):\n");scanf("%d%d",&x2,&y2);printf("\n(x3,y3):\n");scanf("%d%d",&x3,&y3);

curve1=(x2-x1)/(y2-y1);curve2=(x3-x2)/(y3-y2);

if(curve1==curve2)printf("\nAll three points fall on one straight line.\n");else

Solution:

Solution:

Page 793: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

printf("\nThese three points do not fall on one straight line.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(k) Given the coordinates (x, y) of a center of a circle and it’s radius, write a program which will determine whether a point lies inside the circle, on the circle or outside the circle.(Hint: Use sqrt( ) and pow( ) functions)

#include<stdio.h>#include<conio.h>#include<math.h>main() {

int x,y,x_,y_,r,point;clrscr();

printf("Please enter the coordinates of center: \n");printf("(x,y): ");scanf("%d%d",&x,&y);printf("\nPlease enter the radius of circle: \n");scanf("%d",&r);printf("\nPlease enter the point to check: \n");printf("(x`,y`): ");scanf("%d%d",&x_,&y_);

point=pow(x_,2)+pow(y_,2)+pow(x,2)+pow(y,2)-(2*x_*x)-(2*y_*y)-pow(r,2);

if(point<0)printf("\nThe point lies inside the circle.\n");

if(point>0)printf("\nThe point lies outside the circle.\n");

if(point==0)printf("\nThe point lies on the circle.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(l) Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis or at the origin, viz. (0, 0).

#include<stdio.h>#include<conio.h>main() {

int x,y;clrscr();

printf("Please enter points\n");printf("(x,y): \n");scanf("%d%d",&x,&y);

Solution:

Solution:

Page 794: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

if(x==0&&y!=0) {printf("\nThe point lies on Y AXIS.\n");}

else if(x!=0&&y==0) {printf("\nThe point lies on X AXIS.\n");}

else if(x==0&&y==0) {printf("\nThe point lies at the origin.\n");}

else {printf("\nThe point doesn't lie on any axis or at origin.\n");}

getch();return 0;

}

___________________________________________________________________

(a) Any year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators && and ||.

#include<stdio.h>#include<conio.h>main() {

int yr;clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

if(yr%4==0 || !((yr%4)>0) )printf("\nThe is a LEAP YEAR.\n");

elseprintf("\nThis is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol.The following table shows the range of ASCII values for various characters.

The following table shows the range of ASCII values for various characters.

Exercise [F]

Solution:

Page 795: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

Characters

Characters ASCII values

A – Z 65 - 90a – z 97 - 1220 – 9 48 - 57special symbols 0 - 47, 58 - 64, 91 - 96, 123 - 127

#include<stdio.h>#include<conio.h>main() {

char ch;clrscr();

printf("Please enter any character:");scanf("%c",&ch);

if(ch>=65&&ch<=90)printf("\nThe character you entered is a CAPITAL LETTER.\n");

if(ch>=97&&ch<=122)printf("\nThe character you entered is a SMALL LETTER.\n");

if(ch>=48&&ch<=57)printf("\nThe character you entered is a DIGIT.\n");

if(ch>=0&&ch<=47 || ch>=58&&ch<=64 || ch>=91&&ch<=96 || ch>=123&&ch<=127)printf("\nThe character you entered is a SPECIAL SYMBOL.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(c) An Insurance company follows following rules to calculate premium.(1) If a person’s health is excellent and the person is between 25 and 35 years of age and lives in a city and is a male then the premium is Rs. 4 per thousand and his policy amount cannot exceed Rs. 2 lakhs.(2) If a person satisfies all the above conditions except that the sex is female then the premium is Rs. 3 per thousand and her policy amount cannot exceed Rs. 1 lakh.(3) If a person’s health is poor and the person is between 25 and 35 years of age and lives in a village and is a male then the premium is Rs. 6 per thousand and his policy cannot exceed Rs. 10,000.(4) In all other cases the person is not insured.

Write a program to output whether the person should be insured or not, his/her premium rate and maximum amount for which he/she can be insured.

Solution:

Solution:

Page 796: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

#include<stdio.h>#include<conio.h>main() {

int age,premium,p_a,hlt,rsdnc,sex;long amount;clrscr();

printf("Please tell the HEALTH of the person\n(1 for excellent or 2 for poor) :\n");scanf("%d",&hlt);

printf("Please tell the AGE of the person: \n");scanf("%d",&age);

printf("Please tell the residence\n(1 for city or 2 for village) : \n");scanf("%d",&rsdnc);

printf("Please tell you sex\n(1 for male or 2 for female) : \n");scanf("%d",&sex);

if(hlt==1 && age>=25&&age<=35 && rsdnc==1 && sex==1) {premium=4;amount=200000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==1||hlt==2 && age>=25&&age<=35 && rsdnc==1||rsdnc==2 && sex==2) {premium=3;amount=100000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==2 && age>=25&&age<=35 && rsdnc==2 && sex==1) {premium=6;amount=10000;

printf("\nThis person is insured.\n");printf("Premium rate is = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else {printf("\nThis person cannot be insured.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) A certain grade of steel is graded according to the following conditions:(i) Hardness must be greater than 50(ii) Carbon content must be less than 0.7(iii) Tensile strength must be greater than 5600

The grades are as follows:

Page 797: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

Grade is 10 if all three conditions are metGrade is 9 if conditions (i) and (ii) are metGrade is 8 if conditions (ii) and (iii) are metGrade is 7 if conditions (i) and (iii) are metGrade is 6 if only one condition is metGrade is 5 if none of the conditions are met

Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and output the grade of the steel.

#include<stdio.h>#include<conio.h>main() {

int hdn,tnsl,hardness=50,tensile_strength=5600;

float c,carbon_content=0.7;

clrscr();

printf("Please enter the Hardness: \n");scanf("%d",&hdn);

printf("\nPlease enter the Carbon content: \n");scanf("%f",&c);

printf("\nPlease enter the Tensile Strength: \n");scanf("%d",&tnsl);

if(hdn>hardness && c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 10.\n");

else if(hdn>hardness && c<carbon_content)printf("\nThe steel has been Graded 9.\n");

else if(c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 8.\n");

else if(hdn>hardness && tnsl>tensile_strength)printf("\nThe steel has been Graded 7.\n");

else if(hdn>hardness || c<carbon_content || tnsl>tensile_strength)printf("\nThe steel has been Graded 6.\n");

elseprintf("\nThe steel has been Graded 5.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A library charges a fine for every book returned late. For first 5 days the fine is 50 paise, for 6-10 days fine is one rupee and above 10 days fine is 5 rupees. If you return the book after 30 days your membership will be cancelled. Write a program to accept the number of days the

Solution:

Page 798: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

member is late to return the book and display the fine or the appropriate message.

#include<stdio.h>#include<conio.h>main() {int days;clrscr();

printf("Please enter the days of being late in returning the book:\n");scanf("%d",&days);

if(days<=5)printf("\nYou have been fined for 50 paise.\n");

if(days>=6&&days<=10)printf("\nYou have been fined for 1 rupee.\n");

if(days>10&&days<30)printf("\nYou have been fined for 5 rupee.\n");

if(days>=30)printf("\nYour membership has been cancelled.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.

#include<stdio.h>#include<conio.h>main() {

int s1,s2,s3,ls,ss1,ss2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d%d%d",&s1,&s2,&s3);

if(s1>s2&&s1>s3){ls=s1;ss1=s2;ss2=s3;}if(s2>s1&&s2>s3) {ls=s2;ss1=s1;ss2=s3;}if(s3>s1&&s3>s2) {ls=s3;ss1=s1;ss2=s2;}

Solution:

Solution:

Page 799: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

if((ss1+ss2)>ls) {printf("\nThe Triangle is VALID.\n");}else {printf("The triangle is NOT VALID.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(g) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.

#include<stdio.h>#include<conio.h>

main() {

int s1,s2,s3,largest,s_1,s_2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d %d %d",&s1,&s2,&s3);

if(s1==s2&&s1!=s3||s1==s3&&s1!=s2 || s2==s3&&s2!=s1||s2==s1&&s2!=s3 ||s3==s1&&s3!=s2||s3==s2&&s3!=s1){printf("The Triangle is ISOSCELES.\n");}

if(s1==s2&&s2==s3 || s2==s1&&s2==s3 || s3==s1&&s3==s2){printf("The Triangle is EQUILATERAL.\n");}

if(s1!=s2&&s2!=s3 || s2!=s1&&s1!=s3 || s3!=s1&&s1!=s2){printf("The Triangle is SCALENE.\n");}

if(s1>s2&&s1>s3){largest=s1;s_1=s2;s2=s3;}

if(s2>s1&&s2>s3){largest=s2;s_1=s1;s_2=s3;}

if(s3>s1&&s3>s2){largest=s3;s_1=s1;s_2=s2;}

if(pow(largest,2)==pow(s_1,2)+pow(s_2,2))printf("The Triangle is RIGHT ANGLED.\n");

getch();return 0;}

Solution:

Page 800: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

------------------------------------------------------------------------------------------------------------

(h) In a company, worker efficiency is determined on the basis of the time required for a worker to complete a particular job. If the time taken by the worker is between 2 – 3 hours, then the worker is said to be highly efficient. If the time required by the worker is between 3 – 4 hours, then the worker is ordered to improve speed. If the time taken is between 4 – 5 hours, the worker is given training to improve his speed, and if the time taken by the worker is more than 5 hours, then the worker has to leave the company. If the time taken by the worker is input through the keyboard, find the efficiency of the worker.

#include<stdio.h>#include<conio.h>main() {

int hrs;clrscr();

printf("Please enter the hours of completing job: ");scanf("%d",&hrs);

if(hrs>=2 && hrs<=3)printf("\nThe worker is HIGHLY EFFICIENT.\n");

if(hrs>=3 && hrs<=4)printf("\nThe worker is ordered to IMPROVE SPEED.\n");

if(hrs>=4 && hrs<= 5)printf("\nThe worker should be given TRAINING TO IMPROVE SPEED.\n");

if(hrs>5)printf("\nThe worker should be asked to leave the company.\n");

elseprintf("The worker is HIGHLY EFFICIENT.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(i) A university has the following rules for a student to qualify for a degree with A as the main subject and B as the subsidiary subject: (a) He should get 55 percent or more in A and 45 percent or more in B. (b) If he gets than 55 percent in A he should get 55 percent or more in B. However, he should get at least 45 percent in A. (c) If he gets less than 45 percent in B and 65 percent or more in A he is allowed to reappear in an examination in B to qualify. (d) In all other cases he is declared to have failed.

Write a program to receive marks in A and B and Output whether the student has passed, failed or is allowed to reappear in B.

#include<stdio.h>

Solution:

Solution:

Page 801: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

#include<conio.h>main() {

int a,b;clrscr();

printf("Please enter the marks in subject A: \n");scanf("%d",&a);

printf("\nPlease enter the marks in subject B: \n");scanf("%d",&b);

if(a>=55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a==55 && b>=55 || a==55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a>=65 && b<45) {printf("Student is allowed to reappear in the exam of B to qualify.\n"); }

else {printf("Student has failed.\n"); }

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) The policy followed by a company to process customer orders is given by the following rules:

(a) If a customer order is less than or equal to that in stock and has credit is OK, supply has requirement.(b) If has credit is not OK do not supply. Send him intimation.(c) If has credit is Ok but the item in stock is less than has order, supply what is in stock. Intimate to him data the balance will be shipped.

Write a C program to implement the company policy.

#include<stdio.h>#include<conio.h>main() {

int stock,credit,order;clrscr();

printf("Please enter the stock available: ");scanf("%d",&stock);printf("\nPlease enter the order: ");scanf("%d",&order);printf("\nPlease enter the credit: ");scanf("%d",&credit);

if(credit!=0&&order<=stock) {

Solution:

Page 802: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

printf("\nSupply\n");}

else if(credit!=0&&order>stock) {printf("\nAvailable items will be supplied.\n");}

else {printf("\nNo supply.\n");}

getch();return 0;

}______________________________________________________________________

(a) Using conditional operators determine: (1) Whether the character entered through the keyboard is a lower case alphabet or not.(2) Whether a character entered through the keyboard is a special symbol or not.

#include<stdio.h>#include<conio.h>

char main() {

char ch;clrscr();

printf("Please enter a character: \n");scanf("%c",&ch);

if(ch>=97 && ch<=122) {printf("\n[A] This character is a SMALL CASE alphabet.\n");}

else {printf("\n[A] This character is NOT A SMALL CASE alphabet.\n");}

if(ch>=0&&ch<=47||ch>=58&&ch<=64||ch>=91&&ch<=96||ch>=123&&ch<=127){printf("\n[B] This character is a SPECIAL SYMBOL.\n");}

else{printf("\n[B] This character is NOT A SPECIAL SYMBOL.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

Exercise [J]

Solution:

Page 803: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T07:03:00-08:00&max-results=7&reverse-paginate=true[07-Apr-14 9:15:34 PM]

(b) Write a program using conditional operators to determine whether a year entered through the keyboard is a leap year or not.

#include<stdio.h>#include<conio.h>main () {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4!=0)printf("\nThis is NOT A LEAP YEAR.\n");

elseprintf("\nThis is a LEAP YEAR.\n");

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(c) Write a program to find the greatest of the three numbers entered through the keyboard using conditional operators.

#include<stdio.h>#include<conio.h>

main() {

int n1,n2,n3;clrscr();

printf("\nPlease enter 3 numbers: \n");scanf("%d %d %d",&n1,&n2,&n3);

if(n1>n2 && n1>n3) {printf("\n%d is the greatest number of the three numbers.\n",n1);}

else if(n2>n1 && n2>n3) {printf("\n%d is the greatest number of the three numbers.\n",n2);}

else if(n3>n2 && n3>n1) {printf("\n%d is the greatest number of the three numbers.\n",n3);}

else {printf("\nwrong input!\n");}

getch();return 0;

}

_______________________________________________________________________

Solution:

Solution:

Page 805: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

will be uploaded soon ( solutions of Let us C++ and Let us JAVA ), Let me know if you need help in any program here.

Let us C solutions ( By Chetan )

Thursday, 30 January 2014

Let Us C / Chapter 2 (The Decision Control Structure)

(a) If cost price and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss he incurred.

#include<stdio.h>#include<conio.h>main() {

int cp,sp,rslt;clrscr();

printf("Please enter the cost price of the item: \n");scanf("%d",&cp);

printf("Please enter the selling price of the item: \n");scanf("%d",&sp);

if(cp>sp) {rslt=cp-sp;printf("\nSeller has incurred LOSS of %d rupees.\n",rslt);}

if(cp<sp){rslt=sp-cp;printf("\nSeller has made PROFIT of %d rupees.\n",rslt);}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Any integer is input through the keyboard. Write a program to find out whether it is an odd number or even number.

#include<stdio.h>

Exercise [C]

Solution:

Solution:

Chetan Raikwar

2 have me in circles View all

Add to circles

Google+ Followers

Chetan Raikwar

Follow2

This is Chetan Raikwar, Living in Jabalpur, M.P. India.

View my complete profile

About Me

▼ 2014 (16)

▼ January (14)

Let Us C / Chapter 2 (The Decision Control Structu...

Let Us C / Chapter 12 (File Input Output)

Let Us C / Chapter 1 (Getting started)

Let Us C / Chapter 3 (The Loop Control Structure)

Let Us C / Chapter 4 (The Case Control Structure)

Let Us C / Chapter 5 (Functions & Pointers)

Let Us C / Chapter 6 (Data Types Revisited)

Let Us C / Chapter 7 (The C Pre-processor)

Let Us C / Chapter 8 (Arrays)

Let Us C / Chapter 9 (Puppeting on Strings)

Let Us C / Chapter 10 (Structures)

Let Us C / Chapter 11 (Console Input Output)

Let Us C / Chapter 13 (More Issues in Input Output...

Let Us C / Chapter 14 (Operations on Bits)

► February (2)

Blog Archive

More Next Blog» Create Blog Sign In

Page 806: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

#include<conio.h>

main() {

int i;clrscr();

printf("Please enter the number: \n");scanf("%d",&i);

if(i%2==0)printf("\nThe number is EVEN.\n");

elseprintf("\nThe number is ODD.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(c) Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not.(Hint: Use the % (modulus) operator)

#include<stdio.h>#include<conio.h>

main() {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4==0)printf("\nThe year is a LEAP YEAR.\n");

elseprintf("\nThe Year is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input through the keyboard write a program to find out what is the day on 1st January of this year.

#include<stdio.h>#include<conio.h>

main() {

int month=1,year,a,day=1;

clrscr();

printf("Enter year: ");

Solution:

Solution:

Page 807: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

scanf("%d",&year);

/* 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 */

printf("\n\nFirst day is ");

if(day==0)printf("Sunday");

else if(day==1)printf("Monday");

else if(day==2)printf("Tuesday");

else if(day==3)printf("Wednesday");

else if(day==4)printf("Thursday");

else if(day==5)printf("Friday");

else if(day==6)printf("Saturday");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.

#include<stdio.h>#include<conio.h>

main() {

long i,d1,d2,d3,d4,d5,a,b,c,d,n_num;clrscr();

printf("Please enter a five digit number: \n");scanf("%ld",&i);

d1=i/10000;a=i%10000;

d2=a/1000;b=a%1000;

d3=b/100;

Solution:

Page 808: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

c=b%100;

d4=c/10;d=c%10;

d5=d/1;

n_num=(d5*10000)+(d4*1000)+(d3*100)+(d2*10)+(d1*1);

printf("\nThe REVERSED NUMBER is %ld \n",n_num);

if(n_num==i){printf("\nboth numbers are SAME.\n");}else {printf("\nboth number are NOT SAME.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the ages of Ram, Shyam and Ajay are input through the keyboard, write a program to determine the youngest of the three.

#include<stdio.h>#include<conio.h>

main() {

int ram,shyam,ajay;clrscr();

printf("Please enter the age of RAM: ");scanf("%d",&ram);

printf("\nPlease enter the age of SHYAM: ");scanf("%d",&shyam);

printf("\nPlease enter the age or AJAY: ");scanf("%d",&ajay);

if(ram<shyam){if(ram<ajay) {printf("\nRam is the YOUNGEST.\n");} } if(shyam<ram){if(shyam<ajay) {printf("\nShyam is the YOUNGEST.\n");} }

if(ajay<ram) {if(ajay<shyam) {printf("\nAjay is the YOUNGEST.\n");} }

getch();

Solution:

Page 809: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

return 0;

}

------------------------------------------------------------------------------------------------------------

(g)Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.

#include<stdio.h>#include<conio.h>main() {

int a1,a2,a3;clrscr();

printf("Please enter the first angle: \n");scanf("%d",&a1);

printf("\nPlease enter the second angle: \n");scanf("%d",&a2);

printf("\nPlease enter the third angle: \n");scanf("%d",&a3);

if(a1+a2+a3==180) {printf("\nThe triangle is VALID.\n");}

else {printf("\nThe triangle is NOT VALID.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(h) Find the absolute value of a number entered through the keyboard.

#include<stdio.h>#include<conio.h>#include<stdlib.h>main() {

int i,av;clrscr();

printf("Please enter any number: ");scanf("%d",&i);

av=abs(i);

/* abs(); is a standard function to calculate absolute value.\this function has been defined in <stdlib.h> library. */

printf("Absolute value = %d",av);

getch();

Solution:

Solution:

Page 810: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

return 0;

}

------------------------------------------------------------------------------------------------------------

(i) Given the length and breadth of a rectangle, write a program to find whether the area of the rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and breadth = 4 is greater than its perimeter.

#include<stdio.h>#include<conio.h>main() {

int l,b,area,peri;clrscr();

printf("Please enter the length and bredth of a rectangle: \n");scanf("%d%d",&l,&b);

area=l*b;peri=2*(l+b);

if(area>peri) {printf("\nThe Area of Rectangle is GREATER then it's perimeter.\n");}

else {printf("\nThe area of Rectangle is NOT GREATER then it's perimeter.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

#include<stdio.h>#include<conio.h>main() {

int x1,y1,x2,y2,x3,y3,curve1,curve2;clrscr();

printf("Please enter the values of Three points: ");printf("\n(x1,y1):\n");scanf("%d%d",&x1,&y1);printf("\n(x2,y2):\n");scanf("%d%d",&x2,&y2);printf("\n(x3,y3):\n");scanf("%d%d",&x3,&y3);

curve1=(x2-x1)/(y2-y1);curve2=(x3-x2)/(y3-y2);

if(curve1==curve2)printf("\nAll three points fall on one straight line.\n");else

Solution:

Solution:

Page 811: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

printf("\nThese three points do not fall on one straight line.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(k) Given the coordinates (x, y) of a center of a circle and it’s radius, write a program which will determine whether a point lies inside the circle, on the circle or outside the circle.(Hint: Use sqrt( ) and pow( ) functions)

#include<stdio.h>#include<conio.h>#include<math.h>main() {

int x,y,x_,y_,r,point;clrscr();

printf("Please enter the coordinates of center: \n");printf("(x,y): ");scanf("%d%d",&x,&y);printf("\nPlease enter the radius of circle: \n");scanf("%d",&r);printf("\nPlease enter the point to check: \n");printf("(x`,y`): ");scanf("%d%d",&x_,&y_);

point=pow(x_,2)+pow(y_,2)+pow(x,2)+pow(y,2)-(2*x_*x)-(2*y_*y)-pow(r,2);

if(point<0)printf("\nThe point lies inside the circle.\n");

if(point>0)printf("\nThe point lies outside the circle.\n");

if(point==0)printf("\nThe point lies on the circle.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(l) Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis or at the origin, viz. (0, 0).

#include<stdio.h>#include<conio.h>main() {

int x,y;clrscr();

printf("Please enter points\n");printf("(x,y): \n");scanf("%d%d",&x,&y);

Solution:

Solution:

Page 812: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

if(x==0&&y!=0) {printf("\nThe point lies on Y AXIS.\n");}

else if(x!=0&&y==0) {printf("\nThe point lies on X AXIS.\n");}

else if(x==0&&y==0) {printf("\nThe point lies at the origin.\n");}

else {printf("\nThe point doesn't lie on any axis or at origin.\n");}

getch();return 0;

}

___________________________________________________________________

(a) Any year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators && and ||.

#include<stdio.h>#include<conio.h>main() {

int yr;clrscr();

printf("Please enter the year: ");scanf("%d",&yr);

if(yr%4==0 || !((yr%4)>0) )printf("\nThe is a LEAP YEAR.\n");

elseprintf("\nThis is NOT A LEAP YEAR.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(b) Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol.The following table shows the range of ASCII values for various characters.

The following table shows the range of ASCII values for various characters.

Exercise [F]

Solution:

Page 813: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

Characters

Characters ASCII values

A – Z 65 - 90a – z 97 - 1220 – 9 48 - 57special symbols 0 - 47, 58 - 64, 91 - 96, 123 - 127

#include<stdio.h>#include<conio.h>main() {

char ch;clrscr();

printf("Please enter any character:");scanf("%c",&ch);

if(ch>=65&&ch<=90)printf("\nThe character you entered is a CAPITAL LETTER.\n");

if(ch>=97&&ch<=122)printf("\nThe character you entered is a SMALL LETTER.\n");

if(ch>=48&&ch<=57)printf("\nThe character you entered is a DIGIT.\n");

if(ch>=0&&ch<=47 || ch>=58&&ch<=64 || ch>=91&&ch<=96 || ch>=123&&ch<=127)printf("\nThe character you entered is a SPECIAL SYMBOL.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(c) An Insurance company follows following rules to calculate premium.(1) If a person’s health is excellent and the person is between 25 and 35 years of age and lives in a city and is a male then the premium is Rs. 4 per thousand and his policy amount cannot exceed Rs. 2 lakhs.(2) If a person satisfies all the above conditions except that the sex is female then the premium is Rs. 3 per thousand and her policy amount cannot exceed Rs. 1 lakh.(3) If a person’s health is poor and the person is between 25 and 35 years of age and lives in a village and is a male then the premium is Rs. 6 per thousand and his policy cannot exceed Rs. 10,000.(4) In all other cases the person is not insured.

Write a program to output whether the person should be insured or not, his/her premium rate and maximum amount for which he/she can be insured.

Solution:

Solution:

Page 814: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

#include<stdio.h>#include<conio.h>main() {

int age,premium,p_a,hlt,rsdnc,sex;long amount;clrscr();

printf("Please tell the HEALTH of the person\n(1 for excellent or 2 for poor) :\n");scanf("%d",&hlt);

printf("Please tell the AGE of the person: \n");scanf("%d",&age);

printf("Please tell the residence\n(1 for city or 2 for village) : \n");scanf("%d",&rsdnc);

printf("Please tell you sex\n(1 for male or 2 for female) : \n");scanf("%d",&sex);

if(hlt==1 && age>=25&&age<=35 && rsdnc==1 && sex==1) {premium=4;amount=200000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==1||hlt==2 && age>=25&&age<=35 && rsdnc==1||rsdnc==2 && sex==2) {premium=3;amount=100000;

printf("\nThis person is insured.\n");printf("Premium rate = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else if(hlt==2 && age>=25&&age<=35 && rsdnc==2 && sex==1) {premium=6;amount=10000;

printf("\nThis person is insured.\n");printf("Premium rate is = %d rupees per thousand.\n",premium);printf("Person can be insured for maximum amount of %ld rupees.\n",amount);}

else {printf("\nThis person cannot be insured.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(d) A certain grade of steel is graded according to the following conditions:(i) Hardness must be greater than 50(ii) Carbon content must be less than 0.7(iii) Tensile strength must be greater than 5600

The grades are as follows:

Page 815: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

Grade is 10 if all three conditions are metGrade is 9 if conditions (i) and (ii) are metGrade is 8 if conditions (ii) and (iii) are metGrade is 7 if conditions (i) and (iii) are metGrade is 6 if only one condition is metGrade is 5 if none of the conditions are met

Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and output the grade of the steel.

#include<stdio.h>#include<conio.h>main() {

int hdn,tnsl,hardness=50,tensile_strength=5600;

float c,carbon_content=0.7;

clrscr();

printf("Please enter the Hardness: \n");scanf("%d",&hdn);

printf("\nPlease enter the Carbon content: \n");scanf("%f",&c);

printf("\nPlease enter the Tensile Strength: \n");scanf("%d",&tnsl);

if(hdn>hardness && c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 10.\n");

else if(hdn>hardness && c<carbon_content)printf("\nThe steel has been Graded 9.\n");

else if(c<carbon_content && tnsl>tensile_strength)printf("\nThe steel has been Graded 8.\n");

else if(hdn>hardness && tnsl>tensile_strength)printf("\nThe steel has been Graded 7.\n");

else if(hdn>hardness || c<carbon_content || tnsl>tensile_strength)printf("\nThe steel has been Graded 6.\n");

elseprintf("\nThe steel has been Graded 5.\n");

getch();

return 0;

}

------------------------------------------------------------------------------------------------------------

(e) A library charges a fine for every book returned late. For first 5 days the fine is 50 paise, for 6-10 days fine is one rupee and above 10 days fine is 5 rupees. If you return the book after 30 days your membership will be cancelled. Write a program to accept the number of days the

Solution:

Page 816: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

member is late to return the book and display the fine or the appropriate message.

#include<stdio.h>#include<conio.h>main() {int days;clrscr();

printf("Please enter the days of being late in returning the book:\n");scanf("%d",&days);

if(days<=5)printf("\nYou have been fined for 50 paise.\n");

if(days>=6&&days<=10)printf("\nYou have been fined for 1 rupee.\n");

if(days>10&&days<30)printf("\nYou have been fined for 5 rupee.\n");

if(days>=30)printf("\nYour membership has been cancelled.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(f) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.

#include<stdio.h>#include<conio.h>main() {

int s1,s2,s3,ls,ss1,ss2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d%d%d",&s1,&s2,&s3);

if(s1>s2&&s1>s3){ls=s1;ss1=s2;ss2=s3;}if(s2>s1&&s2>s3) {ls=s2;ss1=s1;ss2=s3;}if(s3>s1&&s3>s2) {ls=s3;ss1=s1;ss2=s2;}

Solution:

Solution:

Page 817: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

if((ss1+ss2)>ls) {printf("\nThe Triangle is VALID.\n");}else {printf("The triangle is NOT VALID.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(g) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.

#include<stdio.h>#include<conio.h>

main() {

int s1,s2,s3,largest,s_1,s_2;clrscr();

printf("Please enter the three sides of a triangle: \n");scanf("%d %d %d",&s1,&s2,&s3);

if(s1==s2&&s1!=s3||s1==s3&&s1!=s2 || s2==s3&&s2!=s1||s2==s1&&s2!=s3 ||s3==s1&&s3!=s2||s3==s2&&s3!=s1){printf("The Triangle is ISOSCELES.\n");}

if(s1==s2&&s2==s3 || s2==s1&&s2==s3 || s3==s1&&s3==s2){printf("The Triangle is EQUILATERAL.\n");}

if(s1!=s2&&s2!=s3 || s2!=s1&&s1!=s3 || s3!=s1&&s1!=s2){printf("The Triangle is SCALENE.\n");}

if(s1>s2&&s1>s3){largest=s1;s_1=s2;s2=s3;}

if(s2>s1&&s2>s3){largest=s2;s_1=s1;s_2=s3;}

if(s3>s1&&s3>s2){largest=s3;s_1=s1;s_2=s2;}

if(pow(largest,2)==pow(s_1,2)+pow(s_2,2))printf("The Triangle is RIGHT ANGLED.\n");

getch();return 0;}

Solution:

Page 818: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

------------------------------------------------------------------------------------------------------------

(h) In a company, worker efficiency is determined on the basis of the time required for a worker to complete a particular job. If the time taken by the worker is between 2 – 3 hours, then the worker is said to be highly efficient. If the time required by the worker is between 3 – 4 hours, then the worker is ordered to improve speed. If the time taken is between 4 – 5 hours, the worker is given training to improve his speed, and if the time taken by the worker is more than 5 hours, then the worker has to leave the company. If the time taken by the worker is input through the keyboard, find the efficiency of the worker.

#include<stdio.h>#include<conio.h>main() {

int hrs;clrscr();

printf("Please enter the hours of completing job: ");scanf("%d",&hrs);

if(hrs>=2 && hrs<=3)printf("\nThe worker is HIGHLY EFFICIENT.\n");

if(hrs>=3 && hrs<=4)printf("\nThe worker is ordered to IMPROVE SPEED.\n");

if(hrs>=4 && hrs<= 5)printf("\nThe worker should be given TRAINING TO IMPROVE SPEED.\n");

if(hrs>5)printf("\nThe worker should be asked to leave the company.\n");

elseprintf("The worker is HIGHLY EFFICIENT.\n");

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(i) A university has the following rules for a student to qualify for a degree with A as the main subject and B as the subsidiary subject: (a) He should get 55 percent or more in A and 45 percent or more in B. (b) If he gets than 55 percent in A he should get 55 percent or more in B. However, he should get at least 45 percent in A. (c) If he gets less than 45 percent in B and 65 percent or more in A he is allowed to reappear in an examination in B to qualify. (d) In all other cases he is declared to have failed.

Write a program to receive marks in A and B and Output whether the student has passed, failed or is allowed to reappear in B.

#include<stdio.h>

Solution:

Solution:

Page 819: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

#include<conio.h>main() {

int a,b;clrscr();

printf("Please enter the marks in subject A: \n");scanf("%d",&a);

printf("\nPlease enter the marks in subject B: \n");scanf("%d",&b);

if(a>=55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a==55 && b>=55 || a==55 && b>=45) {printf("Student is qualified for the degree.\n"); }

else if(a>=65 && b<45) {printf("Student is allowed to reappear in the exam of B to qualify.\n"); }

else {printf("Student has failed.\n"); }

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

(j) The policy followed by a company to process customer orders is given by the following rules:

(a) If a customer order is less than or equal to that in stock and has credit is OK, supply has requirement.(b) If has credit is not OK do not supply. Send him intimation.(c) If has credit is Ok but the item in stock is less than has order, supply what is in stock. Intimate to him data the balance will be shipped.

Write a C program to implement the company policy.

#include<stdio.h>#include<conio.h>main() {

int stock,credit,order;clrscr();

printf("Please enter the stock available: ");scanf("%d",&stock);printf("\nPlease enter the order: ");scanf("%d",&order);printf("\nPlease enter the credit: ");scanf("%d",&credit);

if(credit!=0&&order<=stock) {

Solution:

Page 820: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

printf("\nSupply\n");}

else if(credit!=0&&order>stock) {printf("\nAvailable items will be supplied.\n");}

else {printf("\nNo supply.\n");}

getch();return 0;

}______________________________________________________________________

(a) Using conditional operators determine: (1) Whether the character entered through the keyboard is a lower case alphabet or not.(2) Whether a character entered through the keyboard is a special symbol or not.

#include<stdio.h>#include<conio.h>

char main() {

char ch;clrscr();

printf("Please enter a character: \n");scanf("%c",&ch);

if(ch>=97 && ch<=122) {printf("\n[A] This character is a SMALL CASE alphabet.\n");}

else {printf("\n[A] This character is NOT A SMALL CASE alphabet.\n");}

if(ch>=0&&ch<=47||ch>=58&&ch<=64||ch>=91&&ch<=96||ch>=123&&ch<=127){printf("\n[B] This character is a SPECIAL SYMBOL.\n");}

else{printf("\n[B] This character is NOT A SPECIAL SYMBOL.\n");}

getch();return 0;

}

------------------------------------------------------------------------------------------------------------

Exercise [J]

Solution:

Page 821: Let Us C Solutions ( by Chetan )

Let us C solutions ( By Chetan )

http://letuscalllessons.blogspot.com/search?updated-max=2014-01-30T06:51:00-08:00&max-results=7&start=9&by-date=false[07-Apr-14 9:16:59 PM]

(b) Write a program using conditional operators to determine whether a year entered through the keyboard is a leap year or not.

#include<stdio.h>#include<conio.h>main () {

int yr;clrscr();

printf("Please enter the year: \n");scanf("%d",&yr);

if(yr%4!=0)printf("\nThis is NOT A LEAP YEAR.\n");

elseprintf("\nThis is a LEAP YEAR.\n");

getch();return 0;}

------------------------------------------------------------------------------------------------------------

(c) Write a program to find the greatest of the three numbers entered through the keyboard using conditional operators.

#include<stdio.h>#include<conio.h>

main() {

int n1,n2,n3;clrscr();

printf("\nPlease enter 3 numbers: \n");scanf("%d %d %d",&n1,&n2,&n3);

if(n1>n2 && n1>n3) {printf("\n%d is the greatest number of the three numbers.\n",n1);}

else if(n2>n1 && n2>n3) {printf("\n%d is the greatest number of the three numbers.\n",n2);}

else if(n3>n2 && n3>n1) {printf("\n%d is the greatest number of the three numbers.\n",n3);}

else {printf("\nwrong input!\n");}

getch();return 0;

}

_______________________________________________________________________

Solution:

Solution: