You are on page 1of 185

EJNIKO KAI KAPODISTRIAKO PANEPISTHMIO AJHNWN TMHMA PLHROFORIKHS KAI THLEPIKOINWNIWN

EISAGWGHS STON PROGRAMMATISMO


PANAGIWTHS STAMATOPOULOS

SHMEIWSEIS

AJHNA

2007

EISAGWGH STON PROGRAMMATISMO


Kwdikc: Kathgora: Exmhno: Didskwn: K04 Kormc Plhroforikc kai Thlepikoinwnin A' Panagithc Stamatpouloc (takis@di.uoa.gr, Grafeo A48)

Metaptuqiako Sunergtec: Stfanoc Stamthc (stef@di.uoa.gr) Nkoc Pojhtc (pothitos@di.uoa.gr) Dhmtrhc Yonhc (psounis@di.uoa.gr) Ginnhc Belesithc (giavel@di.uoa.gr) Aristotlhc Glentc (arisg@di.uoa.gr) Manlhc Sunodinc (grad0796@di.uoa.gr) Mi Li Triantafulldh (grad0851@di.uoa.gr) Dhmtrhc Katrc (grad0858@di.uoa.gr) Foboc Jeoqrhc (std02209@di.uoa.gr) Stlioc Karampaskhc (std02035@di.uoa.gr) Dhmtrhc Kwtskoc (std02041@di.uoa.gr) 'Anna Nka (std02087@di.uoa.gr) Ea Sitardh (std02115@di.uoa.gr) Dhmtrhc Paprac (std03058@di.uoa.gr) Istoselda majmatoc: http://www.di.uoa.gr/~ip Froum/Lsta epikoinwnac: http://lists.di.uoa.gr

Perieqmeno tou majmatoc


Genik per upologistn kai programmatismo upologistn Istorik anadrom H dom tou upologist H plhrofora ston upologist Logismik kai glssec programmatismo Apaitseic ap ma diadikastik glssa programmatismo Ektelsima progrmmata Metaglttish kai sndesh H glssa programmatismo C Programmatistik peribllonta gia thn C O metaglwttistc gcc Paradegmata apln programmtwn sthn C Qarakthristik kai dunatthtec thc C
Metablhtc, stajerc, tpoi kai dhlseic Entolc antikatstashc, telestc kai parastseic H ro tou elgqou Dom progrmmatoc, sunartseic kai exwterikc metablhtc Embleia kai qrnoc zwc metablhtn

Anadrom Dieujnseic jsewn mnmhc, dektec kai pnakec Dunamik dsmeush mnmhc Sumboloseirc Pnakec deiktn, dektec se dektec kai poludistatoi pnakec Dektec se sunartseic Orsmata grammc entoln Aparijmseic, domc, auto-anaforikc domc (lstec, duadik dntra), enseic, peda bit kai dhmiourga nwn onomtwn tpwn Esodoc kai xodoc Qeirismc arqewn Proepexergastc thc C kai makroentolc

Algrijmoi taxinmhshc pinkwn kai anazthshc se pnakec Odhgec swsto programmatismo Suqn programmatistik ljh sthn C Ergasthriakc askseic kai askseic gia kat' okon ergasa

Eisagwgik jmata
Genik per upologistn Genik per programmatismo upologistn Istorik anadrom Kpoia upologistik problmata Pc na mjoume na programmatzoume; H dom tou upologist H plhrofora ston upologist Logismik kai glssec programmatismo

Genik per upologistn


Upologistc enai na teqnht kataskeasma pou qei thn ikanthta na epexergzetai na snolo ap dedomna pou tou dnontai kai na pargei ta apaitomena apotelsmata. To edoc thc epexergasac pou prpei na gnei epnw sta dedomna prosdiorzetai ap na prgramma me to opoo qoume trofodotsei ton upologist kai to opoo apoteletai ap stoiqeideic ektelsimec entolc pou enai se jsh na frei se prac o upologistc. Giat qreiazmaste upologistc; Gia th grgorh ektlesh qronobrwn arijmhtikn upologismn, gia pardeigma pso enai to , an 2 1 1 1 1 1 1 1 1 6 = 12 + 22 + 32 + 42 + 52 + 62 + 72 + 82 + . . .; Gia thn apodotik diaqerish ogkwdn dedomnwn, gia pardeigma trapezikn logariasmn. Kai gia ta do prohgomena, tautqrona, gia pardeigma sthn prgnwsh kairo. H suggraf programmtwn gia upologistc anafretai me ton genik ro programmatismc upologistn.

Genik per programmatismo upologistn


Sth genik perptwsh, programmatismc (enc upologist) enai o safc kajorismc mac diadikasac, san na snolo ap entolc (to prgramma), pou perigrfei leptomerc ta bmata pou prpei na gnoun gia na epiluje na prblhma upologismo. Ta progrmmata gia na upologist apotelon to logismik tou (software), en h suskeu tou upologist enai to ulik (hardware). 'Ena prgramma trofodotetai s' na upologist, autc to ektele kai pargei to apotlesma thc eplushc tou problmatoc. H suggraf enc progrmmatoc gia thn eplush enc problmatoc propojtei thn epinhsh enc algorjmou, dhlad mac safc kajorismnhc diadikasac msw enc sunlou ektelsimwn bhmtwn, pou enai egguhmno ti met ap na peperasmno pljoc bhmtwn pou ja ektelesjon ja termatsei. 'Ena prgramma enai h diatpwsh enc algorjmou se ma sugkekrimnh glssa programmatismo.

Istorik anadrom
'Abakac, suskeu prosjafairsewn me mpliec (1000 p.Q.) O Mhqanismc twn Antikujrwn (75 p.Q.) Muhammad ibn Musa al-Khwarizmi, prteine thn nnoia thc diadikasac gia autmatouc upologismoc (800 m.Q.) Mhqaniko upologistc gia arijmhtikoc upologismoc (Blaise Pascal, Gottfried Leibniz, 17oc ainac) Analutik mhqan tou Charles Babbage me prth programmatstria thn Ada Lovelace (19oc ainac) Alan Turing, jemeliwtc twn ennoin twn algorjmwn kai tou upologismo, h mhqan Turing (1935) MARK I, o prtoc hlektromhqanikc upologistc meglhc klmakac, IBM, Harvard University (1943) John von Neumann, jemeliwtc thc trqousac arqitektonikc twn upologistn (1945) ENIAC, o prtoc upologistc me luqnec keno, University of Pennsylvania (1946) IBM 7090, o prtoc upologistc me tranzstor (1961) IBM 360, o prtoc upologistc me oloklhrwmna kuklmata tsip (1964) O proswpikc upologistc, to PC (1981) Tim Berners-Lee, eisgage thn ida tou pagksmiou isto sto diadktuo (1990)

Kpoia upologistik problmata


Pc prokuyan ta apotelsmata twn panellhnwn exetsewn gia thn eisagwg se A.E.I. kai T.E.I.; Pc apofaszetai an nac foithtc tou Tmmatc mac qei ekplhrsei tic upoqreseic tou gia lyh tou ptuqou tou; Ti fro ja plhrsei h oikognei mac eftoc; Pc upologsthke to telik pos plhrwmc stouc teleutaouc logariasmoc O.T.E kai D.E.H. pou lbame; Dedomnwn twn analutikn apotelesmtwn se kje eklogik tmma stic ejnikc eklogc, psouc bouleutc eklgei to kje kmma se kje nom; Dedomnwn twn apotelesmtwn mac dhmoskphshc exdou (exit poll) se epilegmna eklogik tmmata, pc mporome na problyoume to telik posost yfwn se lh th qra gia kje kmma pou summetqei stic ejnikc eklogc; Pc mporome na problyoume ton kair sthn Ajna gia ario gia tic erqmenec hmrec, dedomnwn lwn twn apaitomenwn metewrologikn stoiqewn; Pc gnontai oi kratseic aeroporikn eisithrwn; Pc mporome na kataskeusoume to kaltero wrolgio prgramma gia ta majmata tou trqontoc examnou; To kaltero prgramma exetsewn gia thn erqmenh exetastik perodo;

Pc na mjoume na programmatzoume;
Dustuqc o programmatismc den didsketai. Den mporome na mjoume na programmatzoume diabzontac bibla gia programmatism. Den mporome na mjoume na programmatzoume grfontac progrmmata sto qart. O mnoc trpoc na mjoume na programmatzoume enai na grfoume progrmmata ston upologist, na ta ektelome, na brskoume ta ljh pou sgoura qoume knei, na ta diorjnoume, na ektelome pli ta progrmmata, na xanabrskoume ljh, na ta diorjnoume pli, mqri na katafroume na knoume ta progrmmat mac na epiloun ta problmat mac pwc prpei. Epikourik, h angnwsh kai katanhsh kalogrammnwn, tekmhriwmnwn kai orjn programmtwn enai pntote qrsimh, all ap mnh thc den arke.

10

H dom tou upologist


Kentrik monda epexergasac, o epexergastc Mnmh, gia proswrin apojkeush dedomnwn kai programmtwn Deutereousa mnmh, gia mnimh apojkeush dedomnwn kai programmtwn (dskoi, disktec, tainec, CDs, DVDs, klp.) Mondec eisdou/exdou, gia epikoinwna me ton xw ksmo (plhktrolgio, ojnh, ektupwtc, klp.)

11

H plhrofora ston upologist


Duadik yhfa 0 kai 1 (bits - binary digits) Bytes, 1 byte = 8 bits Smbola, ASCII kwdiko (A = 65, B = 66, . . .) Sustmata arjmhshc duadik dekadik oktadik dekaexadik
(01101101)2 = (109)10 = (155)8 = (6D)16 0 27 + 1 26 + 1 25 + 0 24 + 1 23 + 1 22 + 0 21 + 1 20 = 109

H mnmh enai organwmnh se suneq keli, pou to kajna qarakthrzetai ap th diejuns tou, kai msa sta opoa o epexergastc mpore na kataqwrsei, all kai na diabsei ap' aut, plhroforec (duadikoc arijmoc). Sth deutereousa mnmh, h orgnwsh sto qamhl eppedo enai perpou pwc kai sthn (kria) mnmh, all oi kataqwrhmnec plhroforec prospelanontai ap ton qrsth msw arqewn (les) kai katalgwn (directories), kat ma orologa faklwn (folders). Mondec mtrhshc qwrhtikthtac mnmhc 1 Kilobyte (KB) = 210 (= 1024 103 ) bytes 106 ) bytes 109 ) bytes 1 Megabyte (MB) = 220 (= 1048576 1 Gigabyte (GB) = 230 (= 1073741824

12

Logismik kai glssec programmatismo


Logismik sustmatoc Leitourgik ssthma (Microsoft Windows, Unix, . . .) Metaglwttistc (gcc, g++, . . .) Keimenogrfoi (pico, vim, . . .) ... Logismik efarmogn Glssec programmatismo qamhlo epipdou Glssa mhqanc Assembly Glssec programmatismo uyhlo epipdou Cobol, Fortran, Algol, Ada Pascal, C C++, Java, C# Visual Basic SQL Prolog Haskell, Common Lisp PHP Perl, Python ...

13

Ti qreiazmaste ap ma glssa programmatismo;


Mhqanismoc gia esodo (dedomnwn) kai xodo (apotelesmtwn) Pardeigma:

Dibase Misj Upalllou


Upolgise Kratseic Upolgise Kajar Misj Ektpwse Kajar Misj

Diatpwsh akoloujac bhmtwn proc ektlesh Pardeigma:


'Estw 'Ena Orjognio Trgwno ABG me Orj Gwna sto A Bma 1: Upolgise to Tetrgwno thc AB Bma 2: Upolgise to Tetrgwno thc AG Bma 3: Prsjese ta Do Tetrgwna Bma 4: H Pleur BG Isotai me thn Tetragwnik Rza tou Apotelsmatoc

Flaxh plhroforin sth mnmh kai ankths touc Pardeigma:


Misjc = 1500 Axhsh = 0.04 Noc Misjc = Axhsh * Misjc + Misjc

14

Diaforopohsh roc tou elgqou smfwna me sunjkh Pardeigma:

An Katanlwsh < 200 Tte Kstoc = 20 Allic Kstoc = 0.3 * Katanlwsh - 40


Dunatthta diatpwshc epanalhptikn diadikasin Pardeigma:
Arijmc = 1 'Ajroisma = 0 Ensw Arijmc < 1001 'Ajroisma = 'Ajroisma + Arijmc2 Arijmc = Arijmc + 1

Paketrisma suqn qrhsimopoiomenwn leitourgin Pardeigma:

Taxinmhse(Pnaka A) Taxinmhse(Pnaka B) Sugqneuse(Pnaka A, Pnaka B)


Metafor thc roc tou elgqou allo (pol spnia) Pardeigma:

Bma 1: An Q = 30 Tte Pgaine sto Bma 2 Allic Pgaine sto Bma 4 Bma 2: Ektpwse Trinta Bma 3: Pgaine sto Bma 5 Bma 4: Ektpwse 'Oqi trinta Bma 5: . . .

15

Pc kataskeuzoume ektelsimo prgramma;


Sunjwc, grfoume ta progrmmat mac se kpoia glssa programmatismo uyhlo epipdou, gia pardeigma C. Gia lgouc ekolhc suntrhshc enc progrmmatoc, enai pijann na to qoume diaspsei se poll phgaa arqea (source les), pou perilambnoun kdika (code) grammno sth glssa programmatismo pou qoume epilxei. O metaglwttistc (compiler) enai na prgramma pou metatrpei ta phgaa arqea se antikeimenik arqea (object les), ta opoa enai diatupwmna sth glssa mhqanc tou epexergast tou upologist mac. Ta antikeimenik arqea den enai mesa ektelsima ap ton epexergast, ektc tou ti to kajna ap' aut mpore na mhn sunist na plrec prgramma. O sundthc (linker) metatrpei na snolo ap antikeimenik arqea, kajc kai tuqn bibliojkec (libraries) pou ja tou dojon, s' na ektelsimo arqeo (executable le), to opoo epshc enai diatupwmno se glssa mhqanc, all enai mesa ektelsimo ap ton epexergast.

16

H diadikasa thc metaglttishc kai sndeshc


#include... main() { printf(.. }


10010101

01001001 00110001 11000010


11010001 11001101


#include... func(int x) {


11010000 00000001 11010010

00100110 11000000 00000011


11110011 00000011

00000011 11010000 00110001

17

Programmatistik peribllonta gia thn C


Metaglwttistc gcc thc C, ap to prgramma elejerou logismiko GNU, se leitourgik ssthma Unix (gia pardeigma, Solaris se stajmoc ergasac Sun Linux se proswpikoc upologistc) Peribllonta pou uposthrzoun ton metaglwttist gcc, ktw ap leitourgik ssthma Microsoft Windows Dev-C++ Cygwin MinGW Peribllon Microsoft Visual Studio gia Windows, all

den ja qrhsimopoihje sta plasia tou parntoc majmatoc

18

Paradegmata qrshc tou gcc


gcc myprog.c Metaglttish tou phgaou progrmmatoc myprog.c se antikeimenik arqeo kai klsh tou sundth gia thn kataskeu tou ektelsimou progrmmatoc a.out gcc -o myprog myprog.c Metaglttish tou phgaou progrmmatoc myprog.c se antikeimenik arqeo kai klsh tou sundth gia thn kataskeu tou ektelsimou progrmmatoc myprog gcc -c myprog.c Mno metaglttish tou phgaou progrmmatoc myprog.c sto antikeimenik arqeo myprog.o gcc -o prog myprog1.o myprog2.o -lm Mno klsh tou sundth gia kataskeu tou ektelsimou progrmmatoc prog ap ta antikeimenik arqea myprog1.o kai myprog2.o kai th majhmatik bibliojkh (m) 'Allec endiafrousec epilogc tou gcc, ektc ap tic -o, -c kai -l: Gia na klhje mno o proepexergastc, -E Gia na paraqje to apotlesma se glssa assembly, -S

19

H glssa programmatismo C
Metablhtc, stajerc, tpoi kai dhlseic Entolc antikatstashc, telestc kai parastseic H ro tou elgqou Dom progrmmatoc, sunartseic kai exwterikc metablhtc Embleia kai qrnoc zwc metablhtn Anadrom Dieujnseic jsewn mnmhc, dektec kai pnakec Dunamik dsmeush mnmhc Sumboloseirc Pnakec deiktn, dektec se dektec kai poludistatoi pnakec Dektec se sunartseic Orsmata grammc entoln Aparijmseic, domc, auto-anaforikc domc (lstec, duadik dntra), enseic, peda bit kai dhmiourga nwn onomtwn tpwn Esodoc kai xodoc Qeirismc arqewn Proepexergastc thc C kai makroentolc

20

Kalhmra ksme thc C


/* File: helloworld.c */ #include <stdio.h> main() { printf("Hello world\n"); } % gcc -o helloworld helloworld.c % ./helloworld Hello world %

'O,ti perikleetai msa se /* kai */ jewretai sqlio kai den lambnetai upyh ap ton metaglwttist. H gramm #include <stdio.h> enai odhga proc ton proepexergast thc C na sumperilbei s' ekeno to shmeo ta perieqmena tou arqeou epikefaldac (header le) stdio.h, to opoo periqei qrsimec dhlseic gia tic sunartseic eisdou exdou. Kje prgramma C prpei na periqei akribc ma sunrthsh me noma main, pou enai aut ap thn opoa ja arqsei na ekteletai to ektelsimo prgramma pou ja prokyei ap th metaglttish. H printf enai ma sunrthsh exdou, pou tan klhje, ektupnei ,ti thc qei doje msa stic parenjseic, sthn prokemenh perptwsh to alfarijmhtik sumboloseir (string) "Hello world" (qwrc ta "), akoloujomeno ap ma allag grammc (\n).

21

Pso enai to ;
/* File: picomp.c */ #include <stdio.h> #include <math.h> /* Header file for standard I/O library */ /* Header file for math library */

main() { long i; double sum, current, pi; i = 1; /* Denominator of current term sum = 0.0; /* So far sum do { current = 1/(((double) i)*((double) i)); /* Current term sum = sum+current; /* Add current term to sum i++; /* Next term now } while (current > 1.0e-15); /* Stop if current term is very small pi = sqrt(6*sum); /* Compute approximation of pi printf("Summed %8ld terms, pi is %10.8f\n", i-1, pi); } % gcc -o picomp picomp.c -lm % ./picomp Summed 31622777 terms, pi is 3.14159262 %

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

To prgramma upologzei to me bsh th seir: 1 1 1 1 1 1 1 1 2 = 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + ... 6 1 2 3 4 5 6 7 8 To #include <math.h> qreizetai epeid qrhsimopoietai sto prgramma h majhmatik sunrthsh sqrt, gia thn eresh tetragwnikc rzac. Prosoq: Sthn entol metaglttishc kai sndeshc (gcc) qreizetai kai to -lm, gia na sumperilhfje sto ektelsimo prgramma kai h majhmatik bibliojkh thc C.

22

To i sumbolzei ma akraia metablht sthn opoa ja fulssetai, dhlad sthn perioq thc mnmhc pou thc antistoiqe o metaglwttistc, h tim tou trqontoc paronomast kat ton upologism tou ajrosmatoc. Dhlnetai me mgejoc long, ste na mporon na fulaqjon s' autn akraioi megjouc toulqiston 4 bytes, toi toulqiston mqri to 231 1 = 2147483647. An eqe dhlwje aplc san int, mpore na periorizmastan se 2 bytes ga th flaxh, dhlad wc to 215 1 = 32767. Ta sum, current kai pi enai metablhtc gia th flaxh pragmatikn arijmn, tou mqri stigmc upologismnou ajrosmatoc, tou trqontoc rou thc seirc kai thc telikc proseggistikc timc tou , antstoiqa. Dhljhkan san double gia na qoume eswterik anaparstash twn arijmn autn me megalterh akrbeia (dipl) se dekadik yhfa, ap' autn pou ja eqame an eqan dhlwje san float. Me tic entolc antikatstashc i = 1 kai sum = 0.0, dnoume arqikc timc ston trqonta paronomast kai sto mqri stigmc jroisma. H omda entoln msa sto mplok do {..........} while ja ekteletai suneqc, so o trqwn roc tou ajrosmatoc enai megalteroc ap kpoia elqisth tim, thn 1015 (= 1.0e-15).

23

Se kje epanlhyh tou mplok do {..........} while, upologzoume arqik ton trqonta ro tou ajrosmatoc (to prjema (double) sto i uprqei gia na metatrape h tim tou akeraou i se pragmatik tim diplc akrbeiac, prin summetsqei sthn arijmhtik prxh). Met prostjetai o trqwn roc tou ajrosmatoc sto mqri stigmc jroisma, me to sum = sum+current (sunjwc to grfoume kai san sum += current), kai tloc auxnoume ton trqonta paronomast kat 1, me to i++ (isodnamo me to i = i+1). 'Otan teleisei to mplok do {..........} while, sth metablht sum uprqei to jroisma lwn twn rwn thc seirc pou enai megalteroi ap 1015 . Aut enai perpou 2 so me to . Opte, met upologzoume proseggistik to 6 me thn entol pi = sqrt(6*sum) (dhlad 6 sum). Me thn klsh thc sunrthshc printf ektupnetai to apotlesma. Sugkekrimna, ektupnetai ,ti uprqei msa sta ", all sth jsh tou %8ld ektupnetai h tim tou i-1, san dekadikc (d) akraioc megjouc long (l) se 8 toulqiston jseic, stoiqismnoc dexi. Epshc, sth jsh tou %10.8f ektupnetai h upologismnh tim tou , san pragmatikc arijmc (f) se 10 toulqiston jseic, me dexi stoqish, ap tic opoec oi 8 gia to klasmatik mroc.

24

Gryte progrmmata C pou na upologzoun me arket akrbeia ta paraktw ajrosmata. Mporete na brete me poiouc endiafrontec arijmoc isontai;

S1 =

1 1 1 1 1 1 1 1 2 + 2 2 + 2 2 + 2 2 + ... 12 2 3 4 5 6 7 8

1 1 1 1 1 1 1 1 1 + + + + ... 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 S3 = + + + + ... 1 3 5 7 9 11 13 15 17 1 1 1 1 1 + + + + + ... S4 = 1 3 3 5 5 7 7 9 9 11 1 1 1 1 S5 = + + ... 2 3 4 4 5 6 6 7 8 8 9 10 1 1 1 1 1 1 1 1 S6 = 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + . . . 1 2 3 4 5 6 7 8 S2 =

To dio kai gia to ginmeno:

P =

2 2 4 4 6 6 8 8 ... 1 3 3 5 5 7 7 9

25

Pte enai to Orjdoxo Psqa;


/* File: easter.c */ #include <stdio.h> #define STARTYEAR 2001 #define ENDYEAR 2010 main() { int year, a, b, c, d, e; for (year = STARTYEAR ; year <= ENDYEAR ; year++) { a = year % 19; b = year % 4; /* Gauss method for Easter date computation */ c = year % 7; d = (19*a+15) % 30; e = (2*b+4*c+6*d+6) % 7; printf("Easter in the year %d: ", year); if (d+e+4 > 30) /* Easter in May */ printf(" May %d\n", d+e-26); else /* Easter in April */ printf("April %d\n", d+e+4); } } % gcc -o easter easter.c % ./easter Easter in the year 2001: Easter in the year 2002: Easter in the year 2003: Easter in the year 2004: Easter in the year 2005: Easter in the year 2006: Easter in the year 2007: Easter in the year 2008: Easter in the year 2009: Easter in the year 2010: %

April May April April May April April April April April

15 5 27 11 1 23 8 27 19 4

26

To prgramma efarmzei th mjodo tou Gauss gia ton upologism thc hmeromhnac tou Psqa to toc year. Smfwna me autn, to Psqa enai stic (d + e + 4) Aprilou (an h hmeromhna aut enai megalterh ap 30, tte pftei msa ston Mio), pou d = (19 a + 15) mod 30, e = (2 b + 4 c + 6 d + 6) mod 7, a = year mod 19, b = year mod 4 kai c = year mod 7. Me tic dhlseic #define ......... zhtme ap ton proepexergast thc C na antikatastsei msa sto arqeo, pou brei to smbolo pou akolouje to #define me to smbolo pou enai amswc met. Sthn prokemenh perptwsh, zhtme na antikatastaje to STARTYEAR me 2001 kai to ENDYEAR me 2010. To mplok for( E1 ; E2 ; E3 ) {..........} perigrfei nan brqo pou ja prpei na ektelesje epanalambanmena. Prin arqsei h ektles tou, ja ektelesje h entol E1 . Ef' son h sunjkh E2 enai alhjin, ja gnei h trqousa epanlhyh sto brqo. Me to tloc kje epanlhyhc, ekteletai kai h entol E3 . Stic entolc antikatstashc, o telestc % paristnei to uploipo diareshc (mod). H dom if( C ) E1 else E2 shmanei ti jloume na ektelesje h entol ( mplok entoln) E1 , an h sunjkh C enai alhjc, h entol ( mplok entoln) E2 , an h sunjkh C enai yeudc.

27

Na kataskeuasje magik tetrgwno 5 5


/* File: magic.c */ #include <stdio.h> #define SIZE 5 main() { int i, j, k; int x[SIZE][SIZE]; /* The board to be filled for (i=0 ; i < SIZE ; i++) for (j=0 ; j < SIZE ; j++) x[i][j] = 0; /* Mark all squares as empty i = (SIZE-1)/2; /* Go to middle j = SIZE-1; /* right square for (k=1 ; k <= SIZE*SIZE ; k++) { if (x[i][j] != 0) { /* If current not empty i = i-1; /* Move one square up j = j-2; /* and two squares left if (i < 0) i = i+SIZE; /* If you are outside if (j < 0) j = j+SIZE; /* go to the respective square inside } x[i][j] = k; /* Fill current square with number k i++; /* Move one square down if (i == SIZE) i = 0; /* If outside get inside j++; /* Move one square right if (j == SIZE) j = 0; /* If outside get inside } for (i=0 ; i < SIZE ; i++) { for (j=0 ; j < SIZE ; j++) printf("%4d ", x[i][j]); /* Print out board printf("\n"); } } % gcc -o magic magic.c % ./magic 11 10 4 23 17 18 12 6 5 24 25 19 13 7 1 2 21 20 14 8 9 3 22 16 15 %

*/

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

*/

28

To prgramma efarmzei th mjodo tou De la Loub`re gia e na kataskeusei na magik tetrgwno 5 5 (h mjodoc efarmzetai gia peritt mkoc pleurc), dhlad na plasio me 25 jseic se ditaxh tetragnou msa stic opoec enai topojethmnoi oi arijmo ap to 1 wc to 25, ma for o kajnac, tsi ste se kje gramm, kje stlh kai kje ma ap tic do diagwnouc na qoume to dio jroisma (aljeia, pso;). Gia thn perigraf thc mejdou se ma yeudoglssa, dete ton algrijmo 118, sth deterh selda tou http://www.di.uoa.gr/~ip/magic-sq.pdf. O algrijmoc 117, sthn prth selda tou keimnou auto, mpore na efarmosje gia thn kataskeu magikn tetragnwn rtiac pleurc. Me th dlwsh int x[SIZE][SIZE] zhtme na desmeuje qroc gia na didistato pnaka akerawn x me SIZE (= 5) grammc kai SIZE stlec. Prosoq: Oi grammc kai oi stlec arijmontai ap to 0 wc to SIZE-1 (= 4). Me thn kfrash x[3][1], mporome na anaferjome sto stoiqeo pou brsketai sthn 4h gramm kai 2h stlh. Fusik, sthn C mporome na orsoume kai monodistatouc pnakec, all kai pnakec me distash megalterh ap 2. Parathrste th qrsh twn entoln if. Den uprqei tmma else. An isqei h sunjkh, ekteletai h entol ( mplok entoln) pou akolouje. Allic, o legqoc phganei sthn epmenh entol. O telestc != sth sunjkh thc prthc entolc if shmanei diforo (legqoc an to trqon tetragwndio enai gemto).

29

Metatrop pezn grammtwn se kefalaa


/* File: capitalize.c */ #include <stdio.h> main() { int ch; /* Be careful! Declare ch as int because of getchar() and EOF ch = getchar(); /* Read first character while (ch != EOF) { /* Go on if we didnt reach end of file if (ch >= a && ch <= z) /* If lower case letter ch = ch - (a-A); /* Move a-A positions in the ASCII table putchar(ch); /* Print out character ch = getchar(); /* Read next character } } % gcc -o capitalize capitalize.c % cat capinp.txt This is a text file with 2 lines to test the C program "capitalize.c". % ./capitalize < capinp.txt THIS IS A TEXT FILE WITH 2 LINES TO TEST THE C PROGRAM "CAPITALIZE.C". %

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

H sunrthsh getchar parqetai ap thn prtuph (standard) bibliojkh eisdou-exdou thc C. Diabzei na qaraktra ap thn esodo kai epistrfei sto nom thc thn akraia tim tou ASCII kwdiko tou qaraktra. An den uprqei lloc qaraktrac na diabaste, dhlad ftsame sto tloc thc eisdou, tte epistrfei sto nom thc ma eidik tim, to EOF, pou enai #define'd se ma sugkekrimnh akraia tim msa sto arqeo epikefaldac stdio.h.

30

H omda entoln msa sto mplok while {..........} ja ekteletai suneqc, so uprqoun kai lloi qaraktrec gia na diabsoume ap thn esodo. H sunjkh msa sto if enai ma logik szeuxh (telestc &&). Ta a kai A enai stajerc qaraktra kai isontai me thn arijmhtik tim twn kwdikn twn antstoiqwn qaraktrwn ston ASCII pnaka, dhlad a=97 kai A=65. To sugkekrimno prgramma baszetai sthn upjesh ti ston ASCII pnaka oi kefalaoi latiniko qaraktrec enai se suneqmenec jseic kai ti to dio isqei kai gia touc pezoc. Aut ntwc isqei, gi' aut kai to prgramma douleei swst. Gia thn metatrop enc pezo qaraktra se kefalao, den qreizetai na gnwrzoume tic akribec timc twn ASCII kwdikn, arke na metatopsoume ton pez qaraktra kat a-A jseic. H sunrthsh putchar parqetai epshc ap thn prtuph bibliojkh eisdou-exdou thc C (enai h adelf sunrthsh thc getchar) kai h leitourga thc enai na ektupsei sthn xodo ton qaraktra tou opoou ton ASCII kwdik dnoume msa stic parenjseic.

31

Metablhtc, stajerc, tpoi kai dhlseic sthn C


Metablhtc Sumbolik onmata gia jseic mnmhc Apojkeush kai ankthsh dedomnwn Ankoun se tpouc Stajerc Sugkekrimnec timc Ankoun se tpouc Tpoi dedomnwn Gia akeraouc short int short (sunjwc 2 bytes) int (sunjwc 4, spanitera 2 8, bytes, anloga me to mgejoc lxhc tou epexergast) long int long (sunjwc 4, merikc forc 8, bytes) long long int long long (sunjwc 8 bytes) Gia qaraktrec, all kai akeraouc char (1 byte) Gia pragmatikoc arijmoc (kinhtc upodiastolc) float (aplc akrbeiac, sunjwc 4 bytes) double (diplc akrbeiac, sunjwc 8 bytes) long double (ektetamnhc akrbeiac, sunjwc 16 bytes)

32

Paradegmata stajern Akraiec stajerc (jewrontai tpou int): 237, -12345, 22431L (to L sumbolzei ti epijumome na jewrhje h stajer tpou long), 0224 (o oktadikc arijmc 224), 0x1C (o dekaexadikc arijmc 1C) Stajerc qaraktra: A (o ASCII kwdikc tou qaraktra A, dhlad 65) \n (o ASCII kwdikc gia thn allag grammc) \t (o ASCII kwdikc gia ton sthlognmona, tab) 0 (o ASCII kwdikc tou qaraktra 0, dhlad 48) \0 (o qaraktrac me ASCII kwdik 0) \145 (o qaraktrac me ASCII kwdik ton oktadik arijm 145) \xA2 (o qaraktrac me ASCII kwdik ton dekaexadik arijm A2) Stajerc kinhtc upodiastolc (jewrontai tpou double): 23.78, -1.24e-14 (dhlad 1.24 1014 ) Ma eidik kathgora stajern enai ta alfarijmhtik sumboloseirc (strings). Ma sumboloseir enai ma akolouja ap qaraktrec msa se ", gia pardeigma "Hello world\n". Prkeitai, ousiastik, gia nan pnaka qaraktrwn, qwrc ta ", me teleutao stoiqeo tou pnaka to \0 (parlo pou den shmeinetai sth diatpwsh thc sumboloseirc msa sta ").

33

Me ma dlwsh enhmernetai o metaglwttistc gia thn prjes mac na qrhsimopoisoume sto prgramm mac kpoia kpoiec metablhtc sugkekrimnou tpou, tic opoec mporome na arqikopoisoume kai me stajerc tou tpou auto, an jloume, kai antistoiqe s' autc katllhlec jseic mnmhc. Paradegmata:
int i, j, k; char ch; float x, y = 2.34; long count, cost; double pi = 3.14159;

Ta onmata twn metablhtn mporon na perilambnoun, mqri 31 sunolik, pezoc kai kefalaouc qaraktrec, arijmoc kai ton qaraktra _. Den epitrpetai h qrsh desmeumnwn lxewn thc C (p.q. if, float, for, klp.) gia onmata metablhtn. Den enai kal na orzoume metablhtc sta progrmmat mac pou arqzoun ap _, giat ttoia onmata qrhsimopoiontai gia tic metablhtc ap tic bibliojkec kai endqetai na dhmiourghje prblhma. Parti enai epitrept, den enai kal onmata metablhtn na apotelontai mno ap kefalaouc qaraktrec, giat sunjwc dnoume ttoia onmata stic sumbolikc stajerc pou orzoume me #define, gia na tic diaqeiriste o proepexergastc.

34

Sth dlwsh mac akraiac metablhtc mac metablhtc qaraktra, mpore na prohghje o prosdioristc unsigned, pou dhlnei ti oi arijmo pou fulssontai sth metablht prpei na ermhneujon san jetiko ( mhdn). An uprqei sth dlwsh o prosdioristc signed, den uprqei kannac, to perieqmeno thc metablhtc jewretai akraioc me prshmo (jetik arnhtik). Paradegmata:
signed char ch; unsigned char uch; short i; unsigned long int k;

Sth metablht ch fulssontai arijmo ap 128 (= 27 ) wc 127 (= 27 1), en sthn uch ap 0 wc 255 (= 28 1) Sth metablht i fulssontai arijmo ap 32768 (= 215 ) wc 32767 (= 215 1), en sthn k ap 0 wc 4294967295 (= 232 1) Se dlwsh metablhtc, me tautqronh arqikopohsh, mpore na efarmosje o prosdioristc const, pou exasfalzei ti h tim thc metablhtc den ja allxei. Pardeigma:
const double e = 2.71828;

Gia metablhtc, stajerc, tpouc kai dhlseic, analutiktera stic paragrfouc 2.1 wc 2.4 tou [KR].
a Gia th sunqeia, o sumbolismc [KR] ja anafretai sto biblo:

Brian W. Kernighan, Dennis M. Ritchie, H Glssa Programmatismo C.

35

Entolc antikatstashc, telestc kai parastseic


Oi entolc s' na prgramma C, pwc kai oi dhlseic, teleinoun me na ellhnik erwthmatik (;). 'Ena basik edoc entolc enai h entol antikatstashc ( kat thn pio sunjh orologa, entol anjeshc). Enai thc morfc: metablht = parstash Ma entol antikatstashc qei san apotlesma ton upologism thc timc thc parstashc sto dex mloc tou = kai thn anjesh thc timc autc sth metablht sto arister mloc tou =. Pol suqnc enai oi arijmhtikc parastseic pou perigrfoun prxeic metax akraiwn pragmatikn metablhtn kai stajern, msw twn arijmhtikn telestn, dhlad +, -, *, / kai % (uploipo diareshc). Prosoq! Diaresh metax akerawn dnei san apotlesma to phlko thc diareshc.

36

Parastseic pou emplkoun metablhtc kai stajerc diaforetikn tpwn dnoun san apotlesma tim tou eurterou tpou. Gia pardeigma, kpoia arijmhtik prxh metax int kai double dnei apotlesma double. Anjesh mac timc enc tpou se metablht llou tpou qei san apotlesma th metatrop thc timc ston tpo thc metablhtc, ete qwrc apleia plhroforac, ete me apleia plhroforac, anloga me to an o tpoc thc metablhtc qei th dunatthta na anaparastsei plrwc thn anatijmenh tim. Rht metatrop tpou mpore na gnei msw prosarmogc (cast), gia pardeigma, an h metablht i enai akraiou tpou, h kfrash (double) i anafretai sthn tim thc i san pragmatik arijm diplc akrbeiac.

37

Do pol qrsimoi telestc enai oi telestc monadiaac axhshc (++) kai mewshc (--). 'Otan efarmzontai epnw se ma metablht, ete sta arister ete sta dexi thc, qoun san apotlesma thn axhsh, mewsh antstoiqa, thc timc thc metablhtc kat 1. Gia pardeigma, h akolouja entoln
x = 2; y = 9; x++; --y; ++x; x--; y--; ++y;

ja qei san telik apotlesma oi metablhtc x kai y na qoun telik san timc tic 3 kai 8, antstoiqa. Sto pardeigma aut, den eqe kpoia shmasa h topojthsh twn telestn arister dexi thc metablhtc.

Ektc ap autnomh entol, h efarmog twn telestn monadiaac axhshc se ma metablht, mpore na paxei kai to rlo parstashc ( tmmatoc parstashc). Sthn perptwsh aut, qei shmasa an o monadiaoc telestc enai projematikc (arister thc metablhtc) metajematikc (dexi thc metablhtc).

38

'Enac projematikc telestc monadiaac axhshc mewshc se ma parstash uponoe ti prta prpei na gnei h tropopohsh thc timc thc metablhtc (axhsh mewsh, anloga) kai met na qrhsimopoihje h tropopoihmnh tim gia ton upologism thc timc thc parstashc. 'Enac metajematikc telestc monadiaac axhshc mewshc se ma parstash uponoe ti prta prpei na qrhsimopoihje h trqousa tim thc metablhtc gia ton upologism thc timc thc parstashc kai met na gnei h tropopohsh thc timc thc metablhtc (axhsh mewsh, anloga). Pardeigma:
x y z y z = = = = = 4; 7; ++y; z - (x++); x - (--y);

Ti tim ja qoun oi metablhtc x, y kai z met ap autc tic entolc; a


a 5, 3 kai 2, antstoiqa

39

Pol suqn, sthn C, jloume na elgxoume kpoia sunjkh kai anloga me to apotlesma tou elgqou (alhjc yeudc) na probome se kpoia enrgeia. Oi sunjkec sunjwc enai sugkrseic timn arijmhtikn parastsewn, msw twn susqetistikn telestn ( telestn sgkrishc), pou enai oi >, <, >=, <=, == (so) kai != (diforo). Pio snjetec sunjkec mporon na kataskeuasjon ap aplosterec msw twn logikn telestn && (KAI), || ('H) kai ! (OQI). Ousiastik, oi sunjkec den enai kti diaforetik ap tic parastseic. Ma alhjc sunjkh enai ma parstash me tim sh me 1, en ma yeudc sunjkh jewretai ti qei tim 0. Antstoiqa, ma parstash me tim diforh tou 0 mpore na paxei ton rlo mac alhjoc sunjkhc, en an h tim thc enai 0, enai isodnamh me ma yeud sunjkh. Gia pardeigma, grfontac
if (myvar != 0) { ........

enai akribc to dio me to


if (myvar) { ........

40

Merikc forc, enai pol qrsimo na knoume prxeic se eppedo bit metax akerawn timn (metablhtn kai stajern). Aut epitugqnetai msw twn telestn prxewn me bit, pou enai oi: &: KAI |: 'H ^: apokleistik 'H <<: olsjhsh arister >>: olsjhsh dexi ~: sumplrwma wc proc na Pardeigma:
unsigned char x; x = 178; x = x & 074; x = x | 0xD6; x = x ^ 104; x = x >> 3; x = x << 2; x = ~x;

Poia ja enai h telik tim thc metablhtc x;


a 179

41

Kje dimelc telestc (+, -, *, /, %, &, |, ^, <<, >>) mpore na qrhsimopoihje kai me na sntomo trpo se ma entol antikatstashc, wc exc: metablht telestc = parstash Aut h entol enai isodnamh me thn: metablht = metablht telestc parstash Gia pardeigma, h entol
sum += x;

enai isodnamh me thn


sum = sum + x;

Merikc forc, enai qrsimec kai oi parastseic up sunjkh, san thn sunjkh ? parstash 1 : parstash 2 H tim autc thc parstashc enai aut pou qei h parstash 1 , an h sunjkh enai alhjc (dhlad, an qei tim diforh tou 0, jewrntac thn wc parstash kai aut), aut pou qei h parstash 2 , an h sunjkh enai yeudc (dhlad sh me 0). Pardeigma:
z = (a > b) ? a : b;

Me thn entol aut, h tim thc z ja gnei sh me th megalterh tim ap tic a kai b.

42

H qrsh diafrwn telestn msa se ma parstash mpore na prokalsei sgqush ston anagnsth enc progrmmatoc gia to pc akribc ja prpei na upologisje h tim thc parstashc, dhlad gia th seir me thn opoa ja prpei na efarmosjon oi telestc, qi mwc kai ston metaglwttist. Uprqoun sugkekrimnec proteraithtec metax twn telestn, llec perisstero kai llec ligtero anamenmenec, opte h seir efarmogc twn telestn enai safc. Se perptwsh pou jloume na epibloume sugkekrimno trpo efarmogc twn telestn, prpei na qrhsimopoiome parenjseic, akma kai an emaste bbaioi ti se kpoiec periptseic den enai aparathtec lgw twn proteraiottwn twn telestn. Fusik, prpei na apofegontai uperbolc. Sthn entol
x = y + z*w;

den qreizontai parenjseic an jloume h parstash sto dexi mloc na enai h y + (z*w) (lgw thc anamenmenhc megalterhc proteraithtac tou * nanti tou +, pou ntwc isqei). Bbaia, h parstash (y+z) * w enai diaforetik ap thn prohgomenh.

43

Kje entol antikatstashc mpore na jewrhje kai san parstash me tim autn thn timc thc parstashc pou anajtoume sth metablht. 'Etsi, o kormc tou progrmmatoc capitalize.c
ch = getchar(); while (ch != EOF) { if (ch >= a && ch <= z) ch = ch - (a-A); putchar(ch); ch = getchar(); }

ja mporose na grafe pio sumpuknwmna wc exc:


while ((ch = getchar()) != EOF) { if (ch >= a && ch <= z) ch = ch - (a-A); putchar(ch); }

Prosxte, sth sumpuknwmnh ekdoq, tic parenjseic grw ap thn entol antikatstashc ch = getchar(). Enai aparathtec giat o telestc != qei megalterh proteraithta ap ton =. An den tic bzame, ti ja gintan;

44

Gia entolc antikatstashc, telestc kai parastseic sthn C, uprqei ektetamnh anlush stic paragrfouc 2.5 wc 2.12 tou [KR], pou sunodeetai ap pra poll endiafronta paradegmata. Epshc, to Keflaio 1 ap to [KR] (sel. 19 58) enai ma pol periektik proparaskeuastik eisagwg sthn C, pou emplkei pollc nnoiec oi opoec analontai ektenstera sth sunqeia tou biblou. Enai exairetik qrsimh h eisagwg aut, an mh ti llo gia na prospajsei kanec na katalbei ta progrmmata pou perilambnontai eke kai, giat qi, na dokimsei na lsei kai tic askseic tou.

45

Eresh M.K.D. kai E.K.P. tuqawn arijmn


/* File: gcdlcm.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define COMPUTATIONS 8 #define MAXNUMB 1000 /* Header file for srand and rand functions /* Header file for time function /* Pairs of numbers to compute GCD and LCM /* Maximum number */ */ */ */

main() { int i, m, n, large, small, gcd, rem; long curtime, lcm; curtime = time(NULL); /* Current time (in seconds since 1/1/1970) printf("Current time is %ld\n\n", curtime); srand((unsigned int) curtime); /* Seed for random number generator for (i=0 ; i < COMPUTATIONS ; i++) { m = rand() % MAXNUMB + 1; /* Select 1st number in [1,MAXNUMB] n = rand() % MAXNUMB + 1; /* Select 2nd number in [1,MAXNUMB] if (m > n) { /* Which number is larger? large = m; /* Larger is m small = n; } else { large = n; /* Larger is n small = m; } while (small) { /* While small is not 0 rem = large % small; /* Find remainder of large/small large = small; /* New large is previous small small = rem; /* New small is remainder found } gcd = large; /* GCD of m and n equals to final value of large lcm = (m*n)/gcd; /* LCM(m,n) * GCD(m,n) = m * n printf("GCD(%3d,%3d) = %2d LCM(%3d,%3d) = %6ld\n", m, n, gcd, m, n, lcm); } }

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

*/

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

46

% gcc -o gcdlcm gcdlcm.c % ./gcdlcm Current time is 1130666309 GCD(855,405) GCD(125,139) GCD(996,467) GCD(191,890) GCD(548,612) GCD(378,531) GCD(837,127) GCD(938,656) % = 45 = 1 = 1 = 1 = 4 = 9 = 1 = 2 LCM(855,405) LCM(125,139) LCM(996,467) LCM(191,890) LCM(548,612) LCM(378,531) LCM(837,127) LCM(938,656) = = = = = = = = 7695 17375 465132 169990 83844 22302 106299 307664

Gia thn eresh tuqawn zeugarin jetikn akerawn, qrhsimopoietai h sunrthsh rand, h opoa kje for pou kaletai epistrfei na (yeudo)tuqao arijm. H arqikopohsh thc genntriac (yeudo)tuqawn arijmn gnetai kalntac th sunrthsh srand, dnontc thc san parmetro thn trqousa qronik stigm, pwc aut epistrfetai ap th sunrthsh time (h parmetroc NULL pou dnoume sthn time ja suzhthje sto mllon). Gia thn eresh tou Mgistou Koino Diairth (M.K.D.) do arijmn, qrhsimopoiome ton algrijmo tou Eukledh. Dhlad, brskoume to uploipo thc diareshc tou megalterou me ton mikrtero ap touc arijmoc kai antikajistome ton megaltero me ton mikrtero, ton mikrtero me to uploipo thc diareshc kai epanalambnoume th diadikasa mqri o mikrteroc na gnei soc me 0. Tte o zhtomenoc M.K.D. enai o megalteroc. Gia thn eresh tou E.K.P., qrhsimopoiome th sqsh EKP(m, n) MKD(m, n) = m n.

47

H ro tou elgqou sthn C


'Opwc kai se kje glssa programmatismo, tsi kai sthn C, uprqoun entolc pou ephrezoun th ro tou elgqou sta progrmmata (if, switch, while, for, klp.). Stic entolc autc enai pol suqn h qrsh enc mplok entoln. 'Ena mplok entoln apoteletai ap entolc pou enai kleismnec msa se gkistra ({ kai }). An s' na mplok entoln periqetai ma mno entol, aut den enai aparathto na perikleetai msa se gkistra. Enai exairetik qrsimo na melethje lo to Keflaio 3 ap to [KR] (sel. 85 100), sto opoo perigrfontai analutik lec oi domc elgqou pou prosfrei h C. Akolouje ma pio sunoptik perigraf twn domn autn.

48

Entol if
H sntaxh thc entolc if enai: if ( parstash ) mplok entoln 1 else mplok entoln 2 An h parstash enai alhjc (qei tim diforh ap to mhdn), ja ektelesje to mplok entoln 1 , allic to mplok entoln 2 . To tmma ap to else kai met enai proairetik. An den uprqei kai h parstash enai yeudc, o legqoc ja pei sthn epmenh entol tou progrmmatoc, dhlad sthn prth entol met to if. H proairetikthta tou else mpore na prokalsei problmata sthn anagnwsimthta programmtwn me emfwliasmnec entolc if, an den uprqei safc omadopohsh me gkistra. An den uprqoun gkistra pou na epiblloun sugkekrimnh dom, kje else antistoiqe sthn amswc prohgomenh if pou den qei else. Ti akribc shmanei to paraktw;
if (n > 0) if (a > b) z = a; else z = b;

Prosoq! O metaglwttistc den asqoletai me th stoqish.

49

Aut:
if (n > 0) { if (a > b) z = a; else z = b; }

An jlame to else na antistoiqe sto prto if, prepe na to gryoume tsi:


if (n > 0) { if (a > b) z = a; } else z = b;

Ma sunhjismnh qrsh thc entolc if enai tan jloume na elgxoume ma seir ap epllhlec sunjkec, kai anloga me to poia ja breje ti isqei prth, na ektelsoume na mplok entoln. Aut gnetai wc exc: if ( parstash 1 ) mplok entoln 1 else if ( parstash 2 ) mplok entoln 2 ...................................... else if ( parstash n1 ) mplok entoln n1 else mplok entoln n

50

H prohgomenh entol if ja mporose na grafe se ma ekdoq me stoqish wc exc: if ( parstash 1 ) mplok entoln 1 else if ( parstash 2 ) mplok entoln 2 ...................................... else if ( parstash n1 ) mplok entoln n1 else mplok entoln n H sugkekrimnh stoqish, mwc, mllon knei pio dusangnwsth thn entol, opte enai kal na mhn thn akoloujsei kpoioc. 'Ena pardeigma:
if (x > 0) { sign = 1; printf("Number is positive\n"); } else if (x < 0) { sign = -1; printf("Number is negative\n"); } else { sign = 0; printf("Number is zero\n"); }

51

Entol switch
H sntaxh thc entolc switch enai: switch ( parstash ) { case stajer 1 : entolc 1 case stajer 2 : entolc 2 ........................... default: entolc } H switch enai ma diakladwmnh entol apfashc pou leitourge pwc perigrfetai sth sunqeia. H parstash prpei na enai akraia. Upologzetai h tim thc. Kje stajer i prpei na enai akraia stajer kai den prpei na uprqoun do case me thn dia stajer. An h tim pou qei h parstash isotai me kpoia stajer i , tte o legqoc metafretai stic entolc i . An qi, o legqoc metafretai stic entolc (met to default). Oi entolc i (kai entolc ) den enai aparathto na suniston mplok entoln, dhlad na enai kleismnec msa se { kai }.

52

Met thn ektlesh twn entoln se ma case, o legqoc metafretai stic entolc thc epmenhc case, ektc an teleutaa entol thc prohgomenhc case enai h break. Den enai kal praktik oi entolc mac case na suneqzoun me autc thc epmenhc, ektc an isqei to epmeno. Enai dunatn gia perissterec timc thc mac gia thn parstash na jloume na ektelesje h dia omda entoln. S' autn thn perptwsh, topojetome ta antstoiqa case suneqmena kai bzoume thn omda entoln sto teleutao ap' aut. H perptwsh default enai proairetik. An den uprqei kai den tairizei kama case, o legqoc metafretai met thn entol switch. Pardeigma:
switch (x) { case 1: printf("one\n"); break; case 2: case 3: printf("two or three\n"); break; case 4: printf("four\n"); break; default: printf("other\n"); break; }

Ti ja gintan an leipan kpoiec break; Giat blame break kai sthn default perptwsh;

53

Entolc brqou while


Ma pijan sntaxh thc entolc while enai: while ( parstash ) mplok entoln Arqik upologzetai h parstash . An qei tim diforh tou mhdenc (enai alhjc) ekteletai to mplok entoln . Upologzetai pli h parstash kai ensw enai alhjc, ja gnetai o kkloc ektleshc tou mplok entoln , mqri na gnei h parstash yeudc (dhlad sh me to mhdn). Pardeigma:
f = 1; while (--n) f = f*(n+1);

Ti upologzei aut to while;

Epshc, jumhjete kai thn entol while sto http://www.di.uoa.gr/~ip/cprogs/capitalize.c.

54

'Allh pijan sntaxh thc entolc while enai: do mplok entoln while ( parstash ) Arqik ekteletai to mplok entoln . Met, upologzetai h parstash . An qei tim diforh tou mhdenc (enai alhjc) ekteletai pli to mplok entoln kai suneqzetai o kkloc ektlesc tou, mqri na gnei h parstash yeudc (dhlad sh me to mhdn). Gia lgouc kalterhc anagnwsimthtac tou progrmmatoc, akma kai an to mplok entoln apoteletai ap ma mno entol, sunjwc th bzoume msa se { kai }. Pardeigma:
f = 1; do { f = f*n; } while (--n);

Ti upologzei aut to while;

Epshc, jumhjete kai thn entol do/while sto http://www.di.uoa.gr/~ip/cprogs/picomp.c. H basik diafor twn do ekdoqn thc entolc while enai ti sthn prth perptwsh to mplok entoln mpore kai na mhn ektelesje kama for, an h parstash enai arqik yeudc, en sthn ekdoq do/while, to mplok entoln ja ektelesje toulqiston ma for, afo h parstash elgqetai sto tloc.

55

Entol brqou for


H sntaxh thc entolc for enai: for ( parstash 1 ; parstash mplok entoln
2

; parstash 3 )

Diadikastik, isoduname me tic exc entolc: parstash 1 ; while ( parstash 2 ) { mplok entoln parstash 3 ; } Dhlad, arqik upologzetai h parstash 1 . Sunjwc, prkeitai gia thn arqikopohsh enc dekth pou elgqei ma epanalhptik diadikasa. Sth sunqeia, ekteletai epanalambanmena to mplok entoln , pou apotele to sma thc diadikasac, ensw h parstash 2 , pou sunjwc elgqei thn tim tou dekth elgqou, enai alhjc. Prin th diexagwg nac epanlhyhc, ekteletai kai h parstash 3 , pou sunjwc metabllei to dekth elgqou. Pardeigma:
f = 1; for (i=1 ; i <= n ; i++) f = f*i;

Ti upologzei aut to for;

Epshc, jumhjete kai tic entolc for sta http://www.di.uoa.gr/~ip/cprogs/easter.c kai http://www.di.uoa.gr/~ip/cprogs/magic.c.

56

Enai dunatn kpoia ap tic parstash

3 na mhn uprqei, sunjwc h prth /kai h trth. An den uprqei h deterh, tte den gnetai legqoc gia termatism tou brqou, opte prpei aut na gnei biawc me kpoio trpo msa ap to sma thc epanlhyhc. Se kje perptwsh, poia parstash i kai na lepei, ta ; uprqoun kanonik.
1,2

H entol for ( ; ; ) mplok entoln enai h klasik ulopohsh enc atrmonoc brqou. Epshc, sthn C uprqei kai o telestc , (kmma), me ton opoo mporome na kataskeusoume ma snjeth parstash pou ja upologisje ap arister proc ta dexi. H tim thc snjethc parstashc isotai me thn tim thc dexiterhc ap tic aplc pou thn suniston. Merikc forc, jloume na gryoume ma entol for pou ja elgqetai ap perissterouc tou enc dektec. Aut gnetai qrhsimopointac ton telest , sthn parstash 1 kai sthn parstash 3 . Pardeigma:
for (i=0, j=n ; i <= j ; i++, j--) printf("%d\n", i*j);

57

Entolc break kai continue


Ma qrsh thc entolc break enai aut pou edame sthn entol switch, gia ton termatism thc akoloujac entoln pou ja ektelesjon tan tairixei kpoia sugkekrimnh case. Epshc, me thn entol break, mporome na termatsoume biawc tic epanalyeic enc brqou (while, do/while for), prin isqsei h sunjkh termatismo ( tan o brqoc enai atrmwn). Pardeigma:
while (!finished) { ...................... if (bad_data) break; ...................... }

Me thn entol continue, o legqoc sto eswterik enc brqou metafretai sto tloc tou, gia na arqsei h epmenh epanlhyh. Pardeigma:
for (i=0 ; i < n ; i++) { if (a[i] < 0) /* Ignore negative elements */ continue; ............. /* Process positive elements */ }

58

Entol goto kai etiktec


Kje glssa programmatismo, tsi kai h C, qei ma entol gia rht metafor tou elgqou se kpoio llo shmeo (etikta) tou progrmmatoc. Sthn C, h entol aut enai h goto. H goto mpore na qrhsimopoihje se pol exeidikeumnec periptseic, gia pardeigma tan jloume na gnei baih xodoc ap fwliasmnouc brqouc, tan o legqoc brsketai se kpoio eswterik brqo. Aut den mpore na gnei me thn entol break. Pardeigma:
for (i=0 ; i < n ; i++) for (j=0 ; j < m ; j++) if (a[i] == b[j]) goto found; .............. /* Didnt find common element */ found: .............. /* Found a[i] == b[j] */

H entol goto blptei sobar thn ida tou domhmnou programmatismo, giat mpore na odhgsei se progrmmata dusangnwsta kai dskola sunthrsima, kai gi' aut prpei na qrhsimopoietai spnia, an qi kajlou. a
a Sta plasia tou sugkekrimnou majmatoc, apl APAGOREUETAI h

qrsh thc.

59

Dom enc progrmmatoc C

Sunartseic

Ma sunrthsh C enai na autnomo, paketarismno tmma progrmmatoc pou frei se prac ma diadikasa h opoa qei safec prodiagrafc eisdou kai exdou kai sugkekrimno noma. Sunjwc, kwdikopoiome se ma sunrthsh nan algrijmo pou prkeitai na qrhsimopoisoume sto prgramm mac arketc forc ektimome ti enai genikterhc qrhsimthtac kai ja mporose na fane qrsimoc kai se progrmmata pou ja gryoume sto mllon. Se genikc grammc, enai kal praktik na grfoume progrmmata C pou apotelontai ap pollc kai mikrc sunartseic, par ap lgec kai meglec. Akribc ma ap tic sunartseic enc progrmmatoc C prpei na qei to noma main. Enai h sunrthsh ap thn opoa ja xekinsei h ektlesh tou progrmmatoc. Orismc sunrthshc: tpoc noma sunrthshc ( tupikc parmetroi ) { dhlseic kai entolc }

60

Gia ton orism kje sunrthshc, prta dhlnoume to noma pou qei kai, msa se parenjseic, ta onmata kai touc tpouc pou qoun oi, legmenec, tupikc parmetroi , ef' son uprqoun. Oi tupikc parmetroi mac sunrthshc enai metablhtc, stic opoec dnontai sugkekrimnec timc kat thn klsh thc sunrthshc kai oi opoec qrhsimopoiontai msa sto sma thc sunrthshc ( dhlseic kai entolc ) gia na epiteuqje o stqoc thc sunrthshc. To sma mac sunrthshc perikleetai msa se { kai }. Ma sunrthsh mpore na epistryei kpoia tim sto nom thc, h opoa na qrhsimopoihje ap thn sunrthsh pou thn klese. O tpoc thc timc pou epistrfei ma sunrthsh dnetai mprost ap to nom thc, ston orism thc. An den orzetai tpoc epistrofc gia ma sunrthsh, jewretai ti epistrfei int. An den endiafermaste na epistryei ma sunrthsh kpoia tim, prpei na orzoume ti epistrfei void, ton ken tpo. Akma kai an qoume orsei ma sunrthsh na epistrfei kpoio tpo, qi void, den enai telik upoqrewtik na to knei, kai an to knei, den enai upoqrewtik gia thn kalosa sunrthsh na qrhsimopoisei thn epistrefmenh tim.

61

H epistrof timc ap sunrthsh gnetai me thn entol return parstash . Upologzetai h tim pou qei h parstash , epistrfetai kai h sunrthsh termatzei. Me ma apl entol return termatzei qwrc na epistrafe kpoia tim. H sunrthsh main mpore na orzetai
1. ete qwrc tupikc paramtrouc 2. ete me do paramtrouc sugkekrimnwn tpwn, msw twn opown mpore na gnwrzei h main an to prgramma ektelsjhke me orsmata sth gramm entolc kai, an nai, me poia. Perisstera, gi' aut to jma, argtera.

Epshc, h main mpore na epistryei tim tpou int, h opoa enai diajsimh sto peribllon tou leitourgiko sustmatoc ap to opoo ektelsjhke to prgramma. O metaglwttistc apaite prin thn klsh mac sunrthshc na gnwrzei touc tpouc twn tupikn paramtrwn thc kai ton tpo thc epistrefmenhc timc. Sunepc, prpei na prohgetai o orismc mac sunrthshc ap thn klsh thc, , an petai, na qei prohghje aplc ma proanaggela thc sunrthshc (tpoc epistrefmenhc timc, noma kai tpoi tupikn paramtrwn), to legmeno prwttupo thc sunrthshc. Perisstera gia sunartseic, stic paragrfouc 4.1 kai 4.2 tou [KR].

62

Sunrthsh ywshc se dnamh


/* File: powers.c */ #include <stdio.h> #define MAXM 4 #define MAXN 6 int power(int, int); /* Maximum base of powers to compute */ /* Maximum exponent */ /* Prototype of power */

main() { int m, n, p; for (m=2 ; m <= MAXM ; m++) /* Start from base 2 */ for (n=2 ; n <= MAXN ; n++) { /* Start from exponent 2 */ p = power(m,n); /* Call power function */ printf("%d^%d = %d\n", m, n, p); } } int power(int base, int n) { int p; for (p=1 ; n > 0 ; n--) /* base^n equals to */ p *= base; /* base * base * ... * base (n times) */ return p; /* Return result */ } % gcc -o powers powers.c % ./powers 2^2 = 4 2^3 = 8 2^4 = 16 2^5 = 32 2^6 = 64 3^2 = 9 3^3 = 27 3^4 = 81 3^5 = 243 3^6 = 729 4^2 = 16 4^3 = 64 4^4 = 256 4^5 = 1024 4^6 = 4096 %

63

Sunrthsh upologismo paragontiko


/* File: factorial.c */ #include <stdio.h> #define MAXN 12 /* Compute factorials up to MAXN */ */ */ */ */

int factorial(int n) /* No prototype needed { int f; for (f=1 ; n > 0 ; n--) /* Initialize factorial to 1 f *= n; /* Multiply into factorial n, n-1, ..., 1 return f; /* Return result }

main() { int n; /* For all n from 1 to MAXN */ for (n=1 ; n <= MAXN ; n++) /* Call function and */ printf("%2d! = %d\n", n, factorial(n)); /* print result */ } % gcc -o factorial factorial.c % ./factorial 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 11! = 39916800 12! = 479001600 %

64

Embleia kai qrnoc zwc metablhtn


Oi metablhtc pou orzontai msa se ma sunrthsh lgontai autmatec topikc. O lgoc enai ti oi metablhtc autc qoun periorismnh embleia kai qrno zwc. Isqoun mno msa sth sunrthsh pou qoun orisje kai gia so qrno ekteletai h sunrthsh. Ektc ap tic autmatec metablhtc, mporome na orsoume s' na prgramma C kai exwterikc kajolikc metablhtc. Oi metablhtc autc orzontai pwc kai oi autmatec (me ton tpo touc, to nom touc kai me pijan arqikopohs touc), mno pou orzontai xw ap sunartseic, sto dio eppedo me autc. Oi exwterikc metablhtc qoun to protrhma ti enai oratc ap kje sunrthsh, mporon dhlad na qrhsimopoihjon sta smata twn sunartsewn, kai diathrontai kajlh th dirkeia thc ektleshc tou progrmmatoc. Msw twn exwterikn metablhtn, mpore na epiteuqje epikoinwna metax sunartsewn qwrc na qreizetai dedomna pou kpoia sunrthsh prpei na persei se kpoia llh na to knei aut msw paramtrwn.

65

To pleonkthma pou prosfroun oi exwterikc metablhtc mpore na metatrape se meionkthma, an den qrhsimopoiontai me feid. Progrmmata pou qrhsimopoion eurwc exwterikc metablhtc mpore na enai pol dusangnwsta kai dskola sunthrsima. Epshc, sunartseic pou baszontai se exwterikc metablhtc den enai genikc qrshc. An na prgramma enai diaspasmno se poll arqea kai jloume na qoume ma exwterik metablht pou na enai orat ap tic sunartseic se la ta arqea, tte prpei se akribc na arqeo na dsoume ton orism thc metablhtc, gia pardeigma
int sp;

en se kajna ap ta lla arqea prpei na knoume ma dlwsh thc metablhtc, protssontac ton prosdiorist extern, gia pardeigma
extern int sp;

Ousiastik, o metaglwttistc desmeei mnmh gia ma exwterik metablht tan dei ton orism thc (gi' aut prpei na uprqei autc akribc ma for) kai enhmernetai gia ton tpo mac metablhtc tan dei ma dlws thc me extern (jumhjete ti an na prgramma enai diaspasmno se poll arqea, ta arqea aut metaglwttzontai xeqwrist).

66

An jloume h embleia mac exwterikc metablhtc na enai mno to arqeo sto opoo orzetai kai na mhn sugqetai me kpoia exwterik metablht me to dio noma, all se llo arqeo, mporome na protxoume tou orismo thc ton prosdiorist static, gia pardeigma
static double sum;

O prosdioristc static mpore na efarmosje kai se metablhtc pou orzontai msa se sunrthsh, mwc me llh shmasa. H embleia mac topikc metablhtc pou qei orisje san static msa se sunrthsh, enai h sunrthsh aut, all h metablht den enai autmath. Diathretai, pwc kai h tim thc, kai met ton termatism thc sunrthshc. Se na klsh thc sunrthshc, h metablht qei thn tim pou pre met thn prohgomenh klsh. Mh arqikopoihmnec exwterikc metablhtc jewrontai ti qoun tim 0. Mh arqikopoihmnec autmatec metablhtc qoun aprosdiristec timc. Oi tupikc parmetroi mac sunrthshc enai autmatec metablhtc gia th sunrthsh.

67

Oi autmatec metablhtc se ma sunrthsh mporon na orzontai, ektc ap to eppedo tou smatoc thc sunrthshc, kai se pio eswterik mplok entoln (gia pardeigma sto sma mac entolc while). An uprqoun pollaplo orismo gia to dio noma metablhtc se difora mplok, msa se kajna ap' aut isqei o orismc pou gine s' aut, , an den uprqei, autc pou gine sto amswc pio exwterik tou, , an den uprqei, sto pio exwterik, k.o.k. An uprqei sgkroush onmatoc metax mac exwterikc metablhtc kai mac autmathc msa s' na mplok, isqei h autmath. Pardeigma:
int count; float y; double myfun(int y) { int i; .............. while (......) { int i, j; .......... for (.......) { int count; .......... } } }

Poiec metablhtc isqoun po;

68

'Otan metaglwttzetai na prgramma, desmeetai o apaitomenoc qroc gia na fulaqjon lec oi exwterikc metablhtc tou progrmmatoc (all kai oi topikc metablhtc pou qoun dhlwje san static msa se sunartseic). O qroc autc enai twn statikn (kajolikn) dedomnwn kai enai ek twn protrwn gnwstc kai desmeumnoc msa sto ektelsimo prgramma kai antistoiqe sto qro pou ja katalhfje sth mnmh tan fortwje to prgramma gia na ektelesje. Oi autmatec metablhtc mac sunrthshc, akribc epeid qoun periorismno qrno zwc, qoun na diaforetik trpo flaxhc, msw thc, legmenhc, stobac. H stoba gia na prgramma enai ma dom tpou LIFO (Last In First Out), dhlad mporome na eisgoume diadoqik stoiqea s' autn, all an jloume na exaggoume kpoio, ja exaqje aut pou eisqjh pio prsfata. 'Otan kaletai ma sunrthsh, o legqoc metafretai s' autn, all prin arqsei h ektles thc, desmeetai qroc sth stoba gia tic autmatec metablhtc thc (sumperilambanomnwn kai twn tupikn paramtrwn thc). An h sunrthsh aut kalsei sto sma thc llh sunrthsh, akoloujetai h dia diadikasa.

69

'Otan termatzei ma sunrthsh, epistrfei, an qreizetai, kpoia tim sth sunrthsh pou thn klese kai eleujernetai o qroc sth stoba pou eqe krathje gia to peribllon (autmatec metablhtc) thc sunrthshc. O mhqanismc flaxhc twn autmatwn metablhtn twn sunartsewn sth stoba epitrpei th qrsh mac pol isqurc programmatistikc dunatthtac, thc anadromc (recursion). Ma sunrthsh enai anadromik tan kale ton eaut thc. Lgw thc stobac, den uprqei kndunoc sgqushc me tic metablhtc thc sunrthshc kai tic timc touc, afo se kje klsh dhmiourgetai no peribllon sth stoba gia tic metablhtc thc sugkekrimnhc energopohshc. Fusik, prpei h anadromik klsh mac sunrthshc na gnetai up sunjkh, giat allic h ektlesh tou progrmmatoc den ja mporose na gnei me peperasmno trpo. Gia exwterikc kai autmatec metablhtc, all kai gia thn anadrom, dete tic paragrfouc 4.3, 4.4 kai 4.6 wc 4.10 tou [KR].

70

Upologismc paragontiko me anadrom


/* File: recfact.c */ #include <stdio.h> #define MAXN 12 int recfact(int); /* Compute factorials up to MAXN */ /* Prototype of recfact */

main() { int n; /* For all n from 0 to MAXN */ for (n=0 ; n <= MAXN ; n++) /* Call function and */ printf("%2d! = %d\n", n, recfact(n)); /* print result */ } int recfact(int n) { if (!n) return 1; else return n*recfact(n-1); } % gcc -o recfact recfact.c % ./recfact 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 11! = 39916800 12! = 479001600 %

/* If n == 0 */ /* 0! = 1 */ /* n! = n * (n-1)! */

71

Metatropc metax dekadikn kai duadikn arijmn


/* File: convdecbin.c */ #include <stdio.h> #define ERROR -1 /* Return value for illegal character */ int getinteger(int base) { char ch; /* No need to declare ch as int - no EOF handling int val = 0; /* Initialize return value while ((ch = getchar()) != \n) /* Read up to new line if (ch >= 0 && ch <= 0+base-1) /* Legal character? val = base*val + (ch-0); /* Update return value else return ERROR; /* Illegal character read return val; /* Everything OK - Return value of number read } main() { int n, digs[32], ind=0; printf("Please, give a binary number: "); n = getinteger(2); /* Read binary number if (n == ERROR) { printf("Sorry, illegal character\n"); return 1; } else /* Print decimal value of number printf("Decimal equivalent is: %d\n", n); printf("Please, give a decimal number: "); n = getinteger(10); /* Read decimal number if (n == ERROR) { printf("Sorry, illegal character\n"); return 1; } else { /* Convert number to binary digits while (n) { /* Repeat until number equals to 0 digs[ind++] = n%2; /* New digit is number mod 2 n = n/2; /* New number is number/2 } printf("Binary equivalent is: "); while (ind--) /* Print digits in reverse order printf("%d", digs[ind]); printf("\n"); } }

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

*/

*/

*/

*/ */ */ */

*/

72

% gcc -o convdecbin convdecbin.c % ./convdecbin Please, give a binary number: 1000100101111010001001001 Decimal equivalent is: 18019401 Please, give a decimal number: 18019401 Binary equivalent is: 1000100101111010001001001 % ./convdecbin Please, give a binary number: 10011101 Decimal equivalent is: 157 Please, give a decimal number: 65535 Binary equivalent is: 1111111111111111 %

An jewrosame ti h sunrthsh getinteger enai genikc qrhsimthtac, ti akribc ja prepe na bloume s' na phgao arqeo getinteger.c kai ti s' na arqeo epikefaldac getinteger.h, ste na qrhsimopoiome th sunrthsh aut kai se lla progrmmata; Kai na prblhma: H akolouja Fibonacci orzetai wc exc: a0 = 1 a1 = 1 an = an1 + an2 , n 2
Gryte prgramma C pou na upologzei, gia dedomno k , ton (k + 1)-ost ro ak thc akoloujac Fibonacci. Ulopoiste do diaforetikc ekdoqc tou progrmmatoc, ma qwrc anadrom kai ma me anadrom. 'Eqete na sqolisete kti;

73

Dektec
'Enac dekthc sthn C enai ma metablht sthn opoa mporome na kataqwrsoume kpoia diejunsh mnmhc. Sth diejunsh aut mporome na fulxoume kpoia tim sugkekrimnou tpou. H apl ekdoq mac dlwshc metablhtc tpou dekth enai thc morfc: tpoc * metablht Me th dlwsh aut orzoume th metablht na enai dekthc se dedomna pou o tpoc touc enai tpoc . Mporome mwc na orsoume ma metablht na enai dekthc se dedomna tpou dekth pou deqnoun se dedomna pou o tpoc touc enai tpoc . Aut mpore na gnei me ma dlwsh thc morfc: tpoc ** metablht Den uprqei amfibola ti h taktik aut genikeetai kai se pio polplokec dhlseic (dekthc se dekth se dekth klp.), all oi pragmatik qrsimoi dektec, sth meglh pleioyhfa twn programmtwn pou grfoume, enai auto pou orzoume me tic parapnw dhlseic. Per deiktn, all kai pinkwn, pou ja suzhtsoume sth sunqeia, to Keflaio 5 ap to [KR] (sel. 135 178) enai ma anexntlhth phg plhroforin. a
a Ektc, swc, ap ta jmata thc dunamikc dsmeushc mnmhc, pou upr-

qei ma sqetik dustoka.

74

Pardeigma:
int *p; double *pd; char **ppc;

Oi metablhtc p kai pd orsthkan san dektec se akeraouc kai pragmatikoc diplc akrbeiac, antstoiqa. H metablht ppc enai dekthc se jsh mnmhc pou mporome na fulxoume dekth se qaraktrec. Dete kai to sqma:
1003 12543 int 5005 1003 int *p 1007 -3786 int 5011 1013 double *pd 1013 3.14159 double 5019 5025 char **ppc 1021 0.387652e-26 double 5025 1029 char* 1029 1034 1038

g o o d \0 b a d \0 \n \n \0 char 5029 1034 char* 5033 1038 char*

To smbolo * efarmosmno se metablhtc tpou dekth qrhsimopoietai kai stic entolc tou progrmmatoc, wc telestc mmeshc anaforc. 'Otan qoume orsei ma metablht tpou dekth, h kfrash * metablht paristnei to perieqmeno thc jshc mnmhc sthn opoa deqnei h metablht .

75

O antstrofoc tou telest * enai o &. H kfrash & metablht paristnei th diejunsh pou fulssetai h tim gia th metablht , ,ti tpou kai na enai aut. Dhlad, oi telestc * kai & diabzontai wc exc: &p = h diejunsh mnmhc pou enai apojhkeumno to p *p = to perieqmeno thc jshc mnmhc pou deqnei to p Pardeigma:
int x = 5, y, *px, *py, *pz; char c = F, *pc, d; px = &x; py = &y; pc = &c; pz = py; *pz = (*px)++; d = --(*pc); pc = &d; (*pc)--;

Poiec oi timc twn x, y, c, d met ap autc tic entolc;

Ja mporosame na eqame gryei --*pc ant gia --(*pc); b Epshc, gryame (*px)++. Oi parenjseic qreizontai sthn kfrash aut, an jloume o telestc monadiaac axhshc ++ na efarmosje epnw sto perieqmeno thc jshc mnmhc pou deqnei o dekthc px. An eqame gryei *px++, lgw thc uyhlterhc proteraithtac tou telest ++ (all kai tou --) nanti tou telest *, aut ja smaine to *(px++).
a 6, 5, E kai D, antstoiqa b Nai, giat qi;

76

Ti shmanei mwc to *(px++) ( to isodnam tou *px++);

'Omwc, poio enai to nhma na auxsoume na meisoume na dekth kat 1, dhlad na knoume ton dekth na deqnei sthn epmenh prohgomenh jsh mnmhc ap aut pou deiqne; 'Eqei nhma an anafermaste se suneqmenec jseic mnmhc pou, me kpoio trpo, qoume desmesei kai qrhsimopoiome. Ektc ap thn axhsh mewsh enc dekth kat 1 (msw twn telestn monadiaac axhshc kai mewshc ++ kai --), mporome na prosjsoume se na dekth na afairsoume ap autn ma akraia stajer. 'Allec prxeic metax deiktn den epitrpontai, ektc ap thn afaresh deiktn pou deqnoun se stoiqea enc mplok ap dedomna tou diou tpou, pou qoun desmeuje, me kpoio trpo, gia eniaa diaqerish. Epshc, epitrpontai kai sugkrseic metax ttoiwn deiktn.
a 'Oqi, DEN shmanei ti prta ja auxhje o dekthc px kai met ja p-

roume to perieqmeno thc jshc mnmhc pou deqnei h na, auxhmnh, tim tou dekth. Oi parenjseic den deqnoun th seir pou ja gnoun oi upologismo, all to po efarmzontai oi telestc. Sto prokemeno pardeigma, o telestc ++ enai metajematikc, ra prta ja proume to perieqmeno thc jshc mnmhc pou deqnei o dekthc px kai met ja auxhje o dekthc. An jlame prta na auxsoume ton dekth kai met na knoume thn anafor, prepe na gryoume *(++px).

77

An oi pi, pc kai pd enai dektec (se int, char kai double, antstoiqa), oi paraktw entolc enai apoltwc nmimec:
pi = pi+3; pc -= 4; pd = pd-2;

H prsjesh se (afaresh ap) na dekth p mac stajerc n, metabllei ton dekth ste na dexei n jseic mnmhc (qi n bytes), megjouc so aut tou tpou dedomnwn pou deqnei o dekthc, pio met (prin). An oi int, char kai double enai twn 4, 1 kai 8 bytes, antstoiqa, pso ja metablhjon oi dektec pi, pc kai pd; a

Ma pol sunhjismnh qrsh twn deiktn enai sthn perptwsh pou jloume kpoia sunrthsh na epistryei kpoia tim ( kai perissterec), qi san epistrefmenh tim sto nom thc, all epidrntac stic metablhtc thc sunrthshc pou thn klese. Tte, h kalosa sunrthsh prpei na persei sthn kaloumnh th diejunsh mac metablhtc thc, sthn opoa h kaloumnh ja gryei thn tim pou prpei na epistryei. Jewrste to exc prblhma: Jloume na gryoume ma sunrthsh swap, h opoa na antallssei ta perieqmena do akraiwn metablhtn.
a 12, -4 kai -16, antstoiqa

78

'Estw ti gia na antallxoume tic timc twn akraiwn metablhtn a kai b protijmeja na kalsoume th sunrthsh swap(a,b), thn opoa qoume orsei wc exc:
void swap(int x, int y) { int temp; temp = x; x = y; y = temp; }

Giat enai ljoc aut;

Pc ja grfame th swst swap; 'Etsi:


void swap(int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; }

Kai pc ja thn kalosame gia na antallxoume tic timc twn metablhtn a kai b; b

Kai giat qreiazmaste th metablht temp;

a 'Estw ti prin kalsoume thn swap(a,b), oi timc twn metablhtn a kai

b enai 5 kai 8, antstoiqa. Tte, ousiastik kalome swap(5,8), dhlad oi tupikc parmetroi x kai y thc swap, pou enai topikc/autmatec metablhtc gia th sunrthsh, parnoun tic timc 5 kai 8, antstoiqa, antallssontai msa sthn swap oi timc twn x kai y, all oi metablhtc a kai b thc kalosac

sunrthshc den ephrezontai kajlou ap thn allag aut.

b swap(&a,&b) g Gia ton dio lgo pou qreiazmaste na trto potri an jloume na

antallxoume ta perieqmena do llwn pothrin, ektc ki an emaste taqudaktulourgo (:-).

79

Per angnwshc akerawn (kai qi mno)


Mqri stigmc, den gnwrzame kpoio eqrhsto trpo na diabsoume nan akraio msa ap na prgramma C. Tra, me th qrsh deiktn, aut enai efikt. H prtuph bibliojkh eisdou-exdou thc C parqei kai th sunrthsh scanf, pou enai h adelf sunrthsh thc printf, kai me thn opoa mporome na diabsoume ap thn esodo enc progrmmatoc dedomna proc epexergasa. H scanf suntssetai me antstoiqo trpo auto thc printf, dhlad sthn prth parmetro dnoume ma sumboloseir pou perigrfei ti tpwn dedomna skopeoume na diabsoume kai me poion trpo. Oi epmenec parmetroi anafrontai sto po ja fulaqjon oi timc pou diabsthkan. Mno PROSOQH! Epeid h sunrthsh scanf prkeitai na epistryei sth sunrthsh pou thn klese kpoiec timc, stic antstoiqec paramtrouc DEN bzoume tic metablhtc stic opoec jloume na fulaqjon oi timc autc, all dektec stic metablhtc autc. Enai o dioc akribc lgoc gia ton opoo th sunrthsh swap thn kalome san swap(&a,&b), pou a kai b enai akraiec metablhtc.

80

Pardeigma:
int id, rank, *prank; float salary; prank = &rank; printf("Please give id and rank: "); scanf("%d %d", &id, prank); printf("Please give salary: "); scanf("%f", &salary);

H angnwsh timn gia thn akraia metablht id kai th metablht kinhtc upodiastolc salary gnetai pernntac stic sunartseic scanf dektec stic metablhtc autc. 'Omwc sthn prth scanf persame thn dia th metablht prank, afo aut qei dh orisje san dekthc se akraio. Bbaia, sth sunqeia, gia na anaferjome sthn tim pou diabsame, aut prpei na gnei msw tou telest mmeshc anaforc, dhlad *prank, msw thc metablhtc rank. a Oi prodiagrafc %d kai %f stic scanf upodeiknoun ti oi timc pou ja diabaston enai akraiec kai kinhtc upodiastolc, antstoiqa. Uprqoun kai llec prodiagrafc pou mpore na qrhsimopoihjon gia angnwsh timn ap thn scanf, kajc kai kpoiec endiafrousec dunatthtec pou parqontai ap th sunrthsh. Gia perisstera, man scanf tan ja anaferjome analutiktera stic sunartseic thc prtuphc bibliojkhc eisdou-exdou thc C.
a Ja mporosame na eqame apofgei thn entol prank = &rank;

81

Pnakec
'Otan jloume sthn C na qeiristome na snolo ap dedomna diou tpou me eniao kai genik trpo, orzoume na pnaka sugkekrimnou megjouc gia th flaxh twn dedomnwn autn. Me th dlwsh
int myarray[20];

orzoume na monodistato pnaka akerawn me noma myarray ston opoo mporon na fulaqjon to pol 20 akraiec timc. To 20 enai h distash tou pnaka.

'Enac pnakac apojhkeetai sth mnmh se suneqmenec pnta jseic. Msa sto prgramm mac, mporome na anafermaste sta stoiqea tou pnaka myarray, pou qei oriste me distash 20, san myarray[0], myarray[1], . . ., myarray[19]. Genik, me to myarray[i] anafermaste sto stoiqeo tou pnaka myarray me dektha i, pou to i mpore na enai kpoia parstash, qi mno stajer metablht, h opoa prta ja apotimhje kai met ja gnei h prosplash tou stoiqeou myarray[i].
a Prosoq sthn orologa! Ton ro dekthc ed, ton qrhsimopoiome

san ellhnik apdosh tou Aggliko index. Prkeitai gia dekth pnaka. Oi dektec mwc pou edame sthn prohgomenh enthta enai dektec dieujnsewn kai antistoiqon ston Agglik ro pointer. Gia th sunqeia, den ja knoume idiaterh anafor, tan qrhsimopoiome ton ro dekthc, se poia ekdoq anafermaste. Ja prokptei aut ekola ap ta sumfrazmena.

82

An h distash enc pnaka enai N, oi dektec twn stoiqewn tou kumanontai ap 0 wc N-1. Prosoq sto klasik ljoc pou gnetai ston programmatism me th diaqerish pinkwn! Appeira prsbashc ektc twn orwn enc pnaka den enai dunatn na diagnwsje ap ton metaglwttist, me sunpeia na prokyei sobar prblhma kat thn ektlesh tou progrmmatoc. Enai eujnh tou programmatist na exasfalsei ti tan sto prgramm tou knei prsbash sto stoiqeo x[i], pou o pnakac x qei orisje me distash, stw, 100, tte to i den ja qei tim mikrterh ap to 0 megalterh ap to 99, tan gnetai h anafor sto x[i]. Allic . . . Sto Unix, gia pardeigma, ja proume na megaloprepc Segmentation fault kanna Bus error kat thn ektlesh tou progrmmatoc. a
a Eutuqc, dhlad, giat se lla programmatistik peribllonta, mpo-

re na mhn qoume kama ndeixh gia to prblhma, kai na nomzoume ti to prgramm mac enai swst. Bbaia, gia na emaste dkaioi, akma kai sto Unix mpore, se kpoiec periptseic, na mhn proume kpoia ndeixh ti qoume knei ljoc diaqerishc mnmhc kai na nomzoume ti to prgramm mac douleei swst, en aut ja knei lla ant' llwn.

83

Uprqei pol sten sqsh metax twn pinkwn kai twn deiktn dieujnsewn sthn C. Ousiastik, to noma enc pnaka enai nac stajerc dekthc sto prto stoiqeo tou pnaka. Gia pardeigma, an qoume orsei nan pnaka a, tte h kfrash *(a+i) enai isodnamh me thn a[i]. Omowc, kai oi ekfrseic a+i kai &a[i] enai isodnamec. An s' na dekth pa, pou deqnei se stoiqea diou tpou me ton tpo twn stoiqewn enc pnaka a, anajsoume san tim th diejunsh tou prtou, kpoiou llou, stoiqeou tou pnaka, oi ekfrseic pa+ N , pou N enai akraia parstash, enai nmimec wc dieujnseic gia prosplash twn stoiqewn tou pnaka, arke na qoume exasfalsei ti deqnoun msa sta ria tou pnaka. Epshc, mporome ton dekth pa na ton auxnoume na ton meinoume, kai, genik, na ton tropopoiome, kat bolhsh (p.q. pa++, --pa, klp.), pnta up thn propjesh ti msw tou tropopoihmnou dekth ja prospelanoume stoiqea tou pnaka entc twn orwn tou.

84

Pardeigma:
int i, a[8], *pa; for (i=0 ; i<8 ; i++) a[i] = i*i; pa = &a[0]; a[6] = *(a+4); *(pa+3) = a[5]; a[0] = *((pa++)+2); *((++pa)+5) = a[1]; *(&a[5]-1) = *(--pa);
pa: pa+1: pa+2:

a:

16

25

36

49

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7]

Poia ja enai ta perieqmena tou pnaka a met thn ektlesh twn parapnw entoln; a

Prosxte ti en sto prohgomeno pardeigma, tropopoiosame ton dekth pa, aut den mpore na gnei gia to noma tou pnaka, parti enai epitrept na qrhsimopoihje san dekthc (p.q. *(a+4)). Dhlad, apagoreetai na gryoume a++.
a 4, 1, 4, 25, 1, 25, 16, 1

85

Merikc forc, jloume na orsoume ma sunrthsh, h opoa na epexergzetai ta stoiqea enc pnaka. Fusik, ma lsh enai na qei dhlwje o pnakac exwterikc, opte mpore na gnei h epikoinwna me thn kalosa sunrthsh pol apl. Enai pijan, mwc, gia diforouc lgouc, kurwc gia na enai h sunrths mac genikc qrshc, na jloume na persoume ton pnaka sth sunrthsh san parmetro. Sthn perptwsh aut, aplc pernme na dekth sto prto stoiqeo tou pnaka kai, msw auto, h sunrthsh mpore na prospelsei opoiodpote stoiqeo tou. Pardeigma:
main() { int x[50], *myp; .............. myfun(&x[0]); .............. } void myfun(int *px) { int y; .............. y = *(px+2); .............. }

86

Sto prohgomeno pardeigma, h klsh thc sunrthshc myfun ap thn main ja mporose na eqe gnei kai san myfun(x), dhlad na persoume to noma tou pnaka, afo, pwc gnwrzoume, to noma aut enai ousiastik nac dekthc sto prto stoiqeo tou pnaka. An eqame anajsei ston dekth myp th diejunsh tou prtou stoiqeou tou pnaka (myp = &x[0] , isodnama, myp = x), ja mporosame na kalsoume th sunrthsh kai san myfun(myp). An jloume na persoume sth sunrthsh nan upopnaka tou arqiko pnaka, ap na stoiqeo kai met, ja mporosame na thn kalsoume me parmetro th diejunsh tou stoiqeou auto. Gia pardeigma, an qoume knei prta thn anjesh myp = &x[2] me thn klsh myfun(myp) ( ap' eujeac myfun(&x[2])), h sunrthsh myfun ja dei nan pnaka me prto stoiqeo to trto tou arqiko. Epshc, ston orism thc sunrthshc, ja mporosame gia tupik parmetro na bloume to int px[], ant gia to int *px. Enai apoltwc isodnama.

87

Istgramma suqnottwn grammtwn sthn esodo


/* File: histogram.c */ #include <stdio.h> #define YAXISLEN 12 /* Y-axis length */

main() { int i, j, ch, total; int letfr[26]; /* Letter occurrences and frequencies array */ for (i=0 ; i<26 ; i++) letfr[i] = 0; /* Initialize array */ total = 0; /* Initialize counter of total letter occurrences */ while ((ch = getchar()) != EOF) {/* Well-known read-character loop */ if (ch >= A && ch <= Z) { letfr[ch-A]++; /* Found upper case letter */ total++; } if (ch >= a && ch <= z) { letfr[ch-a]++; /* Found lower case letter */ total++; } } printf(" |"); /* Start histogram printing - first Y-axis segment */ for (i=0 ; i<26 ; i++) { /* Convert letter occurrences */ /* to frequencies rounded to nearest integer */ letfr[i] = (int) ((100.0*letfr[i])/total+0.5); printf("%s", (letfr[i] > YAXISLEN) ? "^^" : " "); /* If i-th */ /* letter frequency exceeds Y-axis length, print "^^" */ } printf("\n"); for (j=YAXISLEN ; j>0 ; j--) { /* Print line at j-value of Y-axis */ printf("%2d|", j); /* Print frequency label and Y-axis segment */ for (i=0 ; i<26 ; i++) printf("%s", (letfr[i] >= j) ? "xx" : " "); /* If i-th letter */ /* frequency is greater than or equal to j, print "xx" */ printf("\n"); } /* Print X-axis and letter labels */ printf(" +-----------------------------------------------------\n"); printf(" AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz\n"); }

88

% gcc -o histogram histogram.c % ./histogram < histogram.c | 12| 11| xx xx 10| xx xx 9| xx xx xx xx 8| xx xx xx xx xx 7| xx xx xx xx xx 6|xx xx xx xx xx xx xx 5|xx xxxx xx xx xx xx xx 4|xx xx xxxx xx xx xxxx xxxxxx 3|xx xx xxxx xxxx xx xxxx xxxxxx 2|xx xxxxxxxxxxxxxx xx xxxxxx xxxxxxxx xxxx 1|xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +----------------------------------------------------AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz % ./histogram < /usr/dict/words | 12| 11| xx 10| xx 9|xx xx 8|xx xx xx 7|xx xx xx xxxx xx xx 6|xx xx xx xx xxxx xxxxxx 5|xx xx xx xx xx xxxx xxxxxx 4|xx xx xx xx xx xxxx xxxxxxxx 3|xx xxxxxx xxxx xxxxxxxxxx xxxxxxxx 2|xxxxxxxxxx xxxxxx xxxxxxxxxx xxxxxxxx xx 1|xxxxxxxxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xx +----------------------------------------------------AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz % ./histogram < /usr/include/stdio.h | ^^ 12| xx 11| xx 10| xx xx 9| xx xx xx 8| xxxx xx xx xx 7| xxxx xx xx xx 6| xxxxxx xx xx xxxx 5| xxxxxx xx xxxx xxxxxx 4| xxxxxx xx xx xxxxxx xxxxxx 3|xx xxxxxxxx xx xx xxxxxx xxxxxxxx xx 2|xx xxxxxxxxxx xx xx xxxxxx xxxxxxxx xx 1|xxxxxxxxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxx xx +----------------------------------------------------AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz %

89

Dunamik dsmeush mnmhc


Oi pnakec enai na pol qrsimo ergaleo se kje glssa programmatismo, ra kai sthn C, gia th diaqerish me eniao trpo enc sunlou ap omoeid dedomna. To basik prblhma, mwc, me touc pnakec enai ti prpei na qoume orsei th distash touc msa sto prgramma, bzontac tsi, kat th fsh thc suggrafc tou progrmmatoc, na rio sto pljoc twn dedomnwn pou mporome na apojhkesoume ston pnaka. An orsoume th distash enc pnaka sqetik mikr, knoume oikonoma sth mnmh kat thn ektlesh tou progrmmatoc, all aut qei tte periorismnec dunatthtec. An orsoume th distash pol meglh, mpore to prgramm mac na qeiriste kai perisstera dedomna, all gnetai spatlh sth mnmh tan den qreiazmaste na epexergastome tso poll dedomna. To idanik ja tan to prgramm mac na mhn desmeei mnmh ex arqc, all na to knei aut dunamik, kat th fsh thc ektleshc, anloga me tic angkec tou. Aut, eutuqc, enai efikt. H dunamik dsmeush mnmhc gnetai s' na qro pou diaqeirzetai to prgramma, o opooc lgetai swrc, kai enai diaforetikc ap to statik qro ston opoo fulssontai oi exwterikc metablhtc kai th stoba sthn opoa fulssontai oi autmatec metablhtc twn sunartsewn.

90

Sthn C, h dunamik dsmeush mnmhc gnetai (kurwc) msw thc sunrthshc void *malloc(unsigned int size) Kalntac thn malloc me parmetro nan akraio size,a aut desmeei sto swr size suneqmena bytes kai epistrfei sto nom thc na dekth sto prto ap' aut. O dekthc pou epistrfei h malloc deqnei se tpo void, dhlad ston ken tpo, afo den thn afor ti tpou dedomna ja fulxoume sth mnmh pou dsmeuse. An, gia kpoio lgo, h malloc den mporsei na desmesei th mnmh pou thc zhtjhke, epistrfei sto nom thc ton ken dekth NULL. Pnta, tan kalome thn malloc, prpei na elgqoume an mac epstreye dekth diforo tou NULL kai met na proqwrsoume. Epeid to pljoc twn bytes pou qrhsimopoiontai gia th flaxh dedomnwn kpoiou tpou mpore na diafrei metax diaforetikn metaglwttistn, leitourgikn susthmtwn kai epexergastn, gia na enai ta progrmmat mac metafrsima, to pljoc twn bytes pou zhtme ap thn malloc na desmesei to dnoume msw tou telest sizeof.
a Ston tupik orism thc malloc, o tpoc tou size enai size t, all

aut praktik enai unsigned int.

91

H kfrash sizeof( tpoc ) qei san tim to pljoc twn bytes pou apaitontai sth sugkekrimnh ulopohsh thc C gia na fulaqjon dedomna pou o tpoc touc enai tpoc . Gia pardeigma, me to paraktw tmma progrmmatoc
int n, *p; ................ /* Compute n */ p = malloc(n * sizeof(int)); if (p == NULL) { printf("Sorry, cannot allocate memory\n"); return; } ................ /* Handle data starting at p */

desmeoume dunamik qro sto swr gia na fulaqjon n akraioi.

Sthn pro ANSI C epoq, o dekthc pou epstrefe h malloc (tpou void *) prepe prta na prosarmosje ston katllhlo tpo dekth kai met na anateje se metablht. Dhlad thn klsh thc malloc sto parapnw tmma progrmmatoc ja thn grfame san:
p = (int *) malloc(n * sizeof(int));

Plon, kti ttoio den enai aparathto kai, gia thn akrbeia, den sunstatai.

92

O telestc sizeof mpore na qrhsimopoihje ete san sizeof parstash , ete san sizeof( parstash ), opte aut h kfrash qei san tim to pljoc twn bytes pou apaitontai gia na fulaqje h parstash , p.q. to sizeof buf enai 20, an qoume orsei char buf[20]. PROSOQH! 'Otan desmeoume dunamik mnmh, enai eujnh dik mac na thn apodesmeoume tan den thn qreiazmaste. H apodsmeush mnmhc pou qei desmeuje dunamik gnetai me th sunrthsh void free(void *p) H parmetroc pou pernme sth sunrthsh free enai nac dekthc pou mac eqe epistryei kpoia malloc. Enai pol sobar ljoc s' na prgramma, na desmeoume dunamik mnmh kai na mhn thn apodesmeoume tan den thn qreiazmaste. Ektc ap thn malloc, uprqoun kai do llec sunartseic gia dunamik dsmeush mnmhc (h realloc kai h calloc). Enai pio spnia qrhsimopoiomenec ap thn malloc. Msw thc entolc man, mpore na mjei kanec perissterec plhroforec gi' autc. 'Otan s' na prgramma qrhsimopoiome sunartseic gia dunamik dsmeush kai apodsmeush mnmhc, prpei na qoume sumperilbei sthn arq to arqeo epikefaldac stdlib.h. Dhlad:
#include <stdlib.h>

93

Se sqsh me ta problmata pou dhmiourgontai tan orzoume me statik trpo pnakec gia na diaqeiristome na snolo ap dedomna, ant na knoume dunamik dsmeush mnmhc, ja prpei na anafroume ti sthn C uprqei kai h dunatthta na orsoume pnakec me metablht distash, gia pardeigma:
int array[n];

Fusik, prin ap th dlwsh aut, sthn akraia metablht n prpei na qoume dsei tim.

O basikc periorismc pou uprqei sth dlwsh pinkwn me distash pou den enai gnwst kat th fsh suggrafc tou progrmmatoc, enai ti mpore na gnei gia pnakec pou enai autmatoi, dhlad topiko msa se sunartseic. Den mpore na gnei gia pnakec pou jloume na touc orsoume ston statik qro, exwterik twn sunartsewn. Se kje perptwsh, enai kalterh programmatistik taktik, tan jloume na desmesoume dunamik mnmh, aut na gnetai msw malloc kai deiktn, par me pnakec pou h distas touc enai parametrik. Epshc, na epishmanje ti h dunatthta gia pnakec me parametrik distash prostjhke sto stntarnt thc C to 1999, opte paliteroi metaglwttistc den to dqontai.

94

Sumboloseirc
Ma sumboloseir alfarijmhtik enai nac pnakac ap qaraktrec (dedomna tpou char). O qaraktrac \0, san stoiqeo tou pnaka, deqnei to tloc thc sumboloseirc kai enai apoltwc aparathtoc gia na mporon na leitourgsoun oi sunartseic bibliojkhc gia to qeirism sumboloseirn. Lgw thc meshc sqshc metax pinkwn kai deiktn, se ma sumboloseir mporome na anaferjome kai me na dekth (tpou char *) pou deqnei ston prto qaraktra thc sumboloseirc. Msa s' na prgramma, mporome m' na sntomo trpo na anaferjome se ma sumboloseir gia thn opoa gnwrzoume touc qaraktrec pou periqei, perikleontac autoc touc qaraktrec msa se " (qwrc to \0). Pardeigma:
char *mess = "Hello world!\n";
H e l l o w o r l d ! \n \0

mess:

Oi sumboloseirc pou periqontai msa s' na prgramma fulssontai ston dio qro me to prgramma kai, gi' autn to lgo, den enai dunatn na metablhjon. Gia th diaqeris touc, o metaglwttistc antistoiqe se kje ttoia sumboloseir th diejunsh tou prtou qaraktra thc.

95

Ektc ap thn arqikopohsh enc dekth se char me ma sumboloseir, pwc kname me thn entol
char *mess = "Hello world!\n";

mporome na arqikopoisoume kai na pnaka qaraktrwn me ma sumboloseir, wc exc:


char arrmess[] = "How are you?";

Den uprqei lgoc na orsoume distash gia ton pnaka arrmess, giat aut upologzetai autmata ap to pljoc twn qaraktrwn thc sumboloseirc (sun nan, lgw tou \0).

Ma ousidhc diafor metax twn parapnw entoln, enai ti h metablht mess enai dekthc pou arqikopoijhke me th sumboloseir pou jloume, sth sunqeia, mwc, mpore na allxei tim, an qreizetai, en to noma tou pnaka arrmess, pou epshc arqikopoijhke me ma sumboloseir, leitourge, fusik, kai wc dekthc, mno pou den epitrpetai na metablhje. H deterh ousidhc diafor enai ti den mporome na allxoume to perieqmeno, dhlad touc qaraktrec, thc sumboloseirc "Hello world!\n" pou deqnei arqik o dekthc mess, parti mporome na allxoume thn tim tou diou tou dekth, en mporome na allxoume touc qaraktrec thc sumboloseirc "How are you?", parti den mporome na allxoume to arrmess.

96

Oi sumboloseirc enai na pol qrsimo ergaleo gia ton programmatism sthn C, gi' aut h prtuph bibliojkh thc glssac parqei ma seir ap sunartseic gia th diaqeris touc. 'Otan qrhsimopoiome s' na prgramma sunartseic gia diaqerish sumboloseirn, prpei na qoume sumperilbei sthn arq to arqeo epikefaldac string.h. Dhlad:
#include <string.h>

Merikc ap tic sunartseic autc enai: unsigned int strlen(const char *s) char *strcpy(char *s1, const char *s2) int strcmp(const char *s1, const char *s2) char *strcat(char *s1, const char *s2) H strlen epistrfei to mkoc thc sumboloseirc s (qwrc to telik \0). a H strcpy antigrfei th sumboloseir s2, mqri kai to telik \0, sth sumboloseir s1, thn opoa epistrfei kai sto nom thc. H strcmp sugkrnei tic sumboloseirc s1 kai s2 byte proc byte kai epistrfei nan akraio jetik, mhdn arnhtik, anloga an h sumboloseir s1 akolouje (alfabhtik), tautzetai prohgetai thc sumboloseirc s2, antstoiqa. H sgkrish gnetai me bsh touc ASCII kwdikoc twn qaraktrwn twn sumboloseirn.
a Epismwc o tpoc epistrofc thc sunrthshc enai size t, all autc,

praktik, enai unsigned int.

97

H strcat prosart na antgrafo thc sumboloseirc s2 sto tloc thc s1, diagrfontac prta to \0 thc s1, kai epistrfei to apotlesma kai sto nom thc. Kpoiec ap tic tupikc paramtrouc twn sunartsewn gia diaqerish sumboloseirn qoun dhlwje san const gia na epishmanje ti oi antstoiqec sumboloseirc den ja metablhjon ap tic sunartseic. Oi sunartseic pou dhmiourgon nec sumboloseirc (p.q. strcpy, strcat) den analambnoun kai th dsmeush mnmhc gia th flax touc. Enai eujnh thc kalosac sunrthshc na to knei aut. Uprqoun kai arketc llec endiafrousec kai qrsimec sunartseic diaqerishc sumboloseirn, pwc oi strncpy, strchr, strstr, klp. H entol man enai na mso gia na mjei kanec perissterec plhroforec gi' autc. Kpoiec pijanc ulopoiseic:
a

char *strcpy(char *s1, const char *s2) { char *orig_s1 = s1; while(*s1++ = *s2++); return orig_s1; } int strcmp(const char *s1, const char *s2) { for ( ; *s1 == *s2 ; s1++, s2++) if (! *s1) return 0; return *s1 - *s2; }
a Pc ja ulopoiosame tic strlen kai strcat;

98

Pnakec deiktn kai dektec se dektec


'Opwc mporome na qoume pnakec akerawn, pnakec pragmatikn arijmn (kinhtc upodiastolc, aplc diplc akrbeiac), pnakec qaraktrwn (sumboloseirc), tsi mporome na orsoume sthn C kai pnakec deiktn. Me thn dia logik pou to noma enc pnaka stoiqewn kpoiou tpou mpore na jewrhje (sqedn) isodnamo me na dekth se stoiqea ttoiou tpou, tsi kai to noma enc pnaka deiktn antistoiqe s' na dekth se dekth se stoiqea tou tpou pou deqnoun ta stoiqea tou pnaka. Pardeigma:
int i, j, *px[3], **ppx, s=0; for (i=0 ; i<3 ; i++) { px[i] = malloc((i+2) * sizeof(int)); if (px[i] == NULL) return NO_MEMORY_AVAILABLE; } for (i=0 ; i<3 ; i++) for (j=0 ; j<i+2 ; j++) *(px[i]+j) = i*j; ppx = px; for (i=0 ; i<3 ; i++) { for (j=0 ; j<i+2 ; j++) s += *(*ppx)++; ppx++; }

Poia ja enai h tim thc metablhtc s met thn ektlesh twn parapnw entoln; a
a 15

99

Orsmata grammc entoln


'Otan ektelome na prgramma, jloume na qoume, kat thn klsh tou progrmmatoc, th dunatthta na dnoume sth gramm entoln kpoia orsmata, ta opoa na mporon na persoun sto prgramma, gia na ta epexergaste katllhla. Sthn C, h dunatthta orismtwn sth gramm entoln parqetai msw twn tupikn paramtrwn thc sunrthshc main. Orzontac thn main me do tupikc paramtrouc, ma akraia, sunjwc me noma argc, kai ma pnaka deiktn se qaraktrec ( dekth se dekth se qaraktrec), sunjwc me noma argv, msa sth sunrthsh, mporome na qoume prsbash sta orsmata me ta opoa kljhke to prgramma sth gramm entolc. An na ektelsimo prgramma myprog klhje san
% ./myprog first 241 third

kai h sunrthsh main tou progrmmatoc qei orisje san


main(int argc, char *argv[])

tte, msa sthn main, h metablht argc qei thn tim 4 (sa ta orsmata sun to noma tou progrmmatoc) kai oi dektec argv[0], argv[1], argv[2] kai argv[3] deqnoun sthn arq twn sumboloseirn "./myprog", "first", "241" kai "third", antstoiqa.

100

O dekthc argv[argc] (sto prohgomeno pardeigma o argv[4]) enai o kenc dekthc, NULL. H deterh tupik parmetroc thc main mpore na orisje ete san char *argv[] ete san char **argv, isodnama. 'Otan kpoio risma sth gramm entoln enai akraioc arijmc, msa sto prgramm mac, kat psa pijanthta, ja mac endiafrei na qoume diajsimh thn arijmhtik tim tou arijmo, qi aplc ta yhfa tou san ma sumboloseir. H metatrop mac sumboloseirc pou ta stoiqea thc enai dekadik yhfa sthn antstoiqh arijmhtik tim gnetai me th sunrthsh int atoi(const char *s) H atoi upologzei thn tim thc (arijmhtikc) sumboloseirc s kai thn epistrfei sto nom thc. Sto prohgomeno pardeigma h klsh atoi(argv[2]) ja epstrefe thn tim 241. 'Otan qrhsimopoiome thn atoi, prpei na knoume kai:
#include <stdlib.h>

101

Poludistatoi pnakac
Ektc ap monodistatouc pnakec, sthn C, pwc kai se lec sqedn tic glssec programmatismo, qoume th dunatthta na orsoume kai pnakec me perissterec thc mac diastseic. Me th dlwsh
int matrix[10][8];

orzoume na didistato pnaka me noma matrix me 10 grammc kai 8 stlec.

H anafor sta stoiqea tou pnaka gnetai me trpo antstoiqo me autn twn monodistatwn pinkwn. To stoiqeo matrix[i][j] enai aut pou brsketai sthn i gramm kai sthn j stlh. a An qoume orsei na didistato pnaka, stw me noma matrix, tte to matrix[i] (isodnama to *(matrix+i)) enai nac dekthc sto prto stoiqeo thc i grammc tou pnaka. Opte, to *(matrix[i]+j) (isodnama to *(*(matrix+i)+j)) den enai llo ap to stoiqeo matrix[i][j] tou pnaka.
a Mno, prosoq kai ed, to i prpei na kumanetai, sto pardeigm mac,

ap 0 wc 9 kai to j ap 0 wc 7.

102

'Enac didistatoc pnakac apojhkeetai kat grammc. An anajsoume s' na dekth p, pou deqnei se tpo ,ti kai o tpoc twn stoiqewn tou pnaka, th diejunsh tou prtou stoiqeou tou pnaka (p.q. matrix[0][0]), tte mporome na prospelsoume ta perieqmena tou pnaka, th ma gramm met thn llh, me parastseic thc morfc *(p+i). Epshc, afo to *matrix enai to dio me to matrix[0], dhlad nac dekthc sto prto stoiqeo thc prthc grammc (autc me i=0) tou pnaka, mporome na prospelsoume kat grammc ta perieqmena tou pnaka kai me parastseic thc morfc *(*matrix+i). Fusik, mporome na orsoume kai pnakec me perissterec twn do diastseic, all, se prth fsh, den qoun idiaterh programmatistik qrhsimthta. Pntwc, tan qrhsimopoiome pnakec, anagkastik orzoume sugkekrimnec diastseic kat th fsh suggrafc twn programmtwn mac, me apotlesma ete na knoume spatlh mnmhc ete na periorizmaste sthn eplush problhmtwn me mikr mgejoc. Enai protimtero na qrhsimopoiome dektec kai na knoume dunamik dsmeush mnmhc.

103

An s' na prgramma qreizetai na fulxoume dedomna s' na didistato pnaka, agnstou, kat' arqn, megjouc, ant na dhlsoume kti san
int x[10000][10000];

mporome na orsoume na dekth


int **px;

kai met na knoume:


px = malloc(N * sizeof(int *)); if (px == NULL) return NO_MEMORY_AVAILABLE; for (i=0 ; i<N ; i++) { *(px+i) = malloc(M * sizeof(int)); if (*(px+i) == NULL) return NO_MEMORY_AVAILABLE; }

'Etsi, tan ta N kai M gnoun gnwst kat th fsh ektleshc tou progrmmatoc, ja desmesoume sh akribc mnmh qreiazmaste. Afo mwc teleisoume ,ti qoume na knoume, met prpei na apodesmesoume th mnmh wc exc:
for (i=0 ; i<N ; i++) free(*(px+i)); free(px);

104

Arqikopohsh pinkwn
'Otan orzoume ma metablht, mporome, wc gnwstn, na thc dsoume kai kpoia arqik tim. H dunatthta aut uprqei kai gia touc pnakec. Paradegmata:
int x[7] = {5, 3, -7, 12, 0, -4, 125}; float r[] = {1.2, -4.35, 0.62e-17}; int matrix[3][5] = { {22, 1, -3, 8, 7}, {-2, 0, 24, 7, -10}, {76, 54, 12, -9, 8} }; char arr[][2] = {{a,b},{c,d},{e,f}}; char mess[] = "a dog"; char buff[] = {a, ,d,o,g,\0}; char *str[] = {"Hello", "world", "of", "C"};

Mporome, kat ton orism, na paraleyoume to mgejoc enc monodistatou pnaka, an arqikopoiome la ta stoiqea tou, afo aut mpore na prokyei ap to pljoc twn timn msa sta { kai }. Se poludistatouc pnakec, mporome na paraleyoume to mgejoc mno thc prthc distashc.

105

Dektec se sunartseic
'Opwc ma metablht antistoiqe se ma diejunsh mnmhc pou mporome na th fulxoume s' na dekth katllhlou tpou, pwc epshc mporome na anafermaste se pnakec me th diejunsh tou prtou touc stoiqeou, tsi mporome na anafermaste kai se sunartseic msw deiktn. 'Enac dekthc se sunrthsh enai ma metablht sthn opoa mporome na kataqwrsoume th diejunsh thc prthc ap tic (suneqmenec) jseic mnmhc stic opoec brsketai o kdikac thc sunrthshc. Touc dektec sunartsewn mporome na touc qeiristome perpou pwc kai touc llouc dektec. Me ton telest mmeshc anaforc *, mporome na anaferjome se sugkekrimnec sunartseic, mporome na anajtoume tic timc autn twn deiktn se llouc sumbatoc dektec, mporome na touc pernme san paramtrouc se sunartseic klp. Den qei nhma mwc na touc metablloume (p.q. p++). Pardeigma:
int (*funvar)(char *);

To funvar enai nac dekthc se sunrthsh pou epistrfei int kai qei ma tupik parmetro tpou char *.

Ti diafor ja eqe an grfame to paraktw;


int *funvar(char *);

a Ed to funvar enai to noma sugkekrimnhc sunrthshc, qi dekthc

se sunrthsh, pou epistrfei dekth se akraio (int *) kai qei ma tupik parmetro tpou char *.

106

Diaqerish orismtwn sth gramm entolc


/* File: #include #include #include cmdlineargs.c */ <stdio.h> <stdlib.h> <string.h>

int checkint(char *); void reverse(char *); main(int argc, char *argv[]) { int sum = 0; /* Initialize sum of integers in command line while (--argc) { /* Loop while arguments are present if(checkint(*++argv)) /* Is argument an integer? sum += atoi(*argv); /* Then, sum it into the accumulator else { reverse(argv[0]); /* Else, reverse argument and print it printf("Reversed argument: %s\n", argv[0]); } } /* Finally, print sum of integer arguments printf("\nSum of integers given is: %d\n", sum); } int checkint(char *s) { char *start; while(*s == || *s == \t) s++; /* Eat all whitespace if (*s == - || *s == +) s++; /* Eat one sign start = s; /* Mark the begining of numbers while(*s >= 0 && *s <= 9) s++; /* Eat all numbers return (*s == \0 && start != s); /* Return if there where numbers and nothing else }

*/ */ */ */ */

*/

*/ */ */ */ */

void reverse(char *s) { char c; int i, j; for (i=0, j=strlen(s)-1 ; i<j ; i++, j--) { c = s[i]; /* Visit string from start and end concurrently */ s[i] = s[j]; /* and exchange characters in symmetric */ s[j] = c; /* positions until middle is reached */ } }

107

% gcc -o cmdlineargs cmdlineargs.c % ./cmdlineargs This is a test Reversed argument: sihT Reversed argument: si Reversed argument: a Reversed argument: tset Sum of integers given is: 0 % ./cmdlineargs And 123 another 12 Reversed argument: dnA Reversed argument: rehtona Sum of integers given is: 135 % ./cmdlineargs minus five -5 plus twenty two 22 Reversed argument: sunim Reversed argument: evif Reversed argument: sulp Reversed argument: ytnewt Reversed argument: owt Sum of integers given is: 17 %

Prsjesh poluyfiwn arijmn


/* File: #include #include #include addnumbs.c */ <stdio.h> <stdlib.h> <string.h>

char *addnumbs(char *, char *); main(int argc, char *argv[]) { char *sum; if (argc != 3) { /* Run with exactly two arguments */ printf("Usage: %s <numb1> <numb2>\n", argv[0]); return 1; } if ((sum = addnumbs(argv[1], argv[2])) == NULL) { /* Compute sum */ printf("Sorry, a memory problem occurred\n"); return 1; } printf("%s + %s = %s\n", argv[1], argv[2], sum); free(sum); /* Free memory malloced by addnumbs */ }

108
char *addnumbs(char *s1, char *s2) { int i, j, k, d1, d2, sum, carry; char *s3, *tmp, *result; i = strlen(s1)-1; /* Index to last character of first number j = strlen(s2)-1; /* Index to last character of second number k = (i > j) ? (i+1) : (j+1); /* Index to last character of sum if ((s3 = malloc((k+2)*sizeof(char))) == NULL) return NULL; /* Allocate memory for result s3[k+1] = \0; /* Proper termination of resulting string carry = 0; /* Initial carry for addition for ( ; k>=0 ; i--, j--, k--) { /* Loop till first digit of result is computed d1 = (i >= 0) ? (s1[i]-0) : 0; /* Get i-th digit of s1 d2 = (j >= 0) ? (s2[j]-0) : 0; /* Get j-th digit of s2 sum = d1+d2+carry; /* Sum two digits carry = sum/10; /* Next carry s3[k] = sum%10+0; /* Put k-th digit of result } tmp = s3; /* Save s3 for freeing it afterwards while (*s3 == 0) /* Eat leading 0s in the result s3++; if(*s3 == \0) /* At least one digit is needed s3--; if ((result = malloc((strlen(s3)+1)*sizeof(char))) == NULL) return NULL; /* Allocate memory for result without leading 0s strcpy(result, s3); /* Copy corrected s3 to result free(tmp); /* Free original s3 return result; }

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

*/ */ */

% gcc -o addnumbs addnumbs.c % ./addnumbs 12345 67890 12345 + 67890 = 80235 % ./addnumbs 125 88275346771923625166 125 + 88275346771923625166 = 88275346771923625291 % ./addnumbs 999999999999999 999999 999999999999999 + 999999 = 1000000000999998 % ./addnumbs 0000000000023 00000057 0000000000023 + 00000057 = 80 % ./addnumbs 3252352362364362362366 3262363262362363622 3252352362364362362366 + 3262363262362363622 = 3255614725626724725988 % ./addnumbs 0000000 0000000000 0000000 + 0000000000 = 0 %

109

Aparijmseic
Sthn C parqetai nac bolikc trpoc sndeshc stajern akraiwn timn me onmata, msw twn aparijmsewn. Prkeitai gia ma dunatthta antstoiqh tou #define, mno pou thn diaqeirzetai o metaglwttistc, qi o proepexergastc. Pardeigma:
enum boolean {NO, YES};

Gia th sunqeia, to NO tautzetai me to 0 kai to YES me to 1.

Mporome na dnoume sugkekrimnec timc stic stajerc aparjmhshc, uponontac ti oi epmenec stajerc qoun suneqmenec timc, ektc an kai se autc apoddontai timc. Paradegmata:
enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; enum escapes {BELL = \a, BACKSPACE = \b, TAB = \t, NEWLINE = \n};

Ed, oi stajerc gia touc mnec sthn aparjmhsh months antistoiqon stouc arijmoc ap 1 wc 12, en oi stajerc thc aparjmhshc escapes antistoiqon stic sugkekrimnec timc pou qoun kajorisje gia thn kajema.

Anafor stic aparijmseic, gnetai sthn pargrafo 2.3 tou [KR].

110

Domc
Pollc forc, ma snjeth ontthta mpore na kajorisje ap na snolo dedomnwn, pijanc diaforetikn tpwn, opte ja tan qrsimo na omadopoiosame ta dedomna aut ktw ap na genik noma, me skop na anafermaste sthn ontthta aut me to noma aut. Sthn C, h dunatthta omadopohshc dedomnwn, pou apotelon kat kpoio trpo ta qarakthristik mac programmatistikc ontthtac, parqetai ap tic domc. Ma dom orzetai me ton exc trpo: struct etikta domc { tpoc 1 mloc 1 ; tpoc 2 mloc 2 ; ........................... tpoc n mloc n ; }; O orismc mac domc apoteletai ap touc orismoc twn meln thc, pou perigrfontai san metablhtc sugkekrimnwn tpwn. Fusik, pnakec, dektec akma kai domc mporon na enai mlh mac domc. Gia pio analutik suzthsh per domn, parapmpeste stic paragrfouc 6.1 wc 6.6 tou [KR]. Gia dhmiourga nwn onomtwn tpwn (entol typedef), enseic kai peda bit, pou ja suzhthjon sth sunqeia, oi pargrafoi ap to [KR] enai oi 6.7, 6.8 kai 6.9, antstoiqa.

111

Paradegmata:
struct employee { char firstname[10]; char lastname[18]; int id_number; float salary; }; struct wordinfo { char *word; int nlines; };

Sta paradegmata aut orzoume ma dom struct employee gia thn anaparstash plhroforin gia na upllhlo (mikr noma, epnumo, arijmc mhtrou kai misjc) kai ma dom struct wordinfo gia thn anaparstash thc plhroforac sqetik me thn parxh mac lxhc se kpoio kemeno, kajc kai to pljoc twn grammn stic opoec emfanzetai. O orismc mac domc enai ma dlwsh gia thn opoa den gnetai kpoia dsmeush mnmhc. Mporome mwc na orsoume sugkekrimnec metablhtc pou qoun san tpo ma dom, wc exc: struct etikta domc metablht 1 , . . ., metablht k ; Tte, desmeetai h apaitomenh mnmh gia tic metablhtc, anloga me ton qro pou qreizetai gia na fulaqjon ta mlh thc domc.

112

Paradegmata:
struct employee jim, jane, the_employee; struct wordinfo first_word, next_word, last_word;

'Alla paradegmata dhlsewn domn:


struct point { double x; double y; }; struct upright_rectangle { struct point p1; struct point p2; };

Ed orzoume th dom struct point gia thn anaparstash enc shmeou sto eppedo (msw twn suntetagmnwn tou), kajc kai th dom struct upright rectangle gia thn anaparstash enc orjogwnou parallhlogrmmou sto eppedo, me tic pleurc parllhlec stouc xonec (msw do shmewn pou enai apnanti korufc se ma diagnio). a
a Mporete na orsete domc kai gia llec gewmetrikc ontthtec sto

eppedo, gia pardeigma, eujgramma tmmata, trgwna, kklouc, , anexarttwc prosanatolismo, tetrgwna, rmbouc, orjognia parallhlgramma, (plgia) parallhlgramma kai tuqaa tetrpleura; Mporete na orsete kai gewmetrikc ontthtec ston trisdistato qro;

113

O orismc metablhtn me tpo kpoia sugkekrimnh dom mpore na gnei tautqrona me th dlwsh thc domc. Pardeigma:
struct point { double x; double y; } pa, pb, pc;

Sthn perptwsh aut, den enai aparathto na dsoume etikta sth dom. Gia pardeigma, o exc orismc twn metablhtn pa, pb kai pc enai apodektc:
struct { double x; double y; } pa, pb, pc;

Fusik, tte, an jloume sth sunqeia na orsoume kai llec metablhtc tou tpou thc domc, prpei na epanalboume th dlws thc, afo den thc eqame dsei kpoia etikta.

Metablhtc me tpo dom mporon na anatjentai san timc se llec metablhtc tou diou tpou, mporon na dnontai san orsmata kat thn klsh sunartsewn kai mporon na epistrfontai ap sunartseic sto nom touc.

114

Me ton orism mac metablhtc tpou domc, mporome na knoume kai arqikopohsh twn meln thc. Pardeigma:
struct point my_point = {22.4, -38.9};

Eidik gia autmatec metablhtc tpou domc, arqikopohsh mpore na gnei kai me entol antikatstashc msw epistrofc sunrthshc.

H anafor s' na mloc mac metablhtc tpou domc gnetai me thn parstash metablht . mloc Paradegmata:
struct point vert1, vert2; struct upright_rectangle my_rect; vert1.x = 2.4; vert2.y = 7.8; my_rect.p1.x = -8.3;

H teleutaa entol enai isodnamh me thn


(my_rect.p1).x = -8.3;

epeid o telestc . enai arister prosetairistikc.

115

'Opwc orzoume metablhtc me tpo kpoia dom, tsi mporome na orsoume kai dektec se domc. Pardeigma:
struct point *ppa, *ppb;

Fusik, enai dik mac eujnh na knoume touc dektec ppa kai ppb na dexoun se dieujnseic stic opoec fulssontai ja fulaqjon dedomna tpou domc. Aut mpore na gnei ete me thn anjesh thc diejunshc kpoiac dh orismnhc metablhtc tpou domc, ete me dunamik dsmeush. Paradegmata:
struct point my_point; ppa = &my_point; ppb = malloc(sizeof(struct point));

'Eqontac orsei na dekth se dom, pwc ton ppa sto prohgomeno pardeigma, mporome na anaferjome se sugkekrimno mloc kat ta gnwst, gia pardeigma (*ppa).x. Sthn parstash (*ppa).x oi parenjseic enai aparathtec. An grfame *ppa.x, aut, lgw twn sqetikn proteraiottwn twn telestn . kai * ja tan isodnamo me to *(ppa.x), to opoo mwc, sthn prokemenh perptwsh den enai suntaktik swst, afo to ppa.x den enai dekthc.

116

An nac dekthc deqnei se kpoia dom kai jloume na anaferjome s' na mloc thc, ant na grfoume (* dekthc ). mloc h C mac dnei th dunatthta na gryoume pio apl dekthc -> mloc 'Opwc o telestc ., tsi kai o -> enai arister prosetairistikc. Gia pardeigma, an qoume orsei
struct upright_rectangle *rp;

tte h parstash rp->p1.x enai h dia me thn (rp->p1).x.

Oi telestc . kai -> maz me tic () gia klseic sunartsewn kai tic [] gia dektec pinkwn brskontai sthn koruf thc ierarqac proteraithtac twn telestn kai epomnwc sundontai isqur me touc telestouc. Pardeigma:
struct wordinfo *pw;

Me thn kfrash ++pw->nlines auxnei to nlines giat enai isodnamh me thn ++(pw->nlines). An jlame na auxsoume ton dekth pw ja prepe na gryoume (++pw)->nlines (pw++)->nlinesa , anloga me to pte ja epijumosame na gnei h axhsh tou dekth, prin met thn prosplash tou mlouc nlines.

'Eqontac plon anaferje se louc touc telestc thc C, o Pnakac 2 1 tou [KR] (sel. 83), enai ma pol qrsimh phg gia anafor, sqetik me tic proteraithtc touc.
a Ed den enai aparathtec oi parenjseic, afo den ja uprqe amfibola

gia to ti ja smaine to pw++->nlines.

117

'Opwc sumbanei kai me louc touc tpouc sthn C, mporome na orsoume kai pnakec domn. Pardeigma:
main() { int i, n; struct worddata { char *word; int numb; char let; } wordarray[] = { {"ABCD", 1, a}, {"EF", 2, b}, {"GHIJ", 3, c}, {"KL", 4, d}, {"M", 5, e}}; struct worddata *p = wordarray; n = sizeof(wordarray)/sizeof(struct worddata); printf("%d ", n); for (i=0 ; i<2 ; i++) { printf("%c ", *p->word++); printf("%s ", ++p->word); printf("%c ", p->let++); printf("%c ", (++p)->let); printf("%d ", p++->numb); printf("%d ", ++p->numb); } for (i=0 ; i<n ; i++) printf("%s %d %c ", wordarray[i].word, wordarray[i].numb, wordarray[i].let); printf("\n"); }

Ti ja ektupwje ap to prgramma aut;

a 5 A CD a b 2 4 G IJ c d 4 6 CD 1 b EF 2 b IJ 4 d KL 4 d M 6 e

118

Eresh trignwn megstou kai elaqstou embado


/* File: #include #include #include #include triangles.c */ <stdio.h> <stdlib.h> <time.h> <math.h>

struct point { double x; double y; } *points; struct triangle { struct point a; struct point b; struct point c; };

/* A point in 2 dimensions is defined */ /* by its x- and y- coordinates */

/* A triangle is defined by its three vertices */

struct triangle get_triangle(int, int, int); double triangle_area(struct triangle *); double get_side(struct point, struct point); main(int argc, char *argv[]) { int i, j, k, n = 10; long seed; struct triangle tr, max_tr, min_tr; double area, max_area, min_area; seed = time(NULL); if (argc > 1) n = atoi(argv[1]); if (n < 3) { /* In order to have at least one triangle */ printf("At least three points are needed\n"); return 1; } if ((points = malloc(n * sizeof(struct point))) == NULL) { /* Allocate memory to store n points */ printf("Sorry, not enough memory!\n"); return 1; }

119

/* Initialize random number generator */ srand((unsigned int) seed); for (i=0 ; i<n ; i++) { /* Generate points with coordinates between 0.0 and 100.0 */ /* RAND_MAX is max number that rand() returns - usually 32767 */ (points+i)->x = (100.0 * rand())/(RAND_MAX+1.0); (points+i)->y = (100.0 * rand())/(RAND_MAX+1.0); } for (i=0 ; i<n ; i++) /* Printout points generated */ printf("P%-2d: (%4.1f,%4.1f)\n", i, (points+i)->x, (points+i)->y); tr = get_triangle(0, 1, 2); /* Get first triangle */ area = triangle_area(&tr); /* Compute area of first triangle */ /* Initialize max and min triangles with first triangle */ max_tr = min_tr = tr; max_area = min_area = area; /* Areas of max and min triangles */ for (i=0 ; i < n-2 ; i++) /* Iterate through all combinations */ for (j=i+1 ; j < n-1 ; j++) /* of points in order to form all */ for (k=j+1 ; k < n ; k++) { /* possible triangles */ tr = get_triangle(i, j, k); /* Get current triangle */ area = triangle_area(&tr); /* Area of current triangle */ if (area > max_area) { /* Is current larger than max? */ max_tr = tr; max_area = area; } if (area < min_area) { /* Is current smaller than min? */ min_tr = tr; min_area = area; } } printf("\n"); printf("Max triangle: "); /* Printout max triangle */ printf("(%4.1f,%4.1f) ", max_tr.a.x, max_tr.a.y); printf("(%4.1f,%4.1f) ", max_tr.b.x, max_tr.b.y); printf("(%4.1f,%4.1f) ", max_tr.c.x, max_tr.c.y); printf(" Area: %10.5f\n", max_area); printf("Min triangle: "); /* Printout min triangle */ printf("(%4.1f,%4.1f) ", min_tr.a.x, min_tr.a.y); printf("(%4.1f,%4.1f) ", min_tr.b.x, min_tr.b.y); printf("(%4.1f,%4.1f) ", min_tr.c.x, min_tr.c.y); printf(" Area: %10.5f\n", min_area); }

120

struct triangle get_triangle(int i, int j, int k) { struct triangle tr; tr.a = *(points+i); tr.b = *(points+j); tr.c = *(points+k); return tr; /* Return triangle with vertices i, j, k */ } double triangle_area(struct triangle *tr) { double s1, s2, s3, t; s1 = get_side(tr->a, tr->b); /* s2 = get_side(tr->b, tr->c); /* s3 = get_side(tr->c, tr->a); /* t = (s1+s2+s3)/2; /* Compute return sqrt(t*(t-s1)*(t-s2)*(t-s3)); }

Get length of side ab Get length of side bc Get length of side ca half of the perimeter /* Return area

*/ */ */ */ */

double get_side(struct point p1, struct point p2) { /* Return Euclidean distance between points p1 and p2 */ return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); } % gcc -o triangles triangles.c -lm % ./triangles 17 P0 : (37.5,51.6) P1 : (31.4, 0.8) P2 : (10.3,32.8) P3 : ( 4.5,38.4) P4 : (27.4,96.3) P5 : (28.4,43.0) P6 : (69.8,55.7) P7 : (13.3,71.4) P8 : (17.8,76.2) P9 : ( 3.9, 8.8) P10: (29.6,69.6) P11: (20.6,43.3) P12: ( 9.1,76.1) P13: (33.9,25.6) P14: (34.1,66.4) P15: (15.1,22.9) P16: (67.5,49.7) Max triangle: (27.4,96.3) (69.8,55.7) ( 3.9, 8.8) Min triangle: (28.4,43.0) (17.8,76.2) (33.9,25.6) % Area: 2331.69411 Area: 0.09948

121

Auto-anaforikc domc
Ta mlh mac domc mpore na enai opoioudpote tpou, akma kai dektec se domc tou diou tpou. Qrhsimopointac ttoiou edouc domc, pou onomzontai auto-anaforikc kai enai pol qrsimec ston programmatism, mporome na organsoume dedomna me trpouc pou dieukolnoun exairetik th diaqerish kai epexergasa touc. Oi plon sunjeic organseic dedomnwn msw auto-anaforikn domn enai oi sundedemnec lstec (, apl, lstec) kai ta duadik dntra. Mpore kanec na orsei kai llec organseic dedomnwn, pwc dipl sundedemnec lstec, ourc, dntra qi kat' angkh duadik, klp. 'Estw h dlwsh:
struct listnode { int value; struct listnode *next; };

Aut h dom orzei nan kmbo lstac ston opoo fulssetai nac akraioc kai nac dekthc se kmbo lstac.

An jloume na apojhkesoume ma akolouja ap akeraouc, aprosdiorstou pljouc, all kai metaballmenou kat th dirkeia thc ektleshc enc progrmmatoc, mporome na to knoume bzontac kje akraio s' na kmbo lstac kai deqnontac ap kje kmbo ston epmen tou.

122

H anafor sth lsta gnetai me na dekth ston prto kmbo thc. O teleutaoc kmboc thc lstac qei san dekth se epmeno kmbo to NULL.
listnode *

15

22

37

12

Aut enai ma lsta me stoiqea, kat seir, ta 15, 22, 37 kai 12.

Gia na ulopoisoume th dunamik fsh thc lstac, prpei pnta na gnetai, gia th flaxh enc kmbou thc, h katllhlh dunamik dsmeush mnmhc (msw malloc) kai, fusik, h apodsmeush (msw free), tan den qreiazmaste plon ton kmbo. Oi kmboi mac lstac den fulssontai se diadoqikc jseic mnmhc, afo h mnmh gi' autoc desmeetai me diaforetikc malloc. Aut shmanei ti den mporome na qoume mesh prsbash sto N -ost stoiqeo mac lstac, pwc stouc pnakec, all mno akoloujntac thn alusda twn stoiqewn ap to prto wc to N -ost.

123

H parembol enc kmbou se sugkekrimnh jsh se ma lsta den apaite thn metaknhsh kanenc llou kmbou.Aplc prpei na tropopoihje o dekthc gia epmeno tou kmbou pou prohgetai thc jshc pou eisgetai o noc kmboc, ste na dexei plon ston no kmbo. Epshc, o dekthc gia epmeno tou nou kmbou ja prpei na dexei ston epmeno kmbo ap th jsh pou gine h eisagwg.
listnode *

15

22

37

12

89

Ed, gine eisagwg, sth lsta thc prohgomenhc seldac, tou stoiqeou 89 metax twn stoiqewn 37 kai 12.

Antstoiqa isqoun kai gia th diagraf enc kmbou ap ma lsta. Den apaitetai kama metaknhsh.
listnode *

15

22

37

12

89

Ed, gine diagraf tou stoiqeou 22 ap thn prohgomenh lsta.

124

Fusik, mporome na orsoume kmbouc lstac stouc opoouc h plhrofora pou fulssoume (plhn tou dekth ston epmeno kmbo) na enai opoioudpote tpou, qi mno akraioc, all kai kinhtc upodiastolc, dekthc se kpoio tpo (p.q. sumboloseir), genik otidpote. Epshc, mporome s' na kmbo lstac na orsoume perisstera ap na mlh gia thn plhrofora tou kmbou, gia pardeigma, ma sumboloseir, nan akraio kai na dekth se lsta. a Ma llh, pol qrsimh, orgnwsh dedomnwn msw auto-anaforikn domn enai ta duadik dntra. 'Ena duadik dntro enai ma sullog kmbwn, organwmnwn se ma dendrik ditaxh, kajnac ap touc opoouc mpore na qei mqri do kmbouc-paidi. Kje kmboc qei nan kmbo-gona, ektc ap ton prto kmbo tou dntrou, pou enai o kmboc-rza. Ta paidi enc kmbou anafrontai san to arister kai to dex paid tou kmbou. Gia thn anaparstash enc kmbou qrhsimopoiome ma auto-anaforik dom, pwc h exc:
struct tnode { int value; struct tnode *left; struct tnode *right; };
a Den enai endiafron na mporome na qoume kai lstec ap lstec;

125

Me th qrsh thc domc struct tnode, se kje kmbo tou dntrou fulssetai nac akraioc, all ja mporosame san plhrofora proc flaxh na qoume dedomna opoioudpote tpou, pwc kai stic lstec, kai, fusik, kai perisstera tou enc dedomna. Oi dektec left kai right enai oi dieujnseic twn kmbwn pou enai arister kai dex paid, antstoiqa, tou kmbou. 'Opwc kai stic lstec, an kpoio paid den uprqei, o antstoiqoc dekthc enai NULL. H anafor s' na duadik dntro gnetai msw enc dekth sth rza tou. Kat th dhmiourga enc duadiko dntrou, prpei na desmeetai dunamik mnmh (msw malloc) gia na fulaqje kje kmboc, en tan nac kmboc den qreizetai plon, prpei h mnmh pou katalambnei na apodesmeetai (msw free). Ta duadik dntra enai pragmatik qrsima wc organseic dedomnwn tan enai taxinomhmna. 'Ena duadik dntro enai taxinomhmno tan, me bsh kpoio kritrio ditaxhc sthn plhrofora pou apojhkeoume stouc kmbouc tou, o kmboc-rza petai lwn twn kmbwn sto arister paid tou kai prohgetai lwn twn kmbwn sto dex paid tou kai, epshc, tso to arister so kai to dex paid enai taxinomhmna me thn dia logik.

126

San kritria ditaxhc thc plhroforac twn kmbwn enc dntrou, mporome na qoume thn arijmhtik ditaxh, an h plhrofora aut enai nac akraioc nac pragmatikc arijmc, thn alfabhtik ditaxh, an h plhrofora enai ma sumboloseir. An qoume perissterec thc mac plhroforec ston kmbo, tte kpoia, dhlad to antstoiqo mloc thc domc, pazei ton rlo tou legmenou kleidio, pou me bsh aut orzetai h ditaxh metax do kmbwn. 'Estw h prtash some words to insert into a binary tree. Sto sqma, fanetai na taxinomhmno duadik dntro pou periqei tic lxeic thc prtashc autc stouc kmbouc tou.
tnode *

some

insert

words

into

to

binary

tree

To sugkekrimno dntro kataskeusthke eisgontac stadiak tic lxeic thc prtashc me th seir pou emfanzontai sthn prtash. An eqan eisaqje me diaforetik seir, to dntro ja tan telik diaforetik.
teleutaa lxh thc prtashc proc thn prth;

a Poio ja tan to dntro an h eisagwg twn lxewn gintan ap thn

127

Dhmiourga nwn onomtwn tpwn


Sthn C parqetai h dunatthta, msw thc entolc typedef, na dsoume dik mac onmata se tpouc pou qrhsimopoiome suqn, kai met na orzoume metablhtc autn twn tpwn me bsh to no noma. Paradegmata:
typedef int Length; typedef char *String; typedef struct listnode *Listptr; struct listnode { int value; Listptr next; }; typedef struct tnode *Treeptr; typedef struct tnode { int value; Treeptr left; Treeptr right; } Treenode; Length len, maxlen; String name, line[10]; Listptr a_list; Treenode a_tree_node; Treeptr a_tree;

128

Enseic kai peda bit


'Otan h mnmh tan akrib, eqe nhma sta progrmmat mac na knoume oikonoma mnmhc. 'Enac trpoc gia exoikonmhsh mnmhc enai oi enseic, pou orzontai pwc oi domc (me th lxh-kleid union). Den desmeetai qroc gia la ta mlh thc tan orzetai ma metablht tpou nwshc, all autc pou apaitetai gia th flaxh tou mlouc me tic megalterec apaitseic se mnmh. 'Ola ta mlh fulssontai s' autn ton qro. Pardeigma:
union alternative_data { int ivalue; float fvalue; char *svalue; } id_numb;

Oi enseic enai qrsimec kai gia to paketrisma tupikn paramtrwn sunartsewn, tan autc den qreizontai lec tautqrona kat thn klsh thc sunrthshc. 'Alloc trpoc gia oikonoma mnmhc enai ta peda bit. Orzontac ma dom, mporome na dhlsoume mlh tpou akeraou, all me sugkekrimno pljoc bits to kajna. Pardeigma:
struct { unsigned int mode : 2; unsigned int bool : 1; unsigned int octal : 3; } flags;

129

Diaqerish sundedemnwn listn


/* File: listmanagement.c */ #include <stdio.h> #include <stdlib.h> typedef struct listnode *Listptr; struct listnode { int value; Listptr next; }; int empty(Listptr); int in(Listptr, int); int n_th(Listptr, int, int*); void insert_at_start(Listptr *, int); void insert_at_end(Listptr *, int); int delete(Listptr *, int); void print(Listptr); main() { Listptr alist; int v; alist = NULL;

/* List is NULL */ /* Check if list is empty */ printf("List is%s empty\n", empty(alist) ? "" : " not"); insert_at_start(&alist, 44); /* List is 44--> NULL */ printf("List is "); print(alist); insert_at_end(&alist, 55); /* List is 44--> 55--> NULL */ printf("List is "); print(alist); insert_at_start(&alist, 33); /* List is 33--> 44-> 55--> NULL */ printf("List is "); print(alist); insert_at_end(&alist, 66); /* List is 33--> 44-> 55--> 66--> NULL */ printf("List is "); print(alist); /* Check if list is empty */ printf("List is%s empty\n", empty(alist) ? "" : " not"); /* Check membership */ printf("55 is%s in list\n", in(alist, 55) ? "" : " not"); printf("77 is%s in list\n", in(alist, 77) ? "" : " not");

130

if (n_th(alist, 2, &v)) /* Return 2nd element */ printf("Item no 2 is %d\n", v); else printf("Item no 2 does not exist\n"); if (n_th(alist, 6, &v)) /* Return 6th element */ printf("Item no 6 is %d\n", v); else printf("Item no 6 does not exist\n"); printf("Deleting 55. %s\n", delete(&alist, 55) ? "OK!" : "Failed!"); /* List is 33--> 44--> 66--> NULL */ printf("List is "); print(alist); printf("Deleting 22. %s\n", delete(&alist, 22) ? "OK!" : "Failed!"); /* List is 33--> 44--> 66--> NULL */ printf("List is "); print(alist); printf("Deleting 33. %s\n", delete(&alist, 33) ? "OK!" : "Failed!"); /* List is 44--> 66--> NULL */ printf("List is "); print(alist); } int empty(Listptr list) { if (list == NULL) return 1; else return 0; } /* Check if list is empty */ /* Is it really empty? */ /* Yes, it is */ /* No, it isnt */

int in(Listptr list, int v) /* Check if v is member of list { while (list != NULL) /* Visit list elements up to the end if (list->value == v) /* Did we find what we are looking for? return 1; /* Yes, we did else list = list->next; /* No, go to next element return 0; /* Finally, v is not in list }

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

131

int n_th(Listptr list, int n, int *vaddr) /* Return n-th element of list, if it exists, into vaddr { while (list != NULL) /* Maybe search up to the end of the list if (n-- == 1) { /* Did we reach the right element? *vaddr = list->value; /* Yes, return it return 1; /* We found it } else list = list->next; /* No, go to next element return 0; /* Sorry, list is too short } void insert_at_start(Listptr *ptraddr, int v) /* Insert v as first element of list *ptraddr { Listptr templist; templist = *ptraddr; /* Save current start of list *ptraddr = malloc(sizeof(struct listnode)); /* Space for new node (*ptraddr)->value = v; /* Put value (*ptraddr)->next = templist; /* Next element is former first } void insert_at_end(Listptr *ptraddr, int v) /* Insert v as last element of list *ptraddr { while (*ptraddr != NULL) /* Go to end of list ptraddr = &((*ptraddr)->next);/* Prepare what we need to change *ptraddr = malloc(sizeof(struct listnode)); /* Space for new node (*ptraddr)->value = v; /* Put value (*ptraddr)->next = NULL; /* There is no next element }

*/ */ */ */ */

*/ */

*/ */ */ */ */

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

132

int delete(Listptr *ptraddr, int v) /* Delete element v from list *ptraddr, if it exists { Listptr templist; while ((*ptraddr) != NULL) /* Visit list elements up to the end if ((*ptraddr)->value == v) { /* Did we find what to delete? templist = *ptraddr; /* Yes, save address of its node *ptraddr = (*ptraddr)->next; /* Bypass deleted element free(templist); /* Free memory for the corresponding node return 1; /* We deleted the element } else ptraddr = &((*ptraddr)->next);/* Prepare what we might change return 0; /* We didt find the element we were looking for } void print(Listptr list) /* Print elements { while (list != NULL) { /* Visit list elements up to printf("%d--> ", list->value); /* Print current list = list->next; /* Go to next } printf("NULL\n"); /* Print end } % gcc -o listmanagement listmanagement.c % ./listmanagement List is empty List is 44--> NULL List is 44--> 55--> NULL List is 33--> 44--> 55--> NULL List is 33--> 44--> 55--> 66--> NULL List is not empty 55 is in list 77 is not in list Item no 2 is 44 Item no 6 does not exist Deleting 55. OK! List is 33--> 44--> 66--> NULL Deleting 22. Failed! List is 33--> 44--> 66--> NULL Deleting 33. OK! List is 44--> 66--> NULL % of list the end element element

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

*/ */

*/ */ */ */

of list */

133

Diaqerish duadikn dntrwn


/* File: #include #include #include treemanagement.c */ <stdio.h> <stdlib.h> <string.h>

typedef struct tnode *Treeptr; typedef struct tnode { char *word; Treeptr left; Treeptr right; } Treenode; Treeptr addtree(Treeptr, char *); void treeprint(Treeptr, int); void nodesprint(Treeptr); int treedepth(Treeptr); int treesearch(Treeptr, char *); main(int argc, char *argv[]) { Treeptr p; char buf[80]; p = NULL; /* Initialize binary tree while (scanf("%s", buf) != EOF) /* Read words from input p = addtree(p, buf); /* and insert them into the tree printf("Tree is:\n"), treeprint(p, 0); /* Kind of tree pretty printing printf("\nNodes are:\n"); nodesprint(p); /* Print tree nodes in alphabetical order printf("\n\nTree depth is %d\n", treedepth(p)); /* Compute and print depth of tree printf("\n"); while (--argc) { /* For each argument argv++; /* check whether it coincides with any tree node printf("%s found %s\n", (treesearch(p, *argv)) ? " " : "not", *argv); } }

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

134

Treeptr addtree(Treeptr p, char *w) /* Insert word w into tree p { int cond; if (p == NULL) { /* If tree is empty p = malloc(sizeof(Treenode)); /* Allocate space for new node /* Allocate space to copy word p->word = malloc((strlen(w)+1) * sizeof(char)); strcpy(p->word, w); /* Copy word w to tree node p->left = NULL; /* Left subtree of new node is empty p->right = NULL; /* Right subtree of new node is empty } else if ((cond = strcmp(w, p->word)) < 0) /* Does word w precede word of current node? p->left = addtree(p->left, w); /* If yes, insert it into left subtree else if (cond > 0) /* Does it follow word of current node? p->right = addtree(p->right, w); /* If yes, insert it into right subtree /* If it is the same with word of current node, do not insert it return p; /* Return tree } void treeprint(Treeptr p, int ident) /* Pretty print tree { int i; if (p != NULL) { /* If tree is not empty treeprint(p->right, ident+4); /* Print right subtree 4 places right of root node for (i=0 ; i<ident ; i++) printf(" "); /* Take care for identation printf("%s\n", p->word); /* Print root node treeprint(p->left, ident+4); /* Print left subtree 4 places right of root node } } void nodesprint(Treeptr p) { if (p != NULL) { nodesprint(p->left); printf("%s ", p->word); nodesprint(p->right); } } /* Print tree nodes /* If tree is not empty /* Print left subtree /* Print root node /* Print right subtree

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

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

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

*/ */ */ */ */

135

int treedepth(Treeptr p) /* Compute depth of tree p { int n1, n2; if (p == NULL) /* Depth of empty tree is 0 return 0; n1 = treedepth(p->left); /* Compute depth of left subtree n2 = treedepth(p->right); /* Compute depth of right subtree return (n1 > n2) ? n1+1 : n2+1; /* Return maximun of depths of left and right subtrees plus 1 } int treesearch(Treeptr p, char *w) /* Check whether word w is in tree p { int cond; if (p == NULL) /* If tree is empty return 0; /* We didnt find word if ((cond = strcmp(w, p->word)) == 0) /* Word w is the same with word of current node return 1; else if (cond < 0) /* If w precedes word of current node return treesearch(p->left, w); /* Search left suftree else /* Otherwise return treesearch(p->right, w); /* search right subtree }

*/ */ */ */ */

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

136

% gcc -o treemanagement treemanagement.c % cat words.txt some words to insert into a binary tree % ./treemanagement into found words < words.txt Tree is: words tree to some into insert binary a Nodes are: a binary insert into some to tree words Tree depth is 4 found into not found found found words %

137

Esodoc kai xodoc


Kje prgramma prpei na enai se jsh na epikoinwne me to peribllon tou, dhlad na diabzei dedomna kai na grfei apotelsmata, pote to qreizetai. Sthn C, oi mhqanismo eisdou/exdou parqontai ap ma seir sunartsewn, oi opoec perilambnontai sthn prtuph bibliojkh eisdou/exdou thc glssac. 'Otan qrhsimopoiome sunartseic thc bibliojkhc autc prpei na sumperilambnoume sta progrmmat mac kai to sqetik arqeo epikefaldac:
#include <stdio.h>

Oi mondec eisdou/exdou enai ta remata. Mporome na susqetsoume na arqeo, anogontc to, me na rema, all uprqoun kai prokajorismna remata, aut thc prtuphc eisdou (stdin), thc prtuphc exdou (stdout) kai thc prtuphc exdou gia diagnwstik mhnmata (stderr). Kje prgramma qei, kat' arqn, antistoiqsei sto rema stdin to plhktrolgio kai sta remata stdout kai stderr thn ojnh. H diafor metax stdout kai stderr sunstatai sto ti sunhjzetai ta progrmmata na ektupnoun ta apotelsmat touc sto stdout kai diagnwstik mhnmata sto stderr.

138

Se poll peribllonta (Unix, Command Prompt twn Windows, Cygwin, klp.) uprqei h dunatthta na prgramma pou diabzei ta dedomna tou ap thn prtuph esodo (stdin) na mpore na klhje me anakatejunsh thc prtuphc eisdou se kpoio arqeo, opte ja diabzei plon ta dedomna tou ap to arqeo aut. Pardeigma:
% ./myprog < inp_file

Ed, to prgramma ./myprog, ant na diabsei ta dedomna tou ap to plhktrolgio, ja trofodothje me aut ap to arqeo inp file.

Omowc, mporome na qoume kai anakatejunsh thc prtuphc exdou (stdout) se arqeo, opte, ant na ektupnontai ta apotelsmata enc progrmmatoc sthn ojnh, fulssontai sto arqeo aut. Pardeigma:
% ./otherprog arg1 > out_file

Ed, ant na ektupwjon ta apotelsmata tou progrmmatoc ./otherprog sthn ojnh, ja fulaqjon sto arqeo out file.

139

Epshc, mporome na dhmiourgsoume swlhnseic ap progrmmata, dhlad h xodoc tou prtou progrmmatoc thc swlnwshc na enai esodoc gia to detero prgramma, tou opoou h xodoc na enai esodoc gia to trto, k.o.k. Pardeigma:
% ./prog1 22 13 | ./prog2 | ./prog3 27 | ./prog4 10 99

Ed, ta progrmmata ./prog1, ./prog2, ./prog3 kai ./prog4 summetqoun se ma swlnwsh, pou h xodoc kajenc enai esodoc sto epmeno prgramma sth swlnwsh.

Epishmanetai ti tic anakateujnseic (eisdou kai exdou) kai tic swlhnseic tic diaqeirzetai to peribllon ektleshc twn programmtwn (leitourgik ssthma o,tidpote llo). Ta progrmmata pou summetqoun s' autc pot den to majanoun. Me lla lgia, oi qaraktrec <, > kai |, kajc kai ta onmata arqewn stic anakateujnseic den enai orsmata sth gramm entoln kai den mporome (kai den qreizetai) na ta prospelsoume msw argc kai argv. Sth sunqeia, perigrfontai sunoptik oi pio suqn qrhsimopoiomenec sunartseic thc prtuphc bibliojkhc eisdou/exdou Per eisdou/exdou sthn C, uprqei ektetamnh anafor sto Keflaio 7 tou [KR] (sel. 211 233).

140

int getchar(void) Epistrfei ton epmeno qaraktra ap to stdin, h EOF, an qei diabaste lh h esodoc. int putchar(int ch) Grfei ton qaraktra ch sto stdout. Epistrfei ton qaraktra aut, EOF se perptwsh ljouc. int puts(const char *s) Grfei th sumboloseir s sto stdout kai amswc met ma allag grammc. Epistrfei to pljoc twn qaraktrwn pou grfthkan, EOF se perptwsh ljouc. a int printf(const char *format, <op>1 , <op>2 , ...) Grfei sto stdout ta orsmata <op>1 , <op>2 , . . ., smfwna me thn odhga frmac format, kai epistrfei to pljoc twn qaraktrwn pou grfthkan. H sumboloseir format perilambnei qaraktrec pou metafrontai autosioi sthn xodo kai prodiagrafc metatropc gia thn ektpwsh twn <op>1 , <op>2 , . . . Ma prodiagraf metatropc arqzei me ton qaraktra % kai termatzei me na qaraktra pou deqnei to edoc thc metatropc pou prpei na gnei.
a Uprqei kai h adelf sunrthsh char *gets(char *s), gia thn an-

gnwsh ap to stdin mac sumboloseirc, all den prpei na qrhsimopoietai, gia lgouc asfaleac. Mlista, o gcc dnei sqetik proeidopohsh tan qrhsimopoiome autn th sunrthsh s' na prgramma. Ant' autc, ja dome sth sunqeia thn asfal sunrthsh fgets.

141

H genik morf mac prodiagrafc metatropc enai h exc: %[tr][epp][.akr][mm]qm


'O,ti brsketai msa se [ kai ], mpore kai na mhn uprqei.

Metax tou % kai tou qaraktra metatropc (qm) mpore na uprqoun: Kpoioi tropopoihtc (tr), me opoiadpote seir, dhlad na -, pou epibllei arister stoqish, /kai na +, pou kajorzei ti o arijmc ja emfanzetai pnta me prshmo, /kai na 0, pou, gia arijmoc, epibllei th sumplrwsh tou pltouc pedou me mhdenik sthn arq, ef' son qoume dexi stoqish, dhlad an den qei doje kai to - san tropopoihtc. To elqisto pltoc pedou (epp). Sumplhrnontai ken arister dexi, anloga me th stoqish, mhdenik sthn arq an qoume dexi stoqish kai qei doje kai ndeixh 0 ti jloume sumplrwsh me mhdenik. Ma telea . kai nac arijmc, h akrbeia (akr), pou kajorzei to mgisto arijm qaraktrwn pou ja ektupwjon gia na alfarijmhtik, ton arijm twn yhfwna gia arijm kinhtc upodiastolc ton elqisto arijm yhfwn gia akraio. To mgejoc metablhtc (mm), dhlad h, l L, an prkeitai gia ektpwsh short int, long int long double, antstoiqa.
a dekadikn gia metatropc f, e E shmantikn gia metatropc g G

142

Pijano qaraktrec metatropc enai: d: Gia arijmoc sto dekadik ssthma. o: Gia aprosmastouc oktadikoc arijmoc. x, X: Gia aprosmastouc dekaexadikoc arijmoc. Me metatrop x, ta yhfa met to 9 emfanzontai pez (a, b, c, d, e, f), en me metatrop X, emfanzontai kefalaa (A, B, C, D, E, F). u: Gia aprosmastouc arijmoc sto dekadik ssthma. c: Gia qaraktrec. s: Gia sumboloseirc. f: Gia arijmoc kinhtc upodiastolc, se anaparstash qwrc ekjth. e, E: Gia arijmoc kinhtc upodiastolc, se anaparstash me ekjth. To smbolo thc ywshc se dnamh tou 10 emfanzetai san e E, anloga me ton qaraktra metatropc pou qrhsimopoijhke. g, G: Gia arijmoc kinhtc upodiastolc, se anaparstash me qwrc ekjth, anloga me to mgejoc tou ekjth se sqsh me thn akrbeia pou qei zhthje. An o ekjthc enai mikrteroc tou -4 megalteroc ap soc me thn akrbeia, efarmzetai metatrop e E (anloga me to an qoume g G), allic efarmzetai metatrop f. Ta mhdenik kai h upodiastol sto tloc den emfanzontai. %: Gia ektpwsh tou %.

143

Paradegmata ektupsewn:
int x = 3456 double d = -3768.08549

Prodiagraf
%d %7d %2d %-7d %+7d %07d %7.5d %7o %-7x %7.6X

Ektpwsh
3456 3456 3456 3456 +3456 0003456 03456 6600 d80 000D80

Prodiagraf
%f %14.4f %-14.3f %e %14.4E %-14.3e %g %14.4g %-14.3G %014.4f

Ektpwsh
-3768.085490 -3768.0855 -3768.085 -3.768085e+03 -3.7681E+03 -3.768e+03 -3768.09 -3768 -3.77E+03 -00003768.0855

char *p = "this is a test phrase"

Prodiagraf
%s %25s %12s %.12s %-25s %25.12s %-25.12s

Ektpwsh
this is a test phrase this is a test phrase this is a test phrase this is a te this is a test phrase this is a te this is a te

144

int scanf(const char *format, <op>1 , <op>2 , ...) Diabzei ap to stdin dedomna, smfwna me thn odhga frmac format, kai ta apojhkeei eke pou deqnoun oi dektec <op>1 , <op>2 , . . ., Epistrfei to pljoc twn dedomnwn pou diabsthkan EOF, an qei diabaste lh h esodoc. 'Ena dedomno eisdou enai ma akolouja ap mh leukoc qaraktrec pou termatzei ston epmeno leuk qaraktra,a ston epmeno qaraktra pou anamnetai na diabaste me bsh to format, tan exantlhje to pltoc pedou. H sumboloseir format mpore na perilambnei: Ken sthlognmonec, pou epiblloun thn katanlwsh lwn twn leukn qaraktrwn ap thn trqousa jsh thc eisdou kai met. 'Allouc qaraktrec, ektc ap ton %, pou prpei na sumfwnon me ton epmeno mh leuk qaraktra sthn esodo, allic h scanf stamat to dibasma.
a ken, sthlognmonac allag grammc

145

Prodiagrafc metatropc, pou sqhmatzontai, me aut th seir, ap: ton qaraktra % na proairetik qaraktra *, pou deqnei ti to dedomno pou diabsthke den prpei na fulaqje na proairetik arijm pou kajorzei to mgisto pltoc pedou na proairetik h, gia thn angnwsh short int, na l, gia long int double, na L gia long double. na qaraktra metatropc, antstoiqa me autoc thc printf (d, o, x, u, c, s, f, e, g, %) [. . .], to opoo prokale thn angnwsh thc megalterhc akoloujac qaraktrwn sthn esodo, ap autoc pou perilambnontai msa sta [ kai ], [^. . .], to opoo enai parmoio me to prohgomeno, all diabzontai qaraktrec pou den periqontai msa sta [ kai ] Epishmanetai ti h qrsh thc scanf gia angnwsh sumboloseirn parousizei parmoio prblhma asfleiac me aut thc sunrthshc gets, to opoo mwc antimetwpzetai an dhlwje kai mgisto pltoc pedou (p.q. %20s) gia thn angnwsh.

146

FILE *fopen(const char *filename, const char *mode) Anogei to arqeo me noma filename gia na to qrhsimopoisoume me ton trpo pou perigrfetai sto mode. Epistrfei na rema ( dekth se arqeo), me bsh to opoo mporome sth sunqeia na anafermaste sto arqeo, NULL, an gia kpoio lgo den tan dunatn na anoxei to arqeo. To FILE enai ma dom (typedef'ed ap to stdio.h) me katllhla mlh gia na gnetai o qeirismc tou arqeou. To mode mpore na enai: "r": Gia dibasma ap uprqon arqeo. "w": Gia gryimo se arqeo. An to arqeo den uprqei, dhmiourgetai. An uprqei, ta prohgomena perieqmen tou diagrfontai kai to gryimo arqzei ap thn arq tou arqeou. "a": Gia gryimo se arqeo me prosrthsh sto tloc tou twn nwn dedomnwn, an to arqeo uprqei dh, qwrc diagraf twn prohgomenwn perieqomnwn tou. "r+": Gia dibasma kai gryimo, opoudpote msa se uprqon arqeo, qwrc diagraf twn prohgomenwn perieqomnwn tou. "w+": Gia dibasma kai gryimo, opoudpote msa sto arqeo, me diagraf twn prohgomenwn perieqomnwn tou, ef' son aut uprqei dh. "a+": Gia dibasma ap opoudpote msa ap to arqeo kai gryimo mno sto tloc tou, qwrc diagraf twn prohgomenwn perieqomnwn tou.

147

Se orismna sustmata, gnetai dikrish metax arqewn keimnou kai duadikn arqewn (sto Unix pntwc, qi), opte eke, an jloume na qeiristome na duadik arqeo, prpei sto mode na prosteje kai o qaraktrac b, dhlad na qoume, anloga me thn perptwsh "rb", "wb", "ab", "r+b" ("rb+"), "w+b" ("wb+"), "a+b" ("ab+"). int fclose(FILE *fp) Klenei to rema fp. Epistrfei 0 EOF, se perptwsh epituqac apotuqac, antstoiqa. char *fgets(char *buf, int max, FILE *fp) Diabzei to pol max-1 qaraktrec ap to rema fp, mqri thn allag grammc (\n). Oi qaraktrec pou diabsthkan (maz kai me to \n) fulssontai sth sumboloseir buf, h opoa termatzetai kanonik me \0. Epistrfei to buf, NULL an qei diabaste lh h esodoc. a int feof(FILE *fp) Epistrfei mh mhdenik tim an qoun diabaste la ta dedomna ap to rema fp, dhlad qoume ftsei sto tloc tou arqeou pou antistoiqe sto rema, , allic, 0.
a Epismwc, uprqei kai h sunrthsh char *gets(char *buf), h opoa

knei perpou ,ti kai h fgets. Diabzei ap to rema stdin, qwrc na bzei kpoio pnw rio sto pljoc twn qaraktrwn pou ja diabaston kai, gi' aut akribc, gia lgouc asfaleac, apojarrnetai h qrsh thc. Epshc, h gets den topojete ton qaraktra allagc grammc (\n) pou dibase msa sto buf. An jloume na diabsoume ma gramm qaraktrwn ap thn prtuph esodo, mporome na qrhsimopoisoume thn fgets, dnontac san teleutao risma to stdin, ant na qrhsimopoisoume thn gets.

148

int getc(FILE *fp) Epistrfei ton epmeno qaraktra ap to rema fp, EOF, an qoume ftsei sto tloc tou antstoiqou arqeou. int putc(int ch, FILE *fp) Grfei ton qaraktra ch sto rema fp. Epistrfei ton qaraktra aut, EOF se perptwsh ljouc. int ungetc(int ch, FILE *fp) Gurzei psw sto rema fp ton qaraktra ch, tsi ste na diabaste pli se epmenh angnwsh. Epistrfei ton qaraktra aut, EOF se perptwsh ljouc. int fprintf(FILE *fp, const char *format, <op>1 , <op>2 , ...) 'Idia me thn printf, mno pou grfei sto rema fp, ant gia to stdout. int fscanf(FILE *fp, const char *format, <op>1 , <op>2 , ...) 'Idia me thn scanf, mno pou diabzei ap to rema fp, ant ap to stdin. int sprintf(char *str, const char *format, <op>1 , <op>2 , ...) 'Idia me thn printf, mno pou grfei sth sumboloseir str, ant gia to rema stdout. int sscanf(char *str, const char *format, <op>1 , <op>2 , ...) 'Idia me thn scanf, mno pou diabzei ap th sumboloseir str, ant ap to rema stdin.

149

size t fread(void *ptr, size t size, size t count, FILE *fp) a Diabzei ap to rema fp to pol count dedomna megjouc size to kajna kai ta topojete ap th diejunsh ptr kai met. Epistrfei to pljoc twn dedomnwn pou diabsthkan. O legqoc tlouc thc eisdou mpore na gnei me th sunrthsh feof. size t fwrite(const void *ptr, size t size, size t count, FILE *fp) Grfei sto rema fp to pol count dedomna megjouc size to kajna, parnontc ta ap th diejunsh ptr kai met. Epistrfei to pljoc twn dedomnwn pou grfthkan. An grafon ligtera ap count dedomna, aut ja ofeletai se kpoio ljoc pou sunbh. int fseek(FILE *fp, long offset, int origin) Jtei thn trqousa jsh sto rema fp na enai: offset ( 0) qaraktrec ap thn arq, an to origin qei teje SEEK SET. offset qaraktrec ap thn trqousa jsh, an to origin qei teje SEEK CUR. offset qaraktrec ap to tloc, an to origin qei teje SEEK END.
Epistrfei 0 se perptwsh epituqac.
a O tpoc size t enai o unsigned int, typedef'ed.

150

long ftell(FILE *fp) Epistrfei thn trqousa jsh sto rema fp, -1L se perptwsh ljouc. int fflush(FILE *fp) Grfei sto rema exdou fp ,ti pijanc brsketai sthn endimesh perioq apojkeushc. Epistrfei 0 EOF, se perptwsh epituqac apotuqac, antstoiqa. void perror(const char *s) Ektupnei th sumboloseir s kai ma perigraf tou pio prsfatou ljouc pou qei sumbe. H sunrthsh perror enai pol katatopistik tan qrhsimopoiome sunartseic thc prtuphc bibliojkhc thc C, oi opoec endqetai na prokalsoun kpoio ljoc, gia pardeigma h malloc oi sunartseic diaqerishc arqewn, pwc h fopen, kai mac endiafrei na mjoume poio akribc ljoc prokljhke. Sqetik me th sunrthsh perror enai kai ma exwterik metablht errno, h opoa qei san tim nan akraio pou antistoiqe sto pio prsfato ljoc pou qei sumbe. An jloume na qrhsimopoisoume th metablht errno msa s' na prgramma, prpei na qoume sumperilbei kai to arqeo epikefaldac sto opoo orzetai:
#include <errno.h>

Ma epismansh pou prpei na gnei enai ti den mporome na qrhsimopoisoume opoiadpote sunrthsh se opoiodpote rema. Exarttai ap to mode pou djhke tan noixe to antstoiqo arqeo.

151

Antigraf arqewn
/* File: filecopy.c */ #include <stdio.h> main(int argc, char *argv[]) { FILE *ifp, *ofp; int n; char buf[1024]; if (argc != 3) { fprintf(stderr, "Usage: %s <soure-file> <target-file>\n", argv[0]); return 1; } if ((ifp = fopen(argv[1], "rb")) == NULL) { /* Open source file perror("fopen source-file"); return 1; } if ((ofp = fopen(argv[2], "wb")) == NULL) { /* Open target file perror("fopen target-file"); return 1; } while (!feof(ifp)) { /* While we dont reach the end of source /* Read characters from source file to fill buffer n = fread(buf, sizeof(char), sizeof(buf), ifp); /* Write characters read to target file fwrite(buf, sizeof(char), n, ofp); } fclose(ifp); fclose(ofp); return 0; }

*/

*/

*/ */ */

152

% gcc -o filecopy filecopy.c % ./filecopy Usage: ./filecopy <soure-file> <target-file> % ./filecopy bla foo fopen source-file: No such file or directory % % cat helloworld.c /* File: helloworld.c */ #include <stdio.h> main() { printf("Hello world\n"); } % ./filecopy helloworld.c newhelloworld.c % cat newhelloworld.c /* File: helloworld.c */ #include <stdio.h> main() { printf("Hello world\n"); } % ls -l helloworld.c newhelloworld.c -rw------1 ip www 81 -rw-r----1 ip www 81 % diff helloworld.c newhelloworld.c % % ./filecopy filecopy Copy\ of\ filecopy % ls -l filecopy Copy\ of\ filecopy -rw------1 ip www 6884 -rwx-----1 ip www 6884 % cmp filecopy Copy\ of\ filecopy %

Dec 18 21:45 newhelloworld.c Oct 13 12:42 helloworld.c

Dec 18 21:46 Copy of filecopy Dec 18 21:34 filecopy*

153

Ektpwsh grammn eisdou me antstrofh seir


/* File: #include #include #include revinput.c */ <stdio.h> <stdlib.h> <string.h>

typedef struct Slistnode *SListptr; struct Slistnode { char *line; SListptr next; }; /* A list node structure */ /* with a string as member */

void Sinsert_at_start(SListptr *, char *); void Sprint(SListptr); main() { char buf[1024]; SListptr list; list = NULL; /* Initialize list to store lines to be read while (fgets(buf, sizeof buf, stdin) != NULL) /* Read a line /* and insert it at the start of the list Sinsert_at_start(&list, buf); Sprint(list); /* Print the list, i.e. the input reversed }

*/ */ */ */

void Sinsert_at_start(SListptr *ptraddr, char *buf) /* The well-known insert_at_start function */ { SListptr templist; templist = *ptraddr; *ptraddr = malloc(sizeof(struct Slistnode)); (*ptraddr)->line = malloc((strlen(buf)+1) * sizeof(char)); strcpy((*ptraddr)->line, buf); (*ptraddr)->next = templist; } void Sprint(SListptr list) { while (list != NULL) { printf("%s", list->line); list = list->next; } } /* Just print out the list */

154

% gcc -o revinput revinput.c % ./revinput These are some lines to test program revinput. Ok, one more line. These are my last words before the minus signs --------------------------^D --------------------------before the minus signs These are my last words Ok, one more line. to test program revinput. These are some lines % % cat helloworld.c /* File: helloworld.c */ #include <stdio.h> main() { printf("Hello world\n"); } % % ./revinput < helloworld.c } { printf("Hello world\n"); main() #include <stdio.h> /* File: helloworld.c */

155

O proepexergastc thc C
O proepexergastc thc C enai na autnomo upossthma tou logismiko metaglttishc, to opoo kaletai autmata prin ap thn pragmatik diadikasa thc metaglttishc. O skopc tou proepexergast enai na metasqhmatsei to phgao arqeo C pou tou djhke s' na llo phgao arqeo, smfwna me ma seir ap odhgec pou apeujnontai s' autn. To apotlesma tou proepexergast enai aut to opoo ja uposte th diadikasa thc metaglttishc. Oi grammc tou phgaou arqeou pou arqzoun ap # enai odhgec proc ton proepexergast. Akolouje ma sunoptik perigraf twn pio suqn qrhsimopoiomenwn odhgin tou proepexergast. Sqetik pio analutik anafor gnetai sthn pargrafo 4.11 tou [KR] (sel. 128 133).

156

#include Qrhsimopoietai gia thn eisagwg twn perieqomnwn arqewn epikefaldac sth jsh pou brsketai h odhga. 'Ena arqeo epikefaldac periqei sunjwc dhlseic prwtotpwn sunartsewn, orismoc sumbolikn stajern kai makroentoln (me thn odhga #define), sumperilyeic llwn arqewn epikefaldac, klp. Se arqea epikefaldac, den sunhjzetai na qoume kdika progrmmatoc. Epshc, den knoume #include phgaa arqea kdika C. H odhga #include emfanzetai me do ekdoqc. Prth ekdoq: #include <sysfile.h> O proepexergastc ja yxei na brei to arqeo sysfile.h se katalgouc pou qei dhlsei me kpoio trpo o qrsthc, gia pardeigma me thn epilog -I kat thn klsh tou gcc, stouc katalgouc pou brskontai ta prokajorismna arqea epikefaldac thc glssac, oi opooi mpore na diafroun ap egkatstash se egkatstash. Deterh ekdoq: #include "myfile.h" O proepexergastc ja yxei na brei to arqeo myfile.h se katalgouc tou qrsth, kat' arqn ston katlogo pou brsketai to phgao arqeo, kai met se llouc katalgouc, pou djhkan, gia pardeigma, me thn epilog -I tou gcc. An den breje ote eke to arqeo, ja yxei kai stouc katalgouc arqewn epikefaldac tou sustmatoc. Fusik, enai epitreptc kai dhlseic:
#include <sys/types.h> #include "mydir/anotherdir/myfile.h"

157

#define Qrhsimopoietai gia ton orism sumbolikn stajern makroentoln. 'Opou brei o proepexergastc san lektik smbolo (qi mwc msa se ") th sumbolik stajer thn parametrik makroentol pou orzetai me thn odhga, thn antikajist me to kemeno pou thc qei antistoiqhje. Pardeigma orismo sumbolikc stajerc:
#define YES 1

O proepexergastc ja antikatastsei to YES, pou to brei san lektik smbolo msa sto phgao arqeo me to 1 (qi mwc sto printf("YES\n"), ote kai sto x = YESMAN++).

Pardeigma orismo makroentolc:


#define max(A, B) ((A) > (B) ? (A) : (B))

An brei o proepexergastc sth sunqeia sto arqeo kpoia entol thc morfc
x = max(p+q, r+s);

ja thn antikatastsei me thn


x = ((p+q) > (r+s) ? (p+q) : (r+s));

Parathrste, sto pardeigma aut, ti ta A kai B ja upologisjon telik do forc, afo tsec brskontai sto kemeno antikatstashc, prgma pou mpore sto sugkekrimno pardeigma na mhn enoqle, all se llec periptseic qreizetai prosoq. a
a Pisteete ti h kfrash max(i++, j++) ja antikatastaje swst me

bsh ti eqe sto mual tou mllon o programmatistc pou thn graye;

158

Oi parenjseic grw ap tic paramtrouc sto kemeno antikatstashc mac makroentolc endqetai, se kpoiec periptseic, na enai krsimec. Pardeigma:
#define square(X) X * X

Pc ja antikatastaje to square(a+1); a Aut tan pou jlame; b Pc ja prepe na dhlwje h makroentol; g

Arketc ap tic sunartseic thc glssac pou qrhsimopoiome sta progrmmat mac, enai orismnec san makroentolc msa se arqea epikefaldac kai qi me kdika sth bibliojkh thc glssac. Gia pardeigma, oi gnwstc mac sunartseic getchar kai putchar orzontai msa sto arqeo stdio.h wc exc:
#define getchar() #define putchar(x)
a a+1 * a+1 b 'Oqi, bbaia. g #define square(X)

getc(stdin) putc(x, stdout)

((X) * (X))

159

#if, #else, #elif, #endif, #ifdef, #ifndef Sthn C, uprqei h dunatthta metaglttishc up sunjkh. 'O,ti perilambnetai metax enc #if kai tou amswc epmenou #endif, pou den qei antistoiqhje me kpoio llo #if, ja metaglwttiste mno an h akraia parstash pou brsketai met to #if apotimhje se mh mhdenik tim. Sunjwc, oi akraiec parastseic met to #if sugkrnoun timc sumbolikn stajern, pou qoun antistoiqhje se akraiouc, metax touc me akraiec stajerc, msw twn telestn sgkrishc thc C (==, !=, >, klp.). Me thn odhga #else, arqzei to tmma mac domc #if/#endif pou ja metaglwttiste an h parstash met to #if enai yeudc (sh me mhdn). H odhga #elif mpore na qrhsimopoihje gia pio sntomh graf mac #else thc opoac to sma apoteletai ap ma #if, apofegontac tsi kai to epiplon #endif. Pardeigma:
#if SYSTEM == SYSV #define HDR "sysv.h" #elif SYSTEM == BSD #define HDR "bsd.h" #elif SYSTEM == MSDOS #define HDR "msdos.h" #else #define HDR "default.h" #endif #include HDR

160

Kpoia eidik parstash pou mpore na uprqei met ap na #if enai h defined(NAME), pou apotimtai se 1 an to NAME qei oriste me #define, allic se 0. H odhga
#if defined(NAME)

enai isodnamh me thn


#ifdef NAME

Stic parastseic met ap na #if mporome na qoume kai rnhsh (!). Gia pardeigma, an jloume na exasfalsoume ti ta perieqmena tou arqeou hdr.h ja sumperilhfjon ma mno for se ma polplokh efarmog me pollc sumperilyeic, ja mporosame na to domsoume wc exc:
#if !defined(HDR) #define HDR /* The real contents of hdr.h go here */ #endif

To #if !defined(HDR) ja mporose na grafe isodnama kai san #ifndef HDR

Domc #if (#ifdef, #ifndef)/#endif mpore na enai emfwliasmnec. Me th bojei touc mporome na prosomoisoume emfwliasmna sqlia, kti pou me ton sunjh trpo grafc sqolwn (/* . . . */) den enai dunatn. Pc;

161

Taxinmhsh pinkwn
Uprqoun diforec mjodoi, llec ligtero, llec perisstero apodotikc, gia thn taxinmhsh twn stoiqewn enc pnaka. H taxinmhsh enc pnaka qei nhma tan uprqei ma sqsh ditaxhc sto snolo ap to opoo parnoun timc ta stoiqea tou pnaka. Gia arijmoc (akraiouc kinhtc upodiastolc) qoume thn arijmhtik ditaxh, gia sumboloseirc thn alfabhtik. Gia llouc tpouc dedomnwn, prpei na qei orisje safc h sqsh ditaxhc. Gia pardeigma, ditaxh metax domn mpore na oriste me bsh th ditaxh wc proc na mloc-kleid thc domc (arijmhtik sumboloseir). Sth sunqeia, oi algrijmoi, ta paradegmata kai ta progrmmata pou parousizontai stoqeoun sthn taxinmhsh pinkwn, se axousa seir, me stoiqea pou enai arijmo. Oi mjodoi taxinmhshc mporon na prosarmosjon ekola kai gia periptseic llwn monodistatwn domn dedomnwn, gia pardeigma sundedemnwn listn.

162

'Ena jma pou qei geniktero endiafron stouc algorjmouc enai o qrnoc pou qreizetai gia thn ektles touc, anloga me to mgejoc thc eisdou touc. Aut ekfrzetai me thn poluplokthta qrnou touc. Oi mjodoi taxinmhshc qoun diforec poluplokthtec qrnou, oi opoec antanaklon thn apodotiktht touc. Gia na ekfrsoume thn poluplokthta enc algorjmou, sunjwc qrhsimopoiome ton sumbolism O. 'Otan h esodoc enc algorjmou qei mgejoc n (gia pardeigma to pljoc twn stoiqewn enc pnaka pou jloume na taxinomsoume), lgontac ti h poluplokthta qrnou tou algorjmou enai O(f (n)), ennoome ti o qrnoc ektlesc tou, T (n), den qei megaltero rujm axhshc ap autn thc sunrthshc f (n), so auxnei to n. Dhlad uprqoun C kai n0 ttoia ste T (n) < C f (n) gia kje n > n0 . Gia pardeigma, h poluplokthta tou algorjmou gia thn eresh thc mshc timc n arijmn enai O(n), en h poluplokthta tou algorjmou kataskeuc enc magiko tetragnou n n enai O(n2 ). Se orismnec periptseic, h qronik apdosh enc algorjmou gia esodo megjouc n exarttai kai ap to poia enai h sugkekrimnh esodoc. Stic periptseic autc, mporome na anafermaste sthn poluplokthta qeristhc perptwshc (gia thn pio dskolh esodo) sth msh poluplokthta (msh tim apdoshc gia lec tic pijanc eisdouc).

163

H mjodoc thc fusaldac


Sgkrine zeugria diadoqikn stoiqewn, ap ktw proc ta epnw, kai tan brskeic do pou den enai sth swst seir, antimetjes ta. Met ap to prto prasma, prto stoiqeo ja enai to mikrtero lwn. Kne kai detero prasma, gia ta stoiqea ap to detero kai met, opte tsi ja ljei kai to detero kat seir sth jsh tou. Met ap n1 persmata sunolik, o pnakac ja qei taxinomhje.
6 3 7 2 9 5 8 1 3 8 6 3 7 2 9 5 1 8 3 8 6 3 7 2 9 1 5 8 3 8 1 6 3 7 2 9 5 8 3 8 1 6 3 7 2 9 5 3 8 8 1 2 6 3 7 3 9 5 8 8 1 2 3 6 3 7 5 9 8 8 1 2 3 3 5 6 7 8 8 9

poluplokthta O(n2 )

Gia i = 1, 2, . . ., n1 Gia j = n1, n2, . . ., i An xj1 > xj tte


Antimetjese xj1 kai xj

164

H mjodoc thc epilogc


Brec to mikrtero ap la ta stoiqea kai antimetjes to me to prto. Brec to mikrtero ap ta uploipa kai antimetjes to me to detero. Met ap n1 epilogc kai antimetajseic sunolik, o pnakac ja qei taxinomhje.
6 3 7 2 9 5 8 1 3 8 1 3 7 2 9 5 8 6 3 8 1 2 7 3 9 5 8 6 3 8 1 2 3 7 9 5 8 6 3 8 1 2 3 3 9 5 8 6 7 8 1 2 3 3 5 9 8 6 7 8 1 2 3 3 5 6 8 9 7 8 1 2 3 3 5 6 7 9 8 8 1 2 3 3 5 6 7 8 9 8 1 2 3 3 5 6 7 8 8 9

poluplokthta O(n2 )

Gia i = 1, 2, . . ., n1
min = i1 Gia j = i, i+1, . . ., n1 An xj < xmin tte min = j Antimetjese xi1 kai xmin

165

H mjodoc thc eisagwgc


Topojthse to detero stoiqeo prin met to prto ste na enai sth swst seir. Topojthse to trto sth swst jsh sta dh taxinomhmna prto kai detero. Met topojthse to ttarto sta tra prta. Met ap n1 eisagwgc sunolik, o pnakac ja qei taxinomhje.
6 3 7 2 9 5 8 1 3 8 3 6 7 2 9 5 8 1 3 8 3 6 7 2 9 5 8 1 3 8 2 3 6 7 9 5 8 1 3 8 2 3 6 7 9 5 8 1 3 8 2 3 5 6 7 9 8 1 3 8 2 3 5 6 7 8 9 1 3 8 1 2 3 5 6 7 8 9 3 8 1 2 3 3 5 6 7 8 9 8 1 2 3 3 5 6 7 8 8 9

poluplokthta O(n2 )

Gia i = 1, 2, . . ., n1
j = i1

Ensw j 0 kai xj > xj+1


Antimetjese xj kai xj+1 j = j1

166

H grgorh mjodoc
Me bsh to prto stoiqeo san odhg, qrise ton pnaka se do llouc, nan pou periqei stoiqea mikrtera sa me ton odhg kai nan me megaltera sa. Taxinmhse touc do autoc pnakec me thn dia mjodo anadromik (ef' son qoun toulqiston do stoiqea), opte to telik apotlesma enai h parjesh twn taxinomhmnwn autn pinkwn me endimesh parembol tou odhgo stoiqeou.
6 3 7 2 9 5 8 1 3 8 6 3 7 2 9 5 8 1 3 8 3 3 7 2 9 5 8 1 6 8 3 3 7 2 9 5 8 1 6 8 3 3 6 2 9 5 8 1 7 8 3 3 1 2 9 5 8 6 7 8 3 3 1 2 9 5 8 6 7 8 3 3 1 2 6 5 8 9 7 8 3 3 1 2 6 5 8 9 7 8 3 3 1 2 5 6 8 9 7 8 3 3 1 2 5 6 8 9 7 8 1 2 3 3 5 6 7 8 8 9

msh poluplokthta O(n log n)

167

Sunrthsh qs(x, up, down)


start = up end = down Ensw up < down Ensw xdown xup kai up < down down = down1 An up = down tte Antimetjese xup kai xdown up = up+1 Ensw xup xdown kai up < down up = up+1 An up = down tte Antimetjese xup kai xdown down = down1 An start < up tte Klese qs(x, start, up1) An end > down tte Klese qs(x, down+1, end)
Gia na taxinomsoume ton pnaka x pou qei n stoiqea, ja prpei na kalsoume qs(x, 0, n1).

'Allec mjodoi taxinmhshc H mjodoc tou swro, O(n log n) H mjodoc thc sugqneushc, O(n log n) H mjodoc tou Shell, O(n2 ) (sel. 94 [KR])

168

Mjodoi taxinmhshc
/* File: #include #include #include void void void void void void sorting.c */ <stdio.h> <stdlib.h> <time.h>

bubblesort(int, double *); selectsort(int, double *); insertsort(int, double *); quicksort(int, double *); quicksort_body(double *, int, int); swapd(double *, double *);

main(int argc, char *argv[]) { char method = b, *name; /* Default sorting method is bubblesort int i, n = 10; /* Default array size is 10 long seed; double *x, starttime, endtime; void (*fun)(int, double *); /* Pointer to sorting function seed = time(NULL); /* Get current time, in case seed is not given if (argc > 1) /* First character of first argument method = *argv[1]; /* denotes the employed sorting method if (argc > 2) n = atoi(argv[2]); /* Second argument is number of elements if (argc > 3) /* Third argument is seed for seed = atoi(argv[3]); /* random number generator switch(method) { /* Prepare calling the appropriate method case b: fun = bubblesort; name = "bubblesort"; break; case s: fun = selectsort; name = "selectsort"; break; case i: fun = insertsort; name = "insertsort"; break; case q: fun = quicksort; name = "quicksort"; break; default: printf("Sorry, no such method\n"); return 1; } /* Allocate memory for the array if ((x = malloc(n * sizeof(double))) == NULL) { printf("Sorry, not enough memory\n"); return 1; }

*/ */

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

*/

169
srand((unsigned int) seed); /* Initialize random number generator for (i=0 ; i<n ; i++) /* Generate n double floating point numbers x[i] = ((double) rand())/RAND_MAX; printf("Random numbers\n"); for (i=0 ; i<n ; i++) { printf("%6.4f ", x[i]); /* Print them out if (i%10 == 9) /* 10 in a line printf("\n"); } printf("\n"); printf("Sorting by %s\n", name); starttime = ((double) clock())/CLOCKS_PER_SEC; /* Get CPU time /* consumed since start of program (*fun)(n, x); /* Call sorting method endtime = ((double) clock())/CLOCKS_PER_SEC; /* Again CPU time /* Difference endtime-starttime should be /* CPU time consumed for sorting for (i=0 ; i<n ; i++) { printf("%6.4f ", x[i]); /* Print out sorted array if (i%10 == 9) printf("\n"); } printf("\n"); /* Print out CPU time needed for sorting printf("Time: %.2f secs\n", endtime-starttime); free(x); } void bubblesort(int n, double *x) { int i, j; for (i=1 ; i<=n-1 ; i++) /* Bring appropriate element, /* that is the bubble, to place i-1 for (j=n-1 ; j>=i ; j--) if (x[j-1] > x[j]) /* Compare pairwise from bottom to top swapd(&x[j-1], &x[j]); /* and swap if needed } void selectsort(int n, double *x) { int i, j, min; for (i=1 ; i<=n-1 ; i++) { min = i-1; /* Let current minimum be the for (j=i ; j<=n-1 ; j++) if (x[j] < x[min]) /* Check if any element after min = j; /* than so far minimum and make it the swapd(&x[i-1], &x[min]); } /* Exchange minimum with } */ */

*/ */

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

*/

*/ */ */ */

i-1 element */ i-1 is less */ new minimum */ i-1 element */

170

void insertsort(int n, double *x) { int i, j; for (i=1 ; i<=n-1 ; i++) { /* Insert element at place i in /* its correct position from places 0 to i-1 j = i-1; while (j>=0 && x[j] > x[j+1]) { /* Move repeatedly the element swapd(&x[j], &x[j+1]); /* until it reaches j--; } } /* its correct position }

*/ */ */ */ */

void quicksort(int n, double *x) { quicksort_body(x, 0, n-1); /* Call recursive quicksort to sort */ } /* elements of the array from position 0 to position n-1 */ void quicksort_body(double *x, int up, int down) { int start, end; start = up; /* Save start position of small elements end = down; /* Save end position of large elements while (up < down) { /* Pivot element is at up position while (x[down] >= x[up] && up < down) /* Let down elements down--; /* larger than pivot stay where they are if (up != down) { /* If pivot is not reached swapd(&x[up], &x[down]); /* echange it with smaller element up++; /* Pivot is at down position, move up a bit further } while (x[up] <= x[down] && up < down) /* Let up elements up++; /* smaller than pivot stay where they are if (up != down) { /* If pivot is not reached swapd(&x[up], &x[down]); /* exchange it with larger element down--; /* Pivot is at up position, move down a bit further } } /* Now up = down is the position of the pivot element if (start < up) /* Is there at least one element left of pivot? quicksort_body(x, start, up-1); /* Quick(sort) smaller elements if (end > down) /* Is there at least one element right of pivot? quicksort_body(x, down+1, end); /* Quick(sort) larger elements } void swapd(double *a, double *b) { double temp; temp = *a; *a = *b; *b = temp; }

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

/* Just exchange two doubles */

171

% gcc -o sorting sorting.c % ./sorting b 30 Random numbers 0.7793 0.1050 0.5197 0.8237 0.8140 0.3184 0.8334 0.8853 0.0604 0.9981 0.9160 0.7987 0.6526 0.2380 0.4877 0.3815 0.8499 0.9563 0.5682 0.8995 0.7011 0.8272 0.3778 0.3641 0.3623 0.5319 0.9399 0.2587 0.0387 0.9204 Sorting by bubblesort 0.0387 0.0604 0.1050 0.2380 0.2587 0.3184 0.3623 0.3641 0.3778 0.3815 0.4877 0.5197 0.5319 0.5682 0.6526 0.7011 0.7793 0.7987 0.8140 0.8237 0.8272 0.8334 0.8499 0.8853 0.8995 0.9160 0.9204 0.9399 0.9563 0.9981 Time: 0.00 secs % ./sorting s 30 Random numbers 0.4595 0.8727 0.5696 0.9981 0.7452 0.8356 0.5967 0.9968 0.6831 0.2828 0.1422 0.1314 0.0112 0.1514 0.9064 0.0762 0.9622 0.9530 0.5056 0.0356 0.2680 0.5524 0.3585 0.1433 0.1383 0.1783 0.9059 0.2644 0.3080 0.8845 Sorting by selectsort 0.0112 0.0356 0.0762 0.1314 0.1383 0.1422 0.1433 0.1514 0.1783 0.2644 0.2680 0.2828 0.3080 0.3585 0.4595 0.5056 0.5524 0.5696 0.5967 0.6831 0.7452 0.8356 0.8727 0.8845 0.9059 0.9064 0.9530 0.9622 0.9968 0.9981 Time: 0.00 secs % ./sorting i 30 Random numbers 0.0288 0.4756 0.5888 0.2960 0.9495 0.1113 0.6595 0.1166 0.3072 0.6231 0.6908 0.9518 0.5337 0.5027 0.6060 0.8049 0.8516 0.1825 0.0201 0.2418 0.2553 0.0621 0.9665 0.1353 0.9752 0.1192 0.2774 0.7282 0.6423 0.9476 Sorting by insertsort 0.0201 0.0288 0.0621 0.1113 0.1166 0.1192 0.1353 0.1825 0.2418 0.2553 0.2774 0.2960 0.3072 0.4756 0.5027 0.5337 0.5888 0.6060 0.6231 0.6423 0.6595 0.6908 0.7282 0.8049 0.8516 0.9476 0.9495 0.9518 0.9665 0.9752 Time: 0.00 secs % ./sorting q 30 Random numbers 0.0843 0.5580 0.6041 0.7343 0.3129 0.7320 0.5098 0.6124 0.8065 0.0953 0.5297 0.2080 0.9518 0.7837 0.9656 0.7879 0.9631 0.5661 0.2316 0.2067 0.0451 0.6699 0.6528 0.5289 0.4447 0.4719 0.5746 0.4992 0.1097 0.3981 Sorting by quicksort 0.0451 0.0843 0.0953 0.1097 0.2067 0.2080 0.2316 0.3129 0.3981 0.4447 0.4719 0.4992 0.5098 0.5289 0.5297 0.5580 0.5661 0.5746 0.6041 0.6124 0.6528 0.6699 0.7320 0.7343 0.7837 0.7879 0.8065 0.9518 0.9631 0.9656 Time: 0.00 secs %

172

% hostname zeus % ./sorting b 10000 2006 | tail -4 0.9982 0.9983 0.9985 0.9985 0.9985 0.9986 0.9987 0.9988 0.9989 0.9989 0.9990 0.9994 0.9994 0.9995 0.9995 0.9996 0.9996 0.9997 0.9998 0.9999 Time: 11.18 secs % ./sorting b 30000 2006 | tail -4 0.9994 0.9994 0.9995 0.9995 0.9995 0.9995 0.9995 0.9996 0.9996 0.9997 0.9997 0.9997 0.9997 0.9998 0.9998 0.9999 0.9999 0.9999 0.9999 1.0000 Time: 97.74 secs % ./sorting s 10000 2006 | tail -4 0.9982 0.9983 0.9985 0.9985 0.9985 0.9986 0.9987 0.9988 0.9989 0.9989 0.9990 0.9994 0.9994 0.9995 0.9995 0.9996 0.9996 0.9997 0.9998 0.9999 Time: 5.51 secs % ./sorting s 30000 2006 | tail -4 0.9994 0.9994 0.9995 0.9995 0.9995 0.9995 0.9995 0.9996 0.9996 0.9997 0.9997 0.9997 0.9997 0.9998 0.9998 0.9999 0.9999 0.9999 0.9999 1.0000 Time: 50.46 secs % ./sorting i 10000 2006 | tail -4 0.9982 0.9983 0.9985 0.9985 0.9985 0.9986 0.9987 0.9988 0.9989 0.9989 0.9990 0.9994 0.9994 0.9995 0.9995 0.9996 0.9996 0.9997 0.9998 0.9999 Time: 7.79 secs % ./sorting i 30000 2006 | tail -4 0.9994 0.9994 0.9995 0.9995 0.9995 0.9995 0.9995 0.9996 0.9996 0.9997 0.9997 0.9997 0.9997 0.9998 0.9998 0.9999 0.9999 0.9999 0.9999 1.0000 Time: 69.16 secs % ./sorting q 10000 2006 | tail -4 0.9982 0.9983 0.9985 0.9985 0.9985 0.9986 0.9987 0.9988 0.9989 0.9989 0.9990 0.9994 0.9994 0.9995 0.9995 0.9996 0.9996 0.9997 0.9998 0.9999 Time: 0.04 secs % ./sorting q 30000 2006 | tail -4 0.9994 0.9994 0.9995 0.9995 0.9995 0.9995 0.9995 0.9996 0.9996 0.9997 0.9997 0.9997 0.9997 0.9998 0.9998 0.9999 0.9999 0.9999 0.9999 1.0000 Time: 0.13 secs % ./sorting q 100000 2006 | tail -4 0.9998 0.9998 0.9998 0.9998 0.9998 0.9998 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 Time: 0.45 secs %

173

Anazthsh se pnakec
Pollc forc qoume na pnaka ap stoiqea (arijmoc, sumboloseirc, o,tidpote) kai jloume na dome an na sugkekrimno stoiqeo, diou tpou me aut tou pnaka, ankei ston pnaka. H diadikasa aut lgetai anazthsh. O aplosteroc trpoc na knoume anazthsh s' na pnaka enai me th legmenh seiriak anazthsh. Diatrqoume ta stoiqea tou pnaka, na proc na, mqri na brome to stoiqeo pou yqnoume, an to brome telik. An o pnakac enai megloc, h seiriak anazthsh mpore na enai pol qronobra. An mwc taxinomsoume ton pnaka, stw se axousa seir, mporome na efarmsoume ma pol taqterh mjodo, th duadik anazthsh. Me th duadik anazthsh, sugkrnoume to stoiqeo pou yqnoume me to mesao ( na ap ta do mesaa) stoiqeo tou pnaka. An sumpptei, stamatme thn anazthsh afo to stoiqeo brjhke. An qi, sthn perptwsh pou to stoiqeo prohgetai tou mesaou, yqnoume na to brome sto prto mis tou pnaka. An petai tou mesaou, to yqnoume sto detero mis. H anazthsh ston katllhlo upopnaka gnetai me ton dio trpo, sugkrnontac to stoiqeo me to mesao tou upopnaka kai h diadikasa suneqzei me autn ton trpo, mqric tou ete na breje to stoiqeo ete na ftsoume se ken upopnaka. Poiec enai oi poluplokthtec twn mejdwn;
a

a O(n) kai O(log n), gia th seiriak kai th duadik anazthsh, antstoiqa.

174

Mjodoi anazthshc
/* File: #include #include #include #include searching.c */ <stdio.h> <stdlib.h> <string.h> <time.h>

void heapsort(int, char **); void heapify(char **, int, int); int seqsearch(char *, int, char **); int binsearch(char *, int, char **); void swapwords(char **, char **); main(int argc, char *argv[]) { int k = 0; /* Counter of words that will be read int nmax = 1000; /* Default maximum number of words to read double starttime, endtime; char search = s; /* Default is sequential search char **words, *arg, buf[81]; while (--argc) { arg = *++argv; if (!strcmp(arg, "-max")) { /* Get maximum number if (argc > 1 && --argc) /* of words to read nmax = atoi(*++argv); } else if (!strcmp(arg, "-seq")) /* Select sequential search search = s; else if (!strcmp(arg, "-bin")) /* Select binary search search = b; else if (!strcmp(arg, "-words")) { /* Give words to search for argc--; break; } } argv++; /* Allocate memory to store addresses of words to read if ((words = malloc(nmax * sizeof(char *))) == NULL) { fprintf(stderr, "Not enough memory\n"); exit(1); }

*/ */ */

*/ */ */ */ */

*/

175

while (k < nmax && scanf("%80s", buf) != EOF) { /* Read words until EOF or maximum number reached and */ /* allocate memory to store them */ if ((words[k] = malloc((strlen(buf)+1) * sizeof(char))) == NULL) { fprintf(stderr, "Not enough memory\n"); exit(2); } strcpy(words[k++], buf); } /* Store word read */ if (search == b) /* If binary search selected */ heapsort(k, words); /* sort words via the heapsort method */ starttime = ((double) clock())/CLOCKS_PER_SEC; /* Search start time */ while (argc--) { arg = *argv++; switch (search) { case s: /* The sequential search case */ printf("%sfound %s\n", seqsearch(arg, k, words) ? " " : "not ", arg); break; case b: /* The binary search case */ printf("%sfound %s\n", binsearch(arg, k, words) ? " " : "not ", arg); break; } } endtime = ((double) clock())/CLOCKS_PER_SEC; /* Search end time */ printf("Searching time is %.2f seconds\n", endtime-starttime); } void heapsort(int n, char **x) { int i; for (i=(n/2)-1 ; i>=0 ; i--) /* Transform array to a heap /* A heap is an implicit binary tree where each node is not smaller heapify(x, i, n-1); /* than its immediate successors for(i=n-1 ; i>=1 ; i--) {/* Move root of heap to bottom rightmost swapwords(&x[0], &x[i]); /* position not already settled and heapify(x, 0, i-1); }/*transform to a heap the rest of the tree }

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

176

void heapify(char **x, int root, int bottom) { int maxchild; /* Transform to a heap the subtree starting at root /* up to element bottom while (2*root < bottom) { /* Do we have still work to do? if (2*root+1 == bottom) /* If left child is last to consider maxchild = 2*root+1; /* this is the maximum child else if (strcmp(x[2*root+1], x[2*root+2]) > 0) /* Otherwise maxchild = 2*root+1; /* select maximum between left else maxchild = 2*root+2; /* and right child of root if (strcmp(x[maxchild], x[root]) > 0) {/* Compare maximum child swapwords(&x[maxchild], &x[root]); /* with root and swap root = maxchild; } /* accordingly, defining also the new root else break; } } /* OK, we made our heap

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

int seqsearch(char *w, int n, char **x) { int i; for (i=0 ; i<n ; i++) if (!strcmp(w, x[i])) /* So simple, what to comment here! */ return 1; return 0; } int binsearch(char *w, int n, char **x) { int cond, low, high, mid; low = 0; /* Lower limit for searching high = n-1; /* Upper limit for searching while (low <= high) { /* Do we have space for searching? mid = (low+high)/2; /* Medium element of search interval /* to compare with word we are looking for if ((cond = strcmp(w, x[mid])) < 0) /* Compare medium to word high = mid-1; /* Not found, word might be at first half else if (cond > 0) low = mid+1; /* Not found, word might be at second half else return 1; } /* We found it! return 0; } /* Sorry, word not found

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

void swapwords(char **w1, char **w2) { char *temp; /* The well-known swap function for the strings case */ temp = *w1; *w1 = *w2; *w2 = temp; }

177

% gcc -o searching searching.c % cat test_words.txt Hello there! How are you? Hello!!! I am fine. What about you? Are you OK? Yes, I am fine. Thank you. % ./searching -seq -max 50 -words you word fine I < test_words.txt found you not found word not found fine found I Searching time is 0.00 seconds % ./searching -bin -max 50 -words you word fine I < test_words.txt found you not found word not found fine found I Searching time is 0.00 seconds % ./searching -bin -max 12 -words you word fine I < test_words.txt not found you not found word not found fine found I Searching time is 0.00 seconds % wc -w /usr/dict/words 25143 /usr/dict/words % ./searching -seq -max 26000 \ ? -words cat KRExcerpt.txt < /usr/dict/words | tail found well found to found write found major not found programs found in found many found different not found domains. Searching time is 0.28 seconds % ./searching -bin -max 26000 \ ? -words cat KRExcerpt.txt < /usr/dict/words | tail found well found to found write found major not found programs found in found many found different not found domains. Searching time is 0.00 seconds %

178

% hostname zeus % wc -w large_file.txt 263901 large_file.txt % ./searching -seq -max 300000 \ ? -words cat KRExcerpt.txt < found programs found in found many found different not found domains. Searching time is 0.81 seconds % ./searching -bin -max 300000 \ ? -words cat KRExcerpt.txt < found programs found in found many found different not found domains. Searching time is 0.01 seconds % ./searching -bin -max 300000 \ ? -words cat /usr/dict/words ? 23606 % ./searching -bin -max 300000 \ ? -words cat /usr/dict/words ? 1537 % ./searching -bin -max 300000 \ ? -words cat /usr/dict/words ? found time found timeout not found timepiece not found timeshare not found timetable not found timeworn Searching time is 0.29 seconds % ./searching -seq -max 300000 \ ? -words cat /usr/dict/words ? ^C .......... unacceptable running time %

large_file.txt | tail -6

large_file.txt | tail -6

< large_file.txt \ | grep not found | wc -l < large_file.txt \ | grep found | wc -l < large_file.txt \ | grep time

< large_file.txt \ | grep time

179

'Ena prgramma C prpei na enai . . .


. . . swst. Profanc! Prgramma pou dnei ljoc apotelsmata prpei na diorjwje. . . . apodotik. Ta progrmmata prpei na dnoun ta apotelsmat touc msa se elogo qronik disthma. Bbaia, o orismc tou elogou poiklei anloga me thn perptwsh kai tic sunjkec. Se kje perptwsh, ja prpei na prospajome to prgramm mac na qei th mgisth dunat apdosh. Epshc, ja prpei na elgqoume th sumperifor tou kai gia, pijanc asunjista, meglec eisdouc. Pntwc, na prgramma pou jewrhtik kpoia stigm ja termatsei, all mpore na mhn zome gia na to dome, den qei praktik axa. . . . erwsto. Den prpei to prgramma na bgzei ljh ektleshc, opoiadpote kai an enai h esodoc pou dqthke. Den arke na sumperifretai omal mno gia tic anamenmenec eisdouc. . . . tekmhriwmno. H tekmhrwsh sunstatai sthn kal epilog onomtwn metablhtn, sunartsewn, klp., kajc kai sthn prosjkh sqolwn. H tekmhrwsh prpei na enai tsh sh qreizetai gia na knei to prgramma katanoht. Ote ligterh, all ote kai perissterh. . . . euangnwsto. Prpei na qei sunep stoqish, na apofegontai grammc me perissterouc ap 80 qaraktrec, na uprqoun ken grw ap telestc, pou aut beltinei thn anagnwsimthta.

180

Suqn programmatistik ljh sthn C


Na knoume diaresh metax akerawn, euelpistntac ti ja proume san apotlesma nan arijm kinhtc upodiastolc, en sthn pragmatikthta parnoume to akraio phlko thc diareshc. Na nomsoume ti se ma akraia metablht mporome na fulxoume tim osodpote meglh, ti se ma metablht kinhtc upodiastolc mporome na qoume sh akrbeia jloume. Na knoume ljoc sthn oriak sunjkh termatismo mac domc epanlhyhc. Na qrhsimopoisoume gia telest sgkrishc msa se sunjkh to =, ant gia to ==. Na bloume met ap ma for ma while na ; prin thn entol to mplok entoln pou apotelon to sma touc. Na xeqsoume ti ta stoiqea enc pnaka me distash N arijmontai ap to 0 wc to N-1, kai qi ap to 1 wc to N. Na qeiristome aprsekta touc dektec, gia pardeigma na dokimsoume na gryoume eke pou pisteoume ti deqnei nac dekthc, qwrc na qoume knei thn apaitomenh dsmeush mnmhc. Na desmeoume dunamik mnmh me epanalhptik trpo kai na mhn thn apodesmeoume tan den thn qreiazmaste.

181

Na bloume ; sto tloc mac odhgac #define. Na xeqsoume na bloume parenjseic grw ap to kemeno antikatstashc mac makroentolc, pou orzoume me #define, kai pou allo qreizetai msa s' aut. Na parexhgsoume tic proteraithtec twn telestn, gia pardeigma na gryoume
while (ch = getchar() != EOF)

ant gia
while ((ch = getchar()) != EOF)

Na knoume sgqush anmesa sthn nnoia thc proteraithtac twn telestn, pou qei na knei me to po efarmzetai nac telestc, me th seir ektleshc twn energein pou prosdiorzoun oi telestc. Gia pardeigma, to *p++ enai ntwc to dio me to *(p++), to opoo mwc pollo nomzoun, ljoc, ti shmanei ti prta ja auxhje o dekthc p kai met ja prospelsoume to perieqmeno thc nac diejunshc. OQI. Aplc, o telestc ++ ed enai metajematikc, dhlnontac ti prta ja prospelasje to perieqmeno thc diejunshc pou deqnei o p kai met ja auxhje autc. Oi parenjseic grw ap to p++ deqnoun po efarmzetai o telestc ++ (ston dekth p) kai qi pte ja ektelesje h prxh pou upodeiknei.

182

Na qeiristome aprsekta metablhtc me to dio noma, parexhgntac tic embleiec kajemic, kai na qrhsimopoiome kpoia ap' autc, en pragmatik qrhsimopoiome kpoia llh. Na jewrsoume ti topikc metablhtc enai arqikopoihmnec (gia pardeigma, se 0), parti emec den qoume knei rht kti ttoio. Na diatupsoume aprsekta emfwliasmnec entolc if, paralepontac gkistra { kai } se periptseic pou qreizontai, me apotlesma h entol na enai men suntaktik swst, opte o metaglwttistc den diamartretai, all na shmanei kti llo ap aut pou eqame prjesh na gryoume. Na xeqsoume krsima break stic periptseic mac entolc switch. Na tautsoume to A me to "A". Na parablyoume to gegonc ti ma sumboloseir termatzei me ton qaraktra \0. Na sugkrnoume sumboloseirc me ton telest ==, ant me th sunrthsh strcmp. Na mhn bloume sunjkh termatismo mac anadromc. Na kalsoume thn scanf pernntac s' autn tic metablhtc pou jloume na diabsoume, ant gia tic dieujnseic touc.

183

Bibliografa
Brian W. Kernighan, Dennis M. Ritchie: H Glssa Programmatismo C , Prentice Hall (Ellhnik metfrash, ekdseic

Kleidrijmoc), 1988.
Brian W. Kernighan, Rob Pike: The Practice of Programming, Addison-Wesley, 1999. Jon Bentley: Programming Pearls, 2nd edition, Addison-Wesley,

2000.
Steven S. Skiena: The Algorithm Design Manual, Springer-Verlag,

1998.
H. M. Deitel, P. J. Deitel: C: How to Program, 3rd edition, Prentice Hall, 2001. Niklaoc Misurlc: Eisagwg ston Programmatism me thn C ,

2003.
Eric S. Roberts: H Tqnh kai Epistmh thc C , Addison-Wesley

(Ellhnik metfrash, ekdseic Kleidrijmoc), 2004.


Niklaoc J. Apostoltoc: Programmatismc

Efarmogc, 1995.

Diomdhc Spinllhc: Angnwsh Kdika H Prooptik tou Anoikto Logismiko, ekdseic Kleidrijmoc, 2005. Brian W. Kernighan, Rob Pike: To Peribllon Programmatismo Unix , Prentice Hall (Ellhnik metfrash, ekdseic Kleidrijmoc),

1989.
Donald E. Knuth: The Art of Computer Programming: Sorting and Searching (Vol. 3), 2nd edition, Addison-Wesley, 1998. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Cliord Stein: Introduction to Algorithms, 2nd edition, The MIT Press,

2001.

184

Euqaristec ...
... sth Lktora Izamp Karlh gia th metdosh poltimhc empeirac,

iden kai uliko ap to mjhma tou Antikeimenostrafoc Programmatismo pou didskei sto Tmma mac ap to akadhmak toc 2002 03.
... epshc sthn Izamp kai stouc metaptuqiakoc foithtc Stfano

Stamth kai Nko Pojht pou dibazan me aperiristh upomon ta prwtleia autn twn diafanein/shmeisewn, ensw grafntousan, kai updeixan na pljoc ap ljh kai paraleyeic pou eqan, knontac tautqrona kai protseic gia th dirjws touc.

... gia th suneisfor touc sta ergastria, sthn axiolghsh twn asksewn, sthn upostrixh twn foithtn kai sth diaqerish tou froum epikoinwnac tou majmatoc ...
..., ektc ap ton Stfano kai ton Nko, kai stouc metaptuqiakoc

foithtc Dhmtrh Yonh, Ginnh Belesith, Aristotlh Glent, Manlh Sunodin, Mi Li Triantafulldh, Dhmtrh Katr, Fobo Jeoqrh, Stlio Karampaskh, Dhmtrh Kwtsko, 'Anna Nka, Ea Sitardh kai Dhmtrh Papra kajc kai stouc proptuqiakoc foithtc Dhmtrh-Hla Gkantsio, Ksta Tzannetko, Manlh Platkh, Dhmtrh Rabilo, Jodwr Gewrgou, Mno Karbonh kai Girgo Kastrnh.
..., tloc, kai stouc metaptuqiakoc foithtc (prhn kai nun) Nko

Karampatzikh, Blia Tsagkaldou, Zsh Taqtsdh, Ginnh Fut, Ginnh Probatrh, Katerna Iatropolou, 'Elena Nikolkh, Gita Koltsda kai Spro Mpotsh gia th suneisfor touc kat ta prohgomena akadhmak th. Panagithc Stamatpouloc

You might also like