You are on page 1of 19
eee ao | 90©600060000090900000000009 Uae \ include Haya Sab wrt Voryos. ms Hello Program 1 the editor of your e Create a file named belo cu ice. Here we use guia. Type this in | 8 terminal: et a $ vie hello.c Aetlo.e The classic first ¢ program. oa mcd § vO Stow ooh hood $e int main(void) { printf (*Hellouworld.\n") ; return(o) ; \ ‘To compile the program, $ gee,-o hello hello.c hullo.c - o fillow 00606000000000909279279905 oeoo6oo ceoe cectee hp + welcome ¢ Welcomes the ser by his/her weername to the machine (aoore — th net tat mat vold) {, roe erat ear alien] war's cencltecDs fhe so} Sone = getene USER} Printf(* Hello Sa.-Welcome.to.%a.\n", name, ba) ; rman ‘Te compile the program, 4B gce -o velcone velcone.c tet Dag debe Siyes inlay oyfy VO 2 float darimals +4 ae 2 borate S04, ipl Pit aes | stants Frente ppnee ©0999000000059900 eoao “eee eeeoeo l oop Program 3 Create file natned root.sqr using the editor of your choice Here we wie gvim. Type ‘his in «emia: 8 grim root.aqt.c le catdio.n> je cnath b> int ain (vosd) « int beg, ond prints (\nuwuuuuusuusuuuRooteyandySquares\a\n") ; prints (*Thiay programy computesuthesraot,, Prints (*fronm,tous,whereunvandama [eeccartorass sua aig aA ee cae printf (*Sorry ,Zerovar ativeyvaluesuarevmotuvalid.\m") ; = eRe ee a | Priste meer utbevendigcaasegee mie gy | arene as EN ust” ) | } primes var) i ose ea to 06 Aart (og), bogebeg) a; 104\n Yn gap odie Fetura(o) ‘Te compile the program, $0 -0 root.age roct-sqr,c -he Program 4 Odd of Ever? gram ‘ 9 Create a fle named odd.even.c using the editor of your choice. Here we use gvia. Type ° ‘this in a terminal ” - Sip ealereece \ Freres cache thr the spat anben $0 old or coats es Pe ene okt Hinclude < int main(void) « long nus vhile (ireof(stain)) ¢ printf ("Please,enteryany integer. (Ctrl ~dutovexityiu*) fscanf (stdin, "hd" num) ; At (feof (atdin)) { printf (*\n") ; ©000000000000999990 toad = gum £2, 10-15 o °o oO ° ° ° oe o oC © Largest and Smallest Program 5 Create a file named Irgsm..c using the editor of your choice. Here we use gvin. Type this in a terminal 8 gvim Inge Urgemt.c + This program finds the Largest and smallest number in + the input set Hinclude 0 66 sae masnCvose) EF Boel float big, seal, num ; a 2° big = -1038 ; (9° 7® as peal = 1638) 65 ‘ a a0; 4 while (1feof(stdin)) { printf (“Enteryayreal/ int fecant (stdin, "It" num) ; if (feof (stdin)) { break; big-> (up > big)? num : big = um < small, 7 num ery (Ctr] -dutoyexit) yu Ae iS bit a" printf (*\n\n0f uth printf (*\tomallest, d else ¢ printt (*\n\aExitinguasutherevisunouinput!\n*) 5 } return(o) ; ‘To compile the program, $ gee -o Argum) Irgeal.c 00000090909 ceceeconooooooaoaea0oeoeo00o9 Fibonacci Sequence Program ¢ Create a file named fibonacc4 .c using the editor of your choice. Here we use gvim. Type this in a terminal $ gvim fibonacci.c + fidonacci.c 7 #include Computes the Fibonacci sequence. int main(voia) { int at, a2, num, i, emp ; printf (*Enterytheyfirstuseedjyiu") ; fscanf (stdin, "hd", Rent) ; printf("Enterythe,second,seedy:") ; fecanf (stdin, "%d", gn2) ; printf (*Terminatevafteruuuuuuuiu") ; fecanf(atdin,*%d", Raum); prints ("\nFibonaccivsequence.ofufduaumbersuvithuy*, mumt2) ; printf ("Udyandutduasuseedsyis:\n\n", ni, 02) ; Print#(*yuuutdusuutdu", ni, 2) Are oo for GG = 4 5 i pum ; 164) { tmp = ni + 02 5 7+ compute the -nezt number «/ i= n2; m2 = tmp; 7+ swap the numbers +/ Prints (*uuuuld".22) 5 Ye print at 47 + rintf("\n\n") ; e 5 ine return(0) ‘To compile the program, $ gcc -0 Fibonacci fibonacci.c Enumeration Program 7 0 ae ; Create a fle named enum. using the editor of your choice. Here we use gvim. Type thi 4 terminal: D $ gvim enum.c > > + emme ) + This program demonstrates the enum type. > “ Hinclude > ant main(vosd) ) ‘ . enus daynames (sunday, monday, tuesday, vedn thursday, friday, saturday? ) 0 enum daynames days ; colors(7] = {*Violet", *Indigo", "Blue", "Green*, "Yellow", “Orange”, "Red"} ; char > for (days = sunday ; days <= saturday ; daya++) { printf ("Xdy:uTodayuisu™,days) ; switch (days) { sunday?" printf ("Sunday .u") monday = { printf ("Monday.4") unt tussday > { printf (= Tuesday 4") ‘i vednesday : { printf (*Vadnesday.u' aie case thursday : { printf ("Thursday ..") | case friday; { printf (*Friday.u") rt Case saturday : { prints (*Saturéayu*) nw |? printf (*Suitableycolouryiauls.\n", coloraldays]) i , return (0) ; ‘To compile the program, $ gcc ~o enum enum.c Oe ao SCSCCHOSCsS SOS OSD OOOO OO aS *eeeecooaoocea Pr Projectile Trajectory Vv rogram § a i c If w is the initial velocity and @ is the angle of projection of a projectile, the total distance travelled 3 and the maximum height reached by the projectile are given by ‘The trajectory is given by Create file named projectile.c using the editor of your choice. Here we use gvim. Type this in a terminal: $ gvim projectile.c projectile.c Compute the trajectory of a projectile sh . jot with an initial velocity I tt an angle. Also, finds the maz. height and distance travelled The progr wise 7pites the trajectory date to 6 péte geen ae wMch can be used by plotting prograns Like gauplor, #include include int main(vosa) « Tost shatasytait vali, geotel yor aie? float theta rad, t1, (2, max’h int 1 char name [100] FILE *let ; ox aa ‘Ast printf (*Enterutheuanglevot, ‘fscant (stdin, "41" Atheta) theta_rad = theta’s HPI/180, ; UPFojectiony (degr Print£(*Enterutheuinitialvelocit Yule u iy") ; {scant (stdin, *Zf" einit_vel) rut iter fecant (stdin fot_dise = inte velesaic. marth = inst ‘ /* Check whether we can o; pen the file for writing, */ Af CClst = fopen(name, "w)) == NULL) O{ /* We can’t. Exit. +/ Print{(*Cannotyopenyfilevksuforyuriting.\n",name) ; return 1 ; o tprint{ (lav, "#Projectilevtrajectoryudatau\n") + tprint# (lst, *#uuuulmitialuvelocityuu fprintf (iat, {printf (1st {printf (1st %10.A%m/o\n" init _val) “Muuuudngleuuusuuuuuuuuuy WhO. 4f,degrees\n", theta) “Bucuumax uheightuuuuuuuutus-10.4fo\n",max_h) ; “Muuuulax udistanceyuuuuu:uh-10. 4fa\n", tot dist) ti = tan(theta_rad) t2 = g/(2einit_veleinit_vel+cos(theta_rad)*cos(theta_rad)) /* The distance travelled is divided into 100 parts and corresponding + heights are calculated. These are written to the file. +/ 1-0 while (x <= tot_dist) { x = ivtot_dist/100 yor xett = xexet2 Af (Gy <0) ( break ; } fprintf (ist ,"%10.6f£4115.6f\n", x,y) 5 ? fclose(1st) return (0) ; ‘To compile the program, $ gcc -0 projectile projectile.c ~Im ee ee re C€ececeoococooonoonoo9o A typical ran wok! be as shown below: ro $ fprojectate ° Hater the angle of projection (degrees) © 38 Hater the anitial velocity (w/a): 25 < tonto filename to write the trajectory data; proji.dat ‘Total distance travelled = §9.929 = Maximum height reached = 10.491 0m $ fprojectite Hnter the angle of projection (degrees) : 45 ‘Sater the initial velocity (/s) : 28 Eater filename to urite the trajectory data : proj2.dat ‘Total distance travelled = 63.76 Maximum height reached = 15.94 0 projectile ‘Barer the angle of projection (degrees) : 65 Enter the initial welecity (a/s) : 25 Eater filename to write the trajectory data : proj3.dat Total distance travelled = 48.895 Maximum height reached = 26.192 $ gmpict gnuplot set xlabel "Distance travelled (@)* ee nae ely gauplot> plot "projt.dat" ti “angles3S*, eee, _ sprojS.dat* ti angle-65* ees Sn gruplow cCeeeceeeeooecoononon oo OOOO O00 08D OOOO D Program 9 Create a file named prime .¢ using the editor of your cholee, Here we ‘terminal pein Type thie in $ gvin prime.¢ * oan + Program checks whether the input number Gx prime or not. v include Himelude ine main(voia) « poet Long num, 1, Lsprime, i, sign ; 8 host ao 4 printf ("Pleaseyenteryanyintegery (Ctrl “dy tovexit), fecanf (stdin, "Td" nu J At (tqotCaraim)) ¢ Jf prime Naa) : <0 1:05 fe Check 47 num ta ve #/ (aun); ul = Gane) agre(aun)+t tu") g $4 (aun < 2) ( nus == 27 prints (Numbers ioupris printt (*Numberyieuneit Ant): Fuprimeynor uc } else ( for (ind; iemul; 404) ( ispri 205 Af Ciaprime) { break ; } 2 Seprine 7 prince (*hauisuaupri Print# Ad uisyaotuaupris y y vbite (1) ; retura(o) 3 £ ‘To compile the program, § acc -o prime prine.c -tm fon iol 0 Ik I oo ------- Roots of # Quadratic Equation Program 10 Create ile named quad.roota.c using the editor of your choice, Here we ae gv ‘his in 8 terminal $ gvim quad roots ” + quad roots. + Computes the roots of @ quadratic equation / include #snelude cnath n> int caplx-0, Host Lin vase Cin) ¢ Pinte Tnpututheve yor ut fecant( fa, kb ke) ey) 42 Chuan) {2 Obit val fle printf (Theufirstycoofficientycannotybeuze) yyequationaxse2ebrec\m\t\e*) ; UTeyuagain \a") 5 > laced 6 = agrt(tabel2))/(20a) 5 re -b/(Qea) 5 printt Roots of utheyequationarey*) ; eaplz 7 printf (*imaginaryy:yI10.4futullO Afyivandu M0. 4fy-uKie eine) printt (*realy:yHt0.Afuanduht0.4fu\n", r+z, r-2) 5 eerteasolt fe Ay a "To compile the program, § ce -0 quad. roots quad roote.c ln oo0oo0o0gg79 (a (akon oti Factoriat Program 11 On a 82 bit computer, the fnetorial of a number > 12 will eause an overflow. ‘This program ‘computes the factorial by the regular method forall aumbers < 12 and uses Stisling approximation ‘o ealeulato the factorial for numbers > 12. The Stirling's formula is given as etc eee ie Varn (2) (14a, ica reent soeemet |) ‘We me unt theft tre ema to calulle the facto bac )nt eel bw sem 5)" (1+ aa + ace) ‘The error in the values calculated thus are very small. A few examples are given below ast ‘Computed: 1307675405008 ‘Actual 1307674368000 Dit 1037698 Bx 00079 9% 0 ‘Computed + $0414008854066674172507000587008710277901572832022242621049012224 ‘Actual '3041409320171837804361 2608 166061768841877641568960512000000000000 Dit 652853206128804482420943941433613981263061730671040012224 En 0000021 % Create a fle named factorial.c using the editor of your choice. Here we use gvim. Type ‘this i terminal: $ gvim factorial.c factorta utes the factorial of a gtven integer, Does a direct tation form <= 12 a1 Stirling's formula for m > 12, double precision float Ament ay wo { printe(Entervany integer toucalculateyitsufactorial, Tecanf (stdin, "Xd", &n1) if (ms 0) ¢ printf (*Undef ined, d else { » if (nl == 0) { printf ("Thankuyou.\n") break ; ) al <= 12-7 printf (*4i2dtu-uzd\n", nt, factorial (nt)) Printe("Xi2dlu=u%-100.02\n", ini, fact ora COutouext uct) , wforuaunegativeynumber.\n") ; dowhite (mi) ; i ~ return (0) ; “WA l= Coe unsigned long int factorial (int n) { ar return 1; veturn(m + factorial(n-1)) ; , 0) 11 G@ == 1) ble fact_big(int n) { double x ; = sqrt (26H_P: = (94.0/02 return(x) ; ) © pow(n/M_E,n) + Factors Program 12 Create a file named factors. using the editor of your choice. Here we use gvia. Type this in a terminal: $ gvim factors.c + factors.c + Given an integer, find its factors. / #include #include int main(void) { long n, num, divisor, rem, limit ; while (!feof(stdin)) { printf ("Pleaseyentervanyintegery (Ctrl -dytoyexit)yiu") 5 fscanf(stdin,"Zd",kn) 5 Af (feof(stdin)) { break ; } prints (\tukausu" sm) Bum = abs{a) ; divieor = 2; Tieit ~ agre(pum)#1 gnile (divisor <= Limit) ¢ ; Fen = num divisor ; f+ start dividing «/ if Ciren) { printf ("%dutuu' hun /= divisor divisor = 25 Limit = sqrt(mum)+t ; } else { divisors 5 J+ try with net number #/ > 7 divisor) ; /+ we have a divisor +/ 7+ repeat the process for the sigh y nue == 1? printf(*\n") : printf ("%du",num) n <0? printf(*#,-1\n") : printf ("\n"), oF return(0) ; y ‘To compile the program, gee -0 factors tactors.c -le Pascal's Triangle > Program 13 ¥ Pascal's triangle determines the coefficients which arise in binomial expansions o o (e+ u)" = aor” + a,2"-'y + agz"—2y? +--+ aq izy"! + ony” ‘The coefficients a, in this expansion ‘are the numbers on row n of Pascal's triangle. The formula used to calculate the coefficients is Create a file named pas-tri.c in a terminal: using the editor of your choice. Here we use gvim. Type this $ gvim pas.tri.c rn Pas_tri.c This program calculates the Pascal Triangle. ” include include int main(void) ‘ 3 int i, j, k, order ; unsigned long int factorial (int) ; ; double fact_big(int) ; printf (*\uusuusuuuuuuuuuuuuPascal printf (*Inpututhevorderus:u") ; fscanf(stdin,"%d" Border) ; i < order ; itt) { kc i; kee) { t_big(i)/(fact_big(k) + fact_big(i-k)) ; printf (*Z10d",9) 5 , printe(\ y return (0) Foublo fact _bigdint a) { double x if (n cw 12) { xX = factorial (n) } else { X= sqrt (Q*N_PTen) * pow(m/M_E,n) * (1#1.0/(124n)+1.0/(288enen)) xt 5 . return (x) } ‘To compile the program, $ gcc -o pas.tri pas.tri.c Im To execute the program, $ -/pastri a a we a SP ee ee Tee : ° Liner Ragouion: Program 14 ‘This method fits a straight line of the form y = maze to a set of n data points (7;,,). The function that is minimised is x Wlm,e) = Yo (wm - er)? ‘The above equation will be at its minimum vanish, ith respect to m and c, when the first derivatives % ae ” =2)) a(y — m- cx) } To simplify, let » x x ” SENGS.= D055 Syed wi See a? is Sey) zits | AZ SSee — (Sz? et aS cot fi ‘The solutions are SexSy~S2Sey - , _ SSzy - SeSy a = 7 Create « file named Linreg.c using the editor of your choice. Here we use gvim. in a terminal: Lanreg.c ” Hinclude include Fit a line of the type y = mz + c to the given data se int main(void) t float x(200], y(200], sx = 0., sx2 = 0., mo 0.,¢=0., delt jut n= 0,25 char 1ine(200) ; while (1) ( fgets (ine, 200, = secant (line "Xs 16 (Gr = HOF), as sx += x(n} ; 8x2 += (x(n) ¢ x{n]) ; /* Accumulate the sums #/ sy += (xtn) + y(n)) 5 sy te yln) ; net; y delta = stsx2 - sx*sx ms (stexy - sxtsy)/delta ; /* Calculate m and c #/ c= (sx2¥sy - sxesxy)/delta ; printf ("\nDataypointsuuuu(m)u:u%12d\n", m) ; printf ("Least -squaresyliney:uh12.6fusuxutul-12-6f\n\n", m, c) ; return (0) ‘To execute the program, ‘To compile the program, $ gcc -o linreg linreg.c -1n ‘To use the program, first create a file test .dat with the data points given on the right side. The first column contains the z values and the ‘second column has the corresponding y values. The above data points can be replaced by those for which you have to fit the line. ‘The program run looks like this: $ -/linreg < test.dat Nooeune yoeweny ebeggor Data points (n): z, Eee ote Least-squares line : 0.830715 + x + 0.992855 ee Using gnuplot, plot of the data points with the least-squares line: $ gouplot gnuplot> set xlabel "x" ig guplot> set ylabel “y" ak gmplow plot "test.dat" wp ti "Data", 0.690715 + x + 0.992855 «

You might also like