training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

commit 22a14ea979a91155819e5e86fb62f6a87e8f3ebf
parent 73db4e13aaf407c3ee0f4af0586838d7502c5e61
Author: Claudio <claudio@clabook.(none)>
Date:   Sun, 31 Mar 2013 11:54:09 +0200

Add the exercises.

Diffstat:
Aexercises/README.md | 4++++
Aexercises/apue/book_code.tar.bz2 | 0
Aexercises/apue/ex-3.2.c | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/ex-3.6.c | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/ex-4.1.c | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/ex-4.19.c | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/ex-4.7.c | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/ex-6.2.c | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/ex-6.3.c | 39+++++++++++++++++++++++++++++++++++++++
Aexercises/apue/ex-6.4.c | 38++++++++++++++++++++++++++++++++++++++
Aexercises/apue/ex-7.5.c | 28++++++++++++++++++++++++++++
Aexercises/apue/ex-8.2.c | 41+++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/ex-8.6.c | 30++++++++++++++++++++++++++++++
Aexercises/apue/ex-8.7.c | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/ex-9.2.c | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/holes.c | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/others/error.c | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/others/ex-4.12.c | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/others/ex-8.3.c | 36++++++++++++++++++++++++++++++++++++
Aexercises/apue/others/ftw4.c | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/others/ourhdr.h | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/apue/others/pathalloc.c | 36++++++++++++++++++++++++++++++++++++
Aexercises/apue/others/tellwait.c | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch1-2/calc.c | 20++++++++++++++++++++
Aexercises/deitel/ch1-2/calc2.c | 29+++++++++++++++++++++++++++++
Aexercises/deitel/ch1-2/cerchio.c | 21+++++++++++++++++++++
Aexercises/deitel/ch1-2/getintbychar.c | 17+++++++++++++++++
Aexercises/deitel/ch1-2/graph.c | 21+++++++++++++++++++++
Aexercises/deitel/ch1-2/iniziali | 25+++++++++++++++++++++++++
Aexercises/deitel/ch1-2/largegual.c | 25+++++++++++++++++++++++++
Aexercises/deitel/ch1-2/multiplo.c | 21+++++++++++++++++++++
Aexercises/deitel/ch1-2/pairs.c | 21+++++++++++++++++++++
Aexercises/deitel/ch1-2/powtab.c | 24++++++++++++++++++++++++
Aexercises/deitel/ch1-2/print1-4.c | 19+++++++++++++++++++
Aexercises/deitel/ch1-2/scacchiera.c | 23+++++++++++++++++++++++
Aexercises/deitel/ch1-2/smallarge5.c | 45+++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch1-2/smpmm.c | 45+++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch1-2/splitint.c | 27+++++++++++++++++++++++++++
Aexercises/deitel/ch10/10.3 | 31+++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/10.5 | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/10.6 | 37+++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/checkunion.c | 24++++++++++++++++++++++++
Aexercises/deitel/ch10/fig10_07_mod.c | 46++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/fig10_16_mod.c | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/packc.c | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/packc4.c | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/portablepbits.c | 42++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/power2.c | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/reverseBits.c | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/shift.c | 41+++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch10/unionfloat.c | 20++++++++++++++++++++
Aexercises/deitel/ch11/datasize.c | 32++++++++++++++++++++++++++++++++
Aexercises/deitel/ch11/esimpletron2.c | 519+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch11/fig08_14_mod.c | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch11/fig11_07_mod.c | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch11/file-matching2.c | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch11/hardware.c | 242+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch11/mkrecord.c | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch11/oldmast.dat | 0
Aexercises/deitel/ch11/oldmast.dat.1 | 0
Aexercises/deitel/ch11/person.c | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch11/trans.dat | 0
Aexercises/deitel/ch11/trans.dat.1 | 0
Aexercises/deitel/ch12/Semplice.c | 625+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/binarySearchTree.c | 21+++++++++++++++++++++
Aexercises/deitel/ch12/concatenate.c | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/depth.c | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/evalpfexp.c | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/evalpfexp2.c | 168+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/fig12_19_mod.c | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/fig12_19_mod2.c | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/fig12_19_mod3.c | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/inverse.c | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/levelOrder.c | 308+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/listcalc.c | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/market.c | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/merge.c | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/outputTree.c | 336+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/palindrom.c | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/searchList.c | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/semplice.txt | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/stackinv.c | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch12/topostfix.c | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/3.46/intcrypt.c | 37+++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/3.46/intdecrypt.c | 37+++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/3.47/esA.c | 27+++++++++++++++++++++++++++
Aexercises/deitel/ch3/3.47/esB.c | 34++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/3.47/esC.c | 45+++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/asterisk.c | 21+++++++++++++++++++++
Aexercises/deitel/ch3/bin2dec.c | 37+++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/cerchio2.c | 21+++++++++++++++++++++
Aexercises/deitel/ch3/chkseven.c | 26++++++++++++++++++++++++++
Aexercises/deitel/ch3/compsum.c | 20++++++++++++++++++++
Aexercises/deitel/ch3/dynchess.c | 26++++++++++++++++++++++++++
Aexercises/deitel/ch3/fig03_10fix.c | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/getkm.c | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/getprov.c | 24++++++++++++++++++++++++
Aexercises/deitel/ch3/howfast.c | 20++++++++++++++++++++
Aexercises/deitel/ch3/infloop.c | 17+++++++++++++++++
Aexercises/deitel/ch3/interest.c | 29+++++++++++++++++++++++++++++
Aexercises/deitel/ch3/largest.c | 25+++++++++++++++++++++++++
Aexercises/deitel/ch3/largest2.c | 31+++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/outofbadjet.c | 45+++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/palindromo.c | 27+++++++++++++++++++++++++++
Aexercises/deitel/ch3/pow.c | 23+++++++++++++++++++++++
Aexercises/deitel/ch3/ppdec.c | 25+++++++++++++++++++++++++
Aexercises/deitel/ch3/quadrato.c | 35+++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/quadrato_empty.c | 45+++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/salario.c | 32++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/shownum.c | 20++++++++++++++++++++
Aexercises/deitel/ch3/tab246.c | 26++++++++++++++++++++++++++
Aexercises/deitel/ch3/tabdcm.c | 21+++++++++++++++++++++
Aexercises/deitel/ch3/triangolo.c | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch3/triangolo2.c | 45+++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/asterisk.c | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/breakfor.c | 24++++++++++++++++++++++++
Aexercises/deitel/ch4/cal.c | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/contfor.c | 20++++++++++++++++++++
Aexercises/deitel/ch4/creditlimit.c | 34++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/dec2rom.c | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/dec2rom2.c | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/demorgan.c | 38++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/fatt15tab.c | 20++++++++++++++++++++
Aexercises/deitel/ch4/fig04_07.mod.c | 41+++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/fig04_07.mod2.c | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/getavrg.c | 24++++++++++++++++++++++++
Aexercises/deitel/ch4/getpay.c | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/getpg.c | 24++++++++++++++++++++++++
Aexercises/deitel/ch4/getrate.c | 26++++++++++++++++++++++++++
Aexercises/deitel/ch4/getrate2.c | 26++++++++++++++++++++++++++
Aexercises/deitel/ch4/getsmall.c | 25+++++++++++++++++++++++++
Aexercises/deitel/ch4/getweekvalue.c | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/intsum30.c | 18++++++++++++++++++
Aexercises/deitel/ch4/istogram.c | 27+++++++++++++++++++++++++++
Aexercises/deitel/ch4/numtab.c | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/numtab2.c | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/oddingprod15.c | 18++++++++++++++++++
Aexercises/deitel/ch4/rombo.c | 30++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/rombo2.c | 41+++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch4/seqsum.c | 25+++++++++++++++++++++++++
Aexercises/deitel/ch4/tpbf.c | 19+++++++++++++++++++
Aexercises/deitel/ch5/456.txt | 22++++++++++++++++++++++
Aexercises/deitel/ch5/HorT.c | 41+++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/c2f2c_2.c | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/cfuncs.c | 47+++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/checkmf.c | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/craps.c | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/dice.c | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/distance.c | 24++++++++++++++++++++++++
Aexercises/deitel/ch5/elementar.c | 37+++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/elementar2.c | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/elementar3.c | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/elementar4.c | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/even.c | 35+++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/forms.c | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/gcd.c | 29+++++++++++++++++++++++++++++
Aexercises/deitel/ch5/getcharge.c | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/getsecs.c | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/getsquare.c | 29+++++++++++++++++++++++++++++
Aexercises/deitel/ch5/getsquare2.c | 36++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/hanoi.c | 38++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/hypo.c | 27+++++++++++++++++++++++++++
Aexercises/deitel/ch5/interval.c | 20++++++++++++++++++++
Aexercises/deitel/ch5/intgroup.c | 27+++++++++++++++++++++++++++
Aexercises/deitel/ch5/intpow.c | 37+++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/isfirst.c | 30++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/multiple.c | 36++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/mystery.c | 33+++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/nguess.c | 36++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/nguess2.c | 46++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/perfect.c | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/power.c | 28++++++++++++++++++++++++++++
Aexercises/deitel/ch5/qualityPoints.c | 36++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/recgcd.c | 26++++++++++++++++++++++++++
Aexercises/deitel/ch5/recmain.c | 14++++++++++++++
Aexercises/deitel/ch5/recsee.c | 31+++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/revint.c | 36++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/round4.c | 48++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/showfloor.c | 19+++++++++++++++++++
Aexercises/deitel/ch5/smallfloat.c | 27+++++++++++++++++++++++++++
Aexercises/deitel/ch5/splitint.c | 37+++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch5/x_val.c | 17+++++++++++++++++
Aexercises/deitel/ch6/8.txt | 30++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/airlines.c | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/autocraps.c | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/bsort2.c | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/clochk.c | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/dice.c | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/dups.c | 47+++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/fig06_16_2.c | 195+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/getpay.c | 39+++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/sales.c | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/toth_2.c | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/toth_b.c | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/toth_c.c | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/toth_d.c | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/toth_rand.c | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/toth_rand2.c | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/turgraph.c | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch6/turgraph2.c | 192+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/esimpletron.c | 457+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/funcptr.c | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/maze.c | 217+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/maze2.c | 266+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/maze3.c | 271+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/poker.c | 670+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/poker2.c | 903+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/poker3.c | 907+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/poker_mod.c | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/quicksort.c | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/sim_TL.c | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/simpletron.c | 247+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch7/simpletron_base.c | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/4atof.c | 22++++++++++++++++++++++
Aexercises/deitel/ch8/4atoi.c | 21+++++++++++++++++++++
Aexercises/deitel/ch8/ascii.c | 24++++++++++++++++++++++++
Aexercises/deitel/ch8/assprot.c | 30++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/chcmp.c | 48++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/cmp2s.c | 31+++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/countwords.c | 43+++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/cruciverb_BROKEN.c | 234+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/dataconv.c | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/diffwordc.c | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/filter-ed.c | 35+++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/filterb.c | 30++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/hl.c | 27+++++++++++++++++++++++++++
Aexercises/deitel/ch8/justify.c | 47+++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/limerick.c | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/limerick2.c | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/metrics3.c | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/mkphrase.c | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/morse | 0
Aexercises/deitel/ch8/morse.c | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/myctype.c | 177+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/mystrcnp.c | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/mystrcomp.c | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/mystrconv.c | 243+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/mystrio.c | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/mystrlen.c | 29+++++++++++++++++++++++++++++
Aexercises/deitel/ch8/mystrmem.c | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/mystrsrch.c | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/n2w.c | 262+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/ncmp2s.c | 33+++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/phone.c | 24++++++++++++++++++++++++
Aexercises/deitel/ch8/piglatin.c | 42++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/promptletter.c | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/search.c | 26++++++++++++++++++++++++++
Aexercises/deitel/ch8/searchc.c | 26++++++++++++++++++++++++++
Aexercises/deitel/ch8/searchctot.c | 46++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/searchtot.c | 44++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/strcomp.c | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/strorder.c | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/strtok_rev.c | 36++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/textanalysis.c | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch8/wordocc.c | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch9/escapes.c | 24++++++++++++++++++++++++
Aexercises/deitel/ch9/ex94.c | 42++++++++++++++++++++++++++++++++++++++++++
Aexercises/deitel/ch9/nsum.c | 28++++++++++++++++++++++++++++
Aexercises/deitel/ch9/simplecmp.c | 16++++++++++++++++
Aexercises/deitel/deitel_code.tar.gz | 0
260 files changed, 20415 insertions(+), 0 deletions(-)

diff --git a/exercises/README.md b/exercises/README.md @@ -0,0 +1,4 @@ +Excercises +========== + +Exercises I did while learning programming. diff --git a/exercises/apue/book_code.tar.bz2 b/exercises/apue/book_code.tar.bz2 Binary files differ. diff --git a/exercises/apue/ex-3.2.c b/exercises/apue/ex-3.2.c @@ -0,0 +1,119 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 3.2 +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <errno.h> + +/* + * Determinate the maximum number of open files (fds) +*/ +#ifdef OPEN_MAX +static int openmax = OPEN_MAX; +#else +#define OPEN_MAX_GUESS 256 +static int openmax = 0; +#endif + +/* + * Functions prototypes +*/ +int set_open_max(void); +int my_dup2(int fd1, int fd2); + +int +main(void) +{ + + /* set the openmax variable */ + if( set_open_max() ) + return EXIT_FAILURE ; + + /* + * Testing the function + */ + if( my_dup2(STDOUT_FILENO, 5) == -1 ) { + perror("my_dup2()"); + return EXIT_FAILURE ; /* Something went wrong */ + } + + /* Write to the new file descriptor */ + if( write(5, "my_dup2()", 9) != 9 ) { + perror("write()"); + return EXIT_FAILURE ; /* Something went wrong */ + } + + /* + * File descriptors are implicitally at the end of the program + */ + + return EXIT_SUCCESS ; +} /* eof main() */ + +/* + * Set the maximum number of file descriptors. + * Adapted from the APUE sample program 2.3. +*/ +int +set_open_max(void) +{ + + if( ! openmax ) { + + errno = 0; + + if( (openmax = sysconf(_SC_OPEN_MAX)) < 0 ) { + if( ! errno ) + openmax = OPEN_MAX_GUESS; + else + return -1; + } + + } + + return 0; +} /* eof set_open_max() */ + +/* + * Duplicate a file descriptor (non atomically) +*/ +int +my_dup2(int fd1, int fd2) +{ + int fds_total = 0, *fds_list; + + /* check if are valid file descriptors */ + if( fd1 < 0 || fd1 > openmax || fd2 < 0 || fd2 > openmax ) { + errno = EBADF; + return -1; + } + + /* If the descriptors are not the same then duplicate fd1 to fd2 */ + if( fd1 != fd2 ) { + + /* Allocate the file descriptors container */ + if( (fds_list = calloc(1, openmax * sizeof(int))) == NULL ) + return -1; + + /* close fd2 first, if open */ + (void)close(fd2); + + /* get the duplicated file descriptor number "fd2" */ + while( (fds_list[fds_total] = dup(fd1)) != fd2 ) + ++fds_total; + + /* close the others descriptors */ + while( --fds_total >= 0 ) + (void)close(fds_list[fds_total]); + + free(fds_list); + + } + + return fd2; +} /* eof my_dup2() */ + diff --git a/exercises/apue/ex-3.6.c b/exercises/apue/ex-3.6.c @@ -0,0 +1,76 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 3.6 +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> +#include <sys/types.h> +#include <sys/stat.h> + +#define FILE "test" + +int +main(void) +{ + int fd; + char buf[10] = { 0 }; + + printf("lseek(2) test for RW file with append flag\n\n"); + + /* open the file */ + printf("open(2)..."); + if( (fd = open(FILE, O_RDWR | O_APPEND | O_CREAT | O_TRUNC, S_IRWXU)) == -1 ) { + printf(" KO\n"); + return EXIT_FAILURE; + } + printf("OK\n"); + + /* write something */ + printf("write(2)..."); + if( write(fd, "{first write call}", 18) != 18 ) { + printf(" KO\n"); + (void)close(fd); + return EXIT_FAILURE; + } + printf(" OK\n"); + + printf("\nTrying to seek 5 bytes from the beginning of the file..\n\n"); + + /* move somewhere */ + printf("lseek(2)..."); + if( lseek(fd, 5, SEEK_SET) < 0 ) { + printf(" KO\n"); + (void)close(fd); + return EXIT_FAILURE; + } + printf(" OK\n"); + + /* read something */ + printf("read(2)..."); + if( read(fd, buf, 5) == -1 ) { + printf(" KO\n"); + (void)close(fd); + return EXIT_FAILURE; + } + printf(" OK\n"); + + /* write something, again */ + printf("write(2)..."); + if( write(fd, "[2nd write]", 11) != 11 ) { + printf(" KO\n"); + (void)close(fd); + return EXIT_FAILURE; + } + printf(" OK\n"); + + close(fd); + + printf("\nTest finished. Check the '%s' file.\n", FILE); + + return EXIT_SUCCESS; +} /* eof main() */ + diff --git a/exercises/apue/ex-4.1.c b/exercises/apue/ex-4.1.c @@ -0,0 +1,54 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 4.1 +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <sys/stat.h> + +int +main(int argc, char *argv[]) +{ + int i; + struct stat buf; + char *ptr; + + for(i = 1; i < argc; i++) { + printf("%s: ", argv[i]); + /* + * Do not use lstat(2) + */ + if(stat(argv[i], &buf) < 0) { + perror("stat"); + continue; + } + + if( S_ISREG(buf.st_mode)) + ptr = "regular"; + else if( S_ISDIR(buf.st_mode)) + ptr = "directory"; + else if( S_ISCHR(buf.st_mode)) + ptr = "character special"; + else if( S_ISBLK(buf.st_mode)) + ptr = "block special"; + else if( S_ISFIFO(buf.st_mode)) + ptr = "fifo"; +#ifdef S_ISLNK + else if( S_ISLNK(buf.st_mode)) + ptr = "symbolic link"; +#endif +#ifdef S_ISSOCK + else if( S_ISDIR(buf.st_mode)) + ptr = "socket"; +#endif + else + ptr = "** unknown mode **"; + + printf("%s\n", ptr); + } + + return EXIT_FAILURE; +} /* eof main() */ + diff --git a/exercises/apue/ex-4.19.c b/exercises/apue/ex-4.19.c @@ -0,0 +1,59 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 4.19 + * + * NOTE: the exercise is done assuming PATH_MAX already defined +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <sys/stat.h> +#include <unistd.h> +#include <limits.h> + +#define DIRNAME "ex-4.19_dir" + +int +main(void) +{ + int i, levels, umask_save; + char cwd[PATH_MAX * 2] = { 0 }; + + umask_save = umask(0); /* Store the umask value and clear the mask */ + + levels = PATH_MAX / sizeof(DIRNAME) + 1; + + printf("Creating a %d-levels deep directories tree..", levels); + fflush(stdout); + + /* Create a deep directories tree */ + for(i = 0; i < levels; i++) { + + /* Create the directory */ + if( mkdir(DIRNAME, 0700) == -1 ) { + perror("\nmkdir"); + break; + } + + /* Enter the directory */ + if( chdir(DIRNAME) == -1 ) { + perror("\nchdir"); + break; + } + + } + + /* Get the working directory on the leaf directory */ + if( getcwd(cwd, sizeof(cwd)) == NULL ) { + perror("\ngetcwd"); + printf("\tdirectory: %d; full path length: %d\n", i, sizeof(DIRNAME)*i); + } + + printf(" done\n"); + + (void)umask(umask_save); /* Restore the umask value (pretty useless here) */ + + return EXIT_SUCCESS; +} /* eof main() */ + diff --git a/exercises/apue/ex-4.7.c b/exercises/apue/ex-4.7.c @@ -0,0 +1,59 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 4.7 +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> +#include <sys/stat.h> + +#define BUFSIZE 8192 + +int +main(int argc, char *argv[]) +{ + int fd, fd2; + ssize_t size; + char buf[BUFSIZE] = { 0 }; + + /* Arguments check */ + if( argc != 3 ) { + printf("Usage: %s <source file> <destination file>\n", argv[0]); + return EXIT_FAILURE; + } + + /* open the source file */ + if( (fd = open(argv[1], O_RDONLY)) == -1 ) { + perror("open(source)"); + return EXIT_FAILURE; + } + + /* open the destination file */ + if( (fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) == -1 ) { + perror("open(destination)"); + + close(fd); /* close the source file */ + return EXIT_FAILURE; + } + + /* copy the file */ + while( (size = read(fd, buf, 1)) > 0 ) { + if( *buf && write(fd2, buf, size) != size ) { + perror("write"); + break; + } + } + + /* read error */ + if( size == -1 ) + perror("read"); + + close(fd); + close(fd2); + + return EXIT_SUCCESS; +} /* eof main() */ + diff --git a/exercises/apue/ex-6.2.c b/exercises/apue/ex-6.2.c @@ -0,0 +1,55 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 6.2 +*/ + +#include <stdio.h> +#include <stdlib.h> + +#include <paths.h> /* Needed for _PATH_SHADOW */ + +#if defined(_PATH_SHADOW) +# include <shadow.h> +#else +# include <pwd.h> +#endif + +int +main(int argc, char *argv[]) +{ + char *user, *pass; + +#if defined(_PATH_SHADOW) + struct spwd *p; +#else + struct passwd *p; +#endif + + /* Check the arguments */ + if( argc != 2 ) { + printf("Usage: %s <username>\n", argv[0]); + return EXIT_FAILURE; + } + + /* Get the informations */ +#if defined(_PATH_SHADOW) + if( (p = getspnam(argv[1])) == NULL ) + return EXIT_FAILURE; + + user = p->sp_namp; + pass = p->sp_pwdp; +#else + if( (p = getpwnam(argv[1])) == NULL ) + return EXIT_FAILURE; + + user = p->pw_name; + pass = p->pw_passwd; +#endif + + /* Show the informations */ + printf("Encrypted password for %s: %s\n", user, pass); + + return EXIT_SUCCESS; +} /* eof main() */ + diff --git a/exercises/apue/ex-6.3.c b/exercises/apue/ex-6.3.c @@ -0,0 +1,39 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 6.3 + * + * NOTE: operating system field has not been implemented + * since a Makefile is needed for this purpose. +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <sys/utsname.h> + +int +main(void) +{ + struct utsname un; + + /* Get the informations */ + if( uname(&un) == -1 ) { + perror("uname"); + return EXIT_FAILURE; + } + + /* Show the informations */ + printf("%s %s %s %s %s", + un.sysname, un.nodename, un.release, + un.version, un.machine); + +#if defined(__Linux__) +# define _UTSNAME_DOMAIN_LENGHT 1 + printf(" %s", un.domainname); +#endif + + printf("\n"); + + return EXIT_SUCCESS; +} /* eof main() */ + diff --git a/exercises/apue/ex-6.4.c b/exercises/apue/ex-6.4.c @@ -0,0 +1,38 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 6.4 + * + * Sample output: ven feb 15 16:30:43 CET 2008 +*/ + + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define TMBUFSZ 64 + +int +main(void) +{ + struct tm *tm_t; + char tmbuf[TMBUFSZ]; + time_t tmcal; + + tmcal = time(NULL); + + /* Get the broken-down local time */ + if( (tm_t = localtime(&tmcal)) == NULL ) { + perror("localtime"); + return EXIT_FAILURE; + } + + /* Generate the output string */ + strftime(tmbuf, TMBUFSZ, "%a %b %d %X %Z %Y", tm_t); + + printf("%s\n", tmbuf); + + return EXIT_SUCCESS; +} /* eof main() */ + diff --git a/exercises/apue/ex-7.5.c b/exercises/apue/ex-7.5.c @@ -0,0 +1,28 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 7.5 +*/ + +#include <stdio.h> +#include <stdlib.h> + +typedef void ExitFunc(void); + +ExitFunc efunc; /* Exit function */ +int atexit(ExitFunc); /* Prototyped again */ + +int +main(void) +{ + + atexit(efunc); + + return EXIT_SUCCESS; +} /* eof main() */ + +void efunc(void) +{ + printf("Exiting...\n"); +} /* eof efunc() */ + diff --git a/exercises/apue/ex-8.2.c b/exercises/apue/ex-8.2.c @@ -0,0 +1,41 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 8.2 +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <unistd.h> + +pid_t vfunc(void); + +int +main(void) +{ + pid_t pid; + + if( (pid = vfunc()) == -1 ) { + perror("vfunc"); + return EXIT_FAILURE; + } + + printf("[%d] Returning..\n", pid); + + return EXIT_SUCCESS; +} /* eof main() */ + +pid_t +vfunc(void) +{ + pid_t pid = vfork(); + +#if !defined(__linux__) + if( pid > 0 ) + sleep(2); /* Parent: wait a bit to child returns first */ +#endif + + return pid; +} /* eof vfunc() */ + diff --git a/exercises/apue/ex-8.6.c b/exercises/apue/ex-8.6.c @@ -0,0 +1,30 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 8.6 +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <unistd.h> + +int +main(void) +{ + pid_t pid; + + if( (pid = fork()) == -1 ) { + perror("fork"); + return EXIT_FAILURE; + } + else if( pid ) { +#if !defined(__linux__) + sleep(1); /* Wait a bit to make a zombie */ +#endif + system("ps"); + } + + return EXIT_SUCCESS; /* Make C compiler happy! */ +} /* eof main() */ + diff --git a/exercises/apue/ex-8.7.c b/exercises/apue/ex-8.7.c @@ -0,0 +1,54 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 8.7 +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <dirent.h> +#include <unistd.h> +#include <fcntl.h> + +void pflags(int fd); + +int +main(void) +{ + DIR *dir; + const char *dirname = "/"; + int fd; + + /* open the directory stream */ + if( (dir = opendir(dirname)) == NULL ) { + perror("opendir"); + return EXIT_FAILURE; + } + pflags(dirfd(dir)); /* close-on-exec flag status */ + + /* Open the directory for reading */ + if( (fd = open(dirname, O_RDONLY)) == -1 ) { + closedir(dir); + perror("open"); + return EXIT_FAILURE; + } + + pflags(fd); /* close-on-exec flag status */ + + close(fd); /* close the descriptor */ + closedir(dir); /* close the stream */ + + return EXIT_SUCCESS; /* Make C compiler happy! */ +} /* eof main() */ + +void +pflags(int fd) +{ + int flags; + + if( (flags = fcntl(fd, F_GETFD)) != -1 ) + printf("close-on-exec: %s\n", (flags & FD_CLOEXEC ? "on" : "off")); + +} /* eof pflags() */ + diff --git a/exercises/apue/ex-9.2.c b/exercises/apue/ex-9.2.c @@ -0,0 +1,56 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 9.2 +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> + +int +main(int argc, char *argv[]) +{ + pid_t pid; + + strncpy(argv[0], "ex-9.2", strlen(argv[0])); + + if( (pid = fork()) ) + exit(1); + + if( (pid = fork()) == -1 ) { + perror("fork"); + return EXIT_FAILURE; + } + else if( pid == 0 ) { /* child */ + sleep(1); /* Wait for the parent to terminate (?) */ + + if( setsid() == -1 ) { /* Start a new session */ + perror("setsid"); + return EXIT_FAILURE; + } + + /* Some dirty output */ + printf("\n"); + + system( +#if defined(__linux__) + "ps jx" +#else + "ps jx -otpgid" +#endif + ); + + sleep(1); + } + + /* + * The parent just terminate + * + * ... + */ + + return EXIT_SUCCESS; /* Make C compiler happy! */ +} /* eof main() */ + diff --git a/exercises/apue/holes.c b/exercises/apue/holes.c @@ -0,0 +1,57 @@ +/* + * File holes. + * + * APUE experimental - Just to understand. +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> +#include <sys/stat.h> + +#define FILE_NAME "test.hole" +#define BUFSZ 512 + +int +main(void) +{ + int fd; + char before[BUFSZ]; + char after[] = "This is the text written after the hole"; + + for(fd = 0; fd < BUFSZ; fd++) + before[fd] = 'X'; + + /* open the file */ + if( (fd = open(FILE_NAME, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU)) == -1 ) { + perror("open"); + return EXIT_FAILURE; + } + + /* write few data */ + if( write(fd, before, sizeof(before)) != sizeof(before) ) { + perror("write"); + close(fd); + return EXIT_FAILURE; + } + + /* seek after the end of file */ + if( lseek(fd, BUFSZ * BUFSZ, SEEK_SET) < 0 ) { + perror("lseek"); + close(fd); + return EXIT_FAILURE; + } + + /* write few data (make the hole) */ + if( write(fd, after, sizeof(after)) != sizeof(after) ) { + perror("write"); + close(fd); + return EXIT_FAILURE; + } + + close(fd); /* close the file */ + + return EXIT_SUCCESS; +} /* eof main() */ + diff --git a/exercises/apue/others/error.c b/exercises/apue/others/error.c @@ -0,0 +1,98 @@ +#include <errno.h> /* for definition of errno */ +#include <stdarg.h> /* ANSI C header file */ +#include "ourhdr.h" + +static void err_doit(int, const char *, va_list); + +char *pname = NULL; /* caller can set this from argv[0] */ + +/* Nonfatal error related to a system call. + * Print a message and return. */ + +void +err_ret(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + err_doit(1, fmt, ap); + va_end(ap); + return; +} + +/* Fatal error related to a system call. + * Print a message and terminate. */ + +void +err_sys(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + err_doit(1, fmt, ap); + va_end(ap); + exit(1); +} + +/* Fatal error related to a system call. + * Print a message, dump core, and terminate. */ + +void +err_dump(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + err_doit(1, fmt, ap); + va_end(ap); + abort(); /* dump core and terminate */ + exit(1); /* shouldn't get here */ +} + +/* Nonfatal error unrelated to a system call. + * Print a message and return. */ + +void +err_msg(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + err_doit(0, fmt, ap); + va_end(ap); + return; +} + +/* Fatal error unrelated to a system call. + * Print a message and terminate. */ + +void +err_quit(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + err_doit(0, fmt, ap); + va_end(ap); + exit(1); +} + +/* Print a message and return to caller. + * Caller specifies "errnoflag". */ + +static void +err_doit(int errnoflag, const char *fmt, va_list ap) +{ + int errno_save; + char buf[MAXLINE]; + + errno_save = errno; /* value caller might want printed */ + vsprintf(buf, fmt, ap); + if (errnoflag) + sprintf(buf+strlen(buf), ": %s", strerror(errno_save)); + strcat(buf, "\n"); + fflush(stdout); /* in case stdout and stderr are the same */ + fputs(buf, stderr); + fflush(NULL); /* flushes all stdio output streams */ + return; +} diff --git a/exercises/apue/others/ex-4.12.c b/exercises/apue/others/ex-4.12.c @@ -0,0 +1,142 @@ +/* + * Advanced Programming in the UNIX(r) Environment + * + * Exercise 4.12 +*/ + +#include <sys/types.h> +#include <sys/stat.h> +#include <dirent.h> +#include <limits.h> + +#include "ourhdr.h" + +typedef int Myfunc(const char *, const struct stat *, int); + /* function type that's called for each filename */ + +static Myfunc myfunc; +static int myftw(char *filename, Myfunc* func); + +static long nreg, ndir, nblk, nchr, nfifo, nslink, nsock, ntot; + +int +main(int argc, char *argv[]) +{ + int ret; + + if (argc != 2) + err_quit("usage: ftw <starting-pathname>"); + + ret = myftw(argv[1], myfunc); /* does it all */ + + if ( (ntot = nreg + ndir + nblk + nchr + nfifo + nslink + nsock) == 0) + ntot = 1; /* avoid divide by 0; print 0 for all counts */ + printf("regular files = %7ld, %5.2f %%\n", nreg, nreg*100.0/ntot); + printf("directories = %7ld, %5.2f %%\n", ndir, ndir*100.0/ntot); + printf("block special = %7ld, %5.2f %%\n", nblk, nblk*100.0/ntot); + printf("char special = %7ld, %5.2f %%\n", nchr, nchr*100.0/ntot); + printf("FIFOs = %7ld, %5.2f %%\n", nfifo, nfifo*100.0/ntot); + printf("symbolic links = %7ld, %5.2f %%\n", nslink,nslink*100.0/ntot); + printf("sockets = %7ld, %5.2f %%\n", nsock, nsock*100.0/ntot); + + exit(ret); +} + +/* + * Descend through the hierarchy, starting at "pathname". + * The caller's func() is called for every file. + */ + +#define FTW_F 1 /* file other than directory */ +#define FTW_D 2 /* directory */ +#define FTW_DNR 3 /* directory that can't be read */ +#define FTW_NS 4 /* file that we can't stat */ + +/* + * Descend through the hierarchy, starting at "filename". + * If "filename" is anything other than a directory, we lstat() it, + * call func(), and return. For a directory, we call ourself + * recursively for each name in the directory. + */ +static int /* we return whatever func() returns */ +myftw(char *filename, Myfunc* func) +{ + struct stat statbuf; + struct dirent *dirp; + DIR *dp; + int ret; + + if (lstat(filename, &statbuf) < 0) + return(func(filename, NULL, FTW_NS)); /* stat error */ + + if (S_ISDIR(statbuf.st_mode) == 0) + return(func(filename, &statbuf, FTW_F)); /* not a directory */ + + /* + * It's a directory. First call func() for the directory, + * then process each filename in the directory. + */ + + if ( (ret = func(filename, NULL, FTW_D)) != 0) + return(ret); + + if ( (dp = opendir(filename)) == NULL) + return(func(filename, NULL, FTW_DNR)); + + if( chdir(filename) == -1 ) /* enter the directory */ + return(func(filename, NULL, FTW_DNR)); + + while ( (dirp = readdir(dp)) != NULL) { + if (strcmp(dirp->d_name, ".") == 0 || + strcmp(dirp->d_name, "..") == 0) + continue; /* ignore dot and dot-dot */ + + if ( (ret = myftw(dirp->d_name, func)) != 0) /* recursive */ + break; /* time to leave */ + + } + + if (closedir(dp) < 0) + err_ret("can't close directory %s", filename); + + chdir(".."); /* back to the parent directory */ + + return(ret); +} + +static int +myfunc(const char *pathname, const struct stat *statptr, int type) +{ + switch (type) { + case FTW_F: + switch (statptr->st_mode & S_IFMT) { + case S_IFREG: nreg++; break; + case S_IFBLK: nblk++; break; + case S_IFCHR: nchr++; break; + case S_IFIFO: nfifo++; break; + case S_IFLNK: nslink++; break; + case S_IFSOCK: nsock++; break; + case S_IFDIR: + err_dump("for S_IFDIR for %s", pathname); + /* directories should have type = FTW_D */ + } + break; + + case FTW_D: + ndir++; + break; + + case FTW_DNR: + err_ret("can't read directory %s", pathname); + break; + + case FTW_NS: + err_ret("stat error for %s", pathname); + break; + + default: + err_dump("unknown type %d for pathname %s", type, pathname); + } + + return(0); +} diff --git a/exercises/apue/others/ex-8.3.c b/exercises/apue/others/ex-8.3.c @@ -0,0 +1,36 @@ +#include <sys/types.h> +#include "ourhdr.h" + +static void charatatime(char *); + +int +main(void) +{ + pid_t pid; + + TELL_WAIT(); + + if ( (pid = fork()) < 0) + err_sys("fork error"); + else if (pid == 0) { + WAIT_PARENT(); + charatatime("output from child\n"); + TELL_PARENT(getppid()); + } else { + charatatime("output from parent\n"); + TELL_CHILD(pid); + WAIT_CHILD(); + } + exit(0); +} + +static void +charatatime(char *str) +{ + char *ptr; + int c; + + setbuf(stdout, NULL); /* set unbuffered */ + for (ptr = str; (c = *ptr++); ) + putc(c, stdout); +} diff --git a/exercises/apue/others/ftw4.c b/exercises/apue/others/ftw4.c @@ -0,0 +1,149 @@ +#include <sys/types.h> +#include <sys/stat.h> +#include <dirent.h> +#include <limits.h> +#include "ourhdr.h" + +typedef int Myfunc(const char *, const struct stat *, int); + /* function type that's called for each filename */ + +static Myfunc myfunc; +static int myftw(char *, Myfunc *); +static int dopath(Myfunc *); + +static long nreg, ndir, nblk, nchr, nfifo, nslink, nsock, ntot; + +int +main(int argc, char *argv[]) +{ + int ret; + + if (argc != 2) + err_quit("usage: ftw <starting-pathname>"); + + ret = myftw(argv[1], myfunc); /* does it all */ + + if ( (ntot = nreg + ndir + nblk + nchr + nfifo + nslink + nsock) == 0) + ntot = 1; /* avoid divide by 0; print 0 for all counts */ + printf("regular files = %7ld, %5.2f %%\n", nreg, nreg*100.0/ntot); + printf("directories = %7ld, %5.2f %%\n", ndir, ndir*100.0/ntot); + printf("block special = %7ld, %5.2f %%\n", nblk, nblk*100.0/ntot); + printf("char special = %7ld, %5.2f %%\n", nchr, nchr*100.0/ntot); + printf("FIFOs = %7ld, %5.2f %%\n", nfifo, nfifo*100.0/ntot); + printf("symbolic links = %7ld, %5.2f %%\n", nslink,nslink*100.0/ntot); + printf("sockets = %7ld, %5.2f %%\n", nsock, nsock*100.0/ntot); + + exit(ret); +} + +/* + * Descend through the hierarchy, starting at "pathname". + * The caller's func() is called for every file. + */ + +#define FTW_F 1 /* file other than directory */ +#define FTW_D 2 /* directory */ +#define FTW_DNR 3 /* directory that can't be read */ +#define FTW_NS 4 /* file that we can't stat */ + +static char *fullpath; /* contains full pathname for every file */ + +static int /* we return whatever func() returns */ +myftw(char *pathname, Myfunc *func) +{ + fullpath = path_alloc(NULL); /* malloc's for PATH_MAX+1 bytes */ + /* ({Prog pathalloc}) */ + strcpy(fullpath, pathname); /* initialize fullpath */ + + return(dopath(func)); +} +/* + * Descend through the hierarchy, starting at "fullpath". + * If "fullpath" is anything other than a directory, we lstat() it, + * call func(), and return. For a directory, we call ourself + * recursively for each name in the directory. + */ +static int /* we return whatever func() returns */ +dopath(Myfunc* func) +{ + struct stat statbuf; + struct dirent *dirp; + DIR *dp; + int ret; + char *ptr; + + if (lstat(fullpath, &statbuf) < 0) + return(func(fullpath, &statbuf, FTW_NS)); /* stat error */ + + if (S_ISDIR(statbuf.st_mode) == 0) + return(func(fullpath, &statbuf, FTW_F)); /* not a directory */ + + /* + * It's a directory. First call func() for the directory, + * then process each filename in the directory. + */ + + if ( (ret = func(fullpath, &statbuf, FTW_D)) != 0) + return(ret); + + ptr = fullpath + strlen(fullpath); /* point to end of fullpath */ + *ptr++ = '/'; + *ptr = 0; + + if ( (dp = opendir(fullpath)) == NULL) + return(func(fullpath, &statbuf, FTW_DNR)); + /* can't read directory */ + + while ( (dirp = readdir(dp)) != NULL) { + if (strcmp(dirp->d_name, ".") == 0 || + strcmp(dirp->d_name, "..") == 0) + continue; /* ignore dot and dot-dot */ + + strcpy(ptr, dirp->d_name); /* append name after slash */ + + if ( (ret = dopath(func)) != 0) /* recursive */ + break; /* time to leave */ + } + ptr[-1] = 0; /* erase everything from slash onwards */ + + if (closedir(dp) < 0) + err_ret("can't close directory %s", fullpath); + + return(ret); +} +static int +myfunc(const char *pathname, const struct stat *statptr, int type) +{ + switch (type) { + case FTW_F: + switch (statptr->st_mode & S_IFMT) { + case S_IFREG: nreg++; break; + case S_IFBLK: nblk++; break; + case S_IFCHR: nchr++; break; + case S_IFIFO: nfifo++; break; + case S_IFLNK: nslink++; break; + case S_IFSOCK: nsock++; break; + case S_IFDIR: + err_dump("for S_IFDIR for %s", pathname); + /* directories should have type = FTW_D */ + } + break; + + case FTW_D: + ndir++; + break; + + case FTW_DNR: + err_ret("can't read directory %s", pathname); + break; + + case FTW_NS: + err_ret("stat error for %s", pathname); + break; + + default: + err_dump("unknown type %d for pathname %s", type, pathname); + } + + return(0); +} diff --git a/exercises/apue/others/ourhdr.h b/exercises/apue/others/ourhdr.h @@ -0,0 +1,108 @@ +/* Our own header, to be included *after* all standard system headers */ + +#ifndef __ourhdr_h +#define __ourhdr_h + +#include <sys/types.h> /* required for some of our prototypes */ +#include <stdio.h> /* for convenience */ +#include <stdlib.h> /* for convenience */ +#include <string.h> /* for convenience */ +#include <unistd.h> /* for convenience */ + +#define MAXLINE 4096 /* max line length */ + +#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) + /* default file access permissions for new files */ +#define DIR_MODE (FILE_MODE | S_IXUSR | S_IXGRP | S_IXOTH) + /* default permissions for new directories */ + +typedef void Sigfunc(int); /* for signal handlers */ + + /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */ +#if defined(SIG_IGN) && !defined(SIG_ERR) +#define SIG_ERR ((Sigfunc *)-1) +#endif + +#define min(a,b) ((a) < (b) ? (a) : (b)) +#define max(a,b) ((a) > (b) ? (a) : (b)) + + /* prototypes for our own functions */ +char *path_alloc(int *); /* {Prog pathalloc} */ +int open_max(void); /* {Prog openmax} */ +void clr_fl(int, int); /* {Prog setfl} */ +void set_fl(int, int); /* {Prog setfl} */ +void pr_exit(int); /* {Prog prexit} */ +void pr_mask(const char *); /* {Prog prmask} */ +Sigfunc *signal_intr(int, Sigfunc *);/* {Prog signal_intr_function} */ + +int tty_cbreak(int); /* {Prog raw} */ +int tty_raw(int); /* {Prog raw} */ +int tty_reset(int); /* {Prog raw} */ +void tty_atexit(void); /* {Prog raw} */ +#ifdef ECHO /* only if <termios.h> has been included */ +struct termios *tty_termios(void); /* {Prog raw} */ +#endif + +void sleep_us(unsigned int); /* {Ex sleepus} */ +ssize_t readn(int, void *, size_t);/* {Prog readn} */ +ssize_t writen(int, const void *, size_t);/* {Prog writen} */ +int daemon_init(void); /* {Prog daemoninit} */ + +int s_pipe(int *); /* {Progs svr4_spipe bsd_spipe} */ +int recv_fd(int, ssize_t (*func)(int, const void *, size_t)); + /* {Progs recvfd_svr4 recvfd_43bsd} */ +int send_fd(int, int); /* {Progs sendfd_svr4 sendfd_43bsd} */ +int send_err(int, int, const char *);/* {Prog senderr} */ +int serv_listen(const char *); /* {Progs servlisten_svr4 servlisten_44bsd} */ +int serv_accept(int, uid_t *); /* {Progs servaccept_svr4 servaccept_44bsd} */ +int cli_conn(const char *); /* {Progs cliconn_svr4 cliconn_44bsd} */ +int buf_args(char *, int (*func)(int, char **)); + /* {Prog bufargs} */ + +int ptym_open(char *); /* {Progs ptyopen_svr4 ptyopen_44bsd} */ +int ptys_open(int, char *); /* {Progs ptyopen_svr4 ptyopen_44bsd} */ +#ifdef TIOCGWINSZ +pid_t pty_fork(int *, char *, const struct termios *, + const struct winsize *); /* {Prog ptyfork} */ +#endif + +int lock_reg(int, int, int, off_t, int, off_t); + /* {Prog lockreg} */ +#define read_lock(fd, offset, whence, len) \ + lock_reg(fd, F_SETLK, F_RDLCK, offset, whence, len) +#define readw_lock(fd, offset, whence, len) \ + lock_reg(fd, F_SETLKW, F_RDLCK, offset, whence, len) +#define write_lock(fd, offset, whence, len) \ + lock_reg(fd, F_SETLK, F_WRLCK, offset, whence, len) +#define writew_lock(fd, offset, whence, len) \ + lock_reg(fd, F_SETLKW, F_WRLCK, offset, whence, len) +#define un_lock(fd, offset, whence, len) \ + lock_reg(fd, F_SETLK, F_UNLCK, offset, whence, len) + +pid_t lock_test(int, int, off_t, int, off_t); + /* {Prog locktest} */ + +#define is_readlock(fd, offset, whence, len) \ + lock_test(fd, F_RDLCK, offset, whence, len) +#define is_writelock(fd, offset, whence, len) \ + lock_test(fd, F_WRLCK, offset, whence, len) + +void err_dump(const char *, ...); /* {App misc_source} */ +void err_msg(const char *, ...); +void err_quit(const char *, ...); +void err_ret(const char *, ...); +void err_sys(const char *, ...); + +void log_msg(const char *, ...); /* {App misc_source} */ +void log_open(const char *, int, int); +void log_quit(const char *, ...); +void log_ret(const char *, ...); +void log_sys(const char *, ...); + +void TELL_WAIT(void); /* parent/child from {Sec race_conditions} */ +void TELL_PARENT(pid_t); +void TELL_CHILD(pid_t); +void WAIT_PARENT(void); +void WAIT_CHILD(void); + +#endif /* __ourhdr_h */ diff --git a/exercises/apue/others/pathalloc.c b/exercises/apue/others/pathalloc.c @@ -0,0 +1,36 @@ +#include <errno.h> +#include <limits.h> +#include "ourhdr.h" + +#ifdef PATH_MAX +static int pathmax = PATH_MAX; +#else +static int pathmax = 0; +#endif + +#define PATH_MAX_GUESS 1024 /* if PATH_MAX is indeterminate */ + /* we're not guaranteed this is adequate */ +char * +path_alloc(int *size) + /* also return allocated size, if nonnull */ +{ + char *ptr; + + if (pathmax == 0) { /* first time through */ + errno = 0; + if ( (pathmax = pathconf("/", _PC_PATH_MAX)) < 0) { + if (errno == 0) + pathmax = PATH_MAX_GUESS; /* it's indeterminate */ + else + err_sys("pathconf error for _PC_PATH_MAX"); + } else + pathmax++; /* add one since it's relative to root */ + } + + if ( (ptr = malloc(pathmax + 1)) == NULL) + err_sys("malloc error for pathname"); + + if (size != NULL) + *size = pathmax + 1; + return(ptr); +} diff --git a/exercises/apue/others/tellwait.c b/exercises/apue/others/tellwait.c @@ -0,0 +1,66 @@ +#include <signal.h> +#include "ourhdr.h" + +static volatile sig_atomic_t sigflag; + /* set nonzero by signal handler */ +static sigset_t newmask, oldmask, zeromask; + +static void +sig_usr(int signo) /* one signal handler for SIGUSR1 and SIGUSR2 */ +{ + sigflag = 1; + return; +} + +void +TELL_WAIT() +{ + if (signal(SIGUSR1, sig_usr) == SIG_ERR) + err_sys("signal(SIGINT) error"); + if (signal(SIGUSR2, sig_usr) == SIG_ERR) + err_sys("signal(SIGQUIT) error"); + + sigemptyset(&zeromask); + + sigemptyset(&newmask); + sigaddset(&newmask, SIGUSR1); + sigaddset(&newmask, SIGUSR2); + /* block SIGUSR1 and SIGUSR2, and save current signal mask */ + if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) + err_sys("SIG_BLOCK error"); +} + +void +TELL_PARENT(pid_t pid) +{ + kill(pid, SIGUSR2); /* tell parent we're done */ +} + +void +WAIT_PARENT(void) +{ + while (sigflag == 0) + sigsuspend(&zeromask); /* and wait for parent */ + + sigflag = 0; + /* reset signal mask to original value */ + if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) + err_sys("SIG_SETMASK error"); +} +void +TELL_CHILD(pid_t pid) +{ + kill(pid, SIGUSR1); /* tell child we're done */ +} + +void +WAIT_CHILD(void) +{ + while (sigflag == 0) + sigsuspend(&zeromask); /* and wait for child */ + + sigflag = 0; + /* reset signal mask to original value */ + if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) + err_sys("SIG_SETMASK error"); +} diff --git a/exercises/deitel/ch1-2/calc.c b/exercises/deitel/ch1-2/calc.c @@ -0,0 +1,20 @@ +/* Calcola il prodotto di tre interi */ +#include <stdio.h> + +/* Funzione principale */ +int main() +{ + int x, y, z, result; + + printf("Imetti tre interi: "); + scanf("%d%d%d", &x, &y, &z); + + result = x * y * z; + + printf("The product is"); + printf(" %d\n",result); + + return 0; + +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/calc2.c b/exercises/deitel/ch1-2/calc2.c @@ -0,0 +1,29 @@ +/* Esercizio 2.16 (Cap. 2) + * Calcola la somma, prodotto, differenza + * quoziente e resto di due interi */ + +#include <stdio.h> + +int main() +{ + int x, y; + + printf("\nDammi i 2 interi per il calcolo: "); + scanf("%d%d", &x, &y); + + printf("\nSomma: %d\n", x + y); + printf("Prodotto: %d\n", x * y); + + if (x > y) + printf("Differenza: %d\n", x - y); + + if (x < y) + printf("Differenza: %d\n", y - x); + + printf("Quoziente: %d\n", x / y); + printf("Resto: %d\n", x % y); + + return 0; + +} /* E0F main **/ + diff --git a/exercises/deitel/ch1-2/cerchio.c b/exercises/deitel/ch1-2/cerchio.c @@ -0,0 +1,21 @@ +/* Esercizio 2.20 (Cap. 2) + Leggo il raggio di un cerchio e calcolo il diametro, + la circonferenza e l'aria dello stesso */ + +#include <stdio.h> + +int main() +{ + int raggio; + + printf("Raggio del cerchio: "); + scanf("%d", &raggio); + + printf("Diametro: %f\n", raggio * 2.0); + printf("Circonferenza: %f\n", 3.14159 * 2 * raggio); + printf("Area %f\n", raggio*raggio * 3.14159); + + return 0; + +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/getintbychar.c b/exercises/deitel/ch1-2/getintbychar.c @@ -0,0 +1,17 @@ +/* Esercizio 2.29 (Cap. 2) + Determina l'intero equivalente almeno di: + A B C a b c 0 1 2 $ * + / e dello spazio. */ + +#include <stdio.h> + +int main() +{ + printf("A = %d\tB = %d\tC = %d\n", 'A', 'B', 'C'); + printf("a = %d\tb = %d\tc = %d\n", 'a', 'b', 'c'); + printf("0 = %d\t1 = %d\t2 = %d\n", '0', '1', '2'); + printf("$ = %d\t* = %d\t+ = %d\n", '$', '*', '+'); + printf("/ = %d\t@ = %d\t^ = %d\n", '/', '@', '^'); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/graph.c b/exercises/deitel/ch1-2/graph.c @@ -0,0 +1,21 @@ +/* Esercizio 2.21 (Cap. 2) + Visualizzo una scatola, un ovale, + una freccia e un diamante. */ + +#include <stdio.h> + +int main() +{ + printf("*********\t *** \t *\t *\n"); + printf("*\t*\t * *\t ***\t * *\n"); + printf("*\t*\t* *\t*****\t * *\n"); + printf("*\t*\t* *\t *\t * *\n"); + printf("*\t*\t* *\t *\t * *\n"); + printf("*\t*\t* *\t *\t * *\n"); + printf("*\t*\t* *\t *\t * *\n"); + printf("*\t*\t * *\t *\t * *\n"); + printf("*********\t *** \t *\t *\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/iniziali b/exercises/deitel/ch1-2/iniziali @@ -0,0 +1,25 @@ +Esercizio 2.25 (Cap. 2) + + CCCCCCC + C C +C C +C C +C C +C C + +MMMMMMMMMMM + M + M + MM + M + M +MMMMMMMMMMM + +AAAAAAAAA + A A + A A + A A + A A + A A +AAAAAAAA + diff --git a/exercises/deitel/ch1-2/largegual.c b/exercises/deitel/ch1-2/largegual.c @@ -0,0 +1,25 @@ +/* Esercizio 2.18 (Cap. 2) + * Chiedo due interi e mostro quello maggiore seguito + * dal letterale "is larger". Se i numeri sono uguali + * stampo il messaggio corrispondente. */ + +#include <stdio.h> + +int main() +{ + int a, b; + + printf("Inserisci 2 interi: "); + scanf("%d%d", &a, &b); + + if (a > b) + printf("%d is larger\n", a); + if (a < b) + printf("%d is larger\n", b); + if (a == b) + printf("These numbers are equal.\n"); + + return 0; + +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/multiplo.c b/exercises/deitel/ch1-2/multiplo.c @@ -0,0 +1,21 @@ +/* Esercizio 2.26 (Cap. 2) + Dati due interi determino e visualizzo + se il primo e' multiplo del secondo. */ + +#include <stdio.h> + +int main() +{ + int a, b; + + printf("Dammi 2 interi: "); + scanf("%d%d", &a, &b); + + if (a%b == 0) + printf("%d e' multiplo di %d\n", a, b); + if (a%b != 0) + printf("%d non e' multiplo di %d\n", a, b); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/pairs.c b/exercises/deitel/ch1-2/pairs.c @@ -0,0 +1,21 @@ +/* Esercizio 2.24 (Cap. 2) + Dato un intero calcola se e' pari o dispari. */ + +#include <stdio.h> + +int main() +{ + int n; + + printf("Inserisci un intero: "); + scanf("%d", &n); + + if (n%2 == 0) + printf("%d e' pari\n", n); + + if (n%2 != 0) + printf("%d e' dispari\n", n); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/powtab.c b/exercises/deitel/ch1-2/powtab.c @@ -0,0 +1,24 @@ +/* Esercizio 2.31 (Cap. 2) + Mostra una tabella con il calcolo dei + quadrati e cubi dei numeri da 0 a 10. */ + +#include <stdio.h> + +int main() +{ + printf("numero\tquadrato\tcubo\n"); + printf("0\t0\t\t0\n"); + printf("1\t1\t\t1\n"); + printf("2\t%d\t\t%d\n", 2*2, 2*2*2); + printf("3\t%d\t\t%d\n", 3*3, 3*3*3); + printf("4\t%d\t\t%d\n", 4*4, 4*4*4); + printf("5\t%d\t\t%d\n", 5*5, 5*5*5); + printf("6\t%d\t\t%d\n", 6*6, 6*6*6); + printf("7\t%d\t\t%d\n", 7*7, 7*7*7); + printf("8\t%d\t\t%d\n", 8*8, 8*8*8); + printf("9\t%d\t\t%d\n", 9*9, 9*9*9); + printf("10\t%d\t\t%d\n", 10*10, 10*10*10); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/print1-4.c b/exercises/deitel/ch1-2/print1-4.c @@ -0,0 +1,19 @@ +/* Esercizio 2.17 (Cap. 2) + * Visualizzo i numeri da 1 a 4 sulla stessa riga */ + +#include <stdio.h> + +int main() +{ + printf("a) 1, 2, 3, 4\n"); /* Primo metodo */ + printf("b) %d, %d, %d, %d\n", 1, 2, 3, 4); /* Secondo metodo */ + + /* Terzo medoto */ + printf("c) 1, "); + printf("2, "); + printf("3, "); + printf("4\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/scacchiera.c b/exercises/deitel/ch1-2/scacchiera.c @@ -0,0 +1,23 @@ +/* Esercizio 2.27 (Cap. 2) + Stampa una scacchiera prima con 8 printf(1), + infine col minor numero di printf(1) possibiile. */ + +#include <stdio.h> + +int main() +{ + printf("* * * * * * * *\n"); + printf(" * * * * * * * *\n"); + printf("* * * * * * * *\n"); + printf(" * * * * * * * *\n"); + printf("* * * * * * * *\n"); + printf(" * * * * * * * *\n"); + printf("* * * * * * * *\n"); + printf(" * * * * * * * *\n\n"); + + printf("* * * * * * * *\n * * * * * * * *\n* * * * * * * *\n * * * * * * * *\n" + "* * * * * * * *\n * * * * * * * *\n* * * * * * * *\n * * * * * * * *\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/smallarge5.c b/exercises/deitel/ch1-2/smallarge5.c @@ -0,0 +1,45 @@ +/* Esercizio 2.23 (Cap. 2) + Determina il maggiore e il minore + nell'insieme di 5 interi. */ + +#include <stdio.h> + +int main() +{ + int a, b, c, d, e; + int small, large; + + printf("Dammi 5 interi: "); + scanf("%d%d%d%d%d", &a, &b, &c, &d, &e); + + /* Trovo il maggiore */ + if (a > b) + large = a; + if (b > a) + large = b; + if (c > large) + large = c; + if (d > large) + large = d; + if (e > large) + large = e; + + /* Trovo il minore */ + if (a > b) + small = b; + if (a < b) + small = a; + if (c < small) + small = c; + if (d < small) + small = d; + if (e < small) + small = e; + + /* Stampo i risultati */ + printf("Maggiore: %d\n", large); + printf("Minore: %d\n", small); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/smpmm.c b/exercises/deitel/ch1-2/smpmm.c @@ -0,0 +1,45 @@ +/* Esercizio 2.19 (Cap. 2) + Visualizza la somma, media, prodotto, + minore e maggiore di 3 interi. */ + +#include <stdio.h> + +int main() +{ + int a, b, c; + int largest, smallest; + + printf("Input three different integers: "); + scanf("%d%d%d", &a, &b, &c); + + printf("Sum is %d\n", a + b + c); + printf("Average is %d\n", (a + b + c) / 3); + printf("Product is %d\n", a * b * c); + + /* Trovo il > e il < di tre numeri (a, b, c) */ + + if (a > b) + largest = a; + + if (a < b) + largest = b; + + if (c > largest) + largest = c; + + if (a < b) + smallest = a; + + if (a > b) + smallest = b; + + if (c < smallest) + smallest = c; + + printf("Smallest: %d\n", smallest); + printf("Largest: %d\n", largest); + + return 0; + +} /* E0F main */ + diff --git a/exercises/deitel/ch1-2/splitint.c b/exercises/deitel/ch1-2/splitint.c @@ -0,0 +1,27 @@ +/* Esercizio 2.30 (Cap. 2) + Dato un intero di 5 cifre stampare una cifra alla volta + ognuna separata da 3 spazi: 42339 = 4 2 3 3 9. */ + +#include <stdio.h> + +int main() +{ + int n; + int n1, n2, n3, n4, n5; + + printf("Dammi un intero di 5 cifre: "); + scanf("%d", &n); + + /* Spezzetto l'intero nelle sue singole cifre */ + n1 = n / 10000; + n2 = (n / 1000) % 10; + n3 = (n / 100) % 10; + n4 = (n / 10) % 10; + n5 = n % 10; + + /* Stampo le cifre */ + printf("%d %d %d %d %d\n",n1, n2, n3, n4, n5); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch10/10.3 b/exercises/deitel/ch10/10.3 @@ -0,0 +1,31 @@ +/* Exercise 10.3 */ + +a) + struct part { + int partNumber; + char partName[25]; + }; + +b) + typedef struct part Part; + +c) + Part a, b[10], *ptr; + +d) + printf("Number of part: "); + scanf("%d", &a.partNumber); + + printf("Name of part: "); + scanf("%s", &a.partName); + +e) + b[3] = a; + +f) + ptr = b; + +g) + printf("P.No: %d\n", ptr[3]->partNumber); + printf("P.Na: %s\n", ptr[3]->partName); + diff --git a/exercises/deitel/ch10/10.5 b/exercises/deitel/ch10/10.5 @@ -0,0 +1,55 @@ +/* Exercise 10.5 */ + +a) + struct inventory { + char partName[30]; + int partNumber + int stock + int reorder; + double price; + }; + +b) + union data { + char c; + short s; + long b; + float f; + double d; + }; + +c) + struct address { + char streetAddress[25]; + char city[20]; + char state[3]; + char zipCode[6]; + }; + +d) + struct student { + char firstName[15]; + char lastName[15]; + struct address homeAddress; + }; + +e) + struct test { + int a: 1; + int b: 1; + int c: 1; + int d: 1; + int e: 1; + int f: 1; + int g: 1; + int h: 1; + int i: 1; + int j: 1; + int k: 1; + int l: 1; + int m: 1; + int n: 1; + int o: 1; + int p: 1; + }; + diff --git a/exercises/deitel/ch10/10.6 b/exercises/deitel/ch10/10.6 @@ -0,0 +1,37 @@ +/* Exercise 10.6 */ + +struct customer { + char lastName[15]; + char firstName[15]; + int customerNumber; + + struct { + char phoneNumber[11]; + char address[50]; + char city[15]; + char state[3]; + char zipCode[6]; + } personal; + +} custmerRecord, *customerPtr; + +customerPtr = &customerRecord; + + +a) customerRecord.lastName; +b) customerPtr->lastName; +c) customerRecor.firstName; +d) customerPtr->firstName; +e) customerRecor.customerNumber; +f) customerPtr->customerNumber; +g) customerRecord.personal.phoneNumber; +h) customerPtr->personal.phoneNumber; +i) customerRecord.personal.address; +j) customerPtr->personal.address; +k) customerRecord.personal.city; +l) customerPtr->personal.city; +m) customerRecord.personal.state; +n) customerPtr->personal.state; +o) customerRecord.personal.zipCode; +p) customerPtr->personal.zipCode; + diff --git a/exercises/deitel/ch10/checkunion.c b/exercises/deitel/ch10/checkunion.c @@ -0,0 +1,24 @@ +/* Exercise 10.8 */ + +#include <stdio.h> + +typedef union values { + char c; + short s; + int i; + long b; +} List; + +int main(void) +{ + List lval; + + printf("Char short int long: "); + scanf("%c%hi%d%ld", &lval.c, &lval.s, &lval.i, &lval.b); + + printf("Char: %c\nShort: %hi\nInt: %d\nLong: %ld\n", + lval.c, lval.s, lval.i, lval.b); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch10/fig10_07_mod.c b/exercises/deitel/ch10/fig10_07_mod.c @@ -0,0 +1,46 @@ +/* Exercise 10.11 */ + +/* Fig. 10.7: fig10_07.c + Printing an unsigned integer in bits */ +#include <stdio.h> + +typedef unsigned u_int; /* Portable definition */ +void displayBits( u_int value ); /* prototype */ + +int main(void) +{ + u_int x; /* variable to hold user input */ + + printf( "Enter an unsigned integer: " ); + scanf( "%lu", &x ); + + displayBits( x ); + + return 0; /* indicates successful termination */ + +} /* end main */ + +/* display bits of an unsigned integer value */ +void displayBits( u_int value ) +{ + u_int c; /* counter */ + + /* define displayMask and left shift 31 bits */ + u_int displayMask = 1 << 31; + + printf( "%10lu = ", value ); + + /* loop through bits */ + for ( c = 1; c <= 32; c++ ) { + putchar( value & displayMask ? '1' : '0' ); + value <<= 1; /* shift value left by 1 */ + + if ( c % 8 == 0 ) { /* output space after 8 bits */ + putchar( ' ' ); + } /* end if */ + + } /* end for */ + + putchar( '\n' ); +} /* end function displayBits */ + diff --git a/exercises/deitel/ch10/fig10_16_mod.c b/exercises/deitel/ch10/fig10_16_mod.c @@ -0,0 +1,79 @@ +/* Exercise 10.7 */ + +/* Fig. 10.16: fig10_16.c + Representing cards with bit fields in a struct */ + +#include <stdio.h> +#include <stdlib.h> + +/* bitCard structure definition with bit fields */ +struct bitCard { + unsigned face : 4; /* 4 bits; 0-15 */ + unsigned suit : 2; /* 2 bits; 0-3 */ + unsigned color : 1; /* 1 bit; 0-1 */ +}; /* end struct bitCard */ + +typedef struct bitCard Card; /* new type name for struct bitCard */ + +void fillDeck( Card * const wDeck ); /* prototype */ +void shuffle( Card * const wDeck ); /* prototype */ +void deal( const Card * const wDeck ); /* prototype */ + +int main(void) +{ + Card deck[ 52 ]; /* create array of Cards */ + + fillDeck( deck ); + deal( deck ); + + return 0; /* indicates successful termination */ + +} /* end main */ + +/* initialize Cards */ +void fillDeck( Card * const wDeck ) +{ + int i; /* counter */ + + /* loop through wDeck */ + for ( i = 0; i <= 51; i++ ) { + wDeck[ i ].face = i % 13; + wDeck[ i ].suit = i / 13; + wDeck[ i ].color = i / 26; + } /* end for */ + +} /* end function fillDeck */ + +/* shuffle the cards */ +void shuffle( Card * const wDeck ) +{ + int i, j; + + Card temp; + + for(i = 0; i < 52; i++) { + j = rand() % 52; + temp = wDeck[i]; + wDeck[i] = wDeck[j]; + wDeck[j] = temp; + } + +} /* end function shuffle */ + +/* output cards in two column format; cards 0-25 subscripted with + k1 (column 1); cards 26-51 subscripted k2 (column 2) */ +void deal( const Card * const wDeck ) +{ + int k1; /* subscripts 0-25 */ + int k2; /* subscripts 26-51 */ + + /* loop through wDeck */ + for ( k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) { + printf( "Color:%2d Suit:%2d Card:%3d ", + wDeck[ k1 ].color, wDeck[ k1 ].face, wDeck[ k1 ].suit ); + printf( "Color:%2d Suit:%2d Card:%3d\n", + wDeck[ k2 ].color, wDeck[ k2 ].face, wDeck[ k2 ].suit ); + } /* end for */ + +} /* end function deal */ + diff --git a/exercises/deitel/ch10/packc.c b/exercises/deitel/ch10/packc.c @@ -0,0 +1,84 @@ +/* Exercise 10.13/14 */ + +#include <stdio.h> + +typedef unsigned u_int; + +void pbits(u_int n); +u_int packC(char a, char b); +void UnpackC(u_int pack, char *a, char *b); + +int main(void) +{ + char a, b; + u_int result; + + /* Take the chars */ + printf("two chars: "); + scanf("%c%*c%c", &a, &b); + + /* Print the values in bits */ + printf("pbits(%d):\t", a); + pbits(a); + + putchar('\n'); + + printf("pbits(%d):\t", b); + pbits(b); + + putchar('\n'); + + /* Pack the chars and print the values */ + result = packC(a, b); + + printf("pbits(%u):\t", result); + pbits(result); + + putchar('\n'); + + a = b = '\0'; /* Clean the variables */ + + /* UnPack the chars and print the values */ + UnpackC(result, &a, &b); + printf("Uncompressed: a[%c] b[%c]\n", a, b); + + return 0; +} /* E0F main */ + +/* Print a number in bits */ +void pbits(u_int n) +{ + u_int mask = 1 << 31; + int i; + + for(i = 1; i <= 32; i++) { + printf("%u", n & mask ? 1 : 0); + + if( !(i % 8) ) + putchar(' '); + + n <<= 1; + } + +} /* eof pbits() */ + +/* Compress two char to an unsigned */ +u_int packC(char a, char b) +{ + return (a << 8) | b; +} /* eof packC() */ + +/* UnCompress and unsigned to two chars */ +void UnpackC(u_int pack, char *a, char *b) +{ + u_int num = pack; + + num &= 65280; + *a = num >>= 8; + + num = pack; + num &= 255; + *b = pack; + +} /* eof UnpackC() */ + diff --git a/exercises/deitel/ch10/packc4.c b/exercises/deitel/ch10/packc4.c @@ -0,0 +1,92 @@ +/* Exercise 10.15/16 */ + +#include <stdio.h> +#include <string.h> + +typedef unsigned u_int; + +void pbits(u_int n); +u_int packC(char *s); +void UnpackC(u_int pack, char *s); + +int main(void) +{ + int i; + char string[5] = { 0 }; + u_int result; + + /* Take the chars */ + printf("4 chars: "); + scanf("%s", string); + + /* Print the values in bits */ + for(i = 0; i < 4; i++) { + printf("pbits(%d):\t\t", (int)string[i]); + pbits(string[i]); + putchar('\n'); + } + + /* Pack the chars and print the values */ + result = packC(string); + + printf("\npbits(%u):\t", result); + pbits(result); + + putchar('\n'); + + printf("string: %s\n", string); + + /* UnPack the chars and print the values */ + UnpackC(result, string); + printf("\nUncompressed: %s\n", string); + + return 0; +} /* E0F main */ + +/* Print a number in bits */ +void pbits(u_int n) +{ + u_int mask = 1 << 31; + int i; + + for(i = 1; i <= 32; i++) { + printf("%u", n & mask ? 1 : 0); + + if( !(i % 8) ) + putchar(' '); + + n <<= 1; + } + +} /* eof pbits() */ + +/* Compress [1,4] char to an unsigned */ +u_int packC(char *s) +{ + int i; + u_int ret = s[0]; + + for(i = 1; i < 4; i++) { + ret <<= 8; + ret |= s[i]; + } + + return ret; +} /* eof packC() */ + +/* UnCompress and unsigned to [1,4] chars */ +void UnpackC(u_int pack, char *s) +{ + int i; + u_int mask = 255 << 24; + + s[0] = (mask & pack) >> 24; + + for(i = 0; i < 3; i++) { + s[i] = (mask & pack) >> (24 - i * 8); + mask >>= 8; + } + s[i] = (mask & pack) >> (24 - i * 8); + +} /* eof UnpackC() */ + diff --git a/exercises/deitel/ch10/portablepbits.c b/exercises/deitel/ch10/portablepbits.c @@ -0,0 +1,42 @@ +/* Exercise 10.18 */ + +#include <stdio.h> + +typedef unsigned u_int; + +void pbits(u_int n); + + +int main(void) +{ + u_int num; + + num = 12345; + + pbits(num); + putchar('\n'); + + return 0; +} /* E0F main */ + +/* Print a number in bits */ +void pbits(u_int n) +{ + u_int mask = 1 << 31; + int i; + + for(i = 1; i <= 32; i++) { + if( sizeof(int) == 4 ) + printf("%u", n & mask ? 1 : 0); + else + printf("%ul", n & mask ? 1 : 0); + + if( !(i % 8) ) + putchar(' '); + + n <<= 1; + } + +} /* eof pbits() */ + + diff --git a/exercises/deitel/ch10/power2.c b/exercises/deitel/ch10/power2.c @@ -0,0 +1,49 @@ +/* Exercise 10.12 */ + +#include <stdio.h> + +typedef unsigned u_int; + +void pbits(u_int n); +u_int power2(u_int n, int pow); + +int main(void) +{ + u_int num; + int pow; + + printf("Num and pow: "); + scanf("%u%d", &num, &pow); + + num = power2(num, pow); + + printf("pbits(%u): ", num); + pbits(num); + + printf("\n"); + + return 0; +} /* E0F main */ + +/* Print a number in bits */ +void pbits(u_int n) +{ + u_int mask = 1 << 31; + int i; + + for(i = 1; i <= 32; i++) { + printf("%u", n & mask ? 1 : 0); + + if( !(i % 8) ) + putchar(' '); + + n <<= 1; + } + +} /* eof pbits() */ + +u_int power2(u_int n, int pow) +{ + return n <<= pow; +} + diff --git a/exercises/deitel/ch10/reverseBits.c b/exercises/deitel/ch10/reverseBits.c @@ -0,0 +1,50 @@ +/* Exercise 10.17 */ + +#include <stdio.h> + +typedef unsigned u_int; + +void pbits(u_int n); +u_int reverseBits(u_int num); + +int main(void) +{ + u_int num; + + printf("Give me a number: "); + scanf("%u", &num); + + printf("before:\t"); + pbits(num); + putchar('\n'); + + printf("after:\t"); + pbits( reverseBits(num) ); + putchar('\n'); + + return 0; +} /* E0F main */ + +/* Print a number in bits */ +void pbits(u_int n) +{ + u_int mask = 1 << 31; + int i; + + for(i = 1; i <= 32; i++) { + printf("%u", n & mask ? 1 : 0); + + if( !(i % 8) ) + putchar(' '); + + n <<= 1; + } + +} /* eof pbits() */ + +/* Reverse the bits order to an u_int number */ +u_int reverseBits(u_int num) +{ + return ~num; +} /* eof reverseBits()*/ + diff --git a/exercises/deitel/ch10/shift.c b/exercises/deitel/ch10/shift.c @@ -0,0 +1,41 @@ +/* Exercise 10.10 */ + +#include <stdio.h> + +void tobits(int n); + +int main(void) +{ + int num = 9; + + printf("tobits(%d):\t", num); + tobits(num); + + num >>= 4; + printf("\n"); + + printf("tobits(%d):\t", num); + tobits(num); + + printf("\n"); + + return 0; +} /* E0F main */ + +/* Print a number in bits */ +void tobits(int n) +{ + int i; + unsigned mask = 1 << 31; + + for(i = 1; i <= 32; i++) { + printf("%d", n & mask ? 1 : 0); + + if( !(i % 8) ) + putchar(' '); + + n <<= 1; + } + +} /* eof tobits() */ + diff --git a/exercises/deitel/ch10/unionfloat.c b/exercises/deitel/ch10/unionfloat.c @@ -0,0 +1,20 @@ +/* Exercise 10.8 */ + +#include <stdio.h> + +union floatingPoint { + float f; + double d; + long double x; +} fp; + +int main(void) +{ + printf("Float double long_double: "); + scanf("%f%lf%Lf", &fp.f, &fp.d, &fp.x); + + printf("float: %f\ndouble: %f\nlong double: %Lf\n", fp.f, fp.d, fp.x); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch11/datasize.c b/exercises/deitel/ch11/datasize.c @@ -0,0 +1,32 @@ +/* Exercise 11.16 */ + +#include <stdio.h> +#include <stdlib.h> + +#define BUF 255 + +int main(void) +{ + FILE *fd; + + if( (fd = fopen("datasize.dat", "w")) == NULL) { + printf("%s: cannot open the file\n", "datasize.dat"); + exit(-1); + } + + fprintf(fd, "%-30s%4s\n", "Data type", "Size"); + fprintf(fd, "%-30s%4d\n", "char", sizeof(char)); + fprintf(fd, "%-30s%4d\n", "unsigned char", sizeof(unsigned char)); + fprintf(fd, "%-30s%4d\n", "short int", sizeof(short int)); + fprintf(fd, "%-30s%4d\n", "unsigned short int", sizeof(unsigned short int)); + fprintf(fd, "%-30s%4d\n", "int", sizeof(int)); + fprintf(fd, "%-30s%4d\n", "unsigned int", sizeof(unsigned int)); + fprintf(fd, "%-30s%4d\n", "long int", sizeof(long int)); + fprintf(fd, "%-30s%4d\n", "unsigned long int", sizeof(unsigned long int)); + fprintf(fd, "%-30s%4d\n", "float", sizeof(float)); + fprintf(fd, "%-30s%4d\n", "double", sizeof(double)); + fprintf(fd, "%-30s%4d\n", "long double", sizeof(long double)); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch11/esimpletron2.c b/exercises/deitel/ch11/esimpletron2.c @@ -0,0 +1,519 @@ +/* Exercise 11.17 */ + +/* The Extended Simpletron (and LMS) implementation2 */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <math.h> + +#define MEMSIZE 1000 +#define MAXWORD 7 + +#define DUMP "es2.dump" /* Dump file */ + +/* Input/Output */ +#define READ 10 +#define WRITE 11 +#define NEWLINE 12 +#define SREAD 13 +#define SWRITE 14 + +/* Loading/Storing */ +#define LOAD 20 +#define STORE 21 + +/* Arithmetical */ +#define ADD 30 +#define SUBTRACT 31 +#define DIVIDE 32 +#define MULTIPLY 33 +#define REST 34 +#define POWER 35 + +/* Reference and control */ +#define BRANCH 40 +#define BRANCHNEG 41 +#define BRANCHZERO 42 +#define HALT 43 + +int checkword(int word, int size); +void dump(float acc, int icounter, float mem[]); +int r_htoi(const char string[]); +char * p_itoh(int num, char str[], int z); + +int main(void) +{ + char s_mem[MAXWORD] = { 0 }; + float memory[MEMSIZE] = { 0 }, accumulator = 0; + + FILE *fd; + char infile[30] = { 'x' }; + + int operationCode = 0, instructionRegister = 0, operand = 0; + int i, j, k, err = 0; + float t_val = 0, f_tmp; + + while((*infile != 'y' && *infile != 'n') && strlen(infile) == 1) { + printf("Enter in interactive mode (y/n): "); + scanf("%c%*c", infile); + } + + if(infile[0] == 'n') { + + printf("Input file: "); + scanf("%s", infile); + + if( (fd = fopen(infile, "r")) == NULL) { + printf("%s: cannot open the file\n", infile); + exit(-1); + } + } + else + infile[0] = '\0'; + + printf("*** Welcome to the Simpletron! ***\n" + "*** Please enter your program one instruction ***\n" + "*** (or data word) at a time. I will type the ***\n" + "*** location number and a question mark (?). ***\n" + "*** You then type the word for that location. ***\n" + "*** Use the sentinel -999999 to stop entering ***\n" + "*** your program. ***\n"); + + for(i = 0; i < MEMSIZE; i++) { + while(1) { + + /* Interactive mode */ + if( infile[0] == '\0' ) { + printf("%.2d ?? ", i); + scanf("%s", s_mem); + } + else + /* Non-interactive mode (read from a file) */ + fscanf(fd, "%s", s_mem); + + memory[i] = r_htoi(s_mem); + + if(memory[i] == -999999) { + memory[i] = 0; + i = MEMSIZE; /* Terminate the for loop */ + break; + } + + if(s_mem[0] != '+') { + printf("*** Invalid instruction: %s\n", s_mem); + printf("*** Please use '+' or exit.\n"); + + /* If is in non-interactive mode, exit */ + if( infile[0] != '\0' ) + exit(-1); + + continue; + } + + if( checkword((int)memory[i], MEMSIZE) ) { + printf("*** Invalid instruction: +%.0f\n" + "*** Please retype it or exit.\n", memory[i]); + } + else + break; + + } /* end while */ + } /* end for (i) */ + + printf("*** Program loading completed ***\n" + "*** Program execution begins ***\n"); + + for(i = 0; i < MEMSIZE; i++) { + instructionRegister = (int)memory[i]; + + operationCode = + instructionRegister / (instructionRegister <= 9999 ? 100 : 1000); + operand = + instructionRegister % (instructionRegister <= 9999 ? 100 : 1000); + + /* this is required because after the switch() + statement the 'i' counter is incremented of 1. */ + if(operationCode >= BRANCH) + --operand; + + switch(operationCode) { + case READ: + printf("\nInsert a word: "); + scanf("%f", &memory[operand]); + + break; + case WRITE: + printf("\nMemory location: %.2d\nWord: %.2f\n", + operand, memory[operand]); + + break; + case NEWLINE: + printf("\n"); + break; + case SREAD: + /* If this instruction is used then HALT is required */ + printf("\nInsert a string: "); + scanf("%s", s_mem); + + if(strlen(s_mem) > 3) { + err = 3; + break; + } + + for(j = 0; (unsigned)j < strlen(s_mem); j++) { + if((int)s_mem[j] > 99) { + err = 4; + t_val = j; + break; + } + } + memory[operand] = 0; + + for(j = strlen(s_mem), k = 1; j >= 0; k *= 100, j--) + memory[operand] += s_mem[j] * k; + + for(t_val = 0.1, k = 1; k < memory[operand]; t_val *= 0.10, k *= 10) ; + t_val /= 0.10; + + memory[operand] *= t_val; + memory[operand] += strlen(s_mem); + + break; + case SWRITE: + printf("\nMemory location: %.0f\nWord: ", memory[operand]); + for(j = (int)memory[operand], t_val = 100; j ; t_val *= 100, j--) { + f_tmp = memory[operand] * t_val; + k = (int)f_tmp % 100; + printf("%c", k); + } + printf("\n"); + + break; + case LOAD: + accumulator = memory[operand]; + break; + case STORE: + memory[operand] = accumulator; + break; + + case ADD: + accumulator += memory[operand]; + + break; + case SUBTRACT: + accumulator -= memory[operand]; + + break; + case DIVIDE: + if( !memory[operand] ) + err = 2; + else + accumulator /= memory[operand]; + + break; + case MULTIPLY: + accumulator *= memory[operand]; + + break; + case REST: + accumulator = (int)accumulator % (int)memory[operand]; + + break; + + case POWER: + accumulator = pow(accumulator, memory[operand]); + break; + + case BRANCH: + i = operand; + break; + case BRANCHNEG: + if(accumulator < 0) + i = operand; + + break; + case BRANCHZERO: + if(!accumulator) + i = operand; + + break; + + case HALT: + i = MEMSIZE; /* terminate the for loop */ + /* dump(accumulator, i, memory); */ + + break; + case 0: + break; + + default: + printf("*** unknown error: %d\n", instructionRegister); + dump(accumulator, i, memory); + printf("\nAre'nt you using HALT (+4300)?\n"); + exit(-1); + } + + if(accumulator > MEMSIZE * MEMSIZE - 1 || + accumulator < MEMSIZE * -MEMSIZE + 1) + err = 1; + + if(err) { /* Error messages manager */ + printf("\n*** "); + switch(err) { + case 1: + printf("Out of the accumulator limit"); + break; + case 2: + printf("Attempt to divide by zero"); + break; + case 3: + printf("You can put max 3 numbers for memory location"); + break; + case 4: + printf("This ASCII code is too long: %d (%c)", + s_mem[(int)t_val], s_mem[(int)t_val]); + } + + printf(" ***\n"); + + printf("*** Simpletron execution abnormally terminated ***\n"); + dump(accumulator, i, memory); + exit(-1); + } + + } /* end for (i) */ + + dump(accumulator, i, memory); + printf("\n*** Simpletron execution terminated ***\n"); + + return 0; +} /* E0F main */ + +/* Check if a "word" is correct */ +int checkword(int word, int size) +{ + if( word < 0 || word >= MEMSIZE * MEMSIZE || + word % (word <= 9999 ? 100 : 1000) >= size ) { + return 1; + } + + switch(word / (word <= 9999 ? 100 : 1000)) { + case READ: + case WRITE: + case NEWLINE: + case SREAD: + case SWRITE: + case LOAD: + case STORE: + case ADD: + case SUBTRACT: + case DIVIDE: + case MULTIPLY: + case REST: + case POWER: + case BRANCH: + case BRANCHNEG: + case BRANCHZERO: + case HALT: + case 0: + break; + default: + return 1; + + } /* end switch (word) */ + + return 0; + +} /* eof checkword() */ + +/* Show a dump of the current memory state */ +void dump(float acc, int icounter, float mem[]) +{ + int i, j; + char string[6] = { 0 }; + + FILE *fd; + + if( (fd = fopen(DUMP, "w")) == NULL) { + printf("%s: cannot open the file\ndumping..", DUMP); + } + + fprintf(fd, "\nREGISTERS:\n"); + fprintf(stdout, "\nREGISTERS:\n"); + + fprintf(fd, + "accumulator\t\t%c%s\n", acc < 0 ? '-' : '+', p_itoh(acc, string, 4)); + fprintf(stdout, + "accumulator\t\t%c%s\n", acc < 0 ? '-' : '+', p_itoh(acc, string, 4)); + + fprintf(fd, "instructionCounter\t%s\n", p_itoh(icounter, string, 2)); + fprintf(stdout, "instructionCounter\t%s\n", p_itoh(icounter, string, 2)); + + fprintf(fd, "instructionRegister\t%c%s\n", mem[icounter] < 0 ? '-' : '+', + p_itoh(mem[icounter] < 0 ? -mem[icounter] : mem[icounter], string, 4)); + fprintf(stdout, "instructionRegister\t%c%s\n", mem[icounter] < 0 ? '-' : '+', + p_itoh(mem[icounter] < 0 ? -mem[icounter] : mem[icounter], string, 4)); + + fprintf(fd, + "operationCode\t\t%s\n", p_itoh(mem[icounter] / 100, string, 2)); + fprintf(stdout, + "operationCode\t\t%s\n", p_itoh(mem[icounter] / 100, string, 2)); + fprintf(fd, + "operand\t\t\t%s\n", p_itoh((int)mem[icounter] % 100, string, 2)); + fprintf(stdout, + "operand\t\t\t%s\n", p_itoh((int)mem[icounter] % 100, string, 2)); + + fprintf(fd, "\nMEMORY:\n"); + fprintf(stdout, "\nMEMORY:\n"); + + /* Print the header */ + printf("%3c", ' '); + for(i = 0; i < 10; i++) { + fprintf(fd, "%5d ", i); + fprintf(stdout, "%5d ", i); + } + fprintf(fd, "\n"); + fprintf(stdout, "\n"); + + for(i = 0; i < MEMSIZE; i += 10) { + printf("%.3d", i); + for(j = i; j < i+10; j++) { + fprintf(fd, " %c%s", mem[j] < 0 ? '-' : '+', + p_itoh(mem[j] < 0 ? -mem[j] : mem[j], string, 4)); + fprintf(stdout, " %c%s", mem[j] < 0 ? '-' : '+', + p_itoh(mem[j] < 0 ? -mem[j] : mem[j], string, 4)); + } + fprintf(fd, "\n"); + fprintf(stdout, "\n"); + } + +} /* eof dump() */ + +int r_htoi(const char string[]) +{ + int i, num = 0, n = 1; + char s[1] = { 0 }; + + for(i = strlen(string) - 1; i >= 0; i--) { + if(string[i] >= 'A' && string[i] <= 'F') + n *= 10; + + n *= 10; + } + + n /= 10; + + for(i = 0; i < 7; n /= 10, i++) { + + if(string[i] >= 'A' && string[i] <= 'F') { + num += 1 * n; + n /= 10; + } + + switch(string[i]) + { + case 'A': + case 'a': + /* 0 */ + break; + case 'B': + case 'b': + num += 1 * n; + break; + case 'C': + case 'c': + num += 2 * n; + break; + case 'D': + case 'd': + num += 3 * n; + break; + case 'E': + case 'e': + num += 4 * n; + break; + case 'F': + case 'f': + num += 5 * n; + break; + default: + *s = string[i]; + if(string[0] == '-') + num -= atoi(s) * n; + else + num += atoi(s) * n; + } /* end switch */ + + } + + return num; +} + +char * p_itoh(int num, char str[], int z) +{ + int i, idx = 0; + + if(num > 0) { + if(num <= 9) i = 1; + else if(num <= 99) i = 10; + else if(num <= 999) i = 100; + else if(num <= 9999) i = 1000; + else if(num <= 99999) i = 10000; + else { + printf("error in p_itoh(): unknown range: %d\n", num); + printf("\nAre'nt you using HALT (+4300)?\n"); + exit(-1); + } + } + else if(!num) { + for(i = 0; i < (int)sizeof(str); i++) { + if(i < z) str[i] = '0'; + else str[i] = ' '; + } + return str; + } + else { + printf("Negative numbers are not allowed!\n"); + return 0; + } + + for( ; i ; idx++, i /= 10) { + + if( (num / i % 10) == 1 ) { + + i /= 10; + if(!i) break; + switch(num / i % 10) { + case 0: + str[idx] = 'A'; + break; + case 1: + str[idx] = 'B'; + break; + case 2: + str[idx] = 'C'; + break; + case 3: + str[idx] = 'D'; + break; + case 4: + str[idx] = 'E'; + break; + case 5: + str[idx] = 'F'; + break; + default: + str[idx] = (char)(num / i % 10) + '0'; + i *= 10; + } + } + + else { + str[idx] = (char)(num / i % 10) + '0'; + } + } /* end for (i) */ + + return str; +} + diff --git a/exercises/deitel/ch11/fig08_14_mod.c b/exercises/deitel/ch11/fig08_14_mod.c @@ -0,0 +1,57 @@ +/* Exercise 11.15 */ + +/* Fig. 8.14: fig08_14.c + Using getchar and puts */ +#include <stdio.h> +#include <stdlib.h> + +int main(void) +{ + char c; /* variable to hold character input by user */ + char sentence[ 80 ]; /* create char array */ + int i = 0; /* initialize counter i */ + FILE *in = stdin, *out = stdout; + char input[15], output[15]; + + fputs( "enter your choice: ", out ); + scanf("%d%*c", &i); + + if(i == 1) { + fputs( "Input file: ", out ); + scanf("%s", input); + + if( (in = fopen(input, "r")) == NULL) { + printf("%s: cannot open the file\n", input); + exit(-1); + } + + fputs( "Output file: ", out ); + scanf("%s", output); + + if( (out = fopen(output, "w")) == NULL) { + printf("%s: cannot open the file\n", output); + exit(-1); + } + } + else + /* prompt user to enter line of text */ + puts( "Enter a line of text:" ); + + i = 0; + + /* use getchar to read each character */ + while( ( c = fgetc(in) ) != '\n') { + sentence[ i++ ] = c; + } /* end while */ + + sentence[ i++ ] = '\n'; /* insert a newline */ + sentence[ i ] = '\0'; /* terminate string */ + + /* use puts to display sentence */ + fputs( "\nThe line entered was:\n", out ); + fputs( sentence, out ); + + return 0; /* indicates successful termination */ + +} /* end main */ + diff --git a/exercises/deitel/ch11/fig11_07_mod.c b/exercises/deitel/ch11/fig11_07_mod.c @@ -0,0 +1,49 @@ +/* Exercise 11.9 */ + +/* Fig. 11.7: fig11_07.c + Reading and printing a sequential file */ +#include <stdio.h> + +#define SIZE 29 + +struct record { + int account; + char name[SIZE]; + char address[SIZE]; + int phone; + double balance; + char notes[255]; +}; + +int main(int argc, char *argv[]) +{ + FILE *cfPtr; + struct record recPtr; + + if(argc != 2) { + printf("Usage: %s <file>\n", argv[0]); + return -1; + } + + /* fopen opens file; exits program if file cannot be opened */ + if ( ( cfPtr = fopen( argv[1], "r" ) ) == NULL ) { + printf( "File could not be opened\n" ); + } /* end if */ + else { /* read account, name and balance from file */ + printf( "%-10s%-13s%s\n", "Account", "Name", "Balance" ); + fread(&recPtr, sizeof(struct record), 1, cfPtr); + + /* while not end of file */ + while ( !feof( cfPtr ) ) { + printf( "%-10d%-13s%7.2f\n", + recPtr.account, recPtr.name, recPtr.balance ); + fread(&recPtr, sizeof(struct record), 1, cfPtr); + } /* end while */ + + fclose( cfPtr ); /* fclose closes the file */ + } /* end else */ + + return 0; /* indicates successful termination */ + +} /* end main */ + diff --git a/exercises/deitel/ch11/file-matching2.c b/exercises/deitel/ch11/file-matching2.c @@ -0,0 +1,99 @@ +/* Exercise 11.10 + * + * NOTE: i suppose that the records stored to the + * files are in an ascending order sequence. +*/ + +#include <stdio.h> +#include <stdlib.h> + +#define SIZE 29 + +struct record { + int account; + char name[SIZE]; + char address[SIZE]; + int phone; + double balance; + char notes[255]; +}; + +int main(void) +{ + FILE *clients, *trans, *newfile; + struct record cRec, tRec; + int found; + + /* open the clients file */ + if( (clients = fopen("oldmast.dat", "r")) == NULL ) { + printf("%s: cannot open the file\n", "oldmast.dat"); + exit(-1); + } + + /* open the transactions file */ + if( (trans = fopen("trans.dat", "r")) == NULL ) { + printf("%s: cannot open the file\n", "trans.dat"); + exit(-1); + } + + /* open the new archive file */ + if ( (newfile = fopen("newmast.dat", "w")) == NULL ) { + printf("%s: cannot open the file\n", "newmast.dat"); + exit(-1); + } + + /* Read the first record */ + fread(&cRec, sizeof(struct record), 1, clients); + + /* loop the clients */ + while( !feof(clients) ) { + + fread(&tRec, sizeof(struct record), 1, trans); + + /* check the transactions */ + while( !feof(trans) && tRec.account <= cRec.account ) { + if(tRec.account == cRec.account) { + cRec.balance += tRec.balance; + } + fread(&tRec, sizeof(struct record), 1, trans); + } + fwrite(&cRec, sizeof(struct record), 1, newfile); + + rewind(trans); + fread(&cRec, sizeof(struct record), 1, clients); + } + + fread(&tRec, sizeof(struct record), 1, trans); + + /* check the mismathed transactions */ + while( !feof(trans) ) { + + rewind(clients); + fread(&cRec, sizeof(struct record), 1, clients); + + found = 0; + + /* loop the clients */ + while( !feof(clients) && cRec.account <= tRec.account ) { + if(cRec.account == tRec.account) { + found = 1; + break; + } + fread(&cRec, sizeof(struct record), 1, clients); + } + + if(!found) { + printf("Unmatched transaction record for account number %d\n", + tRec.account); + } + + fread(&tRec, sizeof(struct record), 1, trans); + } + + fclose(clients); + fclose(trans); + fclose(newfile); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch11/hardware.c b/exercises/deitel/ch11/hardware.c @@ -0,0 +1,242 @@ +/* Exercise 11.12 */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define REC 100 +#define LEN 30 + +struct hwlist { + int id; + char product[LEN]; + int quantity; + double price; +}; + +int main(void) +{ + FILE *fd; + struct hwlist blank_t = { 0, "blank", 0, 0.0 }; + struct hwlist list_t = blank_t; + char string[LEN]; + int i; + + /* open the file */ + if( (fd = fopen("hardware.dat", "w")) == NULL ) { + printf("cannot open the file %s\n", "hardware.dat"); + exit(-1); + } + + /* create the empty records */ + for(i = 1; i <= REC; i++) { + list_t.id = i; + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + } + + /* S T A R T O F B A S E D A T A */ + + list_t.id = 3; + fseek(fd, (list_t.id - 1) * sizeof(struct hwlist), SEEK_SET); + strncpy(list_t.product, "Smerigliatrice elettrica", 25); + list_t.quantity = 7; + list_t.price = 57.98; + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + + list_t.id = 17; + fseek(fd, (list_t.id - 1) * sizeof(struct hwlist), SEEK_SET); + strncpy(list_t.product, "Martello", 9); + list_t.quantity = 76; + list_t.price = 11.99; + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + + list_t.id = 24; + fseek(fd, (list_t.id - 1) * sizeof(struct hwlist), SEEK_SET); + strncpy(list_t.product, "Sega da traforo", 16); + list_t.quantity = 21; + list_t.price = 11.00; + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + + list_t.id = 39; + fseek(fd, (list_t.id - 1) * sizeof(struct hwlist), SEEK_SET); + strncpy(list_t.product, "Falciatrice", 12); + list_t.quantity = 3; + list_t.price = 79.50; + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + + list_t.id = 56; + fseek(fd, (list_t.id - 1) * sizeof(struct hwlist), SEEK_SET); + strncpy(list_t.product, "Sega elettrica", 15); + list_t.quantity = 18; + list_t.price = 99.99; + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + + list_t.id = 68; + fseek(fd, (list_t.id - 1) * sizeof(struct hwlist), SEEK_SET); + strncpy(list_t.product, "Giravite", 9); + list_t.quantity = 106; + list_t.price = 6.99; + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + + list_t.id = 77; + fseek(fd, (list_t.id - 1) * sizeof(struct hwlist), SEEK_SET); + strncpy(list_t.product, "Martello da fabbro", 19); + list_t.quantity = 11; + list_t.price = 21.50; + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + + list_t.id = 83; + fseek(fd, (list_t.id - 1) * sizeof(struct hwlist), SEEK_SET); + strncpy(list_t.product, "Chiave inglese", 15); + list_t.quantity = 34; + list_t.price = 7.50; + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + + /* E N D O F B A S E D A T A */ + + freopen("hardware.dat", "r+", fd); + + while(1) { + printf( /* Menu */ + "\nChoose an action\n\n" + "\t1. Edit a record\n" + "\t2. Delete a record\n" + "\t3. Show all records\n" + "\t4. Exit\n" + "\nChoose: " + ); /* end menu */ + scanf("%d", &i); + + if(i == 4) + break; + + printf("\n"); + + switch(i) + { + case 1: /* Edit a record */ + printf("Insert a product ID: "); + scanf("%d", &i); + + printf("\n"); + + fseek(fd, (i - 1) * sizeof(struct hwlist), SEEK_SET); + fread(&list_t, sizeof(struct hwlist), 1, fd); + + printf("ID: %d\nName: %s\nQuantity: %d\nPrice: %.2f\n\n", + list_t.id, list_t.product, list_t.quantity, list_t.price); + + printf("Insert the new data or '-1' to leave unchanged\n\n"); + + printf("ID: %d (unchangable)\n", list_t.id); + printf("Name [%s]: ", list_t.product); + fscanf(stdin, "%s", string); + + if( strncmp(string, "-1", 2) ) { + strncpy(list_t.product, string, sizeof(list_t.product)); + } + + printf("Quantity [%d]: ", list_t.quantity); + fscanf(stdin, "%s", string); + if( strncmp(string, "-1", 2) ) { + list_t.quantity = atoi(string); + } + + printf("Price [%.2f]: ", list_t.price); + fscanf(stdin, "%s", string); + + if( memcmp(string, "-1", 2) ) { + list_t.price = atof(string); + } + + fseek(fd, -1 * sizeof(struct hwlist), SEEK_CUR); + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + + break; + case 2: /* Delete a record */ + printf("Insert a product ID: "); + scanf("%d", &i); + + printf("\n"); + + fseek(fd, (i - 1) * sizeof(struct hwlist), SEEK_SET); + fread(&list_t, sizeof(struct hwlist), 1, fd); + + if( + !memcmp(list_t.product, "blank", 5) || + list_t.quantity + ) { + printf("Cannot delete product number %d.\n", list_t.id); + break; + } + + printf("ID: %d\nName: %s\nQuantity: %d\nPrice: %.2f\n\n", + list_t.id, list_t.product, list_t.quantity, list_t.price); + + printf("Are you sure (y/n)?: "); + fscanf(stdin, "%s", string); + + printf("\nProduct number %d has ", list_t.id); + + if( !memcmp(string, "y", strlen(string)) ) { + list_t = blank_t; + list_t.id = i; + fseek(fd, -1 * sizeof(struct hwlist), SEEK_CUR); + fwrite(&list_t, sizeof(struct hwlist), 1, fd); + } + else + printf("NOT "); + + printf("been deleted.\n"); + + break; + case 3: /* Show all records */ + rewind(fd); + + printf("\n%-10s%-30s%-15s%-10s\n", + "ID", "Product", "Quantity", "Price"); + + for(i = 0; i < 60; i++) + printf("-"); + printf("\n"); + + i = 0; + fread(&list_t, sizeof(struct hwlist), 1, fd); + while( !feof(fd) ) { + if( memcmp(list_t.product, "blank", 5) ) { + printf("%-10d%-30s%-15d%-10.2f\n", + list_t.id, list_t.product, list_t.quantity, list_t.price); + } + else { + fread(&list_t, sizeof(struct hwlist), 1, fd); + continue; + } + fread(&list_t, sizeof(struct hwlist), 1, fd); + + if( !(++i % 10) ) { + if(i == 10) getchar(); + printf( + "\nPress return to continue " + "(or q and return to end)..\n" + ); + string[0] = getchar(); + + if(string[0] == 'q') + break; + } + } + + printf("\n"); + + break; + default: + printf("Invalid choose, please retry.\n"); + } + + } + + fclose(fd); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch11/mkrecord.c b/exercises/deitel/ch11/mkrecord.c @@ -0,0 +1,76 @@ +/* Exercise 11.8 */ + +#include <stdio.h> +#include <stdlib.h> + +#define SIZE 29 + +struct record { + int account; + char name[SIZE]; + char address[SIZE]; + int phone; + double balance; + char notes[255]; +}; + +int main(void) +{ + FILE *master, *trans; + struct record rec; + + if( (master = fopen("oldmast.dat", "w")) == NULL ) { + printf("Shit, i can't open the file %s\n", "oldmast.dat"); + exit(-1); + } + + if( (trans = fopen("trans.dat", "w")) == NULL ) { + printf("Oh, fucked filesystem.. i can't open the file %s\n", "trans.dat"); + exit(-1); + } + + printf("Inserting data for the master file\n"); + + printf("Account number (0 to end): "); + scanf("%d", &rec.account); + + /* writing to the "master" file */ + while( rec.account > 0 ) { + printf("Name: "); + scanf("%s", rec.name); + printf("Balance: "); + scanf("%lf", &rec.balance); + + fwrite(&rec, sizeof(struct record), 1, master); + printf("record stored!\n\n"); + + printf("Account number (0 to end): "); + scanf("%d", &rec.account); + } + + printf("Inserting data for the transactions file\n"); + + printf("Avvount number (0 to end): "); + scanf("%d", &rec.account); + + /* writing to the "trans" file */ + while( rec.account > 0 ) { + + rec.name[0] = '\0'; /* not required */ + + printf("Balance: "); + scanf("%lf", &rec.balance); + + fwrite(&rec, sizeof(struct record), 1, trans); + printf("record stored!\n\n"); + + printf("Account number (0 to end): "); + scanf("%d", &rec.account); + } + + fclose(master); + fclose(trans); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch11/oldmast.dat b/exercises/deitel/ch11/oldmast.dat Binary files differ. diff --git a/exercises/deitel/ch11/oldmast.dat.1 b/exercises/deitel/ch11/oldmast.dat.1 Binary files differ. diff --git a/exercises/deitel/ch11/person.c b/exercises/deitel/ch11/person.c @@ -0,0 +1,84 @@ +/* Exercise 11.11 */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define REC 100 + +struct person { + char lastName[15]; + char firstName[15]; + char age[4]; +}; + +int main(void) +{ + struct person empty = { "unassigned", "", "0" }; + struct person guy = { "unassigned", "", "0" }; + FILE *fd; + int i; + + if( (fd = fopen("nameage.dat", "w")) == NULL) { + printf("cannot open the file \"%s\"\n", "nameage.dat"); + exit(-1); + } + + /* --- A --- */ + + /* write the recors */ + for(i = 0; i < REC; i++) { + fwrite(&empty, sizeof(struct person), 1, fd); + } + + /* --- B --- */ + + /* insert ten entries of Surname, name and age to the file */ + for(i = 0; i < 10; i++) { + printf("Surname, name and age: "); + scanf("%s%s%s", guy.lastName, guy.firstName, guy.age); + fwrite(&guy, sizeof(struct person), 1, fd); + } + + /* --- C --- */ + + /* seek to one of the ten latest entries */ + fseek(fd, 100 + rand() % 10 * sizeof(struct person), SEEK_SET); + + fread(&guy, sizeof(struct person), 1, fd); + if( ! strncmp(guy.lastName, "unassigned", sizeof(guy.lastName)) && + ! strncmp(guy.firstName, "", 1) && ! strncmp(guy.age, "", 1) ) { + + printf("No info\n"); + + } + printf("\n[update]: Surname, name and age: "); + scanf("%s%s%s", guy.lastName, guy.firstName, guy.age); + fwrite(&guy, sizeof(struct person), 1, fd); + + /* --- D --- */ + + fseek(fd, 100 * sizeof(struct person), SEEK_SET); + + for(i = 100; i < 110 && !feof(fd); i++) { /* feof() not required */ + if( strncmp(guy.lastName, "unassigned", sizeof(guy.lastName)) || + strncmp(guy.firstName, "", 1) || strncmp(guy.age, "", 1) ) { + i = 1; + break; + } + fread(&guy, sizeof(struct person), 1, fd); + } + + if(i == 1) { + fwrite(&empty, sizeof(struct person), 1, fd); + } + else { + printf("No empty records!\n"); + } + + + fclose(fd); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch11/trans.dat b/exercises/deitel/ch11/trans.dat Binary files differ. diff --git a/exercises/deitel/ch11/trans.dat.1 b/exercises/deitel/ch11/trans.dat.1 Binary files differ. diff --git a/exercises/deitel/ch12/Semplice.c b/exercises/deitel/ch12/Semplice.c @@ -0,0 +1,625 @@ +/* + * Exercise 12.27 + * The Simple compiler + * + * WARNING: this code is *very* unstable! + * NO WARRANTY!! - USE AT YOUR OWN RISK!! +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <ctype.h> + +#define INPUT "source.s" +#define OUTPUT "fout.lms" + +#define SIZE 255 +#define BUF 100 + +/* Symbol table */ +typedef struct symtab_t { + int symbol; + char type; /* 'L', 'C' or 'V' */ + int location; /* from 00 to 99 */ +} Table; + +/* Stack structure */ +typedef struct stack_t { + char c; + struct stack_t *next; +} Stack; + +/* + * Prototypes +*/ +char pop(Stack **stackp); +void push(Stack **stackp, char value); +void topostfix(char infix[], char postfix[]); +void evalpfexp(char *expr, Table *stab, int *icount, + int *t, int *emem, int *lmsmem); +int calculate(int op1, int op2, char operator); +int isoper(char c); +char isempty(Stack *stackp); +int precedence(char op1, char op2); +char stacktop(Stack *stackp); +int getcode(char *cmd); +int getsym(int c, int len, Table *stab); +void pw_lmsmem(int *lmsmem, const int size, char *o_file); +void showtab(Table *stab, const int size); + +/* Compilation steps */ +void fstep(Table *stab, char *infile, int *lmsmem, int *flags); +void sstep(Table *stab, int *lmsmem, int *flags, int size); + +/* The main function */ +int main(void) +{ + int lmsmem[BUF], flags[BUF]; + Table stab[BUF]; + int c; + + fstep( stab, (char *)INPUT, lmsmem, flags ); /* The 1st step */ + sstep( stab, lmsmem, flags, BUF ); /* The 2nd step */ + + printf("\nShow the symbol table (y/n)?: "); + while( (c = fgetc(stdin)) != EOF ) { + if( c == 'y' ) { + showtab(stab, BUF); + break; + } + else if( c == 'n' ) + break; + else { + puts("\nInvalid input"); + printf("Show the symbol table (y/n)?: "); + } + } + + putchar('\n'); + + return 0; +} /* E0F main */ + +/* + * First step: create the symbol table and some incomplete + * instruction putting them to the memory array "lmsmem" +*/ +void fstep(Table *stab, char *infile, int *lmsmem, int *flags) +{ + FILE *fd; + char cline[SIZE]; /* Current line */ + char postfix[BUF], *tokp; + + const int size = BUF - 1; + int t = 0, icount = 0; + int emem = size; /* End memory */ + int x, i; + + /* Initialize the data */ + for(i = 0; i < BUF; i++) { + lmsmem[i] = 0; + flags[i] = -1; + + stab[i].location = 0; + stab[i].type = stab[i].symbol = '0'; + } + + /* open the file */ + if( (fd = fopen(infile, "r")) == NULL ) { + printf("Cannot open the file: %s\n", infile); + exit(-1); + } + + fgets(cline, sizeof(cline), fd); + cline[ strlen(cline) + 1 ] = '\0'; + while( !feof(fd) ) { + + /* Line number */ + if( (tokp = strtok(cline, " ")) != NULL ) { + stab[t].symbol = atoi(tokp); + stab[t].type = 'L'; + stab[t].location = icount; + ++t; + } + + if( (tokp = strtok(NULL, " ")) != NULL ) { + + /* check the command */ + switch( getcode(tokp) ) { + case 1: /* rem */ + + /* do nothing */ + + break; + case 10: /* input */ + + /* take the variable */ + if( (tokp = strtok(NULL, " ")) != NULL ) { + + if( (x = getsym(*tokp, size, stab)) == -1 ) { + stab[t].symbol = *tokp; + stab[t].type = 'V'; + x = stab[t].location = emem--; + ++t; + } + else + x = stab[x].location; + + lmsmem[icount] = 1000 + x; + } + + ++icount; + break; + case 3: /* let */ + + /* Add all symbols to the table */ + tokp = strtok(NULL, " "); + while( tokp != NULL ) { + if( !isoper(*tokp) && *tokp != '=' && + getsym(*tokp, size, stab) == -1 + ) { + stab[t].symbol = *tokp; + stab[t].location = emem--; + stab[t].type = isdigit((int)*tokp) ? 'C' : 'V'; + ++t; + } + tokp = strtok(NULL, " "); + } + + /* Retrieve the right side of the expression.. */ + for(x = 0; cline[x] != '='; x++) ; + x += 2; + + memset(postfix, '\0', sizeof(postfix)); + + while( cline[x] != '\0' ) { + strncat(postfix, &cline[x], sizeof(postfix)); + strncat(postfix, " ", sizeof(postfix)); + x += 2; + } + + memset(cline, '\0', sizeof(cline)); + memcpy(cline, postfix, sizeof(cline)); + + /* ..and convert it to postfix format */ + topostfix(cline, postfix); + + /* + * Evalutate the results and create + * the Simpletron instructions + */ + evalpfexp(postfix, stab, &icount, &t, &emem, lmsmem); + + ++icount; + break; + case 11: /* print */ + + tokp = strtok(NULL, " "); /* Take the variable */ + x = getsym(*tokp, size, stab); + + lmsmem[icount] = 1100 + stab[x].location; + + ++icount; + break; + case 40: /* goto */ + + tokp = strtok(NULL, " "); /* Take the line number */ + lmsmem[icount] = 4000; + if( (x = getsym(atoi(tokp), size, stab)) == -1 ) + flags[icount] = *tokp; + else + lmsmem[icount] += stab[x].location; + + ++icount; + break; + case 6: /* if */ + + tokp = strtok(NULL, " "); + if( (x = getsym(atoi(tokp), size, stab)) == -1 ) { + stab[t].symbol = *tokp; + stab[t].type = 'V'; + x = stab[t].location = emem--; + ++t; + } + else + x = stab[x].location; + + lmsmem[icount++] = 2000 + x; /* +20x */ + + tokp = strtok(NULL, " "); /* Skip the operator */ + tokp = strtok(NULL, " "); /* Read the 2nd variable */ + if( (x = getsym(*tokp, size, stab)) == -1 ) { + stab[t].symbol = *tokp; + stab[t].type = 'V'; + x = stab[t].location = emem--; + ++t; + } + else + x = stab[x].location; + + lmsmem[icount++] = 3100 + x; /* +31x */ + + /* Read the branch position */ + while( getcode(tokp) != 40 && tokp != NULL ) + tokp = strtok(NULL, " "); + tokp = strtok(NULL, " "); + + /* Look for the destination in the symbol table */ + lmsmem[icount] = 4200; + if( (x = getsym(*tokp, size, stab)) == -1 ) { + flags[icount] = atoi(tokp); + } + else + lmsmem[icount] += stab[x].location; + + ++icount; + break; + case 43: /* end */ + lmsmem[icount] = 4300; + + ++icount; + + break; + default: /* unknown command */ + puts("Some error.."); + } + } + + fgets(cline, sizeof(cline), fd); + } + + fclose(fd); /* Close the input file */ + +} /* eof fstep() */ + +/* + * Second step: find the incomplete instructions, complete them + * and write the results to the screen and in the OUTPUT file +*/ +void sstep(Table *stab, int *lmsmem, int *flags, int size) +{ + int i, x; + + for(i = 0; i < size; i++) { + if( flags[i] != -1 ) { + x = getsym(flags[i], size, stab); + lmsmem[i] += stab[x].location; + } + } + + /* Show the memory and write it to a file */ + pw_lmsmem(lmsmem, size, (char *)OUTPUT); + +} /* eof sstep() */ + +/* + * Print the whole LMS memory array +*/ +void pw_lmsmem(int *lmsmem, const int size, char *o_file) +{ + FILE *fd; + int i; + + /* Open the file */ + if( (fd = fopen(o_file, "wb+")) == NULL ) { + printf("Cannot open the file: %s\n", o_file); + return; + } + + puts("\n> Simpletron memory"); + for(i = 0; i < size && lmsmem[i]; i++) { + printf("%.2d: %+.4d\n", i, lmsmem[i]); + fprintf(fd, "%+.4d\n", lmsmem[i]); + } + + fclose(fd); +} /* eof pw_lmsmem() */ + +/* + * Print the whole symbol table +*/ +void showtab(Table *stab, const int size) +{ + int i; + + puts("\n> Symbol table"); + + for(i = 1; i < size; i++) { + if( stab[i - 1].type == '0' ) + break; + + if( stab[i - 1].type == 'L' ) + printf("s[%2d] ", stab[i - 1].symbol); + else + printf("s[%2c] ", stab[i - 1].symbol); + + printf("t[%1c] l[%.2d]\n", stab[i - 1].type, stab[i - 1].location); + } +} /* eof showtab() */ + +/* + * Returns the position of 'c' in the Table 'stab' +*/ +int getsym(int c, int len, Table *stab) +{ + int i; + + for(i = 0; i < len; i++) { + if( stab[i].symbol == c ) + return i; + } + + return -1; +} /* eof getsym() */ + +/* + * Returns the Simpletron operation code + * from the Simple instruction 'cmd' +*/ +int getcode(char *cmd) +{ + if( !memcmp(cmd, "rem", 3) ) + return 1; + else if( !memcmp(cmd, "input", 5) ) /* read - 10 */ + return 10; + else if( !memcmp(cmd, "let", 3) ) + return 3; + else if( !memcmp(cmd, "print", 5) ) /* write - 11 */ + return 11; + else if( !memcmp(cmd, "goto", 4) ) /* branch - 40 */ + return 40; + else if( !memcmp(cmd, "if", 2) ) + return 6; + else if( !memcmp(cmd, "end", 3) ) + return 43; + + return 0; +} /* eof getcode() */ + +/* + * Pop a value from top of the stack +*/ +char pop(Stack **stackp) +{ + Stack *tstackp; /* temporary stack pointer for free(3) */ + char ret = ( *stackp )->c; + + tstackp = *stackp; + *stackp = ( *stackp )->next; + + free(tstackp); + + return ret; +} /* eof pop() */ + +/* + * Push a value in top of the stack +*/ +void push(Stack **stackp, char value) +{ + Stack *newnode; + + if( (newnode = malloc( sizeof(Stack) )) == NULL ) { + printf("push(): cannot allocate the memory\n"); + return; + } + newnode->c = value; + newnode->next = NULL; + + newnode->next = *stackp, + *stackp = newnode; + +} /* eof push() */ + +/* + * Convert from infix format to reverse polish suffix + * E.g.: + * + * The expression (1 + 5) * 9 - 2 / 6 + * will be equal to 1 5 + 9 * 2 6 / - + * +*/ +void topostfix(char infix[], char postfix[]) +{ + Stack *stackp = NULL; + int i = 0, j = 0; + + push(&stackp, '('); + infix[ (int)strlen(infix) ] = ')'; + infix[ (int)strlen(infix) ] = '\0'; + + while( ! isempty(stackp) ) { + if( isspace( (int)infix[i] ) ) ; + else if( infix[i] == '(' ) { + push(&stackp, '('); + } + else if( isoper(infix[i]) ) { + while( precedence(infix[i], stacktop(stackp)) != -1 ) { + postfix[j++] = pop(&stackp); + postfix[j++] = ' '; + } + + push(&stackp, infix[i]); + } + else if( infix[i] == ')' ) { + while( stacktop(stackp) != '(' && isoper(stacktop(stackp)) ) { + postfix[j++] = pop(&stackp); + postfix[j++] = ' '; + } + pop(&stackp); /* remove the '(' from the stack */ + } + else { + postfix[j++] = infix[i]; + postfix[j++] = ' '; + } + + ++i; + } +} /* eof topostfix() */ + +/* + * Generate the Simpletron instructions from the + * reverse polish suffix notation expressions +*/ +void evalpfexp(char *expr, Table *stab, int *icount, + int *t, int *emem, int *lmsmem) +{ + Stack *stackp; + char *tokp; + int i, x, y; + + expr[ (int)strlen(expr) + 1 ] = '\0'; + + tokp = strtok(expr, " "); + while( tokp != NULL ) { + if( ! isoper( *tokp ) ) { + + /* find the symbol in the table */ + for(i = 0; i < BUF; i++) { + if( *tokp == stab[i].symbol ) + break; + } + + if( i == BUF ) { /* Not found */ + stab[*t].symbol = isdigit((int)*tokp) ? atoi(tokp) : *tokp; + stab[*t].type = isdigit((int)*tokp) ? 'C' : 'V'; + stab[*t].location = *emem--; + i = *t; + ++*t; + } + + push(&stackp, stab[i].location); + } + else { + y = pop(&stackp); + x = pop(&stackp); + + /* Make the instructions */ + lmsmem[(*icount)++] = 2000 + x; + lmsmem[(*icount)++] = 3000 + y; + lmsmem[(*icount)++] = 2100 + *emem; + lmsmem[(*icount)++] = 2000 + *emem; + lmsmem[(*icount)] = 2100 + x; + + --*emem; + + push(&stackp, lmsmem[*icount]); + } + + tokp = strtok(NULL, " "); + } + +} /* eof evalpfexp() */ + +/* + * Calculate the value of expression "op1 operator op2" +*/ +int calculate(int op1, int op2, char operator) +{ + int i; + + switch(operator) { + case '+': + return op1 + op2; + case '-': + return op1 - op2; + case '*': + return op1 * op2; + case '/': + if( !op2 ) { + printf("calculate(): cannot divide for zero\n"); + exit(-1); + } + else + return op1 / op2; + case '^': + for(i = op2, op2 = op1; i > 1; i--) { + op1 *= op2; + } + + return op1; + case '%': + return op1 % op2; + } + + return -1; +} /* eof calculate() */ + +/* + * Check if 'c' is a valid operator +*/ +int isoper(char c) +{ + switch(c) { + case '+': + case '-': + case '*': + case '/': + case '^': + case '%': + return 1; + } + + return 0; +} /* eof isoper() */ + +/* + * Determine if the stack is empty this is a "predicate function" +*/ +char isempty(Stack *stackp) +{ + return stackp == NULL; +} /* eof isempty() */ + +/* + * Determine if the priority of op1 is less then, equal to + * or greter then op2 and return respectively, -1, 0 and 1. +*/ +int precedence(char op1, char op2) +{ + int x = 2; + char *p = &op1; + + while( x-- ) { + if( !x ) + p = &op2; + + switch( *p ) { + case '%': + case '/': + case '*': + *p = '1'; + break; + case '-': + case '+': + *p = '2'; + break; + case '^': + *p = '3'; + break; + default: + return -1; + } + + } + + x = (op1 - '0') - (op2 - '0'); + + if( x > 0 ) + return 1; + else if( x < 0 ) + return -1; + + return 0; +} /* eof precedence() */ + +/* + * As pop() but don't extract the value from top of stack + * This is a "predicate function" +*/ +char stacktop(Stack *stackp) +{ + return stackp->c; +} /* eof stacktop() */ + diff --git a/exercises/deitel/ch12/binarySearchTree.c b/exercises/deitel/ch12/binarySearchTree.c @@ -0,0 +1,21 @@ +/* Exercise 12.23 */ + +Tree binarySearchTree( Tree *treePtr, int value ) +{ + Tree *retp = treePtr; + + if( retp != NULL ) { + if( (retp->left != NULL && retp->data == value) || + (retp->right != NULL && retp->data == value) + ) return retp; + + if( retp->data > value ) + return binarySearchTree( retp->left, value ); + else + return binarySearchTree( retp->rightr, value ); + } + + return NULL; + +} /* eof searchTree() */ + diff --git a/exercises/deitel/ch12/concatenate.c b/exercises/deitel/ch12/concatenate.c @@ -0,0 +1,87 @@ +/* Exercise 12.6 */ + +#include <stdio.h> +#include <stdlib.h> + +struct list { + char c; + struct list *next; +}; + +typedef struct list List; +typedef List * ListPtr; + +/* + * Prototypes +*/ +ListPtr createlist(int x); +void showlist(ListPtr startPtr); +void concatenate(ListPtr list1, ListPtr list2); + +int main(void) +{ + ListPtr list1 = createlist('0'); + ListPtr list2 = createlist('A'); + + showlist(list1); + showlist(list2); + + concatenate(list1, list2); + + showlist(list1); + + return 0; +} /* E0F main */ + +ListPtr createlist(int x) +{ + ListPtr newList; + ListPtr currentPtr; + int i = 0; + + newList = malloc( sizeof(List) ); + currentPtr = newList; + + while(1) { + currentPtr->c = x + i++; + + if(i < 10) { + currentPtr->next = malloc( sizeof(List) ); + currentPtr = currentPtr->next; + } + else + break; + } + currentPtr->next = NULL; /* close the list */ + + return newList; +} /* end of createlist() */ + +void showlist(ListPtr startPtr) +{ + ListPtr currentPtr; + + if( startPtr != NULL) { + + currentPtr = startPtr; + + while( currentPtr != NULL ) { + printf("%c --> ", currentPtr->c); + currentPtr = currentPtr->next; + } + } + printf("NULL\n"); + +} /* eof showlist() */ + +void concatenate(ListPtr list1, ListPtr list2) +{ + ListPtr l1 = list1; + + while( l1->next != NULL ) + l1 = l1->next; + + l1->next = list2; + +} /* eof contatenate() */ + diff --git a/exercises/deitel/ch12/depth.c b/exercises/deitel/ch12/depth.c @@ -0,0 +1,94 @@ +/* Exercise 12.19 */ + +#include <stdio.h> +#include <stdlib.h> + +struct tree { + struct tree *left; + int data; + struct tree *right; +}; +typedef struct tree Node; + +void insnode(Node **nodep, int value); +int depth(Node *nodep); +void showtree(Node *nodep); + +int main(void) +{ + Node *root = NULL; + int i; + + for(i = 0; i < 20; i++) { + insnode(&root, i); + } + + printf("The tree have %d levels which are:\n", depth(root)); + showtree(root); + + putchar('\n'); + + return 0; +} /* E0F main */ + +/* + * Insert an ordered value in the tree +*/ +void insnode(Node **nodep, int value) +{ + if( *nodep == NULL ) { + + if( (*nodep = malloc( sizeof(Node) )) == NULL ) { + printf("Cannot allocate the memory"); + return; + } + + ( *nodep )->data = value; + ( *nodep )->left = NULL; + ( *nodep )->right = NULL; + } + else { + + if( value <= ( *nodep )->data ) { + insnode( &( ( *nodep )->left ), value ); + } + else if( value > ( *nodep )->data ) { + insnode( &( ( *nodep )->right ), value ); + } + } + +} /* eof insnode() */ + +/* + * Returns the number of tree levels +*/ +int depth(Node *nodep) +{ + Node *currentPtr = nodep; + static int count = 0; + + if( nodep != NULL ) { + ++count; + depth(currentPtr->left); + depth(currentPtr->right); + } + + return count; + +} /* eof depth() */ + +/* + * Show the whole tree +*/ +void showtree(Node *nodep) +{ + Node *currentPtr = nodep; + + if( nodep != NULL ) { + printf("%d ", currentPtr->data); + showtree(currentPtr->left); + showtree(currentPtr->right); + } + +} /* eof showtree() */ + diff --git a/exercises/deitel/ch12/evalpfexp.c b/exercises/deitel/ch12/evalpfexp.c @@ -0,0 +1,158 @@ +/* Exercise 12.13 */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <ctype.h> + +struct stack_t { + int n; + struct stack_t *next; +}; +typedef struct stack_t Stack; + +/* + * Prototypes +*/ +void push(Stack **stackp, char value); +char pop(Stack **stackp); +char isempty(Stack *stackp); +int calculate(int op1, int op2, char operator); +int evalpfexp(char *expr); +int isoper(char c); + +/* main function */ +int main(void) +{ + char string[] = { "6 2 + 5 * 8 4 / -" }; + + printf("%s = %d\n", string, evalpfexp(string)); + + return 0; +} /* E0F main */ + +/* + * Push a value in top of the stack +*/ +void push(Stack **stackp, char value) +{ + Stack *newnode; + + if( (newnode = malloc( sizeof(Stack) )) == NULL ) { + printf("push(): cannot allocate the memory\n"); + return; + } + newnode->n = value; + newnode->next = NULL; + + newnode->next = *stackp, + *stackp = newnode; + +} /* eof push() */ + +/* + * Pop a value from top of the stack +*/ +char pop(Stack **stackp) +{ + Stack *tstackp; /* temporary stack pointer for free(3) */ + int ret = ( *stackp )->n; + + tstackp = *stackp; + *stackp = ( *stackp )->next; + + free(tstackp); + + return ret; +} /* eof pop() */ + +/* + * Determine if the stack is empty this is a "predicate function" +*/ +char isempty(Stack *stackp) +{ + if( stackp == NULL ) + return 1; + + return 0; +} /* eof isempty() */ + +/* + * Calculate the value of expression "op1 operator op2" +*/ +int calculate(int op1, int op2, char operator) +{ + int i; + + switch(operator) { + case '+': + return op1 + op2; + case '-': + return op1 - op2; + case '*': + return op1 * op2; + case '/': + if( !op2 ) + return 0; + else + return op1 / op2; + case '^': + for(i = op2, op2 = op1; i > 1; i--) { + op1 *= op2; + } + + return op1; + case '%': + return op1 % op2; + } + + return -1; +} /* eof calculate() */ + +/* + * Check if 'c' is a valid operator +*/ +int isoper(char c) +{ + switch(c) { + case '+': + case '-': + case '*': + case '/': + case '^': + case '%': + break; + default: + return 0; + } + + return 1; +} /* eof isoper() */ + +/* + * Evalutate the expression in reverse polish notation +*/ +int evalpfexp(char *expr) +{ + Stack *stackp; + int i = -1; + int x, y; + + expr[ (int)strlen(expr) ] = '\0'; + + while( expr[++i] != '\0' ) { + if( isdigit((int)expr[i]) ) { + push(&stackp, expr[i] - '0'); + } + else if( isoper(expr[i]) ) { + x = pop(&stackp); + y = pop(&stackp); + + push(&stackp, calculate(y, x, expr[i])); + } + } + + return pop(&stackp); + +} /* eof evalpfexp() */ + diff --git a/exercises/deitel/ch12/evalpfexp2.c b/exercises/deitel/ch12/evalpfexp2.c @@ -0,0 +1,168 @@ +/* Exercise 12.14 */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <ctype.h> + +struct stack_t { + int n; + struct stack_t *next; +}; +typedef struct stack_t Stack; + +/* + * Prototypes +*/ +void push(Stack **stackp, char value); +char pop(Stack **stackp); +char isempty(Stack *stackp); +int calculate(int op1, int op2, char operator); +int evalpfexp(char *expr); +int isoper(char c); + +/* main function */ +int main(void) +{ + char string[] = { "12 13 + 5 * 8 4 / -" }; + + printf("%s = %d\n", string, evalpfexp(string)); + + return 0; +} /* E0F main */ + +/* + * Push a value in top of the stack +*/ +void push(Stack **stackp, char value) +{ + Stack *newnode; + + if( (newnode = malloc( sizeof(Stack) )) == NULL ) { + printf("push(): cannot allocate the memory\n"); + return; + } + newnode->n = value; + newnode->next = NULL; + + newnode->next = *stackp, + *stackp = newnode; + +} /* eof push() */ + +/* + * Pop a value from top of the stack +*/ +char pop(Stack **stackp) +{ + Stack *tstackp; /* temporary stack pointer for free(3) */ + int ret = ( *stackp )->n; + + tstackp = *stackp; + *stackp = ( *stackp )->next; + + free(tstackp); + + return ret; +} /* eof pop() */ + +/* + * Determine if the stack is empty this is a "predicate function" +*/ +char isempty(Stack *stackp) +{ + if( stackp == NULL ) + return 1; + + return 0; +} /* eof isempty() */ + +/* + * Calculate the value of expression "op1 operator op2" +*/ +int calculate(int op1, int op2, char operator) +{ + int i; + + switch(operator) { + case '+': + return op1 + op2; + case '-': + return op1 - op2; + case '*': + return op1 * op2; + case '/': + if( !op2 ) + return 0; + else + return op1 / op2; + case '^': + for(i = op2, op2 = op1; i > 1; i--) { + op1 *= op2; + } + + return op1; + case '%': + return op1 % op2; + } + + return -1; +} /* eof calculate() */ + +/* + * Check if 'c' is a valid operator +*/ +int isoper(char c) +{ + switch(c) { + case '+': + case '-': + case '*': + case '/': + case '^': + case '%': + break; + default: + return 0; + } + + return 1; +} /* eof isoper() */ + +/* + * Evalutate the expression in reverse polish notation +*/ +int evalpfexp(char *expr) +{ + Stack *stackp; + int i = -1; + int x, y; + + expr[ (int)strlen(expr) + 1 ] = '\0'; + + while( expr[++i] != '\0' ) { + if( isdigit((int)expr[i]) ) { + x = y = 1; + + /* set y */ + for( ; isdigit((int)expr[i + x]) && expr[i + x] != '\0'; ++x, y *= 10) + ; /* empty body */ + + for(x = 0; isdigit((int)expr[i]) && expr[i] != '\0'; y /= 10, i++) { + x += (expr[i] - '0') * y; + } + + push(&stackp, x); + } + else if( isoper(expr[i]) ) { + x = pop(&stackp); + y = pop(&stackp); + + push(&stackp, calculate(y, x, expr[i])); + } + } + + return pop(&stackp); + +} /* eof evalpfexp() */ + diff --git a/exercises/deitel/ch12/fig12_19_mod.c b/exercises/deitel/ch12/fig12_19_mod.c @@ -0,0 +1,134 @@ +/* Exercise 12.16 */ + +/* Fig. 12.19: fig12_19.c + Create a binary tree and traverse it + preorder, inorder, and postorder */ +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +/* self-referential structure */ +struct treeNode { + struct treeNode *leftPtr; /* pointer to left subtree */ + int data; /* node value */ + struct treeNode *rightPtr; /* pointer to right subtree */ +}; /* end structure treeNode */ + +typedef struct treeNode TreeNode; /* synonym for struct treeNode */ +typedef TreeNode *TreeNodePtr; /* synonym for TreeNode* */ + +/* prototypes */ +void insertNode( TreeNodePtr *treePtr, int value ); +void inOrder( TreeNodePtr treePtr ); +void preOrder( TreeNodePtr treePtr ); +void postOrder( TreeNodePtr treePtr ); + +/* function main begins program execution */ +int main(void) +{ + int i; /* counter to loop from 1-10 */ + int item; /* variable to hold random values */ + TreeNodePtr rootPtr = NULL; /* tree initially empty */ + + srand( time( NULL ) ); + printf( "The numbers being placed in the tree are:\n" ); + + /* insert random values between 1 and 15 in the tree */ + for ( i = 1; i <= 10; i++ ) { + item = rand() % 15; + printf( "%3d", item ); + insertNode( &rootPtr, item ); + } /* end for */ + + /* traverse the tree preOrder */ + printf( "\n\nThe preOrder traversal is:\n" ); + preOrder( rootPtr ); + + /* traverse the tree inOrder */ + printf( "\n\nThe inOrder traversal is:\n" ); + inOrder( rootPtr ); + + /* traverse the tree postOrder */ + printf( "\n\nThe postOrder traversal is:\n" ); + postOrder( rootPtr ); + + putchar('\n'); + + return 0; /* indicates successful termination */ + +} /* end main */ + +/* insert node into tree */ +void insertNode( TreeNodePtr *treePtr, int value ) +{ + + /* if tree is empty */ + if ( *treePtr == NULL ) { + *treePtr = malloc( sizeof( TreeNode ) ); + + /* if memory was allocated then assign data */ + if ( *treePtr != NULL ) { + ( *treePtr )->data = value; + ( *treePtr )->leftPtr = NULL; + ( *treePtr )->rightPtr = NULL; + } /* end if */ + else { + printf( "%d not inserted. No memory available.\n", value ); + } /* end else */ + + } /* end if */ + else { /* tree is not empty */ + + /* data to insert is less than data in current node */ + if ( value <= ( *treePtr )->data ) { + insertNode( &( ( *treePtr )->leftPtr ), value ); + } /* end if */ + + /* data to insert is greater than data in current node */ + else if ( value > ( *treePtr )->data ) { + insertNode( &( ( *treePtr )->rightPtr ), value ); + } /* end else if */ + + } /* end else */ + +} /* end function insertNode */ + +/* begin inorder traversal of tree */ +void inOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + inOrder( treePtr->leftPtr ); + printf( "%3d", treePtr->data ); + inOrder( treePtr->rightPtr ); + } /* end if */ + +} /* end function inOrder */ + +/* begin preorder traversal of tree */ +void preOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + printf( "%3d", treePtr->data ); + preOrder( treePtr->leftPtr ); + preOrder( treePtr->rightPtr ); + } /* end if */ + +} /* end function preOrder */ + +/* begin postorder traversal of tree */ +void postOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + postOrder( treePtr->leftPtr ); + postOrder( treePtr->rightPtr ); + printf( "%3d", treePtr->data ); + } /* end if */ + +} /* end function postOrder */ + diff --git a/exercises/deitel/ch12/fig12_19_mod2.c b/exercises/deitel/ch12/fig12_19_mod2.c @@ -0,0 +1,136 @@ +/* Exercise 12.17 */ + +/* Fig. 12.19: fig12_19.c + Create a binary tree and traverse it + preorder, inorder, and postorder */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define SIZE 100 + +/* self-referential structure */ +struct treeNode { + struct treeNode *leftPtr; /* pointer to left subtree */ + char data[SIZE]; /* node value */ + struct treeNode *rightPtr; /* pointer to right subtree */ +}; /* end structure treeNode */ + +typedef struct treeNode TreeNode; /* synonym for struct treeNode */ +typedef TreeNode *TreeNodePtr; /* synonym for TreeNode* */ + +/* prototypes */ +void insertNode( TreeNodePtr *treePtr, char *string ); +void inOrder( TreeNodePtr treePtr ); +void preOrder( TreeNodePtr treePtr ); +void postOrder( TreeNodePtr treePtr ); + +/* function main begins program execution */ +int main(void) +{ + TreeNodePtr rootPtr = NULL; /* tree initially empty */ + char string[SIZE], *tokp; + + printf("Insert a phrase: "); + fgets(string, SIZE, stdin); + printf( "The current string being placed in the tree are:\n" ); + printf("%s\n", string); + + tokp = strtok(string, " "); + while( tokp != NULL ) { + insertNode( &rootPtr, tokp ); + tokp = strtok(NULL, " "); + } + + /* traverse the tree preOrder */ + printf( "\nThe preOrder traversal is:\n" ); + preOrder( rootPtr ); + + /* traverse the tree inOrder */ + printf( "\n\nThe inOrder traversal is:\n" ); + inOrder( rootPtr ); + + /* traverse the tree postOrder */ + printf( "\n\nThe postOrder traversal is:\n" ); + postOrder( rootPtr ); + + putchar('\n'); + + return 0; /* indicates successful termination */ + +} /* end main */ + +/* insert node into tree */ +void insertNode( TreeNodePtr *treePtr, char *string ) +{ + + /* if tree is empty */ + if ( *treePtr == NULL ) { + *treePtr = malloc( sizeof( TreeNode ) ); + + /* if memory was allocated then assign data */ + if ( *treePtr != NULL ) { + strncpy( ( *treePtr )->data, string, SIZE ); + ( *treePtr )->leftPtr = NULL; + ( *treePtr )->rightPtr = NULL; + } /* end if */ + else { + printf( "%s not inserted. No memory available.\n", string ); + } /* end else */ + + } /* end if */ + else { /* tree is not empty */ + + /* data to insert is less than data in current node */ + if ( memcmp(string, ( *treePtr )->data, SIZE) <= 0 ) { + insertNode( &( ( *treePtr )->leftPtr ), string ); + } /* end if */ + + /* data to insert is greater than data in current node */ + else { + insertNode( &( ( *treePtr )->rightPtr ), string ); + } /* end else if */ + + } /* end else */ + +} /* end function insertNode */ + +/* begin inorder traversal of tree */ +void inOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + inOrder( treePtr->leftPtr ); + printf( "%s ", treePtr->data ); + inOrder( treePtr->rightPtr ); + } /* end if */ + +} /* end function inOrder */ + +/* begin preorder traversal of tree */ +void preOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + printf( "%s ", treePtr->data ); + preOrder( treePtr->leftPtr ); + preOrder( treePtr->rightPtr ); + } /* end if */ + +} /* end function preOrder */ + +/* begin postorder traversal of tree */ +void postOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + postOrder( treePtr->leftPtr ); + postOrder( treePtr->rightPtr ); + printf( "%s ", treePtr->data ); + } /* end if */ + +} /* end function postOrder */ + diff --git a/exercises/deitel/ch12/fig12_19_mod3.c b/exercises/deitel/ch12/fig12_19_mod3.c @@ -0,0 +1,227 @@ +/* Exercise 12.22 */ + +/* Fig. 12.19: fig12_19.c + Create a binary tree and traverse it + preorder, inorder, and postorder */ +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +/* self-referential structure */ +struct treeNode { + struct treeNode *leftPtr; /* pointer to left subtree */ + int data; /* node value */ + struct treeNode *rightPtr; /* pointer to right subtree */ +}; /* end structure treeNode */ + +typedef struct treeNode TreeNode; /* synonym for struct treeNode */ +typedef TreeNode *TreeNodePtr; /* synonym for TreeNode* */ + +/* prototypes */ +void insertNode( TreeNodePtr *treePtr, int value ); +void inOrder( TreeNodePtr treePtr ); +void preOrder( TreeNodePtr treePtr ); +void postOrder( TreeNodePtr treePtr ); +int deleteNode( TreeNodePtr *treePtr, int value ); + +/* + * NOTE: this function returns the daddy of + * the node, not the node in itself. +*/ +TreeNodePtr searchTree( TreeNodePtr treePtr, int value ); + +/* function main begins program execution */ +int main(void) +{ + int i; /* counter to loop from 1-10 */ + int item; /* variable to hold random values */ + TreeNodePtr rootPtr = NULL; /* tree initially empty */ + + srand( time( NULL ) ); + printf( "The numbers being placed in the tree are:\n" ); + + /* insert random values between 1 and 15 in the tree */ + for ( i = 1; i <= 10; i++ ) { + item = rand() % 15; + printf( "%3d", item ); + insertNode( &rootPtr, item ); + } /* end for */ + + printf("\n\nInsert the value to remove: "); + scanf("%d", &item); + + if( deleteNode( &rootPtr, item ) ) { + printf("Value not found or value is root: %d\n", item); + return -1; + } + + /* traverse the tree preOrder */ + printf( "\nThe preOrder traversal is:\n" ); + preOrder( rootPtr ); + + /* traverse the tree inOrder */ + printf( "\n\nThe inOrder traversal is:\n" ); + inOrder( rootPtr ); + + /* traverse the tree postOrder */ + printf( "\n\nThe postOrder traversal is:\n" ); + postOrder( rootPtr ); + + putchar('\n'); + + return 0; /* indicates successful termination */ + +} /* end main */ + +/* insert node into tree */ +void insertNode( TreeNodePtr *treePtr, int value ) +{ + + /* if tree is empty */ + if ( *treePtr == NULL ) { + *treePtr = malloc( sizeof( TreeNode ) ); + + /* if memory was allocated then assign data */ + if ( *treePtr != NULL ) { + ( *treePtr )->data = value; + ( *treePtr )->leftPtr = NULL; + ( *treePtr )->rightPtr = NULL; + } /* end if */ + else { + printf( "%d not inserted. No memory available.\n", value ); + } /* end else */ + + } /* end if */ + else { /* tree is not empty */ + + /* data to insert is less than data in current node */ + if ( value <= ( *treePtr )->data ) { + insertNode( &( ( *treePtr )->leftPtr ), value ); + } /* end if */ + + /* data to insert is greater than data in current node */ + else if ( value > ( *treePtr )->data ) { + insertNode( &( ( *treePtr )->rightPtr ), value ); + } /* end else if */ + + } /* end else */ + +} /* end function insertNode */ + +/* begin inorder traversal of tree */ +void inOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + inOrder( treePtr->leftPtr ); + printf( "%3d", treePtr->data ); + inOrder( treePtr->rightPtr ); + } /* end if */ + +} /* end function inOrder */ + +/* begin preorder traversal of tree */ +void preOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + printf( "%3d", treePtr->data ); + preOrder( treePtr->leftPtr ); + preOrder( treePtr->rightPtr ); + } /* end if */ + +} /* end function preOrder */ + +/* begin postorder traversal of tree */ +void postOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + postOrder( treePtr->leftPtr ); + postOrder( treePtr->rightPtr ); + printf( "%3d", treePtr->data ); + } /* end if */ + +} /* end function postOrder */ + +/* + * Delete a node from the tree +*/ +int deleteNode( TreeNodePtr *treePtr, int value ) +{ + TreeNodePtr rm_parentp = searchTree( *treePtr, value ); + TreeNodePtr *rm_childp; + TreeNodePtr currentPtr; + + /* a simple check */ + if( rm_parentp == NULL || *treePtr == NULL ) + return 1; + + /* set the "parent" pointer */ + if( rm_parentp->leftPtr != NULL && rm_parentp->leftPtr->data == value ) + rm_childp = &rm_parentp->leftPtr; + else + rm_childp = &rm_parentp->rightPtr; + + /* remove a leaf node */ + if( ( *rm_childp )->leftPtr == NULL && ( *rm_childp )->rightPtr == NULL ) { + + *rm_childp = NULL; + free( *rm_childp ); + } + /* remove a one-child node: is this code unreadable? :| */ + else if(((*rm_childp)->leftPtr != NULL) ^ ((*rm_childp)->rightPtr != NULL)) { + + rm_parentp = *rm_childp; + + if( ( *rm_childp )->leftPtr != NULL ) + *rm_childp = ( *rm_childp )->leftPtr; + else + *rm_childp = ( *rm_childp )->rightPtr; + + free( rm_parentp ); + } + /* remove a two-children node */ + else { + currentPtr = ( *rm_childp )->leftPtr; + while( currentPtr->rightPtr != NULL ) { + currentPtr = currentPtr->rightPtr; + } + + rm_parentp = *rm_childp; /* will be freed */ + + currentPtr->rightPtr = ( *rm_childp )->rightPtr; + ( *rm_childp )->rightPtr = NULL; + *rm_childp = ( *rm_childp )->leftPtr; + + free( rm_parentp ); + } + + return 0; +} /* eof deleteNode()*/ + +/* + * Find a node and returns its daddy +*/ +TreeNodePtr searchTree( TreeNodePtr treePtr, int value ) +{ + TreeNodePtr retp = treePtr; + + if( retp != NULL ) { + if( (retp->leftPtr != NULL && retp->leftPtr->data == value) || + (retp->rightPtr != NULL && retp->rightPtr->data == value) + ) return retp; + + if( retp->data > value ) + return searchTree( retp->leftPtr, value ); + else + return searchTree( retp->rightPtr, value ); + } + + return NULL; + +} /* eof searchTree() */ + diff --git a/exercises/deitel/ch12/inverse.c b/exercises/deitel/ch12/inverse.c @@ -0,0 +1,86 @@ +/* Exercise 12.9 */ + +#include <stdio.h> +#include <stdlib.h> + +struct list { + char c; + struct list *next; +}; +typedef struct list List; + +void showlist(List *list); +void r_showlist(List *list); +void insert(List **list, char value); + +int main(void) +{ + List *mylist = NULL; + int i; + + for(i = 0; i < 10; i++) + insert(&mylist, 65 + i); + + showlist(mylist); + r_showlist(mylist); + putchar('\n'); + + return 0; +} /* E0F main */ + +void showlist(List *list) +{ + List *currentPtr = list; + + if(currentPtr != NULL) { + printf("%c --> ", currentPtr->c); + showlist(currentPtr->next); + } + else { + printf("NULL\n"); + } + +} /* eof showlist() */ + +void r_showlist(List *list) +{ + List *currentPtr = list; + + if(currentPtr != NULL) { + r_showlist(currentPtr->next); + printf(" --> %c", currentPtr->c); + } + else { + printf("NULL"); + } + +} /* eof r_showlist() */ + +void insert(List **list, char value) +{ + List *newPtr; + List *previousPtr = NULL, *currentPtr = *list;; + + if( (newPtr = malloc( sizeof(List) )) == NULL) { + printf("Cannot allocate the memory\n"); + return; + } + newPtr->c = value; + newPtr->next = NULL; + + while( currentPtr != NULL && value > currentPtr->c) { + previousPtr = currentPtr; + currentPtr = currentPtr->next; + } + + if( previousPtr == NULL ) { + newPtr->next = *list; + *list = newPtr; + } + else { + previousPtr->next = newPtr; + newPtr->next = currentPtr; + } + +} /* eof insert() */ + diff --git a/exercises/deitel/ch12/levelOrder.c b/exercises/deitel/ch12/levelOrder.c @@ -0,0 +1,308 @@ +/* Exercise 12.24 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +/* Tree structure */ +struct treeNode { + struct treeNode *leftPtr; + int data; + struct treeNode *rightPtr; +}; +typedef struct treeNode TreeNode; +typedef TreeNode *TreeNodePtr; + +/* Queue structure */ +struct queue_t { + TreeNodePtr data; + struct queue_t *next; +}; +typedef struct queue_t Queue; + +/* + * Prototypes +*/ +void insertNode( TreeNodePtr *treePtr, int value ); +int deleteNode( TreeNodePtr *treePtr, int value ); + +void enqueue(Queue **head, Queue **tail, TreeNodePtr value); +TreeNodePtr dequeue(Queue **head, Queue **tail); + +void inOrder( TreeNodePtr treePtr ); +void preOrder( TreeNodePtr treePtr ); +void postOrder( TreeNodePtr treePtr ); +void levelOrder(TreeNodePtr root); + +/* + * NOTE: this function returns the parent node, not the node in itself. +*/ +TreeNodePtr searchTree( TreeNodePtr treePtr, int value ); + +/* function main begins program execution */ +int main(void) +{ + int i; /* counter to loop from 1-10 */ + int item; /* variable to hold random values */ + TreeNodePtr rootPtr = NULL; /* tree initially empty */ + + srand( time( NULL ) ); + printf( "The numbers being placed in the tree are:\n" ); + + /* insert random values between 1 and 15 in the tree */ + for ( i = 1; i <= 10; i++ ) { + item = rand() % 15; + printf( "%3d", item ); + insertNode( &rootPtr, item ); + } /* end for */ + + printf("\n\nInsert the value to remove: "); + scanf("%d", &item); + + if( deleteNode( &rootPtr, item ) ) { + printf("Value not found or value is root: %d\n", item); + return -1; + } + + /* traverse the tree preOrder */ + printf( "\nThe preOrder traversal is:\n" ); + preOrder( rootPtr ); + + /* traverse the tree inOrder */ + printf( "\n\nThe inOrder traversal is:\n" ); + inOrder( rootPtr ); + + /* traverse the tree postOrder */ + printf( "\n\nThe postOrder traversal is:\n" ); + postOrder( rootPtr ); + + /* traverse the tree levelOrder */ + printf( "\n\nThe levelOrder traversal is:\n" ); + levelOrder( rootPtr ); + + putchar('\n'); + + return 0; /* indicates successful termination */ + +} /* end main */ + +/* insert node into tree */ +void insertNode( TreeNodePtr *treePtr, int value ) +{ + + /* if tree is empty */ + if ( *treePtr == NULL ) { + *treePtr = malloc( sizeof( TreeNode ) ); + + /* if memory was allocated then assign data */ + if ( *treePtr != NULL ) { + ( *treePtr )->data = value; + ( *treePtr )->leftPtr = NULL; + ( *treePtr )->rightPtr = NULL; + } /* end if */ + else { + printf( "%d not inserted. No memory available.\n", value ); + } /* end else */ + + } /* end if */ + else { /* tree is not empty */ + + /* data to insert is less than data in current node */ + if ( value <= ( *treePtr )->data ) { + insertNode( &( ( *treePtr )->leftPtr ), value ); + } /* end if */ + + /* data to insert is greater than data in current node */ + else if ( value > ( *treePtr )->data ) { + insertNode( &( ( *treePtr )->rightPtr ), value ); + } /* end else if */ + + } /* end else */ + +} /* end function insertNode */ + +/* begin inorder traversal of tree */ +void inOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + inOrder( treePtr->leftPtr ); + printf( "%3d", treePtr->data ); + inOrder( treePtr->rightPtr ); + } /* end if */ + +} /* end function inOrder */ + +/* begin preorder traversal of tree */ +void preOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + printf( "%3d", treePtr->data ); + preOrder( treePtr->leftPtr ); + preOrder( treePtr->rightPtr ); + } /* end if */ + +} /* end function preOrder */ + +/* begin postorder traversal of tree */ +void postOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + postOrder( treePtr->leftPtr ); + postOrder( treePtr->rightPtr ); + printf( "%3d", treePtr->data ); + } /* end if */ + +} /* end function postOrder */ + +/* + * Delete a node from the tree +*/ +int deleteNode( TreeNodePtr *treePtr, int value ) +{ + TreeNodePtr rm_parentp = searchTree( *treePtr, value ); + TreeNodePtr *rm_childp; + TreeNodePtr currentPtr; + + /* a simple check */ + if( rm_parentp == NULL || *treePtr == NULL ) + return 1; + + /* set the "parent" pointer */ + if( rm_parentp->leftPtr != NULL && rm_parentp->leftPtr->data == value ) + rm_childp = &rm_parentp->leftPtr; + else + rm_childp = &rm_parentp->rightPtr; + + /* remove a leaf node */ + if( ( *rm_childp )->leftPtr == NULL && ( *rm_childp )->rightPtr == NULL ) { + + *rm_childp = NULL; + free( *rm_childp ); + } + /* remove a one-child node: is this code unreadable? :| */ + else if(((*rm_childp)->leftPtr != NULL) ^ ((*rm_childp)->rightPtr != NULL)) { + + rm_parentp = *rm_childp; + + if( ( *rm_childp )->leftPtr != NULL ) + *rm_childp = ( *rm_childp )->leftPtr; + else + *rm_childp = ( *rm_childp )->rightPtr; + + free( rm_parentp ); + } + /* remove a two-children node */ + else { + currentPtr = ( *rm_childp )->leftPtr; + while( currentPtr->rightPtr != NULL ) { + currentPtr = currentPtr->rightPtr; + } + + rm_parentp = *rm_childp; /* will be freed */ + + currentPtr->rightPtr = ( *rm_childp )->rightPtr; + ( *rm_childp )->rightPtr = NULL; + *rm_childp = ( *rm_childp )->leftPtr; + + free( rm_parentp ); + } + + return 0; +} /* eof deleteNode()*/ + +/* + * Find a node and returns its daddy +*/ +TreeNodePtr searchTree( TreeNodePtr treePtr, int value ) +{ + TreeNodePtr retp = treePtr; + + if( retp != NULL ) { + if( (retp->leftPtr != NULL && retp->leftPtr->data == value) || + (retp->rightPtr != NULL && retp->rightPtr->data == value) + ) return retp; + + if( retp->data > value ) + return searchTree( retp->leftPtr, value ); + else + return searchTree( retp->rightPtr, value ); + } + + return NULL; + +} /* eof searchTree() */ + +/* + * Insert a "value" to the queue +*/ +void enqueue(Queue **head, Queue **tail, TreeNodePtr value) +{ + Queue *newqueue; + + if( (newqueue = malloc( sizeof(Queue) )) == NULL ) { + printf("Cannot allocate the memory\n"); + return; + } + newqueue->data = value; + newqueue->next = NULL; + + /* if the queue is empty */ + if( *head == NULL ) { + *head = newqueue; + } + else { + ( *tail )->next = newqueue; + } + + *tail = newqueue; + +} /* eof enqueue() */ + +/* + * Remove an element from the queue and return its value +*/ +TreeNodePtr dequeue(Queue **head, Queue **tail) +{ + TreeNodePtr value; + Queue *temp = *head; + + value = ( *head )->data; + *head = ( *head )->next; + + /* if the queue is empty */ + if( *head == NULL ) { + *tail = NULL; + } + + free( temp ); + + return value; +} /* eof dequeue() */ + +/* + * Begin levelorder traversal of tree +*/ +void levelOrder(TreeNodePtr root) +{ + Queue *head = NULL, *tail = NULL; + TreeNodePtr currentNode; + + enqueue( &head, &tail, root ); + + while( head != NULL && (currentNode = dequeue(&head, &tail)) != NULL ) { + printf("%3d", currentNode->data); + + if( currentNode->leftPtr != NULL ) + enqueue(&head, &tail, currentNode->leftPtr); + + if( currentNode->rightPtr != NULL ) + enqueue(&head, &tail, currentNode->rightPtr); + } +} /* eof levelOrder() */ + diff --git a/exercises/deitel/ch12/listcalc.c b/exercises/deitel/ch12/listcalc.c @@ -0,0 +1,85 @@ +/* Exercise 12.8 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +struct list { + int n; + struct list *next; +}; + +typedef struct list List; + +void insert(List **list, int value); +void showlist(List *list); + +int main(void) +{ + List *mylist = NULL; + int i, sum = 0; + double media = 0; + + srand( time(NULL) ); + + for(i = 0; i < 25; i++) + insert(&mylist, 1 + rand() % 100); + + showlist(mylist); + + /* calculate the sum */ + while( mylist != NULL ) { + sum += mylist->n; + ++media; + + mylist = mylist->next; + } + + media = sum / media; + + printf("Sum: %d\nMedia: %.2f\n", sum, media); + + return 0; +} /* E0F main */ + +void showlist(List *list) +{ + List *currentPtr = list; + + while( currentPtr != NULL ) { + printf("%d --> ", currentPtr->n); + currentPtr = currentPtr->next; + } + + printf("NULL\n"); + +} /* eof showlist() */ + +void insert(List **list, int value) +{ + List *newPtr; + List *previousPtr = NULL, *currentPtr = *list;; + + if( (newPtr = malloc( sizeof(List) )) == NULL) { + printf("Cannot allocate the memory\n"); + return; + } + newPtr->n = value; + newPtr->next = NULL; + + while( currentPtr != NULL && value > currentPtr->n) { + previousPtr = currentPtr; + currentPtr = currentPtr->next; + } + + if( previousPtr == NULL ) { + newPtr->next = *list; + *list = newPtr; + } + else { + previousPtr->next = newPtr; + newPtr->next = currentPtr; + } + +} /* eof insert() */ + diff --git a/exercises/deitel/ch12/market.c b/exercises/deitel/ch12/market.c @@ -0,0 +1,110 @@ +/* Exercise 12.15 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define HOURS 12 +#define INTER 4 + +struct queue_t { + int client; + struct queue_t *next; +}; +typedef struct queue_t Queue; + +void enqueue(Queue **hqueuep, Queue **tqueuep, int value); +int dequeue(Queue **hqueuep, Queue **tqueuep); +char isempty(Queue *queuep); + +/* main function */ +int main(void) +{ + int c_time; /* current client */ + int s_time; /* service time */ + int i, client; + + Queue *hqueue = NULL, *tqueue = NULL; + + srand( time(NULL ) ); + + c_time = 1 + rand() % INTER; + + s_time = 1 + rand() % INTER; + c_time += 1 + rand() % INTER; + + /* For each minute of the work day (HOURS hours) */ + for(i = client = 0; i < 60 * HOURS; i++) { + + if( ! --c_time ) { + printf("[+]: %d\n", ++client); + enqueue(&hqueue, &tqueue, client); + c_time = 1 + rand() % INTER; + + if( ! --s_time ) { + printf("[-]: %d\n", dequeue(&hqueue, &tqueue)); + s_time = 1 + rand() % INTER; + } + } + } + + return 0; +} /* E0F main */ + +/* + * Determine if the stack is empty this is a "predicate function" +*/ +char isempty(Queue *queuep) +{ + if( queuep == NULL ) + return 1; + + return 0; +} /* eof isempty() */ + +/* + * Put another value in queue +*/ +void enqueue(Queue **hqueuep, Queue **tqueuep, int value) +{ + Queue *newqueue; + + if( (newqueue = malloc(sizeof(Queue))) == NULL) { + printf("Cannot allocate the memory\n"); + return; + } + newqueue->client = value; + newqueue->next = NULL; + + if( isempty( *hqueuep ) ) { + *hqueuep = newqueue; + } + else { + ( *tqueuep )->next = newqueue; + } + + *tqueuep = newqueue; + +} /* eof enqueue() */ + +/* + * Show and remove a value from the top of queue +*/ +int dequeue(Queue **hqueuep, Queue **tqueuep) +{ + Queue *tmpqueuep; + int ret; + + ret = ( *hqueuep )->client; + tmpqueuep = *hqueuep; + *hqueuep = ( *hqueuep )->next; + + if( *hqueuep == NULL ) { + *tqueuep = NULL; + } + + free( tmpqueuep ); + + return ret; +} /* eof dequeue() */ + diff --git a/exercises/deitel/ch12/merge.c b/exercises/deitel/ch12/merge.c @@ -0,0 +1,111 @@ +/* Exercise 12.7 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +struct list { + int n; + struct list *next; +}; + +typedef struct list List; + +/* + * Prorotype +*/ +void insert(List **list, int value); +void showlist(List *list); +List *merge(List *list, List *append); + +int main(void) +{ + List *list1 = NULL, *list2 = NULL; + List *list3; + int i; + + srand( time(NULL) ); + + for(i = 0; i < 10; i++) { + insert(&list1, 1 + rand() % 99); + insert(&list2, 1 + rand() % 99); + } + + list3 = merge(list1, list2); + + showlist(list1); + showlist(list2); + showlist(list3); + + return 0; +} /* E0F main */ + +void insert(List **list, int value) +{ + List *newPtr; + List *previousPtr = NULL, *currentPtr = *list;; + + if( (newPtr = malloc( sizeof(List) )) == NULL) { + printf("Cannot allocate the memory\n"); + return; + } + newPtr->n = value; + newPtr->next = NULL; + + while( currentPtr != NULL && value > currentPtr->n) { + previousPtr = currentPtr; + currentPtr = currentPtr->next; + } + + if( previousPtr == NULL ) { + newPtr->next = *list; + *list = newPtr; + } + else { + previousPtr->next = newPtr; + newPtr->next = currentPtr; + } + +} /* eof insert() */ + +void showlist(List *list) +{ + List *currentPtr = list; + + while( currentPtr != NULL ) { + printf("%d --> ", currentPtr->n); + currentPtr = currentPtr->next; + } + + printf("NULL\n"); + +} /* eof showlist() */ + +List *merge(List *list, List *append) +{ + List *currentPtr = list; + List *newPtr; + + if( (newPtr = malloc( sizeof(List) )) == NULL ) { + printf("Cannot allocate memory\n"); + return NULL; + } + newPtr = newPtr->next; + + /* insert list1 */ + while( currentPtr != NULL ) { + insert(&newPtr, currentPtr->n); + currentPtr = currentPtr->next; + } + + currentPtr = append; + + /* insert list2 */ + while( currentPtr != NULL ) { + insert(&newPtr, currentPtr->n); + currentPtr = currentPtr->next; + } + + return newPtr; +} /* eof merge() */ + diff --git a/exercises/deitel/ch12/outputTree.c b/exercises/deitel/ch12/outputTree.c @@ -0,0 +1,336 @@ +/* Exercise 12.25 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +/* Tree structure */ +struct treeNode { + struct treeNode *leftPtr; + int data; + struct treeNode *rightPtr; +}; +typedef struct treeNode TreeNode; +typedef TreeNode *TreeNodePtr; + +/* Queue structure */ +struct queue_t { + TreeNodePtr data; + struct queue_t *next; +}; +typedef struct queue_t Queue; + +/* + * Prototypes +*/ +void insertNode( TreeNodePtr *treePtr, int value ); +int deleteNode( TreeNodePtr *treePtr, int value ); + +void enqueue(Queue **head, Queue **tail, TreeNodePtr value); +TreeNodePtr dequeue(Queue **head, Queue **tail); + +void outputTree(TreeNodePtr root, int totalSpaces); + +void inOrder( TreeNodePtr treePtr ); +void preOrder( TreeNodePtr treePtr ); +void postOrder( TreeNodePtr treePtr ); +void levelOrder(TreeNodePtr root); + + +/* + * NOTE: this function returns the parent node, not the node in itself. +*/ +TreeNodePtr searchTree( TreeNodePtr treePtr, int value ); + +/* function main begins program execution */ +int main(void) +{ + int i; /* counter to loop from 1-10 */ + int item; /* variable to hold random values */ + TreeNodePtr rootPtr = NULL; /* tree initially empty */ + + srand( time( NULL ) ); + printf( "The numbers being placed in the tree are:\n" ); + + /* insert random values between 1 and 15 in the tree */ + for ( i = 1; i <= 10; i++ ) { + item = 1 + rand() % 10; + printf( "%3d", item ); + insertNode( &rootPtr, item ); + } /* end for */ + + printf("\n\nInsert the value to remove: "); + scanf("%d", &item); + + if( deleteNode( &rootPtr, item ) ) { + printf("Value not found or value is root: %d\n", item); + return -1; + } + + /* traverse the tree preOrder */ + printf( "\nThe preOrder traversal is:\n" ); + preOrder( rootPtr ); + + /* traverse the tree inOrder */ + printf( "\n\nThe inOrder traversal is:\n" ); + inOrder( rootPtr ); + + /* traverse the tree postOrder */ + printf( "\n\nThe postOrder traversal is:\n" ); + postOrder( rootPtr ); + + /* traverse the tree levelOrder */ + printf( "\n\nThe levelOrder traversal is:\n" ); + levelOrder( rootPtr ); + + puts("\n\nShow the tree\n\n"); + outputTree(rootPtr, 0); + + putchar('\n'); + + return 0; /* indicates successful termination */ + +} /* end main */ + +/* insert node into tree */ +void insertNode( TreeNodePtr *treePtr, int value ) +{ + + /* if tree is empty */ + if ( *treePtr == NULL ) { + *treePtr = malloc( sizeof( TreeNode ) ); + + /* if memory was allocated then assign data */ + if ( *treePtr != NULL ) { + ( *treePtr )->data = value; + ( *treePtr )->leftPtr = NULL; + ( *treePtr )->rightPtr = NULL; + } /* end if */ + else { + printf( "%d not inserted. No memory available.\n", value ); + } /* end else */ + + } /* end if */ + else { /* tree is not empty */ + + /* data to insert is less than data in current node */ + if ( value <= ( *treePtr )->data ) { + insertNode( &( ( *treePtr )->leftPtr ), value ); + } /* end if */ + + /* data to insert is greater than data in current node */ + else if ( value > ( *treePtr )->data ) { + insertNode( &( ( *treePtr )->rightPtr ), value ); + } /* end else if */ + + } /* end else */ + +} /* end function insertNode */ + +/* begin inorder traversal of tree */ +void inOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + inOrder( treePtr->leftPtr ); + printf( "%3d", treePtr->data ); + inOrder( treePtr->rightPtr ); + } /* end if */ + +} /* end function inOrder */ + +/* begin preorder traversal of tree */ +void preOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + printf( "%3d", treePtr->data ); + preOrder( treePtr->leftPtr ); + preOrder( treePtr->rightPtr ); + } /* end if */ + +} /* end function preOrder */ + +/* begin postorder traversal of tree */ +void postOrder( TreeNodePtr treePtr ) +{ + + /* if tree is not empty then traverse */ + if ( treePtr != NULL ) { + postOrder( treePtr->leftPtr ); + postOrder( treePtr->rightPtr ); + printf( "%3d", treePtr->data ); + } /* end if */ + +} /* end function postOrder */ + +/* + * Delete a node from the tree +*/ +int deleteNode( TreeNodePtr *treePtr, int value ) +{ + TreeNodePtr rm_parentp = searchTree( *treePtr, value ); + TreeNodePtr *rm_childp; + TreeNodePtr currentPtr; + + /* a simple check */ + if( rm_parentp == NULL || *treePtr == NULL ) + return 1; + + /* set the "parent" pointer */ + if( rm_parentp->leftPtr != NULL && rm_parentp->leftPtr->data == value ) + rm_childp = &rm_parentp->leftPtr; + else + rm_childp = &rm_parentp->rightPtr; + + /* remove a leaf node */ + if( ( *rm_childp )->leftPtr == NULL && ( *rm_childp )->rightPtr == NULL ) { + + *rm_childp = NULL; + free( *rm_childp ); + } + /* remove a one-child node: is this code unreadable? :| */ + else if(((*rm_childp)->leftPtr != NULL) ^ ((*rm_childp)->rightPtr != NULL)) { + + rm_parentp = *rm_childp; + + if( ( *rm_childp )->leftPtr != NULL ) + *rm_childp = ( *rm_childp )->leftPtr; + else + *rm_childp = ( *rm_childp )->rightPtr; + + free( rm_parentp ); + } + /* remove a two-children node */ + else { + currentPtr = ( *rm_childp )->leftPtr; + while( currentPtr->rightPtr != NULL ) { + currentPtr = currentPtr->rightPtr; + } + + rm_parentp = *rm_childp; /* will be freed */ + + currentPtr->rightPtr = ( *rm_childp )->rightPtr; + ( *rm_childp )->rightPtr = NULL; + *rm_childp = ( *rm_childp )->leftPtr; + + free( rm_parentp ); + } + + return 0; +} /* eof deleteNode()*/ + +/* + * Find a node and returns its daddy +*/ +TreeNodePtr searchTree( TreeNodePtr treePtr, int value ) +{ + TreeNodePtr retp = treePtr; + + if( retp != NULL ) { + if( (retp->leftPtr != NULL && retp->leftPtr->data == value) || + (retp->rightPtr != NULL && retp->rightPtr->data == value) + ) return retp; + + if( retp->data > value ) + return searchTree( retp->leftPtr, value ); + else + return searchTree( retp->rightPtr, value ); + } + + return NULL; + +} /* eof searchTree() */ + +/* + * Insert a "value" to the queue +*/ +void enqueue(Queue **head, Queue **tail, TreeNodePtr value) +{ + Queue *newqueue; + + if( (newqueue = malloc( sizeof(Queue) )) == NULL ) { + printf("Cannot allocate the memory\n"); + return; + } + newqueue->data = value; + newqueue->next = NULL; + + /* if the queue is empty */ + if( *head == NULL ) { + *head = newqueue; + } + else { + ( *tail )->next = newqueue; + } + + *tail = newqueue; + +} /* eof enqueue() */ + +/* + * Remove an element from the queue and return its value +*/ +TreeNodePtr dequeue(Queue **head, Queue **tail) +{ + TreeNodePtr value; + Queue *temp = *head; + + value = ( *head )->data; + *head = ( *head )->next; + + /* if the queue is empty */ + if( *head == NULL ) { + *tail = NULL; + } + + free( temp ); + + return value; +} /* eof dequeue() */ + +/* + * Begin levelorder traversal of tree +*/ +void levelOrder(TreeNodePtr root) +{ + Queue *head = NULL, *tail = NULL; + TreeNodePtr currentNode; + + enqueue( &head, &tail, root ); + + while( head != NULL && (currentNode = dequeue(&head, &tail)) != NULL ) { + printf("%3d", currentNode->data); + + if( currentNode->leftPtr != NULL ) + enqueue(&head, &tail, currentNode->leftPtr); + + if( currentNode->rightPtr != NULL ) + enqueue(&head, &tail, currentNode->rightPtr); + } +} /* eof levelOrder() */ + +/* + * Show a binary tree +*/ +void outputTree(TreeNodePtr root, int totalSpaces) +{ + int i; + TreeNodePtr currentNode = root; + + while( currentNode != NULL ) { + + outputTree(currentNode->rightPtr, totalSpaces + 5); + + for(i = 1; i <= totalSpaces; i++) + putchar(' '); + printf("%d\n", currentNode->data); + + currentNode = currentNode->leftPtr; + totalSpaces += 5; + } + +} /* eof outputTree() */ + diff --git a/exercises/deitel/ch12/palindrom.c b/exercises/deitel/ch12/palindrom.c @@ -0,0 +1,85 @@ +/* Exercise 12.11 */ + +#include <stdio.h> +#include <stdlib.h> + +struct stack_t { + char c; + struct stack_t *next; +}; + +typedef struct stack_t Stack; + +int palindrom(char *s); +void push(Stack **stack, char value); +char pop(Stack **stack); + +int main(void) +{ + char *string; + + printf("Give me a string: "); + scanf("%s", string); + + printf("The string is "); + if( palindrom(string) ) { + putchar('a'); + } + else { + printf("NOT a"); + } + printf(" palindrom\n"); + + return 0; +} /* E0F main */ + +void push(Stack **stack, char value) +{ + Stack *newnode; + + if( (newnode = malloc( sizeof(Stack) )) == NULL ) { + printf("Cannot allocate the memory\n"); + return; + } + newnode->c = value; + newnode->next = *stack; + + *stack = newnode; + +} /* eof push() */ + +char pop(Stack **stack) +{ + Stack *stackp; + char ret; + + ret = ( *stack )->c; + + stackp = *stack; + *stack = ( *stack )->next; + + free(stackp); + + return ret; +} /* eof pop() */ + +int palindrom(char *s) +{ + Stack *stackp = NULL; + int i = 0; + + /* push the string */ + while( s[i] != '\0' ) { + push(&stackp, s[i++]); + } + + /* pop the string and check the order */ + i = 0; + while( stackp != NULL ) { + if( pop(&stackp) != s[i++] ) + return 0; + } + + return 1; +} /* eof palindrom() */ + diff --git a/exercises/deitel/ch12/searchList.c b/exercises/deitel/ch12/searchList.c @@ -0,0 +1,112 @@ +/* Exercise 12.21 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +struct list_t { + int data; + struct list_t *next; +}; +typedef struct list_t List; + +void insert(List **listp, int value); +void printl(List *listp); +List *searchList(List *listp, int value); + +int main(void) +{ + int number; + List *mylist = NULL; + List *myvalue = NULL; + + srand( time(NULL) ); + + /* populate the list */ + for(number = 0; number < 10; number++) { + insert(&mylist, 1 + rand() % 100); + } + + printf("What value you are looking for? : "); + scanf("%d", &number); + + myvalue = searchList(mylist, number); + + printl(mylist); + + putchar('\n'); + + if( myvalue != NULL ) { + printf("Found %d to the list. Printing the remaining values..\n", number); + printl(myvalue); + } + else { + printf("Can't find %d to the list\n", number); + } + + return 0; +} /* E0F main */ + +/* + * Insert a value to the list +*/ +void insert(List **listp, int value) +{ + List *newptr; + List *currentPtr; + List *previousPtr = NULL; + + if( (newptr = malloc( sizeof(List) )) == NULL ) { + printf("Cannot allocate the memory: %d not inserted\n", value); + return; + } + newptr->data = value; + newptr->next = NULL; + + currentPtr = *listp; + + while( currentPtr != NULL && value > currentPtr->data ) { + previousPtr = currentPtr; + currentPtr = currentPtr->next; + } + + if( previousPtr == NULL ) { + newptr->next = *listp; + *listp = newptr; + } + else { + previousPtr->next = newptr; + newptr->next = currentPtr; + } + +} /* eof insert() */ + +/* + * Print a the list values using '-->' as separator +*/ +void printl(List *listp) +{ + List *currentPtr = listp; + + while( currentPtr != NULL ) { + printf("%d --> ", currentPtr->data); + currentPtr = currentPtr->next; + } + puts("NULL"); + +} /* eof printl() */ + +/* + * Found a value to the list and returns a pointer to its position +*/ +List *searchList(List *listp, int value) +{ + List *currentPtr = listp; + + while( currentPtr != NULL && currentPtr->data != value ) + currentPtr = currentPtr->next; + + return currentPtr; + +} /* eof searchList() */ + diff --git a/exercises/deitel/ch12/semplice.txt b/exercises/deitel/ch12/semplice.txt @@ -0,0 +1,87 @@ +/* Exercise 12.26 */ + +--- a) +10 rem Prendo in input 3 numeri +11 input a +12 input b +13 input c +20 rem Determino la media +21 let s = (a + b + c) / 3 +30 rem Stampo il risultato +31 print s + +--- b) +10 rem Prendo in input n interi fino al valore sentinella +11 input n +12 if n == -9999 goto 31 +20 rem Aggiungo n a s (s += n) +21 let s = s + n +22 goto 11 +30 rem Stampo il risultato e termino l'esecuzione +31 print s +32 end + +--- c) +10 rem Prendo in input 7 interi +11 let i = 7 +12 if i < 0 goto 21 +13 input n +14 let s = s + n +15 let i = i - 1 +16 goto 12 +20 rem Calcolo la media +21 let m = s / 7 +22 print m +23 end + +--- d) +10 rem Prendo il primo intero +11 input i +12 let n = i +13 if i == 0 goto 27 +20 rem Prendo in input i numeri +21 input n +22 if i > n goto 24 +23 let n = i +24 let i = i - 1 +25 goto 13 +26 rem Stampo il maggiore ed esco +27 print n +28 end + +--- e) +10 rem Prendo in input 10 interi +11 let i = 10 +13 input x +13 if i == 0 goto 20 +14 input y +15 if y > x goto 17 +16 let x = y +17 let i = i - 1 +18 goto 13 +19 rem Stampo il minore ed esco +20 print x +21 end + +--- f) +10 rem Ciclo gli interi pari tra 2 e 20 (inclusi) +11 let i = 2 +12 let n = n + i +20 if i == 30 goto 31 +21 let i = i + 2 +22 goto 12 +30 rem Stampo la somma ed esco +31 print n +32 end + +--- g) +10 rem Ciclo gli interi dispari tra 1 e 9 (inclusi) +11 let i = 1 +12 let n = n * i +20 if i == 9 goto 31 +21 let i = i + 2 +22 goto 12 +30 rem Stampo il prodotto ed esco +31 print n +32 end + diff --git a/exercises/deitel/ch12/stackinv.c b/exercises/deitel/ch12/stackinv.c @@ -0,0 +1,84 @@ +/* Exercise 12.10 */ + +#include <stdio.h> +#include <stdlib.h> + +struct stack { + char c; + struct stack *next; +}; + +typedef struct stack Stack; + +/* + * Prototype +*/ +void reverse(char *s); +void push(Stack **sPtr, char val); +char pop(Stack **s); + +int main(void) +{ + char *string; + + printf("Give me a string: "); + scanf("%s", string); + + reverse(string); + + return 0; +} /* E0F main */ + +void reverse(char *s) +{ + int i; + char c; + Stack *mystack; + + if( (mystack = malloc( sizeof(Stack) )) == NULL ) { + printf("Cannot allocate the memory\n"); + return; + } + mystack->next = NULL; + + for(i = 0; s[i] != '\0'; i++) + push(&mystack, s[i]); + + while( (c = pop(&mystack)) != '\0' ) + printf("%c", c); + + putchar('\n'); + +} /* eof reverse() */ + +void push(Stack **sPtr, char val) +{ + Stack *newNode; + + if( (newNode = malloc( sizeof(Stack) )) == NULL ) { + printf("Cannot allocate the memory\n"); + return; + } + + newNode->c = val; + newNode->next = *sPtr; + + *sPtr = newNode; + +} /* eof push() */ + +char pop(Stack **s) +{ + char c; + Stack *temp; + + temp = *s; + + c = ( *s )->c; + *s = ( *s )->next; + + free(temp); + + return c; +} /* eof pop() */ + diff --git a/exercises/deitel/ch12/topostfix.c b/exercises/deitel/ch12/topostfix.c @@ -0,0 +1,206 @@ +/* Exercise 12.12 */ + +#include <stdio.h> +#include <stdlib.h> +#include <ctype.h> +#include <string.h> + +#define BUF 50 + +struct stack_t { + char c; + struct stack_t *next; +}; +typedef struct stack_t Stack; + +/* + * Prototypes +*/ +int isoper(char c); +int precedence(char op1, char op2); +void push(Stack **stackp, char value); +char pop(Stack **stackp); +char stacktop(Stack *stackp); +char isempty(Stack *stackp); +void topostfix(char infix[], char postfix[]); + +/* main function */ +int main(void) +{ + char string1[BUF] = { 0 }; + char string2[BUF] = { 0 }; + + printf("Insert an expression: "); + fgets(string1, BUF, stdin); + + topostfix(string1, string2); + + printf("To polish infix notation: %s\n", string2); + + return 0; +} /* E0F main */ + +/* + * Check if 'c' is a valid operator +*/ +int isoper(char c) +{ + switch(c) { + case '+': + case '-': + case '*': + case '/': + case '^': + case '%': + return 1; + } + + return 0; +} /* eof isoper() */ + +/* + * Determine if the priority of op1 is less then, equal to + * or greter then op2 and return respectively, -1, 0 and 1. +*/ +int precedence(char op1, char op2) +{ + int x = 2; + char *p = &op1; + + while( x-- ) { + if( !x ) + p = &op2; + + switch( *p ) { + case '%': + case '/': + case '*': + *p = '1'; + break; + case '-': + case '+': + *p = '2'; + break; + case '^': + *p = '3'; + break; + default: + return -1; + } + + } + + x = (op1 - '0') - (op2 - '0'); + + if( x > 0 ) + return 1; + else if( x < 0 ) + return -1; + + return 0; +} /* eof precedence() */ + +/* + * Push a value in top of the stack +*/ +void push(Stack **stackp, char value) +{ + Stack *newnode; + + if( (newnode = malloc( sizeof(Stack) )) == NULL ) { + printf("push(): cannot allocate the memory\n"); + return; + } + + newnode->c = value; + newnode->next = *stackp, + + *stackp = newnode; + +} /* eof push() */ + +/* + * Pop a value from top of the stack +*/ +char pop(Stack **stackp) +{ + Stack *tstackp; /* temporary stack pointer for free(3) */ + char ret = ( *stackp )->c; + + tstackp = *stackp; + *stackp = ( *stackp )->next; + + free(tstackp); + + return ret; +} /* eof pop() */ + +/* + * As pop() but don't extract the value from top of stack + * This is a "predicate function" +*/ +char stacktop(Stack *stackp) +{ + return stackp->c; +} /* eof stacktop() */ + +/* + * Determine if the stack is empty + * This is a "predicate function" +*/ +char isempty(Stack *stackp) +{ + if( stackp == NULL ) + return 1; + + return 0; +} /* eof isempty() */ + +/* + * Convert from infix format to reverse polish suffix + * E.g.: + * + * The expression (1 + 5) * 9 - 2 / 6 + * is equivalent to 1 5 + 9 * 2 6 / - + * +*/ +void topostfix(char infix[], char postfix[]) +{ + Stack *stackp = NULL; + int i = 0, j = 0; + + push(&stackp, '('); + infix[ (int)strlen(infix) ] = ')'; + infix[ (int)strlen(infix) ] = '\0'; + + while( ! isempty(stackp) ) { + if( isspace( (int)infix[i] ) ) ; /* ignore the blank spaces */ + + else if( isdigit((int)infix[i]) ) { + postfix[j++] = infix[i]; + } + else if( infix[i] == '(' ) { + push(&stackp, '('); + } + else if( isoper(infix[i]) ) { + postfix[j++] = ' '; + + while( precedence(infix[i], stacktop(stackp)) != -1 ) { + postfix[j++] = pop(&stackp); + } + + push(&stackp, infix[i]); + postfix[j++] = ' '; + } + else if( infix[i] == ')' ) { + postfix[j++] = ' '; + while( stacktop(stackp) != '(' && isoper(stacktop(stackp)) ) { + postfix[j++] = pop(&stackp); + } + pop(&stackp); /* remove the '(' from the stack */ + } + + ++i; + } +} /* eof topostfix() */ + diff --git a/exercises/deitel/ch3/3.46/intcrypt.c b/exercises/deitel/ch3/3.46/intcrypt.c @@ -0,0 +1,37 @@ +/* + * Esercizio 3.46 + * Questo software cifra un intero di 4 cifre. + * + * Algoritmo: sostituisce ogni cifra con il resto della + * divisione di (la somma di quella cifra più 7) per 10. + * In seguito, scambia la prima cifra con la terza e la + * seconda con la quarta. + * + * NOTA: 7 cifra, 3 decifra. +*/ + +#include <stdio.h> + +int main() +{ + int num; + int p, s, t, q; + + printf("Inserire l'intero da cifrare: "); + scanf("%d", &num); + + p = num / 1000 % 10; /* primo */ + s = num / 100 % 10; /* secondo */ + t = num / 10 % 10; /* terzo */ + q = num / 1 % 10; /* quarto */ + + p = (p + 7) % 10; + s = (s + 7) % 10; + t = (t + 7) % 10; + q = (q + 7) % 10; + + printf("Numero cifrato: %d%d%d%d\n", t, q, p, s); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/3.46/intdecrypt.c b/exercises/deitel/ch3/3.46/intdecrypt.c @@ -0,0 +1,37 @@ +/* + * Esercizio 3.46 + * Questo software decifra un intero di 4 cifre. + * + * Algoritmo: sostituisce ogni cifra con il resto della + * divisione di (la somma di quella cifra più 3) per 10. + * In seguito, scambia la prima cifra con la terza e la + * seconda con la quarta. + * + * NOTA: 3 decifra, 7 cifra. +*/ + +#include <stdio.h> + +int main() +{ + int num; + int p, s, t, q; + + printf("Inserire l'intero da decifrare: "); + scanf("%d", &num); + + p = num / 1000 % 10; /* primo */ + s = num / 100 % 10; /* secondo */ + t = num / 10 % 10; /* terzo */ + q = num / 1 % 10; /* quarto */ + + p = (p + 3) % 10; + s = (s + 3) % 10; + t = (t + 3) % 10; + q = (q + 3) % 10; + + printf("Numero decifrato: %d%d%d%d\n", t, q, p, s); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/3.47/esA.c b/exercises/deitel/ch3/3.47/esA.c @@ -0,0 +1,27 @@ +/* + * Esercizio 3.47 (a) + * +*/ + +#include <stdio.h> + +int main() +{ + int n, ncp, norig; /* intero e "copia di intero" */ + int i; /* contatore */ + + printf("Inserisci un numero: "); + scanf("%d", &n); + + if (n >= 1) { + norig = ncp = n; /* creo una copia di n per poterla decrementare */ + i = n; /* imposto il contatore */ + while(--i > 0) + n *= --ncp; + printf("%d! = %d\n", norig, n); + } + else printf("Non sono ammessi numeri negativi!\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/3.47/esB.c b/exercises/deitel/ch3/3.47/esB.c @@ -0,0 +1,34 @@ +/* + * Esercizio 3.47 (b) + * +*/ + +#include <stdio.h> + +int main() +{ + float e = 1.0; /* e = 1 + ... */ + + int ncp; /* e "copia di intero" */ + int n = 1; /* fattoriale di intero */ + int i, c = 1; /* contatori */ + + while(c < 34) { + n = c; /* n + 1 */ + + ncp = n; /* creo una copia di n per poterla decrementare */ + i = n; /* imposto il contatore */ + while(--i > 0) + n *= --ncp; + + /* n = c! */ + + e += (float) c / n; + ++c; + } + + printf("e = %.2f\n", e); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/3.47/esC.c b/exercises/deitel/ch3/3.47/esC.c @@ -0,0 +1,45 @@ +/* Esercizio 3.47 (c) */ + +#include <stdio.h> + +int main() +{ + /* Costanti */ + float e = 1.0; /* e = 1 + ... */ + int x = 1; + + int p_count; /* contatore per la potenza */ + int f_count; /* contatore per il fattoriale */ + + int fatt; /* fattoriale */ + int c_fatt; /* copia del fattoriale per il decremento */ + + int c_val = 1; /* common value: fattoriale e potenza */ + + while(c_val < 5) { + fatt = c_fatt = c_val; /* Reinizializzo */ + p_count = f_count = 1; /* le variabili. */ + + /* elevo x a potenza */ + while(++p_count < c_val) + x *= x; + + /* calcolo il fattoriale */ + while(--c_fatt > 1) + fatt = --c_fatt; + + /* elevo e a potenza */ + p_count = 1; + while(++p_count < c_val) + e *= e; + + e += (float) x / fatt; + + ++c_val; + } + + printf("e elevato a x = %.2f\n", e); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/asterisk.c b/exercises/deitel/ch3/asterisk.c @@ -0,0 +1,21 @@ +/* + * Esercizio 3.38 + * Visualizza 100 asterischi uno per volta. +*/ + +#include <stdio.h> + +int main() +{ + int i = 1; + + while(i <= 100) { + printf("*"); + if (i % 10 == 0) + printf("\n"); + ++i; + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/bin2dec.c b/exercises/deitel/ch3/bin2dec.c @@ -0,0 +1,37 @@ +/* + * Esercizio 3.36 + * Convertitore di numeri: da binario a decimale. +*/ + +#include <stdio.h> + +int main() +{ + int num, i = 1; + + printf("Numero binario: "); + scanf("%d", &num); + + if (num > 9999) + printf("Sono ammessi solo valori a 4 cifre!\n"); + else { + while(i <= 1000) { + if (num / i % 10 != 1) + if (num / i % 10 != 0) { + printf("Sono ammessi solo numeri binari!\n"); + break; + } + + i *= 10; + } + } + + if (i > 1000) { + printf("Numero decimale: %d\n", + (num % 10) + (num / 10 % 10) * 2 + + (num / 100 % 10) * 4 + (num / 1000 % 10) * 8); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/cerchio2.c b/exercises/deitel/ch3/cerchio2.c @@ -0,0 +1,21 @@ +/* Esercizio 2.20 (Cap. 2) + Leggo il raggio di un cerchio e calcolo il diametro, + la circonferenza e l'aria dello stesso */ + +#include <stdio.h> + +int main() +{ + float raggio; + + printf("Raggio del cerchio: "); + scanf("%f", &raggio); + + printf("Diametro: %.2f\n", raggio * 2.0); + printf("Circonferenza: %.2f\n", 3.14159 * 2 * raggio); + printf("Area %.2f\n", raggio*raggio * 3.14159); + + return 0; + +} /* E0F main */ + diff --git a/exercises/deitel/ch3/chkseven.c b/exercises/deitel/ch3/chkseven.c @@ -0,0 +1,26 @@ +/* + * Esercizio 3.39 + * Conta le occorrenze dei numeri '7' di un intero +*/ + +#include <stdio.h> + +int main() +{ + int num, tot = 0; /* Numero inserito e totale */ + int i = 1; + + printf("Dammi un intero: "); + scanf("%d", &num); + + while(i <= 10000) { + if (num / i % 10 == 7) + ++tot; + i *= 10; + } + + printf("Sono state trovate %d occorrenze\n", tot); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/compsum.c b/exercises/deitel/ch3/compsum.c @@ -0,0 +1,20 @@ +/* Esercizio 3.5 (Cap 3) + Calcola la somma degli interi da 1 a 10 */ + +#include <stdio.h> + +int main() +{ + int sum = 0, x = 1; /* Inizializzo le variabili */ + + while(x <= 10) { + sum += x; + x++; + } + + /* Stampo i risultati */ + printf("The sum is: %d\n", sum); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/dynchess.c b/exercises/deitel/ch3/dynchess.c @@ -0,0 +1,26 @@ +/* + * Esercizio 3.40 + * Visualizzo una scacchiera con 3 printf(1); +*/ + +#include <stdio.h> + +int main() +{ + int x = 1, y; /* contatori */ + + while(x <= 8) { + y = 0; + while(y < 8) { + printf("* "); + ++y; + } + printf("\n"); + if (x % 2) + printf(" "); + ++x; + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/fig03_10fix.c b/exercises/deitel/ch3/fig03_10fix.c @@ -0,0 +1,53 @@ +/* Fig. 3.10: fig03_10.c + Analisi dei risultati dell'esame */ +#include <stdio.h> + +/* l'esecuzione del programma inizia dalla funzione main */ +int main() +{ + /* inizializza le variabili nelle dichiarazioni */ + int passes = 0; /* numero di promozioni */ + int failures = 0; /* numero di bocciature */ + int student = 1; /* conttore degli studenti */ + int result; /* risultato di un esame */ + + /* elabora 10 studenti; ciclo controllato da un contatore */ + while ( student <= 10 ) { + + /* sollecita l'utente a inserire i dati e ottiene i valori + da quest'ultimo */ + printf( "Enter result (1=pass,2=fail): "); + scanf("%d", &result ); + + /* se il risultato è 1, incremente il numero di promozioni */ + if ( result == 1 ) { + passes = passes + 1; + } /* fine del ramo if */ + else if ( result == 2 ) { /* altrimenti incremente le bocciature */ + failures = failures + 1; + } /* fine del raom else */ + else { + printf("Valore non corretto (%d)\n", result); + continue; + } + + student = student +1; /* incremente il contatore degli studenti */ + } /* fine del comando while */ + + /* fase di terminazione; visualizza il numero di promozioni + e di bocciature */ + printf( "Passed %d\n", passes ); + printf( "Failed %d\n", failures ); + + /* se più di otto studenti sono stati promossi, visualizza + "raise tuition" */ + if ( passes > 8 ) { + printf( "Raise tuition\n" ); + } /* fine del comando if */ + + return 0; /* chiusura con successo */ + +} /* fine della funzione main */ + + + diff --git a/exercises/deitel/ch3/getkm.c b/exercises/deitel/ch3/getkm.c @@ -0,0 +1,60 @@ +/* Esercizio 3.17 (Cap. 3) + * Mostra i Km per litro di ogni tanta e, infine, di tutte le tange assieme. + * + -*- Pseudo-codice -*- + Primo raffinamento: + Prende i Km percorsi e i litri utilizzati per ogni pieno. + Calcola i Km per litro di ogni pieno + Calcola i Km per litro totali + + Secondo raffinamento: + Inizializzo il totale dei Km + Inizializzo il totale dei Litri + + prendi il numero dei litri (o il valore dummy) + prendi il numero dei Km + + Finche' non viene immesso il valore dummy + dividi i km inseriti per i litri inseriti + stampa il risultato + salva la somma dei litri + salva la somme dei Km + + prendi il numero dei litri (o il valore dummy) + se non e' stato inserito il valore dummy + prendi il numero dei Km + + dividi il totale dei Km per il totale dei Litri + stampa il risultato + -*- Fine Pseudo-codice -*- +*/ + +#include <stdio.h> + +int main() +{ + int tot_km=0, km; /* Kilometri */ + float tot_litri=0, litri; /* Litri */ + + printf("Numero di litri utilizzati (-1, esce): "); + scanf("%f", &litri); + + /* Calcolo i Km/l per il pieno corrente */ + while(litri != -1) { + printf("Numero di Km percorsi: "); + scanf("%d", &km); + tot_litri += litri; + tot_km += km; + + printf("Km percorsi per litro: %f\n\n", km / litri); + + printf("Numero di litri utilizzati (-1, esce): "); + scanf("%f", &litri); + } + + /* Calcolo i Km/l per il totale dei pieni */ + printf("Totale Km/l: %f\n", tot_km / tot_litri); + + +} /* E0F main */ + diff --git a/exercises/deitel/ch3/getprov.c b/exercises/deitel/ch3/getprov.c @@ -0,0 +1,24 @@ +/* Esercizio 3.19 (Cap. 3) + * + * Calcolo il salario settimanale degli + * operai di un'azienda chimica +*/ + +#include <stdio.h> + +int main() +{ + float lorde; + + printf("Vendite lorde (-1 esce): "); + scanf("%f", &lorde); + + while((int)lorde != -1) { + printf("Salario: $%.2f\n\n", lorde * 9 / 100 + 200); + printf("Vendite lorde (-1 esce): "); + scanf("%f", &lorde); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/howfast.c b/exercises/deitel/ch3/howfast.c @@ -0,0 +1,20 @@ +/* + * Esercizio 3.37 + * Calcola la velocità del PC +*/ + +#include <stdio.h> + +int main() +{ + int i = 1; + + while(i < 3000000) { + if (i % 1000000 == 0) + printf("%d\n", i); + ++i; + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/infloop.c b/exercises/deitel/ch3/infloop.c @@ -0,0 +1,17 @@ +/* + * Esercizio 3.41 + * Stampa i multipli di 2 all'infinito +*/ + +#include <stdio.h> + +int main() +{ + int i = 2; + + while(1) + printf("%d\n", i *= 2); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/interest.c b/exercises/deitel/ch3/interest.c @@ -0,0 +1,29 @@ +/* Esercizio 3.20 (Cap. 3) + * + * Calcola l'interesse semplice di un mutuo +*/ + +#include <stdio.h> + +int main() +{ + float principal, rate; + int days; + + printf("Inserire capitale: "); + scanf("%f", &principal); + + while((int)principal != -1) { + printf("Inserire tasso: "); + scanf("%f", &rate); + printf("Inserire i giorni: "); + scanf("%d", &days); + + printf("Interesse semplice: %.2f\n\n", principal * rate * days / 365); + printf("Inserire capitale: "); + scanf("%f", &principal); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/largest.c b/exercises/deitel/ch3/largest.c @@ -0,0 +1,25 @@ +/* Esercizio 3.24 (Cap. 3) + * + * Trovo il più grande tra una serie di numeri +*/ + +#include <stdio.h> + +int main() +{ + int counter = 1, largest = 0, number; + + while(counter <= 10) { + printf("Inserisci un numero [%d di 10]: ", counter); + scanf("%d", &number); + + if (number > largest) + largest = number; + + ++counter; + } + + printf("Il numero più grande è %d\n", largest); + + return 0; +} /* E0F main */ diff --git a/exercises/deitel/ch3/largest2.c b/exercises/deitel/ch3/largest2.c @@ -0,0 +1,31 @@ +/* Esercizio 3.27 + * + * Trova i 2 numeri maggiori tra 10 numeri +*/ + +#include <stdio.h> + +int main() +{ + int largest = 0, largest2 = 0, counter = 1, number; + + while(counter <= 10) { + printf("Dammi un numero [%d di 10]: ", counter); + scanf("%d", &number); + + if (number > largest2) { + if (number > largest) { + largest2 = largest; + largest = number; + } + else largest2 = number; + } + + ++counter; + } + + printf("I 2 presunti largest sono %d e %d\n", largest2, largest); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/outofbadjet.c b/exercises/deitel/ch3/outofbadjet.c @@ -0,0 +1,45 @@ +/* Esercizio 3.18 (Cap 3) + * + * Determino se il cliente abbia superato + * il limite di credito sul suo conto. +*/ + +#include <stdio.h> + +int main() +{ + int account; /* Numero cliente */ + float saldoIniz, limiteCred, totArts, totCred; + + printf("Numero di conto (-1 esce): "); + scanf("%d", &account); + + while(account != -1) { + printf("Saldo iniziale: "); + scanf("%f", &saldoIniz); + + printf("Totale articoli in conto: "); + scanf("%f", &totArts); + + printf("Totale crediti: "); + scanf("%f", &totCred); + + printf("Limite di credito: "); + scanf("%f", &limiteCred); + + if ((saldoIniz + totArts - totCred) > limiteCred) { + printf("Account:\t%d\n", account); + printf("Credit limit:\t%2.f\n", limiteCred); + printf("Balance:\t%2.f\n", saldoIniz + totArts - totCred); + printf("Credit Limit Exceeded.\n"); + } + + printf("\nNumero di conto (-1 esce): "); + scanf("%d", &account); + + } + + return 0; + +} /* E0F main */ + diff --git a/exercises/deitel/ch3/palindromo.c b/exercises/deitel/ch3/palindromo.c @@ -0,0 +1,27 @@ +/* Esercizio 3.35 + * + * Dato un intero stabilisce se + * questo è un palindromo o no. +*/ + +#include <stdio.h> + +int main() +{ + int numero, yn = 0; + + printf("Inserisci un numero: "); + scanf("%d", &numero); + + if (numero / 10000 % 10 == numero % 10) + if (numero / 1000 % 10 == numero / 10 % 10) + yn = 1; + + if (yn) + printf("%d è un numero palindromo.\n", numero); + else + printf("%d NON è un numero palindromo.\n", numero); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/pow.c b/exercises/deitel/ch3/pow.c @@ -0,0 +1,23 @@ +/* Esercizio 3.8 (Cap 3) + Calcola la potenza di x elevato a y */ + +#include <stdio.h> + +int main() +{ + int i = 1, power = 1; + int x, y; /* Variabili per l'input */ + + printf("Dammi 2 interi, x elevato a y: "); + scanf("%d%d", &x, &y); + + while(i <= y) { + power *= x; + ++i; + } + + printf("%d elevato a %d è uguale a %d\n", x, y, power); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/ppdec.c b/exercises/deitel/ch3/ppdec.c @@ -0,0 +1,25 @@ +/* Esercizio 3.22 (Cap. 3) + * + * Dimostra la differenza tra il predecremento + * e il postdecremento utilizzando l'operatore --. +*/ + +#include <stdio.h> + +int main() +{ + int i = 10; + + printf("i vale %d: verrà postdecrementata 5 volte..\n", i); + while(i > 5) + printf("ciclo: i-- vale %d\n", i--); + + printf("Quì i vale %d: verrà predecrementata altre 5 volte..\n", i); + while(i > 0) + printf("ciclo: --i vale %d\n", --i); + + printf("Infine, dopo 2 cicli, i vale %d.\n", i); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/quadrato.c b/exercises/deitel/ch3/quadrato.c @@ -0,0 +1,35 @@ +/* Esercizio 3.33 + * + * Dato il lato disegna un quadrato di asterischi +*/ + +#include <stdio.h> + +int main() +{ + int lato, y, x = 0; + + printf("Dammi un lato del quadrato: "); + scanf("%d", &lato); + + if (lato < 1) { + printf("Usare i numeri da 1 a 20\n"); + } + + while(x < lato) { + if (lato > 20) { + printf("Usare i numeri da 1 a 20\n"); + break; + } + + y = 0; + while(y < lato) { + printf("*"); + ++y; + } + printf("\n"); + ++x; + } + + return 0; +} /* E0F main */ diff --git a/exercises/deitel/ch3/quadrato_empty.c b/exercises/deitel/ch3/quadrato_empty.c @@ -0,0 +1,45 @@ +/* Esercizio 3.34 + * + * Dato il lato disegna un quadrato di asterischi, vuoto. +*/ + +#include <stdio.h> + +int main() +{ + int lato, y, x = 0; + + printf("Dammi un lato del quadrato: "); + scanf("%d", &lato); + + if (lato < 1) { + printf("Usare i numeri da 1 a 20\n"); + } + + while(x < lato) { + if (lato > 20) { + printf("Usare i numeri da 1 a 20\n"); + break; + } + + y = 0; + while(y < lato) { + if (x == 0) + printf("*"); + else if (x == lato - 1) + printf("*"); + else { + if (y == 0) /* se è il primo asterisco.. */ + printf("*"); /* ..mostralo */ + else if ( y == lato - 1) /* se è l'ultimo.. */ + printf("*"); /* ..pure */ + else printf(" "); /* altrimenti mostra uno spazio */ + } + ++y; + } + printf("\n"); + ++x; + } + + return 0; +} /* E0F main */ diff --git a/exercises/deitel/ch3/salario.c b/exercises/deitel/ch3/salario.c @@ -0,0 +1,32 @@ +/* Esercizio 3.21 (Cap. 3) + * + * Determina la paga lorda per ogni impiegato +*/ + +#include <stdio.h> + +int main() +{ + int hours; + float rate; + + printf("Enter # of hours worked (-1 to end): "); + scanf("%d", &hours); + + while(hours != -1) { + printf("Enter hourly rate of the worker ($00.00): "); + scanf("%f", &rate); + + printf("Salary is $"); + if (hours <= 40) + printf("%.2f\n\n", rate * hours); + else + printf("%.2f\n\n", rate * 40 + rate + rate / 2); + + printf("Enter # of hours worked (-1 to end): "); + scanf("%d", &hours); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/shownum.c b/exercises/deitel/ch3/shownum.c @@ -0,0 +1,20 @@ +/* Esercizio 3.23 (Cap. 3); + * + * Stampa i numeri da 1 a 10 uno a fianco + * all'altro con 3 spazi tra ognuno. +*/ + +#include <stdio.h> + +int main() +{ + int i = 1; + while(i <= 10) { + printf("%d ", i); + ++i; + } + printf("\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/tab246.c b/exercises/deitel/ch3/tab246.c @@ -0,0 +1,26 @@ +/* Esercizio 3.26 + * + * Stampa una tabella di multipli di 2, 4 e 5 +*/ + +#include <stdio.h> + +int main() +{ + int i=3; + + printf("A A+2A+4A+6\n\n"); + while(i <= 15) { + if (i == 3) + printf("%d %d %d %d\n", i, i+2, i+4, i+6); + else if (i == 6) + printf("%d %d %d %d\n", i, i+2, i+4, i+6); + else if (i == 9) + printf("%d %d %d %d\n", i, i+2, i+4, i+6); + else + printf("%d %d %d %d\n", i, i+2, i+4, i+6); + i += 3; + } + + return 0; +} /* E0F main */ diff --git a/exercises/deitel/ch3/tabdcm.c b/exercises/deitel/ch3/tabdcm.c @@ -0,0 +1,21 @@ +/* Esercizio 3.25 (Cap. 3) + * + * Stampa una tabella con i numeri da 1 + * a 10 moltiplicati per 10, 100 e 100. +*/ + +#include <stdio.h> + +int main() +{ + int i=1; + + printf("N\t10*N\t100*N\t1000*N\n\n"); + while(i <= 10) { + printf("%d\t%d\t%d\t%d\n", i, 10*i, 100*i, 1000*i); + ++i; + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/triangolo.c b/exercises/deitel/ch3/triangolo.c @@ -0,0 +1,60 @@ +/* + * Esercizio 3.44 + * Dati 3 float diversi da 0 determino se questi + * possono rappresentare i lati di un triangolo. +*/ + +#include <stdio.h> + +int main() +{ + float cat1, cat2, cat3; + int valid = 0; + + printf("Inserire il valori [n n n]: "); + scanf("%f%f%f", &cat1, &cat2, &cat3); + + /* Controllo il cateto 1 */ + if (cat1 != 0) { + if (cat1 < cat2 + cat3) { + if (cat2 > cat3) { + if (cat1 > cat2 - cat3) + ++valid; + } + else if (cat1 > cat3 - cat2) + ++valid; + } + } + + /* Controllo il cateto 2 */ + if (cat2 != 0) { + if (cat2 < cat1 + cat3) { + if (cat1 > cat3) { + if (cat2 > cat1 - cat3) + ++valid; + } + else if (cat1 > cat3 - cat1) + ++valid; + } + } + + /* Controllo il cateto 3 */ + if (cat3 != 0) { + if (cat3 < cat1 + cat2) { + if (cat1 > cat2) { + if (cat3 > cat1 - cat2) + ++valid; + } + else if (cat3 > cat2 - cat1) + ++valid; + } + } + + if (valid == 3) + printf("Valori validi: %.2f, %.2f e %.2f\n", cat1, cat2, cat3); + else + printf("Valori NON validi: %.2f, %.2f e %.2f\n", cat1, cat2, cat3); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch3/triangolo2.c b/exercises/deitel/ch3/triangolo2.c @@ -0,0 +1,45 @@ +/* + * Esercizio 3.45 + * Dati 3 interi diversi da 0 determino se questi possono + * rappresentare i lati di un triangolo rettangolo. +*/ + +#include <stdio.h> + +int main() +{ + int cat1, cat2, cat3; + int valid = 0; + + printf("Inserire il valori [n n n]: "); + scanf("%d%d%d", &cat1, &cat2, &cat3); + + /* Riassunto (non usare) + * if (a*a == c*c - b*b && b*b == c*c - a*a && c*c == a*a + b*b) + */ + + /* Controllo il cateto 1 */ + if (cat1 != 0) { + if (cat1 * cat1 == cat3 * cat3 - cat2 * cat2) + ++valid; + } + + /* Controllo il cateto 2 */ + if (cat2 != 0) { + if (cat2 * cat2 == cat3 * cat3 - cat1 * cat1) + ++valid; + } + + if (cat3 != 0) { + if (cat3 * cat3 == cat1*cat1 + cat2*cat2) + ++valid; + } + + if (valid == 3) + printf("Valori validi: %d, %d e %d\n", cat1, cat2, cat3); + else + printf("Valori NON validi: %d, %d e %d\n", cat1, cat2, cat3); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/asterisk.c b/exercises/deitel/ch4/asterisk.c @@ -0,0 +1,51 @@ +/* Esercizio 4.16 */ + +#include <stdio.h> + +int main() +{ + int i, x; + + /* stampo il primo triangolo */ + printf("(A)\n"); + for (i = 1; i <= 10; ++i) { + for (x = i; x >= 1; --x) + printf("*"); + + printf("\n"); + } + + /* stampo il secondo triangolo */ + printf("(B)\n"); + for (i = 10 ; i >= 1; --i) { + for (x = i; x >= 1; --x) + printf("*"); + + printf("\n"); + } + + /* stampo il terzo triangolo */ + printf("(C)\n"); + for (i = 1; i <= 10; ++i) { + for (x = i - 1; x >= 1; --x) + printf(" "); + for (x = 11 - i; x >= 1; --x) + printf("*"); + + printf("\n"); + } + + /* stampo il quarto triangolo */ + printf("(D)\n"); + for (i = 10; i >= 1; --i) { + for (x = i - 1; x >= 1; --x) + printf(" "); + for (x = 11 - i; x >= 1; --x) + printf("*"); + + printf("\n"); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/breakfor.c b/exercises/deitel/ch4/breakfor.c @@ -0,0 +1,24 @@ +/* Esercizio 4.37 */ + +#include <stdio.h> + +int main() +{ + int x, i; + + for(x = 1; x <= 10; x++) { + + if (x == 5) { + i = x; + x = 11; + } + else + printf("%d ", x); + + } /* end for (x) */ + + printf("\nBroke out of loop at x == %d\n", i); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/cal.c b/exercises/deitel/ch4/cal.c @@ -0,0 +1,157 @@ +/* Esercizio 4.36 */ + +#include <stdio.h> + +int main() +{ + int giorno, mese, anno; + int giorni; /* giorni del mese corrente */ + + /* l_giorni: copia di giorni (per il loop) + * newline: per indentare e andare a capo. */ + int l_giorni = 0, newline = 0, i; + + do { /* Prendo in input l'anno */ + printf("Inserire anno [ '94 - '99 ]: "); + scanf("%d", &anno); + } while(anno < 1994 || anno > 1999); + printf("\n"); + + for(i = 1994; i <= anno; ++i) { + + /* mesi */ + for(mese = 1; mese <= 12; ++mese) { + + /* conto i giorni */ + switch(mese) { + case 1: + case 3: + case 5: + case 7: + case 8: + case 10: + case 12: + giorni = 31; + break; + + case 2: + if ( !( i % 4 ) && i % 100 || !( i % 400 ) ) + giorni = 29; + else + giorni = 28; + + break; + + case 4: + case 6: + case 9: + case 11: + giorni = 30; + + } /* end switch (mese) */ + + if (i == anno) { /* se è l'anno richiesto */ + + printf("%5s", " "); + + switch(mese) { + case 1: + printf("Gennaio"); + break; + case 2: + printf("Febbraio"); + break; + case 3: + printf("Marzo"); + break; + case 4: + printf("Aprile"); + break; + case 5: + printf("Maggio"); + break; + case 6: + printf("Giugno"); + break; + case 7: + printf("Luglio"); + break; + case 8: + printf("Agosto"); + break; + case 9: + printf("Settembre"); + break; + case 10: + printf("Ottobbre"); + break; + case 11: + printf("Novembre"); + break; + case 12: + printf("Dicembre"); + } + + printf(" %d\n", anno); + + /* ciclo i giorni */ + printf("%3s%3s%3s%3s%3s%3s%3s\n", + "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Do"); + + for(giorno = 1; giorno <= giorni; ++giorno) { + + if (giorno == 1) { /* primo del mese */ + + switch((l_giorni+giorno) % 7) { + + case 0: /* venerdì */ + printf("%3s%3s%3s%3s", + " ", " ", " ", " "); + newline = 5; + break; + case 1: /* Sabato */ + printf("%3s%3s%3s%3s%3s", + " ", " ", " ", " ", " "); + newline = 6; + break; + case 2: /* domenica */ + printf("%3s%3s%3s%3s%3s%3s", + " ", " ", " ", " ", " ", " "); + newline = 0; + break; + case 3: /* lunedì */ + newline = 1; + break; + case 4: /* martedì */ + printf("%3s", " "); + newline = 2; + break; + case 5: /* mercoledì */ + printf("%3s%3s", " ", " "); + newline = 3; + break; + case 6: /* giovedì */ + printf("%3s%3s%3s", " ", " ", " "); + newline = 4; + + } /* end switch (giorn? % 7) */ + } /* end if (giorno == 1) */ + + printf("%3d", giorno); + + if( !(newline % 7) && giorno != giorni) + printf("\n"); + ++newline; + + } /* end for (giorno <= giorni) */ + printf("\n\n"); + } /* end if (i == anno) */ + + l_giorni += giorni; + + } /* for (mesi) */ + } /* for (anno) */ + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/contfor.c b/exercises/deitel/ch4/contfor.c @@ -0,0 +1,20 @@ +/* Esercizio 4.39 */ + +#include <stdio.h> + +int main() +{ + int x; + + for(x = 1; x <= 10; x++) { + + if ( !(x == 5) ) + printf("%d ", x); + + } /* end for (x) */ + + printf("\nNOT used continue to skip printing the value 5\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/creditlimit.c b/exercises/deitel/ch4/creditlimit.c @@ -0,0 +1,34 @@ +/* Esercizio 4.17 */ + +#include <stdio.h> + +int main() +{ + int i, account; + float c_limit, c_saldo; + + for (i = 1; i <= 3; ++i) { + printf("Account number: "); + scanf("%d", &account); + printf("Current credit limit: "); + scanf("%f", &c_limit); + printf("Current credit: "); + scanf("%f", &c_saldo); + + printf("\n------------------------\n"); + printf("Account number: %d\n", account); + printf("New credit limit: %.2f\n", c_limit /= 2); + printf("Current credit: %.2f\n", c_saldo); + printf("------------------------\n"); + + if ((int) c_saldo > c_limit) { + printf("* You are out of limit!\n"); + printf("------------------------\n"); + } + printf("\n"); + + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/dec2rom.c b/exercises/deitel/ch4/dec2rom.c @@ -0,0 +1,88 @@ +/* Esercizio 4.33 */ + +#include <stdio.h> + +int main() +{ + int i, j; + + printf("Decimale\tRomani\n"); + + for(i = 900; i < 1000; ++i) { + + printf("%d\t\t", i); + + if (i < 10) + j = i; + else + j = i / 1 % 10; + + switch(i / 10 % 10) { /* decine */ + case 1: + printf("X"); + break; + case 2: + printf("XX"); + break; + case 3: + printf("XXX"); + break; + case 4: + printf("XL"); + break; + case 5: + printf("L"); + break; + case 6: + printf("LX"); + break; + case 7: + printf("LXX"); + break; + case 8: + printf("XXC"); + break; + case 9: + printf("XC"); + break; + } /* end of switch (decine) */ + + switch(j) { /* unità */ + case 1: + printf("I"); + break; + case 2: + printf("II"); + break; + case 3: + printf("III"); + break; + case 4: + printf("IV"); + break; + case 5: + printf("V"); + break; + case 6: + printf("VI"); + break; + case 7: + printf("VII"); + break; + case 8: + printf("VIII"); + break; + case 9: + printf("IX"); + break; + + } /* end of switch (unit) */ + + printf("\n"); + } + + printf("%d\t\tC\n", i); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/dec2rom2.c b/exercises/deitel/ch4/dec2rom2.c @@ -0,0 +1,70 @@ +/* Esercizio 4.33 */ + +#include <stdio.h> + +int main() +{ + int i, num = 1984; + + /* migliaia */ + for(i = num / 1000; i >= 1; --i) { + printf("M"); + num -= 1000; + } + + /* cinque-centinaia */ + if (num / 500) { + printf("D"); + num -= 500; + } + + /* centinaia */ + for(i = num / 100; i >= 1; --i) { + + if (i == 4) { + printf("CD"); + num -= 400; + break; + } + printf("C"); + num -= 100; + } + + /* stampo le decine */ + if (num / 10 >= 5) { + printf("L"); + num -= 50; + } + + /* stampo il resto delle decine */ + for(i = num / 10; i >= 1; --i) { + if (i == 4) { + printf("XL"); + num -= 40; + break; + } + printf("X"); + num -= 10; + } + + /* cinquetti */ + if (num >= 5) { + printf("V"); + num -= 5; + } + + for(i = num ; i >= 1 ; --i) { + if (i == 4) { + printf("IV"); + num -= 4; /* not required */ + break; + } + printf("I"); + num -= 1; /* not required */ + } + + printf("\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/demorgan.c b/exercises/deitel/ch4/demorgan.c @@ -0,0 +1,38 @@ +/* Esercizio 4.29 */ + +/* + * a) !( x < 5 ) && !( y >= 7) + * b) !( a == b ) || !( g != 5 ) + * c) !( ( x <= 8 ) && ( Y > 4 ) ) + * d) !( ( i > 4 ) || ( j <= 6 ) ) + ********************************** + * a) !( x < 5 || y >= 7 ) + * b) !( a == b && g != 5 ) + * c) ( !( x <= 8 ) || !( Y > 4 ) ) + * d) ( !( i > 4 ) && !( j <= 6 ) ) +*/ + +#include <stdio.h> + +int main() +{ + int i = 3, j = 5, k = 9; + + printf("Expression\t\t\tvalue\n"); + printf("!( %d < 5 ) && !( %d >= 7)\t%d\n", i, j, !(i<5)&&!(j>=7)); + printf("!( %d < 5 || %d >= 7 )\t\t%d\n\n", i, j, !(i<5||j>=7)); + + printf("!( ( %d == %d ) || !( %d != 5 )\t%d\n", i, j, k, !((i==j)||!(k!=5))); + printf("!( %d == %d && %d != 5 )\t\t%d\n\n", i, j, k, !(i==j&&k!=5)); + + printf("!( ( %d <= 8 ) && ( %d > 4 ) )\t%d\n", i, j, !((i<=8)&&(j>4))); + printf("( !( %d <= 8 ) || !( %d > 4 ) )\t%d\n\n", i, j, (!(i<=8)||!(j>4))); + + printf("!( ( %d > 4 ) || ( %d <= 6 ) )\t%d\n", i, j, !((k>4)||(j<=6))); + printf("( !( %d > 4 ) && !( %d <= 6 ) )\t%d\n\n", i, j, (!(i>4)&&!(j<=6))); + + + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/fatt15tab.c b/exercises/deitel/ch4/fatt15tab.c @@ -0,0 +1,20 @@ +/* Esercizio 4.14 */ + +#include <stdio.h> + +int main() +{ + int c_val, i; /* contatori */ + int fatt = 1; /* Fattoriale */ + + for (i = 1; i <= 5; ++i) { + for (c_val = i; c_val >= 1; --c_val) { + fatt *= c_val; + } + printf("%d! = %d\n", i, fatt); + fatt = 1; + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/fig04_07.mod.c b/exercises/deitel/ch4/fig04_07.mod.c @@ -0,0 +1,41 @@ +/* Esercizio 4.30 (1) */ + +#include <stdio.h> + +int main() +{ + int grade; + int aCount = 0, bCount = 0, cCount = 0, dCount = 0, fCount = 0; + + printf("Enter the letter grades.\n"); + printf("Enter the EOF chatacter to end input.\n"); + + while (( grade = getchar()) != EOF ) { + + if (grade == 'A' || grade == 'a') + ++aCount; + else if (grade == 'B' || grade == 'b') + ++bCount; + else if (grade == 'C' || grade == 'c') + ++cCount; + else if (grade == 'D' || grade == 'd') + ++dCount; + else if (grade == 'F' || grade == 'f') + ++fCount; + else if (grade == '\n' || grade == '\t' || grade == ' ') ; /* nothing */ + else { + printf("Incorrect letter grade entered."); + printf("Enter a new grade.\n"); + } + } /* end of while */ + + printf("Totals for each letter grade are:\n"); + printf("A: %d\n", aCount); + printf("B: %d\n", bCount); + printf("C: %d\n", cCount); + printf("D: %d\n", dCount); + printf("F: %d\n", fCount); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/fig04_07.mod2.c b/exercises/deitel/ch4/fig04_07.mod2.c @@ -0,0 +1,52 @@ +/* Esercizio 4.30 (2) */ + +#include <stdio.h> + +int main() +{ + int grade; + int aCount = 0, bCount = 0, cCount = 0, dCount = 0, fCount = 0; + + printf("Enter the letter grades.\n"); + printf("Enter the EOF chatacter to end input.\n"); + + while (( grade = getchar()) != EOF ) { + + if (grade == 'A' || grade == 'a') { + ++aCount; + continue; + } + if (grade == 'B' || grade == 'b') { + ++bCount; + continue; + } + if (grade == 'C' || grade == 'c') { + ++cCount; + continue; + } + if (grade == 'D' || grade == 'd') { + ++dCount; + continue; + } + if (grade == 'F' || grade == 'f') { + ++fCount; + continue; + } + if (grade == '\n' || grade == '\t' || grade == ' ') + continue; + + printf("Incorrect letter grade entered."); + printf("Enter a new grade.\n"); + + } /* end of while */ + + printf("Totals for each letter grade are:\n"); + printf("A: %d\n", aCount); + printf("B: %d\n", bCount); + printf("C: %d\n", cCount); + printf("D: %d\n", dCount); + printf("F: %d\n", fCount); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/getavrg.c b/exercises/deitel/ch4/getavrg.c @@ -0,0 +1,24 @@ +/* Esercizio 4.10 */ + +#include <stdio.h> + +int main() +{ + int i, value; + float average = 0; /* media */ + + printf("Intero: "); + scanf("%d", &value); + + for (i = 0; value != 9999; ++i) { + average += (float) value; + + printf("Intero: "); + scanf("%d", &value); + } + + printf("La media è %.2f\n", average / i); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/getpay.c b/exercises/deitel/ch4/getpay.c @@ -0,0 +1,134 @@ +/* Esercizio 4.28 */ + +#include <stdio.h> + +int main() +{ + int code = 0, w_time, arts; /* code, ore lavorative e arts */ + int a_code = 0; + float paga; + + printf("\nInserire codice di pagamento (-1 esce): "); + scanf("%d", &code); + while(code != EOF) { + + switch(code) { + case 1: + printf("\n-+- MANAGER -+-\n"); + printf("\nCodice di pagamento: %d\n", code); + printf("Paga settimanale: $350.00\n"); + + break; + case 2: + printf("\n-+- LAVORATORI AD ORE -+-\n\n"); + + printf("Ore lavorative: "); + scanf("%d", &w_time); + printf("Paga oraria fissa: "); + scanf("%f", &paga); + + /* calcolo la paga */ + if (w_time <= 40) + paga *= w_time; + else + paga *= 40 + w_time + paga / 2 * (w_time - 40); + + printf("\nCodice di pagamento: %d\n", code); + printf("Ore lavorative: %d\n", w_time); + printf("Paga settimanale: $%.2f\n", paga); + + break; + case 3: + printf("\n-+- LAVORATORI A PROVVIGIONE -+-\n\n"); + + printf("Importo vendite lorde: "); + scanf("%f", &paga); + + paga = (paga * 5.7) / 100 + 250; + + printf("\nCodice di pagamento: %d\n", code); + printf("Paga settimanale: $%.2f\n", paga); + + break; + case 4: + printf("\n-+- LAVORATORI A COTTIMO -+-\n\n"); + + /* sfrutto w_time come 'code' */ + printf("Tipo di articolo [1-3]: "); + scanf("%d", &w_time); + + switch(w_time) { + + case 1: + if (a_code == 2 || a_code == 3) + break; + + a_code = 1; + printf("\n** ARTICOLO 1\n\n"); + printf("Numero articoli (-1 esce): "); + scanf("%d", &arts); + paga = 5.15 * arts; + + break; + case 2: + if (a_code == 1 || a_code == 3) + break; + + a_code = 2; + printf("\n** ARTICOLO 2\n\n"); + printf("Numero articoli (-1 esce): "); + scanf("%d", &arts); + paga = 9.13 * arts; + + break; + case 3: + if (a_code == 1 || a_code == 2) + break; + + a_code = 3; + printf("\n** ARTICOLO 3\n\n"); + printf("Numero articoli (-1 esce): "); + scanf("%d", &arts); + paga = 13.5 * arts; + + break; + case ' ': + case '\t': + case '\n': + break; + + default: + printf("Selezione non valida!\n"); + + } /* eof switch: lavoratori a cottimo */ + + printf("\nCodice di pagamento: %d\n", code); + printf("Codice articolo: %d\n", a_code); + printf("Numero articoli: %d\n", arts); + printf("Paga settimanale: %.2f\n", paga); + a_code = 0; + + break; + + case ' ': + case '\t': + case '\n': + break; + + default: + printf("\nCodice di pagamento errato: %d\n", code); + printf("\nCodici attualmente disponibili:\n\n"); + printf("\t1: Mangager\n"); + printf("\t2: Lavoratori ad ore\n"); + printf("\t3: Lavoratori a provvigione\n"); + printf("\t4: Lavoratori a cottimo\n"); + } + printf("\nInserire codice di pagamento (-1 esce): "); + scanf("%d", &code); + } + + printf("\nCalcolo eseguito correttamente!\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/getpg.c b/exercises/deitel/ch4/getpg.c @@ -0,0 +1,24 @@ +/* + * Esercizio 4.26 + * pi = 4 - (4 / 3) + (4 / 5) - (4 / 7) + (4 / 9) - (4 / 11) + ... +*/ + +#include <stdio.h> + +int main() +{ + double pi = 4.0; + int i, t = 1; + + printf("PI VALUE\t(+/-) 4 / X\tTERMS\n"); + for (i = 3; pi > 3.141593; ++t, i += 2) { + pi -= 4.0 / i; + i += 2; + pi += 4.0 / i; + } + + printf("%f\t4 / %d\t%d\n", pi, i, t); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/getrate.c b/exercises/deitel/ch4/getrate.c @@ -0,0 +1,26 @@ +/* Esercizio 4.15 */ + +#include <stdio.h> +#include <math.h> + +int main() +{ + double amount; + double principal = 1000.0; + double rate = 0.5; + int year, r; + + for (r = 5; r <= 10 ; rate += 0.1, ++r) { + + printf("\n%4s%21s [%d%%]\n", "Year", "Amount of deposit", r); + for (year = 1; year <= 10; year++) { + + amount = principal * pow(1.0 + rate, year); + + printf("%4d%21.2f\n", year, amount); + } + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/getrate2.c b/exercises/deitel/ch4/getrate2.c @@ -0,0 +1,26 @@ +/* Esercizio 4.15 */ + +#include <stdio.h> +#include <math.h> + +int main() +{ + int amount; + int principal = 1000; + double rate = 0.5; + int year, rest, rest2; + + printf("%4s%21s\n", "Year", "Amount of deposit"); + for (year = 1; year <= 10; year++) { + + amount = principal * pow(1 + rate, year); + rest = rest2 = principal * pow(1 + rate, year) * 100; + rest = (int) rest / 10 % 10; + rest2 = (int) rest2 % 10; + + printf("%4d%18d.%d%d\n", year, amount, rest, rest2); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/getsmall.c b/exercises/deitel/ch4/getsmall.c @@ -0,0 +1,25 @@ +/* Esercizio 4.11 */ + +#include <stdio.h> + +int main() +{ + int i, small; + int c_val; + + printf("Intero: "); + scanf("%d", &c_val); + + for (i = c_val; i >= 1; --i) { + printf("Intero: "); + scanf("%d", &c_val); + + if (small > c_val) + small = c_val; + } + + printf("Smallest: %d\n", small); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/getweekvalue.c b/exercises/deitel/ch4/getweekvalue.c @@ -0,0 +1,55 @@ +/* Esercizio 4.19 */ + +#include <stdio.h> + +int main() +{ + int productid = 0, quantity; + int prod1 = 0, prod2 = 0, prod3 = 0, prod4 = 0, prod5 = 0; /* product list */ + + printf("Product ID: "); + scanf("%d", &productid); + + while(productid != EOF) { + printf("Day's quantity: "); + scanf("%d", &quantity); + + switch(productid) { + case 1: + prod1 += quantity; + break; + case 2: + prod2 += quantity; + break; + case 3: + prod3 += quantity; + break; + case 4: + prod4 += quantity; + break; + case 5: + prod5 += quantity; + break; + + /* questi caratteri.. + case '\n': + case '\t': + case ' ': + break; + ..verranno ignorati. */ + + default: + printf("Il prodotto inserito non è valido!\n"); + printf("Verificare l'ID e riprovare.\n"); + break; + } + printf("\nProduct ID: "); + scanf("%d", &productid); + } + + printf("Total products price: $%.2f\n", (2.98 * prod1) + (4.50 * prod2) + \ + (9.98 * prod3) + (4.49 * prod4) + (6.87 * prod5)); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/intsum30.c b/exercises/deitel/ch4/intsum30.c @@ -0,0 +1,18 @@ +/* Esercizio 4.12 */ + +#include <stdio.h> + +int main() +{ + int i; + int sum = 0; + + for (i = 2; i <= 30; i += 2) { + if (! (i % 2)) + printf("%d ", i); + } + + printf("\n"); + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/istogram.c b/exercises/deitel/ch4/istogram.c @@ -0,0 +1,27 @@ +/* Esercizio 4.18 */ + +#include <stdio.h> + +int main() +{ + int num, i, x; + + for(i = 1; i <= 5; ++i) { + printf("Inserisci un numero [-%d]: ", 6-i); + scanf("%d", &num); + + /* se è compreso tra 1 e 30 */ + if (num >= 1 && num <= 30) { + for(x = num; x >= 1; --x) /* stampo num asterischi */ + printf("*"); + } + else { + printf("Usare i numeri da 1 a 30"); + --i; + } + printf("\n"); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/numtab.c b/exercises/deitel/ch4/numtab.c @@ -0,0 +1,71 @@ +/* Esercizio 4.25 */ + +#include <stdio.h> +#include <math.h> + +int main() +{ + int num, c_num; + int base; /* start from base 2 (binary) */ + int i, j, p; + + printf("Dec\tBin\tOct\tHex\n"); + for(num = 0; num <= 15; num++) { + printf("%d\t", num); + + /* print equivalent in base "base" */ + /* base: 2, (4), 8, 16 */ + for(i = 1; i <= 4; i++) { + + /* dynamic base */ + if(i == 2) /* ignore base 4 */ + continue; + base = pow(2, i); + + /* found the values order.. */ + for(j = 0; pow(base, j) <= num; j++) { + p = pow(base, j); + } /* ..and print the symbols one for one */ + c_num = num; + for(j = p; j >= 1; j /= base) { + if(base == 16 && c_num / j >= 10) { + + switch(c_num / j) { + case 10: + printf("A"); + break; + case 11: + printf("B"); + break; + case 12: + printf("C"); + break; + case 13: + printf("D"); + break; + case 14: + printf("E"); + break; + case 15: + printf("F"); + + } /* end switch (c_num / j) */ + continue; + } /* end if */ + + printf("%d", c_num / j); + if (!num) break; + + c_num %= j; + } /* end for (j) */ + + printf("\t"); + + } /* end for (i) */ + + printf("\n"); + } /* end for (num) */ + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/numtab2.c b/exercises/deitel/ch4/numtab2.c @@ -0,0 +1,68 @@ +/* Esercizio 4.34 */ + +#include <stdio.h> +#include <math.h> + +int main() +{ + int num, c_num; + int base; /* start from base 2 (binary) */ + int i, j, p, check; + + for(num = 1; num <= 256; num++) { + printf("%d%3s", num, " "); + + /* print equivalent in "base" */ + for(i = 1; i <= 4; i++) { + + /* dynamic base */ + if(i == 2) /* ignore base 4 */ + continue; + base = pow(2, i); + + /* found the values order.. */ + for(j = 0; pow(base, j) <= num; j++) { + p = pow(base, j); + } /* ..and print the symbols one for one */ + c_num = num; + for(j = p; j >= 1; j /= base) { + + if(base == 16 && c_num / j >= 10 && c_num / j <= 15) { + + switch(c_num / j) { + case 10: + printf("A"); + break; + case 11: + printf("B"); + break; + case 12: + printf("C"); + break; + case 13: + printf("D"); + break; + case 14: + printf("E"); + break; + case 15: + printf("F"); + + } /* end switch (c_num / j) */ + + continue; + } /* end if (hex) */ + + printf("%d", c_num / j); + c_num %= j; + } /* end for (j) */ + + printf("%3s", " "); + } /* end for (i) */ + + printf("\n"); + } /* end for (num) */ + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/oddingprod15.c b/exercises/deitel/ch4/oddingprod15.c @@ -0,0 +1,18 @@ +/* Esercizio 4.13 */ + +#include <stdio.h> + +int main() +{ + int i, product = 1; + + for (i = 1; i <= 15; i += 2) { + if (i % 2) /* never used */ + product += i; + } + + printf("Product of all integers from 1 to 15 is %d\n", product); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/rombo.c b/exercises/deitel/ch4/rombo.c @@ -0,0 +1,30 @@ +/* Esercizio 4.31 */ + +#include <stdio.h> + +int main() +{ + int i, j, k, x; + + for(i = 1, x = 4; i <= 9; i += 2, --x) { + for(j = x; j >= 1; --j) /* stampa 'x' spazi */ + printf(" "); + + for(k = i; k >= 1; --k) /* stampa 'i' asterischi */ + printf("*"); + + printf("\n"); + } + + for(i = 7, x = 1; i >= 1; i -= 2, ++x) { + for(j = x; j >= 1; --j) /* stampa 'x' spazi */ + printf(" "); + + for(k = i; k >= 1; --k) /* stampa 'i' asterischi */ + printf("*"); + printf("\n"); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/rombo2.c b/exercises/deitel/ch4/rombo2.c @@ -0,0 +1,41 @@ +/* Esercizio 4.32 */ + +#include <stdio.h> + +int main() +{ + int i, j, k, x; + int lines; + + printf("Numero di linee: "); + scanf("%d", &lines); + + if (lines % 2 && lines >= 1 && lines <= 19) { + + for(i = 1, x = lines / 2; i <= lines; i += 2, --x) { + for(j = x; j >= 1; --j) /* stampa 'x' spazi */ + printf(" "); + + for(k = i; k >= 1; --k) /* stampa 'i' asterischi */ + printf("*"); + + printf("\n"); + } + + for(i = lines - 2, x = 1; i >= 1; i -= 2, ++x) { + for(j = x; j >= 1; --j) /* stampa 'x' spazi */ + printf(" "); + + for(k = i; k >= 1; --k) /* stampa 'i' asterischi */ + printf("*"); + printf("\n"); + } /* end of for */ + + } /* End IF */ + else + printf("Usare interi dispari da 1 a 19\n"); + + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch4/seqsum.c b/exercises/deitel/ch4/seqsum.c @@ -0,0 +1,25 @@ +/* Esercizio 4.9 */ + +#include <stdio.h> + +int main() +{ + int counter, value; + int total = 0; /* volutamente NON inizializzato */ + /* nell'intestazione del for() */ + + printf("Intero: "); + scanf("%d", &value); + + for (counter = value; counter >= 1; --counter) { + printf("Intero [-%d]: ", counter); + scanf("%d", &value); + + total += value; + } + + printf("La domma dei valori è %d\n", total); + + return 0; +} /* E0F */ + diff --git a/exercises/deitel/ch4/tpbf.c b/exercises/deitel/ch4/tpbf.c @@ -0,0 +1,19 @@ +/* Esercizio 4.27 + * Terne pitagoriche: brute force. */ + +#include <stdio.h> + +int main() +{ + int i, j, k; + + printf("IPOTENUSA\tCATETO 1\tCATETO 2\n"); + for (i = 1; i < 500; ++i) + for (j = i ; j > i / 2; --j) + for (k = 1; k < j ; ++k) + if (i * i == j * j + k * k) + printf("%d\t\t%d\t\t%d\n", i, j, k); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/456.txt b/exercises/deitel/ch5/456.txt @@ -0,0 +1,22 @@ +/* Esercizio 5.4 */ + +a) float hypotenuse(float side1, float side2) +b) int smallest(int x, int y, int x) +c) void instructions(void) +d) float intToFloat(int number) + +/* Esercizio 5.5 */ + +a) float hypotenuse(float, float); +b) int smallest(int, int, int); +c) void instructions(void); +d) float intToFloat(int); + +/* Esercizio 5.6 */ + +a) register int count = 0; +b) static float lastVal; +c) extern int number; /* errato */ +c) static int number; /* all'esterno di ogni dichiarazione di funzione. */ + /* corretto */ + diff --git a/exercises/deitel/ch5/HorT.c b/exercises/deitel/ch5/HorT.c @@ -0,0 +1,41 @@ +/* Exercise 5.31 */ + +#include <stdio.h> +#include <stdlib.h> + +int flip(void); + +int main() +{ + int i; + int heads, tails; + heads = tails = 0; + + srand( time(NULL) ); + + for(i = 1; i <= 100; i++) { + if(flip()) + ++heads; + else + ++tails; + } /* end for (i) */ + + printf("Results:\n"); + printf("Heads: %d\nTails: %d\n", heads, tails); + + return 0; +} /* E0F main */ + +/* simulate a currency launch */ +int flip(void) +{ + int n = rand() % 2; + + if(n) + printf("Heads\n"); + else + printf("Tails\n"); + + return n; +} /* eof flip() */ + diff --git a/exercises/deitel/ch5/c2f2c_2.c b/exercises/deitel/ch5/c2f2c_2.c @@ -0,0 +1,57 @@ +/* Exercise 5.24 */ + +#include <stdio.h> + +double celsius(double); +double fahrenheit(double); + +int main() +{ + double i, j; + int line = 9; /* number of entries for line */ + + /* print 1st table */ + printf("\t\t\tFrom °C to °F (1-100)\n\n"); + for(i = 0.0; i < 100 ; i += line) { + printf("°C:\t"); + for(j = i; j < i + line && j <= 100; j++) + printf("%.1f\t", j); + + printf("\n°F:\t"); + for(j = i; j < i + line && j <= 100; j++) { + printf("%.1f\t", fahrenheit(j)); + } + printf("\n"); + } + + /* print 2nd table */ + printf("\n\t\t\tFrom °F to °C (32-212)\n\n"); + for(i = 32; i <= 212; i += line) { + printf("°F:\t"); + for(j = i; j < i + line && j <= 212; j++) + printf("%.1f\t", j); + + printf("\n°C:\t"); + for(j = i; j < i + line && j <= 212; j++) + printf("%.1f\t", celsius(j)); + + printf("\n"); + } + + return 0; +} /* E0F main */ + +/* convert from Celsius to Fahrenheit */ +double celsius(double fahrenheit) +{ + /* °C=(5/9)x(°F-32) */ + return (5.0 / 9.0) * (fahrenheit - 32); +} /* eof celsius() */ + +/* convert from Fahrenheit to Celsius */ +double fahrenheit(double celsius) +{ + /* °F=(9/5)°C+32 */ + return (9.0 / 5.0) * celsius + 32; +} /* eof fahrenheit() */ + diff --git a/exercises/deitel/ch5/cfuncs.c b/exercises/deitel/ch5/cfuncs.c @@ -0,0 +1,47 @@ +/* Exercise 5.49 */ + +#include <stdio.h> +#include <math.h> + +int main() +{ + int i; + + printf("\n\t\tPrint a lot of (math?) tables\n\n"); + + /* sqrt(), exp() and log() */ + for(i = 1; i <= 10; i++) { + printf("sqrt(%.2f) == %.2f\t", (double)i, sqrt((double)i)); + printf("exp(%.2f) == %.2f\t", (double)i, exp((double)i)); + printf("log(%.2f) == %.2f\n", (double)i, log((double)i)); + } + + printf("\n"); + + /* fabs(), ceil() and floor() */ + for(i = 1; i <= 10; i++) { + printf("fabs(%.2f) == %.2f\t", (double)i, fabs((double)i)); + printf("ceil(%.2f) == %.2f\t", (double)i, ceil((double)i)); + printf("floor(%.2f) == %.2f\n", (double)i, floor((double)i)); + } + + printf("\n"); + + /* pow() and fmod() */ + for(i = 1; i <= 10; i++) { + printf("pow(%.1f, %d) == %.2f\t\t", (double)i, 3, pow( (double)i, 3) ); + printf("fmod(%.2f, 3) == %.2f\n", (double)i, fmod( (double)i, 3) ); + } + + printf("\n"); + + /* sin(), cos() and tan() */ + for(i = 1; i <= 10; i++) { + printf("sin(%.2f) == %.2f\t", (double)i, sin((double)i)); + printf("cos(%.2f) == %.2f\t", (double)i, cos((double)i)); + printf("tan(%.2f) == %.2f\n", (double)i, tan((double)i)); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/checkmf.c b/exercises/deitel/ch5/checkmf.c @@ -0,0 +1,70 @@ +/* Esercizio 5.3 */ + +#include <stdio.h> +#include <math.h> + +int main() +{ + printf("Expr\t\tBook\t\tCheck\n"); + + /* sqrt(3) */ + printf("sqrt(900.0)\t30.0\t\t%.1f\n", sqrt(900.0)); + printf("sqrt(9.0)\t3.0\t\t%.1f\n", sqrt(9.0)); + printf("\n"); + + /* exp(3) */ + printf("exp(1.0)\t2.178282\t%f\n", exp(1.0)); + printf("exp(2.0)\t7.389056\t%f\n", exp(2.0)); + printf("\n"); + + /* log(3) */ + printf("log(2.718282)\t1.0\t\t%.1f\n", log(2.718282)); + printf("log(7.389056)\t2.0\t\t%.1f\n", log(7.389056)); + printf("\n"); + + /* log10(3) */ + printf("log10(1.0)\t0.0\t\t%.1f\n", log10(1.0)); + printf("log10(10.0)\t1.0\t\t%.1f\n", log10(10.0)); + printf("log10(100.0)\t2.0\t\t%.1f\n", log10(100.0)); + printf("\n"); + + /* fabs(3) */ + printf("fabs(5.0)\t5.0\t\t%.1f\n", fabs(5.0)); + printf("fabs(0.0)\t0.0\t\t%.1f\n", fabs(0.0)); + printf("fabs(-5.0)\t-5.0\t\t%.1f\t*\n", fabs(-5.0)); /* diff */ + printf("\n"); + + /* ceil(3) */ + printf("ceil(9.2)\t10.0\t\t%.1f\n", ceil(9.2)); + printf("ceil(-9.9)\t-9.0\t\t%.1f\n", ceil(-9.9)); + printf("\n"); + + /* floor(3) */ + printf("floor(9.2)\t9.0\t\t%.1f\n", floor(9.2)); + printf("floor(-9.8)\t-10.0\t\t%.1f\n", floor(-9.8)); + printf("\n"); + + /* pow(3) */ + printf("pow(2, 7)\t128.0\t\t%.1f\n", pow(2, 7)); + printf("pow(9, .5)\t3.0\t\t%.1f\n", pow(9, .5)); + printf("\n"); + + /* fmod(3) */ + printf("fmod(13.657, 2.333)\t1.992\t%.3f\n", fmod(13.657, 2.333)); + printf("\n"); + + /* sin(3) */ + printf("sin(0.0)\t0.0\t\t%.1f\n", sin(0.0)); + printf("\n"); + + /* cos(3) */ + printf("cos(0.0)\t1.0\t\t%.1f\n", cos(0.0)); + printf("\n"); + + /* tan(3) */ + printf("tan(0.0)\t0.0\t\t%.1f\n", tan(0.0)); + printf("\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/craps.c b/exercises/deitel/ch5/craps.c @@ -0,0 +1,97 @@ +/* Exercise 5.51 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +enum Status { CONTINUE, WON, LOST }; + +int rollDice(void); +int play(void); + +int main() +{ + int bankBalance = 1000, wager; + + while(bankBalance) { + + do { + printf("Bank balance: $%d\n", bankBalance); + printf("Enter your wager: "); + scanf("%d", &wager); + } while(wager > bankBalance || wager <= 0); + + if(play() == WON) + bankBalance += wager; + else + bankBalance -= wager; + } + + printf("Bank balance: $0\n"); + + return 0; +} /* E0F main */ + +/* play a time */ +int play(void) { + int sum, myPoint; + + enum Status gameStatus; + + srand( time(NULL) ); + + sum = rollDice(); + + switch(sum) { + case 7: + case 11: + gameStatus = WON; + break; + case 2: + case 3: + case 12: + gameStatus = LOST; + break; + default: + gameStatus = CONTINUE; + myPoint = sum; + printf("Point is %d\n", myPoint); + break; /* optional */ + } /* end switch (sum) */ + + while(gameStatus == CONTINUE) { + sum = rollDice(); + + if(sum == myPoint) + gameStatus = WON; + else + if(sum == 7) + gameStatus = LOST; + + } /* end while (gameStatus) */ + + if(gameStatus == WON) { + printf("Player wins\n"); + return WON; + } + else { + printf("Player loses\n"); + return LOST; + } + +} /* eof play() */ + +/* launch the dice, calculate the sum and print results */ +int rollDice(void) { + int die1, die2; + int workSum; + + die1 = 1 + rand() % 6; + die2 = 1 + rand() % 6; + workSum = die1 + die2; + + printf("Player rolled %d + %d = %d\n", die1, die2, workSum); + + return workSum; +} /* end rollDice() */ + diff --git a/exercises/deitel/ch5/dice.c b/exercises/deitel/ch5/dice.c @@ -0,0 +1,97 @@ +/* Exercise 5.51 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +enum Status { CONTINUE, WON, LOST }; + +int rollDice(void); +int play(void); + +int main() +{ + int bankBalance = 1000, wager; + + while(bankBalance) { + + do { + printf("Bank balance: $%d\n", bankBalance); + printf("Enter your wager: "); + scanf("%d", &wager); + } while(wager > bankBalance || wager <= 0); + + if(play() == WON) + bankBalance += wager; + else + bankBalance -= wager; + } + + printf("Bank balance: $0\n"); + + return 0; +} /* E0F main */ + +/* play a time */ +int play(void) { + int sum, myPoint; + + enum Status gameStatus; + + srand( time(NULL) ); + + sum = rollDice(); + + switch(sum) { + case 7: + case 11: + gameStatus = WON; + break; + case 2: + case 3: + case 12: + gameStatus = LOST; + break; + default: + gameStatus = CONTINUE; + myPoint = sum; + printf("Point is %d\n", myPoint); + break; /* optional */ + } /* end switch (sum) */ + + while(gameStatus == CONTINUE) { + sum = rollDice(); + + if(sum == myPoint) + gameStatus = WON; + else + if(sum == 7) + gameStatus = LOST; + + } /* end while (gameStatus) */ + + if(gameStatus == WON) { + printf("Player wins\n"); + return WON; + } + else { + printf("Player loses\n"); + return LOST; + } + +} /* eof play() */ + +/* launch the dice, calculate the sum and print results */ +int rollDice(void) { + int die1, die2; + int workSum; + + die1 = 1 + rand() % 6; + die2 = 1 + rand() % 6; + workSum = die1 + die2; + + printf("Player rolled %d + %d = %d\n", die1, die2, workSum); + + return workSum; +} /* end rollDice() */ + diff --git a/exercises/deitel/ch5/distance.c b/exercises/deitel/ch5/distance.c @@ -0,0 +1,24 @@ +/* Exercise 5.45 */ + +#include <stdio.h> + +double distance(double, double, double, double); + +int main() +{ + double a, b, c, d; + + printf("Give me x1 x2 y1 y2: "); + scanf("%lf%lf%lf%lf", &a, &b, &c, &d); + + printf("Distance is %.2f.\n", distance(a, b, c, d)); + + return 0; +} /* E0F main */ + +/* Calculate the distance between two points */ +double distance(double x1, double y1, double x2, double y2) +{ + return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); /* taken from the web */ +} /* eof distance() */ + diff --git a/exercises/deitel/ch5/elementar.c b/exercises/deitel/ch5/elementar.c @@ -0,0 +1,37 @@ +/* Exercise 5.32 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +int main() +{ + int n1 = 1 + rand() % 9; + int n2 = 1 + rand() % 9; + int num; + + + while(1) { + srand( time(NULL) ); + + printf("How much is %d times %d?\n", n1, n2); + printf("Answer (%d to end): ", EOF); + scanf("%d", &num); + + if(num == EOF) + break; + + printf("\n"); + if(num == n1 * n2) { + printf("Very good!"); + n1 = 1 + rand() % 9; + n2 = 1 + rand() % 9; + } + else + printf("No. Please try again."); + printf("\n\n"); + } /* end while (num) */ + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/elementar2.c b/exercises/deitel/ch5/elementar2.c @@ -0,0 +1,62 @@ +/* Exercise 5.33 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +int main() +{ + int n1 = 1 + rand() % 9; + int n2 = 1 + rand() % 9; + int num; + + + while(1) { + srand( time(NULL) ); + + printf("How much is %d times %d?\n", n1, n2); + printf("Answer (%d to end): ", EOF); + scanf("%d", &num); + + if(num == EOF) + break; + + printf("\n"); + if(num == n1 * n2) { + switch(1 + rand() % 4) { + case 1: + printf("Very good!"); + break; + case 2: + printf("Excellent!"); + break; + case 3: + printf("Nice work!"); + break; + case 4: + printf("Keep up the good work!"); + } + n1 = 1 + rand() % 9; + n2 = 1 + rand() % 9; + } + else + switch(1 + rand() % 4) { + case 1: + printf("No. Please try again."); + break; + case 2: + printf("Wrong. Try one more."); + break; + case 3: + printf("Don't give up!"); + break; + case 4: + printf("No. Keep trying."); + } /* end switch */ + + printf("\n\n"); + } /* end while (num) */ + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/elementar3.c b/exercises/deitel/ch5/elementar3.c @@ -0,0 +1,67 @@ +/* Exercise 5.34 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +int main() +{ + int n1, n2; + int num, i = 0; + + int correct = 0; + + for(i = 1; i <= 10; i++) { + srand( time(NULL) ); + + n1 = 1 + rand() % 9; + n2 = 1 + rand() % 9; + + printf("How much is %d times %d?\n", n1, n2); + printf("Answer: "); + scanf("%d", &num); + + printf("\n"); + if(num == n1 * n2) { + switch(1 + rand() % 4) { + case 1: + printf("Very good!"); + break; + case 2: + printf("Excellent!"); + break; + case 3: + printf("Nice work!"); + break; + case 4: + printf("Keep up the good work!"); + } + ++correct; + } + else + switch(1 + rand() % 4) { + case 1: + printf("No. Please try again."); + break; + case 2: + printf("Wrong. Try one more."); + break; + case 3: + printf("Don't give up!"); + break; + case 4: + printf("No. Keep trying."); + } /* end switch */ + + printf("\n\n"); + } /* end for (i) */ + + + if( (100 * correct) / 10 < 75) + printf("Please ask your instructor for extra help\n"); + + printf("Game over!\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/elementar4.c b/exercises/deitel/ch5/elementar4.c @@ -0,0 +1,160 @@ +/* Exercise 5.44 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +void pok(void); +void pko(void); + +int main() +{ + int n1, n2, num; /* random numbers and user input */ + int level, mode; /* level and mode */ + int mode2; /* mode2 needed for mode 5 */ + int correct = 0; /* counter for correct answer */ + int i; /* only a counter for loops */ + + do { + printf("Choose a level.\n"); + printf( + "\t1: one number (easy)\n" + "\t2: two numbers (medium)\n" + ); + + printf(": "); + scanf("%d", &level); + + } while( level < 1 || level > 2 ); + + level = level == 1 ? 9 : 99; /* set level */ + + do { + printf("\nChoose a mode.\n"); + printf( + "\t1: addition (easy)\n" + "\t2: removal (medium)\n" + "\t3: moltiplication (hard)\n" + "\t4: division (very hard)\n" + "\t5: two operations (random)\n" + ); + + printf(": "); + scanf("%d", &mode); + + } while( mode < 1 || mode > 5 ); + + printf("\n"); + + for(i = 1; i <= 10; i++) { + srand( time(NULL) ); + + n1 = 1 + rand() % level; + n2 = 1 + rand() % level; + + if(mode == 5) + mode2 = 1 + rand() % 4; + else mode2 = mode; + + switch(mode2) { /* set mode */ + case 1: /* addition */ + printf("How much is %d plus %d?\n", n1, n2); + printf("Answer: "); + scanf("%d", &num); + + printf("\n"); + if(num == n1 + n2) { + pok(); + ++correct; + } + else + pko(); + break; + case 2: /* removal */ + printf("How much is %d minus %d?\n", n1, n2); + printf("Answer: "); + scanf("%d", &num); + + printf("\n"); + if(num == n1 - n2) { + pok(); + ++correct; + } + else + pko(); + break; + case 3: /* moltiplication */ + printf("How much is %d times %d?\n", n1, n2); + printf("Answer: "); + scanf("%d", &num); + + printf("\n"); + if(num == n1 * n2) { + pok(); + ++correct; + } + else + pko(); + break; + case 4: /* division */ + printf("How much is %d divided %d?\n", n1, n2); + printf("Answer: "); + scanf("%f", &num); + + printf("\n"); + if(num == n1 / n2) { + pok(); + ++correct; + } + else + pko(); + } /* end switch (mode) */ + + printf("\n\n"); + + } /* end for (i) */ + + if( (100 * correct) / 10 < 75) + printf("Please ask your instructor for extra help\n"); + + printf("Game over!\n"); + + return 0; +} /* E0F main */ + +/* print a nice string :-) */ +void pok(void) +{ + switch(1 + rand() % 4) { + case 1: + printf("Very good!"); + break; + case 2: + printf("Excellent!"); + break; + case 3: + printf("Nice work!"); + break; + case 4: + printf("Keep up the good work!"); + } +} /* eof pok() */ + +/* print a less nice string :| */ +void pko(void) +{ + switch(1 + rand() % 4) { + case 1: + printf("No. Please try again."); + break; + case 2: + printf("Wrong. Try one more."); + break; + case 3: + printf("Don't give up!"); + break; + case 4: + printf("No. Keep trying."); + } /* end switch */ +} /* eof pko() */ + diff --git a/exercises/deitel/ch5/even.c b/exercises/deitel/ch5/even.c @@ -0,0 +1,35 @@ +/* Esercizio 5.18 */ + +#include <stdio.h> + +int even(int); + +int main() +{ + int num; + + printf("Give me a number (%d to end): ", EOF); + scanf("%d", &num); + while(num != EOF) { + printf("%d ", num); + if(!even(num)) + printf("is even\n"); + else + printf("is odd\n"); + + printf("Give me a number (%d to end): ", EOF); + scanf("%d", &num); + } /* end while (num) */ + + return 0; +} /* E0F main */ + +/* check if n is even */ +int even(int n) +{ + if( !(n % 2)) + return 0; + else + return 1; +} /* eof even() */ + diff --git a/exercises/deitel/ch5/forms.c b/exercises/deitel/ch5/forms.c @@ -0,0 +1,106 @@ +/* Exercise 5.21 */ + +void triangle(int, int, int); +void square(int, int, int); + +int main() +{ + int n, c, choose = 0; + + while(choose > 4 || choose < 1) { + printf( + "\nFigures:\n\n" + " 1: empty triangle\n" + " 2: full triangle\n" + " 3: empty square\n" + " 4: full square\n" + "\n" + ); + + printf("Choose a figure number: "); + scanf("%d", &choose); + } + + printf("\nGive me height: "); + scanf("%d", &n); + + getchar(); /* take newline and, of course, ignore it */ + + printf("Give me the character: "); + c = getchar(); + + printf("\n"); + switch(choose) { + case 1: + triangle(n, c, 0); + break; + case 2: + triangle(n, c, 1); + break; + case 3: + square(n, c, 0); + break; + case 4: + square(n, c, 1); + break; + } /* end switch (choose) */ + printf("\n"); + + return 0; +} /* E0F main */ + +/* Show a triangle of "character" of "height" size */ +void triangle(int height, int character, int full) +{ + int i, j, k, x; + + for(i = height - 1, x = 1; i >= 1; x+=2, i--) { + for(j = 1; j <= i; j++) + printf(" "); + + printf("%c", character); + + if(i == height - 1) { + printf("\n"); + continue; + } + + for(k = x; k > 2; k--) + printf("%c", full ? character : ' '); + + printf("%c\n", character); + } + + /* print the base */ + if(full) + height = height-- * 2; + + for(i = 1; i <= height ; i++) + printf("%c%s", character, full ? "" : " "); + printf("\n"); +} /* eof triangle() */ + +/* Show a square of "character" of "height" size */ +void square(int height, int character, int full) +{ + int i, j; + + int base() { + for(i = full ? height : height / 2 + (!(height % 2) ? 0 : 1); i >= 1; i--) + printf("%c%s", character, full ? "" : " "); + printf("\n"); + } + + base(height); + /* begin square */ + for(i = height - 2; i >= 1; i--) { + printf("%c", character); + for(j = 1; j <= height - (full ? 2 : !(height % 2) ? 3 : 2 ); j++) + printf("%c", full ? character : ' '); + printf("%c\n", character); + } + /* end square */ + base(height); + +} /* eof square() */ + diff --git a/exercises/deitel/ch5/gcd.c b/exercises/deitel/ch5/gcd.c @@ -0,0 +1,29 @@ +/* Exercise 5.29 */ + +int gcd(int, int); + +int main() +{ + int num1, num2; + + printf("Give me two numbers: "); + scanf("%d%d", &num1, &num2); + + printf("GCD: %d\n", gcd(num1, num2)); + + return 0; +} /* E0F main */ + +/* return GCD between two numbers */ +int gcd(int x, int y) +{ + int i; + + for(i = x; i >= 2; i--) { + if( !(x % i) && !(y % i) ) + return i; + } + return 1; + +} /* eof gcd() */ + diff --git a/exercises/deitel/ch5/getcharge.c b/exercises/deitel/ch5/getcharge.c @@ -0,0 +1,82 @@ +/* Esercizio 5.9 */ + +#include <stdio.h> + +float calculateCharges(float); + +int main() +{ + int i; + float t_hours = 0.0, t_charge = 0.0; + float c1_hours, c2_hours, c3_hours; + float c_charge; /* for all clients */ + + for(i = 1; i <= 3; i++) { + printf("Client %d, get hours: ", i); + switch(i) { + case 1: + scanf("%f", &c1_hours); + break; + case 2: + scanf("%f", &c2_hours); + break; + case 3: + scanf("%f", &c3_hours); + break; + } /* end switch (i) */ + } /* end for (i) */ + + printf("\nCar\tHours\tCharge\n"); + for(i = 1; i <= 3; i++) { + switch(i) { + case 1: + c_charge = calculateCharges(c1_hours); + printf("%d\t%.1f\t%.2f\n", i, c1_hours, c_charge); + t_charge += c_charge; + t_hours += c1_hours; + break; + case 2: + c_charge = calculateCharges(c2_hours); + printf("%d\t%.1f\t%.2f\n", i, c2_hours, c_charge); + t_charge += c_charge; + t_hours += c2_hours; + break; + case 3: + c_charge = calculateCharges(c3_hours); + printf("%d\t%.1f\t%.2f\n", i, c3_hours, c_charge); + t_charge += c_charge; + t_hours += c3_hours; + } /* end switch (i) */ + } /* end for (i) */ + + printf("TOTAL\t%.1f\t%.2f\n", t_hours, t_charge); + + return 0; +} /* E0F main */ + +/* calcultate client charge */ +float calculateCharges(float x) +{ + /* x = hours + t = charge */ + + float t = 1.50; + int i; + + if (x > 3.0) { + for(i = 3; i <= x * 100.0 / 100.0; i++) { + t += 0.50; + } + if(x - (i - 1)) + t += 0.50; + } + else + t += 0.50; + + if( t > 10.0) + t = 10.0; + + return t; + +} /* E0F calculateChages */ + diff --git a/exercises/deitel/ch5/getsecs.c b/exercises/deitel/ch5/getsecs.c @@ -0,0 +1,54 @@ +/* Esercizio 5.23 */ + +#include <stdio.h> + +int getsecs(int, int, int); + +int main() +{ + int h, m, s; + int t_1, t_2; + + printf("Give me the first time (hh mm ss): "); + scanf("%d%d%d", &h, &m, &s); + if( !(t_1 = getsecs(h, m, s)) ) { + printf("Wrong date: %d:%d:%d\n", h, m, s); + return -1; + } + + printf("Give me the first time (hh mm ss): "); + scanf("%d%d%d", &h, &m, &s); + if( !(t_2 = getsecs(h, m, s)) ) { + printf("Wrong date: %d:%d:%d\n", h, m, s); + return -1; + } + + printf("Difference in second it: %ds\n", t_1 >= t_2 ? t_1 - t_2 : t_2 - t_1); + + return 0; +} /* E0F main */ + +/* Count the seconds between 12:00 and "hh:mm:ss" */ +int getsecs(int hh, int mm, int ss) +{ + int i; + + if(hh > 12 || (hh == 12 && (mm || ss)) ) { + printf("Date is deleted!\n"); + return 0; + } + + /* count seconds from hh to 12 */ + for(i = hh; i < 12; i++) { + ss += 3600; + } /* eof for (i) */ + + /* count the seconds of mm */ + for(i = mm; i >= 1; i--) { + ss += 60; + } + + return 43200 - ss; + +} /* eof getsecs() */ + diff --git a/exercises/deitel/ch5/getsquare.c b/exercises/deitel/ch5/getsquare.c @@ -0,0 +1,29 @@ +/* Esercizio 5.19 */ + +void square(int); + +int main() +{ + int n; + + printf("Give me the side: "); + scanf("%d", &n); + + square(n); + + return 0; +} /* E0F main */ + +/* Print a square of "side" size */ +void square(int side) +{ + int i, j; + + for(i = side; i >= 1; i--) { + for(j = side; j >= 1; j--) + printf("*"); + printf("\n"); + } + +} /* eof square() */ + diff --git a/exercises/deitel/ch5/getsquare2.c b/exercises/deitel/ch5/getsquare2.c @@ -0,0 +1,36 @@ +/* Esercizio 5.20 */ + +#include <stdio.h> + +void square(int, int); + +int main() +{ + int n, c; + + printf("Give me the side: "); + scanf("%d", &n); + + getchar(); /* take newline and, of course, ignore it */ + + printf("Give me the character: "); + c = getchar(); + + square(n, c); + + return 0; +} /* E0F main */ + +/* Print a square of "side" size */ +void square(int side, int fillCharacter) +{ + int i, j; + + for(i = side; i >= 1; i--) { + for(j = side; j >= 1; j--) + printf("%c", fillCharacter); + printf("\n"); + } + +} /* eof square() */ + diff --git a/exercises/deitel/ch5/hanoi.c b/exercises/deitel/ch5/hanoi.c @@ -0,0 +1,38 @@ +/* Exercise 5.39 */ + +#include <stdio.h> + +int hanoi(int, int, int, int); + +int main() +{ + int d = 4; /* disks number */ + + printf("Total moves: %d\n", hanoi(d, 1, 3, 2)); + + return 0; +} /* E0F main */ + + +/* Move the disks of the Hanoi towers */ +int hanoi(int disks, int p_src, int p_dst, int p_tmp) +{ + static int moves = 0; + ++moves; + + if(disks == 1) { + printf("%d => %d\n", p_src, p_dst); + } + else { + /* 1. Move n - 1 disks from pole 1 to 2, using the 3 as temp pole */ + /* 2. Move the latest disk (largest) from pole 1 to 3 */ + /* 3. Move the n - 1 disks from pole 2 to 3, using the 1 as temp pole */ + + hanoi(disks - 1, p_src, p_tmp, p_dst); + printf("%d => %d\n", p_src, p_dst); + hanoi(disks - 1, p_tmp, p_dst, p_src); + } + + return moves; +} /* eof hanoi() */ + diff --git a/exercises/deitel/ch5/hypo.c b/exercises/deitel/ch5/hypo.c @@ -0,0 +1,27 @@ +/* Esercizio 5.15 */ + +#include <stdio.h> +#include <math.h> + +double hypotenuse(double, double); + +int main() +{ + int i; + double side1, side2; + + for(i = 1; i <= 3; i++) { + printf("Give me sides (s1 s2): "); + scanf("%lf%lf", &side1, &side2); + + printf("Side1\tSide2\tHypotenuse\n"); + printf("%.1f\t%.1f\t%.1f\n", side1, side2, hypotenuse(side1, side2)); + } + + return 0; +} /* E0F main */ + +double hypotenuse(double x, double y) +{ + return sqrt(x*x + y*y); +} /* eof hypotenuse() */ diff --git a/exercises/deitel/ch5/interval.c b/exercises/deitel/ch5/interval.c @@ -0,0 +1,20 @@ +/* Esercizio 5.13 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +int main() +{ + srand(time(NULL)); + + printf("1 <= %d <= 2\n", 1 + rand() % 2); + printf("1 <= %d <= 100\n", 1 + rand() % 100); + printf("0 <= %d <= 9\n", rand() % 10); + printf("1000 <= %d <= 1112\n", 1000 + 1 + rand() % 112); + printf("-1 <= %d <= 3\n", -1 + rand() % 5); + printf("-3 <= %d <= 11\n", -3 + rand() % 15); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/intgroup.c b/exercises/deitel/ch5/intgroup.c @@ -0,0 +1,27 @@ +/* Esercizio 5.14 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +int main() +{ + int i; + + srand( time(NULL) ); + + /* 2 4 6 8 10 */ + while((i = 2 + rand() % 10) % 2) ; + printf("2 4 6 8 10: %d\n", i); + + /* 3 5 7 9 11 */ + while( !( (i = 3 + rand() % 9) % 2) ) ; + printf("3 5 7 9 11: %d\n", i); + + /* 6 10 14 18 22 */ + while( (i = 6 + rand() % 17) % 4 != 2) ; + printf("6 10 14 18 22: %d\n", i); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/intpow.c b/exercises/deitel/ch5/intpow.c @@ -0,0 +1,37 @@ +/* Esercizio 5.16 */ + +#include <stdio.h> + +int integerPower(int, int); + +int main() +{ + int b, e; + + printf("Insert base: "); + scanf("%d", &b); + while(b != EOF) { + printf("Insert exponent: "); + scanf("%d", &e); + + printf("\n%d^%d = %d\n", b, e, integerPower(b, e)); + + printf("\nInsert base: "); + scanf("%d", &b); + } + + return 0; +} /* E0F main */ + +/* Return value of base^exponent */ +int integerPower(int base, int exponent) +{ + int i, x = base; + + for(i = 1; i < exponent; i++) { + x *= base; + } /* end for (i) */ + + return x; +} /* eof integerPower() */ + diff --git a/exercises/deitel/ch5/isfirst.c b/exercises/deitel/ch5/isfirst.c @@ -0,0 +1,30 @@ +/* Exercise 5.27 */ + +int isfirst(int); + +int main() +{ + int n; + + for(n = 1; n <= 10000; n += 2) { + if(isfirst(n)) + printf("%d\t", n); + } /* end for (n) */ + + printf("\n"); + return 0; +} /* E0F main */ + +/* check if num is first */ +int isfirst(int num) +{ + int i; + + for(i = 2; i <= 9; i++) { + if( (!(num % i) && (num != i)) || num == 2 ) + return 0; + } /* end for (i) */ + + return 1; +} /* eof isfirst() */ + diff --git a/exercises/deitel/ch5/multiple.c b/exercises/deitel/ch5/multiple.c @@ -0,0 +1,36 @@ +/* Esercizio 5.17 */ + +#include <stdio.h> + +int multiple(int, int); + +int main() +{ + int num1, num2; + + while(1) { + printf("Give me two numbers (^C to end): "); + scanf("%d%d", &num1, &num2); + + if(multiple(num1, num2)) + printf("%d is multiple of %d\n", num1, num2); + else + printf("%d is NOT multiple of %d\n", num1, num2); + + } /* end while(1) */ + + return 0; +} /* E0F main */ + +/* Check if x is multiple of y */ +int multiple(int x, int y) +{ + if(!y) + return 0; + else if(x > y && !(x % y) || y < 0 && x < y && !(x % y)) + return 1; + else + return 0; + +} /* eof multiple() */ + diff --git a/exercises/deitel/ch5/mystery.c b/exercises/deitel/ch5/mystery.c @@ -0,0 +1,33 @@ +/* Exercise 4.48 */ + +#include <stdio.h> + +int mystery(int, int); + +int main() +{ + int x, y; + + printf("Enter two integers: "); + scanf("%d%d", &x, &y); + + printf("The result is %d\n", mystery(x, y)); + + return 0; +} /* E0F main */ + +/* multiplies a for b times recursively */ +int mystery(int a, int b) +{ + if(b == -1) + return -a; + else if(b == 1) + return a; + else { + if(b > 1) + return a + mystery(a, b - 1); + else + return -a + mystery(a, b + 1); + } +} /* eof mystery() */ + diff --git a/exercises/deitel/ch5/nguess.c b/exercises/deitel/ch5/nguess.c @@ -0,0 +1,36 @@ +/* Exercise 5.35 */ + +#include <stdio.h> +#include <stdlib.h> + +int main() +{ + int num, gnum; + + while(gnum = 1 + rand() % 1000) { + printf("\nI have a number between 1 and 1000.\n"); + printf("Can you guess my number?\n"); + printf("Please type your first guess.\n"); + scanf("%d", &num); + + while(num != gnum) { + if(num < gnum) + printf("Too low. Try again.\n"); + else + printf("Too high. Try again.\n"); + + scanf("%d", &num); /* try again */ + } /* end while */ + + printf("\nExcellent! you guessed the number!\n"); + printf("Would you like to play again (y or n)?\n"); + + getchar(); /* take newline and, of course, ignore it */ + + if(getchar() == 'n') + break; + } /* end while */ + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/nguess2.c b/exercises/deitel/ch5/nguess2.c @@ -0,0 +1,46 @@ +/* Exercise 5.36 */ + +#include <stdio.h> +#include <stdlib.h> + +int main() +{ + int num, gnum; + int tests; + + while(gnum = 1 + rand() % 1000) { + printf("\nI have a number between 1 and 1000.\n"); + printf("Can you guess my number?\n"); + printf("Please type your first guess.\n"); + scanf("%d", &num); + + tests = 1; + while(num != gnum) { + ++tests; + if(num < gnum) + printf("Too low. Try again.\n"); + else + printf("Too high. Try again.\n"); + + scanf("%d", &num); /* try again */ + } /* end while */ + + if(tests == 10) + printf("Ahah! You know the secret!\n"); + else if(tests < 10) + printf("Either you know the secret or you go lucky!\n"); + else + printf("You should be able to do better!\n"); + + printf("Would you like to play again (y or n)?\n"); + + getchar(); /* take newline and, of course, ignore it */ + + if(getchar() == 'n') /* not so strict :-) */ + break; + + } /* end while */ + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/perfect.c b/exercises/deitel/ch5/perfect.c @@ -0,0 +1,56 @@ +/* Exercise 5.26 */ + +/* +Time results with "n <= 100000": + + 6: 1 2 3 = 6 + 28: 1 2 4 7 14 = 28 + 496: 1 2 4 8 16 31 62 124 248 = 496 + 8128: 1 2 4 8 16 32 64 127 254 508 1016 2032 4064 = 8128 + + 166.42s real 159.95s user 0.00s system +*/ + +#include <stdio.h> + +int perfect(int); + +int main() +{ + int n, s, f; + + for(n = 1; n <= 100000; n++) { + if(perfect(n)) { + printf("%d: ", n); + for(s = 1, f = 0; s < n; s++) { + if( !(n % s) ) { + printf("%d ", s); + f += s; + } + } + printf("= %d\n", f); + } + } /* end for (n) */ + + return 0; + +} /* E0F main */ + +/* check if num is a perfect number */ +int perfect(int num) +{ + int i, f_sum = 0; + + /* check its factors */ + for(i = 1; i < num; i++) { + if( !(num % i) ) { + /* num is multiple of i */ + f_sum += i; + } + } + + if(f_sum == num) return 1; + + return 0; +} /* eof perfect() */ + diff --git a/exercises/deitel/ch5/power.c b/exercises/deitel/ch5/power.c @@ -0,0 +1,28 @@ +/* Exercise 5. 37 */ + +#include <stdio.h> + +int power(int, int); + +int main() +{ + int base, exponent; + + printf("Give me a base and exponent: "); + scanf("%d%d", &base, &exponent); + + printf("Result: %d\n", power(base, exponent)); + + return 0; +} /* E0F main */ + +/* calculate power of an integer (recursively) */ +int power(int b, int e) +{ + if(e == 1) + return b * e; + + return b * power(b, e - 1); + +} /* eof power() */ + diff --git a/exercises/deitel/ch5/qualityPoints.c b/exercises/deitel/ch5/qualityPoints.c @@ -0,0 +1,36 @@ +/* Exercise 5.30 */ + +#include <stdio.h> + +int qualityPoints(int); + +int main() +{ + int average; + + printf("Give me your average: "); + scanf("%d", &average); + + printf("Your score is %d.\n", qualityPoints(average)); + + return 0; +} /* E0F main */ + +/* return a score depending of average */ +int qualityPoints(int avr) +{ + if(avr > 100) /* He/she is a genius :-) */ + return 100; + + if(avr >= 90 && avr <= 100) + return 4; + else if(avr >= 80 && avr <= 89) + return 3; + else if(avr >= 70 && avr <= 79) + return 2; + else if(avr >= 60 && avr <= 69) + return 1; + else + return 0; +} /* eof qualityPoints() */ + diff --git a/exercises/deitel/ch5/recgcd.c b/exercises/deitel/ch5/recgcd.c @@ -0,0 +1,26 @@ +/* Exercise 5.42 */ + +#include <stdio.h> + +int gcd(int, int); + +int main() +{ + int num1, num2; + + printf("Give me two numbers: "); + scanf("%d%d", &num1, &num2); + printf("GCD between %d and %d is %d.\n", num1, num2, gcd(num1, num2)); + + return 0; +} /* E0F main */ + +/* Calculate the GCD recursively */ +int gcd(int x, int y) +{ + if(y == 0) + return x; + + return gcd(y, x % y); +} /* eof gcd() */ + diff --git a/exercises/deitel/ch5/recmain.c b/exercises/deitel/ch5/recmain.c @@ -0,0 +1,14 @@ +/* Exercise 5.43 */ + +#include <stdio.h> + +int main() +{ + static int count = 1; + + printf("%d\n", count++); + main(); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/recsee.c b/exercises/deitel/ch5/recsee.c @@ -0,0 +1,31 @@ +/* Exercise 5.41 */ + +#include <stdio.h> + +long factorial(long number); + +int main() +{ + int i; + + for(i = 0; i <= 10; i++) { + printf("%2d! = %ld\n\n", i, factorial(i)); + } + + return 0; +} /* E0F main */ + +/* Recursive definition of factorial() function */ +long factorial(long number) { + + if(number) printf("=> %d * factorial(%d)\n", number, number - 1); + + if(number <= 1) { + printf("===> ", " "); + return 1; + } + else + return number * factorial(number - 1); + +} /* eof factorial() */ + diff --git a/exercises/deitel/ch5/revint.c b/exercises/deitel/ch5/revint.c @@ -0,0 +1,36 @@ +/* Exercise 5.28 */ + +#include <stdio.h> +#include <math.h> + +void revint(int); + +int main() +{ + int number; + + printf("Give me a number: "); + scanf("%d", &number); + + revint(number); + printf("\n"); + + return 0; +} /* E0F main */ + +/* print a int to reverse */ +void revint(int num) +{ + int i; + + if(num > pow(10, 9)) { + printf("Number is too large!"); + return; + } + for(i = 1; i <= pow(10, 8); i *= 10) { + if(num / i % 10) + printf("%d", num / i % 10); + } /* end for (i) */ + +} /* eof revint() */ + diff --git a/exercises/deitel/ch5/round4.c b/exercises/deitel/ch5/round4.c @@ -0,0 +1,48 @@ +/* Esercizio 5.11 */ + +#include <stdio.h> +#include <math.h> + +float roundToInteger(float); +float roundToTenths(float); +float roundToHundreths(float); +float roundToThousandths(float); + +int main() +{ + float num = 21.199; + + do { + printf("%.3f %.3f %.3f %.3f\n", + roundToInteger(num), + roundToTenths(num), + roundToHundreths(num), + roundToThousandths(num)); + + printf("Give me a number (0 to end): "); + scanf("%f", &num); + } while(num * 100 / 100); + + return 0; +} /* E0F main */ + +float roundToInteger(float n) +{ + return floor( n * 1 + .5) / 1; +} /* eof roundToInteger */ + +float roundToTenths(float n) +{ + return floor( n * 10 + 5.) / 10; +} /* eof roundToTenths */ + +float roundToHundreths(float n) +{ + return floor( n * 100 + .5) / 100; +} /* eof roundToHundreths */ + +float roundToThousandths(float n) +{ + return floor( n * 1000 + .5) / 1000; +} /* eof roundToThousandths */ + diff --git a/exercises/deitel/ch5/showfloor.c b/exercises/deitel/ch5/showfloor.c @@ -0,0 +1,19 @@ +/* Esercizio 5.10 */ + +#include <stdio.h> +#include <math.h> + +int main() +{ + double num = 1; + + while(num * 100 / 100) { + printf("%.2f is now %.0f\n", num, floor( num )); + + printf("Give me a number (0 to end): "); + scanf("%lf", &num); + } /* end while (num) */ + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch5/smallfloat.c b/exercises/deitel/ch5/smallfloat.c @@ -0,0 +1,27 @@ +/* Exercise 5.25 */ + +float smallfloat(float, float, float); + +int main() +{ + float num1, num2, num3; + + printf("Give me 3 float numbers: "); + scanf("%f%f%f", &num1, &num2, &num3); + printf("Smallest is %.2f\n", smallfloat(num1, num2, num3)); + + return 0; +} /* E0F main */ + +/* return the smallest of three float numbers */ +float smallfloat(float x, float y, float z) +{ + if(x <= y && x <= z) + return x; + else if(y < z) + return y; + else + return z; + +} /* eof smallfloat() */ + diff --git a/exercises/deitel/ch5/splitint.c b/exercises/deitel/ch5/splitint.c @@ -0,0 +1,37 @@ +/* Exercise 5.22 */ + +#include <stdio.h> + +void splint(int); /* splint :-) */ + +int main() +{ + int num = 0; + + while(num < 1 || num > 32767) { + printf("Give me an integer between 1 and 32767: "); + scanf("%d", &num); + } + + splint(num); + + return 0; +} /* E0F main */ + +/* Split an integer in the range 1-32767 */ +void splint(int n) +{ + int i, check = 0; + + for(i = 10000; i >= 1; i /= 10) { + if(n / i % 10 != 0) + check = 1; + if(!check) + continue; + + printf("%d ", n / i % 10); + } + printf("\n"); + +} /* eof splint() */ + diff --git a/exercises/deitel/ch5/x_val.c b/exercises/deitel/ch5/x_val.c @@ -0,0 +1,17 @@ +/* Esercizio 5.8 */ + +#include <stdio.h> +#include <math.h> + +int main() +{ + printf("%.1f\n", fabs( 7.5 )); + printf("%.1f\n", fabs( 0.0 )); + printf("%.1f\n", ceil( 0.0 )); + printf("%.1f\n", fabs( -6.4 )); + printf("%.1f\n", ceil( -6.4 )); + printf("%.1f\n", ceil( -fabs( -8+floor( -5.5) ) )); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch6/8.txt b/exercises/deitel/ch6/8.txt @@ -0,0 +1,30 @@ +/* Exercise 6.8 */ + +a) printf("%c\n", f[6]); + +b) + printf("Give me a value: "); + scanf("%lf", &b[4]); + +c) + for(i = 0; i < 5; i++) + g[i] = 8; + +d) + double tot; + for(i = 0; i < 100; i++) + tot += c[i]; + +e) + for(i = 0; i < 11; i++) + b[i] = a[i]; + +f) + int l, s; /* large and small */ + for(i = 0; i < 99; i++) { + if(w[i] > large) + large = w[i]; + else if(w[i] < small) + small = w[i]; + } + diff --git a/exercises/deitel/ch6/airlines.c b/exercises/deitel/ch6/airlines.c @@ -0,0 +1,109 @@ +/* Exercise 6.21 */ + +#include <stdio.h> +#include <stdlib.h> + +#define POS 10 + +int getpost(int, int []); + +int main() +{ + int positions[POS+1] = { 0 }; /* positions[0] do a lot of things :-) */ + int c; /* 1 = first class, 2 = economy. */ + + srand( time(NULL) ); /* for the flight numbers ;) */ + + /* available classes (2 + 1): ac[0] is not a class */ + int ac[3] = { 0, 1, 1 }; + + int chclass = 0; /* for auto-change of class check */ + + while(1) { + + if(!chclass) { + printf("\n" + "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n" + "American airlines international airport :-)\n" + "AIRLINES PRENOTATION SYSTEM! (C)Claudio M.\n" + "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n" + "\nPlease type 1 for \"first class\"\n" + "Please type 2 for \"economy\"\n" + "Choose: "); + scanf("%d", &c); + printf("\n"); + } + else + --chclass; + + positions[0] = getpos(c, positions); + + if(positions[0] == -1) { + printf("The class %d is not exists, choose another class.\n", c); + continue; + } + else if(positions[0]) { + printf("<==================[ BOARDING PAPER ]==================>\n" + "Class: %d\n" + "Positions: %d\n" + "Fly number: *%d\n\n" + "Thank you for fly with us!\n" + "Hope you enjoy with our company.\n" + "<==================[ BOARDING PAPER ]==================>\n" + ,c, positions[0], 6789 + rand() & 1000); + positions[positions[0]] = 1; + + printf("\nPress a key for reserve a flight.\n"); + getchar(); /* ignore the newline */ + getchar(); /* wait for a key */ + } + else { /* there are not positions available in the class */ + ac[c] = 0; + + /* check if there is at least one available class */ + for(ac[0] = 0, positions[0] = 1; positions[0] <= 2; positions[0]++) + ac[0] += ac[positions[0]]; + + if(!ac[0]) { + printf("Sorry! There are not classes available.\n"); + printf("Take your car or run ;)\n"); + break; + } + + while( (positions[0] = getchar()) != 'n' && positions[0] != 'y') { + printf("Class %d is full! Want you try to check class %d?\n" + "Choose (y / n): ", c, c == 1 ? 2 : 1); + } + + if(positions[0] == 'n') { + printf("Next flight leaves in 3 hours\n"); + break; + } + c = c == 1 ? 2 : 1; + ++chclass; + } + } /* end while(1) */ + + return 0; +} /* E0F main */ + +/* Return the first free position of a class */ +int getpos(int class, int v[]) +{ + if(class != 1 && class != 2) { + return -1; + } + + int i; + int x = class == 1 ? 1 : 6; + int y = class == 1 ? 5 : 10; + + for(i = x; i <= y; i++) { + if(!v[i]) { + return i; + } + } /* end for (i) */ + + return 0; +} /* eof getpos() */ + diff --git a/exercises/deitel/ch6/autocraps.c b/exercises/deitel/ch6/autocraps.c @@ -0,0 +1,86 @@ +/* Exercise 6.20 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +enum Status { CONTINUE, WON, LOST }; + +int rollDice(void); +int play(void); + +int main() +{ + int i; + int c[2] = { 0 }; + + srand( time(NULL) ); + printf("Runs\tWIN\tLOST\n"); + for(i = 1; i <= 1000; i++) { + ++c[play() - 1]; + printf("%d\t%d\t%d\n", i, c[0], c[1]); + } + + printf("Total wins: %d\nTotal loses: %d\n", c[0], c[1]); + + return 0; +} /* E0F main */ + +/* play a time */ +int play(void) { + int sum, myPoint; + + enum Status gameStatus; + + //srand( time(NULL) ); + + sum = rollDice(); + + switch(sum) { + case 7: + case 11: + gameStatus = WON; + break; + case 2: + case 3: + case 12: + gameStatus = LOST; + break; + default: + gameStatus = CONTINUE; + myPoint = sum; + break; /* optional */ + } /* end switch (sum) */ + + while(gameStatus == CONTINUE) { + sum = rollDice(); + + if(sum == myPoint) + gameStatus = WON; + else + if(sum == 7) + gameStatus = LOST; + + } /* end while (gameStatus) */ + + if(gameStatus == WON) { + return WON; + } + else { + return LOST; + } + +} /* eof play() */ + +/* launch the dice, calculate the sum and print results */ +int rollDice(void) { + int die1, die2; + int workSum; + + die1 = 1 + rand() % 6; + die2 = 1 + rand() % 6; + workSum = die1 + die2; + + return workSum; +} /* end rollDice() */ + diff --git a/exercises/deitel/ch6/bsort2.c b/exercises/deitel/ch6/bsort2.c @@ -0,0 +1,63 @@ +/* Exercise 6.11 * + +/* Bubble Sort */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define SIZE 10 + +void parray(int [], int); + +int main() +{ + int array[SIZE]; + int i, j, t_val; + + srand( time(NULL) ); + + /* assign a random value to every element of array[] */ + for(i = 0; i < SIZE; i++) { + array[i] = 1 + rand() % 999; + } + + printf("This is the array before order:\n"); + parray(array, SIZE); + + /* bubble sort */ + int t_val2; + for(i = 0; i < SIZE; i++) { + for(j = 0; j < SIZE - i; j++) { + if(array[j] > array[j + 1]) { + t_val = array[j]; + array[j] = array[j + 1]; + array[j + 1] = t_val; + } /* end if */ + } /* end for (j) */ + + if(t_val2 == t_val) + break; + + } /* end for (i) */ + + printf("\nThis is the array after the order:\n"); + parray(array, SIZE); + + printf("\n"); + + return 0; +} /* E0F main */ + +/* print an array */ +void parray(int a[], int size) +{ + int i; + + for(i = 0; i < size; i++) + printf("%d ", a[i]); + + printf("\n"); + +} /* eof parray() */ + diff --git a/exercises/deitel/ch6/clochk.c b/exercises/deitel/ch6/clochk.c @@ -0,0 +1,71 @@ +/* Exercise 6.15 */ + +#include <stdio.h> +#define SIZE 20 + +int bs(int, const int [], int); +void bsort(int [], int); + +int main() +{ + int num[SIZE + 1] = { 0 }; + int i, j; + int c = 1; + + int k; + for(i = 1; i <= SIZE; i++) { + do { + printf("Give me a number (10-100): "); + scanf("%d", &num[0]); + } while(num[0] < 10 || num[0] > 100); + + bsort(num, SIZE); + + if(!bs(num[0], num, SIZE)) + printf("New number: %d\n", num[c++] = num[0]); + } /* end for (i) */ + + return 0; +} /* E0F main */ + +/* Binary search: find (?) key in the array v[] */ +int bs(int key, const int v[], int s) +{ + int i, m; + int low = 1; + + while(low <= s) { + m = (low + s) / 2; + if(key == v[m]) + return m; + + if(key < v[m]) + s = m - 1; + else + low = m + 1; + } + return 0; + +} /* eof bs() */ + +/* Order an array using Bubble Sort algorithm */ +void bsort(int v[], int s) +{ + int i, j; + int t_val, t_val2; + + for(i = 0; i < s; i++) { + for(j = 1; j < s - i; j++) { + if(v[j] > v[j + 1]) { + t_val = v[j]; + v[j] = v[j + 1]; + v[j + 1] = t_val; + } /* end if */ + } /* end for (j) */ + + if(t_val2 == t_val) + break; + } /* end for (i) */ + +} /* eof bsort() */ + diff --git a/exercises/deitel/ch6/dice.c b/exercises/deitel/ch6/dice.c @@ -0,0 +1,56 @@ +/* Exercise 6.19 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> +#include "../practice/mt19937ar.c" + +int dice(void); + +#define LAUNCHES 36000 +#define LIMIT 50 + +int main() +{ + int i, t; + int results[13] = { 0 }; + + init_genrand( time(NULL ) ); + //srand( time(NULL) ); + + for(i = 1; i <= LAUNCHES; i++) + ++results[dice()]; + + printf("Print the results (* = not sense)\n"); + printf("There is a tollerance of \"n [-+] %d\"\n\n", LIMIT); + for(i = 2; i <= 12; i++) { + printf("%d:\t%d", i, results[i]); + + if(i <= 7) { + t = LAUNCHES / 36 * (i - 1); + + if(results[i] < t - LIMIT || results[i] > t + LIMIT) + printf("\t*\tout of range (%d-%d)", t - LIMIT, t + LIMIT); + } + else { + t = LAUNCHES / 36 * ((14 - i) - 1); + + if(results[i] < t - LIMIT || results[i] > t + LIMIT) + printf("\t*\tout of range (%d-%d)", t - LIMIT, t + LIMIT); + + } + printf("\n"); + } + + return 0; +} /* E0F main */ + +int dice(void) +{ + //int d1 = 1 + rand() % 6; + //int d2 = 1 + rand() % 6; + int d1 = 1 + genrand_int32() % 6; + int d2 = 1 + genrand_int32() % 6; + return d1 + d2; +} + diff --git a/exercises/deitel/ch6/dups.c b/exercises/deitel/ch6/dups.c @@ -0,0 +1,47 @@ +/* Exercise 6.28 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define SIZE 20 + +int ison(int, int [], int); + +int main(void) +{ + int tree[SIZE] = { 0 }; + int num, p = 0; /* the number and its position */ + + int i; /* just a counter */ + + srand( time(NULL) ); + + for(i = 1; i <= SIZE; i++) { + num = 1 + rand() % 20; + if( !ison(num, tree, SIZE) ) + tree[p++] = num; + } + + for(i = 0; i < SIZE; i++) + if(tree[i]) + printf("%d ", tree[i]); + + printf("\n"); + + return 0; +} /* E0F main */ + +/* check if 'n' in on 'v[]'. + * If yes return its position, else 0 */ +int ison(int n, int v[], int s) +{ + int c; + + for(c = 0; c < s; c++) + if(v[c] == n) + return c; + + return 0; +} + diff --git a/exercises/deitel/ch6/fig06_16_2.c b/exercises/deitel/ch6/fig06_16_2.c @@ -0,0 +1,195 @@ +/* Exercise 6.14 */ + +#include <stdio.h> +#define SIZE 100 + +/* function prototypes */ +void mean( const int answer[] ); +void median( int answer[] ); +void mode( int freq[], const int answer[] ) ; +void bubbleSort( int a[] ); +void printArray( const int a[] ); + +/* function main begins program execution */ +int main() +{ + int frequency[ 10 ] = { 0 }; /* initialize array frequency */ + + /* initialize array response */ + int response[ SIZE ] = + { 0, 8, 8, 9, 8, 9, 8, 9, 8, 9, + 7, 8, 9, 9, 9, 8, 9, 8, 9, 8, + 6, 9, 8, 9, 3, 9, 8, 9, 8, 9, + 7, 8, 9, 8, 9, 8, 9, 7, 8, 9, + 6, 7, 8, 9, 8, 9, 9, 8, 9, 2, + 7, 8, 9, 8, 9, 8, 9, 7, 5, 3, + 5, 6, 7, 2, 5, 3, 9, 4, 6, 4, + 7, 8, 9, 6, 8, 7, 8, 9, 7, 8, + 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, + 4, 5, 6, 1, 6, 5, 7, 8, 7 }; + + /* process responses */ + mean( response ); + median( response ); + mode( frequency, response ); + + return 0; /* indicates successful termination */ + +} /* end main */ + +/* calculate average of all response values */ +void mean( const int answer[] ) +{ + int j; /* counter for totaling array elements */ + int total = 0; /* variable to hold sum of array elements */ + + printf( "%s\n%s\n%s\n", "********", " Mean", "********" ); + + /* total response values */ + for ( j = 0; j < SIZE; j++ ) { + total += answer[ j ]; + } /* end for */ + + printf( "The mean is the average value of the data\n" + "items. The mean is equal to the total of\n" + "all the data items divided by the number\n" + "of data items ( %d ). The mean value for\n" + "this run is: %d / %d = %.4f\n\n", + SIZE, total, SIZE, ( double ) total / SIZE ); +} /* end function mean */ + +/* sort array and determine median element's value */ +void median( int answer[] ) +{ + printf( "\n%s\n%s\n%s\n%s", + "********", " Median", "********", + "The unsorted array of responses is" ); + + printArray( answer ); /* output unsorted array */ + + bubbleSort( answer ); /* sort array */ + + printf( "\n\nThe sorted array is" ); + printArray( answer ); /* output sorted array */ + + /* display median element */ + + if( !(SIZE % 2) ) + /* if the number is pair */ + printf("\n\nThe median is the mean of the two middle elements\n" + "%d and %d of the sorted %d element array.\n" + "For this run the median is %d\n\n", + answer[SIZE / 2], answer[SIZE / 2 + 1], SIZE, + (answer[SIZE / 2] + answer[SIZE / 2 + 1]) / 2 ); + else + printf( "\n\nThe median is element %d " + "of the sorted %d element array.\n" + "For this run the median is %d\n\n", + SIZE / 2, SIZE, answer[ SIZE / 2 ] ); + +} /* end function median */ + +/* determine most frequent response */ +void mode( int freq[], const int answer[] ) +{ + int rating; /* counter for accessing elements 1-9 of array freq */ + int j; /* counter for summarizing elements 0-98 of array answer */ + int h; /* counter for diplaying histograms of elements in array freq */ + int largest = 0; /* represents largest frequency */ + int p_mode = 0; /* represents the mode clone */ + int modeValue = 0; /* respesents most frequent response */ + + printf( "\n%s\n%s\n%s\n", + "********", " Mode", "********" ); + + /* initialize frequencies to 0 */ + for ( rating = 1; rating <= 9; rating++ ) { + freq[ rating ] = 0; + } /* end for */ + + /* summarize frequencies */ + for ( j = 0; j < SIZE; j++ ) { + ++freq[ answer[ j ] ]; + } /* end for */ + + /* output headers for result columns */ + printf( "%s%11s%19s\n\n%54s\n%54s\n\n", + "Response", "Frequency", "Histogram", + "1 1 2 2", "5 0 5 0 5" ); + + /* output results */ + for ( rating = 1; rating <= 9; rating++ ) { + printf( "%8d%11d ", rating, freq[ rating ] ); + + /* keep track of mode value and largest frequency value */ + if ( freq[ rating ] > largest ) { + largest = freq[ rating ]; + modeValue = rating; + } /* end if */ + else if(freq[ rating ] == largest) { + /* There is a pair of modes */ + p_mode = rating; + } + + /* output histogram bar representing frequency value */ + for ( h = 1; h <= freq[ rating ]; h++ ) { + printf( "*" ); + } /* end inner for */ + + printf( "\n" ); /* being new line of output */ + } /* end outer for */ + + /* display the mode value */ + printf("The mode is the most frequent value.\n"); + if(freq[p_mode] == freq[modeValue]) + printf("For this run the modes are %d and %d which" + " occurred %d times.\n", modeValue, p_mode, largest ); + else + printf("For this run the mode is %d which occurred" + " %d times.\n", modeValue, largest ); + +} /* end function mode */ + +/* function that sorts an array with bubble sort algorithm */ +void bubbleSort( int a[] ) +{ + int pass; /* pass counter */ + int j; /* comparison counter */ + int hold; /* temporary location used to swap elements */ + + /* loop to control number of passes */ + for ( pass = 1; pass < SIZE; pass++ ) { + + /* loop to control number of comparisons per pass */ + for ( j = 0; j < SIZE - 1; j++ ) { + + /* swap elements if out of order */ + if ( a[ j ] > a[ j + 1 ] ) { + hold = a[ j ]; + a[ j ] = a[ j + 1 ]; + a[ j + 1 ] = hold; + } /* end if */ + + } /* end inner for */ + + } /* end outer for */ + +} /* end function bubbleSort */ + +/* output array contents (20 values per row) */ +void printArray( const int a[] ) +{ + int j; /* counter */ + + /* output array contents */ + for ( j = 0; j < SIZE; j++ ) { + + if ( j % 20 == 0 ) { /* begin new line every 20 values */ + printf( "\n" ); + } /* end if */ + + printf( "%2d", a[ j ] ); + } /* end for */ + +} /* end function printArray */ + diff --git a/exercises/deitel/ch6/getpay.c b/exercises/deitel/ch6/getpay.c @@ -0,0 +1,39 @@ +/* Exercise 6.10 */ + +#include <stdio.h> + +#define BASE 200 /* base pay */ +#define XC 9 /* percentage */ +#define I_VAL 10 /* intervals */ + +int main() +{ + int interval[I_VAL] = { 0 }; /* interval[0] == current total */ + + printf("Enter your gross total (%d to end): ", EOF); + scanf("%d", &interval[0]); + + while(interval[0] != EOF) { + interval[0] = BASE + interval[0] * XC / 100; + printf("\nYour pay is $%d\n\n", interval[0]); + + if(interval[0] >= 1000) + ++interval[1]; + else + ++interval[interval[0] / 100 % 10]; + + printf("Enter your gross total (%d to end): ", EOF); + scanf("%d", &interval[0]); + } + + printf("Results:\n"); + + for(interval[0] = 2; interval[0] < I_VAL; interval[0]++) { + printf("$%d to $%d: %d\n", + interval[0] * 100, interval[0] * 100 + 99, interval[interval[0]]); + } + printf("More of $%d: %d\n", 1000, interval[1]); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch6/sales.c b/exercises/deitel/ch6/sales.c @@ -0,0 +1,102 @@ +/* Exercise 6.22 */ + +#include <stdio.h> + +#define VEND 4 +#define PROD 5 + +int main() +{ + double sales[PROD + 1][VEND + 1] = { 0 }; + int v, p; + double t; + + while(1) { + printf("\nEnter new monthly vendor ticket.\n\n"); + printf("Vendor ID (%d to end): ", EOF); + scanf("%d", &v); + + if( (v >= 1 && v <= VEND) || v == EOF ) + break; + else + printf("Invalid vendor ID: %d\n" + "Please check your vendor and try again.\n", v); + } + + while(v != EOF) { + + while(1) { + printf("Product ID: "); + scanf("%d", &p); + + if(p < 1 || p > PROD) + printf("Invalid product ID: %d\n" + "Please check your product and try again.\n", p); + else + break; + } + + while(1) { + printf("Monthly total for this product: "); + scanf("%lf", &t); + + if( t < 0 ) + printf("Invalid value: %d\n", t); + else + break; + } + + sales[p][v] += t; + + while(1) { + printf("\nEnter new monthly vendor ticket.\n\n"); + printf("Vendor ID (%d to end): ", EOF); + scanf("%d", &v); + + if( (v >= 1 && v <= VEND) || v == EOF ) + break; + else + printf("Invalid vendor ID: %d\n" + "Please check your vendor and try again.\n", v); + } + } + + printf("\nThe results for this run are the follow:\n"); + + /* print the header (cols - vendors) */ + printf("\nV:"); + for(v = 1; v <= VEND; v++) + printf("\t V0%d\t", v); + printf("\t TOT\n\n"); + + /* sum the rows and the cols for the total */ + /* of each product and each vendor. */ + for(p = 1; p <= PROD; p++) { + t = 0; + printf("P%d:\t", p); + for(v = 1; v <= VEND; v++) { + t += sales[p][v]; + printf("$%.2f\t\t", sales[p][v]); + } + printf("$%.2f\n", t); + t = 0; + } + printf("\nTOT\t"); + + /* print the totals of all products for each vendor */ + + sales[0][0] = 0; /* total of *all* products for *all* vendors */ + + for(v = 1; v <= VEND; v++) { + t = 0; + for(p = 1; p <= PROD; p++) { + t += sales[p][v]; + } + printf("$%.2f\t\t", t); + sales[0][0] += t; + } + printf("$%.2f\n\n", sales[0][0]); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch6/toth_2.c b/exercises/deitel/ch6/toth_2.c @@ -0,0 +1,136 @@ +/* Exercise 6.29 */ + +#include <stdio.h> + +#define BSIZE 8 /* board size */ + +int cyclical(int r, int c, int row, int col, int hor[], int ver[], int size); + +int main(void) +{ + int board[BSIZE][BSIZE] = { { 0 } }; + /* 0 1 2 3 4 5 6 7 */ + int horizontal[BSIZE] = { 2, 1, -1, -2, -2, -1, 1, 2 }; + int vertical[BSIZE] = { -1, -2, -2, -1, 1, 2, 2, 1 }; + + /* Method "heuristic of accessibility" */ + int accessibility[BSIZE+1][BSIZE] = { + { 2, 3, 4, 4, 4, 4, 3, 2 }, + { 3, 4, 6, 6, 6, 6, 4, 3 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 3, 4, 6, 6, 6, 6, 4, 3 }, + { 2, 3, 4, 4, 4, 4, 3, 2 }, + { BSIZE } /* extra value */ + }; + + int nr, nc; /* next position according with the "accessibility" matrix */ + int pass = 0; /* write permission checker :-) */ + int v1, v2, mn; + + int moveNumber = 0, i, r, c; + int currentRow = 0, currentColumn = 0; + int sr = currentRow; + int sc = currentColumn; + board[currentRow][currentColumn] = -1; /* current position */ + /* current accessibility position */ + --accessibility[currentRow][currentColumn]; + + + for(i = 1; i <= BSIZE*BSIZE; i++) { + nr = BSIZE; + nc = 0; + for(moveNumber = 0; moveNumber < BSIZE; moveNumber++) { + + /* read next potential position */ + r = currentRow + vertical[moveNumber]; + c = currentColumn + horizontal[moveNumber]; + + /* it's not out of chessboard */ + if( (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) && !board[r][c] ) { + pass = 1; /* write access granted :-) */ + + /* check accessibility level */ + if(accessibility[r][c] < accessibility[nr][nc]) { + nr = r; + nc = c; + } + else if(accessibility[r][c] == accessibility[nr][nc]) { + /* check *one* sublevel (r, c) */ + for(mn = 0, v1 = BSIZE; mn < BSIZE; mn++) { + if((accessibility[r+vertical[mn]][c+horizontal[mn]]<v1) && + (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) && + !board[r][c]) + v1 = accessibility[r + vertical[mn]][c + horizontal[mn]]; + } + + /* check *one* sublevel (nr, nc) */ + for(mn = 0, v2 = BSIZE; mn < BSIZE; mn++) { + if((accessibility[nr+vertical[mn]][nc+horizontal[mn]]<v2) && + (nr >= 0 && r < BSIZE) && (nc >= 0 && c < BSIZE) && + !board[nr][nc]) + v2 = accessibility[nr + vertical[mn]][nc + horizontal[mn]]; + } + + /* check'n set */ + if(v1 < v2) { + nr = r; + nc = c; + } + } + } /* end if */ + } /* end for (moveNumber) */ + + if(pass) { + currentRow = nr; + currentColumn = nc; + --accessibility[nr][nc]; + board[currentRow][currentColumn] = i; + pass = 0; + } + else /* stalled */ + break; + } /* end for (i) */ + + mn = 0; + for(r = 0; r < BSIZE; r++) { + for(c = 0; c < BSIZE; c++) { + if(board[r][c]) { + printf(" + "); + ++mn; + } + else + printf(" - "); + } + printf("\n"); + } + printf("Moves: %d\n", mn); + + /* check if the turn is cyclical */ + if(cyclical(sr, sc, currentRow, currentColumn, horizontal, vertical, BSIZE)) + printf("The turn is cyclical!\n"); + else + printf("The turn is *not* cyclical!\n"); + + return 0; +} /* E0F main */ + +/* check if a turn is cyclical */ +int cyclical(int r, int c, int row, int col, int hor[], int ver[], int size) +{ + int x, y; + + for(x = 0; x < size; x++) { + if(r + ver[x] == row) { + for(y = 0; y < BSIZE; y++) { + if(c + hor[y] == col) + return 1; + } /* end for */ + } /* end if */ + } /* end for (x) */ + + return 0; /* is not cyclical */ +} /* eof cyclical() */ + diff --git a/exercises/deitel/ch6/toth_b.c b/exercises/deitel/ch6/toth_b.c @@ -0,0 +1,49 @@ +/* Exercise 6.24 (b) */ + +#include <stdio.h> + +#define BSIZE 8 /* board size */ + +int main(void) +{ + int board[BSIZE][BSIZE] = { { 0 } }; + /* 0 1 2 3 4 5 6 7 */ + int horizontal[BSIZE] = { 2, 1, -1, -2, -2, -1, 1, 2 }; + int vertical[BSIZE] = { -1, -2, -2, -1, 1, 2, 2, 1 }; + + int moveNumber, i, r, c; + int currentRow = 0, currentColumn = 0; + board[currentRow][currentColumn] = -1; /* current position */ + + for(i = 1; i <= BSIZE*BSIZE; i++) { + for(moveNumber = 0; moveNumber < BSIZE; moveNumber++) { + + r = currentRow + vertical[moveNumber]; + c = currentColumn + horizontal[moveNumber]; + + if( (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) && !board[r][c] ) { + currentRow += vertical[moveNumber]; + currentColumn += horizontal[moveNumber]; + board[r][c] = i; + break; + } + } /* end for (moveNumber) */ + } /* end for (i) */ + + moveNumber = 0; + for(r = 0; r < BSIZE; r++) { + for(c = 0; c < BSIZE; c++) { + if(board[r][c]) { + printf("+"); + ++moveNumber; + } + else + printf("-"); + } + printf("\n"); + } + printf("Moves: %d\n", moveNumber); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch6/toth_c.c b/exercises/deitel/ch6/toth_c.c @@ -0,0 +1,84 @@ +/* Exercise 6.24 (c) */ + +#include <stdio.h> + +#define BSIZE 8 /* board size */ + +int main(void) +{ + int board[BSIZE][BSIZE] = { { 0 } }; + /* 0 1 2 3 4 5 6 7 */ + int horizontal[BSIZE] = { 2, 1, -1, -2, -2, -1, 1, 2 }; + int vertical[BSIZE] = { -1, -2, -2, -1, 1, 2, 2, 1 }; + + /* Method "heuristic of accessibility" */ + int accessibility[BSIZE][BSIZE] = { + { 2, 3, 4, 4, 4, 4, 3, 2 }, + { 3, 4, 6, 6, 6, 6, 4, 3 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 3, 4, 6, 6, 6, 6, 4, 3 }, + { 2, 3, 4, 4, 4, 4, 3, 2 } + }; + + /* next position according with the "accessibility" matrix */ + int new_r, new_c; + + int cal; /* current accessibility level */ + int pass = 0; /* write permission checker :-) */ + + int moveNumber = 0, i, r, c; + int currentRow = 0, currentColumn = 0; + board[currentRow][currentColumn] = -1; /* current position */ + + for(i = 1; i <= BSIZE*BSIZE; i++) { + cal = BSIZE; + for(moveNumber = 0; moveNumber < BSIZE; moveNumber++) { + + /* read next potential position */ + r = currentRow + vertical[moveNumber]; + c = currentColumn + horizontal[moveNumber]; + + /* it's not out of chessboard */ + if( (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) && !board[r][c] ) { + pass = 1; /* write access granted :-) */ + + /* check accessibility level */ + if(accessibility[r][c] < cal) { + new_r = r; + new_c = c; + cal = accessibility[new_r][new_c]; + } + } + } /* end for (moveNumber) */ + + if(pass) { + currentRow = new_r; + currentColumn = new_c; + --accessibility[new_r][new_c]; + board[currentRow][currentColumn] = i; + pass = 0; + } + else /* stalled */ + break; + } /* end for (i) */ + + moveNumber = 0; + for(r = 0; r < BSIZE; r++) { + for(c = 0; c < BSIZE; c++) { + if(board[r][c]) { + printf("+"); + ++moveNumber; + } + else + printf("-"); + } + printf("\n"); + } + printf("Moves: %d\n", moveNumber); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch6/toth_d.c b/exercises/deitel/ch6/toth_d.c @@ -0,0 +1,108 @@ +/* Exercise 6.24 (d) */ + +#include <stdio.h> + +#define BSIZE 8 /* board size */ + +int main(void) +{ + int board[BSIZE][BSIZE] = { { 0 } }; + /* 0 1 2 3 4 5 6 7 */ + int horizontal[BSIZE] = { 2, 1, -1, -2, -2, -1, 1, 2 }; + int vertical[BSIZE] = { -1, -2, -2, -1, 1, 2, 2, 1 }; + + /* Method "heuristic of accessibility" */ + int accessibility[BSIZE+1][BSIZE] = { + { 2, 3, 4, 4, 4, 4, 3, 2 }, + { 3, 4, 6, 6, 6, 6, 4, 3 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 4, 6, 8, 8, 8, 8, 6, 4 }, + { 3, 4, 6, 6, 6, 6, 4, 3 }, + { 2, 3, 4, 4, 4, 4, 3, 2 }, + { BSIZE } /* extra value */ + }; + + int nr, nc; /* next position according with the "accessibility" matrix */ + int pass = 0; /* write permission checker :-) */ + int v1, v2, mn; + + int moveNumber = 0, i, r, c; + int currentRow = 0, currentColumn = 0; + board[currentRow][currentColumn] = -1; /* current position */ + /* current accessibility position */ + --accessibility[currentRow][currentColumn]; + + for(i = 1; i <= BSIZE*BSIZE; i++) { + nr = BSIZE; + nc = 0; + for(moveNumber = 0; moveNumber < BSIZE; moveNumber++) { + + /* read next potential position */ + r = currentRow + vertical[moveNumber]; + c = currentColumn + horizontal[moveNumber]; + + /* it's not out of chessboard */ + if( (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) && !board[r][c] ) { + pass = 1; /* write access granted :-) */ + + /* check accessibility level */ + if(accessibility[r][c] < accessibility[nr][nc]) { + nr = r; + nc = c; + } + else if(accessibility[r][c] == accessibility[nr][nc]) { + /* check *one* sublevel (r, c) */ + for(mn = 0, v1 = BSIZE; mn < BSIZE; mn++) { + if((accessibility[r+vertical[mn]][c+horizontal[mn]]<v1) && + (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) && + !board[r][c]) + v1 = accessibility[r + vertical[mn]][c + horizontal[mn]]; + } + + /* check *one* sublevel (nr, nc) */ + for(mn = 0, v2 = BSIZE; mn < BSIZE; mn++) { + if((accessibility[nr+vertical[mn]][nc+horizontal[mn]]<v2) && + (nr >= 0 && r < BSIZE) && (nc >= 0 && c < BSIZE) && + !board[nr][nc]) + v2 = accessibility[nr + vertical[mn]][nc + horizontal[mn]]; + } + + /* check'n set */ + if(v1 < v2) { + nr = r; + nc = c; + } + } + } /* end if */ + } /* end for (moveNumber) */ + + if(pass) { + currentRow = nr; + currentColumn = nc; + --accessibility[nr][nc]; + board[currentRow][currentColumn] = i; + pass = 0; + } + else /* stalled */ + break; + } /* end for (i) */ + + mn = 0; + for(r = 0; r < BSIZE; r++) { + for(c = 0; c < BSIZE; c++) { + if(board[r][c]) { + printf(" + "); + ++mn; + } + else + printf(" - "); + } + printf("\n"); + } + printf("Moves: %d\n", mn); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch6/toth_rand.c b/exercises/deitel/ch6/toth_rand.c @@ -0,0 +1,51 @@ +/* Exercise 6.25 (a) */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define BSIZE 8 /* board size */ + +int main(void) +{ + int board[BSIZE][BSIZE] = { { 0 } }; + /* 0 1 2 3 4 5 6 7 */ + int horizontal[BSIZE] = { 2, 1, -1, -2, -2, -1, 1, 2 }; + int vertical[BSIZE] = { -1, -2, -2, -1, 1, 2, 2, 1 }; + + int moveNumber, i, r, c; + int currentRow = 0, currentColumn = 0; + board[currentRow][currentColumn] = -1; /* current position */ + + srand( time(NULL) ); + + for(i = 1; i <= BSIZE*BSIZE; i++) { + moveNumber = rand() % 8; + + r = currentRow + vertical[moveNumber]; + c = currentColumn + horizontal[moveNumber]; + + if( (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) && !board[r][c] ) { + currentRow += vertical[moveNumber]; + currentColumn += horizontal[moveNumber]; + board[r][c] = i; + } + } /* end for (i) */ + + moveNumber = 0; + for(r = 0; r < BSIZE; r++) { + for(c = 0; c < BSIZE; c++) { + if(board[r][c]) { + printf(" + "); + ++moveNumber; + } + else + printf(" - "); + } + printf("\n"); + } + printf("Moves: %d\n", moveNumber); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch6/toth_rand2.c b/exercises/deitel/ch6/toth_rand2.c @@ -0,0 +1,76 @@ +/* Exercise 6.25 (c) */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define BSIZE 8 /* board size */ + +int main(void) +{ + int board[BSIZE][BSIZE] = { { 0 } }; + /* 0 1 2 3 4 5 6 7 */ + int horizontal[BSIZE] = { 2, 1, -1, -2, -2, -1, 1, 2 }; + int vertical[BSIZE] = { -1, -2, -2, -1, 1, 2, 2, 1 }; + + int moveNumber, i, r, c; + int currentRow, currentColumn; + + int clen[20] = { 0 }; /* max integer size */ + long int test = 0; /* total tests */ + int n = 0; /* tests where x < y */ + + srand( time(NULL) ); + + while(moveNumber < 64) { + ++test; + + currentRow = currentColumn = 0; + board[currentRow][currentColumn] = -1; /* current position */ + for(i = 1; i <= BSIZE*BSIZE; ++i) { + moveNumber = rand() % 8; + + r = currentRow + vertical[moveNumber]; + c = currentColumn + horizontal[moveNumber]; + + if( (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) && + !board[r][c] ) { + currentRow += vertical[moveNumber]; + currentColumn += horizontal[moveNumber]; + board[r][c] = i; + } + + } /* end for (i) */ + + moveNumber = 0; + for(r = 0; r < BSIZE; r++) { + for(c = 0; c < BSIZE; c++) { + if(board[r][c]) { + ++moveNumber; + board[r][c] = 0; + } + } + } + + if(moveNumber > clen[n-1]) + clen[n++] = moveNumber; + + if(n == 20) { + printf("Out of limit!\n"); + return -1; + } + } /* end while (moveNumber) */ + + printf("Turns: %ld\n", test); /* total turns */ + + /* print the table */ + for( ; n > 1; n--) { + printf("%d=%d\t", n, clen[n]); + if( !(n % 10) ) { + printf("\n"); + } + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch6/turgraph.c b/exercises/deitel/ch6/turgraph.c @@ -0,0 +1,149 @@ +/* Exercise 6.25 + + * Command list: + * 1: Pen is up + * 2: Pen is down + * 3: Right + * 4: Left + * 5.n: Go ahead of n steps + * 6: print the floor + * 9: end of data (quit) +*/ + +#include <stdio.h> +#define SIZE 50 +#define CMD 11 + +int getroute(int, int); +void pmatrix(double [][SIZE], int); + +int main(void) +{ + double floor[SIZE][SIZE] = { {0} }; + + /* NOTE: don't use (for example) "5.9" but "5.09" and the + * 5.01 command do nothing: it write in the current position + * which has been already written bye the previous command. */ + + /* Don't forget '2' to write and '1', '6' and '9' to end */ + + double cmds[CMD] = { 2, 5.25, 3, 5.12, 3, 5.25, 3, 5.12, 1, 6, 9 }; + + /* Square (CMD = 11) + double cmds[CMD] = { 2, 5.12, 3, 5.12, 3, 5.12, 3, 5.12, 1, 6, 9 }; + */ + + /* C (CMD = 11) + double cmds[CMD] = { 3, 3, 2, 5.09, 4, 5.06, 4, 5.09, 1, 6, 9 }; + */ + /* H (CMD = 16) + double cmds[CMD] = { + 3, 2, 5.09, 4, 4, 5.05, 3, 5.08, 4, 5.05, 3, 3, 5.09, 1, 6, 9 + }; + */ + + int pen = 0; /* 0 don't write */ + int route = 4, i, j; + + int r = 0, c = 0; /* rows and cols */ + r = c = SIZE/2-1; /* Logo start from middle of floor */ + + /* loop all commands (cmds[]) */ + for(i = 0; i < CMD; i++) { + /* check the command */ + switch( (int)cmds[i] ) { + case 1: + pen = 0; + break; + case 2: + pen = 1; + break; + case 3: + case 4: + route = getroute(route, (int)cmds[i]); + break; + case 5: + j = (int)(cmds[i] * 100) % 100; + + if(cmds[i] == 5.02 || cmds[i] == 5.06) /* fix 5.02 and 5.06 */ + ++j; + + /* Overflow check */ + if( (route == 1 && r + j > SIZE) || (route == 2 && r - j < 0) || + (route == 3 && c - j < 0) || (route == 4 && c + j > SIZE) + ) { + printf("You can't go out of floor (%dx%d): 5.%d\n", + SIZE, SIZE, j); + return -1; + } + + for( ; j ; j--) { + /* UP[1], DOWN[2], LEFT[3], RIGHT[4] */ + + if(route > 2) + floor[r][route == 4 ? c++ : c--] = pen; + else + floor[route == 2 ? r-- : r++][c] = pen; + + } /* end for (j) */ + + /* cursor in the current position */ + if(route == 4) c--; + else if(route == 3) ++c; + else if(route == 2) ++r; + else --r; + + break; + case 6: + /* print the matrix */ + pmatrix(floor, SIZE); + break; /* not required */ + } /* end switch (cmds[i]) */ + + } /* end for (i) */ + printf("\n"); + + return 0; +} /* E0F main */ + +/* find the route "d" starting from "cr" */ +int getroute(int cr, int d) +{ + switch(cr) { + case 1: /* Up */ + return d; + break; + case 2: /* Down */ + return d == 4 ? 3 : 4; + break; + case 3: /* Left */ + return d == 3 ? 2 : 1; + break; + case 4: /* Right */ + return d == 4 ? 2 : 1; + break; + default: /* Uhm? */ + printf("Maybe you need a compass? :-)\n"); + return 0; + } +} /* end of getroute() */ + +/* Print the matrix */ +void pmatrix(double m[][SIZE], int s) +{ + int r, c; + + for(r = 0; r < s; r++) { + for(c = 0; c < s; c++) { + if(m[r][c]) + printf("+"); + else { + if(c == s - 1 || c == 0) printf("."); /* wall */ + printf(" "); + } + } + printf("\n"); + } + +} /* eof pmatrix() */ + diff --git a/exercises/deitel/ch6/turgraph2.c b/exercises/deitel/ch6/turgraph2.c @@ -0,0 +1,192 @@ +/* Exercise 6.23 (extended) + + * Command list: + * 1: Pen is up + * 2: Pen is down + * 3: Right + * 4: Left + * 5.n: Go ahead of n steps + * 6: print the floor + + * 8.n: Go in diagonal of n steps + if 3 is used go Down-Right (\) + if 4 (or nothing) is used go Down-Left (/) + + * 9: end of data (quit) +*/ + +#include <stdio.h> + +#define SIZE 50 +#define CMD 17 + +int getroute(int, int); +void pmatrix(double [][SIZE], int); + +int main(void) +{ + double floor[SIZE][SIZE] = { {0} }; + + /* NOTE: don't use (for example) "5.9" but "5.09" and the + * 5.01 command do nothing: it write in the current position + * which has been already written by the previous command. */ + + /* Don't forget '2' to write and '1', '6' and '9' to end */ + + /* Square (CMD = 11) + double cmds[CMD] = { 2, 5.12, 3, 5.12, 3, 5.12, 3, 5.12, 1, 6, 9 }; + */ + + /* C (CMD = 11) + double cmds[CMD] = { 3, 3, 2, 5.09, 4, 5.06, 4, 5.09, 1, 6, 9 }; + */ + /* H (CMD = 16) + double cmds[CMD] = { + 3, 2, 5.09, 4, 4, 5.05, 3, 5.08, 4, 5.05, 3, 3, 5.09, 1, 6, 9 + }; + */ + + /* Rumble (CMD = 17) + * /\ + * \/ */ + double cmds[CMD] = { + 2, 8.08, /* write \ */ + 3, 8.08, /* write / */ + 1, /* remove this for a middle's line */ + 4, 4, 5.15, /* back to start point */ + 2, 4, 4, /* change route */ + 8.08, /* write / */ + 3, 8.08, /* write \ */ + 1, 6, 9 /* end */ + }; + + int pen = 0; /* 0 don't write */ + int route = 4, i, j; + + int r = 0, c = 0; /* rows and cols */ + r = c = SIZE/2-1; /* Logo start from middle of floor */ + + /* loop all commands (cmds[]) */ + for(i = 0; i < CMD; i++) { + /* check the command */ + switch( (int)cmds[i] ) { + case 1: + pen = 0; + break; + case 2: + pen = 1; + break; + case 3: + case 4: + route = getroute(route, (int)cmds[i]); + break; + case 5: + j = (int)(cmds[i] * 100) % 100; + + if(cmds[i] == 5.02 || cmds[i] == 5.06) /* fix 5.02 and 5.06 */ + ++j; + + /* Overflow check */ + if( (route == 1 && r + j > SIZE) || (route == 2 && r - j < 0) || + (route == 3 && c - j < 0) || (route == 4 && c + j > SIZE) + ) { + printf("You can't go out of floor (%dx%d): 5.%d\n", + SIZE, SIZE, j); + return -1; + } + + for( ; j; j--) { + /* UP[1], DOWN[2], LEFT[3], RIGHT[4] */ + + if(route > 2) + floor[r][route == 4 ? c++ : c--] = pen; + else + floor[route == 2 ? r-- : r++][c] = pen; + + } /* end for (j) */ + + /* cursor in the current position */ + if(route == 4) c--; + else if(route == 3) ++c; + else if(route == 2) ++r; + else --r; + + break; + case 6: + /* print the matrix */ + pmatrix(floor, SIZE); + break; /* not required */ + case 8: + /* diagonal, oblique */ + j = (int)(cmds[i] * 100) % 100; + + if(cmds[i] == 8.02 || cmds[i] == 8.06) /* fix 8.02 and 8.06 */ + ++j; + + /* Overflow check + WIP */ + + for( ; j; j--) { + if(route == 1) /* right */ + floor[r++][c--] = pen; + else /* left. */ + floor[r++][c++] = pen; + } + + /* cursor in the current position */ + if(route == 1) + ++c; + else + --c; + --r; + + break; + } /* end switch (cmds[i]) */ + + } /* end for (i) */ + printf("\n"); + + return 0; +} /* E0F main */ + +/* find the route "d" starting from "cr" */ +int getroute(int cr, int d) +{ + switch(cr) { + case 1: /* Up */ + return d; + break; + case 2: /* Down */ + return d == 4 ? 3 : 4; + break; + case 3: /* Left */ + return d == 3 ? 2 : 1; + break; + case 4: /* Right */ + return d == 4 ? 2 : 1; + break; + default: /* Uhm? */ + printf("Maybe you need a compass? :-)\n"); + return 0; + } +} /* end of getroute() */ + +/* Print the matrix */ +void pmatrix(double m[][SIZE], int s) +{ + int r, c; + + for(r = 0; r < s; r++) { + for(c = 0; c < s; c++) { + if(m[r][c]) + printf("+"); + else { + if(c == s - 1 || c == 0) printf("."); /* wall */ + printf(" "); + } + } + printf("\n"); + } + +} /* eof pmatrix() */ + diff --git a/exercises/deitel/ch7/esimpletron.c b/exercises/deitel/ch7/esimpletron.c @@ -0,0 +1,457 @@ +/* Exercise 7.29 */ + +/* The Extended Simpletron (and LMS) implementation */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <math.h> + +#define MEMSIZE 1000 +#define MAXWORD 7 + +/* Input/Output */ +#define READ 10 +#define WRITE 11 +#define NEWLINE 12 +#define SREAD 13 +#define SWRITE 14 + +/* Loading/Storing */ +#define LOAD 20 +#define STORE 21 + +/* Arithmetical */ +#define ADD 30 +#define SUBTRACT 31 +#define DIVIDE 32 +#define MULTIPLY 33 +#define REST 34 +#define POWER 35 + +/* Reference and control */ +#define BRANCH 40 +#define BRANCHNEG 41 +#define BRANCHZERO 42 +#define HALT 43 + +int checkword(int word, int size); +void dump(float acc, int icounter, float mem[]); +int r_htoi(const char string[]); +char * p_itoh(int num, char str[], int z); + +int main(void) +{ + char s_mem[MAXWORD] = { 0 }; + float memory[MEMSIZE] = { 0 }, accumulator = 0; + + int operationCode = 0, instructionRegister = 0, operand = 0; + int i, j, k, err = 0; + float t_val = 0, f_tmp; + + printf("*** Welcome to the Simpletron! ***\n" + "*** Please enter your program one instruction ***\n" + "*** (or data word) at a time. I will type the ***\n" + "*** location number and a question mark (?). ***\n" + "*** You then type the word for that location. ***\n" + "*** Use the sentinel -999999 to stop entering ***\n" + "*** your program. ***\n"); + + for(i = 0; i < MEMSIZE; i++) { + while(1) { + printf("%.2d ?? ", i); + scanf("%s", s_mem); + + memory[i] = r_htoi(s_mem); + + if(memory[i] == -999999) { + memory[i] = 0; + i = MEMSIZE; /* Terminate the for loop */ + break; + } + + if(s_mem[0] != '+') { + printf("*** Invalid instruction: %s\n", s_mem); + printf("*** Please use '+' or exit.\n"); + continue; + } + + if( checkword((int)memory[i], MEMSIZE) ) { + printf("*** Invalid instruction: +%.0f\n" + "*** Please retype it or exit.\n", memory[i]); + } + else + break; + + } /* end while */ + } /* end for (i) */ + + printf("*** Program loading completed ***\n" + "*** Program execution begins ***\n"); + + for(i = 0; i < MEMSIZE; i++) { + instructionRegister = (int)memory[i]; + + operationCode = + instructionRegister / (instructionRegister <= 9999 ? 100 : 1000); + operand = + instructionRegister % (instructionRegister <= 9999 ? 100 : 1000); + + /* this is required because after the switch() + statement the 'i' counter is incremented of 1. */ + if(operationCode >= BRANCH) + --operand; + + switch(operationCode) { + case READ: + printf("\nInsert a word: "); + scanf("%f", &memory[operand]); + + break; + case WRITE: + printf("\nMemory location: %.2d\nWord: %.2f\n", + operand, memory[operand]); + + break; + case NEWLINE: + printf("\n"); + break; + case SREAD: + /* If this instruction is used then HALT is required */ + printf("\nInsert a string: "); + scanf("%s", s_mem); + + if(strlen(s_mem) > 3) { + err = 3; + break; + } + + for(j = 0; (unsigned)j < strlen(s_mem); j++) { + if((int)s_mem[j] > 99) { + err = 4; + t_val = j; + break; + } + } + memory[operand] = 0; + + for(j = strlen(s_mem), k = 1; j >= 0; k *= 100, j--) + memory[operand] += s_mem[j] * k; + + for(t_val = 0.1, k = 1; k < memory[operand]; t_val *= 0.10, k *= 10) ; + t_val /= 0.10; + + memory[operand] *= t_val; + memory[operand] += strlen(s_mem); + + break; + case SWRITE: + printf("\nMemory location: %.0f\nWord: ", memory[operand]); + for(j = (int)memory[operand], t_val = 100; j ; t_val *= 100, j--) { + f_tmp = memory[operand] * t_val; + k = (int)f_tmp % 100; + printf("%c", k); + } + printf("\n"); + + break; + case LOAD: + accumulator = memory[operand]; + break; + case STORE: + memory[operand] = accumulator; + break; + + case ADD: + accumulator += memory[operand]; + + break; + case SUBTRACT: + accumulator -= memory[operand]; + + break; + case DIVIDE: + if( !memory[operand] ) + err = 2; + else + accumulator /= memory[operand]; + + break; + case MULTIPLY: + accumulator *= memory[operand]; + + break; + case REST: + accumulator = (int)accumulator % (int)memory[operand]; + + break; + + case POWER: + accumulator = pow(accumulator, memory[operand]); + break; + + case BRANCH: + i = operand; + break; + case BRANCHNEG: + if(accumulator < 0) + i = operand; + + break; + case BRANCHZERO: + if(!accumulator) + i = operand; + + break; + + case HALT: + i = MEMSIZE; /* terminate the for loop */ + /* dump(accumulator, i, memory); */ + + break; + case 0: + break; + + default: + printf("*** unknown error: %d\n", instructionRegister); + dump(accumulator, i, memory); + printf("\nAre'nt you using HALT (+4300)?\n"); + exit(-1); + } + + if(accumulator > MEMSIZE * MEMSIZE - 1 || + accumulator < MEMSIZE * -MEMSIZE + 1) + err = 1; + + if(err) { /* Error messages manager */ + printf("\n*** "); + switch(err) { + case 1: + printf("Out of the accumulator limit"); + break; + case 2: + printf("Attempt to divide by zero"); + break; + case 3: + printf("You can put max 3 numbers for memory location"); + break; + case 4: + printf("This ASCII code is too long: %d (%c)", + s_mem[(int)t_val], s_mem[(int)t_val]); + } + + printf(" ***\n"); + + printf("*** Simpletron execution abnormally terminated ***\n"); + dump(accumulator, i, memory); + exit(-1); + } + + } /* end for (i) */ + + /* dump(accumulator, i, memory); */ + printf("\n*** Simpletron execution terminated ***\n"); + + return 0; +} /* E0F main */ + +/* Check if a "word" is correct */ +int checkword(int word, int size) +{ + if( word < 0 || word >= MEMSIZE * MEMSIZE || + word % (word <= 9999 ? 100 : 1000) >= size ) { + return 1; + } + + switch(word / (word <= 9999 ? 100 : 1000)) { + case READ: + case WRITE: + case NEWLINE: + case SREAD: + case SWRITE: + case LOAD: + case STORE: + case ADD: + case SUBTRACT: + case DIVIDE: + case MULTIPLY: + case REST: + case POWER: + case BRANCH: + case BRANCHNEG: + case BRANCHZERO: + case HALT: + case 0: + break; + default: + return 1; + + } /* end switch (word) */ + + return 0; + +} /* eof checkword() */ + +/* Show a dump of the current memory state */ +void dump(float acc, int icounter, float mem[]) +{ + int i, j; + char string[6] = { 0 }; + + printf("\nREGISTERS:\n"); + + printf("accumulator\t\t%c%s\n", acc < 0 ? '-' : '+', p_itoh(acc, string, 4)); + printf("instructionCounter\t%s\n", p_itoh(icounter, string, 2)); + + printf("instructionRegister\t%c%s\n", mem[icounter] < 0 ? '-' : '+', + p_itoh(mem[icounter] < 0 ? -mem[icounter] : mem[icounter], string, 4)); + + printf("operationCode\t\t%s\n", p_itoh(mem[icounter] / 100, string, 2)); + printf("operand\t\t\t%s\n", p_itoh((int)mem[icounter] % 100, string, 2)); + + printf("\nMEMORY:\n"); + + /* Print the header */ + printf("%3c", ' '); + for(i = 0; i < 10; i++) + printf("%5d ", i); + printf("\n"); + + for(i = 0; i < MEMSIZE; i += 10) { + printf("%.3d", i); + for(j = i; j < i+10; j++) { + printf(" %c%s", mem[j] < 0 ? '-' : '+', + p_itoh(mem[j] < 0 ? -mem[j] : mem[j], string, 4)); + } + printf("\n"); + } + +} /* eof dump() */ + +int r_htoi(const char string[]) +{ + int i, num = 0, n = 1; + char s[1] = { 0 }; + + for(i = strlen(string) - 1; i >= 0; i--) { + if(string[i] >= 'A' && string[i] <= 'F') + n *= 10; + + n *= 10; + } + + n /= 10; + + for(i = 0; i < 7; n /= 10, i++) { + + if(string[i] >= 'A' && string[i] <= 'F') { + num += 1 * n; + n /= 10; + } + + switch(string[i]) + { + case 'A': + case 'a': + /* 0 */ + break; + case 'B': + case 'b': + num += 1 * n; + break; + case 'C': + case 'c': + num += 2 * n; + break; + case 'D': + case 'd': + num += 3 * n; + break; + case 'E': + case 'e': + num += 4 * n; + break; + case 'F': + case 'f': + num += 5 * n; + break; + default: + *s = string[i]; + if(string[0] == '-') + num -= atoi(s) * n; + else + num += atoi(s) * n; + } /* end switch */ + + } + + return num; +} + +char * p_itoh(int num, char str[], int z) +{ + int i, idx = 0; + + if(num > 0) { + if(num <= 9) i = 1; + else if(num <= 99) i = 10; + else if(num <= 999) i = 100; + else if(num <= 9999) i = 1000; + else if(num <= 99999) i = 10000; + else { + printf("error in p_itoh(): unknown range: %d\n", num); + printf("\nAre'nt you using HALT (+4300)?\n"); + exit(-1); + } + } + else if(!num) { + for(i = 0; i < (int)sizeof(str); i++) { + if(i < z) str[i] = '0'; + else str[i] = ' '; + } + return str; + } + else { + printf("Negative numbers are not allowed!\n"); + return 0; + } + + for( ; i ; idx++, i /= 10) { + + if( (num / i % 10) == 1 ) { + + i /= 10; + if(!i) break; + switch(num / i % 10) { + case 0: + str[idx] = 'A'; + break; + case 1: + str[idx] = 'B'; + break; + case 2: + str[idx] = 'C'; + break; + case 3: + str[idx] = 'D'; + break; + case 4: + str[idx] = 'E'; + break; + case 5: + str[idx] = 'F'; + break; + default: + str[idx] = (char)(num / i % 10) + '0'; + i *= 10; + } + } + + else { + str[idx] = (char)(num / i % 10) + '0'; + } + } /* end for (i) */ + + return str; +} + diff --git a/exercises/deitel/ch7/funcptr.c b/exercises/deitel/ch7/funcptr.c @@ -0,0 +1,149 @@ +/* Exercise 7.28 */ + +/* Fig. 6.22: fig06_22.c + Double-subscripted array example */ +#include <stdio.h> +#define STUDENTS 3 +#define EXAMS 4 + +/* function prototypes */ +void minimum( const int grades[][ EXAMS ], int pupils, int tests ); +void maximum( const int grades[][ EXAMS ], int pupils, int tests ); +void average( const int setOfGrades[][ EXAMS ], int pupils, int tests ); +void printArray( const int grades[][ EXAMS ], int pupils, int tests ); + +/* function main begins program execution */ +int main(void) +{ + /* initialize student grades for three students (rows) */ + const int studentGrades[ STUDENTS ][ EXAMS ] = + { { 77, 68, 86, 73 }, + { 96, 87, 89, 78 }, + { 70, 90, 86, 81 } }; + + void (*processGrades[4])(const int [][EXAMS], int, int) = { + printArray, minimum, maximum, average + }; + int sel; + + while(1) { + printf("Enter a choice:\n" + " 0 Print the array of grades\n" + " 1 Find the minimum grade\n" + " 2 Find the maximum grade\n" + " 3 Print the average on all tests for each student\n" + " 4 End program\n"); + printf("Selection: "); + scanf("%d", &sel); + + if(sel > 4 || sel < 0) { + printf("\nInvalid choice: choose another option\n\n"); + } + else if(sel == 4) + return 0; + else + break; + } + + (*processGrades[sel])( studentGrades, STUDENTS, EXAMS ); + + return 0; /* indicates successful termination */ + +} /* end main */ + +/* Find the minimum grade */ +void minimum( const int grades[][ EXAMS ], int pupils, int tests ) +{ + int i; /* student counter */ + int j; /* exam counter */ + int lowGrade = 100; /* initialize to highest possible grade */ + + /* loop through rows of grades */ + for ( i = 0; i < pupils; i++ ) { + + /* loop through columns of grades */ + for ( j = 0; j < tests; j++ ) { + + if ( grades[ i ][ j ] < lowGrade ) { + lowGrade = grades[ i ][ j ]; + } /* end if */ + + } /* end inner for */ + + } /* end outer for */ + + printf("Lowest grade: %d\n", lowGrade); + +} /* end function minimum */ + +/* Find the maximum grade */ +void maximum( const int grades[][ EXAMS ], int pupils, int tests ) +{ + int i; /* student counter */ + int j; /* exam counter */ + int highGrade = 0; /* initialize to lowest possible grade */ + + /* loop through rows of grades */ + for ( i = 0; i < pupils; i++ ) { + + /* loop through columns of grades */ + for ( j = 0; j < tests; j++ ) { + + if ( grades[ i ][ j ] > highGrade ) { + highGrade = grades[ i ][ j ]; + } /* end if */ + + } /* end inner for */ + + } /* end outer for */ + + printf("Highest grade: %d\n", highGrade); + +} /* end function maximum */ + +/* Determine the average grade for a particular student */ +void average( const int setOfGrades[][ EXAMS ], int pupils, int tests ) +{ + int i, j; /* exam counters */ + int total = 0; /* sum of test grades */ + + /* total all grades for one student */ + for ( i = 0; i < pupils; i++ ) { + for( j = 0; j < tests; j++) { + total += setOfGrades[ i ][ j ]; + } + + printf("The average grade for student %d is %.2f\n", + i, (double) total / j); + total = 0; + } /* end for */ + +} /* end function average */ + +/* Print the array */ +void printArray( const int grades[][ EXAMS ], int pupils, int tests ) +{ + int i; /* student counter */ + int j; /* exam counter */ + + printf( "The array is:\n" ); + + /* output column heads */ + printf( " [0] [1] [2] [3]" ); + + /* output grades in tabular format */ + for ( i = 0; i < pupils; i++ ) { + + /* output label for row */ + printf( "\nstudentGrades[%d] ", i ); + + /* output grades for one student */ + for ( j = 0; j < tests; j++ ) { + printf( "%-5d", grades[ i ][ j ] ); + } /* end inner for */ + + } /* end outer for */ + printf("\n"); + +} /* end function printArray */ + diff --git a/exercises/deitel/ch7/maze.c b/exercises/deitel/ch7/maze.c @@ -0,0 +1,217 @@ +/* Exercise 7.25 */ + +#include <stdio.h> +#include <stdlib.h> +#define SIZE 12 + +#define RIGHT 1 +#define DOWN 2 +#define LEFT 3 +#define UP 4 + +void mazeTraverse(char maze[][SIZE], int r, int c, int route); + +void pmaze(char maze[][SIZE]); + +int ahead(char maze[][SIZE], int *r, int *c, int route); +int toright(char maze[][SIZE], int r, int c, int route); +int chroute(int route, int nroute); + +int main(void) +{ + char maze[SIZE][SIZE] = { + { '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' }, + { '#', '.', '.', '.', '#', '.', '.', '.', '.', '.', '.', '#' }, + { '.', '.', '#', '.', '#', '.', '#', '#', '#', '#', '.', '#' }, + { '#', '#', '#', '.', '#', '.', '.', '.', '.', '#', '.', '#' }, + { '#', '.', '.', '.', '.', '#', '#', '#', '.', '#', '.', '.' }, + { '#', '#', '#', '#', '.', '#', '.', '#', '.', '#', '.', '#' }, + { '#', '.', '.', '#', '.', '#', '.', '#', '.', '#', '.', '#' }, + { '#', '#', '.', '#', '.', '#', '.', '#', '.', '#', '.', '#' }, + { '#', '.', '.', '.', '.', '.', '.', '.', '.', '#', '.', '#' }, + { '#', '#', '#', '#', '#', '#', '.', '#', '#', '#', '.', '#' }, + { '#', '.', '.', '.', '.', '.', '.', '#', '.', '.', '.', '#' }, + { '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' } + }; + + mazeTraverse(maze, 2, 0, RIGHT); + + return 0; +} /* E0F main */ + +/* Traverse a maze founding the exit, if exists */ +void mazeTraverse(char maze[][SIZE], int r, int c, int route) +{ + maze[r][c] = (maze[r][c] != 'x' && maze[r][c] != 'X') ? 'x' : 'X'; + printf("\n"); + pmaze(maze); + + if(c == SIZE - 1) { + return; + } + + if(ahead(maze, &r, &c, route)) { + if(toright(maze, r, c, route)) { + + /* A little fix */ + maze[r][c] = maze[r][c] == 'x' ? '.' : 'X'; + + route = chroute(route, LEFT); + } + } + else { + if(!toright(maze, r, c, route)) { + route = chroute(route, RIGHT); + } + } + + if(!c) return; + + mazeTraverse(maze, r, c, route); + + +} /* eof mazeTraverse() */ + +/* Print a maze */ +void pmaze(char maze[][SIZE]) +{ + int i, j; + + for(i = 0; i < SIZE; i++) { + for(j = 0; j < SIZE; j++) { + printf("%c ", maze[i][j]); + } + printf("\n"); + } + +} /* eof pmaze() */ + +/* Ehm.. go ahead :-) */ +int ahead(char maze[][SIZE], int *r, int *c, int route) +{ + switch(route) + { + case RIGHT: + if(maze[*r][*c + 1] == '#') + return 1; + else + ++*c; + break; + case DOWN: + if(maze[*r + 1][*c] == '#') + return 1; + else + ++*r; + break; + case LEFT: + if(maze[*r][*c - 1] == '#') + return 1; + else + --*c; + break; + case UP: + if(maze[*r - 1][*c] == '#') + return 1; + else + --*r; + break; + default: + printf("Where are you going?\n"); + exit(-1); + } + + return 0; +} /* eof ahead() */ + +/* Check if the wall is to the right side */ +int toright(char maze[][SIZE], int r, int c, int route) +{ + switch(route) + { + case RIGHT: + if(maze[r + 1][c] == '#') + return 1; + break; + case DOWN: + if(maze[r][c - 1] == '#') + return 1; + break; + case LEFT: + if(maze[r - 1][c] == '#') + return 1; + break; + case UP: + if(maze[r][c + 1] == '#') + return 1; + break; + default: + printf("What's your position?\n"); + exit(-1); + + } + + return 0; +} /* eof toright() */ + +/* Turn to left */ +int chroute(int route, int nroute) +{ + switch(route) { + case RIGHT: + if(nroute == RIGHT) + route = DOWN; + else if(nroute == DOWN) + route = LEFT; + else if(nroute == LEFT) + route = UP; + else if(nroute == UP) + ; /* don't change */ + else + route = 0; + break; + case DOWN: + if(nroute == RIGHT) + route = LEFT; + else if(nroute == DOWN) + route = UP; + else if(nroute == LEFT) + route = RIGHT; + else if(nroute == UP) + ; /* don't change */ + else + route = 0; + break; + case LEFT: + if(nroute == RIGHT) + route = UP; + else if(nroute == DOWN) + route = RIGHT; + else if(nroute == LEFT) + route = DOWN; + else if(nroute == UP) + ; /* don't change */ + else + route = 0; + break; + case UP: + if(nroute == RIGHT || nroute == UP || + nroute == LEFT || nroute == DOWN) { + route = nroute; + } + else + route = 0; + break; + default: + printf("Where do you want to go?\n"); + exit(-1); + } + + + if(!route) { + printf("ERROR: invalid route: %d\n", nroute); + return -1; + } + + return route; +} /* eof chroute() */ + diff --git a/exercises/deitel/ch7/maze2.c b/exercises/deitel/ch7/maze2.c @@ -0,0 +1,266 @@ +/* Exercise 7.26 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define SIZE 12 +#define LOOPS 100 + +#define RIGHT 1 +#define DOWN 2 +#define LEFT 3 +#define UP 4 + +void mazeTraverse(char maze[][SIZE], int r, int c, int ret[], int route); +void mazeGenerator(char maze[][SIZE], int ret[]); + +void pmaze(char maze[][SIZE]); + +void go(char maze[][SIZE], int *r, int *c, int route); + +int ahead(char maze[][SIZE], int *r, int *c, int route, int check); +int toright(char maze[][SIZE], int r, int c, int route); +int chroute(int route, int nroute); + +int main(void) +{ + char maze[SIZE][SIZE]; + int ret[4] = { 0 }, route; + + srand( time(NULL) ); + + mazeGenerator(maze, ret); + + /* Set the route */ + if(!ret[0]) route = DOWN; + else if(ret[0] == SIZE - 1) route = UP; + else if(!ret[1]) route = RIGHT; + else if(ret[1] == SIZE - 1) route = LEFT; + + mazeTraverse(maze, ret[0], ret[1], ret, route); + + return 0; +} /* E0F main */ + +/* Generate a maze and put it to the "maze" matrix */ +void mazeGenerator(char maze[][SIZE], int ret[]) +{ + int row, col, i = 0; + + /* Inizialize the maze */ + for(row = 0; row < SIZE; row++) + for(col = 0; col < SIZE; col++) + maze[row][col] = '#'; + + + row = rand() % SIZE; + col = !row || row == SIZE-1 ? 1 + rand()%(SIZE-2) : rand()%2 ? SIZE-1 : 0; + + ret[0] = row; + ret[1] = col; + + if(!ret[1] || ret[1] == SIZE - 1) { + ret[2] = rand() % 2 ? 0 : SIZE - 1; + ret[3] = 1 + rand() % 10; + } + else { + ret[2] = 1 + rand() % 10; + ret[3] = rand() % 2 ? 0 : SIZE - 1; + } + + maze[ret[0]][ret[1]] = '.'; /* Start point */ + maze[ret[2]][ret[3]] = 'E'; /* End point */ + + /* Create the path */ + while(i++ < LOOPS) { + row = 1 + rand() % 10; + col = 1 + rand() % 10; + + maze[row][col] = '.'; + } + +} /* eof mazeGenerator() */ + +/* Traverse a maze founding the exit, if exists */ +void mazeTraverse(char maze[][SIZE], int r, int c, int ret[], int route) +{ + maze[r][c] = (maze[r][c] != 'x' && maze[r][c] != 'X') ? 'x' : 'X'; + printf("\n"); + + pmaze(maze); + + + if(ahead(maze, &r, &c, route, 1)) { + if(toright(maze, r, c, route)) { + + /* A little fix */ + maze[r][c] = maze[r][c] == 'x' ? '.' : 'X'; + + route = chroute(route, LEFT); + } + } + else { + if(!toright(maze, r, c, route)) { + route = chroute(route, RIGHT); + } + } + + if(r == ret[0] && c == ret[1]) { + printf("Closed maze!\n"); + return; + } + + if(r == ret[2] && c == ret[3]) { + printf("Exit found!\n"); + return; + } + else + mazeTraverse(maze,r, c, ret, route); + + +} /* eof mazeTraverse() */ + +/* Print a maze */ +void pmaze(char maze[][SIZE]) +{ + int i, j; + + for(i = 0; i < SIZE; i++) { + for(j = 0; j < SIZE; j++) { + printf("%c ", maze[i][j]); + } + printf("\n"); + } + +} /* eof pmaze() */ + +/* Ehm.. go ahead :-) */ +int ahead(char maze[][SIZE], int *r, int *c, int route, int check) +{ + switch(route) + { + case RIGHT: + if(maze[*r][*c + 1] == '#' && check) + return 1; + else + ++*c; + break; + case DOWN: + if(maze[*r + 1][*c] == '#' && check) + return 1; + else + ++*r; + break; + case LEFT: + if(maze[*r][*c - 1] == '#' && check) + return 1; + else + --*c; + break; + case UP: + if(maze[*r - 1][*c] == '#' && check) + return 1; + else + --*r; + break; + default: + printf("Where are you going?\n"); + exit(-1); + } + + return 0; +} /* eof ahead() */ + +/* Check if the wall is to the right side */ +int toright(char maze[][SIZE], int r, int c, int route) +{ + switch(route) + { + case RIGHT: + if(maze[r + 1][c] == '#') + return 1; + break; + case DOWN: + if(maze[r][c - 1] == '#') + return 1; + break; + case LEFT: + if(maze[r - 1][c] == '#') + return 1; + break; + case UP: + if(maze[r][c + 1] == '#') + return 1; + break; + default: + printf("What's your position?\n"); + exit(-1); + + } + + return 0; +} /* eof toright() */ + +/* Turn to left */ +int chroute(int route, int nroute) +{ + switch(route) { + case RIGHT: + if(nroute == RIGHT) + route = DOWN; + else if(nroute == DOWN) + route = LEFT; + else if(nroute == LEFT) + route = UP; + else if(nroute == UP) + ; /* don't change */ + else + route = 0; + break; + case DOWN: + if(nroute == RIGHT) + route = LEFT; + else if(nroute == DOWN) + route = UP; + else if(nroute == LEFT) + route = RIGHT; + else if(nroute == UP) + ; /* don't change */ + else + route = 0; + break; + case LEFT: + if(nroute == RIGHT) + route = UP; + else if(nroute == DOWN) + route = RIGHT; + else if(nroute == LEFT) + route = DOWN; + else if(nroute == UP) + ; /* don't change */ + else + route = 0; + break; + case UP: + if(nroute == RIGHT || nroute == UP || + nroute == LEFT || nroute == DOWN) { + route = nroute; + } + else + route = 0; + break; + default: + printf("Where do you want to go?\n"); + exit(-1); + } + + + if(!route) { + printf("ERROR: invalid route: %d\n", nroute); + return -1; + } + + return route; +} /* eof chroute() */ + diff --git a/exercises/deitel/ch7/maze3.c b/exercises/deitel/ch7/maze3.c @@ -0,0 +1,271 @@ +/* Exercise 7.27 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define ROWS 19 +#define COLS 19 + +#define LOOPS ROWS * COLS + +#define RIGHT 1 +#define DOWN 2 +#define LEFT 3 +#define UP 4 + +void mazeTraverse(char maze[][COLS], int r, int c, int ret[], int route); +void mazeGenerator(char maze[][COLS], int ret[]); + +void pmaze(char maze[][COLS]); + +void go(char maze[][COLS], int *r, int *c, int route); + +int ahead(char maze[][COLS], int *r, int *c, int route, int check); +int toright(char maze[][COLS], int r, int c, int route); +int chroute(int route, int nroute); + +int main(void) +{ + char maze[ROWS][COLS]; + int ret[4] = { 0 }, route; + + srand( time(NULL) ); + + mazeGenerator(maze, ret); + + /* Set the route */ + if(!ret[0]) route = DOWN; + else if(ret[0] == ROWS - 1) route = UP; + else if(!ret[1]) route = RIGHT; + else if(ret[1] == COLS - 1) route = LEFT; + + mazeTraverse(maze, ret[0], ret[1], ret, route); + + return 0; +} /* E0F main */ + +/* Generate a maze and put it to the "maze" matrix */ +void mazeGenerator(char maze[][COLS], int ret[]) +{ + int row, col, i = 0; + + /* Inizialize the maze */ + for(row = 0; row < ROWS; row++) + for(col = 0; col < COLS; col++) + maze[row][col] = '#'; + + row = rand() % ROWS; + col = !row || row == ROWS-1 ? 1 + rand()%(COLS-2) : rand()%2 ? COLS-1 : 0; + + ret[0] = row; + ret[1] = col; + + if(!ret[1] || ret[1] == COLS - 1) { + ret[2] = rand() % 2 ? 0 : ROWS - 1; + ret[3] = 1 + rand() % (COLS - 2); + } + else { + ret[2] = 1 + rand() % (ROWS - 2); + ret[3] = rand() % 2 ? 0 : COLS - 1; + } + + maze[ret[0]][ret[1]] = '.'; /* Start point */ + maze[ret[2]][ret[3]] = 'E'; /* End point */ + + /* Create the path */ + while(i++ < LOOPS) { + row = 1 + rand() % (ROWS - 2); + col = 1 + rand() % (COLS - 2); + + maze[row][col] = '.'; + } + +} /* eof mazeGenerator() */ + +/* Traverse a maze founding the exit, if exists */ +void mazeTraverse(char maze[][COLS], int r, int c, int ret[], int route) +{ + static int print = 1; + + maze[r][c] = (maze[r][c] != 'x' && maze[r][c] != 'X') ? 'x' : 'X'; + + if(print) { /* Don't show the route changes */ + printf("\n"); + pmaze(maze); + } + + if(ahead(maze, &r, &c, route, 1)) { + if(toright(maze, r, c, route)) { + + /* A little fix */ + maze[r][c] = maze[r][c] == 'x' ? '.' : 'X'; + + route = chroute(route, LEFT); + print = 0; + } + else print = 1; + } + else { + if(!toright(maze, r, c, route)) { + route = chroute(route, RIGHT); + } + else print = 1; + } + + if(r == ret[0] && c == ret[1]) { + printf("Closed maze!\n"); + return; + } + else if(r == ret[2] && c == ret[3]) { + printf("Exit found: row %d, col %d.\n", ret[2], ret[3]); + return; + } + else + mazeTraverse(maze, r, c, ret, route); + +} /* eof mazeTraverse() */ + +/* Print a maze */ +void pmaze(char maze[][COLS]) +{ + int i, j; + + for(i = 0; i < ROWS; i++) { + for(j = 0; j < COLS; j++) { + printf("%c ", maze[i][j]); + } + printf("\n"); + } + +} /* eof pmaze() */ + +/* Ehm.. go ahead :-) */ +int ahead(char maze[][COLS], int *r, int *c, int route, int check) +{ + switch(route) + { + case RIGHT: + if(maze[*r][*c + 1] == '#' && check) + return 1; + else + ++*c; + break; + case DOWN: + if(maze[*r + 1][*c] == '#' && check) + return 1; + else + ++*r; + break; + case LEFT: + if(maze[*r][*c - 1] == '#' && check) + return 1; + else + --*c; + break; + case UP: + if(maze[*r - 1][*c] == '#' && check) + return 1; + else + --*r; + break; + default: + printf("Where are you going?\n"); + exit(-1); + } + + return 0; +} /* eof ahead() */ + +/* Check if the wall is to the right side */ +int toright(char maze[][COLS], int r, int c, int route) +{ + switch(route) + { + case RIGHT: + if(maze[r + 1][c] == '#') + return 1; + break; + case DOWN: + if(maze[r][c - 1] == '#') + return 1; + break; + case LEFT: + if(maze[r - 1][c] == '#') + return 1; + break; + case UP: + if(maze[r][c + 1] == '#') + return 1; + break; + default: + printf("What's your position?\n"); + exit(-1); + + } + + return 0; +} /* eof toright() */ + +/* Turn to left */ +int chroute(int route, int nroute) +{ + switch(route) { + case RIGHT: + if(nroute == RIGHT) + route = DOWN; + else if(nroute == DOWN) + route = LEFT; + else if(nroute == LEFT) + route = UP; + else if(nroute == UP) + ; /* don't change */ + else + route = 0; + break; + case DOWN: + if(nroute == RIGHT) + route = LEFT; + else if(nroute == DOWN) + route = UP; + else if(nroute == LEFT) + route = RIGHT; + else if(nroute == UP) + ; /* don't change */ + else + route = 0; + break; + case LEFT: + if(nroute == RIGHT) + route = UP; + else if(nroute == DOWN) + route = RIGHT; + else if(nroute == LEFT) + route = DOWN; + else if(nroute == UP) + ; /* don't change */ + else + route = 0; + break; + case UP: + if(nroute == RIGHT || nroute == UP || + nroute == LEFT || nroute == DOWN) { + route = nroute; + } + else + route = 0; + break; + default: + printf("Where do you want to go?\n"); + exit(-1); + } + + + if(!route) { + printf("ERROR: invalid route: %d\n", nroute); + return -1; + } + + return route; +} /* eof chroute() */ + diff --git a/exercises/deitel/ch7/poker.c b/exercises/deitel/ch7/poker.c @@ -0,0 +1,670 @@ +/* Exercise 7.14 */ + +/* Fig. 7.24: fig07_24.c + Card shuffling dealing program */ +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define CARDS 5 +#define DECK 26 +#define PLAYERS 2 + +/* Points setting * + * NOTE: the points *must* have an offset >= 15 and P_PAIR + * must should be >= 15 too to works properly. Else, + * Else, the game will sh0w only INVALID results and + * wrong winners. + */ +#define OFFSET 15 + +/* I'll tweak these, maybe.. a day :-) */ +#define P_PAIR OFFSET +#define P_DOUBLE P_PAIR + OFFSET +#define P_TRIS P_DOUBLE + OFFSET +#define P_SCALE P_TRIS + OFFSET +#define P_FULL P_SCALE + OFFSET +#define P_POKER P_FULL + OFFSET +#define P_COLOR P_POKER + OFFSET +#define P_SFLUSH P_COLOR + OFFSET +#define P_RFLUSH P_SFLUSH + OFFSET + +/* prototypes */ +void shuffle( int wDeck[][ 13 ] ); + +void deal( int wDeck[][ 13 ], const char *wFace[], const char *wSuit[], + int cards[][CARDS][2], int player, int wCards, int show); + +int getp(int cards[][CARDS][2], int player, const char *wFace[], + const char *wSuit[], int n_cards, int *r_suit, int type[]); + +void order(int a[][CARDS][2], int p, int size); +void rswap(int *a, int *b); + +int chcs(int cards[][CARDS][2], int player, int type[], const char *wFace[], + const char *wSuit[], int wDeck[][13], int n_cards); + +int main(void) +{ + int i, type[1 + PLAYERS], winner[3] = { 0 }, points[1 + PLAYERS] = { 0 }; + int p[1 + PLAYERS][2] = { { 0 } }; + int cards[1 + PLAYERS][CARDS][2] = { { { 0 } } }; + + /* initialize suit array */ + const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; + + /* initialize face array */ + const char *face[ 13 ] = + { "Ace", "Deuce", "Three", "Four", + "Five", "Six", "Seven", "Eight", + "Nine", "Ten", "Jack", "Queen", "King" }; + + /* initialize deck array */ + int deck[ 4 ][ 13 ] = { { 0 } }; + + srand( time( 0 ) ); /* seed random-number generator */ + + shuffle( deck ); + + /* S t a r t */ + printf("GaMe STaRTeD!\n\n"); + printf("Deck: %d\nCards for player: %d\nNumber of players: %d\n\n\n", + DECK, CARDS, PLAYERS); + + for(i = 0; i < PLAYERS + 1; i++) { + if(!i) + printf("*** Computer is playing..\n"); + else + printf("*** Player %d is playing..\n", i); + + printf("-----------------------------------------\n"); + deal( deck, face, suit, cards, i, CARDS, !i ? i : 1); + + printf("\n\n"); + + /* p[i][0] == points + * p[i][1] == suit of highest card (whitin the highest kind) + * i == the player + * p[0][?] == the computer + */ + p[i][0] = getp(cards, i, face, suit, CARDS, &p[i][1], type); + + printf("\nScore: %d ", p[i][0]); + if(i) printf("(suit points reserved: %d)", 4 - p[i][1]); + + printf("\n"); + printf("-----------------------------------------\n"); + + /* so */ + points[i] = p[i][0] - p[i][1]; /* points - seed(0 highest, 3 lowest) */ + printf("\n\n"); + } + + /* Changes */ + + /* Change the cards, if needed */ + if( chcs(cards, 0, type, face, suit, deck, CARDS) ) { + /* If cards are changed */ + p[0][0] = getp(cards, 0, face, suit, CARDS, &p[0][1], type); + printf("\n"); + } + + /* F i n i s h */ + + /* Check the winner and print the classifies */ + for(i = 0; i < PLAYERS + 1; i++) { + if(p[i][0] > winner[0]) { + winner[0] = p[i][0]; + winner[1] = p[i][1]; + winner[3] = i; + } + else if(p[i][0] == winner[0]) { /* Pair: check the suit */ + if(p[i][1] < winner[1]) { + winner[0] = p[i][0]; + winner[1] = p[i][1]; + winner[3] = i; + } + } + } /* end for (i) */ + + printf("\n\tC l a s s i f i e s\n\n"); + printf("%16s%9s\n", "Player", "Points"); + printf("%16s%9d\n", "PC", p[0][0]); + for(i = 1; i < PLAYERS + 1; i++) { + printf("%16d%9d\n", i, p[i][0]); + } + printf("\n"); + + if(!winner[3]) + printf("* Computer won with %d points.\n", winner[0]); + else + printf("* Player %d won with %d points.\n", winner[3], winner[0]); + + printf("\n"); + return 0; /* indicates successful termination */ + +} /* end main */ + +/* shuffle cards in deck */ +void shuffle( int wDeck[][ 13 ] ) +{ + int row; /* row number */ + int column; /* column number */ + int card; /* counter */ + + /* for each of the 52 cards, choose slot of deck randomly */ + for ( card = 1; card <= DECK; card++ ) { + + /* choose new random location until unoccupied slot found */ + do { + row = rand() % 4; + column = rand() % 13; + } while( wDeck[ row ][ column ] != 0 ); /* end do...while */ + + /* place card number in chosen slot of deck */ + wDeck[ row ][ column ] = card; + } /* end for */ + +} /* end function shuffle */ + +/* deal cards in deck */ +void deal( int wDeck[][ 13 ], const char *wFace[], const char *wSuit[], + int cards[][CARDS][2], int player, int wCards, int show) +{ + int card; /* card counter */ + int row; /* row counter */ + int column; /* column counter */ + int i = 0; + + if(show == 2) + printf("==> Computer is changing cards..\n\n"); + + /* deal each of the 52 cards */ + for ( card = 1; card <= DECK; card++ ) { + /* loop through rows of wDeck */ + for ( row = 0; row <= 3; row++ ) { + + /* loop through columns of wDeck for current row */ + for ( column = 0; column <= 12; column++ ) { + /* if slot contains current card, display card */ + if ( wDeck[ row ][ column ] == card ) { + + if(show == 2) + printf( "%5s of %-8s => ", wFace[cards[player][i][0]], + wSuit[cards[player][i][1]]); + + cards[player][i][0] = column; + cards[player][i][1] = row; + + if(!show) + printf("%15s", " HIDDEN "); + else + printf( "%5s of %-8s", wFace[ column ], wSuit[ row ]); + + ++i; + + if(show != 2) printf("%c", !(card % 2) ? '\n' : '\t'); + else printf("\n"); + + wDeck[row][column] = 0; + + /* dealing only "wCards" cards */ + if(i == wCards) { + printf("\n"); + return; + } + + } /* end if */ + + } /* end for */ + + } /* end for */ + + } /* end for */ + +} /* end function deal */ + +/* Get the points of a player */ +int getp(int cards[][CARDS][2], int player, const char *wFace[], + const char *wSuit[], int n_cards, int *r_suit, int type[]) +{ + int i, points; + int scale = 0, n; + int o[13][2] = { { 0 } }; /* occurrences */ + + + int kind = 0, face, suit; + /* 0 = nothing + * 1 = Pair + * 2 = Double + * 3 = Tris + * 4 = scale + * 5 = Full + * 6 = Poker + * 7 = Color + * 8 = straight flush + * 9 = royal flush + */ + + /* Inizitialize the o[0,12][1] to 4. Note that 4 is + * a value (random) greather then highest suit (3). */ + for(i = 0; i < 13; i++) + o[i][1] = 4; + + /* count the occurrences of each card's face and + * save to the current index the highest suit */ + for(i = 0; i < n_cards; i++) { + ++o[cards[player][i][0]][0]; + + /* store the index of the highest suit */ + if(o[cards[player][i][0]][1] > cards[player][i][1]) + o[cards[player][i][0]][1] = cards[player][i][1]; + + } + + /* Ok, now don't forget this: + * + * o[i][0] == the occurrences + * o[i][1] == the suit + * i == the face + */ + + /* check if there is a pair/double/tris/full/poker */ + for(i = 0; i < 13; i++) { + switch(o[i][0]) { + case 2: + /* if this is the 1st pair */ + if(!kind) /* is a pair */ + kind = 1; + + /* else could be a double */ + else if(kind == 1) + kind = 2; + + else /* else is full */ + kind = 3; + + break; + case 3: + /* If is the current game is a pair */ + if(kind == 1) + kind = 5; /* then become "full" */ + + else /* else is tris */ + kind = 3; + + break; + case 4: + /* Oh, this is Poker! :-) */ + kind = 6; + break; + default: + /* !o[i][0] */ + ; + + } /* end switch (o[i]) */ + + if( o[i][0] > 1 && (kind != 2 || (kind == 2 && face < i)) ) { + /* If is double and the current pair is not greather + * then previous, then i don't store its face/suit */ + + face = i; + suit = o[i][1]; + } + + } /* end for (i) */ + + + /* Here i've checked: pair, double, tris, full and poker. + * "face" and "suit" contains the highest value of the current + * "kind". The suit is required if there are an "equal" result + * for change (increment or decrement) the current value of + * each one basing on the suit. + * Missing: scale, color and "all cards are not equals". */ + + + /* if all cards are different store the highest of these */ + if(kind == 0 && !scale) { + for(i = 0, face = -1; i < n_cards; i++) { + + /* search the highest */ + if((!face ? 13 : face) < (!cards[player][i][0] ? 13 : + cards[player][i][0]) ) { + face = cards[player][i][0]; + suit = cards[player][i][1]; + } + + /* if are equal, store the suit */ + else if(face == cards[player][i][0]) { + if(suit < cards[player][i][1]) { + suit = cards[player][i][1]; + } + } + + } + } + + /* check the color */ + for(i = 0, n = 4; i < n_cards; i++) { + if(! (n == 4) ) { + if(cards[player][i][1] != n) + n = - 1; + } + else + n = cards[player][i][1]; + } + if(n != -1) /* live enjoy: life's colored :-) */ + kind = 7; + + /* check the scale / *_flush */ + order(cards, player, n_cards); + + for(i = n = 1; i < n_cards; i++) { + if(cards[i - 1][0] + 1 != cards[i][0]) { + n = 0; + break; + } + } + if(n) { /* This is scale / *_flush */ + + if(kind == 7) { /* *_flush */ + if(face == 0) { /* royal flush */ + kind = 9; + } + + else { /* straight flush */ + kind = 8; + } + } + else { /* just scale */ + kind = 4; + } + } + + *r_suit = suit; + type[player] = kind; + + /* Print the kind of game and assign the points */ + switch(kind) { + case 0: /* Nothing */ + printf("All cards are differents!\n" + "You could win with the %s of %s\n", + wFace[face], wSuit[suit]); + + points = face; + break; + case 1: /* Pair */ + printf("Oh, it is a pair of %ss!\n", wFace[face]); + + points = P_PAIR + face; + break; + case 2: /* Double */ + printf("Double to %ss\n", wFace[face]); + + points = P_DOUBLE + face; + break; + case 3: /* Tris */ + printf("This is tris of %ss!\n", wFace[face]); + + points = P_TRIS + face; + break; + case 4: /* Scale */ + printf("Yeah, you have done a scale to %s\n", wFace[face]); + + points = P_SCALE + face; + break; + case 5: /* Full */ + printf("*** FULL of %ss!\n", wFace[face]); + + points = P_FULL + face; + break; + case 6: /* Poker */ + printf("Wow, it's Poker of %ss!\n", wFace[face]); + + points = P_POKER + face; + break; + case 7: /* Color */ + printf("%d points of color (%s)\n", P_COLOR, wSuit[suit]); + + points = P_COLOR + face; + break; + case 8: /* Straight flush */ + printf("* Straight flush to %s*\n", wFace[face]); + + points = P_SFLUSH + face; + break; + case 9: /* Royal flush */ + printf("*| Royal Flush (%s) |*\n", wSuit[suit]); + + points = P_RFLUSH + face; + break; + default: /* (?) */ + printf("### error in function getp()\n"); + exit(-1); + + } /* end switch(kind) */ + + if(!face) points += 13; /* add the Ace's points */ + + return points + 1; /* + 1 == [1,13] rather then [0,12] */ +} /* eof getp() */ + +/* Order an array in descending mode */ +void order(int a[][CARDS][2], int p, int size) +{ + int i, hold; + + for(i = 1; i < size; i++) { + if(a[p][i - 1][0] > a[p][i][0]) { + /* swap the face */ + hold = a[p][i][0]; + a[p][i][0] = a[p][i - 1][0]; + a[p][i - 1][0] = hold; + + /* swap the suit */ + hold = a[p][i][1]; + a[p][i][1] = a[p][i - 1][1]; + a[p][i - 1][1] = hold; + } + } /* end for (i) */ + +} /* eof order() */ + +/* Change the cards if needed, else return 0 */ +int chcs(int cards[][CARDS][2], int player, int type[], const char *wFace[], + const char *wSuit[], int wDeck[][13], int n_cards) +{ + int i, ret; + + switch(type[player]) { + case 9: /* Royal flush */ + case 8: /* Straight flush */ + + ret = 0; + break; + case 7: /* Color */ + /* Try to do a Royal flush */ + ret = 0; + + for(i = 0; i < n_cards; i++) { + if(cards[player][i][0] + 1 == cards[player][i + 1][0]) { + ++ret; + } + } + + /* if miss only a card to Royal Flush */ + if(ret == 3) { + /* risk: change one card */ + + if(cards[player][0][0] + 1 == cards[player][1][0]) { + rswap(&cards[player][0][0], &cards[player][n_cards - 1][0]); + rswap(&cards[player][0][1], &cards[player][n_cards - 1][1]); + } + + ret = 1; + } + else /* do nothing */ + ret = 0; + + break; + + case 5: /* Full */ + case 4: /* Scale */ + + /* Stay */ + ret = 0; + + break; + + case 6: /* Poker */ + + /* cards is ordered so the "intruder" + * have to be at begin or at end */ + + if(cards[n_cards - 1][0] != cards[2][0]) { + + /* copy [0] to [n_cards - 1] */ + + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][0][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][0][1]); + } + + /* else cards[player][n_cards - 1][0] <=> cards[player][2][0] */ + + /* and insert a new card on [0] */ + deal( wDeck, wFace, wSuit, cards, player, 1, 2); + + ret = 1; + break; + case 2: /* Double */ + /* change 1 card */ + + /* cards is ordered so the "intruder" + * have to be at begin or at end */ + + if(cards[player][n_cards - 1][0] != cards[player][5][1] && + cards[player][n_cards - 1][0] != cards[player][3][0]) { + + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][0][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][0][1]); + } + + /* else cards[0][0] is already free */ + deal( wDeck, wFace, wSuit, cards, player, 1, 2); + + ret = 1; + break; + case 3: /* Tris */ + /* change 2 cards */ + + /* cards is ordered so the "intruderS" + * DON'T have to be at middle */ + + for(i = 0; i < n_cards / 2; i++) { + if(cards[i][0] == cards[2][0]) + break; + } + + if(!i) { + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][0][0]); + rswap(&cards[player][n_cards - 2][0], &cards[player][1][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][0][1]); + rswap(&cards[player][n_cards - 2][1], &cards[player][1][1]); + } + else if(i == 1) { + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][2][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][2][1]); + } + + /* insert 2 cards on [0] and [1] */ + deal( wDeck, wFace, wSuit, cards, player, 2, 2); + + ret = 2; + break; + case 1: /* Pair */ + /* change 3 cards */ + + for(i = 0; i < n_cards; i++) { + if(cards[player][i][0] == cards[player][i + 1][0]) + break; + } + + + /* The face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][i][0]); + rswap(&cards[player][n_cards - 2][0], &cards[player][i+1][0]); + + /* The suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][i][1]); + rswap(&cards[player][n_cards - 2][1], &cards[player][i+1][1]); + + deal( wDeck, wFace, wSuit, cards, player, 3, 2); + + ret = 3; + break; + case 0: /* Nothing */ + /* Change all cards */ + ret = 0; + + /* If i have a Jack, a Queen, a King or an Ace, hold it */ + for(i = 0; i < n_cards; i++) { + /* 9 == Ten */ + if( (!cards[player][i][0] ? 13 : cards[player][i][0]) > 9 && + (!cards[player][i][0] ? 13 : cards[player][i][0]) > ret) { + ret = (!cards[player][i][0] ? 13 : cards[player][i][0]); + + rswap(&cards[player][0][0], &cards[player][i][0]); + rswap(&cards[player][0][1], &cards[player][i][1]); + } + } + rswap(&cards[player][0][0], &cards[player][n_cards - 1][0]); + rswap(&cards[player][0][1], &cards[player][n_cards - 1][1]); + + /* else change all cards */ + + if(!ret) { + deal( wDeck, wFace, wSuit, cards, player, n_cards, 2); + ret = n_cards; + } + else { + deal( wDeck, wFace, wSuit, cards, player, n_cards - 1, 2); + ret = n_cards - 1; + } + + break; + default: /* (?) */ + printf("### error in function chcs()\n"); + exit(-1); + + } /* end switch (type[player]) */ + + + if(ret) + printf("Computer has changed %d %s.\n\n", + ret, ret > 1 ? "cards" : "card" ); + + return ret; +} /* eof chcs() */ + +/* Swap two variable for reference */ +void rswap(int *a, int *b) +{ + int hold; + + hold = *a; + *a = *b; + *b = hold; +} /* eof rswap() */ + diff --git a/exercises/deitel/ch7/poker2.c b/exercises/deitel/ch7/poker2.c @@ -0,0 +1,903 @@ +/* exercise 7.15 */ + +/* Fig. 7.24: fig07_24.c + Card shuffling dealing program */ +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define CARDS 5 +#define DECK 26 + +/* Points setting * + * NOTE: the points *must* have an offset >= 15 and P_PAIR + * must should be >= 15 too to works properly. Else, + * Else, the game will sh0w only INVALID results and + * wrong winners. + */ +#define OFFSET 15 + +/* I'll tweak these, maybe.. a day :-) */ +#define P_PAIR OFFSET +#define P_DOUBLE P_PAIR + OFFSET +#define P_TRIS P_DOUBLE + OFFSET +#define P_SCALE P_TRIS + OFFSET +#define P_FULL P_SCALE + OFFSET +#define P_POKER P_FULL + OFFSET +#define P_COLOR P_POKER + OFFSET +#define P_SFLUSH P_COLOR + OFFSET +#define P_RFLUSH P_SFLUSH + OFFSET + +/* prototypes */ +void shuffle( int wDeck[][ 13 ] ); + +void deal( int wDeck[][ 13 ], const char *wFace[], const char *wSuit[], + int cards[][CARDS][2], int player, int wCards, int show); + +int getp(int cards[][CARDS][2], int player, const char *wFace[], + const char *wSuit[], int n_cards, int *r_suit, int *r_face, + int type[], int show); + +void order(int a[][CARDS][2], int p, int size); +void rswap(int *a, int *b); + +int chcs(int cards[][CARDS][2], int player, int type[], const char *wFace[], + const char *wSuit[], int wDeck[][13], int n_cards); + +int chch(int cards[][CARDS][2], int n_cards, int player, int wDeck[][13], + const char *wFace[], const char *wSuit[], int kind, + int r_face, int r_suit, int show); + +void p_points(int kind, int face, int suit, + const char *wFace[], const char *wSuit[], int show); + +int main(void) +{ + int i, type[2], winner[3] = { 0 }, points[2] = { 0 }; + int p[2][2] = { { 0 } }; + int cards[2][CARDS][2] = { { { 0 } } }; + int c; /* change tracer */ + int theface[2], thesuit; + + /* initialize suit array */ + const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; + + /* initialize face array */ + const char *face[ 13 ] = + { "Ace", "Deuce", "Three", "Four", + "Five", "Six", "Seven", "Eight", + "Nine", "Ten", "Jack", "Queen", "King" }; + + /* initialize deck array */ + int deck[ 4 ][ 13 ] = { { 0 } }; + + if(CARDS > DECK / 2) { + printf("Too many cards: redefine the CARDS constant.\n"); + exit(-1); + } + + srand( time( 0 ) ); /* seed random-number generator */ + + shuffle( deck ); + + /* S t a r t */ + printf("GaMe STaRTeD!\n\n" + "Deck: %d\nCards for player: %d\n\n\n", DECK, CARDS); + + for(i = 0; i < 2; i++) { + printf("*** "); + if(!i) + printf("Computer"); + else + printf("Player %d", i); + + printf("'s cards..\n"); + + printf("-----------------------------------------\n\n"); + + deal( deck, face, suit, cards, i, CARDS, !i ? 0 : 1 ); + + /* p[i][0] == points + * p[i][1] == suit of highest card (whitin the highest kind) + * i == the player + * p[0][?] == the computer + */ + if(i) printf("\n"); + p[i][0] = getp(cards, i, face, suit, CARDS, &p[i][1], + &theface[i], &type[i], i); + + if(i) { + thesuit = p[1][1]; /* take the user's suit */ + + printf("\n: Score: %d ", p[i][0]); + printf("(suit points reserved: %d)", 4 - p[i][1]); + } + + printf("\n-----------------------------------------\n"); + + /* so */ + points[i] = p[i][0] - p[i][1]; /* points - seed(0 highest, 3 lowest) */ + printf("\n\n"); + } + + printf("Now is time to change the cards..\n"); + printf("Press a key to continue.\n"); + getchar(); + + /* Player change the cards */ + c = chch(cards, CARDS, 1, deck, face, suit, type[1], + theface[1], thesuit, 1); + if(c) { + printf("Player 1 has changed %d %s.\n\n", c, c > 1 ? "cards" : "card" ); + + p[1][0] = getp(cards, 1, face, suit, CARDS, &p[1][1], + &theface[1], &type[1], 1); + } + + /* Computer change the cards */ + c = chcs(cards, 0, &type[0], face, suit, deck, CARDS); + if(c) { + printf("Computer has changed %d %s.\n\n", c, c > 1 ? "cards" : "card" ); + + p[0][0] = getp(cards, 0, face, suit, CARDS, + &p[0][1], &theface[0], &type[0], 0); + } + + printf("\n\n"); + + + /* F i n i s h */ + + /* Check the winner and print the classifies */ + for(i = 0; i < 2; i++) { + if(p[i][0] > winner[0]) { + winner[0] = p[i][0]; + winner[1] = p[i][1]; + winner[3] = i; + } + else if(p[i][0] == winner[0]) { /* Pair: check the suit */ + if(p[i][1] < winner[1]) { + winner[0] = p[i][0]; + winner[1] = p[i][1]; + winner[3] = i; + } + } + } /* end for (i) */ + + /* Show the cards */ + for(i = 1; i >= 0; i--) { + if(!i) + printf("Computer"); + else + printf("Player 1"); + printf("'s cards:\n"); + + printf("-------------------------------"); + printf("-----------------------------\n"); + + for(c = 0; c < CARDS; c++) { + printf("%15s of %-8s", face[cards[i][c][0]], suit[cards[i][c][1]]); + printf("%c", !(c % 2) ? '\n' : '\t'); + } + + printf("\n\n"); + p_points(type[i], theface[i], p[i][1], face, suit, 1); + + printf("\n\tTotal points: %d (suit %d)\n", p[i][0], p[i][1]); + printf("-------------------------------"); + printf("-----------------------------\n"); + printf("\n\n"); + } + + + printf("\n\tC l a s s i f i e s\n\n"); + + printf("%16s%9s\n", "Player", "Points"); + printf("%16s%9d\n", "PC", p[0][0]); + printf("%16d%9d\n", 1, p[1][0]); + + printf("\n"); + + if(!winner[3]) + printf("* Computer won with %d points.\n", winner[0]); + else + printf("* Player %d won with %d points.\n", winner[3], winner[0]); + + printf("\n"); + return 0; /* indicates successful termination */ + +} /* end main */ + +/* shuffle cards in deck */ +void shuffle( int wDeck[][ 13 ] ) +{ + int row; /* row number */ + int column; /* column number */ + int card; /* counter */ + + /* for each of the 52 cards, choose slot of deck randomly */ + for ( card = 1; card <= DECK; card++ ) { + + /* choose new random location until unoccupied slot found */ + do { + row = rand() % 4; + column = rand() % 13; + } while( wDeck[ row ][ column ] != 0 ); /* end do...while */ + + /* place card number in chosen slot of deck */ + wDeck[ row ][ column ] = card; + } /* end for */ + +} /* end function shuffle */ + +/* deal cards in deck */ +void deal( int wDeck[][ 13 ], const char *wFace[], const char *wSuit[], + int cards[][CARDS][2], int player, int wCards, int show) +{ + int card; /* card counter */ + int row; /* row counter */ + int column; /* column counter */ + int i = 0; + + if(show == 2) { + printf("\n===> "); + if(!player) + printf("Computer"); + else + printf("Player %d", player); + + printf(" is changing cards..\n\n"); + } + + /* deal each of the 52 cards */ + for ( card = 1; card <= DECK; card++ ) { + /* loop through rows of wDeck */ + for ( row = 0; row <= 3; row++ ) { + + /* loop through columns of wDeck for current row */ + for ( column = 0; column <= 12; column++ ) { + /* if slot contains current card, display card */ + if ( wDeck[ row ][ column ] == card ) { + + if(show == 2) { + if(!player) { + printf("\tHIDDEN => "); + } + else { + printf( "%5s of %-8s => ", wFace[cards[player][i][0]], + wSuit[cards[player][i][1]]); + } + } + + cards[player][i][0] = column; + cards[player][i][1] = row; + + if(!show) + printf("\tHIDDEN"); + else + printf( "%5s of %-8s", wFace[ column ], wSuit[ row ]); + + ++i; + + if(show != 2) printf("%c", !(card % 2) ? '\n' : '\t'); + else printf("\n"); + + wDeck[row][column] = 0; + + /* dealing only "wCards" cards */ + if(i == wCards) { + printf("\n"); + return; + } + + } /* end if */ + + } /* end for */ + + } /* end for */ + + } /* end for */ + +} /* end function deal */ + +/* Get the points of a player */ +int getp(int cards[][CARDS][2], int player, const char *wFace[], + const char *wSuit[], int n_cards, int *r_suit, int *r_face, + int *type, int show) +{ + int i, points; + int scale = 0, n; + int o[13][2] = { { 0 } }; /* occurrences */ + + int kind = 0, face, suit; + /* 0 = nothing + * 1 = Pair + * 2 = Double + * 3 = Tris + * 4 = scale + * 5 = Full + * 6 = Poker + * 7 = Color + * 8 = straight flush + * 9 = royal flush + */ + + /* Inizitialize the o[0,12][1] to 4. Note that 4 is + * a value (random) greather then highest suit (3). */ + for(i = 0; i < 13; i++) + o[i][1] = 4; + + /* count the occurrences of each card's face and + * save to the current index the highest suit */ + for(i = 0; i < n_cards; i++) { + ++o[cards[player][i][0]][0]; + + /* store the index of the highest suit */ + if(o[cards[player][i][0]][1] > cards[player][i][1]) + o[cards[player][i][0]][1] = cards[player][i][1]; + + } + + /* Ok, now don't forget this: + * + * o[i][0] == the occurrences + * o[i][1] == the suit + * i == the face + */ + + /* check if there is a pair/double/tris/full/poker */ + for(i = 0; i < 13; i++) { + switch(o[i][0]) { + case 2: + /* if this is the 1st pair */ + if(!kind) /* is a pair */ + kind = 1; + + /* else could be a double */ + else if(kind == 1) + kind = 2; + + else /* else is full */ + kind = 3; + + break; + case 3: + /* If is the current game is a pair */ + if(kind == 1) + kind = 5; /* then become "full" */ + + else /* else is tris */ + kind = 3; + + break; + case 4: + /* Oh, this is Poker! :-) */ + kind = 6; + break; + default: + /* !o[i][0] */ + ; + + } /* end switch (o[i]) */ + + if( o[i][0] > 1 && (kind != 2 || (kind == 2 && + (!face ? 13 : face) < (!i ? 13 : i) )) ) { + + /* If is double and the current pair is less + * then previous, i don't store its face/suit */ + + face = i; + suit = o[i][1]; + } + + } /* end for (i) */ + + + /* Here i've checked: pair, double, tris, full and poker. + * "face" and "suit" contains the highest value of the current + * "kind". The suit is required if there are an "equal" result + * for change (increment or decrement) the current value of + * each one basing on the suit. + * Missing: scale, color and "all cards are not equals". */ + + + /* if all cards are different store the highest of these */ + if(kind == 0 && !scale) { + for(i = 0, face = -1; i < n_cards; i++) { + + /* search the highest */ + if((!face ? 13 : face) < (!cards[player][i][0] ? 13 : + cards[player][i][0]) ) { + face = cards[player][i][0]; + suit = cards[player][i][1]; + } + + /* if are equal, store the suit */ + else if(face == cards[player][i][0]) { + if(suit < cards[player][i][1]) { + suit = cards[player][i][1]; + } + } + + } + } + + /* check the color */ + for(i = 0, n = 4; i < n_cards; i++) { + if(! (n == 4) ) { + if(cards[player][i][1] != n) + n = - 1; + } + else + n = cards[player][i][1]; + } + if(n != -1) /* live enjoy: life's colored :-) */ + kind = 7; + + /* check the scale / *_flush */ + order(cards, player, n_cards); + + for(i = n = 1; i < n_cards; i++) { + if(cards[i - 1][0] + 1 != cards[i][0]) { + n = 0; + break; + } + } + if(n) { /* This is scale / *_flush */ + + if(kind == 7) { /* *_flush */ + if(face == 0) { /* royal flush */ + kind = 9; + } + + else { /* straight flush */ + kind = 8; + } + } + else { /* just scale */ + kind = 4; + } + } + + *r_suit = suit; + *r_face = face; + *type = kind; + + /* Assign the points */ + switch(kind) { + case 0: /* Nothing */ + + points = face; + break; + case 1: /* Pair */ + + points = P_PAIR + face; + break; + case 2: /* Double */ + + points = P_DOUBLE + face; + break; + case 3: /* Tris */ + + points = P_TRIS + face; + break; + case 4: /* Scale */ + + points = P_SCALE + face; + break; + case 5: /* Full */ + + points = P_FULL + face; + break; + case 6: /* Poker */ + + points = P_POKER + face; + break; + case 7: /* Color */ + + points = P_COLOR + face; + break; + case 8: /* Straight flush */ + + points = P_SFLUSH + face; + break; + case 9: /* Royal flush */ + + points = P_RFLUSH + face; + break; + default: /* (?) */ + printf("### error in function getp()\n"); + exit(-1); + + } /* end switch(kind) */ + + /* Notice the points to the user */ + p_points(kind, face, suit, wFace, wSuit, show); + + if(!face) points += 13; /* add the Ace's points */ + + return points + 1; /* + 1 == [1,13] rather then [0,12] */ +} /* eof getp() */ + +/* Order an array in descending mode */ +void order(int a[][CARDS][2], int p, int size) +{ + int i; + + for(i = 1; i < size; i++) { + if(a[p][i - 1][0] > a[p][i][0]) { + /* swap the face */ + rswap(&a[p][i][0], &a[p][i - 1][0]); + + /* swap the suit */ + rswap(&a[p][i][1], &a[p][i - 1][1]); + } + } /* end for (i) */ + +} /* eof order() */ + +/* Change the card (without user interaction) */ +int chcs(int cards[][CARDS][2], int player, int type[], const char *wFace[], + const char *wSuit[], int wDeck[][13], int n_cards) +{ + int i, ret; + + switch(type[player]) { + case 9: /* Royal flush */ + case 8: /* Straight flush */ + + ret = 0; + break; + case 7: /* Color */ + /* Try to do a Royal flush */ + ret = 0; + + for(i = 0; i < n_cards; i++) { + if(cards[player][i][0] + 1 == cards[player][i + 1][0]) { + ++ret; + } + } + + /* if miss only a card to Royal Flush */ + if(ret == 3) { + /* risk: change one card */ + + if(cards[player][0][0] + 1 == cards[player][1][0]) { + rswap(&cards[player][0][0], &cards[player][n_cards - 1][0]); + rswap(&cards[player][0][1], &cards[player][n_cards - 1][1]); + } + + ret = 1; + } + else /* do nothing */ + ret = 0; + + break; + + case 5: /* Full */ + case 4: /* Scale */ + + /* Stay */ + ret = 0; + + break; + + case 6: /* Poker */ + /* Change a card */ + ret = 1; + + /* cards is ordered so the "intruder" + * have to be at begin or at end */ + + if(cards[n_cards - 1][0] != cards[2][0]) { + + /* copy [0] to [n_cards - 1] */ + + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][0][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][0][1]); + } + + /* else cards[player][n_cards - 1][0] <=> cards[player][2][0] */ + + /* and insert a new card on [0] */ + deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + break; + case 2: /* Double */ + /* change 1 card */ + ret = 1; + + /* cards is ordered so the "intruder" + * have to be at begin or at end */ + + if(cards[player][n_cards - 1][0] != cards[player][5][1] && + cards[player][n_cards - 1][0] != cards[player][3][0]) { + + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][0][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][0][1]); + } + + /* else cards[0][0] is already free */ + deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + break; + case 3: /* Tris */ + /* change 2 cards */ + ret = 2; + + /* cards is ordered so the "intruderS" + * DON'T have to be at middle */ + + for(i = 0; i < n_cards / 2; i++) { + if(cards[i][0] == cards[2][0]) + break; + } + + if(!i) { + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][0][0]); + rswap(&cards[player][n_cards - 2][0], &cards[player][1][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][0][1]); + rswap(&cards[player][n_cards - 2][1], &cards[player][1][1]); + } + else if(i == 1) { + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][2][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][2][1]); + } + + /* insert 2 cards on [0] and [1] */ + deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + break; + case 1: /* Pair */ + /* change 3 cards */ + ret = 3; + + for(i = 0; i < n_cards; i++) { + if(cards[player][i][0] == cards[player][i + 1][0]) + break; + } + + /* The face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][i][0]); + rswap(&cards[player][n_cards - 2][0], &cards[player][i+1][0]); + + /* The suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][i][1]); + rswap(&cards[player][n_cards - 2][1], &cards[player][i+1][1]); + + deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + break; + case 0: /* Nothing */ + /* Change all cards */ + ret = 0; + + /* If i have a Jack, a Queen, a King or an Ace, hold it */ + for(i = 0; i < n_cards; i++) { + /* 9 == Ten */ + if( (!cards[player][i][0] ? 13 : cards[player][i][0]) > 9 && + (!cards[player][i][0] ? 13 : cards[player][i][0]) > ret) { + ret = (!cards[player][i][0] ? 13 : cards[player][i][0]); + + rswap(&cards[player][0][0], &cards[player][i][0]); + rswap(&cards[player][0][1], &cards[player][i][1]); + } + } + rswap(&cards[player][0][0], &cards[player][n_cards - 1][0]); + rswap(&cards[player][0][1], &cards[player][n_cards - 1][1]); + + /* else change all cards */ + + if(!ret) + ret = n_cards; + else + ret = n_cards - 1; + + deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + break; + default: /* (?) */ + printf("### error in function chcs()\n"); + exit(-1); + + } /* end switch (type[player]) */ + + return ret; +} /* eof chcs() */ + +/* Swap two variable for reference */ +void rswap(int *a, int *b) +{ + int hold; + + hold = *a; + *a = *b; + *b = hold; +} /* eof rswap() */ + +/* Change the cards (with user interaction) */ +int chch(int cards[][CARDS][2], int n_cards, int player, int wDeck[][13], + const char *wFace[], const char *wSuit[], int kind, + int r_face, int r_suit, int show) +{ + int i, j, ret = 0; + int changes[CARDS] = { 0 }; + + + printf(".=== CHANGE -=#| PLAYER %d |#=- CHANGE ===.\n\n", player); + + printf("Player %d is changing the cards..\n", player); + + while(ret != EOF) { + + /* Check if something is changed.. */ + for(i = 0, ret = 0; i < n_cards; i++) { + if(changes[i]) { + ++ret; + } + } + + if(ret) { /* ..if yes show it.. */ + + printf("\nHeld cards:\n\n"); + for(i = 0, ret = 0; i < n_cards; i++) { + if(changes[i]) { + + printf( "\t[%d] %5s of %-8s", i, + wFace[cards[player][i][0]], wSuit[cards[player][i][1]]); + printf("%c", !(++ret % 2) ? '\n' : '\t'); + + } + } + printf("\n\n"); + + } + else { + /* ..else do nothing. */ + printf("\n\n===> No held cards!\n\n"); + } + + if(ret == n_cards) { + printf("You are holding all cards!\n\n\n"); + } + else { + printf("\nYour current cards are:\n\n"); + for(i = 0, ret = 0; i < n_cards; i++) { + if(!changes[i]) { + printf( "\t[%d] %5s of %-8s", i, + wFace[cards[player][i][0]], wSuit[cards[player][i][1]]); + printf("%c", !(++ret % 3) ? '\t' : '\n'); + } + + } + printf("\n\n"); + } + + p_points(kind, r_face, r_suit, wFace, wSuit, show); + + while(ret != EOF) { + + printf("\n\n"); + printf("What card(s) you would to hold? (%d to end)\n" + "Selection: ", EOF); + + scanf("%d", &ret); + + if( (ret >= 0 && ret < n_cards) || ret == EOF) + break; + + else { + printf("\nInvalid selection."); + continue; + } + } + + if(ret != EOF) { + /* If is selected, then unselect else select */ + changes[ret] = !changes[ret] ? 1 : 0; + } + + } /* end while (ret) */ + + /* count the cards that will be changed (ret) */ + for(i = 0, ret = 0; i < n_cards; i++) { + if(!changes[i]) + ++ret; + } + + /* put the card to change at begin of the array */ + for(i = 0; i < n_cards; i++) { + if(changes[i]) { + for(j = n_cards - 1; j > i; j--) { + if(!changes[j]) { + rswap(&cards[player][i][0], &cards[player][j][0]); + rswap(&cards[player][i][1], &cards[player][j][1]); + } + } + } + } /* end for (i) */ + + if(ret) deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + return ret; +} /* eof chch() */ + +/* Print a message(s) (the points) basing on the "kind" */ +void p_points(int kind, int face, int suit, + const char *wFace[], const char *wSuit[], int show) +{ + if(show) printf(": "); + + switch(kind) { + case 0: /* Nothing */ + if(show) + printf("All cards are differents!\n" + ": You could win with the %s of %s\n", + wFace[face], wSuit[suit]); + + break; + case 1: /* Pair */ + if(show) + printf("Oh, it is a pair of %ss!\n", wFace[face]); + + break; + case 2: /* Double */ + if(show) + printf("Double to %ss\n", wFace[face]); + + break; + case 3: /* Tris */ + if(show) + printf("This is tris of %ss!\n", wFace[face]); + + break; + case 4: /* Scale */ + if(show) + printf("Yeah, you have done a scale to %s\n", wFace[face]); + + break; + case 5: /* Full */ + if(show) + printf("*** FULL of %ss!\n", wFace[face]); + + break; + case 6: /* Poker */ + if(show) + printf("Wow, it's Poker of %ss!\n", wFace[face]); + + break; + case 7: /* Color */ + if(show) + printf("%d points of color (%s)\n", P_COLOR, wSuit[suit]); + + break; + case 8: /* Straight flush */ + if(show) + printf("* Straight flush to %s*\n", wFace[face]); + + break; + case 9: /* Royal flush */ + if(show) + printf("*| Royal Flush (%s) |*\n", wSuit[suit]); + + break; + default: /* (?) */ + printf("### error in function p_points()\n"); + exit(-1); + + } /* end switch(kind) */ + +} /* eof p_points() */ + diff --git a/exercises/deitel/ch7/poker3.c b/exercises/deitel/ch7/poker3.c @@ -0,0 +1,907 @@ +/* Exercise 7.16 */ + +/* Fig. 7.24: fig07_24.c + Card shuffling dealing program */ +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define CARDS 5 + +/* Points setting * + * NOTE: the points *must* have an offset >= 15 and P_PAIR + * must should be >= 15 too to works properly. Else, + * the game will sh0w only INVALID results and wrong + * winners. + */ +#define OFFSET 15 + +/* I'll tweak these, maybe.. a day :-) */ +#define P_PAIR OFFSET +#define P_DOUBLE P_PAIR + OFFSET +#define P_TRIS P_DOUBLE + OFFSET +#define P_SCALE P_TRIS + OFFSET +#define P_FULL P_SCALE + OFFSET +#define P_POKER P_FULL + OFFSET +#define P_COLOR P_POKER + OFFSET +#define P_SFLUSH P_COLOR + OFFSET +#define P_RFLUSH P_SFLUSH + OFFSET + +/* prototypes */ +void shuffle( int wDeck[][ 13 ] ); + +void deal( int wDeck[][ 13 ], const char *wFace[], const char *wSuit[], + int cards[][CARDS][2], int player, int wCards, int show); + +int getp(int cards[][CARDS][2], int player, const char *wFace[], + const char *wSuit[], int n_cards, int *r_suit, int *r_face, + int type[], int show); + +void order(int a[][CARDS][2], int p, int size); +void rswap(int *a, int *b); + +int chcs(int cards[][CARDS][2], int player, int type[], const char *wFace[], + const char *wSuit[], int wDeck[][13], int n_cards); + +int chch(int cards[][CARDS][2], int n_cards, int player, int wDeck[][13], + const char *wFace[], const char *wSuit[], int kind, + int r_face, int r_suit, int show); + +void p_points(int kind, int face, int suit, + const char *wFace[], const char *wSuit[], int show); + +int main(void) +{ + int i, type[2], winner[3] = { 0 }, points[2] = { 0 }; + int p[2][2] = { { 0 } }; + int cards[2][CARDS][2] = { { { 0 } } }; + int c; /* change tracer */ + int theface[2], thesuit; + + /* initialize suit array */ + const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; + + /* initialize face array */ + const char *face[ 13 ] = + { "Ace", "Deuce", "Three", "Four", + "Five", "Six", "Seven", "Eight", + "Nine", "Ten", "Jack", "Queen", "King" }; + + /* initialize deck array */ + int deck[ 4 ][ 13 ] = { + { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }, + { 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 }, + { 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 }, + { 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52 } + }; + + + if(CARDS > 52 / 2) { + printf("Too many cards: redefine the CARDS constant.\n"); + exit(-1); + } + + srand( time( 0 ) ); /* seed random-number generator */ + + shuffle( deck ); + + /* S t a r t */ + printf("GaMe STaRTeD! (%d cards for player)\n\n", CARDS); + + for(i = 0; i < 2; i++) { + printf("*** "); + if(!i) + printf("Computer"); + else + printf("Player %d", i); + + printf("'s cards..\n"); + + printf("-----------------------------------------\n\n"); + + deal( deck, face, suit, cards, i, CARDS, !i ? 0 : 1 ); + + /* p[i][0] == points + * p[i][1] == suit of highest card (whitin the highest kind) + * i == the player + * p[0][?] == the computer + */ + if(i) printf("\n"); + p[i][0] = getp(cards, i, face, suit, CARDS, &p[i][1], + &theface[i], &type[i], i); + + if(i) { + thesuit = p[1][1]; /* take the user's suit */ + + printf("\n: Score: %d ", p[i][0]); + printf("(suit points reserved: %d)", 4 - p[i][1]); + } + + printf("\n-----------------------------------------\n"); + + /* so */ + points[i] = p[i][0] - p[i][1]; /* points - seed(0 highest, 3 lowest) */ + printf("\n\n"); + } + + printf("Now is time to change the cards..\n"); + printf("Press a key to continue.\n"); + getchar(); + + /* Player change the cards */ + c = chch(cards, CARDS, 1, deck, face, suit, type[1], + theface[1], thesuit, 1); + if(c) { + printf("Player 1 has changed %d %s.\n\n", c, c > 1 ? "cards" : "card" ); + + p[1][0] = getp(cards, 1, face, suit, CARDS, &p[1][1], + &theface[1], &type[1], 1); + } + + /* Computer change the cards */ + c = chcs(cards, 0, &type[0], face, suit, deck, CARDS); + if(c) { + printf("Computer has changed %d %s.\n\n", c, c > 1 ? "cards" : "card" ); + + p[0][0] = getp(cards, 0, face, suit, CARDS, + &p[0][1], &theface[0], &type[0], 0); + } + + printf("\n\n"); + + + /* F i n i s h */ + + /* Check the winner and print the classifies */ + for(i = 0; i < 2; i++) { + if(p[i][0] > winner[0]) { + winner[0] = p[i][0]; + winner[1] = p[i][1]; + winner[3] = i; + } + else if(p[i][0] == winner[0]) { /* Pair: check the suit */ + if(p[i][1] < winner[1]) { + winner[0] = p[i][0]; + winner[1] = p[i][1]; + winner[3] = i; + } + } + } /* end for (i) */ + + printf("Press a key to know the winner\n" + "or type ^C if you have fear :-)\n"); + + getchar(); getchar(); + printf("\n"); + + /* Show the cards */ + for(i = 1; i >= 0; i--) { + if(!i) + printf("Computer"); + else + printf("Player 1"); + printf("'s cards:\n"); + + printf("-------------------------------"); + printf("-----------------------------\n"); + + for(c = 0; c < CARDS; c++) { + printf("%15s of %-8s", face[cards[i][c][0]], suit[cards[i][c][1]]); + printf("%c", !(c % 2) ? '\n' : '\t'); + } + + printf("\n\n"); + p_points(type[i], theface[i], p[i][1], face, suit, 1); + + printf("\n\tTotal points: %d (suit %d)\n", p[i][0], p[i][1]); + printf("-------------------------------"); + printf("-----------------------------\n"); + printf("\n\n"); + } + + + printf("\n\tC l a s s i f i e s\n\n"); + + printf("%16s%9s\n", "Player", "Points"); + printf("%16s%9d\n", "PC", p[0][0]); + printf("%16d%9d\n", 1, p[1][0]); + + printf("\n"); + + if(!winner[3]) + printf("* Computer won with %d points.\n", winner[0]); + else + printf("* Player %d won with %d points.\n", winner[3], winner[0]); + + printf("\n"); + return 0; /* indicates successful termination */ + +} /* end main */ + +/* shuffle cards in deck */ +void shuffle( int wDeck[][ 13 ] ) +{ + int row; + int column; + + for(row = 0; row < 4; row++) { + for(column = 0; column < 13; column++) { + rswap(&wDeck[row][column], &wDeck[rand() % 4][rand() % 13]); + } + } + +} /* end function shuffle */ + +/* deal cards in deck */ +void deal( int wDeck[][ 13 ], const char *wFace[], const char *wSuit[], + int cards[][CARDS][2], int player, int wCards, int show) +{ + int card; /* card counter */ + int row; /* row counter */ + int column; /* column counter */ + int i = 0, found; + + if(show == 2) { + printf("\n\n===> "); + if(!player) + printf("Computer"); + else + printf("Player %d", player); + + printf(" is changing cards..\n\n"); + } + + /* deal each of the 52 cards */ + for ( card = 1; card <= 52; card++ ) { + found = 0; /* found the card? :-) */ + + /* loop through rows of wDeck */ + for ( row = 0; row <= 3 && !found; row++ ) { + + /* loop through columns of wDeck for current row */ + for ( column = 0; column <= 12 && !found; column++ ) { + /* if slot contains current card, display card */ + if ( wDeck[ row ][ column ] == card ) { + + if(show == 2) { + if(!player) { + printf("\tHIDDEN => "); + } + else { + printf( "%5s of %-8s => ", wFace[cards[player][i][0]], + wSuit[cards[player][i][1]]); + } + } + + cards[player][i][0] = column; + cards[player][i][1] = row; + + if(!show) + printf("\tHIDDEN"); + else + printf( "%5s of %-8s", wFace[ column ], wSuit[ row ]); + + ++i; + + if(show != 2) printf("%c", !(card % 2) ? '\n' : '\t'); + else printf("\n"); + + wDeck[row][column] = 0; + + /* dealing only "wCards" cards */ + if(i == wCards) { + printf("\n"); + return; + } + + found = 1; + + + } /* end if */ + + } /* end for */ + + } /* end for */ + + } /* end for */ + +} /* end function deal */ + +/* Get the points of a player */ +int getp(int cards[][CARDS][2], int player, const char *wFace[], + const char *wSuit[], int n_cards, int *r_suit, int *r_face, + int *type, int show) +{ + int i, points; + int scale = 0, n; + int o[13][2] = { { 0 } }; /* occurrences */ + + int kind = 0, face, suit; + /* 0 = nothing + * 1 = Pair + * 2 = Double + * 3 = Tris + * 4 = scale + * 5 = Full + * 6 = Poker + * 7 = Color + * 8 = straight flush + * 9 = royal flush + */ + + /* Inizitialize the o[0,12][1] to 4. Note that 4 is + * a value (random) greather then highest suit (3). */ + for(i = 0; i < 13; i++) + o[i][1] = 4; + + /* count the occurrences of each card's face and + * save to the current index the highest suit */ + for(i = 0; i < n_cards; i++) { + ++o[cards[player][i][0]][0]; + + /* store the index of the highest suit */ + if(o[cards[player][i][0]][1] > cards[player][i][1]) + o[cards[player][i][0]][1] = cards[player][i][1]; + + } + + /* Ok, now don't forget this: + * + * o[i][0] == the occurrences + * o[i][1] == the suit + * i == the face + */ + + /* check if there is a pair/double/tris/full/poker */ + for(i = 0; i < 13; i++) { + switch(o[i][0]) { + case 2: + /* if this is the 1st pair */ + if(!kind) /* is a pair */ + kind = 1; + + /* else could be a double */ + else if(kind == 1) + kind = 2; + + else /* else is full */ + kind = 3; + + break; + case 3: + /* If is the current game is a pair */ + if(kind == 1) + kind = 5; /* then become "full" */ + + else /* else is tris */ + kind = 3; + + break; + case 4: + /* Oh, this is Poker! :-) */ + kind = 6; + break; + default: + /* !o[i][0] */ + ; + + } /* end switch (o[i]) */ + + if( o[i][0] > 1 && (kind != 2 || (kind == 2 && + (!face ? 13 : face) < (!i ? 13 : i) )) ) { + + /* If is double and the current pair is less + * then previous, i don't store its face/suit */ + + face = i; + suit = o[i][1]; + } + + } /* end for (i) */ + + + /* Here i've checked: pair, double, tris, full and poker. + * "face" and "suit" contains the highest value of the current + * "kind". The suit is required if there are an "equal" result + * for change (increment or decrement) the current value of + * each one basing on the suit. + * Missing: scale, color and "all cards are not equals". */ + + + /* if all cards are different store the highest of these */ + if(kind == 0 && !scale) { + for(i = 0, face = -1; i < n_cards; i++) { + + /* search the highest */ + if((!face ? 13 : face) < (!cards[player][i][0] ? 13 : + cards[player][i][0]) ) { + face = cards[player][i][0]; + suit = cards[player][i][1]; + } + + /* if are equal, store the suit */ + else if(face == cards[player][i][0]) { + if(suit < cards[player][i][1]) { + suit = cards[player][i][1]; + } + } + + } + } + + /* check the color */ + for(i = 0, n = 4; i < n_cards; i++) { + if(! (n == 4) ) { + if(cards[player][i][1] != n) + n = - 1; + } + else + n = cards[player][i][1]; + } + if(n != -1) /* live enjoy: life's colored :-) */ + kind = 7; + + /* check the scale / *_flush */ + order(cards, player, n_cards); + + for(i = n = 1; i < n_cards; i++) { + if(cards[i - 1][0] + 1 != cards[i][0]) { + n = 0; + break; + } + } + if(n) { /* This is scale / *_flush */ + + if(kind == 7) { /* *_flush */ + if(face == 0) { /* royal flush */ + kind = 9; + } + + else { /* straight flush */ + kind = 8; + } + } + else { /* just scale */ + kind = 4; + } + } + + *r_suit = suit; + *r_face = face; + *type = kind; + + /* Assign the points */ + switch(kind) { + case 0: /* Nothing */ + + points = face; + break; + case 1: /* Pair */ + + points = P_PAIR + face; + break; + case 2: /* Double */ + + points = P_DOUBLE + face; + break; + case 3: /* Tris */ + + points = P_TRIS + face; + break; + case 4: /* Scale */ + + points = P_SCALE + face; + break; + case 5: /* Full */ + + points = P_FULL + face; + break; + case 6: /* Poker */ + + points = P_POKER + face; + break; + case 7: /* Color */ + + points = P_COLOR + face; + break; + case 8: /* Straight flush */ + + points = P_SFLUSH + face; + break; + case 9: /* Royal flush */ + + points = P_RFLUSH + face; + break; + default: /* (?) */ + printf("### error in function getp()\n"); + exit(-1); + + } /* end switch(kind) */ + + /* Notice the points to the user */ + p_points(kind, face, suit, wFace, wSuit, show); + + if(!face) points += 13; /* add the Ace's points */ + + return points + 1; /* + 1 == [1,13] rather then [0,12] */ +} /* eof getp() */ + +/* Order an array in descending mode */ +void order(int a[][CARDS][2], int p, int size) +{ + int i; + + for(i = 1; i < size; i++) { + if(a[p][i - 1][0] > a[p][i][0]) { + /* swap the face */ + rswap(&a[p][i][0], &a[p][i - 1][0]); + + /* swap the suit */ + rswap(&a[p][i][1], &a[p][i - 1][1]); + } + } /* end for (i) */ + +} /* eof order() */ + +/* Change the card (without user interaction) */ +int chcs(int cards[][CARDS][2], int player, int type[], const char *wFace[], + const char *wSuit[], int wDeck[][13], int n_cards) +{ + int i, ret; + + switch(type[player]) { + case 9: /* Royal flush */ + case 8: /* Straight flush */ + + ret = 0; + break; + case 7: /* Color */ + /* Try to do a Royal flush */ + ret = 0; + + for(i = 0; i < n_cards; i++) { + if(cards[player][i][0] + 1 == cards[player][i + 1][0]) { + ++ret; + } + } + + /* if miss only a card to Royal Flush */ + if(ret == 3) { + /* risk: change one card */ + + if(cards[player][0][0] + 1 == cards[player][1][0]) { + rswap(&cards[player][0][0], &cards[player][n_cards - 1][0]); + rswap(&cards[player][0][1], &cards[player][n_cards - 1][1]); + } + + ret = 1; + } + else /* do nothing */ + ret = 0; + + break; + + case 5: /* Full */ + case 4: /* Scale */ + + /* Stay */ + ret = 0; + + break; + + case 6: /* Poker */ + /* Change a card */ + ret = 1; + + /* cards is ordered so the "intruder" + * have to be at begin or at end */ + + if(cards[n_cards - 1][0] != cards[2][0]) { + + /* copy [0] to [n_cards - 1] */ + + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][0][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][0][1]); + } + + /* else cards[player][n_cards - 1][0] <=> cards[player][2][0] */ + + /* and insert a new card on [0] */ + deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + break; + case 2: /* Double */ + /* change 1 card */ + ret = 1; + + /* cards is ordered so the "intruder" + * have to be at begin or at end */ + + if(cards[player][n_cards - 1][0] != cards[player][5][1] && + cards[player][n_cards - 1][0] != cards[player][3][0]) { + + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][0][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][0][1]); + } + + /* else cards[0][0] is already free */ + deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + break; + case 3: /* Tris */ + /* change 2 cards */ + ret = 2; + + /* cards is ordered so the "intruderS" + * DON'T have to be at middle */ + + for(i = 0; i < n_cards / 2; i++) { + if(cards[i][0] == cards[2][0]) + break; + } + + if(!i) { + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][0][0]); + rswap(&cards[player][n_cards - 2][0], &cards[player][1][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][0][1]); + rswap(&cards[player][n_cards - 2][1], &cards[player][1][1]); + } + else if(i == 1) { + /* the face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][2][0]); + + /* the suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][2][1]); + } + + /* insert 2 cards on [0] and [1] */ + deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + break; + case 1: /* Pair */ + /* change 3 cards */ + ret = 3; + + for(i = 0; i < n_cards; i++) { + if(cards[player][i][0] == cards[player][i + 1][0]) + break; + } + + /* The face */ + rswap(&cards[player][n_cards - 1][0], &cards[player][i][0]); + rswap(&cards[player][n_cards - 2][0], &cards[player][i+1][0]); + + /* The suit */ + rswap(&cards[player][n_cards - 1][1], &cards[player][i][1]); + rswap(&cards[player][n_cards - 2][1], &cards[player][i+1][1]); + + deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + break; + case 0: /* Nothing */ + /* Change all cards */ + ret = 0; + + /* If i have a Jack, a Queen, a King or an Ace, hold it */ + for(i = 0; i < n_cards; i++) { + /* 9 == Ten */ + if( (!cards[player][i][0] ? 13 : cards[player][i][0]) > 9 && + (!cards[player][i][0] ? 13 : cards[player][i][0]) > ret) { + ret = (!cards[player][i][0] ? 13 : cards[player][i][0]); + + rswap(&cards[player][0][0], &cards[player][i][0]); + rswap(&cards[player][0][1], &cards[player][i][1]); + } + } + rswap(&cards[player][0][0], &cards[player][n_cards - 1][0]); + rswap(&cards[player][0][1], &cards[player][n_cards - 1][1]); + + /* else change all cards */ + + if(!ret) + ret = n_cards; + else + ret = n_cards - 1; + + deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + break; + default: /* (?) */ + printf("### error in function chcs()\n"); + exit(-1); + + } /* end switch (type[player]) */ + + return ret; +} /* eof chcs() */ + +/* Swap two variable for reference */ +void rswap(int *a, int *b) +{ + int hold; + + hold = *a; + *a = *b; + *b = hold; +} /* eof rswap() */ + +/* Change the cards (with user interaction) */ +int chch(int cards[][CARDS][2], int n_cards, int player, int wDeck[][13], + const char *wFace[], const char *wSuit[], int kind, + int r_face, int r_suit, int show) +{ + int i, j, ret = 0; + int changes[CARDS] = { 0 }; + + while(ret != EOF) { + + printf("\n\n\t\t..:: CHANGING THE CARDS ::..\n"); + + /* Check if something is changed.. */ + for(i = 0, ret = 0; i < n_cards; i++) { + if(changes[i]) { + ++ret; + } + } + + if(ret) { /* ..if yes show it.. */ + + printf("\nHeld cards:\n\n"); + for(i = 0, ret = 0; i < n_cards; i++) { + if(changes[i]) { + + printf( "\t[%d] %5s of %-8s", i, + wFace[cards[player][i][0]], wSuit[cards[player][i][1]]); + printf("%c", !(++ret % 2) ? '\n' : '\t'); + + } + } + printf("\n\n"); + + } + else { + /* ..else do nothing. */ + printf("\n\n===> No held cards!\n\n"); + } + + if(ret == n_cards) { + printf("You are holding all cards!\n\n\n"); + } + else { + printf("\nYour current cards are:\n\n"); + for(i = 0, ret = 0; i < n_cards; i++) { + if(!changes[i]) { + printf( "\t[%d] %5s of %-8s", i, + wFace[cards[player][i][0]], wSuit[cards[player][i][1]]); + printf("%c", !(++ret % 2) ? '\t' : '\n'); + } + + } + printf("\n\n"); + } + + p_points(kind, r_face, r_suit, wFace, wSuit, show); + + while(ret != EOF) { + + printf("\n\n"); + printf("What card(s) you would to hold? (%d to confirm)\n" + "Selection: ", EOF); + + scanf("%d", &ret); + + if( (ret >= 0 && ret < n_cards) || ret == EOF) + break; + + else { + printf("\nInvalid selection."); + continue; + } + } + + if(ret != EOF) { + /* If is selected, then unselect else select */ + changes[ret] = !changes[ret] ? 1 : 0; + } + + } /* end while (ret) */ + + /* count the cards that will be changed (ret) */ + for(i = 0, ret = 0; i < n_cards; i++) { + if(!changes[i]) + ++ret; + } + + /* put the card to change at begin of the array */ + for(i = 0; i < n_cards; i++) { + if(changes[i]) { + for(j = n_cards - 1; j > i; j--) { + if(!changes[j]) { + rswap(&cards[player][i][0], &cards[player][j][0]); + rswap(&cards[player][i][1], &cards[player][j][1]); + } + } + } + } /* end for (i) */ + + if(ret) deal( wDeck, wFace, wSuit, cards, player, ret, 2); + + return ret; +} /* eof chch() */ + +/* Print a message(s) (the points) basing on the "kind" */ +void p_points(int kind, int face, int suit, + const char *wFace[], const char *wSuit[], int show) +{ + if(show) printf(": "); + + switch(kind) { + case 0: /* Nothing */ + if(show) + printf("All cards are differents!\n" + ": You could win with the %s of %s\n", + wFace[face], wSuit[suit]); + + break; + case 1: /* Pair */ + if(show) + printf("Oh, it is a pair of %ss!\n", wFace[face]); + + break; + case 2: /* Double */ + if(show) + printf("Double to %ss\n", wFace[face]); + + break; + case 3: /* Tris */ + if(show) + printf("This is tris of %ss!\n", wFace[face]); + + break; + case 4: /* Scale */ + if(show) + printf("Yeah, you have done a scale to %s\n", wFace[face]); + + break; + case 5: /* Full */ + if(show) + printf("*** FULL of %ss!\n", wFace[face]); + + break; + case 6: /* Poker */ + if(show) + printf("Wow, it's Poker of %ss!\n", wFace[face]); + + break; + case 7: /* Color */ + if(show) + printf("%d points of color (%s)\n", P_COLOR, wSuit[suit]); + + break; + case 8: /* Straight flush */ + if(show) + printf("* Straight flush to %s*\n", wFace[face]); + + break; + case 9: /* Royal flush */ + if(show) + printf("*| Royal Flush (%s) |*\n", wSuit[suit]); + + break; + default: /* (?) */ + printf("### error in function p_points()\n"); + exit(-1); + + } /* end switch(kind) */ + +} /* eof p_points() */ + diff --git a/exercises/deitel/ch7/poker_mod.c b/exercises/deitel/ch7/poker_mod.c @@ -0,0 +1,65 @@ +/* Fig. 7.24: fig07_24.c + Card shuffling dealing program */ +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +/* prototypes */ +void shuffleAndDeal( int wDeck[][ 13 ], int n_cards, + const char *wFace[], const char *wSuit[] ); + +int main(void) +{ + /* initialize suit array */ + const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; + + /* initialize face array */ + const char *face[ 13 ] = + { "Ace", "Deuce", "Three", "Four", + "Five", "Six", "Seven", "Eight", + "Nine", "Ten", "Jack", "Queen", "King" }; + + /* initialize deck array */ + int deck[ 4 ][ 13 ] = { { 0 } }; + + srand( time( 0 ) ); /* seed random-number generator */ + + shuffleAndDeal( deck, 5, face, suit ); + + return 0; /* indicates successful termination */ + +} /* end main */ + + + +/* shuffle and deal cards in deck */ +void shuffleAndDeal( int wDeck[][ 13 ], int n_cards, + const char *wFace[], const char *wSuit[] ) +{ + int row; /* row number */ + int column; /* column number */ + int card; /* counter */ + + /* for each of the 52 cards, choose slot of deck randomly */ + for ( card = 1; card <= 26; card++ ) { + + /* choose new random location until unoccupied slot found */ + do { + row = rand() % 4; + column = rand() % 13; + } while( wDeck[ row ][ column ] != 0 ); /* end do...while */ + + /* place card number in chosen slot of deck */ + wDeck[ row ][ column ] = card; + + if(n_cards) { + printf( "%5s of %-8s%c", wFace[ column ], wSuit[ row ], + card % 2 == 0 ? '\n' : '\t' ); + --n_cards; + } + + } /* end for */ + printf("\n"); + +} /* end function shuffleAndDeal */ + diff --git a/exercises/deitel/ch7/quicksort.c b/exercises/deitel/ch7/quicksort.c @@ -0,0 +1,109 @@ +/* Exercise 7.24 */ + +#include <stdio.h> + +void quicksort(int array[], int sidx, int eidx); +int partition(int array[], int num, int size); +void iswap(int *a, int *b); +void i_pa(int a[], int size); + +int main(void) +{ + int a[] = { + 8, 2, 25, 15, 31, 78, 23, 69, 19, 10, 41, 1, 1, 1, + 33, 58, 9, 15, 19, 8, 100, 28, 12, 5, 234, 734, 9, + 23, 12312, 21, 1231, 2123, 21321, 12, 123, 3, 432, + 2, 354, 34, 2, 3, 4, 423, 34, 685, 65, 4, 22, 521 + }; + + int size = ( sizeof(a) / sizeof(int) ); + + printf("The array before the order:\t"); + i_pa(a, size); + + quicksort(a, 0, size - 1); + + printf("\nThe array after the order:\t"); + i_pa(a, size); + + return 0; +} /* E0F main */ + +/* Sort an array using the quicksort algorithm */ +void quicksort(int array[], int sidx, int eidx) +{ + int newidx; + + if(sidx == eidx) + return; + + newidx = partition(array, sidx, eidx); + + if(newidx == sidx) { + quicksort(array, newidx + 1, eidx); + } + else if(newidx == eidx) { + quicksort(array, sidx, newidx - 1); + } + else { + quicksort(array, newidx + 1, eidx); + quicksort(array, sidx, newidx - 1); + } + +} /* eof quicksort() */ + +/* Partition a number to an array */ +int partition(int a[], int num, int size) +{ + int l = 0, r = size; + + while(1) { + + for( ; r > num; r--) { + if(a[r] < a[num]) { + iswap(&a[r], &a[num]); + num = r; + break; + } + } + + for(; l < num; l++) { + if(a[l] > a[num]) { + iswap(&a[l], &a[num]); + num = l; + break; + } + } + + if(l == r) + break; + + } + + return num; + +} + +/* Swap two element */ +void iswap(int *a, int *b) +{ + int hold = *a; + *a = *b; + *b = hold; +} /* eof iswap() */ + +void i_pa(int a[], int size) +{ + int i; + + printf("\n"); + + for(i = 1; i <= size; i++) { + printf("%6d ", a[i - 1]); + + if( !(i % 10) ) + printf("\n"); + } + +} /* end i_pa() */ + diff --git a/exercises/deitel/ch7/sim_TL.c b/exercises/deitel/ch7/sim_TL.c @@ -0,0 +1,125 @@ +/* Exercise 7.17 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#include <unistd.h> + +#define LEN 70 + +void move(int who[]); +void show(int who[]); + +int main(void) +{ + int who[2] = { 0, 0 }; + + srand( time(NULL) ); + + /* Start */ + printf("BANG !!!!!\nAND THEY'RE OF !!!!!"); + + while(who[0] <= LEN && who[1] <= LEN) { + printf("\n\n"); + + move(who); /* move the players */ + show(who); /* show current position */ + + sleep(1); + } + printf("\n\n"); + + /* check the winner */ + if(who[0] > LEN && who[1] <= LEN) { + printf("TORTOISE WINS!!! YAY!!!\n"); + } + else if(who[1] > LEN && who[0] <= LEN) { + printf("Hare wins. Yuch.\n"); + } + else { /* There is no winner! */ + printf("who[0] = %d && who[1] = %d\n", who[0], who[1]); + if( rand() % 2 ) { + printf("It's a tie!\n"); + } + else { + printf("I want to win the turtle!! :-)\n"); + } + } + + return 0; +} /* E0F main */ + +/* Move the players */ +void move(int who[]) +{ + int i = 1 + rand() % 10; + + /* Move the turtle (who[0]) */ + if(i <= 5) /* 50% limped fast */ + who[0] += 3; + + else if(i >= 6 && i <= 7)/* 20% slide */ + who[0] -= 6; + + else /* i >=8: 30% limpied slow */ + ++who[0]; + + /* Check if the turtle is out of path */ + if(who[0] < 0) + who[0] = 0; + + + /* Move the hare (who[1]) */ + if(i <= 2) /* 20% (sleep) */ + ; /* stay in the same position */ + + else if(i >= 3 && i <= 4) /* 20% long jump */ + who[1] += 9; + + else if(i == 5) /* 10% Long slide */ + who[1] -= 12; + + else if(i >= 6 && i <= 8) /* 30% short jump */ + ++who[1]; + + else /* i >= 9: 20% short slide */ + who[1] -= 2; + + /* Check if the hare is out of path */ + if(who[1] < 0) + who[1] = 0; + + +} /* eof move() */ + +/* Show the situation ;) */ +void show(int who[]) +{ + int i; + + /* Show the turtle position */ + for(i = 0; i < LEN; i++) { + + /* If are both here */ + if(i == who[0] && i == who[1]) { + printf("OUCH!!!"); + i += 6; /* Align the path */ + } + + /* If is the turtle */ + else if(i == who[0]) + printf("T"); + + /* If is the hare */ + else if(i == who[1]) + printf("L"); + + /* If is empty */ + else + printf("."); + + } + +} /* eof show() */ + diff --git a/exercises/deitel/ch7/simpletron.c b/exercises/deitel/ch7/simpletron.c @@ -0,0 +1,247 @@ +/* Exercise 7.19 */ + +/* The Simpletron (and LMS) implementation */ + +#include <stdio.h> +#include <stdlib.h> + +#define MEMSIZE 100 + +/* Input/Output */ +#define READ 10 +#define WRITE 11 + +/* Loading/Storing */ +#define LOAD 20 +#define STORE 21 + +/* Arithmetical */ +#define ADD 30 +#define SUBTRACT 31 +#define DIVIDE 32 +#define MULTIPLY 33 + +/* Reference and control */ +#define BRANCH 40 +#define BRANCHNEG 41 +#define BRANCHZERO 42 +#define HALT 43 + +int checkword(int word, int size); +void dump(int acc, int icounter, int mem[]); + +int main(void) +{ + int memory[MEMSIZE] = { 0 }, i, err = 0; + + int operationCode = 0, instructionRegister = 0; + int accumulator = 0, operand = 0; + + printf("*** Welcome to the Simpletron! ***\n" + "*** Please enter your program one instruction ***\n" + "*** (or data word) at a time. I will type the ***\n" + "*** location number and a question mark (?). ***\n" + "*** You then type the word for that location. ***\n" + "*** Type the sentinel -99999 to stop entering ***\n" + "*** your program. ***\n"); + + for(i = 0; i < MEMSIZE; i++) { + while(1) { + printf("%.2d ?? ", i); + scanf("%d", &memory[i]); + + if(memory[i] == -99999) { + memory[i] = 0; + i = MEMSIZE; /* Terminate the for loop */ + break; + } + + if( checkword(memory[i], MEMSIZE) ) { + printf("*** Invalid instruction: %d\n", memory[i]); + printf("*** Please retype it or exit.\n"); + } + else + break; + + } /* end while */ + } /* end for (i) */ + + printf("*** Program loading completed ***\n" + "*** Program execution begins ***\n"); + + for(i = 0; i < MEMSIZE; i++) { + instructionRegister = memory[i]; + + operationCode = instructionRegister / 100; + operand = instructionRegister % 100; + + /* this is required because after the switch() + statement the 'i' counter is incremented of 1. */ + if(operationCode >= BRANCH) + --operand; + + switch(operationCode) { + case READ: + printf("Insert a word: "); + scanf("%d", &memory[operand]); + + break; + case WRITE: + printf("\nMemory location: %.2d\nWord: %d\nASCII: %c\n", + operand, memory[operand], memory[operand]); + break; + case LOAD: + accumulator = memory[operand]; + break; + case STORE: + memory[operand] = accumulator; + break; + + case ADD: + accumulator += memory[operand]; + + if(accumulator > +9999 || accumulator -9999) + err = 1; + + break; + case SUBTRACT: + accumulator -= memory[operand]; + + if(accumulator > +9999 || accumulator -9999) + err = 1; + + break; + case DIVIDE: + accumulator /= memory[operand]; + + if( !memory[operand] ) + err = 2; + + break; + case MULTIPLY: + accumulator *= memory[operand]; + + if(accumulator > +9999 || accumulator -9999) + err = 1; + + break; + + case BRANCH: + i = operand; + break; + case BRANCHNEG: + if(accumulator < 0) + i = operand; + + break; + case BRANCHZERO: + if(!accumulator) + i = operand; + + break; + + case HALT: + printf("*** Simpletron execution terminated ***\n"); + dump(accumulator, i, memory); + return 0; + + break; + case 0: + break; + + default: + printf("*** unknown error: %d\n", instructionRegister); + exit(-1); + } + + /* fatal errors check */ + if(err) { + switch(err) { + case 1: + printf("*** Out of the accumulator limit ***\n"); + break; + case 2: + printf("*** Attempt to divide by zero ***\n"); + break; + } + + printf("*** Simpletron execution abnormally terminated ***\n"); + dump(accumulator, i, memory); + exit(-1); + } + + + } /* end for (i) */ + + dump(accumulator, i, memory); + + return 0; +} /* E0F main */ + +/* Check if a "word" is correct */ +int checkword(int word, int size) +{ + if(word < 0 || word > 9999 || word % 100 >= size) { + return 1; + } + + switch(word / 100) { + case READ: + case WRITE: + case LOAD: + case STORE: + case ADD: + case SUBTRACT: + case DIVIDE: + case MULTIPLY: + case BRANCH: + case BRANCHNEG: + case BRANCHZERO: + case HALT: + case 0: + break; + default: + return 1; + + } /* end switch (word) */ + + return 0; + +} /* eof checkword() */ + +/* Show a dump of the current memory state */ +void dump(int acc, int icounter, int mem[]) +{ + int i, j; + + printf("\nREGISTERS:\n"); + printf("accumulator\t\t%c%.4d\n" + "instructionCounter\t%.2d\n" + "instructionRegister\t%c%.4d\n" + "operationCode\t\t%.2d\n" + "operand\t\t\t%.2d\n", + acc < 0 ? '-' : '+', acc < 0 ? -acc : acc, + icounter, mem[icounter] < 0 ? '-' : '+', + mem[icounter] < 0 ? -mem[icounter] : mem[icounter], + mem[icounter] / 100, mem[icounter] % 100); + + + printf("\nMEMORY:\n"); + + /* Print the header */ + printf("%3c", ' '); + for(i = 0; i < 10; i++) + printf("%5d ", i); + printf("\n"); + + for(i = 0; i < MEMSIZE; i += 10) { + printf("%.2d", i); + for(j = i; j < i+10; j++) { + printf(" %c%.4d", + mem[j] < 0 ? '-' : '+', mem[j] < 0 ? -mem[j] : mem[j]); + } + printf("\n"); + } + +} /* eof dump() */ + diff --git a/exercises/deitel/ch7/simpletron_base.c b/exercises/deitel/ch7/simpletron_base.c @@ -0,0 +1,183 @@ +/* Exercise 7.18 (a, b, and c) */ + +/* The Simpletron (and LMS) implementation */ + +#include <stdio.h> +#include <stdlib.h> + +#define MEMSIZE 100 +#define BUFSIZE 21 + +/* Input/Output */ +#define READ 10 +#define WRITE 11 + +/* Loading/Storing */ +#define LOAD 20 +#define STORE 21 + +/* Arithmetical */ +#define ADD 30 +#define SUBTRACT 31 +#define DIVIDE 32 +#define MULTIPLY 33 + +/* Reference and control */ +#define BRANCH 40 +#define BRANCHNEG 41 +#define BRANCHZERO 42 +#define HALT 43 + +void checkword(int word, int size); + +int main(void) +{ + int memory[MEMSIZE] = { 0 }; + int accumulator = 0, i; + + int m_loc, cmd; /* the memory location and the command */ + + int program[BUFSIZE] = { + + /* Calculate the sum of 2 numbers + +1009, +1010, +2009, +3110, + +4107, +1109, +4300, +1110, + +4300, +0000, +0000 */ + + /* Calculate the largest of 2 numbers + +1007, +1008, +2007, +3008, + +2109, +1109, +4300, +0000, + +0000, +0000 */ + + + /* 7.18 (a): take 10 numbers (in a loop with a dummy value) + and calculate its sum */ + /* + +1008, +2008, +4106, +3009, + +2109, +4000, +1109, +4300, + +0000, +0000 + */ + + /* 7.18 (b): take 7 numbers positive or negative (in a loop + with a counter) and calculate the media */ + /* + 7, 7, 1, +1020, +2020, + +3021, +2121, +2001, +3102, + +2101, +4212, +4003, +2021, + +3200, +2120, +1120, +4300, + +0000, +0000, +0000, +0000 + */ + + /* 7.18 (c): take a serie of numbers and determine and print + the largest. The first number readed set how many + values will be inserted */ + +1000, 1, +2000, +2117, + +2000, +3101, +2100, +4214, + +1018, +2018, +3117, +4104, +2018, +4003, + +2017, +1117, +4300 + }; + + /* Load the program into the memory */ + for(i = 0; i < BUFSIZE; i++) { + checkword(program[i], MEMSIZE); /* check the word */ + memory[i] = program[i]; /* passed - loaded */ + } + + /* Execute the program: i use BUFSIZE to optimize */ + for(i = 0; i < MEMSIZE; i++) { + m_loc = memory[i] % 100; + cmd = memory[i] / 100; + + /* this is required because after the switch() + statement the 'i' counter is incremented of 1. */ + if(cmd >= BRANCH) + --m_loc; + + switch(cmd) { + case READ: + printf("Insert a word: "); + scanf("%d", &memory[m_loc]); + + break; + case WRITE: + printf("\nMemory location: %d\nWord: %d\n", + m_loc, memory[m_loc]); + break; + case LOAD: + accumulator = memory[m_loc]; + break; + case STORE: + memory[m_loc] = accumulator; + break; + + case ADD: + accumulator += memory[m_loc]; + break; + case SUBTRACT: + accumulator -= memory[m_loc]; + break; + case DIVIDE: + accumulator /= memory[m_loc]; + break; + case MULTIPLY: + accumulator *= memory[m_loc]; + break; + + case BRANCH: + i = m_loc; + break; + case BRANCHNEG: + if(accumulator < 0) + i = m_loc; + + break; + case BRANCHZERO: + if(!accumulator) + i = m_loc; + + break; + + case HALT: + return 0; + + case 0: + break; + + default: + printf("simpletron: unknown error.\n"); + exit(-1); + } + } /* end for (i) */ + + return 0; +} /* E0F main */ + +/* check if a "word" is correct */ +void checkword(int word, int size) +{ + if(word < 0 || word > 9999 || word % 100 >= size) + printf("*** Simpletron: unkwown word: %d\n", word); + + switch(word / 100) { + case READ: + case WRITE: + case LOAD: + case STORE: + case ADD: + case SUBTRACT: + case DIVIDE: + case MULTIPLY: + case BRANCH: + case BRANCHNEG: + case BRANCHZERO: + case HALT: + case 0: + break; + default: + printf("*** Simpletron: unknown word: %d\n", word); + exit(-1); + + } /* end switch (word) */ + +} /* eof checkword() */ + diff --git a/exercises/deitel/ch8/4atof.c b/exercises/deitel/ch8/4atof.c @@ -0,0 +1,22 @@ +/* Exercise 8.8 */ + +#include <stdio.h> +#include <stdlib.h> + +int main(void) +{ + char s[8] = { 0 }; + int i; + float total = 0; + + for(i = 0; i < 4; i++) { + printf("Give me a string (int?): "); + gets(s); + total += atof(s); + } + + printf("The total is: %.2f\n", total); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/4atoi.c b/exercises/deitel/ch8/4atoi.c @@ -0,0 +1,21 @@ +/* Exercise 8.7 */ + +#include <stdio.h> +#include <stdlib.h> + +int main(void) +{ + char s[8] = { 0 }; + int i, total = 0; + + for(i = 0; i < 4; i++) { + printf("Give me a string (int?): "); + gets(s); + total += atoi(s); + } + + printf("The total is: %d\n", total); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/ascii.c b/exercises/deitel/ch8/ascii.c @@ -0,0 +1,24 @@ +/* Exercise 8.25 */ + +#include <stdio.h> + +int main(void) +{ + int code; + +/* Exercise 8.25: first step. + printf("Give me the ASCII code: "); + scanf("%d", &code); + + printf("The character is: %c\n", code); +*/ + + /* Exercise 8.25: final step. */ + printf("ASCII code\tASCII character\n"); + for(code = 0; code <= 255; code++) { + printf("%.3d\t%c\n", code, code); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/assprot.c b/exercises/deitel/ch8/assprot.c @@ -0,0 +1,30 @@ +/* Exercise 8.37 */ + +#include <stdio.h> +#include <string.h> + +#define NUMBERS 9 + +int main(void) +{ + char import[NUMBERS] = { 0 }; + int n = NUMBERS; + + printf("Give me the import: "); + gets(import); + while( (int)strlen(import) > NUMBERS ) { + printf("Error: too many numbers\n"); + printf("Give me the import: "); + gets(import); + } + + printf("Protect number: "); + n -= (int)strlen(import); + while(n--) + printf("*"); + + printf("%s\n", import); + + return 0; +} + diff --git a/exercises/deitel/ch8/chcmp.c b/exercises/deitel/ch8/chcmp.c @@ -0,0 +1,48 @@ +/* Exercise 8.5 */ + +#include <stdio.h> +#include <ctype.h> + +int main(void) +{ + char c; + + puts("Give me a char"); + c = getchar(); + putchar('\n'); + + /* Start the comparision */ + printf("%c %s an alpha character (%u)\n", + c, isalpha((int)c) ? "is" : "is not", isalpha((int)c)); + printf("%c %s an upper character (%u)\n", + c, isupper((int)c) ? "is" : "is not", isupper((int)c)); + printf("%c %s a lower character (%u)\n", + c, islower((int)c) ? "is" : "is not", islower((int)c)); + printf("%c %s a digit character (%u)\n", + c, isdigit((int)c) ? "is" : "is not", isdigit((int)c)); + printf("%c %s a hex digit character (%u)\n", + c, isxdigit((int)c) ? "is" : "is not", isxdigit((int)c)); + printf("%c %s an alnum character (%u)\n", + c, isalnum((int)c) ? "is" : "is not", isalnum((int)c)); + printf("%c %s a space character (%u)\n", + c, isspace((int)c) ? "is" : "is not", isspace((int)c)); + printf("%c %s a punctuation character (%u)\n", + c, ispunct((int)c) ? "is" : "is not", ispunct((int)c)); + printf("%c %s a printer character (%u)\n", + c, isprint((int)c) ? "is" : "is not", isprint((int)c)); + printf("%c %s a graphic character (%u)\n", + c, isgraph((int)c) ? "is" : "is not", isgraph((int)c)); + printf("%c %s a control character (%u)\n", + c, iscntrl((int)c) ? "is" : "is not", iscntrl((int)c)); + printf("%c %s a blank character (%u)\n", + c, isblank((int)c) ? "is" : "is not", isblank((int)c)); + printf("%c %s an ASCII character (%u)\n", + c, isascii((int)c) ? "is" : "is not", isascii((int)c)); + + printf("%c to upper is %c\n", c, toupper((int)c)); + printf("%c to lower is %c\n", c, tolower((int)c)); + printf("%c to ASCII is %c\n", c, toascii((int)c)); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/cmp2s.c b/exercises/deitel/ch8/cmp2s.c @@ -0,0 +1,31 @@ +/* Exercise 8.9 */ + +#include <stdio.h> +#include <string.h> + +int main(void) +{ + char s1[10]; + char s2[10]; + int val; + + printf("Give me a string (s1): "); + gets(s1); + printf("Give me another string (s2): "); + gets(s2); + + val = strcmp(s1, s2); + printf("s1 is "); + + if(!val) + printf("equal to"); + else if(val < 0) + printf("less then"); + else + printf("greater then"); + + printf(" s2\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/countwords.c b/exercises/deitel/ch8/countwords.c @@ -0,0 +1,43 @@ +/* Exercise 8.20 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +#define STRINGS 10 +#define BUF 254 + +int main(void) +{ + char string[STRINGS][BUF] = { { 0 } }, *tokp; + int i = 0, counter = 0; + + /* Take the strings */ + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + + while( atoi(string[i++]) != -1 ) { + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + } + + string[i - 1][0] = '\0'; /* Remove the '-1' */ + + for(i = 0; i < STRINGS; i++) { + tokp = strtok(string[i], " "); + + while( tokp != NULL ) { + ++counter; + tokp = strtok(NULL, " "); + } + + } + + if(!counter) + printf("There are no words!\n"); + else + printf("There are %d words!\n", counter); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/cruciverb_BROKEN.c b/exercises/deitel/ch8/cruciverb_BROKEN.c @@ -0,0 +1,234 @@ +/* Exercise 8.42 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <time.h> +#include <ctype.h> + +#define VER 12 +#define HOR (VER + (VER / 2)) + +#define BCELL 35 +#define WCELL 46 + +#define WORDS 98 + +void gridgen(char grid[][HOR][5], int ver, int hor); +void insnums(char grid[][HOR][5], int ver, int hor); +void showgrid(char grid[][HOR][5]); +void inswords(char grid[][HOR][5], char const * dict[WORDS * 2 + 1]); + +int main(void) +{ + char grid[VER][HOR][5] = { { { 0 } } }; + + char const * dict[WORDS * 2 + 1] = { + /* Words */ + "CLAUDIO", "PALERMO", "ITA", + "KATY", "NADIA", "DALILA", "CATRINE", "CRISTINA", + "QUINDICILETTERE", "QUESTESONOSEDICI", "SPACCO", + "TENLETTERS", "CINQUE", "THESIX", "FOUR", "SIX", + "SEX", "BSD", "UNIX", "GATTO", "MIAO", + "SIAMOATREDICI", "SIAMODIECI", "ALTREDIECI", + "QUATTORDICIBIS", "TRENTA", "OTTO", "UNODUETRE", + "PA", "ME", "EN", "CT", "TP", "CL", "SI", "RA", "AG", + "DODICIPAROLE", "UNGRUPPOUTENTI", "UNIXUSERGROUP", + "ILSETTE", "VENTOTTO", "LUG", "SUX", "OOP", "IP", "ID", + "EIGHTNUM", "NINEWORDS", "NOVENOVES", "QUESTESONODICIOTTO", + "DOMINATORIDELMONDO", "ABCDEFGHIJK", "THREE", "IDUE", "SET", + "POP", "DICATRENTATRE", "SHOCK", "BURNING", "DICIASSETTENUMERI", + "INUMERI", "ALICEADSLHOMETV4MB" "TEST", "FIGA", "QUESTAEVITA", + "META", "LAPROMESSA", "BLACK", "UNALTROTEN", "QUATTROGATTI", + "RET", "VELOCE", "POWER", "TAG", "RESTO", "ILLOOP", "SHUTDOWN", + "TESI", "LEGA", "NASO", "TANA", "SAGGEZZA", "CODA", "VITA", + "TESSERE", "LEANCORE", "GLIALBORI", "QUATTROCENTOVENTI", "CHECK", + "MARKED", "TV", "IPASSORICORSIVI", "GO", "VI", "SONOANCORADICIOTTO", + "TESTO", "CENTOVENTI", "SCACCOALLAREGINA", "QUADRO", + + /* Definitions */ + "Lo sviluppatore di questo software", + "La città dello sviluppatore di questo software :-)", + "Uno stato europeo", + "Nome di donna k..", "Nome di donna na..", "Nome di donna d..", + "Nome di donna: ca..", "Nome di donna cr..", "tanto per", + "le ho contate", "ciò che faccio :P", "in inglese", "un numero", + "un altro numero :-)", "un quattro di quattro lettere", + "il numero delle sue lettere è pari alla meta del suo valore", + "sicurezza extrema :P", "Il tipo di Unix migliore al mondo", + "un sistema operativo caso ;)", "fa miao", "lo fa il gatto", + "numero corrente", "quante dicono di essere?", "ce ne sono..", + "un articolo :p", "La metà delle sue lettere per 10 dà il suo nome", + "Il doppio delle sue lettere diviso 2 da il suo nome", "Da uno a nove" + "Palermo (sigla)", "Messina (sigla)", "Enna (sigla)", "Catania (sigla)", + "Trapani (sigla)", "Caltanissetta (sigla)", "Siracusa (sigla)", + "Ragusa (sigla)", "Agrigento (sigla)", "Tante parole quante lettere su..", + "UUG", "UUG (sigla)", "Un numero", "Aggiungi *20* e dividi per *due*", + "Gruppo utenti linux", "Questo non funziona..", + "Programmazione orientata agli oggetti", "Internet Protocol", + "Identification number", "L'otto ;)", "Nove parole", + "Nove nove al plurale :P", "Lo dice chi le conta", "Io e Claudio ;)", + "Le prime undici", "Tre con cinque", + "Anche se tanti, solo due.. con 4 (lol)", + "Si usa per impostare qualcosa su qualsiasi shell", + "In assembler si usa per rimuovere..", "Lo dice il dottore", + "effetto provato dall'hiphop di Claudio :-)", "Masterizzando", + "Il numero di lettere in esso scritto corrisponde alle sue lettere (uhm?)", + "Una generalizzazione matematica..", "prova", "ce n'è in abbondanza :-)", + "Lo dice che stà bene", "La insegue il viaggiatore", + "Somiglia a un giuramento :-)", "Nero", "Ancora uno", "Lo sono in pochi", + "Valore di ritorno", "Claudio scrive..", "Accende il PC", + "L'html ne è pieno", "L'operatore col simbolo di percentuale", + "Il *ciclo* storpiato", "Arresto del sistema", "La si sà per la laurea", + "L'insieme dei materiale che costituiscono un oggetto", + "Lo possiede chi ci sa fare", "Vi rimane chi si nasconde", + "La possiede chi apprende dalle esperienze altrui", + "Il gatto ne ha più di una", "L'uomo ne ha una soltanto", + "Si presentano all'ingresso", "Le navi ne hanno almeno due", + "Quando tutto cominciò", + "140 più il numero delle sue lettere * 3 dà il numero in esso scritto :-)" + "Controllo", "Spuntato, visitato", "La vecchia scatola magica", + "Una solo può generarne molti", "Andare", "L'editor per eccellenza ;)", + "Ne ho aggiunte ancora", "Lo scrive il cantante", "60 * 2 :)", + "lo si fa alla moglie del re", + "Lo si trova in gallerie d'arte e in ogni videogame :-)" + }; + + srand( time(NULL) ); + + gridgen(grid, VER, HOR); + /* inswords(grid, dict); */ + showgrid(grid); + + return 0; +} /* E0F main */ + +/* ehm.. show the grid :-) */ +void showgrid(char grid[][HOR][5]) +{ + int i, j; + for(i = 0; i < VER; i++) { + for(j = 0; j < HOR; j++) + printf("%4s", grid[i][j]); + printf("\n"); + } +} + +/* create an empty grid */ +void gridgen(char grid[][HOR][5], int ver, int hor) +{ + int i, j; + + for(i = 0; i < ver; i++) { + for(j = 0; j < hor; j++) { + if( !(rand() % 5) ) + *grid[i][j] = BCELL; + else + *grid[i][j] = WCELL; + } + } + + insnums(grid, ver, hor); + +} /* eof gridgen() */ + +/* insert the numbers to an empty grid */ +void insnums(char grid[][HOR][5], int ver, int hor) +{ + int i, j, num = 1; + + for(i = 0; i < ver; i++) { + for(j = 0; j < hor; j++) { + + if(*grid[i][j] == BCELL) + continue; + + if( /* Toggle the closed cells */ + (*grid[i - 1][j] == BCELL || !i) && + (*grid[i + 1][j] == BCELL || i == ver - 1) && + (*grid[i][j + 1] == BCELL || j == hor - 1) && + (*grid[i][j - 1] == BCELL || !j) + ) { + + if(j < hor - 1) { + *grid[i][j + 1] = WCELL; + --j; + } + else if( i < ver - 1 ) { + *grid[i + 1][j] = WCELL; + } + else { /* Latest cell down/right */ + *grid[i][j] = BCELL; + } + } + + else if( /* Check the cell to put it the number */ + ((*grid[i][j - 1] == BCELL || !j) && + (*grid[i][j + 1] != BCELL && j < hor - 1)) || + ((*grid[i - 1][j] == BCELL || !i) && + (*grid[i + 1][j] != BCELL && i < ver - 1)) + ) { + + if( num <= 9 ) { + *grid[i][j] = num + (int)'0'; + } + else if(num <= 99) { + grid[i][j][0] = num / 10 % 10 + '0'; + grid[i][j][1] = num % 10 + '0'; + } + else if(num <= 999) { + grid[i][j][0] = num / 100 % 10 + '0'; + grid[i][j][1] = num / 10 % 10 + '0'; + grid[i][j][2] = num % 10 + '0'; + } + ++num; + + } + } + } +} /* eof insnums() */ + +/* Insert the words to the cruciverb */ +void inswords(char grid[][HOR][5], char const * dict[WORDS * 2 + 1]) +{ + int i, j, k, x, len; + int done[WORDS] = { 0 }; + + for(i = 0; i < VER; i++) { + for(j = 0, len = 0; j <= HOR; j++) { + + /* Found a delimiter (BCELL or right border) */ + if( (*grid[i][j] == BCELL || j == HOR) && len ) { + + k = -1; /* Count the string */ + while(++k < WORDS * 2) { + if( *dict[k] != 1 && + (int)strlen(dict[k]) == len && + done[k] != '*' ) + break; + } + + /* Overwrite the token with the string */ + if(k < WORDS) { + done[k] = '*'; /* Marked as inserted */ + + x = k; + for(k = 0; k < len; k++) { + + grid[i][j - len + k][0] = ' '; /* clean */ + grid[i][j - len + k][1] = dict[x][k]; + grid[i][j - len + k][2] = '\0'; /* clean */ + + + } + } + + len = 0; + } + else { /* Increment the token size */ + ++len; + } + } + } +} /* eof inswords() */ + diff --git a/exercises/deitel/ch8/dataconv.c b/exercises/deitel/ch8/dataconv.c @@ -0,0 +1,65 @@ +/* Exercise 8.36 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +int main(void) +{ + char data[11] = { 0 }, *tokp; + + printf("Insert data: "); + gets(data); + + tokp = strtok(data, "/"); + printf("%d ", atoi(tokp)); + + tokp = strtok(NULL, "/"); + + switch(atoi(tokp)) { + case 1: + printf("January"); + break; + case 2: + printf("February"); + break; + case 3: + printf("March"); + break; + case 4: + printf("April"); + break; + case 5: + printf("Maj"); + break; + case 6: + printf("June"); + break; + case 7: + printf("July"); + break; + case 8: + printf("August"); + break; + case 9: + printf("September"); + break; + case 10: + printf("October"); + break; + case 11: + printf("November"); + break; + case 12: + printf("December"); + break; + default: + printf("Unknown month"); + } + + tokp = strtok(NULL, "/"); + printf(" 19%d\n", atoi(tokp)); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/diffwordc.c b/exercises/deitel/ch8/diffwordc.c @@ -0,0 +1,123 @@ +/* Exercise 8.34 (c) */ + +/* NOTE: orderall() is not so "smart" */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <ctype.h> + +#define SIZE 10 +#define BUF 254 +#define MAX 30 + +int ison(char s[][BUF], char *word); +char *sclean(char *s); +void orderall(char s[][BUF], int n[MAX]); + + +int main(void) +{ + char string[SIZE][BUF] = { { 0 } }, *tokp; + int i, idx, midx = 0, counter[MAX] = { 0 }; + char sstr[MAX][BUF] = { { 0 } }; + + /* Take the strings */ + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + + while( atoi(string[i++]) != EOF ) { + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + } + + string[i - 1][0] = '\0'; /* Remove the '-1' */ + + for(i = 0; i < SIZE; i++) { + + /* count the words */ + tokp = strtok(string[i], " "); + while( tokp != NULL ) { + + if( (idx = ison(sstr, tokp)) > midx) + midx = idx; + + if(idx == -1) { + strcpy(sstr[++midx], tokp); + counter[midx] = 1; + } + else { + ++counter[idx]; + } + + tokp = strtok(NULL, " "); + } + } + + orderall(sstr, counter); /* Order the output */ + + /* Show the results */ + printf("\nTABLE..\n\n%4s%31s\n", "Word", "Occurrences"); + printf("-----------------------------------\n"); + for(i = 0; i < MAX; i++) { + if( strlen(sstr[i]) ) + printf("%c%-13s\t\t%11.2d\n", + toupper((int)sstr[i][0]), &sstr[i][1], counter[i]); + } + + printf("\n"); + + return 0; +} /* E0F main */ + +/* locate word to s[][] strings */ +int ison(char s[][BUF], char *word) +{ + int i; + + for(i = 0; i < MAX; i++) { + if( ! strcmp(s[i], sclean(word)) ) + return i; + } + + return -1; +} /* eof ison() */ + +/* clean a string :-) */ +char *sclean(char *s) +{ + int i; + + for(i = 0; s[i] != '\0'; i++) + s[i] = !ispunct((int)s[i]) ? tolower((int)s[i]) : ' '; + + return s; + +} /* eof sclean() */ + +/* Order alphabetically s and swap the indexes in the n array */ +void orderall(char s[][BUF], int n[MAX]) +{ + int i, j, num; + char string[BUF] = { 0 }; + + for(i = 0; i < MAX - 1; i++) { + for(j = 0; j < MAX - 1; j++) { + + if( strcmp(s[j], s[j + 1]) > 0 ) { + + /* swap the strings */ + strcpy(string, s[j]); + strcpy(s[j], s[j + 1]); + strcpy(s[j + 1], string); + + /* swap the numbers */ + num = n[j]; + n[j] = n[j + 1]; + n[j + 1] = num; + } + + } + } +} /* eof orderall */ + diff --git a/exercises/deitel/ch8/filter-ed.c b/exercises/deitel/ch8/filter-ed.c @@ -0,0 +1,35 @@ +/* Exercise 8.24 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <ctype.h> + +#define SIZE 10 +#define BUF 255 + +int main(void) +{ + char strings[SIZE][BUF]; + int i = 0, j; + + printf("Give me a string (%d to end): ", EOF); + gets(strings[i]); + + while( atoi(strings[i++]) != EOF ) { + printf("Give me a string (%d to end): ", EOF); + gets(strings[i]); + + for(j = 0; j < (int)strlen(strings[i]); j++) + strings[i][j] = tolower((int)strings[i][j]); + } + + for(i = 0; i < SIZE; i++) { + /* If the current string terminate with "ed", then print it */ + if( !strncmp( &strings[i][ strlen(strings[i]) - 2 ], "ed", 2 ) ) + printf("%s\n", strings[i]); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/filterb.c b/exercises/deitel/ch8/filterb.c @@ -0,0 +1,30 @@ +/* Exercise 8.23 */ + +#include <stdio.h> +#include <stdlib.h> +#include <ctype.h> + +#define SIZE 10 +#define BUF 255 + +int main(void) +{ + char strings[SIZE][BUF]; + int i = 0; + + printf("Give me a string (%d to end): ", EOF); + gets(strings[i]); + + while( atoi(strings[i++]) != EOF ) { + printf("Give me a string (%d to end): ", EOF); + gets(strings[i]); + } + + for(i = 0; i < SIZE; i++) { + if( tolower((int)strings[i][0]) == 'b') + printf("%s\n", strings[i]); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/hl.c b/exercises/deitel/ch8/hl.c @@ -0,0 +1,27 @@ +/* Exercise 8.6 */ + +#include <stdio.h> +#include <ctype.h> +#include <string.h> + +int main(void) +{ + int i; + char s[100]; + + printf("Give me a string: "); + gets(s); + + printf("Upper: "); + for(i = 0; (unsigned)i < strlen(s); i++) + printf("%c", toupper((int)s[i])); + putchar('\n'); + + printf("Lower: "); + for(i = 0; (unsigned)i < strlen(s); i++) + printf("%c", tolower((int)s[i])); + putchar('\n'); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/justify.c b/exercises/deitel/ch8/justify.c @@ -0,0 +1,47 @@ +/* Exercise 8.35 */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define SIZE 30 +#define BUF 255 + +#define C4L 65 /* Characters for line */ + +int main(void) +{ + int i = 0, j; + char string[SIZE][BUF] = { { 0 } }; + + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + while( atoi(string[i++]) != EOF && i < SIZE ) { + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + } + string[i - 1][0] = '\0'; /* remove the EOF */ + + /* loop the strings */ + for(i = 0; i < SIZE && strlen(string[i]); i++) { + + /* print the current line formatted */ + printf("%10c", ' '); /* Margin left */ + for(j = 1; j <= BUF && j <= (int)strlen(string[i]); j++) { + printf("%c", string[i][j - 1]); + + if( !(j % C4L) ) { /* Characters for line */ + printf("\n%10c", ' '); /* Margin left */ + + /* Toggle the spaces and the newlines */ + if(string[i][j] == ' ' || string[i][j + 1] == '\n') + ++j; + } + } + printf("%10c\n", ' '); /* Margin right */ + + } /* end for (i) */ + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/limerick.c b/exercises/deitel/ch8/limerick.c @@ -0,0 +1,106 @@ +/* Exercise 8.12 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <ctype.h> +#include <time.h> + +#define LIMS 5 +#define WORDS 5 /* Words for string (article, noun, etc.) */ +#define SIZE 30 + +int main(void) +{ + int i, j, k, x, l, rloop, rhymes[5] = { 0 }; + char tmp_s[SIZE], phrase[SIZE]; + const char * tokp; + + const char * const article = "the a one some any"; + const char * const noun = "boy girl do town car"; + const char * const verb = "drove jumped ran walked skipped"; + const char * const preposition = "to from over under on"; + + /* Store the memory address for each string */ + const char * const string[6] = { + article, noun, verb, + preposition, article, noun + }; + + srand( time(NULL) ); + + for(l = 0; l < LIMS; l++) { + + /* loop the phrases */ + for(i = 0; i < 5; i++) { + + /* loop the *string[] */ + for(j = 0; j < 6; j++) { + + /* Create the phrase */ + rloop = 1 + rand() % WORDS; + + for(k = 0; k < rloop && tokp != NULL; k++) { + if(!k) { + strcpy(tmp_s, string[j]); + tokp = strtok(tmp_s, " "); + } + else tokp = strtok(NULL, " "); + + if(i && j == 5) { + /* Check the rhymes */ + for(x = 0; x < 5; x++) { + if(!x) { + strcpy(tmp_s, string[j]); + tokp = strtok(tmp_s, " "); + } + else tokp = strtok(NULL, " "); + + /* set the rhymes */ + if(i == 1) { + if(tokp[strlen(tokp) - 1] == rhymes[0]) { + break; + } + } + else if(i == 2) { + if(tokp[strlen(tokp) - 1] != rhymes[0]) + break; + } + else if(i == 3) { + if(tokp[strlen(tokp) - 1] == rhymes[2]) + break; + } + else if(i == 4) { + if(tokp[strlen(tokp) - 1] == rhymes[0]) + break; + } + + } + } + } + + /* Append the token in the phrase */ + if(!j) + strcpy(phrase, tokp); + else { + strcat(phrase, tokp); + } + strcat(phrase, " "); + } + rhymes[i] = phrase[strlen(phrase) - 2]; + strcat(phrase, "\0"); /* "Close" the string */ + + /* Add some graphic stuff :-) */ + phrase[0] = toupper((int)phrase[0]); + phrase[strlen(phrase) - 1] = '.'; + + printf("%2d: %s\n", i + 1, phrase); + + } + + printf("\n"); + } /* end for (l) */ + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/limerick2.c b/exercises/deitel/ch8/limerick2.c @@ -0,0 +1,126 @@ +/* Exercise 8.12 */ + +/* A bad implementation of the limerick generator */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <ctype.h> +#include <time.h> + +#define LIMS 5 +#define WORDS 8 /* Words for string (article, noun, etc.) */ +#define SIZE 90 + +char *strrpbrk(const char * const s, const char * const charset); + +int main(void) +{ + int i, j, k, x, l, rloop, rhymes[5] = { 0 }; + char tmp_s[SIZE], phrase[SIZE]; + const char matches[] = "aeiou", *tokp; + + const char * const article = "the a one some any each no that"; + const char * const noun = "stupid girl guy town car dog cat day"; + const char * const verb = "drove looking ran walked skipped found seen borned"; + const char * const preposition = "to from over under on by in up"; + + /* Store the memory address for each string */ + const char * const string[6] = { + article, noun, verb, + preposition, article, noun + }; + + srand( time(NULL) ); + + for(l = 0; l < LIMS; l++) { + + /* loop the phrases */ + for(i = 0; i < 5; i++) { + + /* loop the *string[] */ + for(j = 0; j < 6; j++) { + + /* Create the phrase */ + rloop = 1 + rand() % WORDS; + + for(k = 0; k < rloop && tokp != NULL; k++) { + if(!k) { + strcpy(tmp_s, string[j]); + tokp = strtok(tmp_s, " "); + } + else tokp = strtok(NULL, " "); + + if(i && j == 5) { + /* Check the rhymes */ + for(x = 0; x < 5; x++) { + if(!x) { + strcpy(tmp_s, string[j]); + tokp = strtok(tmp_s, " "); + } + else tokp = strtok(NULL, " "); + + /* set the rhymes */ + if(i == 1) { + if(*strrpbrk(tokp, matches) == rhymes[0]) { + break; + } + } + else if(i == 2) { + if(*strrpbrk(tokp, matches) != rhymes[0]) + break; + } + else if(i == 3) { + if(*strrpbrk(tokp, matches) == rhymes[2]) + break; + } + else if(i == 4) { + if(*strrpbrk(tokp, matches) == rhymes[0]) + break; + } + } + } + } + + /* Append the token in the phrase */ + if(!j) + strcpy(phrase, tokp); + else + strcat(phrase, tokp); + strcat(phrase, " "); + } + rhymes[i] = *strrpbrk(phrase, matches); + strcat(phrase, "\0"); /* "Close" the string */ + + /* Add some graphic stuff :-) */ + phrase[0] = toupper((int)phrase[0]); + phrase[strlen(phrase) - 1] = '.'; + + printf("%2d: %s\n", i + 1, phrase); + + } + + printf("\n"); + + } /* end for (l) */ + + return 0; +} /* E0F main */ + +/* The same of strbprk(3) except that the check + * is done from end to start of string pointer. */ +char * strrpbrk(const char * const s, const char * const charset) +{ + int i; + char *ret; + + for(i = strlen(s) - 1; i >= 0 ; i--) { + if( (ret = strchr(charset, s[i])) != NULL ) { + break; + } + } + + return ret; + +} /* eof strrbprk() */ + diff --git a/exercises/deitel/ch8/metrics3.c b/exercises/deitel/ch8/metrics3.c @@ -0,0 +1,148 @@ +/* Exercise 8.40 */ + +#include <stdio.h> +#include <string.h> +#include <ctype.h> +#include <stdlib.h> + +#define TYPES 24 +#define SIZE 254 + +char *getkey(char *s, char units[][TYPES][11], int *idx); + +int main(void) +{ + int idx, wordm = 0, loop = 0; + char class, *tokp, string[SIZE], word[12]; + double tot, divs; + + char units[3][TYPES][11] = { + { /* The labels */ + "millimetr", "centimetr", "decimetr", "metr", "kilometr", + "millilitr", "centilitr", "decilitr", "litr", "decalitr", "ettolitr", + "milligramm", "gramm", "decagramm", "kilogramm", "tonnellat", "quintal", + "gallon", "pollic", "pied", "libbr", "yard", + + /* Word meters */ + "quart", "dozzin" }, + + { /* The values */ + "1", "10", "100", "1000", "1000000", + "1", "10", "100", "1000", "10000", "100000", + "1", "1000", "10000", "1000000", "10000000", "100000000", + + /* 3.7853 "2.54" "30.48" "0.4536" "0.9144" */ + "3785", "25.4", "304.8", "4.536", "914.4", + + /* Word meters */ + "4", "12" }, + + { /* The classes */ + "A", "A", "A", "A", "A", + "B", "B", "B", "B", "B", "B", + "C", "C", "C", "C", "C", "C", + "B", "A", "A", "C", "A", + + /* Word meters: 0 divide, 1 multiply */ + "0", "1" } + }; + + printf("Please, write your answer: "); + gets(string); + + tokp = getkey(string, units, &idx); + while(tokp != NULL) { + + /* Check for the "word meters": un quarto, una dozzina, etc. */ + if( !memcmp(tokp, "un", 2) ) + strcpy(word, "1"); + else + strcpy(word, tokp); + + if( *units[2][idx] == '0' || *units[2][idx] == '1' ) { + wordm = 1; /* Mark the "operation" as "Word meter" */ + strcat(word, " "); + + if( (tokp = getkey(NULL, units, &idx)) != NULL ) + strcat(word, tokp); + else + break; + } + + switch(++loop) { + case 1: + divs = atof(units[1][idx]); + class = *units[2][idx]; + break; + case 2: + tot = atof(word); + break; + case 3: + + /* If there is a word meter.. */ + if(wordm) { /* Marked operation */ + if( !memcmp(word, "quart", 5) ) + tot *= atof(units[1][idx]) / 4; + else + tot *= atof(units[1][idx]) * 12; + } + else + tot *= atof(units[1][idx]); + + if(class != *units[2][idx]) { + printf("error: conflict in conversion types\n"); + return -1; + } + + break; + default: + printf("unknown error: please fix this\n"); + break; + } + + /* DeBuG + printf("case[%d]===[ word: %s\n", loop, word); + */ + + tokp = getkey(NULL, units, &idx); + } + + if(loop != 3) + printf("Are you forgetting something? :-)\n"); + else + printf("Results: %.2f\n", tot / divs); + + return 0; +} /* E0F main */ + +/* locate and tokenize the units[][][] elements */ +char *getkey(char *s, char units[][TYPES][11], int *idx) +{ + int i; + char *tokp; + static char *prev_s; + + prev_s = s; + + tokp = strtok( s == NULL ? prev_s : s, " "); + while(tokp != NULL) { + + for(i = 0; i < TYPES; i++) { + if( ! memcmp(tokp, units[0][i], strlen(units[0][i])) || + isdigit((int)*tokp) || !memcmp(tokp, "un", 2) ) { + + /* Toggle the '?' at end of string */ + if( tokp[strlen(tokp) - 1] == '?' ) + tokp[strlen(tokp) - 1] = '\0'; + + if(idx != NULL) *idx = i; + return tokp; + } + } + + tokp = strtok(NULL, " "); + } + + return NULL; +} /* eof getkey() */ + diff --git a/exercises/deitel/ch8/mkphrase.c b/exercises/deitel/ch8/mkphrase.c @@ -0,0 +1,63 @@ +/* Exercise 8.11 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <ctype.h> +#include <time.h> + +#define PHRASES 20 +#define SIZE 30 + +int main(void) +{ + int i, j, k; + char tmp_s[SIZE], phrase[SIZE]; + const char * tokp; + + const char * const article = "the a one some any"; + const char * const noun = "boy girl do town car"; + const char * const verb = "drove jumped ran walked skipped"; + const char * const preposition = "to from over under on"; + + /* Store the memory address for each string */ + const char * const string[6] = { + article, noun, verb, + preposition, article, noun + }; + + srand( time(NULL) ); + + /* loop the phrases */ + for(i = 0; i < PHRASES; i++) { + + /* loop the *string[] */ + for(j = 0; j < 6; j++) { + + /* Copy the string and tokenize it */ + strcpy(tmp_s, string[j]); + tokp = strtok(tmp_s, " "); + for(k = rand() % 5; k && tokp != NULL; k--) + tokp = strtok(NULL, " "); + + /* Append the token in the phrase */ + if(!j) + strcpy(phrase, tokp); + else { + strcat(phrase, tokp); + } + strcat(phrase, " "); + } + strcat(phrase, "\0"); /* "Close" the string */ + + /* Add some graphic stuff :-) */ + phrase[0] = toupper((int)phrase[0]); + phrase[strlen(phrase) - 1] = '.'; + + printf("Phrase %2d: %s\n", i+1, phrase); + + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/morse b/exercises/deitel/ch8/morse Binary files differ. diff --git a/exercises/deitel/ch8/morse.c b/exercises/deitel/ch8/morse.c @@ -0,0 +1,118 @@ +/* Exercise 8.39 */ + +#include <stdio.h> +#include <string.h> +#include <ctype.h> + +#define SIZE 254 +#define CHARS 39 + +void tomorse(char *string, char table[][CHARS][7]); +void toeng(char *string, char table[][CHARS][7]); + +int main(void) +{ + char string[SIZE] = { 0 }; + char table[2][CHARS][7] = { + + /* Morse code [A,Z] */ + { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", + ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", + "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", + + /* Numbers [0,9] */ + "-----", ".----", "..---", "...--", "....-", ".....", "-....", + "--...", "---..", "----.", + + /* Fullstop, comma and query */ + ".-.-.-", "--..--", "..--.." }, + + /* English charset [A,Z] */ + { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + + /* Numbers [0,9] */ + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", + + /* Fullstop, comma and query */ + ".", ",", "*" } + }; + + printf("Give me an english word: "); + gets(string); + tomorse(string, table); + + printf("\nGive me a morse code: "); + gets(string); + toeng(string, table); + + printf("\n"); + + return 0; +} /* E0F main */ + +/* Print a string converted to morse */ +void tomorse(char *string, char table[][CHARS][7]) +{ + int i, j, c; + char *tokp; + + tokp = strtok(string, " "); + while(tokp != NULL) { + c = 0; + + for(i = 0; i < (int)strlen(tokp); i++) { + for(j = 0; j < CHARS; j++) { + if ( toupper((int)tokp[i]) == *table[1][j] ) { + printf("%s", table[0][j]); + c = 1; + break; + } + } + + /* Unknown characters */ + if(!c) + printf("?"); + + printf(" "); + } + + printf(" "); + tokp = strtok(NULL, " "); + } + +} /* eof toeng() */ + +/* Print a string converted to english */ +void toeng(char *string, char table[][CHARS][7]) +{ + int i, c; + char *tokp; + + tokp = strtok(string, " "); + while(tokp != NULL) { + c = 0; + + for(i = 0; i < CHARS; i++) { + if( !(memcmp(tokp, table[0][i], + strlen(tokp) > strlen(table[0][i]) ? + strlen(tokp) : strlen(table[0][i]) )) ) { + + printf("%s", table[1][i]); + c = 1; + break; + } + } + + /* Unknown characters */ + if(!c) + printf("?"); + + if( !(strncmp((tokp + strlen(tokp) + 1), " ", 2)) ) + printf(" "); + + tokp = strtok(NULL, " "); + } + +} /* eof toeng() */ + diff --git a/exercises/deitel/ch8/myctype.c b/exercises/deitel/ch8/myctype.c @@ -0,0 +1,177 @@ +/* Exercise 8.26 */ + +#include <stdio.h> + +int isdigit(int c); +int isalpha(int c); +int isalnum(int c); +int isxdigit(int c); +int islower(int c); +int isupper(int c); +int tolower(int c); +int toupper(int c); +int isspace(int c); +int iscntrl(int c); +int ispunct(int c); +int isprint(int c); +int isgraph(int c); + +int main(void) +{ + char c; + + printf("Give me a char: "); + scanf("%c", &c); + + printf("The char %c (%d) %s %s\n", c, c, + isdigit(c) ? "is" : "is not", "a digit"); + + printf("The char %c (%d) %s %s\n", c, c, + isalpha(c) ? "is" : "is not", "alphabetic"); + + printf("The char %c (%d) %s %s\n", c, c, + isalnum(c) ? "is" : "is not", "alphanumeric"); + + printf("The char %c (%d) %s %s\n", c, c, + isxdigit(c) ? "is" : "is not", "hexadecimal"); + + printf("The char %c (%d) %s %s\n", c, c, + islower(c) ? "is" : "is not", "lower"); + + printf("The char %c (%d) %s %s\n", c, c, + isupper(c) ? "is" : "is not", "upper"); + + printf("The char %c (%d) to lower is %c\n", c, c, tolower(c)); + printf("The char %c (%d) to upper is %c\n", c, c, toupper(c)); + + printf("The char %c (%d) %s %s\n", c, c, + iscntrl(c) ? "is" : "is not", "of control"); + + printf("The char %c (%d) %s %s\n", c, c, + ispunct(c) ? "is" : "is not", "a punctuation"); + + printf("The char %c (%d) %s %s\n", c, c, + isprint(c) ? "is" : "is not", "printing"); + + printf("The char %c (%d) %s %s\n", c, c, + isspace(c) ? "is" : "is not", "a space"); + + printf("The char %c (%d) %s %s\n", c, c, + isgraph(c) ? "is" : "is not", "a graph"); + + return 0; + +} /* E0F main */ + +/* + * All the follow functions return true if the + * test pass and false if the test don't pass. +*/ + +/* Check if c is a decimal character */ +int isdigit(int c) +{ + if( c >= 48 && c <= 59 ) + return 1; /* True */ + return 0; /* False */ + +} /* eof isdigit() */ + +/* Check if c is an alphanumeric character */ +int isalpha(int c) +{ + if( islower(c) || isupper(c) ) + return 1; /* True */ + return 0; /* False */ +} /* eof isaplha() */ + +/* Check if c is an alphanumeric character */ +int isalnum(int c) +{ + if( isalpha(c) || isdigit(c) ) + return 1; /* True */ + return 0; /* False */ +} /* eof isalnum() */ + +/* Check if c is a hexadecimal character */ +int isxdigit(int c) +{ + if( isdigit(c) || (tolower(c) >= 97 && tolower(c) <= 102) ) + return 1; /* True */ + return 0; /* False */ +} /* eof isxdigit() */ + +/* Check if c is a lowercase character */ +int islower(int c) +{ + if( c >= 97 && c <= 122 ) + return 1; /* True */ + return 0; /* False */ +} /* eof islower() */ + +/* Check if c is an uppercase character */ +int isupper(int c) +{ + if( c >= 65 && c <= 90 ) + return 1; /* True */ + return 0; /* False */ +} /* eof isupper() */ + +/* If c is upper then will be converted + * to lower else nothing will be done. */ +int tolower(int c) +{ + if( isupper(c) ) + return c + 32; + return c; +} /* eof tolower() */ + +/* If c is lower then will be converted + * to upper else nothing will be done. */ +int toupper(int c) +{ + if( islower(c) ) + return c - 32; + return c; +} /* eof toupper() */ + +/* Check if c is a whitespace character */ +int isspace(int c) +{ + if( (c >= 9 && c <= 13) || c == 32 ) + return 1; /* True */ + return 0; /* False */ +} /* eof isspace() */ + +/* Check if c is a control character */ +int iscntrl(int c) +{ + if( c < 32 || c > 126 ) + return 1; /* True */ + return 0; /* False */ +} /* eof iscntrl() */ + +/* Check if c is a punctuation character: exlude the '(' and ')' */ +int ispunct(int c) +{ + if( isprint(c) && c != 40 && c != 41 ) + return 1; /* True */ + return 0; /* False */ +} /* eof ispunct() */ + +/* Check if c is a printing character */ +int isprint(int c) +{ + if( !iscntrl(c) ) + return 1; /* True */ + return 0; /* False */ +} /* eof isprint() */ + +/* Check if c is a graph character: exclude the space (' ') */ +int isgraph(int c) +{ + if( isprint(c) && c != 32 ) + return 1; /* True */ + return 0; /* False */ +} + diff --git a/exercises/deitel/ch8/mystrcnp.c b/exercises/deitel/ch8/mystrcnp.c @@ -0,0 +1,85 @@ +/* Exercise 8.28 */ + +#include <stdio.h> +#include <string.h> + +char *strcpy(char *s1, const char *s2); +char *strncpy(char *s1, const char *s2, size_t n); +char *strcat(char *s1, const char *s2); +char *strncat(char *s1, const char *s2, size_t n); + +int main(void) +{ + char string1[50] = "this is the first string"; + char string2[] = " and this is the 2nd :-)"; + + printf("BeFoRe\n\tstring1[] = %s\n\tstring2[] = %s\n", string1, string2); + + /* Insert the function here */ + + printf("\naFTeR\n\tstring1[] = %s\n\tstring2[] = %s\n", string1, string2); + + + return 0; +} /* E0F main */ + +/* Copy s2 to s1 and return s1 */ +char *strcpy(char *s1, const char *s2) +{ + int i; + + for(i = 0; ( s1[i] = s2[i] ) != '\0'; i++); + + /* Second version + for(i = 0; ( *(s1 + i) = *(s2 + i) ) != '\0'; i++); + */ + + return s1; + +} /* eof strcpt(1) */ + +/* Copy n characters from s2 to s1 and return s1 */ +char *strncpy(char *s1, const char *s2, size_t n) +{ + int i; + + for(i = 0; i < (int)n; i++) { + if( ( s1[i] = s2[i] ) == '\0' ) + /* Second version + if( ( *(s1 + i) = *(s2 + i) ) == '\0' ) + */ + break; + } + + return s1; +} /* eof strncpy() */ + +/* Append s2 to s1 and return s1 */ +char *strcat(char *s1, const char *s2) +{ + int i, j = (int)strlen(s1); + + for(i = 0; ( s1[j + i] = s2[i] ) != '\0'; i++); + /* Second version + for(i = 0; ( *(s1 + j + i) = *(s2 + i) ) != '\0'; i++); + */ + + return s1; +} /* eof strcat() */ + +/* Append n characters from s2 to s1 and return s1 */ +char *strncat(char *s1, const char *s2, size_t n) +{ + int i, j = (int)strlen(s1); + + for(i = 0; i < (int)n; i++) { + if( (s1[i + j] = s2[i]) == '\0') + /* Second version + if( ( *(s1 + i + j) = *(s2 + i) ) == '\0') + */ + break; + } + + return s1; +} /* eof strncat() */ + diff --git a/exercises/deitel/ch8/mystrcomp.c b/exercises/deitel/ch8/mystrcomp.c @@ -0,0 +1,70 @@ +/* Exercise 8.30 */ + +/* WRONG!! WRONG!! WRONG!! */ + +#include <stdio.h> + +int strcmp(const char *s1, const char *s2); +int strncmp(const char *s1, const char *s2, size_t n); + +int main(void) +{ + char string1[] = "abcdef"; + char string2[] = "abcdea"; + + printf("strcmp() = %d\n", strcmp(string1, string2) ); + printf("strncmp() = %d\n", strncmp(string1, string2, 4) ); + + return 0; +} /* E0F main */ + +/* Compare two strings */ +int strcmp(const char *s1, const char *s2) +{ + int i; + long n1 = 0, n2 = 0; + + for(i = 0; s1[i] != '\0'; i++) + n1 += s1[i]; + + for(i = 0; s2[i] != '\0'; i++) + n2 += s2[i]; + + /* Second version + for(i = 0; *(s1 + i) != '\0'; i++) + n1 += *(s1 + i); + + for(i = 0; *(s2 + i) != '\0'; i++) + n2 += *(s2 + i); + */ + + return n1 - n2; + +} /* eof strcmp() */ + +/* Compare n characters of two strings */ +int strncmp(const char *s1, const char *s2, size_t n) +{ + int i; + long n1 = 0, n2 = 0; + + for(i = 0; i < (int)n; i++) { + if( s1[i] == '\0' ) + break; + + n1 += s1[i]; + n2 += s2[i]; + + /* Second version + if( *(s1 + i) == '\0' ) + break; + + n1 += *(s1 + i); + n2 += *(s2 + i); + */ + } + + return n1 - n2; + +} + diff --git a/exercises/deitel/ch8/mystrconv.c b/exercises/deitel/ch8/mystrconv.c @@ -0,0 +1,243 @@ +/* Exercise 8.27 */ + +#include <stdio.h> +#include <string.h> +#include <ctype.h> + +double atof(const char *nptr); +int atoi(const char *nptr); +long atol(const char *nptr); +double strtod(const char *nptr, char **endptr); +long strtol(const char *nptr, char **endptr, int base); +unsigned long strtoul(const char *nptr, char **endptr, int base); + +int main(void) +{ + char n[] = "11537463.948abc", *strp; + double num; + long lnum; + + int b = 10; + + printf("atof(\"%s\") = %f\n", n, atof(n)); + printf("atoi(\"%s\") = %d\n", n, atoi(n)); + printf("atol(\"%s\") = %ld\n", n, atol(n)); + + num = strtod(n, &strp); + printf("strtod(\"%s\", &strp) = %f (strp: %s)\n", n, num, strp); + + lnum = strtol(n, &strp, b); + printf("strtol(\"%s\", &strp, %d) = %ld (strp: %s)\n", n, b, lnum, strp); + + lnum = strtoul(n, &strp, b); + printf("strtoul(\"%s\", &strp, %d) = %lu (strp: %s)\n", n, b, lnum, strp); + + return 0; +} /* E0F main */ + +/* Convert ASCII string to double */ +double atof(const char *nptr) +{ + double ret; + int i, n = atoi(nptr), p_val = 1; + double d = 1; + char *c; + + /* Calculate the positional value */ + for(p_val = 1; p_val < n; p_val *= 10) + ; /* Empty body */ + + p_val /= 10; /* Toggle the latest (exceded) value */ + + /* Calculate the decimal numbers */ + for(ret = 0, i = 0; i < (int)strlen(nptr); i++) { + if( !isdigit((int)nptr[i]) ) { + ++i; /* Go to.. */ + c = (char *) &nptr[i]; /* ..the next position */ + break; + } + + ret += (int)(nptr[i] - '0') * p_val; + p_val /= 10; + } + + n = atoi(c); /* To be continue.. :-) */ + + /* Calculate the floating point numbers */ + for(i = 0; i < (int)strlen(c); i++) { + if( !isdigit((int)c[i]) ) { + break; + } + + d *= 0.1; + } + + ret += n * d; /* Add the floating point numbers */ + + return ret; +} /* eof atof() */ + +/* Converti ASCII string to integer */ +int atoi(const char *nptr) +{ + int i, n = 0; + long m = 1; + + /* count the numbers for the m size */ + for(i = 0; i < (int)strlen(nptr); i++) { + if( !isdigit( (int)nptr[i] ) ) + break; + m *= 10; + } + m /= 10; + + /* Creating the integer */ + for(i = 0; i < (int)strlen(nptr); i++) { + if( !isdigit( (int)nptr[i] ) ) + break; + + n += (nptr[i] - '0') * m; + m /= 10; + } + + if(nptr[0] == '-') + return -n; + return n; +} /* eof atoi() */ + +/* Convert ASCII string to long */ +long atol(const char *nptr) +{ + long ret; + int i, n = atoi(nptr), p_val = 1; + + /* Calculate the positional value */ + for(p_val = 1; p_val < n; p_val *= 10) + ; /* Empty body */ + + p_val /= 10; /* Toggle the latest (exceded) value */ + + /* Calculate the decimal numbers */ + for(ret = 0, i = 0; i < (int)strlen(nptr); i++) { + if( !isdigit((int)nptr[i]) ) { + break; + } + + ret += (int)(nptr[i] - '0') * p_val; + p_val /= 10; + } + + return ret; +} /* eof atol() */ + +/* Convert ASCII string to double */ +double strtod(const char *nptr, char **endptr) +{ + double ret, d = 1; + int i, n = atoi(nptr), p_val = 1; + char *c; + + /* Calculate the positional value */ + for(p_val = 1; p_val < n; p_val *= 10) + ; /* Empty body */ + + p_val /= 10; /* Toggle the latest (exceded) value */ + + /* Calculate the decimal numbers */ + for(ret = 0, i = 0; i < (int)strlen(nptr); i++) { + if( !isdigit((int)nptr[i]) ) { + ++i; /* Go to.. */ + c = (char *) &nptr[i]; /* ..the next position */ + break; + } + + ret += (int)(nptr[i] - '0') * p_val; + p_val /= 10; + } + + n = atoi(c); /* To be continue.. :-) */ + + /* Calculate the floating point numbers */ + for(i = 0; i < (int)strlen(c); i++) { + if( !isdigit((int)c[i]) ) { + break; + } + + d *= 0.1; + } + endptr[0] = (char *) &c[i]; + + ret += n * d; /* Add the floating point numbers */ + + return ret; +} + + +/* Convert ASCII string to long */ +long strtol(const char *nptr, char **endptr, int base) +{ + long ret; + int i, n = atoi(nptr), p_val = 1; + + /* Skip all numbers <= 5 */ + if(base <= 5) { + endptr[0] = (char *) nptr; + return 0; + } + + /* Calculate the positional value */ + for(p_val = 1; p_val < n; p_val *= base) + ; /* Empty body */ + + if(base <= 7) p_val /= base; /* A little fix */ + + /* Calculate the decimal numbers */ + for(ret = 0, i = 0; i < (int)strlen(nptr); i++) { + if( !isdigit((int)nptr[i]) ) { + break; + } + + ret += (nptr[i] - '0') * p_val; + p_val /= base; + } + ret /= base; /* Toggle a zero */ + + endptr[0] = (char *) &nptr[i]; + + return ret; +} /* eof strtol() */ + +/* Convert ASCII string to unsigned long */ +unsigned long strtoul(const char *nptr, char **endptr, int base) +{ + unsigned long ret; + int i, p_val = 1, n = atoi(nptr); + + /* Skip all numbers <= 5 */ + if(base <= 5) { + endptr[0] = (char *) nptr; + return 0; + } + + /* Calculate the positional value */ + for(p_val = 1; p_val < n; p_val *= base) + ; /* Empty body */ + + if(base <= 7) p_val /= base; /* A little fix */ + + /* Calculate the decimal numbers */ + for(ret = 0, i = 0; i < (int)strlen(nptr); i++) { + if( !isdigit((int)nptr[i]) ) { + break; + } + + ret += (nptr[i] - '0') * p_val; + p_val /= base; + } + ret /= base; /* Toggle a zero */ + + endptr[0] = (char *) &nptr[i]; + + return ret; +} /* eof strtol() */ + diff --git a/exercises/deitel/ch8/mystrio.c b/exercises/deitel/ch8/mystrio.c @@ -0,0 +1,58 @@ +/* Exercise 8.29 */ + +/* This exercise don't have any sense! */ + +int getchar(void); +char *gets(char *s); +int putchar(int c); +int puts(const char *s); + +int main(void) +{ + char c, str[10]; + + printf("Give me a char: "); + c = getchar(); + + printf("\nputchar(): %c\n", putchar(c)); + + printf("Give me a string: "); + gets(str); + + printf("puts(): "); + puts(str); + + printf("\n"); + + return 0; +} /* E0F main */ + +int getchar(void) +{ + char c; + scanf("%c", &c); + return c; +} + +char *gets(char *s) +{ + scanf("%s", s); + return s; +} + +int putchar(int c) +{ + printf("%c", c); + return c; +} + +int puts(const char *s) +{ + printf("%s", s); + + if(*s != '\0') + return 1; + + return -1; +} + diff --git a/exercises/deitel/ch8/mystrlen.c b/exercises/deitel/ch8/mystrlen.c @@ -0,0 +1,29 @@ +/* Exercise 8.33 */ + +#include <stdio.h> + +size_t strlen(const char *s); + +int main(void) +{ + char string[] = "strlen(string): 18"; + + printf("strlen(string): %d\n", strlen(string)); + + return 0; +} /* E0F main */ + +/* computes the lenght of the string s */ +size_t strlen(const char *s) +{ + int i = 0; + + while( s[i++] != '\0' ) ; + + /* Second version + while( *(s + i++) != '\0' ) ; + */ + + return i - 1; +} /* eof strlen() */ + diff --git a/exercises/deitel/ch8/mystrmem.c b/exercises/deitel/ch8/mystrmem.c @@ -0,0 +1,108 @@ +/* Exercise 8.32 */ + +#include <stdio.h> + +void *memcpy(void *s1, const void *s2, size_t n); +void *memmove(void *s1, const void *s2, size_t n); +int memcmp(const void *s1, const void *s2, size_t n); +void *memchr(const void *s, int c, size_t n); +void *memset(void *s, int c, size_t n); + +int main(void) +{ + char strsrc[] = "this is a string!"; + char strdst[40] = { 0 }, *strp; + int n; + + strp = memcpy(strdst, strsrc, sizeof(strdst)); + printf("memcpy(): %s\n", strp); + + strp = memmove(strdst, "\"ab\"", 4); + printf("memmove(): %s\n", strp); + + n = memcmp(strdst, strsrc, 5); + printf("memcmp(): %d\n", n); + + strp = memchr(strsrc, 'a', sizeof(strsrc)); + printf("memchr(): %s\n", strp); + + strp = memset(strdst, 'x', 4); + printf("memset(): %s\n", strdst); + + return 0; +} /* E0F main */ + +/* copy n bytes from s2 to s1 */ +void *memcpy(void *s1, const void *s2, size_t n) +{ + int i; + char *dst = s1; + const char *src = s2; + + for(i = 0; i < (int)n && (*dst++ = *src++) != '\0'; i++) + ; /* Empty body */ + + return s1; +} /* eof memcpy() */ + +/* copy n bytes from s2 to s1. works even + * if s2 and s1 represents the same array */ +void *memmove(void *s1, const void *s2, size_t n) +{ + int i; + char *dst = s1, *tmp; + const char *src = s2; + + for(i = 0; i < (int)n; i++) + *(tmp + i) = *(src + i); + + for(i = 0; i < (int)n; i++) + *dst++ = *tmp++; + + return s1; +} /* eof memmove() */ + +/* compare n bytes of s1 and s2 */ +int memcmp(const void *s1, const void *s2, size_t n) +{ + int i; + const char *s = s1, *d = s2; + + long n1 = 0, n2 = 0; + + for(i = 0; i < (int)n && s[i] != '\0' && d[i] != '\0'; i++) { + n1 += s[i]; + n2 += d[i]; + } + + return n1 - n2; +} /* eof memcmp() */ + +/* locate the character c to the string s */ +void *memchr(const void *s, int c, size_t n) +{ + int i; + char *p = (char *)s; + + for(i = 0; i < (int)n && p[i] != '\0'; i++) { + if( p[i] == (unsigned char)c ) { + return &p[i]; + } + } + + return NULL; +} /* eof memchr() */ + +/* writes n bytes of c to s */ +void *memset(void *s, int c, size_t n) +{ + int i; + char *p = s; + + for(i = 0; i < (int)n; i++) { + p[i] = (unsigned char)c; + } + + return s; +} /* eof memset() */ + diff --git a/exercises/deitel/ch8/mystrsrch.c b/exercises/deitel/ch8/mystrsrch.c @@ -0,0 +1,206 @@ +/* Exercise 8.31 */ + +#include <stdio.h> +#include <string.h> + +char *strchr(const char *s, int c); +size_t strcspn(const char *s1, const char *s2); +size_t strspn(const char *s1, const char *s2); +char *strpbrk(const char *s1, const char *s2); +char *strrchr(const char *s, int c); +char *strstr(const char *S1, const char *s2); +char *strtok(char *s1, const char *s2); + +int main(void) +{ + char string[] = "yet another test string"; + char match[] = "not"; + char search = 'n'; + char *p; + int size; + + p = strchr(string, search); + printf("strchr(string, search): %s\n", p); + + size = strcspn(string, match); + printf("strcspn(string, match): %d\n", size); + + size = strspn(string, match); + printf("strspn(string, match): %d\n", size); + + p = strpbrk(string, match); + printf("strpbrk(string, match): %s\n", p); + + p = strrchr(string, search); + printf("strrchr(string, search): %s\n", p); + + p = strstr(string, match); + printf("strstr(string, match): %s\n", p); + + printf("\nTokenize..\n"); + p = strtok(string, " "); + while( p != NULL ) { + printf("strtok(string, \" \"): %s\n", p); + p = strtok(NULL, " "); + } + + return 0; +} + +/* locate the first occurrence of c to s and returns + * a pointer to c if will be found or NULL if not */ +char *strchr(const char *s, int c) +{ + int i; + + for(i = 0; i < (int)strlen(s); i++) { + if(s[i] == c) + return (char *)&s[i]; + } + + return NULL; + +} /* eof strchr() */ + +/* returns the size of initial segment of s1 which + * don't contains nobody of the characters in s2 */ +size_t strcspn(const char *s1, const char *s2) +{ + int i, j; + + for(i = 0; s1[i] != '\0'; i++) { + for(j = 0; s2[j] != '\0'; j++) { + + if(s1[i] == s2[j]) + return i + 1; + + } + } + + return -1; +} /* eof strcspn() */ + +/* returns the size of initial segment of s1 which + * contains only the characters in the string s2 */ +size_t strspn(const char *s1, const char *s2) +{ + int i, j, f; + + for(i = 0, f = 1; s1[i] != '\0' && f; i++) { + + f = 0; + + for(j = 0; s2[j] != '\0'; j++) { + if(s1[i] == s2[j]) { + f = 1; + break; + } + } + } + + return i - 1; +} /* eof strspn() */ + +/* locate to s1 one of the characters + * in s2 and returns a pointer to it */ +char *strpbrk(const char *s1, const char *s2) +{ + int i, j; + + for(i = 0; s1[i] != '\0'; i++) { + for(j = 0; s2[j] != '\0'; j++) { + if(s1[i] == s2[j]) + return (char *)&s1[i]; + } + } + + return NULL; +} /* eof strpbrk() */ + +/* locate the latest occurrence of c in + * the string s and return its position */ +char *strrchr(const char *s, int c) +{ + int i; + + for(i = (int)strlen(s) - 1; i >= 0; i--) { + if(s[i] == c) + return (char *)&s[i]; + } + + return NULL; +} /* eof strrchr() */ + +/* locate the string s2 to s1 and return its position */ +char *strstr(const char *s1, const char *s2) +{ + int i, j; + + for(i = 0; s1[i] != '\0'; i++) { + if(s1[i] == s2[0]) { + + for(j = 0; s2[j] != '\0'; j++) { + if(s1[i + j] != s2[j]) + break; + } + + if(j == (int)strlen(s2)) + return (char *)&s1[i]; + + } + } + + return NULL; +} /* eof strstr() */ + +/* tokenize s1 using the separator(s) in s2 */ +char *strtok(char *s1, const char *s2) +{ + int i, f, d; + static char *last; + + /* To be continue.. */ + if(s1 == NULL) { + if(last == NULL) + return NULL; + s1 = last; + + } + + /* loop the string */ + for(i = d = 0; s1[i] != '\0'; i++) { + + /* search the separator(s) */ + if(strchr(s2, s1[i]) != NULL) + f = 1; + else + f = 0; + + /* search the first non-separator character */ + if(!d && !f) { + s1 = &s1[i]; + d = 1; /* skip this block the next loop */ + continue; + } + + /* check if the latest token */ + if(s1[i + 1] == '\0') { + f = 1; + ++i; + } + + /* search "the next" separator */ + if(d && f) { + if(s1[i] != '\0') { + s1[i] = '\0'; + last = &s1[i + 1]; + } + else + last = NULL; + return s1; + } + } + + return NULL; +} /* eof strtok() */ + diff --git a/exercises/deitel/ch8/n2w.c b/exercises/deitel/ch8/n2w.c @@ -0,0 +1,262 @@ +/* Exercise 8.38 */ + +#include <stdio.h> +#include <string.h> +#include <ctype.h> + +#define SIZE 10 + +void printw(double n); +void pnumz(int num, int kind); + +double tonum(char *s); + +int main(void) +{ + char number[SIZE] = { 0 }; + double n; + + printf("Give me a number: "); + gets(number); + while( (int)strlen(number) > SIZE ) { + printf("Error: too many numbers\n"); + + printf("Give me a number: "); + gets(number); + } + + n = tonum(number); + + printw(n); + + printf("\n"); + + return 0; +} /* E0F main */ + +/* convert from "1,234.56" format to 1234.56 */ +double tonum(char *s) +{ + int i, num[SIZE] = { 0 }; + double n = 0, x = 1; + char string[SIZE], *tokp; + + strcpy(string, s); + + tokp = strtok(string, ","); + while( tokp != NULL ) { + for(i = 0; tokp[i] != '\0' && !ispunct((int)tokp[i]); i++) { + num[(int)n++] = (int)tokp[i] - '0'; + x *= 10; + } + + tokp = strtok(NULL, ","); + } + x /= 10; + n = 0; + + for(i = 0; (int)x && i < SIZE * 2; i++) { + n += num[i] * x; + x /= 10; + } + + x = 1; + + strtok(s, "."); /* Before '.' */ + tokp = strtok(NULL, "."); /* After the '.' */ + if(tokp != NULL) { + for(i = 0; tokp[i] != '\0'; i++) { + x *= 0.1; + n += (tokp[i] - '0') * x; + } + } + + return n; + +} /* eof tonum() */ + +/* print a number in letters (1) */ +void printw(double n) +{ + int k = 4, x = 1000000000, num; + + do { + num = (int)n / x % 1000; + + if(num) { + pnumz((int)n / x % 1000, k); + } + + --k; + + } while( x /= 1000 ); + + /* Floating numbers */ + if(n - (int)n) + printf(" virgola %.0f", (n - (int)n) * 100); +} /* eof printw() */ + +/* print a number in letters (2) */ +void pnumz(int num, int kind) +{ + switch(num / 100 % 10) { + case 2: + printf("due"); + break; + case 3: + printf("tre"); + break; + case 4: + printf("quattro"); + break; + case 5: + printf("cinque"); + break; + case 6: + printf("sei"); + break; + case 7: + printf("sette"); + break; + case 8: + printf("otto"); + break; + case 9: + printf("nove"); + break; + } + + if( (num / 100 % 10) ) + printf("cento"); + + switch(num / 10 % 10) { + case 1: + switch(num % 10) { + case 0: + printf("dieci"); + break; + case 1: + printf("un"); + break; + case 2: + printf("do"); + break; + case 3: + printf("tre"); + break; + case 4: + printf("quattor"); + break; + case 5: + printf("quin"); + break; + case 6: + printf("se"); + break; + case 7: + printf("diciassette"); + break; + case 8: + printf("diciotto"); + break; + case 9: + printf("diciannove"); + break; + } + + if( (num % 10) < 7 && ( num % 10 ) ) + printf("dici"); + + break; + case 9: + printf("nov"); + break; + case 8: + printf("ott"); + break; + case 7: + printf("sett"); + break; + case 6: + printf("sess"); + break; + case 5: + printf("cinqu"); + break; + case 4: + printf("quar"); + break; + case 3: + printf("trenta"); + break; + case 2: + printf("venti"); + break; + } + + if( (num / 10 % 10) >= 4 ) + printf("anta"); + + if( (num % 10 == 8 && num != 8) || + ((num % 10) == 1 && (num != 1 && num / 10 % 10 != 1) ) ) + printf("\b"); + + if(num / 10 % 10 != 1) { /* If is not [10,19] */ + switch(num % 10) { + case 1: + if (kind == 4 && num == 1) + printf("un"); + else if(kind == 3 && num == 1) + printf("un"); + else if(kind == 2 && num == 1) + printf("mille"); + else + printf("uno"); + break; + case 2: + printf("due"); + break; + case 3: + printf("tre"); + break; + case 4: + printf("quattro"); + break; + case 5: + printf("cinque"); + break; + case 6: + printf("sei"); + break; + case 7: + printf("sette"); + break; + case 8: + printf("otto"); + break; + case 9: + printf("nove"); + break; + } + } /* end if */ + + switch(kind) { + case 4: + if( !(num % 100) || num % 100 > 1 ) + printf("miliardi"); + else + printf("miliardo"); + break; + case 3: + if( !(num % 100) || num % 100 > 1 ) + printf("milioni"); + else + printf("milione"); + break; + case 2: + if(num > 1) + printf("mila"); + break; + } +} /* eof pnumz() */ + diff --git a/exercises/deitel/ch8/ncmp2s.c b/exercises/deitel/ch8/ncmp2s.c @@ -0,0 +1,33 @@ +/* Exercise 8.10 */ + +#include <stdio.h> +#include <string.h> + +int main(void) +{ + char s1[10]; + char s2[10]; + int val, num; + + printf("Give me a string (s1): "); + gets(s1); + printf("Give me another string (s2): "); + gets(s2); + printf("How many characters want to compare?: "); + scanf("%d", &num); + + val = strncmp(s1, s2, num); + printf("s1 is "); + + if(!val) + printf("equal to"); + else if(val < 0) + printf("less then"); + else + printf("greater then"); + + printf(" s2\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/phone.c b/exercises/deitel/ch8/phone.c @@ -0,0 +1,24 @@ +/* Exercise 8.14 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +int main(void) +{ + char phone[] = "(123) 456-78990", *tokp; + int prefix; + long int number; + + tokp = strtok(phone, ")"); + prefix = atoi(++tokp); + + tokp = strtok(NULL, "-"); + number = atoi( strcat(++tokp, strtok(NULL, " ")) ); + + printf("Prefix: %d\n", prefix); + printf("Number: %ld\n", number); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/piglatin.c b/exercises/deitel/ch8/piglatin.c @@ -0,0 +1,42 @@ +/* Exercise 8.13 */ + +#include <stdio.h> +#include <string.h> + +#define SIZE 30 + +void printLatinWord(char *p); + +int main(void) { + char english[SIZE] = "jump the computer"; + char *tokp; + + printf("The english string is:\t\t%s\n", english); + printf("The pig lating string is:\t"); + + tokp = strtok(english, " "); + while( tokp != NULL ) { + printLatinWord(tokp); + tokp = strtok(NULL, " "); + } + + printf("\n"); + + return 0; +} + +/* Take an english word and write it in Pig Latin */ +void printLatinWord(char *p) +{ + char string[20]; + + strcpy(string, ++p); + + string[strlen(string) + 1] = '\0'; + string[strlen(string)] = *(--p); + + strcat(string, "ay"); + + printf("%s ", string); +} /* eof printLatinWord() */ + diff --git a/exercises/deitel/ch8/promptletter.c b/exercises/deitel/ch8/promptletter.c @@ -0,0 +1,77 @@ +/* Exercise 8.41 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +#define BUF 30 +#define SIZE 8 + +void prompt(const char * const debitor, + const char * const address, + const char * const account, + const double money, const int delay); + +int main(void) +{ + char debitor[BUF], address[BUF], account[SIZE], money[SIZE]; + int delay; + + printf("Debitor's (name and surname): "); + gets(debitor); + + printf("Debitor's address: "); + gets(address); + + printf("Account number: "); + gets(account); + + printf("Due money: "); + gets(money); + + printf("How many months of delay: "); + scanf("%d", &delay); + + prompt(debitor, address, account, atof(money), delay); + + return 0; +} /* E0F main */ + + +void prompt(const char * const debitor, + const char * const address, + const char * const account, + const double money, const int delay) +{ + printf("\n----- Letter [%d] -----\n\n", delay >= 5 ? 5 : delay); + switch(delay >= 5 ? 5 : delay) { + case 1: + printf("Hello %s,\n\t" + "we are writing to you because you have one month of delay\n" + "in the payment of our products. Please, it supplies first\n" + "possible! We remember you some data stuff:\n\n" + "\tYour account number: %s\n" + "\tYour address: %s\n" + "\tQuantity to pay: %.2f\n" + "\n" + "We are waiting for your reply, in the while give you\n", + debitor, account, address, money); + break; + case 2: + printf("Letter.. (priority low)\n"); + break; + case 3: + printf("Letter.. (priority medium)\n"); + break; + case 4: + printf("Letter.. (priority high)\n"); + break; + case 5: + printf("Letter.. (priority very high)\n"); + break; + } + printf("\nBest regards\n\nClaudio M. corporation\n12534, Madison DC\nbla..\n"); + printf("\n----- End letter -----\n"); + +} /* eof prompt() */ + diff --git a/exercises/deitel/ch8/search.c b/exercises/deitel/ch8/search.c @@ -0,0 +1,26 @@ +/* Exercise 8.16 */ + +#include <stdio.h> +#include <string.h> + +#define BUF 254 + +int main(void) +{ + char string[BUF], search[BUF / 2], *searchPtr; + + printf("Give me a string: "); + gets(string); + + printf("Give me your search string: "); + gets(search); + + searchPtr = strstr(string, search); /* Start the search */ + while( searchPtr != NULL ) { /* Found all next matches */ + printf("String: %s\n", searchPtr); + searchPtr = strstr(searchPtr + 1, search); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/searchc.c b/exercises/deitel/ch8/searchc.c @@ -0,0 +1,26 @@ +/* Exercise 8.18 */ + +#include <stdio.h> +#include <string.h> + +#define BUF 254 + +int main(void) +{ + char string[BUF], search, *searchPtr; + + printf("Give me a string: "); + gets(string); + + printf("Give me your search character: "); + search = getchar(); + + searchPtr = strchr(string, search); /* Start the search */ + while( searchPtr != NULL ) { /* Found all next matches */ + printf("String: %s\n", searchPtr); + searchPtr = strchr(searchPtr + 1, search); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/searchctot.c b/exercises/deitel/ch8/searchctot.c @@ -0,0 +1,46 @@ +/* Exercise 8.19 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <ctype.h> + +#define STRINGS 10 +#define BUF 254 +#define ASCII 127 + +int main(void) +{ + char string[STRINGS][BUF] = { { 0 } }; + int i = 0, j, counter[ASCII] = { 0 }; + + /* Take the strings */ + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + + while( atoi(string[i++]) != EOF ) { + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + } + + string[i - 1][0] = '\0'; /* Remove the '-1' */ + + for(i = 0; i < STRINGS; i++) { + for(j = 0; (unsigned)j < strlen(string[i]); j++) { + ++counter[tolower((int)string[i][j])]; + } + } + + for(i = 1; i < ASCII; i++) { + if(counter[i]) { + + i == 32 ? printf("spaces") : printf("%c", i); + + printf("[%d] ", counter[i]); + } + } + printf("\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/searchtot.c b/exercises/deitel/ch8/searchtot.c @@ -0,0 +1,44 @@ +/* Exercise 8.17 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +#define STRINGS 10 +#define BUF 254 + +int main(void) +{ + char string[STRINGS][BUF], search[BUF / 2], *searchPtr; + int i = 0, counter = 0; + + /* Take the strings */ + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + + while( atoi(string[i++]) != -1 ) { + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + } + + /* Take the search string */ + printf("Give me your search string: "); + gets(search); + + for(i = 0; i < STRINGS; i++) { + searchPtr = strstr(string[i], search); /* Start the search */ + while( searchPtr != NULL ) { /* Found all next matches */ + //printf("Match found to line %d: %s\n", i, searchPtr); + searchPtr = strstr(searchPtr + 1, search); + ++counter; + } + } + + if(!counter) + printf("No match found!\n"); + else + printf("Found %d matches!\n", counter); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/strcomp.c b/exercises/deitel/ch8/strcomp.c @@ -0,0 +1,57 @@ +/* Exercise 8.30 */ + +#include <stdio.h> + +int strcmp(const char *s1, const char *s2); +int strncmp(const char *s1, const char *s2, size_t n); + +int main(void) +{ + char string1[] = "abcdef"; + char string2[] = "abcdea"; + + printf("strcmp() = %d\n", strcmp(string1, string2) ); + printf("strncmp() = %d\n", strncmp(string1, string2, 4) ); + + return 0; +} /* E0F main */ + +/* Compare two strings */ +int strcmp(const char *s1, const char *s2) +{ + int i; + long n1 = 0, n2 = 0; + + for(i = 0; s1[i] != '\0'; i++) + n1 += s1[i]; + + for(i = 0; s2[i] != '\0'; i++) + n2 += s2[i]; + + return n1 - n2; + +} /* eof strcmp() */ + +int strncmp(const char *s1, const char *s2, size_t n) +{ + int i; + long n1 = 0, n2 = 0; + + for(i = 0; i < (int)n; i++) { + if( s1[i] == '\0' ) + break; + + n1 += s1[i]; + } + + for(i = 0; i < (int)n; i++) { + if( s2[i] == '\0' ) + break; + + n2 += s2[i]; + } + + return n1 - n2; + +} + diff --git a/exercises/deitel/ch8/strorder.c b/exercises/deitel/ch8/strorder.c @@ -0,0 +1,64 @@ +/* Exercise 8.21 */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <ctype.h> + +#define SIZE 20 +#define BUF 254 + +void bsortp(char *string[]); + +int main(void) +{ + char cities[SIZE][BUF], *pointers[SIZE] = { 0 }; + int i = 0, j; + + printf("Give me a city (%d to end): ", EOF); + gets(cities[i]); + + while( atoi(cities[i++]) != EOF ) { + /* convert the string to lowercase */ + for(j = 0; j < (int)strlen(cities[i - 1]); j++) + cities[i - 1][j] = tolower((int)cities[i - 1][j]); + + printf("Give me a city (%d to end): ", EOF); + gets(cities[i]); + } + + cities[i - 1][0] = '\0'; /* Remove the '-1' */ + + /* Copy the address of each phrase to pointers[] */ + for(i = 0; i < SIZE; i++) + pointers[i] = cities[i]; + + bsortp(pointers); /* Order the pointers[] array */ + + /* Print the non-empty strings in the pointer[] */ + for(i = 0; i < SIZE; i++) { + if( strlen(pointers[i]) ) + printf("%s\n", pointers[i]); + } + + return 0; +} /* E0F main */ + +/* Sort an array of pointers using the BubbleSort alrorithm */ +void bsortp(char *string[]) +{ + int i, j; + char *tmpp; + + for(i = 1; i < SIZE; i++) { + for(j = 0; j < SIZE - 2; j++) { + if( strcmp(string[j], string[j + 1]) > 0 ) { + /* Swap the addresses */ + tmpp = string[j]; + string[j] = string[j + 1]; + string[j + 1] = tmpp; + } + } + } +} /* eof bsortp() */ + diff --git a/exercises/deitel/ch8/strtok_rev.c b/exercises/deitel/ch8/strtok_rev.c @@ -0,0 +1,36 @@ +/* Exercise 8.15 */ + +#include <stdio.h> +#include <string.h> + +#define SIZE 254 + +void strtok_rev(char *s); + +int main(void) +{ + char string[SIZE], *c; + + printf("Give me a string: "); + gets(string); + + c = strtok(string, " "); + strtok_rev(string); + printf("%s\n", c); + + return 0; +} /* E0F main */ + +void strtok_rev(char *s) +{ + char *tokp; + + tokp = strtok(NULL, " "); + + if(tokp != NULL) { + strtok_rev(s); + printf("%s ", tokp); + } + +} /* eof strtok_rev() */ + diff --git a/exercises/deitel/ch8/textanalysis.c b/exercises/deitel/ch8/textanalysis.c @@ -0,0 +1,55 @@ +/* Exercise 8.34 (a) */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <ctype.h> + +#define STRINGS 10 +#define BUF 254 +#define ASCII 127 + +int main(void) +{ + char string[STRINGS][BUF] = { { 0 } }; + int i = 0, j, counter[ASCII] = { 0 }; + + /* Take the strings */ + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + + while( atoi(string[i++]) != EOF ) { + printf("Give me a string (%d to end): ", EOF); + gets(string[i]); + } + + string[i - 1][0] = '\0'; /* Remove the '-1' */ + + for(i = 0; i < STRINGS; i++) { + for(j = 0; (unsigned)j < strlen(string[i]); j++) { + ++counter[tolower((int)string[i][j])]; + } + } + + printf("\nOccurrences table\n" + "* (NP = not printable)\n" + "* (SP = spaces)\n\n"); + + for(i = j = 1; i < ASCII; i++) { + if(counter[i]) { + + if(i < 32) printf("NP: "); + else if(i == 32) printf("SP: "); + else printf("%2c: ", i); + printf("%2d | ", counter[i]); + + if( !(j % 4) ) + printf("\n-----------------------------------\n"); + ++j; + } + } + printf("\n\n"); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch8/wordocc.c b/exercises/deitel/ch8/wordocc.c @@ -0,0 +1,52 @@ +/* Exercise 8.34 (b) */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define SIZE 50 +#define BUF 255 +#define MAXWORD 30 + +int main(void) +{ + char string[SIZE][BUF] = { { 0 } }, *tokp; + int count[MAXWORD] = { 0 }; + int i = 0, highest = 0; + + /* start to take the strings */ + printf("str (%d to end): ", EOF); + gets(string[i]); + + /* continue to take the strings */ + while( atoi(string[i++]) != EOF ) { + printf("str (%d to end): ", EOF); + gets(string[i]); + } + string[i - 1][0] = '\0'; /* clear the EOF char */ + + /* count the lenght for each word */ + for(i = 0; i < SIZE; i++) { + + /* tokenizing.. */ + tokp = strtok(string[i], " "); + while( tokp != NULL ) { + ++count[(int)strlen(tokp)]; + + /* this instruction is not optimized */ + if((int)strlen(tokp) > highest) + highest = (int)strlen(tokp); + + tokp = strtok(NULL, " "); + } + } + + /* print the results */ + printf("Word size\tOccurrences\n"); + for(i = 1; i <= highest; i++) { + printf("%9d\t\t%3d\n", i, count[i]); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch9/escapes.c b/exercises/deitel/ch9/escapes.c @@ -0,0 +1,24 @@ +/* Exercise 9.14 */ + +#include <stdio.h> + +int main(void) +{ + + printf("\\\': < \' >\n" + "\\\": < \" >\n" + "\\\?: < \? >\n" + "\\\\: < \\ >\n" + "\\a: < \a >\n" + "\\b: < \b >\n" + "\\f: < \f >\n" + "\\n: < \n >\n" + "\\r: < \r >\n" + "\\t: < \t >\n" + "\\v: < \v >\n" + ); + + + return 0; +} + diff --git a/exercises/deitel/ch9/ex94.c b/exercises/deitel/ch9/ex94.c @@ -0,0 +1,42 @@ +/* Exercise 9.4 */ + +#include <stdio.h> + +int main(void) +{ + unsigned int num = 40000; + int hex, hour, minute, second; + char s[] = "This is a practice string", *ptr; + + printf("\n%-15.8u\n\n", num); + + printf("Hex value: "); + scanf("%i", &hex); + printf(": %i\n", hex); + + printf("\n%+d\n", 200); + printf("%d\n", 200); + + printf("\n%#x\n", 100); + + ptr = s; + while( *ptr != 'p' && ptr != NULL ) + printf("%c", *ptr++); + + printf("\n\n%09.3f\n", 1.234); + + printf("\nTime: "); + scanf("%d%*c%d%*c%d%*c", &hour, &minute, &second); + printf("hour[%d] minute[%d] second[%d]\n", hour, minute, second); + + printf("\nstring: "); + scanf("\"%[^\"]s", s); + printf("string: %s\n", s); + + printf("\nTime[2]: "); + scanf("%*c%d:%d:%d", &hour, &minute, &second); + printf("%d %d %d\n", hour, minute, second); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch9/nsum.c b/exercises/deitel/ch9/nsum.c @@ -0,0 +1,28 @@ +/* Exercise 9.7 */ + +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define SIZE 10 + +int main(void) +{ + int i, tot = 0, num[SIZE]; + + /* srand( time(NULL) ); */ + + /* Initialize the array */ + for(i = 0; i < SIZE; i++) { + num[i] = 1 + rand() % 1000; + } + + /* Print the table */ + for(i = 0; i < SIZE; i++) { + tot += printf("%d", num[i]); + printf("\t%d\n", tot); + } + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/ch9/simplecmp.c b/exercises/deitel/ch9/simplecmp.c @@ -0,0 +1,16 @@ +/* Exercise 9.8 */ + +#include <stdio.h> + +int main(void) +{ + int x, y; + + printf(": "); + scanf("%i%d", &x, &y); + + printf("%d %d\n", x, y); + + return 0; +} /* E0F main */ + diff --git a/exercises/deitel/deitel_code.tar.gz b/exercises/deitel/deitel_code.tar.gz Binary files differ.