Saturday, September 23, 2006

IT Break-out

Yesterday was my birthday... so got a leave from office
sabhi romies office gaye hue the ,

Yuhi akele tanha baithe hue college ki yaad aa gayi wahan ki aish and b'day celebrationssss
Phir kya thaaa socha yahi likh doon..

Anyways just w word of honesty.. yeh idea thoda sa churaya hua hai.. baaki end ka part maine apane hisaab se modify kar diy ahai ;-)

So here you go..
Enjoy!!!


Aaj hamare ODC mein light chali gayi
Lappy band , AC band .. uff jaan nikal gayi
kaafi der jab 'bijli' waapas nahi aayi
tab kisi ko window ki yaad aayi
window khuli.. thandi hawa se pura floor bhar gaya
ye hawa..jo..roj chalti hai .....

elevators nahi chal rahi thi
kuch logon ko stairs bhi dhundni padi
aare ... stairs se toh jaldi pahuncha deti hain
haan ye such hai..
and ye stairs baaki days pe bhi yahi hoti hain

aur maine kya kiya ...
maine usse dekha jo khidki se bahar dekh rahi thi
woh haansi ... achi dikhti hai yaar...
haan bhai.. woh roj hi achi dikhti hai ....
she asked ... walk ? ..
maine kaha haan chalo ..
we talked and talked ..
'project','dart','java','validations',
'no issues','mail','reply' in words ke bina
bhi kaafi saari baaein ho sakti hai doston..
by the way ....she has chin dimple..when she laughsss...

tumhara favorite actor kaun hai .. mera shah rukh ..she said
maine kaha mera bhi ....
she asked really ? kyon ?
i said nahi tum hi bataao .. ( fus gaya)
aur .. actress ..usne puchcha
sharmila tagore ... i said. she said ..
aare but she is so old ...
maine kaha aarey pura to suno..
sharmila tagore ..ki.. beti soha ali khan ..
she said "auh.. very funny" (girls say that a lot hai naa!)
6 baj gaye ...she said ab ghar hi nikal jaatin hoon
but no... light villain banke wapas aa gayi ..
i said .. ab kya... kaam ?
she said haan aur kya ...
hum wapas nikle ...
kuch log ghar bhag rahe the..
ek ne chalte chalte .. apne pm se phone pe kaha ..
sir ab toh main ..
bus mein baith gaya hoon and woh chal padi hai ..
will send that doc tomorrow ...
we looked at each other .. she laughed again .. her dimple ..
toh .. hum pahunch gaye apne apne cubicle
saarein log toh bhaag gaye the
aur hum dono ne ....
apna apna kaam karna chalu kiya …
actoronki dunia se hum 'no issues' ki
duniya mein aa gaye ..
mails and messanger and documents and ....

ab 8 baj gaye..chalo ghar jaana hai
maine duur ka rasta liya ... uske cubicle ke baaju wala
woh abhi baithi hai .. i smiled.. she smiled back..
gettin late haan ? i said nahi .. abhi time hai..
haan baaaaaas.. ye ek mail ...she said
pressed control + enter ..
done ! she said ...
We took the stairs ..
yaar sahi mein stairs jaldi pahunchaati hai (kyon !!)
we walked towards the gate
she said aarey meri bus..
bye ... she said ...
and said.. see you tomorrow
sure...i said
kal log puchenge ye light kyon gayi
and mein puchunga yaar ye light
baar baar kyon nahi jaati...
maana ke light roj nahi jaati hai
per khidki se baahar dekhne mein kya harz hai
khuli saas lene mein kya harz hai
lift mein saamnewaale ke id pe employee id dekhne se acha
Usko haske 'hi..' to keh hi sakte hai
forwards toh bahut bhejte hai ..
koi personal si mail bhejne mein kya harz hai ....
Kyonki doston…light jaayen yaa naa jaayein
Ye hawa to roj hi chalti hain
saaamne wale cubicle ki ladki…. roj hi sunder dikhti hai..... ;-)

Friday, June 23, 2006

Sardar Special

You should be sure the person is Sardar when he:

• puts lipstick on the forehead because he wants to make up his mind.
• gets stabbed in a shoot-out.
• sends a fax with a postage stamp on it.
• tries to drown a fish in water.
• thinks socialism means partying.
• trips over a cordless phone.
• takes a ruler to bed to see how long he slept.
• At the bottom of the application where it says "Sign Here" he puts
"Sagittarius.".
• studies for a blood test and fails.
• sells the car for gas money.
• misses the 44 bus, and takes the 22 twice instead.
• drives to the airport and sees a sign that said, "Airport left", he turns around and
goes home.
• gets locked in Furniture Shop and sleeps on the floor

Pappu NVssss

DISCLAIMER:: The character PAPPU is a virtual character and does-not resembles with any identity, neither any feelings of anyone should be attached with it.ANSHUL GUPTA.

The teacher asks Little Pappu "Which body part goes to heaven first?"
Little Pappu replies "The feet miss"
So the teacher says "Why the feet?" And Little Pappu says "Because when I go in my mummys bedroom at night she has her legs in the air shouting 'Oh my God I'm coming'"

> > > Little Pappu once asked his teacher "Do hearts have legs?." > The teacher answered "Why do you ask that?" > Pappu replied "Yesterday, I heard my dad say sweetheart open your legs."
> > *****************************************************>

Little Pappu's father asked him, "Do you know about the birds and the bees?"
"I don't want to know!" little Johnny said, bursting> into tears. > Confused, the father asked little Johnny what was wrong. > "Oh dad," Little Johnny sobbed, "At age six I got the 'there's no Santa' speech. At age seven I got the 'there's no Easter bunny' speech. Then at age 8 you hit me with the 'there's no tooth fairy' speech! If you're going to tell me now that grown-ups don't really fuck, I've got nothing left to live for!" > ******************************************************> >

Pappu goes to the doctor to have some tests... there after his sugar test....due to the shortage of cotton to wipe the blood, the nurse takes his finger in her mouth,
Pappu says to the nurse....." urine test is coming> up next"!!!

> > > 6 yrs Pappu caught in rape case. In court Lawyer( while holding boy penis):"ur honour, see little boy, can he rape someone?" Boy to lawyer:"Itna na hila, nahin toh case haar jayenge!!"> > >

Little Pappu returns from school and says he got an> F in arithmetic.> "Why?" asks the father.> "The teacher asked 'How much is 2 x 3?' I said 6.> "But that's right!"> "Then she asked me 'How much is 3 x 2?'> "What's the fucking difference?" asks the father.> "That's what I said!" .....> > > >

A few months after his parents were divorced, little Pappu passed by his mom's bedroom and saw her> rubbing her body and moaning, "I need a man, I need a man!" > Over the next couple of months, he saw her doing this several times. One day, he came home from school and heard her moaning. When he peeked into her bedroom, he saw a> man on top of her. > Little Pappu ran into his room, took off his> clothes, threw himself on his bed, started stroking himself, and moaning, "Ohh, I need a bike! I need a bike!"> > > > >

Little Chinki was not the best student in Sunday school. Usually she slept through the class. One day the teacher called on her while she was napping, "Tell me, Chinki, who created the universe?"> > When Chinki didn't stir, little Pappu, a boy seated> in the chair behind her, took a pin and jabbed her> in the rear. "GOD ALMIGHTY!" shouted Chinki and the> teacher said, "Very good" and Chinki fell back asleep. A while later the teacher asked Chinki, "Who is our> Lord and Saviour," But, Chinki didn't even stir from her slumber. Once again, Pappu came to the rescue> and stuck her again. 'JESUS CHRIST!" shouted Chinki and the teacher said, "very good," and Chinki fell back to sleep. Then the teacher asked Chinki a third question. "What> did Eve say to Adam after she had her twenty-third> child?" And again, Pappu jabbed her with the pin.> This time Chinki jumped up and shouted, "IF YOU STICK THAT FUCKING THING IN ME ONE MORE TIME, I'LL BREAK IT IN HALF AND STICK IT UP YOUR ARSE!"> > >

Teacher arrives at the classroom and finds a drawing of a little dick on the board> She simply erases it and starts her class as if> nothing´s happened. Next day a bigger dick is on the board when she arrives and she does the same as on the previous> day.> On the third day a very big dick is on the board and under it´s written: The more you rub it the bigger it grows... > > > >

The teacher, in an attempt to stimulate their minds, asked the class the following question, " What is bright red and shiny?"> Little Pappu jumped up and shouted, " A fire engine> !!!!???"> "No! No!" said the teacher," But I like the way you> think..> Anyone else?"> Little Chinki replied that it was an apple and the> teacher was happy except> Pappu of course..> Anyway, Little Pappu asked the teacher if he can> ask a question to which> she nodded OK. " What is long, hard, rounded and has> hair at one end? "> "Pappu!!!" she screamed, "WE'LL HAVE NONE OF THAT TALK HERE..." Pappu replied, " No, it's a toothbrush, but I like> the way you think"..> > > > >

Little Pappu was sitting in class doing math> problems when his teacher picked him to answer a question.. "Pappu, if there were five birds sitting on a fence and you shot one with> your gun, how many would be left ?"> "None.", replied Pappu. "'cause the rest would fly> away."> "Well, the answer is four," said the teacher. "But I> like the way you are> thinking."> Little Pappu said, "I have a question for you now.> If there were three> women eating ice cream cones in a shop, one licking> her cone, the second> biting her cone, and the third one sucking her cone,> which one is married ?> Well," said the teacher nervously, "I guess the one> sucking the cone?"> "No," said Little Pappu, "the one with the wedding> ring on her finger. But> I like the way you are thinking..> > > > >

Late one night, little Pappu woke up to the some> loud noises coming from> his parents' bedroom. He got out of bed and walked> down the hall towards> his parents room. Before he made it to the end of> the hall, the noises had> ceased and the bathroom light had gone on..> Little Pappu walked into the bathroom and saw his> father removing a used> condom..> "Daddy, what are you doing?" asked little Pappu> His father looked around nervously wondering what he> could tell his son..> I, um, I'm just checking out the bathroom for mice."> replied his father..> Pappu looked at his father with a gaze of confusion> and said, "Well, what> are you doing? Fucking them?"> > > >

Teacher: Use "harassment" in a sentence..> Pappu: Her mouth said 'no', but her ass meant> 'yes'..> > > >

Confused Little Pappu comes home from school with a> note from his teacher,> indicating that "Pappu seems to be having some> difficulty with the> differences between boys and girls, and would his> mother, "please sit down> and have a talk with johnny about this."> So Pappu's mother takes him quietly, by the hand,> upstairs to her bedroom,> and closes the door..> - first, Pappu, you take off my blouse....> so unbuttons her blouse and takes it off..> - ok, now take off my skirt....> and he takes off her skirt..> - now take off my bra....> which he does..> - and now, Pappu, please take off my panties..> and when Pappu finishes removing those, she says,> "Pappu, PLEASE don't> wear any of my clothes to school any more!"> > > >

Little Pappu came running into the house and asked,> "Mommy, can little girls have babies?" "No," said> his mom, "of course not."> Little Pappu then ran back outside and his mom> heard him yell to his> friends, "It's okay, we can play that game again!"> > > >

Little Pappu, on a day when he was being> particularly reckless, was> playing in the backyard one morning.> Soon, some honeybees started swirling around,> annoying little Johnny.> He began stomping on them in his temper.> His father caught him trampling the honeybees, and> after a brief moment of> thought said, "That's it! No honey for you for one> month!"> Later that afternoon, Johnny pondered upon some> butterflies, and soon> started catching them and crushing them under his> feet.> His father again caught him, and after a brief> moment of thought, said, "No> butter for you for one month!" Early that evening,> Johnny's mother was> cooking and saw some cockroaches on the kitchen> floor.> She began stomping on them one by one until all the> cockroaches were dead.> Johnny's mother looked up to find Johnny and his> father standing there> watching her. To which Johnny said, "Are you going> to tell her, daddy, or> do you want me to?"> > > >

A guy's walking down the street and sees Dirty> Pappu smoking a cigarette.> He says, "Kid, you're too young to smoke."> Pappu looks up and doesn't say anything.> The guy says, "How old are you?"> Pappu says, "Six."> The guy says, "Six? When did you start smoking?"> Pappu says, "Right after the first time I got> laid."> The guy says, "Right after the first time you got> laid? When was that?"> Pappu says, "I don't remember. I was drunk."> > > >

One day a 5th grade class was taking a field trip> but the weather was extremely bad and the trip was> to be delayed and they had to stay in a hotel for> the night.> So Little Pappu was sleeping in the same room as> his teacher.> In the middle of the night the teacher woke up and> was frightened by the sight of Pappu standing right> over her.> He asked if he could sleep with her cause he> couldn't sleep.> She said okay, then Pappu asked to lay a little> closer and she said okay.> Then he asked if he could put his finger in her> belly button...and she said> "NO". "But my mommy lets me do it when I can't sleep> and it helps."> So the teacher says “okay fine, do whatever your mom> lets you do."> A few minutes later the teacher says "OH...that’s> not my bellybutton."> And Pappu says, "That’s not my finger either."> > > > > >

Pappu Rocksssss

TEACHER : What is the chemical formula for water? PAPPU : "HIJKLMNO! "!! TEACHER : What are you talking about? PAPPU : Yesterday you said it's H to O ! *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
TEACHER : PAPPU, go to the map and find North America. PAPPU : Here it is! TEACHER : Correct. Now, class, who discovered America? CLASS : PAPPU! *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
TEACHER : PAPPU, how do you spell "crocodile"? PAPPU : "K-R-O-K-O-D-A-I-L" TEACHER : No, that's wrong PAPPU : Maybe it's wrong, but you asked me how I spell it! *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
TEACHER : PAPPU, give me a sentence starting with "I". PAPPU : I is... TEACHER : No, PAPPU. Always say, "I am." PAPPU : All right... "I am the ninth letter of the alphabet." *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
TEACHER : "Can anybody give an example of "COINCIDENCE?" PAPPU : "Sir, my Mother and Father got married on the same day, same time." *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
TEACHER : "George Washington not only chopped down his father's Cherry tree, but also admitted doing it. Now do you know why his father didn't punish him?" PAPPU : "Because George still had the axe in his hand?" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- PAPPU : Daddy, have you ever been to Egypt? FATHER : No. Why do you ask that? PAPPU: Well, where did you get THIS mummy then? *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- TEACHER : What a pair of strange socks you are wearing, one is green and one is blue with red spots ! PAPPU: Yes it's really strange. I've got another pair just like that at home.
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
TEACHER : Now, PAPPU, tell me frankly do you say prayers before eating ? PAPPU: No sir, I don't have to, my mom is a good cook. *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- TEACHER : PAPPU, your composition on "My Dog" is exactly the same as your brother's. Did you copy his ? PAPPU: No, teacher, it's the same dog ! -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
TEACHER : What do you call a person who keeps on talking when people are no longer interested? PAPPU: A teacher ...
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Ways girls turn romantic guys down !!!

HE: I'm a photographer i've been looking for a face like yours! SHE: I'm a plastic surgeon .i've been looking for a face like yours!!!

HE: Hi!didn't we go on a date once? or was it twice? SHE: Must've been once.i never make the same mistake twice!!!

HE: May I have the pleasure of this dance? SHE: No,i'd like to have some pleasure too!!!

HE: How did you get to be so beautiful? SHE: I must've been given your share!!!

HE: Is it hot in here or is it just you? SHE: It's hot!!!

HE: I'd go to the ends of the world for you! SHE: Okay,but would you stay there?

HE: Will you come out with me this Saturday? SHE: Sorry! i'm having a headache this weekend!!!

HE: I think I could make you very happy SHE: Why,are you leaving?

HE: What would you say if I asked u to marry me? SHE: Nothing. I can't talk and laugh at the same time!!!

HE: Shall we go and see a film? SHE: I've already seen it!!!

HE: Do you think it was fate which brought us together? SHE: Nah,it was plain bad luck!!!

HE: You know I can't seem to get your face out of my mind. SHE: Wow really, I have a similar problem I cant seem to get you out of my face!!!

HE: When I look at your face, I can't hold my self down.. SHE: And when I look at your face I can't seem to keep my food down!

HE: You know when they made u they must have broken the mold. SHE: Yeah and when they were making you must have leaked out of your mold!!

HE: Roses are red, Violets are blue, could there be anyone as beautiful as you? SHE: Roses are red, Violets are blue, i'm sure there's no-one as ugly as you!

HE: Do you have a phone number I can reach you on? She: Sorry, telephones are against my religion!!!

HE: Haven't I seen you someplace before? SHE: Yeah, that's why I don't go there anymore.

HE: Is this seat empty? SHE: Yes, and this one will be too if you sit down.

HE: I'd like to call you. What's your number? SHE: It's in the phone book. HE: But I don't know your name. SHE: That's in the phone book too.

HE: Hey, baby, what's your sign? SHE: Do not Enter

HE: I know how to please a woman. SHE: Then please leave me alone.

HE: I want to give myself to you. SHE: Sorry, I don't accept cheap gifts.

HE: I hope you didn't hurt yourself when fell to earth from heaven. SHE: No, but it looks like you landed on your face!

Best of EHSAAN QURAISI

Ek din, main Delhi pahuncha, Station pe ek coolie se bahar jane ka rasta pooncha. Coolie ne kaha: "Bahar jaake poocho."

Maine khud hi rasta dhundh liya, Bahar jaake taxiwale se pooncha: "Bhai saab Lal Kile ka kitna loge?" Jawab mila: "Bechna nahi hai."

Taxi chod, maine bus pakad li, Conductor se pooncha: "Ji, kya mein cigarette pi sakta hoon?" Wo gurrra kar bola: "Hargiz nahi, yaha cigarette pina mana hai." Maine kaha: "Par wo janab to pi rahe hai!" Phir se gurrrraya: "Usne mujhse pooncha nahi hai."

Lal Kile pahucha, hotel gaya. Manager se kaha: "Mujhe room chahiye, satvi manzil pe." Manager ne kaha: "Rahane ke liye ya koodne ke liye?" Room pahucha, waiter se kaha: "Ek paani ka gilas milega?" Usne jawab diya: "Nahi sahab, yahan to saare kanch ke milte hain."

Hotel se nikla, dost ke ghar jaane ke liye, Raste me ek sahab se pooncha: "Janab, ye sadak kaha ko jaati hai?" Janab hans kar bole: "Peechle bees saal se dekh rahan hoon, Yahi padi hai... kahin nahin jaati."

Dost ke ghar pahucha, to mujhe dekhte hi chownk pada, Usne poocha: "Kaise aana hua?" Ab tak to mujhe bhi aadat pad gayi thi, Maine bhi jawab diya: "Train se."

Meri aaobhagat karne ke liye dost ne apni biwi se kaha: "Areeee sunti ho... mera dost pehli baar ghar aaya hai, Uuse kuch taja taja khilao." Sunte hi bhabhiji ne ghar ki sari khidkiya aur darwaje khol diye. Kaha: "Taji hawa kha lijiye."

Dost ne phir se baday pyar se biwi se kaha: "Areeee sunti ho, inhe jara apna chalis saal purana aachar to dikhana." Bhabiji ek baatli me rakha aachar le aayi. Maine bhi apnapan dikhate hue bhabiji se kaha: "Bhabhiji, aachar sirf dikhayengi, chakhayengi nahi?" Bhabiji ne taak jawab diya: "Yuhi agar sab ko chakhati To aachar chalis saal purana kaise hota?"

Thodi der baad dekha, bhabiji apne potey ko sula rah thi, Saath me lori bhi ga rahi thi: "Diploma so ja, diploma so ja." Lori soon mein hairan hua aur dost se poocha: "Yaar, ye diploma kya hai?" Dost ne jawab diya: "Mere grandson ka naam, Beti bambai gayi thi, diploma lene ke liye Aur saath mein ise le aayi, Isiliye hamne iska naam Diploma rakh diya." Phir maine pooncha: "Aajkal tumhari beti kya kar rahi hai?" Dost ne jawab diya: "Bambai gayi hai, degree lene ke liye

Tongue twisters....

Which witch wished which wicked wish?

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~

Peter Piper picked a peck of pickled peppers.
Did Peter Piper pick a peck of pickled peppers?
If Peter Piper picked a peck of pickled peppers,
where's the peck of pickled peppers Peter Piper
picked?

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
How much wood would a woodchuck chuck
if a woodchuck could chuck wood?
He would chuck, he would, as much as he could,
and chuck as much wood as a wood chuck would
if a woodchuck could chuck wood.

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
She sells sea shells by the sea shore.
The shells she sells are surely seashells.
So if she sells shells on the seashore,
I'm sure she sells seashore shells.

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~

A flea and a fly flew up in a flue.
Said the flea, "Let us fly!"
Said the fly, "Let us flee!"
So they flew through a flaw in the flue.

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~

Betty Botter had some butter,
But, she said, "this butter's bitter.
If I bake this bitter butter, it would make my batter
bitter.
But a bit of better butter that would make my batter
better.
So she bought a bit of butter,
better than her bitter butter,
And she baked it in her batter,
and the batter was not bitter.
So 'twas better Betty Botter bought a bit of better
butter.

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~

A big black bug bit a big black bear,
made the big black bear bleed blood.

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~

Lesser leather never weathered wetter weather better.

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~

A bitter biting bittern Bit a better brother bittern,
And the bitter better bittern Bit the bitter biter
back.
And the bitter bittern, bitten, By the better bitten
bittern,
Said: "I'm a bitter biter bit, alack!"

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~

Mr. See owned a saw.
And Mr. Soar owned a seesaw.
Now See's saw sawed Soar's seesaw
Before Soar saw See,
Which made Soar sore.
Had Soar seen See's saw before See sawed Soar's
seesaw,
See's saw would not have sawed Soar's seesaw.
So See's saw sawed Soar's seesaw.
But it was sad to see Soar so sore
Just because See's saw sawed Soar's seesaw!

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~

Silly Sally swiftly shooed seven silly sheep.
The seven silly sheep Silly Sally shooed
shilly-shallied south.
These sheep shouldn't sleep in a shack;
sheep should sleep in a sack.

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~

Peter bought a butter,
The butter Peter bought was bitter,
So Peter Bought A better butter,
To make the bitter butter better.

Tuesday, May 23, 2006

Mounting and formatting of Memory card / USB pen drives

To mount a usb device on Desktop use the folowing commands on terminal as:

fdisk -l
It will display all the devices attached to the desktop, probably the last one is the attached USB device for ex: /dev/sdb1

Use
mount /dev/sdb1 /mnt/usb

It will mount the device in /mnt/usb folder.

To unmount the device use
umount /mnt/usb

To format the device use the following commands:
(Using the same example device /dev/sdb1)

Unmount the device the first:
umount /mnt/usb

then use..
mkfs.ext2 /dev/sdb1
(ext2 for linux filesystem, msdos for windows-dos, ntfs for windows ntfs filesystem.. )

and finally use:
tune2fs -c 100 /dev/sdb1

Mount the device again and here you go...
the device is now ready again to b used.

Setting up of tftp Server on Linux

To have tftp service enabled on your "Technology rich Idiot Box" use the following steps:

Download the tftp package based on Linux flavor from site like:
http://rpm.pbone.net/index.php3?stat=3&search=tftp-server&srodzaj=3

It might have some dependencies for different packages like:
xinetd services
(It can again be downloaded from rpm.pbone site )

Once all the required dependent service RPMs are downloaded, install them using the command on terminal as:
rpm -ivh xinetxxx..i386.rpm
(optional use -U option to update the RPM)

and finally:
rpm -ivh tftp-serverxxx.i386.rpm

Reboot the PC/Lappy for tftp services to be up..

For more info check the following thread:
http://forums.fedoraforum.org/archive/index.php/t-127266.html

Happy TFTPing...

Linux: Setting up of Minicom

Use Terminal to make a setup of minicom.

Type commands as:
minicom -s

A config menu will appear.
Select : Serial Port Setup option
Update the name based on device like:
/dev/ttyUSB0 (In case of Serial to USB connectors) or
/dev/ttyS0 (In case of serial cables)

Press ENTER key.

Save the setup.
It will create a default config file(with name as "dfl") which will be used by the minicom while starting up.

We can have different config files depending on devices being in use... To use a specific config file use the following command:
minicom xyz

Enjoy!!!

Important Links for Linux

To get Linux Kernel Archives, Use following link:
http://www.kernel.org/

To get Resource Packages Managers (RPM) use the following link:
http://rpm.pbone.net/
For more info on RPMs:
http://en.wikipedia.org/wiki/RPM_Package_Manager

How to write kernel image on NAND???

To write the kernel image on NAND follow the steps below.

The parameters being used here are:
280000: This probably represents the baud-rate.
200000: This represents the size of the kernel image.
After calculating all these parameters follow the commands listed below.

Once the board starts and uboot is executed, the command prompt will appear, execute the commands in the following order:

tftp 0x80000000 uImage_touch_IPv6
nand unlock
nand erase 280000 200000
nand ecc sw
nand write.i 0x80000000 280000 200000
nand read.i 0x80000000 280000 200000; bootm 0x80000000

And here you go...
The kernel is now placed in the NAND Flash and next time when you will start the board the kernel will be loaded automatically...
Enjoy!!!

Automating the boot sequence of kernel for OMAP board

To automate the settings and booting sequence of kernel for OMAP board, We have done the following steps:

Store the Kernel image in the NAND flash of the board...
File System is placed on the memory card so all the required folders are kept in the mmc.
Create a script file xyz.sh which will do the settings and launch of applications.
Add the entry of this script file in the file placed at following location:
In MMc Cards file system, check for /etc folder.
In /etc folder search for "init.d" folder, in this folder there will be a file named "rcS".
Open the "rcS" file
Search for "System Initialization Complete"
After this statement user application can be executed..
Add following statements:
echo -n "Starting User application"
sh /app/scripts/xyz.sh

This script will now be executed at the start-up and will do the settings and launch the application..

Happy Launching!!!

Sunday, April 23, 2006

FAQ's of C.. Check out your C Knowledge... Part IX

97.
Why the output of sizeof ( 'a' ) is 2 and not 1 ?Ans: Character constants in C are of type int, hence sizeof ( 'a' ) is equivalent to sizeof ( int ), i.e. 2. Hence the output comes out to be 2 bytes. -------------------------------------------------------------------------------------------------
98.
Can we use scanf( ) function to scan a multiple words string through keyboard?Ans: Yes. Although we usually use scanf( ) function to receive a single word string and gets( ) to receive a multi-word string from keyboard we can also use scanf( ) function for scanning a multi-word string from keyboard. Following program shows how to achieve this.main( ){char buff[15] ;scanf ( "%[^\n]s", buff ) ;puts ( buff ) ;}In the scanf( ) function we can specify the delimiter in brackets after the ^ character. We have specified '\n' as the delimiter. Hence scanf( ) terminates only when the user hits Enter key.-------------------------------------------------------------------------------------------------99. How to set the system date through a C program ?Ans: We can set the system date using the setdate( ) function as shown in the following program. The function assigns the current time to a structure date.#include "stdio.h"#include "dos.h"main( ){struct date new_date ;new_date.da_mon = 10 ;new_date.da_day = 14 ;new_date.da_year = 1993 ;setdate ( &new_date ) ;}-------------------------------------------------------------------------------------------------
100.
How can I write a general-purpose swap without using templates?
Ans: Given below is the program which uses the stringizing preprocessor directive ## for building a general purpose swap macro which can swap two integers, two floats, two chars, etc.#define swap( a, b, t ) ( g ## t = ( a ), ( a ) = ( b ), ( b ) = g ## t )int gint;char gchar;float gfloat ;main( ){int a = 10, b = 20 ;char ch1 = 'a' , ch2 = 'b' ;float f1 = 1.12, f2 = 3.14 ;swap ( a, b, int ) ;printf ( "\na = %d b = %d", a, b ) ;swap ( ch1, ch2, char ) ;printf ( "\nch1 = %c ch2 = %c", ch1, ch2 ) ;swap ( f1, f2, float ) ;printf ( "\nf1 = %4.2f f2 = %4.2f", f1, f2 ) ;}swap ( a, b, int ) would expand to,( gint = ( a ), ( a ) = ( b ), ( b ) = gint )-------------------------------------------------------------------------------------------------101. What is a heap ?Ans : Heap is a chunk of memory. When in a program memory is allocated dynamically, the C run-time library gets the memory from a collection of unused memory called the heap. The heap resides in a program's data segment. Therefore, the amount of heap space available to the program is fixed, and can vary from one program to another.

102.
How to obtain a path of the given file?Ans: The function searchpath( ) searches for the specified file in the subdirectories of the current path. Following program shows how to make use of the searchpath( ) function.
#include "dir.h"void main ( int argc, char *argv[] ){char *path ;if ( path = searchpath ( argv[ 1 ] ) )printf ( "Pathname : %s\n", path ) ;elseprintf ( "File not found\n" ) ;}-------------------------------------------------------------------------------------------------103.
Can we get the process identification number of the current program?
Ans: Yes! The macro getpid( ) gives us the process identification number of the program currently running. The process id. uniquely identifies a program. Under DOS, the getpid( ) returns the Program Segment Prefix as the process id. Following program illustrates the use of this macro. #include #include
void main( ){ printf ( "The process identification number of this program is %X\n", getpid( ) ) ; }
-------------------------------------------------------------------------------------------------

104.
How do I write a function that takes variable number of arguments?
Ans: The following program demonstrates this.
#include #include
void main( ){ int i = 10 ;float f = 2.5 ;char *str = "Hello!" ;vfpf ( "%d %f %s\n", i, f, str ) ;vfpf ( "%s %s", str, "Hi!" ) ; }
void vfpf ( char *fmt, ... ){ va_list argptr ;va_start ( argptr, fmt ) ;vfprintf ( stdout, fmt, argptr ) ;va_end ( argptr ) ; }
Here, the function vfpf( ) has called vfprintf( ) that take variable argument lists. va_list is an array that holds information required for the macros va_start and va_end. The macros va_start and va_end provide a portable way to access the variable argument lists. va_start would set up a pointer argptr to point to the first of the variable arguments being passed to the function. The macro va_end helps the called function to perform a normal return.-------------------------------------------------------------------------------------------------105. Can we change the system date to some other date?
Ans: Yes, We can! The function stime( ) sets the system date to the specified date. It also sets the system time. The time and date is measured in seconds from the 00:00:00 GMT, January 1, 1970. The following program shows how to use this function. #include #include
void main( ){ time_t tm ;int d ;
tm = time ( NULL ) ;
printf ( "The System Date : %s", ctime ( &tm ) ) ;printf ( "\nHow many days ahead you want to set the date : " ) ;scanf ( "%d", &d ) ;
tm += ( 24L * d ) * 60L * 60L ;
stime ( &tm ) ;printf ( "\nNow the new date is : %s", ctime ( &tm ) ) ; } In this program we have used function ctime( ) in addition to function stime( ). The ctime( ) function converts time value to a 26-character long string that contains date and time.-------------------------------------------------------------------------------------------------106.
How to use function strdup( ) in a program?
Ans : The string function strdup( ) copies the given string to a new location. The function uses malloc( ) function to allocate space required for the duplicated string. It takes one argument a pointer to the string to be duplicated. The total number of characters present in the given string plus one bytes get allocated for the new string. As this function uses malloc( ) to allocate memory, it is the programmer’s responsibility to deallocate the memory using free( ). #include #include #include
void main( ){ char *str1, *str2 = "double";
str1 = strdup ( str2 ) ;printf ( "%s\n", str1 ) ;free ( str1 ) ; }-------------------------------------------------------------------------------------------------107.
On including a file twice I get errors reporting redefinition of function. How can I avoid duplicate inclusion?
Ans: Redefinition errors can be avoided by using the following macro definition. Include this definition in the header file.#if !defined filename_h#define filename_h/* function definitions */#endifReplace filename_h with the actual header file name. For example, if name of file to be included is 'goto.h' then replace filename_h with 'goto_h'.-------------------------------------------------------------------------------------------------108. How to write a swap( ) function which swaps the values of the variables using bitwise operators.
Ans: Here is the swap( ) function.swap ( int *x, int *y ){*x ^= *y ;*y ^= *x ;*x ^= *y ;}The swap( ) function uses the bitwise XOR operator and does not require any temporary variable for swapping.

FAQ's of C.. Check out your C Knowledge... Part VIII

85.
Unique combinations for a given numberHow do I write a program which can generate all possible combinations of numbers from 1 to one less than the given number ?main( ){long steps, fval, bstp, cnt1 ;int num, unit, box[2][13], cnt2, cnt3, cnt4 ;printf ( "Enter Number " ) ;scanf ( "%d", &num ) ;num = num <> 12 ? 12 : num ;for ( steps = 1, cnt1 = 2 ; cnt1 <= num ; steps *= cnt1++ ) ;for ( cnt1 = 1 ; cnt1 <= steps ; cnt1++ ){for ( cnt2 = 1 ; cnt2 <= num ; cnt2++ )box[0][cnt2] = cnt2 ;for ( fval = steps, bstp = cnt1, cnt2 = 1 ; cnt2 <= num ; cnt2++ ){if ( bstp == 0 ){cnt4=num ;while ( box[0][cnt4] == 0 )cnt4-- ;}else{fval /= num - cnt2 + 1 ;unit = ( bstp + fval - 1 ) / fval ;bstp %= fval ;for ( cnt4 = 0, cnt3 = 1 ; cnt3 <= unit ; cnt3++ )while ( box[0][++cnt4] == 0 ) ;}box[1][cnt2] = box[0][cnt4] ;box[0][cnt4] = 0 ;}printf ( "\nSeq.No.%ld:", cnt1 ) ;for ( cnt2 = 1 ; cnt2 <= num ; cnt2++ )printf ( " %d", box[1][cnt2] ) ;}}This program computes the total number of steps. But instead of entering into the loop of the first and last combination to be generated it uses a loop of 1 to number of combinations. For example, in case of input being 5 the number of possible combinations would be factorial 5, i.e. 120. The program suffers from the limitation that it cannot generate combinations for input beyond 12 since a long int cannot handle the resulting combinations. Data StructuresHashing...Hashing or hash addressing is a searching technique. Usually, search of an element is carried out via a sequence of comparisons. Hashing differs from this as it is independent of the number of elements n in the collection of data. Here, the address or location of an element is obtained by computing some arithmetic function. Hashing is usually used in file management. The general idea is of using the key to determine the address of a record. For this, a function fun( ) is applied to each key, called the hash function. Some of the popular hash functions are: 'Division' method, 'Midsquare' method, and 'Folding' method. Two records cannot occupy the same position. Such a situation is called a hash collision or a hash clash. There are two basic methods of dealing with a hash clash. The first technique, called rehashing, involves using secondary hash function on the hash key of the item. The rehash function is applied successively until an empty position is found where the item can be inserted. If the hash position of the item is found to be occupied during a search, the rehash function is again used to locate the item. The second technique, called chaining, builds a linked list of all items whose keys hash to the same values. During search, this short linked list is traversed sequentially for the desired key. This technique involves adding an extra link field to each table position.------------------------------------------------------------------------------------------------- 86. The following program demonstrates how to get input from the user in graphics mode, echoed in the current colors and font size and font style.#define ON 1#define OFF 0#include main( ){char nameString[80], ageString[80] ;int age, gd = DETECT, gm ;initgraph ( &gd, &gm, "c:\\tc\\bgi" ) ;setbkcolor ( BLUE ) ;setcolor ( YELLOW ) ;settextstyle ( GOTHIC_FONT, HORIZ_DIR, 0 ) ;moveto ( 0, 0 ) ;outtext ( "Enter your name: " ) ;getGrString ( nameString ) ; moveto ( 0, gety( ) + textheight ( "A" ) ) ;outtext ( "Name: " ) ;outtext ( nameString ) ;moveto ( 0, gety( ) + textheight ( "A" ) ) ;outtext ( "Press key to exit! " ) ;getch( ) ;closegraph( ) ;restorecrtmode( ) ;}getGrString ( char *inputString ){int stringIndex = 0, oldColor ;char ch, outString[2] ;/* xVal will store the screen position for each char */int xVal[255] ;outString[1] = 0 ;xVal[0] = getx( ) ;do{cursor ( ON ) ;ch = getch( ) ;cursor ( OFF ) ;if ( ch == 0 ) /* avoid dealing with all special keys */getch( ) ;else{if ( ch == 8 ) /* backspace */{oldColor = getcolor( ) ;--stringIndex ;if ( stringIndex < stringindex =" 0" oldcolor =" getcolor(" curx =" getx(">#include #include main( ){int a[] = { 2, -34, 56, 78, 112, 33, -7, 11, 45, 29, 6 } ;int s ;time_t t1, t2 ; // time_t defines the value used for time functions = sizeof ( a ) / 2 ;t1 = time ( NULL ) ;sel_sort ( a, s ) ; // sort array by selection sortbub_sort ( a, s ) ; // sort array by bubble sort methodt2 = time ( NULL ) ;printf ( "\nThe difference between two function calls is %f", difftime ( t2, t1 ) ) ;}In the above program we have called difftime( ) function that returns the time elapsed from t1 to t2.-------------------------------------------------------------------------------------------------88.
Generalmain( ){char *s ;s = fun ( 128, 2 ) ;printf ( "\n%s", s ) ;}fun ( unsigned int num, int base ){static char buff[33] ;char *ptr ;ptr = &buff [ sizeof ( buff ) - 1 ] ;*ptr = '\0' ;do{*--ptr = "0123456789abcdef"[ num % base ] ;num /= base ;} while ( num != 0 ) ;return ptr ;}The above program would convert the number 128 to the base 2. You can convert a number to a hexadecimal or octal form by passing the number and the base, to the function fun( ).
Data StructuresWhat is a priority queue?Ans: As we know in a stack, the latest element is deleted and in a queue the oldest element is deleted. It may be required to delete an element with the highest priority in the given set of values and not only the oldest or the newest one. A data structure that supports efficient insertions of a new element and deletions of elements with the highest priority is known as priority queue. There are two types of priority queues: an ascending priority queue is a collection of items into which items can be inserted arbitrarily and from which only the smallest item can be removed. A descending order priority queue is similar but allows only the largest item to be deleted.-------------------------------------------------------------------------------------------------89.
What is the difference between const char *p, char const *p, and char* const p ?
'const char *p' and 'char const *p' are the same, i.e. p points to a constant character. On the other hand, 'char* const p' means p is a constant pointer pointing to a character which means we cannot change the pointer p but we can change the character which p is pointing to.-------------------------------------------------------------------------------------------------90.
What's the difference between a null pointer, a NULL macro, the ASCII NUL character and a null string?Ans: A null pointer is a pointer which doesn't point anywhere. A NULL macro is used to represent the null pointer in source code. It has a value 0 associated with it. The ASCII NUL character has all its bits as 0 but doesn't have any relationship with the null pointer. The null string is just another name for an empty string "".System Utility
Sparse Matrix...A sparse matrix is one where most of its elements are zero. There is no precise definition as to know whether a matrix is sparsed or not, but it is a concept which we all can recognize intuitively. The natural method of representing matrices in memory as two-dimensional arrays may not be suitable for sparse matrices. That is one may save space by storing only those entries which may be nonzero. If this is done, then the matrix may be thought of as an ordered list of non-zero elements only. Information about a non-zero element has three parts:an integer representing its row, an integer representing its column and the data associated with this element.
That is, each element of a matrix is uniquely characterized by its row and column position, say i, j. We might store that matrix as a list of 3-tuples of the form (i, j, data), as shown below,
Although the non-zero elements may be stored in the array in any order, keeping them ordered in some fashion may be advantageous for further processing. Note that above array is arranged in increasing order of the row number of non-zero elements. Moreover, for elements in the same row number, the array is arranged in order of increasing column number.-------------------------------------------------------------------------------------------------91.
Pointers
What does the error "Null Pointer Assignment" mean and what causes this error?
Ans: The Null Pointer Assignment error is generated only in small and medium memory models. This error occurs in programs which attempt to change the bottom of the data segment. In Borland's C or C++ compilers, Borland places four zero bytes at the bottom of the data segment, followed by the Borland copyright notice "Borland C++ - Copyright 1991 Borland Intl.". In the small and medium memory models, a null pointer points to DS:0000. Thus assigning a value to the memory referenced by this pointer will overwrite the first zero byte in the data segment. At program termination, the four zeros and the copyright banner are checked. If either has been modified, then the Null Pointer Assignment error is generated. Note that the pointer may not truly be null, but may be a wild pointer that references these key areas in the data segment.
Data Structures
How to build an expression trees ?
Ans: An expression tree is a binary tree which is built from simple operands and operators of an (arithmetic or logical ) expression by placing simple operands as the leaves of a binary tree and the operators as the interior nodes. If an operator is binary , then it has two nonempty subtrees, that are its left and right operands (either simple operands or sub expressions). If an operator is unary, then only one of its subtrees is nonempty, the one on the left or right according as the operator is written on the right or left of its operand. We traditionally write some unary operators to the left of their operands, such as "-" ( unary negation) or the standard functions like log( ), sin( ) etc. Others are written on the right, such as the factorial function ()!. If the operator is written on the left, then in the expression tree we take its left subtree as empty. If it appears on the right, then its right subtree will be empty. An example of an expression tree is shown below for the expression ( -a <>main( ){printf ( "%f", fmod ( 5.15, 3.0 ) ) ;}The above code snippet would give the output as 2.150000.-------------------------------------------------------------------------------------------------93.
How to extract the integer part and a fractional part of a floating point number?Ans: C function modf( ) can be used to get the integer and fractional part of a floating point.#include "math.h"main( ){double val, i, f ;val = 5.15 ;f = modf ( val, &i ) ;printf ( "\nFor the value %f integer part = %f and fractional part = %f", val, i, f ) ;}The output of the above program will be:For the value 5.150000 integer part = 5.000000 and fractional part = 0.150000
94.
How do I define a pointer to a function which returns a char pointer?Ans:char * ( *p )( ) ; or typedef char * ( * ptrtofun )( ) ; ptrtofun p ;Here is a sample program which uses this definition. main( ) { typedef char * ( * ptrtofun ) ( ) ; char * fun( ) ; ptrtofun fptr ; char *cptr ; fptr = fun ; cptr = (*fptr) ( ) ; printf ( "\nReturned string is \"%s\"", cptr ) ; } char * fun( ) { static char s[ ] = "Hello!" ; printf ( "\n%s", s ) ; return s ; }-------------------------------------------------------------------------------------------------95. What's wrong with the following declaration: char* ptr1, ptr2 ; get errors when I try to use ptr2 as a pointer.
Ans: char * applies only to ptr1 and not to ptr2. Hence ptr1 is getting declared as a char pointer, whereas, ptr2 is being declared merely as a char. This can be rectified in two ways : char *ptr1, *ptr2 ; typedef char* CHARPTR ; CHARPTR ptr1, ptr2 ;-------------------------------------------------------------------------------------------------96.
How to use scanf( ) to read the date in the form of dd-mm-yy? Ans: To read the date in the form of dd-mm-yy one possible way is, int dd, mm, yy ; char ch ; /* for char '-' */ printf ( "\nEnter the date in the form of dd-mm-yy : " ) ; scanf( "%d%c%d%c%d", &dd, &ch, &mm, &ch, &yy ) ; Another way is to use suppression character * is as follows: int dd, mm, yy ; scanf( "%d%*c%d%*c%d", &dd, &mm, &yy ) ; The suppression character '*' suppresses the input read from the standard input buffer for the assigned control character.-------------------------------------------------------------------------------------------------

FAQ's of C.. Check out your C Knowledge... Part VII

73.
What would be the output of following program?
struct syntax{int i ;float g ;char c ;}main( ){printf ( "I won't give you any error" ) ;}
Ans: The above program would get compiled successfully and on execution it would print the message given in printf(). What strikes in the above code snippet is the structure syntax which is declared but not terminated with the statement terminator, the semicolon. The compiler would not give any error message for it, as it assumes that main( ) function have a return type of struct syntax and hence would successfully compile and execute the program.-------------------------------------------------------------------------------------------------74.
How to get the memory size ?Ans: Consider the following program
#include #include main( ){int memsize;memsize = biosmemory( ) ; printf ( "RAM size = %dK\n",memsize ) ;return 0 ;}The function biosmemory uses BIOS interrupt 0x12 to return the size of memory.-------------------------------------------------------------------------------------------------75.
Float FormatHow does C compiler stores float values ?Ans: In C, the float values are stored in a mantissa and exponent form. While writing a number we specify the exponent part in the form of base 10. But, in case of C compiler, the exponent for floats is stored in the form of base 2. Obviously, because, computer stores the numbers in binary form. The C compiler follows an IEEE standard to store a float. The IEEE format expresses a floating-point number in a binary form known as `normalized' form. Normalization involves adjusting the exponent so that the "binary point" (the binary analog of the decimal point) in the mantissa always lies to the right of most significant nonzero digit. In binary representation, this means that the most significant digit of the mantissa is always a 1. This property of the normalized representation is exploited by the IEEE format when storing the mantissa. Let us consider an example of generating the normalized form of a floating point number. Suppose we want to represent the decimal number 5.375. Its binary equivalent can be obtained as shown below:2 5 .375 x 2 = 0.750 0 ------ .750 x 2 = 1.500 1 2 2 1 .500 x 2 = 1.000 1 ------2 1 0------ 0 1 Writing remainders in reverse writing whole parts in the same order we get 101 order in which they are obtained we get 011 thus the binary equivalent of 5.375 would be 101.011. The normalized form of this binary number is obtained by adjusting the exponent until the decimal point is to the right of most significant 1. In this case the result is 1.01011 x 22. The IEEE format for floating point storage uses a sign bit, a mantissa and an exponent for representing the power of 2. The sign bit denotes the sign of the number: a 0 represents a positive value and a 1 denotes a negative value. The mantissa is represented in binary. Converting the floating-point number to its normalized form results in a mantissa whose most significant digit is always 1. The IEEE format takes advantage of this by not storing this bit at all. The exponent is an integer stored in unsigned binary format after adding a positive integer bias. This ensures that the stored exponent is always positive. The value of the bias is 127 for floats and 1023 for doubles. Thus, 1.01011 x 22 is represented as shown below:--- --------------- ---------------------------------------------- 0 100 0000 1 010 1100 0000 0000 0000 0000 --- ---------------- --------------------------------------------- sign bit exponent- mantissa stored in normalized form obtained after adding a bias 127 to exponent 2 Data StructuresWhich is the best sorting method?Ans: There is no sorting method that is universally superior to all others. The programmer must carefully examine the problem and the desired results before deciding the particular sorting method. Some of the sorting methods are given below:Bubble sort : When a file containing records is to be sorted then Bubble sort is the best sorting method when sorting by address is used.
Bsort : It can be recommended if the input to the file is known to be nearly sorted.
Meansort : It can be recommended only for input known to be very nearly sorted.
Quick Sort : In the virtual memory environment, where pages of data are constantly being swapped back and forth between external and internal storage. In practical situations, quick sort is often the fastest available because of its low overhead and its average behavior.
Heap sort : Generally used for sorting of complete binary tree. Simple insertion sort and straight selection sort : Both are more efficient than bubble sort. Selection sort is recommended for small files when records are large and for reverse situation insertion sort is recommended. The heap sort and quick sort are both more efficient than insertion or selection for large number of data.
Shell sort : It is recommended for moderately sized files of several hundred elements.
Radix sort : It is reasonably efficient if the number of digits in the keys is not too large.
76. Calculating Wasted Bytes On Disk
When a file gets stored on the disk, at a time DOS allocates one cluster for it. A cluster is nothing but a group of sectors. However, since all file sizes cannot be expected to be a multiple of 512 bytes, when a file gets stored often part of the cluster remains unoccupied. This space goes waste unless the file size grows to occupy these wasted bytes. The following program finds out how much space is wasted for all files in all the directories of the current drive.
#include #include #include #include #include unsigned bytes_per_cluster ;unsigned long wasted_bytes ;unsigned long num_files = 0 ;main( ){ int ptr = 0, flag = 0, first = 0 ;struct ffblk f[50] ;struct dfree free ;/* get cluster information and calculate bytes per cluster */getdfree ( 0, &free ) ;bytes_per_cluster = free.df_bsec * free.df_sclus ;chdir ( "\\" ) ;/* check out files in root directory first */cal_waste( ) ;/* loop until all directories scanned */while ( ptr != -1 ){ /* should I do a findfirst or a findnext? */if ( first == 0 ) flag = findfirst ( "*.*", &f[ptr], FA_DIREC ) ; else flag = findnext ( &f[ptr] ) ; while ( flag == 0 ){ /* make sure its a directory and skip over . & .. entries */if ( f[ptr].ff_attrib == FA_DIREC && f[ptr].ff_name[0] != '.' ){ flag = chdir ( f[ptr].ff_name ) ; /* try changing directories */if ( flag == 0 ) /* did change dir work? */{ cal_waste( ) ;first = 0 ; /* set for findfirst on next pass */break ; } } flag = findnext ( &f[ptr] ) ; /* search for more dirs */ } if ( flag != 0 ptr == 49 ) /* didn't find any more dirs */{ ptr-- ;chdir ( ".." ) ; /* go back one level */first = 1 ; /* set to findnext on next pass */ }else ptr++ ; } printf ( "There are %lu bytes wasted in %lu files.\n", wasted_bytes, num_files ) ; }cal_waste( ){ int flag = 0 ;long full_cluster ;struct ffblk ff ;/* look for all file types */flag = findfirst ( "*.*", &ff, FA_RDONLY FA_HIDDEN FA_SYSTEM FA_ARCH ) ;while ( flag == 0 ){ num_files++ ;full_cluster = ff.ff_fsize / bytes_per_cluster * bytes_per_cluster ;wasted_bytes += bytes_per_cluster - ( ff.ff_fsize - full_cluster ) ;flag = findnext ( &ff ) ; } }
Data Structures
Polish Notation
The method of writing all operators either before their operation, or after them, is called Polish notation, in honor of its discoverer, the Polish mathematician Jan Lukasiewicz. When the operators are written before their operands, it is called the prefix form. When the operators come after their operands. It is called the postfix form, or, sometimes reverse Polish form or suffix form. In this context, it is customary to use the coined phrase infix form to denote the usual custom of writing binary operators between their operands. For example, the expression A + B becomes +AB in prefix form and AB+ in postfix form. In the expression A + B x C, the multiplication is done first, so we convert it first, obtaining first A + ( BCx ) and then ABCx+ in postfix form. The prefix form of this expression is +A x BC. The prefix and postfix forms are not related by taking mirror images or other such simple transformation. Also all parentheses have been omitted in the Polish forms. -------------------------------------------------------------------------------------------------77. The Longjmp And Setjmp
The C programming language does not let you nest functions. You cannot write a function definition inside another function definition, as in:
int fun1( ) { int fun2() /* such nesting of functions is not allowed */ { ..... } } Because of this restriction it is not possible to hide function names inside a hierarchy. As a result all the functions that you declare within a program are visible to each other. This of course is not a major drawback since one can limit visibility by grouping functions within separate C source files that belong to different logical units of the program. C does, however, suffer in another way because of this design decision. It provides no easy way to transfer control out of a function except by returning to the expression that called the function. For the vast majority of function calls, that is a desirable limitation. You want the discipline of nested function calls and returns to help you understand flow of control through a program. Nevertheless, on some occasions that discipline is too restrictive. The program is sometimes easier to write, and to understand, if you can jump out of one or more function invocations at a single stroke. You want to bypass the normal function returns and transfer control to somewhere in an earlier function invocation.
For example, you may want to return to execute some code for error recovery no matter where an error is detected in your application. The setjmp and the longjmp functions provide the tools to accomplish this. The setjmp function saves the "state" or the "context" of the process and the longjmp uses the saved context to revert to a previous point in the program. What is the context of the process? In general, the context of a process refers to information that enables you to reconstruct exactly the way the process is at a particular point in its flow of execution. In C program the relevant information includes quantities such as values of SP, SS, FLAGS, CS, IP, BP, DI, ES, SI and DS registers.
To save this information Turbo C uses the following structure, which is defined, in the header file 'setjmp.h'. typedef struct { unsigned j_sp ;unsigned j_ss ;unsigned j_flag ;unsigned j_cs ;unsigned j_ip ;unsigned j_bp ;unsigned j_di ;unsigned j_es ;unsigned j_si ;unsigned j_ds ; } jmp_buf[1] ; This is a system-dependent data type because different systems might require different amounts of information to capture the context of a process. In Turbo C, jmp_buf is simply an array of ten 2-byte integers. To understand the mechanics of setjmp and longjmp, look at the following code fragment. #include "setjmp.h"jmp_buf buf ;main( ){ if ( setjmp ( buf ) == 0 ) process( ) ; else handle_error( ) ; /* executed when longjmp is called */ }process( ){ int flag = 0 ;/* some processing is done here *//* if an error occurs during processing flag is set up */ if ( flag ) longjmp ( buf, 1 ) ; }
Upon entry to setjmp the stack contains the address of the buffer buf and the address of the if statement in the main function, to which setjmp will return. The setjmp function copies this return address as well as the current values of registers, SP, SS, FLAGS, BP, DI, ES, SI and DS, into the buffer buf. Then setjmp returns with a zero. In this case, the if statement is satisfied and the process( ) function is called. If something goes wrong in process( ) (indicated by the flag variable), we call longjmp with two arguments: the first is the buffer that contains the context to which we will return. When the stack reverts back to this saved state, and the return statement in longjmp is executed, it will be as if we were returning from the call to setjmp, which originally saved the buffer buf. The second argument to longjmp specifies the return value to be used during this return. It should be other than zero so that in the if statement we can tell whether the return is induced by a longjmp.
The setjmp/longjmp combination enables you to jump unconditionally from one C function to another without using the conventional return statements. Essentially, setjmp marks the destination of the jump and longjmp is a non-local goto that executes the jump. Data Structures
Comparison Trees...
The comparison trees also called decision tree or search tree of an algorithm, is obtained by tracing through the actions of the algorithm, representing each comparison of keys by a vertex of the tree (which we draw as a circle). Inside the circle we put the index of the key against which we are comparing the target key. Branches (lines) drawn down from the circle represent the possible outcomes of the comparison and are labeled accordingly. When the algorithm terminates, we put either F (for failure) or the location where the target is found at the end of the appropriate branch, which we call a leaf, and draw as a square. Leaves are also sometimes called end vertices or external vertices of the tree. The remaining vertices are called the internal vertices of the tree. The comparison tree for sequential search is especially simple.-------------------------------------------------------------------------------------------------78.
Suppose we have a floating-point number with higher precision say 12.126487687 and we wish it to be printed with only precision up to two decimal places. How can I do this?
Ans. This can achieved through the use of suppression char '*' in the format string of printf( ) which is shown in the following program. main( ){int p = 2 ;float n = 12.126487687 ;printf ( "%.*f",p, n ) ;}-------------------------------------------------------------------------------------------------79. Spawning
All programs that we execute from DOS prompt can be thought of as children of COMMAND.COM. Thus, the program that we execute is a child process, whereas COMMAND.COM running in memory is its parent. The process of a parent process giving birth to a child process is known as 'spawning'. If the spawned program so desires, it may in turn spawn children of its own, which then execute and return control to their parent. Who is the parent of COMMAND.COM? COMMAND.COM itself. We can trace the ancestors of our program using the field Parent Process ID (PID) present at offset 0x16 in the Program Segment Prefix (PSP). To trace this ancestry our program should first locate its PSP, extract the parent process ID from it and then use this to find PSP of the parent. This process can be repeated till we reach COMMAND.COM (process ID of COMMAND.COM is its own PSP), the father of all processes. Here is a program which achieves this...
/* SPAWN.C */#include "dos.h"
unsigned oldpsp, newpsp, far *eb_seg, i ;char far *eb_ptr ;
main( ){ oldpsp = _psp ;
while ( 1 ){ printf ( "\n" ) ;printname ( oldpsp ) ;printf ( " spawned by " ) ;
newpsp = * ( ( unsigned far * ) MK_FP ( oldpsp, 0x16 ) ) ;
if ( * ( ( unsigned * ) MK_FP ( newpsp, 0x16 ) ) == newpsp ) break ; else oldpsp = newpsp ;
printname ( newpsp ) ; }
printf ( "%-20s (%04X)", "COMMAND.COM", newpsp ) ; }
printname ( unsigned lpsp ){ char drive[5], dir[68], name[13], ext[5] ;
eb_seg = ( unsigned far * ) MK_FP ( lpsp, 0x2C ) ;eb_ptr = MK_FP ( *eb_seg, 0 ) ;
i = 0 ;while ( 1 ){ if ( eb_ptr[i] == 0 ){ if ( eb_ptr[i + 1] == 0 && eb_ptr[i + 2] == 1 ){ i += 4 ;break ; } }i++ ; }
fnsplit ( eb_ptr + i, drive, dir, name, ext ) ;strcat ( name, ext ) ;printf ( "%-20s (%04X)", name, oldpsp ) ; }
On running the program from within TC the output obtained is shown below. SPWAN.EXE (58A9) spawned by TC.EXE (0672) TC.EXE (0672) spawned by COMMAND.COM (05B8). The program simply copies its own process ID in the variable oldpsp and then uses it to extract its own filename from its environment block. This is done by the function printname( ). The value in oldpsp is then used to retrieve the parent's PID in newpsp. From there the program loops reporting the values of oldpsp, newpsp and the corresponding file names until the program reaches COMMAND.COM.
The printname( ) function first locates the environment block of the program and then extracts the file name from the environment block. The fnsplit( ) function has been used to eliminate the path present prior to the file name. Do not run the program from command line since it would give you only one level of ancestry.
Data Structures
Choosing the data structures to be used for information retrieval. For problems of information retrieval, consider the size, number, and location of the records along with the type and structure of the keys while choosing the data structures to be used. For small records, high-speed internal memory will be used, and binary search trees will likely prove adequate. For information retrieval from disk files, methods employing multiway branching, such as trees, B-trees , and hash tables, will usually be superior. Tries are particularly suited to applications where the keys are structured as a sequence of symbols and where the set of keys is relatively dense in the set of all possible keys. For other applications, methods that treat the key as a single unit will often prove superior. B-trees, together with various generalization and extensions, can be usefully applied to many problems concerned with external information retrieval.
80.
Variably Dimensioned Arrays
While dealing with Scientific or Engineering problems one is often required to make use of multi-dimensioned array. However, when it comes to passing multidimensional arrays to a function C is found wanting. This is because the C compiler wants to know the size of all but the first dimension of any array passed to a function. For instance, we can define a function compute ( int n, float x[] ), but not compute ( int n, x[][]).
Thus, C can deal with variably dimensioned 1-D arrays, but when an array has more than one dimension, the C compiler has to know the size of the last dimensions expressed as a constant. This problem has long been recognized, and some of the solutions that are often used are:
Declare the arrays in the functions to be big enough to tackle all possible situations. This can lead to a wastage of lot of precious memory in most cases. Another solution is to construct multiple-dimension array as an array of pointers. For example, a matrix (2-D array) of floats can be declared as a 1-D array of float pointers, with each element pointing to an array of floats. The problem with this method is that the calling function has to define all arrays in this fashion. This means that any other computations done on the arrays must take this special structure into account.
Another easy solution, though seldom used, exists. This is based on the following method:
Pass the array to the function as though it is a pointer to an array of floats (or the appropriate data type), no matter how many dimensions the array actually has, along with the dimensions of the array. Reference individual array elements as offsets from this pointer. Write your algorithm so that array elements are accessed in storage order. The following program for multiplying two matrices illustrates this procedure. # define M 3# define N 2# define P 4
float a[M][N], b[N][P], c[M][P] ;void mulmat ( int, int, int, float*, float*, float* ) ;
main( ){int i, j ;for ( i = 0 ; i < j =" 0" i =" 0" j =" 0" i =" 0" j =" 0" i =" 0" i =" 0" ptrtob =" b" k =" 0" ptrtoc =" c" j =" 0" i =" 1" j =" 1" k =" 1" j =" 1">#include
#define MAX 100
main( ){ char arr[NUMSLOTS( MAX )] ;int i, j ;
memset ( arr, 0, NUMSLOTS( MAX ) ) ;for ( i = 2 ; i < j =" i">typedef int element ;void initialize_stack ( struct node ** ) ;void push ( struct node **, element ) ;element pop ( struct node * ) ;int isempty ( struct node * ) ;struct node{element data ;struct node *next ;} ;void main( ){struct node *top ;element num ;initialize_stack ( &top ) ;push ( &top, 10 ) ;push ( &top, 20 ) ;push ( &top, 30 ) ;if ( isempty ( top ) )printf ( "\nStack is empty" ) ;else{num = pop ( top ) ;printf ( "\n Popped %d", num ) ;}}void initialize_stack ( struct node **p ){*p = NULL ;}void push ( struct node **p, element n ){struct node *r ;r = ( struct node *) malloc ( sizeof ( struct node ) ) ;r -> data = n ;if ( *p == NULL )r -> next = NULL ;elser -> next = *p ;*p = r ;}element pop ( struct node *p ){element n ;struct node *r ;n = p -> data ;r = p ;p = p -> next ;free ( r ) ;return ( n ) ;}int isempty ( struct node *p ){if ( p == NULL )return ( -1 ) ;elsereturn ( 0 ) ;}Notice how the specific implementation of the data structure is strewn throughout main( ). main( ) must see the definition of the structure node to use the push( ), pop( ), and other stack functions. Thus the implementation is not hidden, but is mixed with the abstract operations.Data Structures
Radix SortThis sorting technique is based on the values of the actual digits in the positional representations of the numbers being sorted. Using the decimal base, for example, where the radix is 10, the numbers can be partitioned into ten groups on the sorter. For example, to sort a collection of numbers where each number is a four-digit number, then, All the numbers are first sorted according to the the digit at unit's place. In the second pass, the numbers are sorted according to the digit at tenth place. In the third pass, the numbers are sorted according to the digit at hundredth place. In the forth and last pass, the numbers are sorted according to the digit at thousandth place. During each pass, each number is taken in the order in which it appears in partitions from unit's place onwards. When these actions have been performed for each digit, starting with the least significant and ending with most significant, the numbers are sorted. This sorting method is called the radix sort.
Let us take another example. Suppose we have a list of names. To sort these names using radix sort method we will have to classify them into 26 groups The list is first sorted on the first letter of each name, i.e. the names are arranged in 26 classes, where the first class consists of those names that begin with alphabet 'A', the second class consists of those names that begin with alphabet 'B' and so on. During the second pass each class is alphabetized according to the second letter of the name, and so on.
84.
Exception Handling in CConsider the following program:#include void main( ){float i ;i = pow ( -2, 3 ) ;printf ( "%f", i ) ;}int matherr ( struct exception *a ){if ( a -> type == DOMAIN ){if ( !strcmp ( a -> name, "pow" ) ){a -> retval = pow ( - ( a -> arg1 ), a -> arg2 ) ;return 1 ;}}return 0 ;}If we pass a negative value in pow( ) function a run time error occurs. If we wish to get the proper output even after passing a negative value in the pow( ) function we must handle the run time error. For this, we can define a function matherr( ) which is declared in the 'math.h' file. In this function we can detect the run-time error and write our code to correct the error. The elements of the exception structure receives the function name and arguments of the function causing the exception.Data StructuresAVL TreesFor ideal searching in a binary search tree, the heights of the left and right sub-trees of any node should be equal. But, due to random insertions and deletions performed on a binary search tree, it often turns out to be far from ideal. A close approximation to an ideal binary search tree is achievable if it can be ensured that the difference between the heights of the left and the right sub trees of any node in the tree is at most one. A binary search tree in which the difference of heights of the right and left sub-trees of any node is less than or equal to one is known as an AVL tree. AVL tree is also called as Balanced Tree. The name "AVL Tree" is derived from the names of its inventors who are Adelson-Veilskii and Landi. A node in an AVL tree have a new field to store the "balance factor" of a node which denotes the difference of height between the left and the right sub-trees of the tree rooted at that node. And it can assume one of the three possible values {-1,0,1}. -------------------------------------------------------------------------------------------------

FAQ's of C.. Check out your C Knowledge... Part V

-------------------------------------------------------------------------------------------------49.
How do I use scanf( ) to read the date in the form 'dd-mm-yy' ?Ans: There are two ways to read the date in the form of 'dd-mm-yy' one possible way is...
int dd, mm, yy ;char ch ; /* for char '-' */printf ( "\nEnter the date in the form of dd-mm-yy : " ) ;scanf( "%d%c%d%c%d", &dd, &ch, &mm, &ch, &yy ) ;
And another best way is to use suppression character * as...
int dd, mm, yy ;scanf( "%d%*c%d%*c%d", &dd, &mm, &yy ) ;
The suppression character * suppresses the input read from the standard input buffer for the assigned control character.-------------------------------------------------------------------------------------------------50.
How do I print a floating-point number with higher precision say 23.34568734 with only precision up to two decimal places?
Ans: This can be achieved through the use of suppression char '*' in the format string of printf( ) as shown in the following program. main( ){ int i = 2 ;float f = 23.34568734 ;printf ( "%.*f", i, f ) ; }The output of the above program would be 23.35.
-------------------------------------------------------------------------------------------------51. Are the expressions *ptr++ and ++*ptr same?
Ans: No. *ptr++ increments the pointer and not the value pointed by it, whereas ++*ptr increments the value being pointed to by ptr. -------------------------------------------------------------------------------------------------
52. strpbrk( )
The function strpbrk( ) takes two strings as parameters. It scans the first string, to find, the first occurrence of any character appearing in the second string. The function returns a pointer to the first occurrence of the character it found in the first string. The following program demonstrates the use of string function strpbrk( ).
#include main( ){ char *str1 = "Hello!" ; char *str2 = "Better" ; char *p ; p = strpbrk ( str1, str2 ) ;
if ( p ) printf ( "The first character found in str1 is %c", *p ) ; else printf ( "The character not found" ) ; } The output of the above program would be the first character found in str1 is e
53.
Can we convert an unsigned long integer value to a string?
Ans: The function ultoa( ) can be used to convert an unsigned long integer value to a string. This function takes three arguments, first the value that is to be converted, second the base address of the buffer in which the converted number has to be stored (with a string terminating null character '\0') and the last argument specifies the base to be used in converting the value. Following example demonstrates the use of this function.
#include void main( ){ unsigned long ul = 3234567231L ;char str[25] ;
ultoa ( ul, str, 10 ) ;printf ( "str = %s unsigned long = %lu\n", str, ul ) ; }-------------------------------------------------------------------------------------------------54. ceil( ) and floor( )
The math function ceil( ) takes a double value as an argument. This function finds the smallest possible integer to which the given number can be rounded up. Similarly, floor( ) being a math function, takes a double value as an argument and returns the largest possible integer to which the given double value can be rounded down. The following program demonstrates the use of both the functions.
#include void main( ){double no = 1437.23167 ;double down, up ;
down = floor ( no ) ;up = ceil ( no ) ;
printf ( "The original number %7.5lf\n", no ) ;printf ( "The number rounded down %7.5lf\n", down ) ;printf ( "The number rounded up %7.5lf\n", up ) ;}The output of this program would be,The original number 1437.23167The number rounded down 1437.00000The number rounded up 1438.00000-------------------------------------------------------------------------------------------------55.
How do I use function ecvt( ) in a program?
Ans: The function ecvt( ) converts a floating-point value to a null terminated string. This function takes four arguments, such as, the value to be converted to string, the number of digits to be converted to string, and two integer pointers. The two-integer pointer stores the position of the decimal point (relative to the string) and the sign of the number, respectively. If the value in a variable, used to store sign is 0, then the number is positive and, if it is non-zero, then the number is negative. The function returns a pointer to the string containing digits. Following program demonstrates the use of this function. #include main( ){ char *str ;double val ;int dec, sign ;int ndig = 4 ;
val = 22 ;str = ecvt ( val, ndig, &dec, &sign ) ;printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ;
val = -345.67 ;ndig = 8 ;str = ecvt ( val, ndig, &dec, &sign ) ;printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ;
// number with a scientific notationval = 3.546712e5 ;ndig = 5 ;str = ecvt ( val, ndig, &dec, &sign ) ;printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ; }
The output of this program would be string = 2200 dec = 2 sign = 0string = 34567000 dec = 3 sign = 1string = 35467 dec = 6 sign = 0 -------------------------------------------------------------------------------------------------
56.
How to run DIR command programmatically?Ans: We can use the system( ) function to execute the DIR command along with its options. Following program shows how this can be achieved:// mydir.cmain ( int argc, char *argv[ ] ){char str[30] ;if ( argc <> mydir abc.c /sThis will search the file 'abc.c' in the current directory.-------------------------------------------------------------------------------------------------57.
Suppose I have a structure having fields name, age, salary and have passed address of age to a function fun( ). How I can access the other member of the structure using the address of age?Ans:struct emp { char name[20] ; int age ; float salary ; } ; main( ) { struct emp e ; printf ( "\nEnter name: " ) ; scanf ( "%s", e.name ) ; printf ( "\nEnter age: " ) ; scanf ( "%d", &e.age ) ; printf ( "\nEnter salary: " ) ; scanf ( "%f", &e.salary ) ; fun ( &e.age ) ; } fun ( int *p ) { struct emp *q ; int offset ; offset = ( char * ) ( & ( ( struct emp * ) 0 ) -> age ) - ( char * ) ( ( struct emp* ) 0 ) ; q = ( struct emp * ) ( ( char * ) p - offset ) ; printf ( "\nname: %s", q -> name ) ; printf ( "\nage: %d", q -> age ) ; printf ( "\nsalary: %f", q -> salary ) ; }
58.
How to restrict the program's output to a specific screen region?Ans: A C function window( ) can be used to restrict the screen output to a specific region. The window( ) function defines a text-mode window. The parameters passed to this function defines the upper-left and lower-right corner of the region within which you want the output. In the following program, the string 'Hello!' gets printed within the specified region. To print the string we must use cprintf( ) function which prints directly on the text-mode window.#include main( ){int i, j ;window ( 20, 8, 60, 17 ) ;for ( i = 0 ; i < j =" 0" pwd =" getpass">main( ){int disk ;disk = _getdrive( ) + 'A' - 1 ;printf ( "The current drive is: %c\n", disk ) ;}-------------------------------------------------------------------------------------------------

FAQ's of C.. Check out your C Knowledge... Part VI

61.
How come the output for both the programs is different when the logic is same?main( ){int i, j ;for ( i = 1, j = 1 ; i <= 5, j <= 100 ; i++, j++ ){gotoxy ( 1, 1, ) ;printf ( "%d %d", i, j ) ;}}main( ){int i, j ;for ( i =1, j = 1; j <= 100, i <= 5; i++, j++ ){gotoxy ( 1, 1 ) ;printf ( "%d %d", i, j ) ;}}Output -> 5 5Even if logic of both the programs is same the output of the first program comes out to be 100, 100, but of the second program it is 5, 5. The comma operator plays a vital role inside the for loop. It always considers the value of the latest variable. So, at the time of testing the condition in for loop, the value of j will be considered in the first program and value of i in the second.-------------------------------------------------------------------------------------------------62. Can we get the x and y coordinate of the current cursor position ?Ans : The function wherex( ) and wherey( ) returns the x-coordinate and y-coordinate of the current cursor position respectively. Both the functions return an integer value. The value returned by wherex( ) is the horizontal position of cursor and the value returned by wherey( ) is the vertical position of the cursor. Following program shows how to use the wherex( ) and wherey( ) functions.#include main( ){printf ( "Just\n To\n Test\n Where\n the cursor\n goes" ) ;printf ( "Current location is X: %d Y: %d\n", wherex( ), wherey( ) ) ;}
63. How do I programmatically delete lines in the text window?Ans: While writing programs that perform screen-based I/O, you may want to-delete the current line's contents, moving one line up, all of the output that follows. In such cases a function called delline( ) can be used. Following code snippet illustrates the use of function delline( ).#include main( ){int i ;clrscr( ) ;for ( i = 0; i <= 23; i++ )printf ( "Line %d\r\n", i ) ;printf ( "Press a key to continue : " ) ;getch( ) ;gotoxy ( 2, 6 ) ;for ( i = 6; i <= 12; i++ )delline( ) ;getch( ) ;}-------------------------------------------------------------------------------------------------64. How do I get the time elapsed between two function calls ?Ans: The function difftime( ) finds the difference between two times. It calculates the elapsed time in seconds and returns the difference between two times as a double value.#include #include #include main( ){int a[] = { 2, -34, 56, 78, 112, 33, -7, 11, 45, 29, 6 } ;int s ;time_t t1, t2 ; // time_t defines the value used for time functions = sizeof ( a ) / 2 ;t1 = time ( NULL ) ;sel_sort ( a, s ) ; // sort array by selection sortbub_sort ( a, s ) ; // sort array by bubble sort methodt2 = time ( NULL ) ;printf ( "\nThe difference between two function calls is %f", difftime ( t2, t1 ) ) ;}In the above program we have called difftime( ) function that returns the time elapsed from t1 to t2.-------------------------------------------------------------------------------------------------65.
How do I use swab( ) in my program ?Ans: The function swab( ) swaps the adjacent bytes of memory. It copies the bytes from source string to the target string, provided that the number of characters in the source string is even. While copying, it swaps the bytes which are then assigned to the target string.
#include #include #include main ( ) {char *str1 = "hS eesll snsiasl not eh es as oher " ;char *str2 ;clrscr( ) ;swab ( str1, str2, strlen ( str1 ) ) ;printf ( "The target string is : %s\n", str2 ) ; // output -- She sells snails on the sea shoregetch( ) ;}-------------------------------------------------------------------------------------------------66.
Turbo C provides various command line compiler options which we can use through TCC. The compiler options include : displaying specific warning messages, generating 8087 hardware instructions, using a filename for generating assembly code, etc. Instead of compiler options being executed at command line we can use these compiler options in our program. This can be achieved using #pragma options. We can use various flags with #pragma options to use the compiler options. All these flags are available in turbo C's online help.-------------------------------------------------------------------------------------------------67.
I have an array declared in file 'F1.C' as,int a[ ] = { 1, 2, 3, 4, 5, 6 } ;and used in the file 'F2.C' as,extern int a[ ] ;
In the file F2.C, why sizeof doesn't work on the array a[ ]?
Ans: An extern array of unspecified size is an incomplete type. You cannot apply sizeof to it, because sizeof operates during compile time and it is unable to learn the size of an array that is defined in another file. You have three ways to resolve this problem: 1. In file 'F1.C' define as, int a[ ] = { 1, 2, 3, 4, 5, 6 } ;int size_a = sizeof ( a ) ;and in file F2.C declare as,extern int a[ ] ;extern int size_a ;2. In file 'F1.H' define, #define ARR_SIZ 6In file F1.C declare as,#include "F1.H"int a[ ARR_SIZ ] ;and in file F2.C declare as,#include "F1.H"extern int a[ ARR_SIZ ] ;3. In file 'F1.C' define as, int a[ ] = { 1, 2, 3, 4, 5, 6, -1 } ;and in file 'F2.C' declare as,extern int a[ ] ;Here the element -1 is used as a sentinel value, so the code can understand the end without any explicit size.
68. How to delete a line from text displayed on the screen?Ans: Sometimes, specially when we are creating a text editor like program we may wish to allow user to delete a line. We can do so by using two functions namely clreol( ) and delline( ). The clreol( ) function deletes the line from the current cursor position to the end of line. The delline() function deletes the entire line at the current cursor position and moves up the following line. Following program shows how to use these functions.#include main( ){int i ;for ( i = 1 ; i <= 20 ; i++ )printf ( "This is Line %d\n", i ) ;getch( ) ;gotoxy ( 1, 7 ) ;clreol( ) ;getch( ) ;gotoxy ( 1, 12 ) ;delline( ) ;getch( ) ;}-------------------------------------------------------------------------------------------------69. How do I programmatically insert lines in the text window?Ans: We can insert a blank line in the text window using the insline( ) function. This function inserts line at current cursor position. While doing so, it shifts down the lines that are below the newly inserted line.#include void main( ){printf ( "The little snail was slowly moving up. She wanted\r\n" ) ;printf ( "to reach the top of the tree. It was chilly\r\n" ) ;printf ( "winter season. Most of the animals were resting in\r\n" ) ;printf ( "their nests as there was a heavy snow fall.\r\n" ) ;printf ( "\r\nPress any key to continue:" ) ;gotoxy ( 10, 2 ) ;getch( ) ;insline( ) ;getch( ) ;} -------------------------------------------------------------------------------------------------
70.
What will be the output of the following program?main( ){unsigned int num ;int i ;printf ( "\nEnter any number" ) ;scanf ( "%u", &num ) ;for ( i = 0 ; i < 16 ; i++ )printf ( "%d", ( num << i & 1 << 15 ) ? 1 : 0 ) ;}Ans: The output of this program is the binary equivalent of the given number. We have used bitwise operators to get the binary number.-------------------------------------------------------------------------------------------------71. Graphics
Building Mouse Cursors...
In text mode the mouse cursor appears as a block, whereas in graphics mode it appears as an arrow. If we wish we can change the graphics cursor to any other shape the way Windows does. The mouse cursor in graphics mode occupies a 16 by 16 pixel box. By highlighting or dehighlighting some of the pixels in this box we can get the desired shape. For example, the following bit-pattern can be used to generate the cursor which looks like an hour-glass. 1111111111111111 0000000000000000 1000000000000001 0000000000000000 1111111111111111 0000000000000000 1000000000000001 0000000000000000 0100000000000010 1000000000000001 0010000000000100 1100000000000011 0000100000010000 1111000000001111 0000001001000000 1111110000111111 0000001001000000 1111110000111111 0000100000010000 1111000000001111 0010000000000100 1100000000000011 0100000000000010 1000000000000001 1000000000000001 0000000000000000 1111111111111111 0000000000000000 1000000000000001 0000000000000000 1111111111111111 0000000000000000 Mouse pointer bitmap Screen Mask the one's in the mouse pointer bitmap indicate that the pixel would be drawn whereas the zeros indicate that the pixel would stand erased. It is important to note that the mouse pointer bit pattern is 32 bytes long. However, while actually writing a program to change the pointer shape we need a 64 byte bit-map. This provision is made to ensure that when the cursor reaches a position on the screen where something is already written or drawn only that portion should get overwritten which is to be occupied by the mouse cursor. Of the 64 bytes the first 32 bytes contain a bit mask which is first ANDed with the screen image, and then the second 32 bytes bit mask is XORed with the screen image.
The following program changes the mouse cursor in graphics mode to resemble an hour glass.
# include "graphics.h"# include "dos.h"
union REGS i, o ;struct SREGS s ;
int cursor[32] = { /* Hour-glass screen mask */0x0000, 0x0000, 0x0000, 0x0000,0x8001, 0xc003, 0xf00f, 0xfc3f,0xfc3f, 0xf00f, 0xc003, 0x8001,0x0000, 0x0000, 0x0000, 0x0000,/* The mouse pointer bitmap */0xffff, 0x8001, 0xffff, 0x8001,0x4002, 0x2004, 0x1008, 0x0240,0x0240, 0x0810, 0x2004, 0x4002,0x8001, 0xffff, 0x8001, 0xffff, } ;main( ){ int gd = DETECT, gm ;initgraph ( &gd, &gm, "c:\\tc\\bgi" ) ;if ( initmouse( ) == -1 ){ closegraph( ) ;printf ( "\n Mouse not installed!" ) ; exit( ) ; } gotoxy ( 10, 1 ) ; printf ( "Press any key to exit..." ) ;changecursor ( cursor ) ; showmouseptr( ) ;getch( ) ; }
initmouse( ){ i.x.ax = 0 ; int86 ( 0x33, &i, &o ) ;return ( o.x.ax == 0 ? -1 : 0 ) ; }showmouseptr( ){ i.x.ax = 1 ; int86 ( 0x33, &i, &o ) ; }changecursor ( int *shape ){ i.x.ax = 9 ; /* service number */i.x.bx = 0 ; /* actual cursor position from left */i.x.cx = 0 ; /* actual cursor position from top */i.x.dx = ( unsigned ) shape ; /* offset address of pointer image*/segread ( &s ) ; s.es = s.ds ; /* segment address of pointer */int86x ( 0x33, &i, &i, &s ) ; }
72.
Towers Of Hanoi
Suppose there are three pegs labeled A, B and C. Four disks are placed on peg A. The bottom-most disk is largest, and disks go on decreasing in size with the topmost disk being smallest. The objective of the game is to move the disks from peg A to peg C, using peg B as an auxiliary peg. The rules of the game are as follows:
Only one disk may be moved at a time, and it must be the top disk on one of the pegs. A larger disk should never be placed on the top of a smaller disk. Suppose we are to write a program to print out the sequence in which the disks should be moved such that all disks on peg A are finally transferred to peg C. Here it is... main( ){ int n = 4 ;move ( n, 'A', 'B', 'C' ) ; }
move ( n, sp, ap, ep )int n ;char sp, ap, ep ;{ if ( n == 1 ) printf ( "\n Move from %c to %c ", sp, ep ) ; else{ move ( n - 1, sp, ep, ap ) ;move ( 1, sp, ' ', ep ) ;move ( n - 1, ap, sp, ep ) ; } } And here is the output...
Move from A to BMove from A to CMove from B to CMove from A to BMove from C to AMove from C to BMove from A to BMove from A to CMove from B to CMove from B to AMove from C to AMove from B to CMove from A to BMove from A to CMove from B to CThis problem is the famous Towers of Hanoi problem, wherein three pegs are to be employed for transferring the disks with the given criteria. Here's how we go about it. We have three pegs: the starting peg, sp, the auxiliary peg ap, and the ending peg, ep, where the disks must finally be. First, using the ending peg as an auxiliary or supporting peg, we transfer all but the last disk to ap. Next the last disk is moved from sp to ep. Now, using sp as the supporting peg, all the disks are moved from ap to ep. ‘A’, B and C denote the three pegs. The recursive function move( ) is called with different combinations of these pegs as starting, auxiliary and ending pegs.-------------------------------------------------------------------------------------------------

FAQ's of C.. Check out your C Knowledge... Part IV

37. Allocating memory for a 3-D array#include "alloc.h"#define MAXX 3#define MAXY 4#define MAXZ 5main( ){int ***p, i, j, k ;p = ( int *** ) malloc ( MAXX * sizeof ( int ** ) ) ;for ( i = 0 ; i < j =" 0" k =" 0" i =" 0" j =" 0">#include
void main( ){double ans ;double n = 4 ;
ans = ldexp ( n, 2 ) ;printf ( "\nThe ldexp value is : %lf\n", ans ) ;}Here, ldexp( ) function would get expanded as ( 4 * 2 * 2 ), and the output would be the ldexp value is : 16.000000-------------------------------------------------------------------------------------------------
39. Can we get the mantissa and exponent form of a given number?
Ans: The function frexp( ) splits the given number into a mantissa and exponent form. The function takes two arguments, the number to be converted as a double value and an int to store the exponent form. The function returns the mantissa part as a double value. Following example demonstrates the use of this function.
#include #include
void main( ){ double mantissa, number ;int exponent ;
number = 8.0 ;mantissa = frexp ( number, &exponent ) ;
printf ( "The number %lf is ", number ) ;printf ( "%lf times two to the ", mantissa ) ;printf ( "power of %d\n", exponent ) ;
return 0 ; }-------------------------------------------------------------------------------------------------40.
How do I write code that executes certain function only at program termination?Ans: Use atexit( ) function as shown in following program.
#include main( ){ int ch ;void fun ( void ) ;atexit ( fun ) ;// code }void fun( void ){ printf ( "\nTerminate program......" ) ;getch( ) ; }-------------------------------------------------------------------------------------------------41. What are memory models?Ans: The compiler uses a memory model to determine how much memory is allocated to the program. The PC divides memory into blocks called segments of size 64 KB. Usually, program uses one segment for code and a second segment for data. A memory model defines the number of segments the compiler can use for each. It is important to know which memory model can be used for a program. If we use wrong memory model, the program might not have enough memory to execute. The problem can be solved using larger memory model. However, larger the memory model, slower is your program execution. So we must choose the smallest memory model that satisfies our program needs. Most of the compilers support memory models like tiny, small, medium, compact, large and huge.
36. What is a stack ?Ans: The stack is a region of memory within which our programs temporarily store data as they execute. For example, when a program passes parameters to functions, C places the parameters on the stack. When the function completes, C removes the items from the stack. Similarly, when a function declares local variables, C stores the variable's values on the stack during the function's execution. Depending on the program's use of functions and parameters, the amount of stack space that a program requires will differ.-------------------------------------------------------------------------------------------------37. Allocating memory for a 3-D array#include "alloc.h"#define MAXX 3#define MAXY 4#define MAXZ 5main( ){int ***p, i, j, k ;p = ( int *** ) malloc ( MAXX * sizeof ( int ** ) ) ;for ( i = 0 ; i < j =" 0" k =" 0" i =" 0" j =" 0">#include
void main( ){double ans ;double n = 4 ;
ans = ldexp ( n, 2 ) ;printf ( "\nThe ldexp value is : %lf\n", ans ) ;}Here, ldexp( ) function would get expanded as ( 4 * 2 * 2 ), and the output would be the ldexp value is : 16.000000-------------------------------------------------------------------------------------------------
39. Can we get the mantissa and exponent form of a given number?
Ans: The function frexp( ) splits the given number into a mantissa and exponent form. The function takes two arguments, the number to be converted as a double value and an int to store the exponent form. The function returns the mantissa part as a double value. Following example demonstrates the use of this function.
#include #include
void main( ){ double mantissa, number ;int exponent ;
number = 8.0 ;mantissa = frexp ( number, &exponent ) ;
printf ( "The number %lf is ", number ) ;printf ( "%lf times two to the ", mantissa ) ;printf ( "power of %d\n", exponent ) ;
return 0 ; }-------------------------------------------------------------------------------------------------40.
How do I write code that executes certain function only at program termination?Ans: Use atexit( ) function as shown in following program.
#include main( ){ int ch ;void fun ( void ) ;atexit ( fun ) ;// code }void fun( void ){ printf ( "\nTerminate program......" ) ;getch( ) ; }-------------------------------------------------------------------------------------------------41. What are memory models?Ans: The compiler uses a memory model to determine how much memory is allocated to the program. The PC divides memory into blocks called segments of size 64 KB. Usually, program uses one segment for code and a second segment for data. A memory model defines the number of segments the compiler can use for each. It is important to know which memory model can be used for a program. If we use wrong memory model, the program might not have enough memory to execute. The problem can be solved using larger memory model. However, larger the memory model, slower is your program execution. So we must choose the smallest memory model that satisfies our program needs. Most of the compilers support memory models like tiny, small, medium, compact, large and huge.
42. How does C compiler store elements in a multi-dimensional array?
Ans: The compiler maps multi-dimensional arrays in two ways—Row major order and Column order. When the compiler places elements in columns of an array first then it is called column-major order. When the compiler places elements in rows of an array first then it is called row-major order. C compilers store multidimensional arrays in row-major order. For example, if there is a multi-dimensional array a[2][3], then according row-major order, the elements would get stored in memory following order: a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2]-------------------------------------------------------------------------------------------------43. If the result of an _expression has to be stored to one of two variables, depending on a condition, can we use conditional operators as shown below?
( ( i < i =" 5" j =" 10" k =" 12," l =" 1" i =" %d" j =" %d" k =" %d" l =" %d" i =" 5" j =" 16" k =" 12" l =" 1-------------------------------------------------------------------------------------------------44." monday =" 1" sunday =" 0">= 1 and <= 12, yy > 1752 or so */static int arr[ ] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 } ;yy = yy - mm < i =" 0">void main( ){ div_t res ;
res = div ( 32, 5 ) ;printf ( "\nThe quotient = %d and remainder = %d ", res.quot, res.rem ) ; }
-----------------------------------------------------------------------------------------------
48. What would the second and the third printf( ) output the following program?
main( ){ char *str[ ] = { "Good Morning""Good Evening""Good Afternoon" } ; printf ( "\nFirst string = %s", str[0] ) ;printf ( "\nSecond string = %s", str[1] ) ;printf ( "\nThird string = %s", str[2] ) ; } Ans: For the above given program, we expect the output as Good Evening and Good Afternoon, for the second and third printf( ). However, the output would be as shown below.
First string = Good MorningGood EveningGood AfternoonSecond string = ( null ) Third string =
What is missing in the above given code snippet is a comma separator which should separate the strings Good Morning, Good Evening and Good Afternoon. On adding comma, we would get the output as shown below.First string = Good MorningSecond string = Good EveningThird string = Good Afternoon-------------------------------------------------------------------------------------------------