Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
9K views
357 pages
Let Us C Book
Uploaded by
Hydra
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save let us c book For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
9K views
357 pages
Let Us C Book
Uploaded by
Hydra
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save let us c book For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save let us c book For Later
You are on page 1
/ 357
Search
Fullscreen
Ve TLC ie AUTHENTIC Guide To ETE a LN (eyLotus Seventeenth Editon Yashavant Kanetkar ob SEVENTEENTH REVISED AND UPDATED EDITION 2020 FIRST ETON 2007 Reprinted 2019 Copynight ® BPB Publications, nda © Let Us Cis a registered trademark of 8PB Publicatons, New Oath, under Registration No: 1135514 ISBN 978-09-69045-606 ‘AI Rights Reserved. No part ofthis publication may be reproduced or distributed in any form or by ary means or storad in a database or etioval system, without the prior witton permission ofthe publisher. LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY ‘The Author and Publisher ofthis book have tried their best o ensure thatthe programmes, procedures and functions described in the book arc correct. However, the author and the publishers make no warranty, of any kind, exrassed or imple, with regard to these programmes or the documentation contained in the book. The author and publisher shal not be liable in any event of any damages, incidental or consequential, in connection wit, or arising out ofthe furnishing, performance or use ofthese programmes, procedures and functions. Produce narne rentoned {are used for ientication purposes only and may be trademarks oftheir respective companies. Al traemarks referred to in the book are acknowedged as properties of their respective owners. Distbutors [BPE PUBLICATIONS. 20, Ansari Road, Darya Gan) ‘New Dath-s 10002 : 23254990/23254091 MRO MEDIA ‘Shop No. §, Mahendra Chambers, 150 DN Ro. Nest to Capital Crems, V.T. (CS, Station, MUMBAL-400 091 Ph: 22078296/22078297 DECCAN AGENCIES 43-329, Bank Street, Hyderabac-s00195 Ph: 24756967/24756400 BPE BOOK CENTRE 376 Old Lajpat Fai Marko,Det 10006 Pr 29881747 Published by Manish Jain for BPS Publications, 20Ansari Road, Darya Ganj, New Del-110002 and Printed at Repro inda Ld, Mumba Dedicated to baba Who coukint be hereto see tis day. ‘About the Author ‘Through his books and online Quest Video Courses on C, C++, Data Structures, VC++, NET, Embedded Systems, etc, Yashavant Kanetkar has created, moulded and groomed lacs of IT careers inthe last two and half decades. Yashavants books and online courses have made a significant contbution in creating top-notch IT manpower in Inia and ebroed ‘Yashavant's books are globally recognized ane millions of students / professionals have benefited from them. Hs books have beoa translated into Hindi, Gujarat, Japanese, Korean and Chinese languages. Many of his books are published in India, USA, Japan, Singapore, Korea and China ‘Yashavantis @ much sought after speaker in the IT flld and has conducted seminarstworkshops at TedEX ITs, NTs, IITs and global sofware companies. ‘Yashavant has been honored vith the prestigious “Distinguished Alumnus Award” by IT Kanpur for his entrepreneurial, professional and academic ‘excollenos, This avard was given to top 50 alurmi of IT Kanpur who have made signieant contribution towsrds ther profession and betterment of soctty in the last 50 yoars. ln recognition of his immense contibution to IT education in india, he has been awarded the “Best NET Technical Contributor" and "Most Valuablo Professiona” awards by Microsof for 5 successive years, Yashavant holds a BE from VJTI Mural and M.Tech, ftom IT Kanpur. Hs current afllation include being a Director of KICTT Pvt Lid. He can be reached at
[email protected]
or through itpiwaukic.eom, Acknowledgments Let Us Chas become an important pat of my ie. [have created and nurtured it for last two decades. While doing $0, Ihave recalved, ln adkstion to the compliments, a lot of suggestions from students, developers, professors, publishers and authors. So much have ther inputs helped me in taking tis book upto its seventeenth edition that ideally should put their names too on the cover page, In particular, lam indebted to Manish Jsin who had @ faith i his book idea, beleved in my wring ability, whispered the wards of encouragement {and made helpful suggestions from time to tme. | hope every author gets @ publisher whois as cooperetive, knowledgeable and supportive as Manish ‘The previous editions ofthis book saw several changes and faclfts. During this course many people helped in executing programs and spating bugs. trust that wth thei collective acumen, all the programs inthis book would run correctly, value the wark that they did @ lot: Any erors, omissions or inconsistencies that romain are, alas, my responsibly [thank all my farnly members for enduring the late nights, the cicking keyboard, and mostly fr puting up with a marathon book effort ‘Thinking of book cover idea is one thing, puting t into action isa diferent cup of tea. This editions cover idea has been implemented by Vinay Indore. Many thanks to him ‘And finaly my heartfelt gratude to the countless students Who made me look into every nook and eranny of C. want Yo remain in thelr dob. ts only because of them that Let Us Cis now pubshed from india, Singapore, USA, Japan, Dubs, Korea and China in multiple languages. Preface Lot Us C has boon part of learning and teaching material in most Enginearing and Science nstutes round the country for years now. From last year oF so, |recolved soveral suggestions tna is size be pruned a bi, as many learnors wno learn C language in thelr Engineering or Scionce curriculum have some famiarity with t. 1am happy to fulfil this request. hope the readers would appreciate the lean look of the current edtion. In one of the previous edition | had realigned the chapters in such @ manner that if C programing course s taught using Let Us C,itcan be finished in 22 lectures of one nour each, wth ona chapter's contents devoted to one lecture. |am happy that many readers tke this ia and reported that this has made their learning path trouble-free. Amore rational reorganization of end-of chapter Exercises inthe book has also been \wel-received. Ring on that feecback had introduced one more feature in the fiteenth ection—KanNotes, These are hand-crafted nctes on Cprogramming. From the reader's emalis | gather that they have turned out to be very useful to help revise the condepts on the day before the ‘examination, vve-voCe or interview. "Many readers also told me that they have inmensely benefited from the inclusion ofthe chapter on interview FAQs. |have improved tis chapter further. The rationale behing tis chaptr is smplo—uitimataly al te readers of Let Us C sooner or later end up in an interviw room where thoy are require to take questions on C programing. |nowhave a proof that this chapter has helped to make that journey smooth and fut In this ection Ihave added 2 separate section titled ‘Programs’ in each chapter. & contain interesting programs based onthe topios covered in the chaptar. Al the programs present inthe book are avallabie in source code form at wwur Kl comPbaokstetusclsourcecoda. You ara tree to unload them, improve them, change them, do whatever vth them. yOu wish to get solutions forthe Exercises inthe Book they are available in another book tiled Let Us C Solutions’. you want some more problems fo practice they are available Inthe book tiled ‘Exploring C’. As usual, neweditions ofthese twa books have also bean launched along vith 17th edition of Lat Us C IF you lke ‘Let Us Cand want to hear the complete video-recordd lectures crated by me on C language (and other subjects like C++, VC++, CH, ava, .NET, Embedded Systoms, et.) then you can vist hitp://quest ksoindia.com fr more dotals. ‘Let Us C's as much your book as it is mine. So f you Teal that | could have done certain job beter than unat | have, or you have any suggestions about what you would ke fo sea in the next ection, please drop a line to
[email protected]
or
[email protected]
Countless Indians have relentlessly worked for cose to three decades to successfully establish “ndia’ as a sofware brand. Attines, | take secret pleasure in seeing that Let Us C has contributed in ts oun smal tte way in shaping so many careers that nave made the “Inca” brand ‘acceptable. Recenty was presented wth “Distinguished Alumnus ANerd” by IT Kanpur. twas great to Agure in lst that contained Narayan Murthy, Chief Mentor, infosys, Dr. D. Subbarao, former Govemor, Reserve Bank of indo, Dr. Rajeev Motwani of Stanford University, Prof H.C. Verma, Mr. Som ital President of NASSCOM, Prof, Mnwalla of Harvard University, Dr. Sanjay Dhande formar Diractr of IIT Kanpur, Prof. Arvind and Prof. Sur of MIT USA and Prof. Ashok Jhunjhunwala of IT Chena | think Let Us C amongst my othr books has been primanlyresponsibe fr helping mo got the “Distinguished Alumnus” award. What was a bit surprising was that almost all who were present knew about the book altady and vented to know from me uhat takes to write @ book that sels in rilions of copies. My reply was—make an honest effort to make the reader understand what you have to say and keep kt simple. I don't knowhow convincing was this ansver, but wal, that ls what Ihave been doing wh this book in alts previous si¢een editions. Ihave folowed the sama Principle wth tis edition to. Alte best and happy programming! YYashavant Kanetkar Table of Contents 1. Gating Started What is C7 Gating Started wath © ‘Alphabets, Digits and Special Symbols Constants, Variables and Keywords Types of Constants Rules for Constructing nteger Constants FRulas for Constructing Real Constants Rul for Constructing Character Constants Types of C Variables Rules for Constructing Variable Names Keywords ‘The First € ProgramFormat © Program Commants a © Program Whats main()? Variables and their Usage Print) and its Purpose Complation and Execution Receiving Input Programs Boorcisos Kandotes 41. C instructions “Types of structions Type Declaration instruction setmeveinseucton Integer and Float Conversions “Type Conversion in Assignments Hierarchy of Operations Assocatvty of Operators Conte structions Programs Barcines KanNotos 1. Decision Control struction The t= ese Statement utile Statements within it else Nested holo 8 A.Wlrd of Caution Programs Brercises Kantotos 1. More Complox Decision Making Use of Logical Operators - Checking Ranges “The oie if Cause Use of Logical Operators - Yes / No ProblemTho | Operator Hararcny of Operators Rovisted ‘The Conditonal Operators Programs Beercises KanNotes 4 Loop Contr instruction Loops ‘The while Loop ‘Tips and Traps More Operators Programs, Berclses KanNotes 1. More Complex Repations The for Loop Nesting of Loops: "Mutipl initalzations inthe for Loop ‘The break Statement ‘The continue Statement “The do-while Loop ‘The Odd Loop Programs, Brerclses Kantotes 4. Case Canto Instruction Decisions using such “The Tips and Traps ‘wich versus i-elso Ladder The goto Keyword Programs Exercises Kaniotes 1. Functions What is a Function?Why use Functions? Passing Values between Functions Order of Passing Arguments Using Library Functions One Dioey sue Return Type of Function Programs Bercises KaniNotes 1. Pointors Call by Value and Call by Reference fn introduction to Pointers Back to Function Calis Conctsions Programs Bercises Kantotes 1. Recursion Recursion Programs Brorcises Kantotes 1. Data Types Rovistod Integers— long, shor, signed , unsigned CChars~ signed, unsigned Reals—foat double ong double AFow More ives... Storage Classes in © Automate Storage Cass Regist Storage Clase Static Storage Class External Storage Class A Few Subtessues Which to Use WhenBerciees Kantotes 1. The € Preprocessor Features of © Preprocessor Macro Expansion Macros wth Arguments ‘Macros versus Functions Filo netusion Coneitional Compilation and #elif Directives Miscltaneaus Directives undef Directive pragma Directive ‘The Bue Proce! Programs Bercises KanNotes 1. Arrays What are Arrays? ‘ASimple Program using Array More on Arrays pray Iitazation ‘Array Elements in Memory ‘Bounds Checking Passing Wray Blmonts to a Function Points and Arrays Accessing Atay Elements using Pointers Passing an Array 0 a Function Flexible Arays Programs Boorcises antotes 1. Muticimansional rays‘Two-Dimenslonal Arays Inaizng a 2-D Array Memory Map of @2-D Array Pointers and 2-D arrays Pointer to an Array Passing 2-0 Array to a Function ‘tay of Pointers SD Array Programs Exercises KanNotes 4. Strings What are Sings More about Stings Pointers and Strings Standard Library Sting Functions stren() swrepy() strcat) stremp() Programs Beercises Kantotes 1. Handling Muttile Strings 2D Array of Charactors ‘tay of Pointers to Strings Limitation of Array of Pointers to Strings Programs Beercises KanNotes 4. Structures Why use Structures? Atay of Structures Intreacies of StructuresSuture Decaration Storage of Structure Elements Copying of Structure Elements Nested Structures Passing Sricte Elements /Snicture Variables Packing Structure Elements Uses of Structures Programs Borcises Kannotos 1. Console nputioutput Types of 10 Console 10 Functions Formattes Console V0 Funetions sprint) and sscanf) Functions Untormatted Console 10 Functions Brisas Kantotos 1. Fe input Output File Operations pening a Fe Reading froma File Closing the Fite Counting Characters, Tabs, Spaces, AAFile-Copy Program Flo Oponing Modes Sting (Line) VO in Fes ‘ext Fes and Binary Files Record 0 in Flos Modifying Records LowLevel Fe ¥0 ALouLovelFile-Copy Prosram Programs Barcines kanNotes1. More Issues In InputiOutput Using argeand argv Detecting Errors in Reacingting Standard Fle Pointers WO Redirection Redirecting the Output Redirecting the Input Both Ways at Once Exercises Kantiotes 1. Operations On Bis it Numbering and Conversion Bit Operations (One's Complement Operator Fight Shift and Lett Shift Operators AWexd of Caution Unity of << Operator Btwse AND, OR and XOR Operators Uty of & Operator Utlty of | Operator Unity of Operator ‘The showts() Function ‘wise Compound Assignment Operators Programs Eeercises KanNotes 1. Mscallaneous Features Enumorated Data Type Uses of Enumerated Data Type ‘Ae Enums Neooseary? Renaming Data Types with typed Typecasting Bit Fields Pointers to FunctionsFunctions Retuming Pointers Functions with Variable Number of Arguments Unions Unity of Unions “The votatio Qualifier Programs Bercises Kannotes 1. Interview FAQs Appond A= Compilation and Execution Aependie®- Precedence Table AependixG - Chasing the Bugs AppendixD - ASCII Chart Periodic Tests Ito IV, Course Tests I! Getting Started ‘You cannot be great atthe start, but you have to start to.be great. So making @ beginning is important. This chapter will help you wat you feet, before beginning a more arduous C journey. CO Sonn nt RRulos for Constructing Character ConstantsTypes of C Variables FRulas for Constructing Variable Names CkKeywords The First C Program Formof a C Program (Comments in a € Program What is mand)? Variables and their Usage print) and its Purpase Compiiaton and Execution Receiving Input Programs Exercises KanNotes Before we can begin to write serious programs in C, i would be interesting to find out what really is C, how t came into existence and how does it ‘compare win other programming languages. inthis chapter. we wauld brely utine these Issues. Four imporlant aspects of any language are—te vay i stores data, the way t operates upon his data, how’ accomplishes input and output, ang hhowit lets you control tne sequence of execution of instructions in program. We would dscuss the frst tee ofthese buiiding blocks inthis chapter. wnat is C2 Cis 2 programming language developed at AT & T's Ball Laboratories of USA in 1972 by Dennis Ritchie, C became popular because itis simple ‘and easy to use. An opinion thats often heard today is—"C has been already superseded by languages Fke C++, C# and Java, so why bother to learn C today’. 'sorously beg to differ wth tis opinion. Thera are several reasons fortis. These areas folows: (@) C++, CH or Java make use of a principle called Object Orinted Programming (OOP) to organize programs which offers many advantages, \While using this organizing principle, you need basic programing skis, So a makes more sense to fst learn C and then migrate to C++, Ci or ava. Though this two-stp learning process may take more time, but atthe end oft, you wil definitly fing t worth the trouble (©) Major parts of popular operating systems tke Windows, UNX,Linuxand Android are writin in C. Moreover, fone isto extend the operating system to vork wih new devioes, one needs to wite device driver programs. These programs are writen exclusively in (6) Common consumer dovices Ike microwave ovens, washing machines and deta cameras are getting smarter by tho day. This smartness comes froma microprocessor, an oparating systom and a program embedded in these devices. These programs have to run fast and workin limited amount of memory. C's the language of choice wile building such operating systems and prograrrs. (4) You must have soen several professional 3D computor games where the user navigates some object, Ike say a spaceship and fras bullets at Invaders, The essence of all such games is speed. Ta match thi expectation of speed, the Gama has fo react fast te the user inputs. The popular gaming frameworks (Ike DirectX that are used for creating such games are writton in C. | hope that these are very convincing reasons why you should adopt C 2s the first step in your quest for learning programming Gotting Started with “There is close analogy between learning English language and learning C language. This is itustratad inthe Figure 1.1Figure 1.1 Aiphabets, Digits and Special Symbols Figure 1.2 shows the valid alphabets, numbors and spacial symbols alowed in C. pl Figure 1.2 Constants, Varablos and Keywords ‘The alphabets, digts ane special symbols when properly combined arm constants, variables and keywords. A constant isan entity that doesn't change, whereas, a variable is an entity that may change. A keyword is @ word that carries special meaning. in programming languages, constants are often called Iterals, whereas variables are called identifiers. Let us now see what diferent types of constants and variables exstin C Types of C Constants Constants nC can be divided into two major catogaries: @ Primary Constants, (6) Secondary Constants ‘These constants are futher categorized as shoum in Figure 1.3, a Figure 1.3, [Athi stage, we would restit our discussion to only Primary constants, namely, Integer, Real and Character constants, Following Rules have eon aid down for constructing these diferent types of constants: Ful for Constructing nteger Constants(@) An etagor constant must have at last ane ag (b) Rust not havea docimal pln. (6) >t can be any of ro, postive or negative. no sign precedes an integer constant itis assumed tobe positive (@) No commas or blanks aro atowod within an intgar constant (6) The alowable range for integer constants is 2147483648 1 +2147483647 Be: 182594 4260 32.76 48.5702 Truly speaking, the range ofan integer constant depends upon the comple. For compilers tke Visual Studi, GCG, tis -2147483648 to 42147483647, whereas for compilers tke Turbo C or Turbo C+, the range is 2768 ta #32767 Rules for Constructing Real Constants Real constants are often called Floating Point constants. Resl constants coulé be wen in two forms-—Fractional form and Exponential form. Following ules must be observed while constructing real constants expressad in fractional form: (@) A real constant must have atleast one dig. (0) must have a decsval point (c) Ran be either postive or negative, Defaut sign is postive (@) No commas or blanks are alloved vthn a real constant. Ex: +92534 428.0 92,76 48.5792 ‘The exponential form usually used f the value ofthe constant is ether too small orto lage. hover, doesnt restrict us in any way fom using exponential form fr ther real constants In exponential form, the real constants represented in two parts. The part appearing before eis called mantissa, wnereas the part following eis callad exponent. Thus 0.000342 can be writen in exponential formas 3420-4 (which in normal arthmetie means 3.42 x 10-4). Following rules must be observed white constructing real constants expressod in exponantial form: (a) The mantissa part and the exponential part should be separated by a letter e oF E. (6) The mantissa part may have a postive or negative sign. Default sign is postive (6) The exponent must have at east one digt, which may be @ postive or negative integer. Defauk sign s postive. (4) Range of real constants expressed in exponential frm is-3.4038 to 3.4628. Be:t8205 4408 0.263 3205 Rules for Constructing Character Constants (@)A character constant a single aphabet. a single agit ora single special symbol enclosed within single inverted commas, (©) Both the inverted commas should point tothe let For example, 'A's a valid character constant, whereas Ais not Bux tos 2 Types of C Variables ‘Apantoular type of variable can hold any the same type of constant. For example, an intager variable can hold only an integer constant. areal verable can hold only areal constant and a character variable can hold only a character constant, Hence there are as many types of variables in a8 the types of constants init In any C program many calculations are done. The results of these ealeulatons are stored in some cits (locations) of computers memary. To ‘make the retrieval and usage ofthese values easy, the memory cells are given nares. Since the value stored in each acation may change, the names given to these locatons are called variable names,The rules for constuting diffrent types of constants are diferent. Howover, for constructing variable names of all ypes, the same set of rules ‘apples. These rules are given below. Rules for Constructing Variable Names (@) A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some compilers alow variable names whose length could be Up to 247 characters. Do not create unnecessary long variable names as it adds to your typing effort. () The frst character inthe variable name must be an alphabet or underscore (_), x: sit pope89 avg basicsalary Wie should eivays create meaningful viable names, For example, while calculating simple interest, we should construct variable names like prin roi, noy to represent Princip, Rate of itorest and Number of years, rath than arbitrary variables ike a,b, €. Rules for creating variable rams remain same for allthe types of primary and secondary variables. So to help ciferentiats between variables, is compulsory to declare the type of any variable that we wish to se ina program. This type declaration is done 2s shoun below. Bes int si, me: foat bass char code: C keywords Keywords are the words whose meaning has ateady been explained to the C compiler (rin broad sense tothe computer). There are only $2 keywords availabe in C. Figure 1.4 gives a ist of these keywords, Figure 1.4 ‘The keywords should not be used as vanable names. However, some C compilers alow you to constrict variable names that exacty resemble the keywords. Compiler vendors provide more keywords apart rom the ones given in Figure 1.5. Though ithas been suggested by the ANSI committee that every such compller-spectic keyword should be preceded by two underscores (as in_ asm), not every vendor follows tis rule ‘The First © Program (Once armod wih the knowledge of variables, constants and keywords, the nex logical step isto combine them te form instructions. However, instead of this, ve wauld wite our frst C program naw. Onoe we have done that we would see in detail the instructions that it made use of The fist programis very simple. lt calculates simple interest fora sot of values representing principal, numberof years and rate of interest. /* Caleuation of simple interest“! 1" author: gekay Date: 25/03/2020") include int maint) cint psi float r,s; I" forma for simple interest si=ptn*r/100; print fn, si return 0; > Lotus now understand this program in deta Format a © Program Form of @ program indicates howit has tobe uriten, There are certain rules about the form of a © pragramthat are applicable to all G programs. These are as under: (@) Each nsucton in aC program writen a8 a separate statement (0) The statements ina program must appear in he same order in which we wish them to be execute. (©) Blank spaces may be inserted botueen to words to improve the readily ofthe statorent (@) At statements shouldbe in ower cae eters (©) Every C statement mist end wth a semicolon (:). Thus; cts as @ statement terminator (0 AC statomnt can bo writen anyuoro ina given Ino. That's why ts oft callod a reeorm language. (g) Usual each ine contains one statement, However, you can wite muliple statements in one ine, provided each slatement is termenaed wth 2 Comments na C Program Comments are used ina C program to dary ether the purpose of the program or the purpose of some statement inthe program. kis a good practice fo begin a program win a comment indicating the purpose ofthe program is author and the Gate on Which the program was ween. Hare are a few tps for wring comments in aC program: (2) Comments can be in small case, capital ora combination. They should be enclosed wihin/"/. Thus, the fist wo statements in our program are comments. (©) Sometimes tis not very obvious as to what a particular statement ina program accomplishes, At such times, a comment can be used to mention the purpose ofthe slatement(s). For example, /* formuia for simple interest") si=ptn*r/100: (6) Any numberof comments can be written st eny place in the program. So a comment can be written before the statement, after the statement or “wthin the statement ae shown Below. forma si pn r/ 100; si=ptntr/100; formula! si=ptntr ("forma “100: (@) Comments cannot be nested. This means one comment cannot be writen inside another comment So folowing comment i invalid*Calof S1/* Author: gokay date: 2803/2020 ** (€) Acommont can be split over more than one line, asin, /PThis comment has three tines int (0 ANSIC permits commonts to be weiten in anothor way as flows: 1" Calculation of simple interest 11 Forma What is main)? ‘main() forms a crucial part of any C program Lat us understand is purpose 2s well as its intricacies. (2) main) is 2 function. isa container for a set of statements. AC program may have muitiple functions. iit contains only one function its name has to be main() Al statements tat belong to main) are enclosed within a pair of braces 0. (©) Like functions in a caleuator. function inC alsa retum a value. main) functon aways returns an integer value, hence there isan int before ‘main(). tis known as retum typeof the function. The integer value tat we are returning is 0. 0 indicates success. statements in ain alto do their intended work, we can return a non-2er6 number from main(). This would indicate failure (6) To way to watch tna value returned by main) varies from one compiler fo another, as shown below Turbo ¢, Turbo Gr+- AIC | Information Visual Studio - $ReturnValue in Watch Window of Dabugger Linux echo $7 at command prompt after execution ofthe program (@) Some compilers ike Turbo CiG+* even permit us to retum nothing from main). In such a case we should precede it wih the keyward vod. But this is the non-standard way of wring tne main() function. Wa would discuss functions and their waking in detain Chapter 8 Variables and their Usage Let us understand the signiicance of constants and variables with reference to our program. (@) Any verable used in ne program must be declared before its used. For example, Int p,m: dactaration */ float, sh * decaration “7 si=ptntr/100; "usage"! (©) nme statement, si=ptn*r/100; and “+ and are the arithmetic operators. The arithmetic operators avaliable in Care + print) and its Purpose does not contain any keyword to display output on the screen. All output to screen is achieved using readymade Bbrary functions lke pint) Let us understand this function wih respect to our program. (2) Once the value of sis csleulated it neds to be displayed on the screen. We have used printf) 10 do 50. (0) To be abio to use the print) function, tis necessary to use sinclude atthe beginning of the program. include i @ preprocessor dactve. is purpose wil be cared in Chaptor 8 () The general form of pent) function is,paint" can contain, Wf for printing real values *% for printing integer values ‘4a for printing character valves ln adation to format specitirs tke %e,%d and tc the format string may also contain any other characters. These characters are printed as they fare uber prin) is executed, (d) Given below are some more examples of usage of print function: Print (947 int (96d el SEF 96", Bn. ih Print (‘Simpl intrest = Rs. A) Print (‘Principal = %sdinRate = %t" , “The output ofthe last statement would look ike tis, Principal = 1000 Rate = 6.500000 ‘The outputs spit over twa ines because of newtine character ‘ni sends the cursor to nex line. Kis one ofthe several Escape Sequences avaiiaba in C. These are discussed in detain Chapter 18 (e) print) can print values of variables a8 ve as raul ofan exprassions ike 3.3 +2, ¢and a +b ed as shown below rin id Yd Sa Ma, 3,3 *2, a+b “ea Note that 3 and caso represent valid expressions Compiton and Execution ‘Once you have weten the program, you need to type It and instruct the machine to exBeuta I. Two ather programs are needed to do this— Ealtor {and Compiler. Edior lets us type our program, whereas Compiler converts our program into machine language program. This conversion is necessary, since machine understands only machine language. ‘Apart trom these tvo, there are other programs which you may need to Improve your programming effetancy— Preprocessor, Linkar and Debugger. Working wlth each one of them individually i a tedious job. Hance, often all these are bundled together with a layer of GUt on top of them. GUI makes using these programs easier for you. This bundle s often called integrated Development Environment (DE), ‘There are many IDES available. Each is argoted towards diferent operating systems and microprocessors. Detalls of which IDE to usa, from where to dovnioad it, howto install and use tare given in Append A. Please go through this appendixand install tha right IDE on your machine betore you try any program in this book Receiving Input ln our fist program we assumed the values of pn and rto be 1000, 3 and 6.5, Everytime we run the program, we Would get the same value for simple intrest. F we want to calculate simple itorest for some other set of values then we are required to incorporate these values in the program, ‘and again compile and execute it, This means that our program's not general enough to calculate simple interest for any set of valves thout being required to make changes in he program. This is nota good practice. “Tomake the program general, the program isl should ask the user to supply the values ofp. n and r through the keyboard during execution, This can be achieved using a function called scan). helps us receive input values them from the keyboard. This f lustreted inthe program given below, PP Cateuaton of simple intarast*!/* Author gokay Dato 25/08/2020) include int main() cl int p.m: float print ("Enter values ofp scant (%d Sd %P, Bp, 8, Br) sieptntr/100; Print ("4 i: return 0: > “The First print) outputs the message ‘Enter values of pn, ron the screen. Here we have not used any expression in print!) which means that Using expressions in print) is optional Nota the use of ampersand ( & ) before the variables inthe scan) function is necessary. &s he ‘Adarass of operator. gives the locaton number (address) used by the variable in memory. When we say a, we are tling scan‘) at which memery locaton should it store the value ‘supped by the user from the keyboard. The dotalled werking ofthe & operator would bo taken up in Chaptor 9 Note that a blank, a tab ora new ne must separate tha values supplied to scan). A blank is created using a spacebar, tab using the Tab key land new ine using the Enter key. This is shown below. Be: Three values separated by blenk: 10005 155 x: Three values separated by tab 1000 5 155 Bc: Three values separa by newline: 1000 5 185 P Output Entor Basic Salary of Ramosh: 1200, Basic Salary of Ramesh = 1200,000000 Dearness Alavance 0.000000 House Rent Alonance = 240,000000 Gross Pay of Ramesh is 1920,000000 Problem 1.2 “Tho distance between to cites (in km) Is Input through the keyboard. Write a program to convert and print this distance in mators, fet, inches and centimeters. Program Conversion of cistance* include int main() c float km, rm, finch, Print ("nEnter the distance in Kilometers scant (6, 8k): m= tan" 1000; em=m* 100; inch = em/2.54; R= inch 112;printf (‘Distance in motors = Sei", m); Print (‘Distance in eantimete wt, em prinf ‘Distance in foot = en, 8); prin Distance in inches = St’ inch) return: , Output Enter the distance in Kiomaters: 3 Distance in eantmeter = 300000.000 Distance in feat = 9842.510591 Distance in inches = 118110.206975 Problem 1.3 IF the marks obtained by a studentin five diferent subjects are input through the keyboard, vite @ program to find out the aggregate marks and percentage marks obtained by the student, Assume thatthe maximum marks that can be obtained by a student in each subjects 100. Program '* Calculation of aggrogate & porcontage marks“) include int main() cl int, m2, m8, m4, m6, agar: fat per printf (\nEnter marks in 5 subjects: "y scant (ed Sh ed Yh a", Bent, m2, A, Am, Br) faggr = mt + oid +3 + mt # m5 a 199" 5: print ("Aggregate Marks = édin’, agg): print (‘Percentage Marks = %fr", per}: return 0; , Output Enter marks in § subjects: 85 75 60 7258 Aggregate Marks = 348 Percentage Marks = 69.000000exam [A] Which of the folowing are invalié C constants and why? [B] Which of he folowing are invaié variable names anc why? [| State whether the following statoments are True or False (a) C language was developed by Dennis Ritchie. (©) Operating systems ike Windows, UNX, Linux and Android are uriten in C. (©) C language programs can easily interact wih hardware of @ PC / Leptop. (4) Areal constant in C can be expressed in both Fractional and Exponential forms, (@)A character vanable can at atime store only one character. (The maxamum value that an integor constant can have Varies trom one compiler to another (6) Usuaty a C statements are vatton in small caso laters. (f) Spaces may be inserted between two words in a C statement (0 Spaces cannot be present within a variable name. (01C programs are converted into machine language wth the help of a program called Editor. (() Most development environments provide an Editor to type aC program and a Compiler to convert it into machine language. (Diet char, oat, real, integer, character, char, main, printf and scan all are keywords. [D] Maten the folowing pais: [E]Point out the eros, ifany, inthe folowing programs: (@) int main() c int 2: float b: int: a=25;b=3.24;e=a+b*b- 35; > (&) #incude int main() c Int = 35; float = 3.24; print (a Sa, a, D+ 1.5, 238); ) (6) finctude int main() c inta,b,¢; scant (a Ma Ma", a,c)y (@)Fincude Int main(y cl Int rn, 2, Print (‘Enter values of marks in 3 subjects") scant (%d Sd Mc, Amt, Bir2, &m3) print ("You entered dl %ed Ye", mt, m2, m8) > IF] Atom the folowing questions: (@) Temperature ofa city in Fahrenheit degrees is input through the keyboard. Write @ program to convert this temperature into Centigrade degrees. (©) The longth and breadth ofa rectangle and radius of acco are input through the keyboard. Write a program to calculate the area and perimeter ofthe rectangle, an the area and eieunference ofthe ecto (6) Paper of size AO has dimensions 1189 mmx 841 mm. Each subsequent size A) is defned as A(n-1) cut in half paralel tots shorter sides. Thus paper of sizo A1 would have dimensions 841 mm xS84 mm. Writa a program to calculate and print paper sis AD, At, A2,.. AB, know + en rr ing Gv er iter + thins sin, in tm a tn + ented toe progemaetien nC Ca aoBe ame Sven vated ured iT Rbmmyf eandey Stocin Pinay 1 oge2) Rel et 3) rar ave sina: jie dae nance om nacre a iin 1) oxy homies change 2)tlanao phon abztenin mane sei ae aga ac Total keywords = 32. Example char, int, oat oe.Print) is @ function tat can print multiple constants and variables Format spectrin print), scant): int-% oat - i, char-%e main) i function that must ainays return an integer value 0-ifitmoets success, 1 ft encounters faire Use "7 OF for @ comment ina program is address of operator and must be used before a variable in scant) C Instructions Rua aera Captain of a Cricket team is as good as his team, ithe team s not ood enough, captain alone cannot do much. Same isthe case with C programming. Unless you knowthe instructions that offers, you can hardly write a good program. This chapter discusses these instructions COeam Types of Instructions “Type Declaration struction ‘thetic Instruction Integer and Float Conversions Type Conversion in Assignment Herarchy of Operations Assodiatity of Operators Control instructions Programs Brercises Kantotes ‘Agrogram is nothing but a set of instructions, Different instructions help us achieve diferent tasks in a program. Inthe last chapter we saw howto ite simple C programs by using different instructions. n this chapter we would expore the instructions thal we used in these programs Types of structions “There are three types of instructions in C: (@) Type Declaration instruction - Ths instruction is used to declare the type of variables used in a C program. (©) Arthmetc instruction - This instruction is used to pertorm arithmetic operations on constants and variables,(6) Control instruction - This instruction is used to control the sequence of execution of various statements in 8 C program. Let us now take a closer look at these instructions, Type Declaration instruction “This instruction is used to declare the type of variables being used in the program. The type dectaration statement is writin atthe beginning of ‘main( function, & few examples are shown below, int bas: fat s, rosssal char name, code Hore area few subta variations of he type deciaratin instruction. () While declaring the type af variable, we can also inline i as shown below. inti = 10, j=25; fost a= 1.5,b=1.99+2.4°1.44 (©) variablo must stand defined before using i. Tho folowing statamont i legal since we aro using variable a before dofning i floatb=a+3.4,a=1.5; (6) The folowing statemants would work inta, be, a=b=c=10 However, he folowing statement would not work intasbaced=10; (Once again we are trying to use b (to assign toa) before detning Arithmetic Instruction ‘An anthmatic instruction in C consists of a variable nam on the lft hand side of on the nght hand side of = variable names and constants connected using aperators Bx: int at Moat kot, deta, alpha, bota, eamena: ad 200; kot 0056; deta = alpha * beta / gamma * 32°25; Hore, + oe the arithmetic operators = the assignment operator. 2,5 and 3200 ere integer constants $3.2 and 0.0056 are real constants. ad's an integer variable kot, deta, alpha, beta, gamma are real variables,Tho variables and constants together are callod ‘operands. While executing an arhmetc statement, the operands on right hand sido are ‘operated upon bythe ‘arithmetic operators’ and the result is assigned, using the assignment operator, tothe variable on left-hand side, ‘An anthmetc statement in G could be of three types. These ere as follows (@) Integer mode arthmetic statement - inthis statement, all operands are either integer variables or integer constants. Ex: inti, king, sae, note + king #issac’ 294 + note - 7689; (0) Real made arthmstic statement - nts statement, all operands are either real constants o real variables. x: flat bee, antink si prin, onoy. ri abe = antink + 25.128/45 “0.3482; Si= prin “any “rol / 100.0 (6) Mxed mode arithmetic statement - in ths statomont, some operands are intagers and some operands are rea floats, prin, ney oi, avg intab, enum i= prin “any “roi! 100.0; avg=(a+b enum) /4; Not the folowing points about Arithmetic instructions carofull: (@) Callous only ane variable on lef-hane side of. That is, 2=K*1i6 legal, whereas k*|= 218 Megat (©) In adstion to the division operator, C also provides @ modular division operator. This operator retums the reminder on ching one integer with another. Thus the expression 10 /2 yields 5, whereas, 10 % 2 yields 0. "Note thatthe modulus operator ( ‘%) cannot be applied on afloat Aso note that on using %, sign of the remainder is always same asthe sign of the numerator. Tus-5 %2 yields -1, whereas, 5 %-2 yelds 1 (c) Arithmetic operations can be performed on ints, float sand chars. Thus the fllowing statements are vat chars ol y=) intz=xy, ASCII codes aro used to represent any charactor in momory. ASC codes of'a'and'b' are 01100001 and 01100010. Thoir decimal equivalents {are 97 and 98, The addition is performed on these decimal values and not on characters themselves. (4) No operators assumed tobe present. t must be writen explicit. nthe folowing example, the multiplication operator after b must be explcity wit, a= cd.boy) usual athnetestatomont a=c7d*b* (x*y) C statement (©) There is no operator nC to perform exponentiton operatan. Exponentiton has tobe carried ou as shown below. fost a: a= pow (20, 20} print 36. Hore pow) function is a standard library function. Ns being used ta raise 3.0 to the powr of 2.0. The pon) function works only wih real numbers, hence we have used 3.0 and 2.0.Ne that fr pout) to work iis necessary to include. include is @ preprocessor directive, We would learn more about standard library unctons in Chapter 8 and about preprocessor in Chapter 12 . You can explore other mathematical functions lke abs), sqrt), sin(), cost), tan(),et., declare in math.h on your own, Integer and Float Conversions To effectively develop C programs, tis necessary to understand the rules used for imglet conversion of leating point and intoger values, These fare mentioned below. Note them careful. (@) An arithmetic operation between an integer nd integer akuays yield an integer result (0) An operation between a real and real aluays yields a real result (c) An operation between an integer and ral aay’ yields areal result. in this operation, the Integer is fst promoted toa ral and then the ‘operation is performed. Hence the result is real | think afew practical examples shown in Figure 2.1 would put the issue beyond doubt Figure 2.1 Type Conversion in Assignments Ifthe type of the expression on RHS and LHS of = are not same then the value of the expression on RHS is promoted or demoted depending on tha type of ine vane on leftnand side of =. For exampia, consider the folowing assignment statements: inti fost»; leas b=30; Here inthe first assignment statement, though 3.5 is@ float, it cannot be stored in since tis an int Hence 3.5 (float) is demnted to 3 (nt) and than stored in|. Opposite happens inthe nex statement. Hors, 30 is prompted to 30.0 and then stored in b , since b being a flea varable cannot hold anything except a float value Instead of a simple expression used inthe above examples, ia complex expression occur, stil tho same rules apply. For example, consider the following program fragment fost a,b,c: int seatb*c/100+32/4-3°4.4; Here in the assignment statomont, some operands are Int s whereas others are feats. As we know. during evaluation ofthe expression, the it s would be promoted to ft s and the result ofthe expression would be afloat. Bul whon this oat value Is assigned to siti again domoted to an int ana then stored in s (Observe the results of tne arithmetic statements shown in Figure 22 . thas been assumed that k isan Intager varlable anda is areal varabla.Figure 22 Note that though the folowing statements give the same result 0, the results are obtained dforanty k=2/9, k=20/9; In the first statement, since both 2 anc 9 are integers, the result isan integer, Le. 0. This Os then assigned to kn the second statement 9 is Promoted o 9.0 and then the vision is performed. Division yields 0.222222. However, this cannot be stored in kk being an int. Hence itis demoted to 0 and then stored in k Hierarchy of Operations \While evaluating an arithmetic statement, some issues may crop up. For exarrple, does the expression 2° x- 3 y correspond to (23)-(3)) orto 2(%-3))? Silay, does A * C correspond to A (BC) of ta (A/ 8) *C? To answer these questions satisfactory, one has to understand the ‘hierarchy of operations. The prionty or precedence in which the operations are performed is called the hierarchy of operations. The hierarchy of commonly used operators is shown in Figure 2.3 Figure 2.9 |Win parentheses the same hierarchy as mentioned in Figure 2.3 is operative. Aso, i there are more than one set of parentheses, the ‘operations wihin tha innermost parentheses would be performed fist, folowed by the operations within the second innermost pair and so on. ‘Atew examples would clanty the issue further. Bxample 2.1: Determine the hierarchy of operations and evaluate the follwing expression, assuming that Is an intoger variable: ie2a/a+ai4e0-2+5/8 ‘Stepuise evaluation ofthis expression is shown below: 1=243/444/448-245/8 i=6/444/448-245/8 ‘operation: * i= 194/448-245/8 ‘operation: / i=n9148-245/8 ‘operation: / i=14148-240 operation: / i=2+8-240 operation: + i=10-240 ‘operation: + isso ‘operation :- ine ‘operation: +Note that 6 /4 gives 1 and not 1.5. This so happens because 6 and 4 both are integers and therefore 6/4 must evaluate to anintoger. Silly § 1 B evaluates to zero, sine 5 and 8 are integers and hence 5/8 must retun an integer value, Example 2.2: Determine the hierarchy of operations and evaluate the folowing expression, assuming that kk isa float variable: ken3/274+3/8 ‘Stopuiso evaluation of this expression is shown below: kk=3/24443/8 kk=1"443/8 ‘operation: / kk=4 43/8, jon: * kk=4+0 / k= operation: + "Note that 3 8 gives zero, again forthe same reason mentoned inthe pravious example, |Althe 45 operators in Care ranked according to thir precedence. We haven't encountered many aut of these operators, so we wor't pursue the subject of precedence any further nara. A ful-ledged lst af all operators and thei precadence le glven in Append. So far we have seen how arithmetic statoments written in C are evaluated, But our knowledge would be incomplete unless ve know how to convert 8 general algebraic expression toa C statement, Some examples of algebraic expressions and their equivalent C expressions are shown in Figure 24 Figure 2.4 ‘Assocatvty of Operators, \When an expression contains te operators of equal proriy, the tia between thems sated using the associatuy ofthe operators. All operators In Cether have Left to Right associativity or Right to Left associativity, Let us understand this withthe help of a few examples, Consider tne expression aral2"s Hore there isa te between operators of same priory, thats between / and ~. This tes sotted using the assoclatvty of / and *. Both enjoy Left to Right associativity. Therefore frsty/ operation is done followed by * Consider one more exoression axbe3; Hore, oth assignment operators have the same priory. So order of operations ls decided using associaty of = operator. = associates trom Right to Let. Therefore, second = is performes earlier han frst =, Consider yet another expression. sbeelds Here * and / enjoys same priory and same associativity (Left to Right). Compiler is fee to perform *or/ operation 2s per is convenience, since no matter which is performed earlier, the result would be the same.‘Appendix gives the aasociatty ofall the aperators available in G. Note that the precedence and associativity ofall oparators is predetermined fand we cannat change Control Instructions Control instructions control the order in whic the instructions in a program got executed. n ther words, the contol instructions determine the flow of contro in a program. There are four types of control instructions in C. They are: (2) Sequence Conte struction (0) Selection or Decision Control struction (©) Repetition or Loop Control struction (4) Case Contr struction ‘The Sequence control instruction ensures that the instructions are executed in the same order in which they appear inthe program Decision and Case contol instructons allow the computer to take a decision as fo which instruction isto be executed nest. The Loop contol instruction helps ‘execute a group of statoments repeatedly. nthe folowing chapters, wo are going to discuss these instructions in deta. P (o)#incude int main() cl floata=5,b=2; Inte. c=a%b: o=alz Print (94a, return 0: > (@)inciade int main() Print ("an inin nin" pnt ("an fv nin’ return 0: > (@)#inctade int main() c inta,b; Print (‘Enter values ofa and b): scant (96a, a, 8) print ("a= Mb = 8", 2b): return 0; > [Ej State whether the folowing statements are True or False:(a) or /, +r represents the correct hierarchy of artmetic operators nC. (©) and 0) can be used in Arithmetic instructions. (c) Hirarchy decides which operator is used fist (4) mG, Arthmetc instruction cannot contain constants on left side of = (©) In C* operator is used for exsonentiaton operation. (f) % operator cannot be used wth floats. TFL in te blanks: @mny 10*x/2 +2: operation wb parored fest. (0) fa isan itegor variable, a= 11 2; wl store_ina (0) The expression, 2 = 22/7 *5 |S; 9ouls evaluate to (@) The expression x=-7 %42 8 would evaluate. () fd isa oat the operation & 17.0 would store in [G] Atemot the folowing questions: (a) fa fei number is nput through the keyboard, write program to calculate the sum of ts digits. (Hint: Use the modulus operator’) (©) Wie program to receive Cartesian co-ordinates (xy) ofa point and convert theminio polar co-ordinates (r) Hint r= sant x + y* and = tan 1 (yx) (6) Wike a program to receive values of latitude (L1,L2) ana longitude (G1, G2), in degrees, of two places on the earth anc output he distance (©) between them in nautical miles. The formula for cstance in nautical miles is: D-=:2963 cos -1 (sin Lt sin L2 + 005 Lt cos L2 * cos (G2- GI) (@) Wind chil actor isthe felt air temperature on exposed skin due to wind. The wind chil larperature is aluays lower than the air temperature, {ands caleuated as per the folowing formula: wet 5.74 + 0.62161 + (0.4275t-35.75) "Ve luhere tis the temperature and vis the wind velocity. Write @ programa receive values af t and v and calculate wind chil factor (we, (6) value of an angle is input through the keyboard, write @ program to print al its Trgonomatric ratios. (0 Two numbers are input through the keyboard into two locations C and D. White a program to interchange the contents of C and D. hop mm void main( s wrong, Correct formis int main() Every complr is targeted tonards a particular OS + Mieoproceesor combination. This combination & known as a platform. A complet created for ‘one platform does not work wih other platform ‘Standard steps in interchanging contents of two variables: (@)/ gives quotiont, % gives remainder. While taking Sh, sign of remainder i same as sign of numerator. % doesnt werk with floats C coffers 3 types of instructions: 1) Type dectaraton 2) Arithmetic 8) Control Declaration and assignment can be combined. Ex: int a3 types of Arithmetic Instructions: 1) itager mode 2) Real made 3) Med mode Rules for arithmetic instructions: + Fone operand is foat, resutt is afloat + Results int only both oporands aro ints a = pow 2,8); would store 25 in a. Remember to include Every operator has 1) Prony 2) Associtvty Priority is */ + Priority can be changed using () ‘Ascodiativity comes into play when priory cannat decide which operation to perform frst. Associativityis either Lto Ror Ro L. to, =has Ro L associativity *) 9ehas Format sting of pint) can contain 1) Format spoctlors te, hd, 2) Escape sequences: many others 3) Any other character Format sting of sean) can catain only format specters Contral instructions contre saquence of execution of instructions ina program 4 types of contol tuations: 1) Sequence 2) Decision 3) Repetition 4) Case Decision Control Instruction a Rare ee | ‘As we lead our life, we have to take decisions. Similary, as we make progress in C programming and ry te Implement comeiicated logics, our program has 1 take decisions. But how? Vell, this chapier has the answer COem ‘The ose Statement ‘utp Statements win f= ese Nestes elses AAword of Cauton ProgramsBeercises Kantiotes \We all nees to ater our actions in face of changing circumstances. fthe weather is fine, then Ill go for astro, the highuay is busy, I would take a diversion, you join our WhatsAop group, | would send you Intoresting videos. You can natice that al these decisions depend on some ceandiion baing mat. In C programs too, we must be able to perform cifferent sets of actions depencing on the circumstances. In the programs witten in Chapters 1 and 2, wo used sequence contol insvuction in which the various statements are executed sequentially, Le, in the same order in which they appear ia the program. in many programming situations, ve want one set ef instructions to be exacuted in one situation, and a diferent set in ancther situation. In C programming, such stations are dealt wth using a decision conta instuction. Thoif-else Statement uses the keywords f and else to implement the dacsion control instruction. The ganeral frm of his statement looks like this It (tis conaiton is true) statement statement; “Tho conation folowing the Keyword if is always enciosod witin a par of parenthoses. tne condition isu, then statement is exocutod. I tne coneon isnot tru, then statement? is executed. The condtion is expressed using ‘relational operators nC. These operators allow us fo compare two values, Figure 3.1 shows how they look and how they are evaluated nC. Figure 3.1 Hore = is the equalty operator and I= the inequality operator. Note that = is used for assignment, whereas, == is used for comparison af two ‘qantties. Let us now understand withthe help of an example howif- else and the relational operators are used ina program. Example 3.1 While purchasing certain ems, a discount of 10% offered f the quantty purchased is more than 1000. quantity and price per ltemare input trough the keyboard, write a program to calculate the total expanses, Given belowis @ program that implements tis logic /*Caleuaton of total epenses *! include int main) fl int ay, ds oat rate, tot print ("Enter quantity and rato")soant (a Ser, Bay, rate}: if(aty > 1000) dis = 10; tot = (aly* rate) - (aly *rate* dis / 100); Print ("Total expenses = Rs. Sif", to) return 0: ) Here is some sample interaction with the program. Enter quantity and rate 1200 15.50 Total exponsos = Rs. 16740.000000 Entor quanity and rate 200 15.50 Total expenses = Rs, 3100,000000 Inthe first run ofthe program, the condition evaluates fo true, 28 1200 (value of aly) is greater than 1000, Therefore, the variable ds gets a value 10, Using this new value, total expenses are calculated and printed In the second run, the condition evaluates to false, as 200 (the value of at ) st greatar than 1000. Thus, dis, his ime gets a value O. Hence the ‘expression afer the minus sign evaluates to zero, thereby offering no discount Note how the statements after if and after else are indented using tab. We would adopt this style throughout this book. Aso note that f we do not ‘wh to do anything when the condition fais, we can drop the else and the statement belonging 10 "Mutiple Sttoments thin if oiso It may so happen that in a program we Want more than ane statement to be executed when the expression flowing ifs satisfied. If such mutiple statomonts are to be executed, then they must be placed within a pai of braces, asilustated in the folowing example: [Example 32: In a company an employee is paid as under: If his basic salary is less than Rs. 1800, than HRA = 10% of basic salary and DA = 90% of basic salary his Salary is elter equal to or above RS. 1600, then HRA = Rs, 500 and DA = 96% of basic salary the employee's salary i input through the keyboard wnte a program o find his gross salary. “The program that implements this logic ls glen below. /* Calculation of gross salary") include intring ( float bs, gs da, ho print (Enter basic slay) scant, bs if (os < 1500)c habs" 10/100: bs *90 100; t ha = 500: ‘da =bs* 98/100; y 95=bs + hra + da; Print ("gross salary = Rs. fn’, gs): return y Figure 3.2 would help you understand the fow of contol in the program. Figure 32 ‘Afowpoinis worth noting about tho program.. (a) The group of statements after the f up to and not including the else is called ani block’. Siar, the statements after the else form the ‘else block. (©) Notice that he else is written exactly below the The statements in thei block and those in the else block have been indented tothe right. “This formatting convention is foloned throughout the book to enable you fo understand the working ofthe program beter. (6) Had there been only one statement to be executed inthe i block and only one statement in the else block, we could have Groped the par of braces.(4) The default scope off as wel as else is the statement immediately after them. To override tis defsuit scope, a par of braces, as shown in the above example, must bo usod. Nested if-else s Ibis perfectly akight if we urite another alse construct within ether the block or the else block. This is called nesting’ ands shown inthe Following code fragment yet) Print (“You would go to heaven tn"): ise in 2) print (‘Hol was created wih you in mind): else Print (‘How about mother earth in"): > Note that the second if checked. fit is false as well, then the second else is exocuted. Joe constructs nested inthe first else block. the condition in the fist is false, then the concltion inthe second if is ‘You can observe how gach time ai-lso construct is nested within another I-lso construc, ts also indented toad clarity to the program, Inoucate this habit of indentation; otherwise you would end up writing programs which nobody (you included) can understand easly at a later date, Note that whether we indent or do not indent the program, it dosen't alter the fow of execution of instructions inthe program. ln the above program, an else occurs within tho“ else block’ ofthe fist i statemant, Simi, in some ather program. an itelse may occur in the If block’ as well Thore s no lint on how deeply thei and the elso can be nested. A Word of Caution Though usually condition is used inf statement, any vad expression wil also do. Thus allthe folowing if statements are val ira +2%5) Print ("This works are ay printf Even this works ir¢) print (Surprisingly eve his works Note that in C.a non-zero value Is considered to be true, whereas a 0 is considered to be fase. Inthe fst, the expression evahates to S and since 5 is non-zero it considered to be true. Hence the print) gets exacuted ln the second i, 10 gots assigned to aso tne ifs now reduced tof (a) ori (10) .Sinca 10 is non-zero, its true hance again print) goes to work Inthe third if, -8 8 @ non-zero number, hence true. So again printf) goss to work. in place of 5 even if float Ike 3.14 were used, would be Considered to be rua, So the Issue isnot whether the number Is integer oF fat, or whether iis posive or negative. ssuo Is whether its 2aro or ‘Another common mistake while using the if statement isto write a semicolon (after the condion, as shown below. scant (dBi tye=5)print ("You entered S10") ‘The; makes the completo interpat the statement as if you have watten it in fowing manner: Print ("You entered Sin") Here, ifthe condition evaluates to true, the; (nl statement, which does nothing on execution) gets executed, flowing which the print) gets ‘executed. the condition fas, then straightaway the print) gots executed. So respective of hethor the condition evaluates to true or false, Print) is bound to get executed. Remember that compiler vould not point cut this as an eror, since as far as the syntaxis concemed, nothing has {gone wrong but the logic has certainty gone awry. P0) Print ("The seller made a profi of Rs. Yi", p); fo) print ("The seller incurred loss of Rs fn.) ite ) print ("There is no loss, no profits"): return 0: ) Output Enter cost price and seling price: 2515 ‘The sale incurred oss of Rs. 10.000000, Problem 32‘Any integer is input through the keyboard. Wte@ program to find out whether itis an odd number or even number, Program 1" Check whether @ number is even or od) include int main) c int printf (“nntar any nub) scant (Ed, 8) ifn %2==0) Print ("The numbers eventn’) else print ("The number is oddin") return » Output Entor any number: 45, ‘The number is odd Probiam 33 ‘Any year i input through the keyboard, Writes programto determine whether the year is leap year or not Program Check unether a year is leap or not“! include int main() c int yr print “enter @ year" scant (a, By print (‘Leap yearPrint (‘Not # Leap yearn": ittyr%4 == 0) Print (‘Leap yearn’; ise Print (‘Not leap yearn’) > return 0; > Output Entor a year: 2020 Leap year EXam TA What wi be the output ofthe following programe: (@)# inoue int main() c int 300, b,« if(a>=400) b=300;¢= 200; Print ("4d Yan ,€) return 0; » ()#inetde int main() c int x= 10, y=20; ity Print (id Yan" xy) return 0; y (0) #incudeint main() cl innxea) foat y= 3.0; ty Print (*xand y are equatin’) else print (*xand y are not equatin", return 0; > (@) ince int main() cl int vz y=x=10) exe tO; nt (‘X= Sa y= 9h 2= Kan. y, 2 return 0; > (e)# inoue Int main(y c inti = 05; char) = 0 print ("Cis WOWhn") else print (°C ls @ headacheln"); return 0: > [B) Point out the erors,itany, in the following programs: (@)# inoue int main() c float a= 1225, 252;itta=b) print ("a and bare equatin’): return 0; ) ()# ince Int main(y c int) =10, k= 12 feo=p) (c)#incudo int main() c exe printf ("asc value of Xis smaller than that of xn"); > (@)#inctude int maint) intx= 10; if (x>=2) then print (94a, return 0; » (©) #inctude int main() a Intx= 10, y= 18;iF («%2=%3) print (“Carpathiansin"} > (N #incude int main(y c inta,b; scant (%d Scr, a,b) if(a>b): printf ("This is a gam’); ose print ("You nave to pay tn’) return 0; > [C] State whether te following statements are True or False (@): 1s avai statomont (0) ls can be nested. (c) fthere are mutiple statements in f or lse block they should be enclosed within a pair of (@) If can occur within ani block but notin the else block. (©) By defaut there is only one statment in block and only one inthe else block ( Nothing happens on execution of a nul statomont. [D] Maten the folowing pats: IE} Wien of ne fokowing are vai ts: (a) if(-25) o)iF(9.18) (ity @it@ro) (@it(a>=b) IF] Attomet the folowing questions: (@) A tve-cigit number i entared trough the kayoars. Whe a program to oblain the reversed number and ta determine whether the original ang reversed numbers are equal ar not (©) rages of Ram, Shyam and Ajay are input through the Keyboard, wrte a program to determine the youngest of he three. (6) Wie a program to chock whether a triangle is valid or not, when the three anges ofthe viangle are ontored through the keyboard. Atiangle 's vag i tme sum of all the three anglos i aqual to 180 dagraes, (@) Write a program to find the absolute valve ofa number entered through the keyboard (€) Given the length and breacth ofa rectangle, wnte@ program ta find whetner the area of the rectangle is greater than its perimeter. For‘example, the aroa ofthe rectangle with longth = 5 and breadth = 4s greater than is perimeter. (0 Given three points (x1, y1), 02, y2) and (2, y3), wtte a program to chack fal he three points fal on one straight tine. (@) Given the coordinates (x) of center ofa circle and its radius, wite a program that wil determine whether a point es inside the circle, on the Crrle or outside the circle, (Hot: Use sqrt) and pow) functions) () Given a point ( y) write a program to nd out if ites on the Xaxis, Y-axis or on tho origin (0) According to Gregorian calendar, twas Monday on the date 01/01/01. any years input through the keyboard wie @ program to find out what isthe day on 1st January ofthis year. hope “Treo ways for taking decisions a program: 1) Using tele statement 2) Using conditional operators 3) Using the switch siatoment General forms of decision contro instruction: if (condition) if (condition) statement! 5 { dse statement! ; statementZ 5 statement2 5 } ase {are optional here { ' statement® ; statements 5 {Jarenecessary here ‘The default scope off and else statement is only the next statement. So, to execute multiple statements hey must be ven in 8 par of braces. Conaiton is bul using relation operators <, > ‘nif need not alvays be associated wth an else. However, an else must aays be associated with an if ‘An ites statement can be nested inside another d-elee statement = Dis assignment a == is companson nia o)resut of bis compared with ¢ If a conaiton is true itis replaced by 1 i false itis replaced by O ‘Any non-zero number is tue, 0 false |e anul statement, €oesn't 60 anything on executionMore Complex Decision Making “Life is complex, so are decisions in life. IF. got good marks in my final year and if my GRE and TOEFL scores are good and if got good recommendations or If do not get a job wth good prospects and if my family conditions permit me, then I woul think of doing MS in US. How can such complex decsion making be implemented in (C2 This chapter wil snow you how. COE Use of Losical Operators - Checking Ranges The else if Clause Use of Logical Operators - Yes No Problem “The ! Operator Hierarchy of Operators Revisited “The Condonal Operators Programs Brercises Kantiotos (We all face situations where the acon tat we carry outs based an multiple conditions. For example, | wil join @ company Ifthe company allocates ‘2 mato location, gives me a good pay package and permis jining period of d weeks. In programing too, action performed may be based on the result of mutile conditions. Such progranering situations can be handled elegantly using Logical Operators. This chaoter explores the use of logical operators and one more ype of operators called conditional operators. Use of Logical Operators - Checking Ranges Ceallons usege of tree logical operators, namely, 86, || and, These are to be read as ‘AND', OR’ and NOT respectively Of these, 8& and ll operators alow tuo or more conditions to be. Let us see how they are used in programs. Consider the following example: Example 4.1: The marks obtained by a student in § diferent subjects are input through the keyboard. The student gets a division as per the following rules: Percentage above or equal to 60 First division Percentage between 50 and 59 - Second dvsion Percentage betwen 40 and 49 - Third division Prcontaye oss than 40 - Fal \Wite a program o calculate the division oblained by the student. “Thora are wo ways in which we can wie @ program for this example. These methods ara glen below.Petnod -1*7 include into) t int, m2, 8, a oe print Emer mark nue sujet) scant (ed Sl Ma Se 960", Amt, m2, AmB, Bm, Br) per = (mt + m2 + m3 + ma + m6) * 100 / 500 if iper>= 60) Print (First avisionin’) ise i if (per >= 50) Print (“Second diision\n"} se c It (per >= 40) Print (“Thre dvasionin") oe Pant ("Fait y > return 0; > “Ths is @ straight formare program. Observe that the program uses nested i-elses. Though the program works fine, thas three disadvantages: (@) As the numberof canctions goon increasing the level of indentation also goes on increasing. As a resul the whole program resp to the right. So much so that entre program isnot visible onthe screen. So if something goes wrong with the program, locating what fs wrong where becomes dificult, (6) is ficult to match the corresponding ifs and else (6) Ris cifeut to maten the corresponcing pair of braces, ‘Al tnese three probloms can be aimnated by usage of Logical Operators. The foBowing program ilustratas ths: /Pathod - 17) include int maint)Int rm, m2, m3, ma, mB, por: Print ("Enter marks in five subjects) Scant (ed Sh Ne Yh 4d", Bent, m2, Ar, Am, Bi) ers (mt + m2 + mi + mA + ms) 500 * 100; it per>= 60) Print (First division if (par >= 50) 84 (por < 60)) pnt (“Second avon’ It (per >= 40) 88 (per <50)) Print ("Thre division") itiper <40) Pant (Fain) return 0; > In the second if statement, the 88 operator is used to combine tuo conditions. ‘Second division’ gets printed only both the conditions evaluate to tue, [he three dsaavantagas ates above have been avercams in his program. However, there I @ negative sige to the program 09. Even ihe first condition turns eut to be true all other conditions are sil checked, Ths ul increase the time of execution of the program. This can be ‘voided using the ese if clause discussed inthe nex! section The elseif Clause Let us now rewrite program fr Example 4.1 using ele if locks, Pr else adder der") if (par >= 60) print (First vision) sf (por Print (“Thre dvasonin") oe Print (ainn"; Using if-else if- else reduces the indentation of the statements, Here the last else goes to work only al condition fal. Aso, ia condition is sated, other conaltons nelowit are not checked. Even in ele if ladder, the last ese s optional Use of Logical Operators - Yes / No Problem ‘Another piace where logical operators are use is when we want io wre programs for complicated logics that uimately bol dawn to only two answors—yos or no. The folowing example ilustrates this:Example 4.2: Acompany insures its dvrsin he foloving casos: + me driver's marred + Fhe drivers unmarried, mal & sbove 30 years of age. + Fhe drivers unmarried, female & above 25 years af age. In allotner cases, the drivers not insured. the marital status, sex and age of the driver are the inputs, write a program to determine whether the driver should be insured or not ‘The final outcome ofthe program wuld be—ather the driver should be insured or the driver should na be insured. So the pragram can be conveniently wnten using logcal operators, For this let us frst ent those cases in whicn the driver is insured. They are—DrWver is married Drivers an unmarried mato above 30 years of age, and Driver isan unmaried female above 25 years of age. Since al these cases lad tothe river being insured, they can be combined together using 88 and || as shown in the program below /r insurance of erver- using logical operators */ include int ming C char sex me stage: print Enter age, sex marta stats" scant (ed Ske ic", Bage, Asex 8s); if (ms == M) Il (ms ==°U 8 sex== M88 age > 30) | (oe Print ("Driver should be insured se print "Driver should not be insuredin" return 0: > In this program, itis important to note that: +The driver wil be insured onli one ofthe conditions encosed in parentheses evaluates to tue, + For the expression in second pai of parentheses to evaluate to tre, each condition in he expression separated by 8& must evaluate to tue. + Even i one ofthe conditions in the second parentheses evaluates to false, then the whole expression evaluates to false. + The last tuo ofthe above arguments apply to thie par of parenthoses as wel In some programs ve may combine the usage of i—else else and ogical operators. Ths is demenstated inthe following program. Example 43: Write a program calculate the salary as per the folowing table:intyos, qual, sal Print ("Enter Gender, Years of Service and Qualifications (0 1 = PG)"; scant (*hete%ée", 8g, Byos, Aqua); if (g == i 88 yos >= 10 88 qual == 1) sal= 15000; ‘else i (g == ¥ 8B yos < 10 88 qual == 1) sal= 10000: Print (\nSolary of Employee = cin, sal:return 0; d [nope you can follow te implementation of this program on your own, ‘The ! Operator “The third logical operator isthe NOT operator, wten as !. This operator reverses the result ofthe expression It operates on. So ithe expression evaluates to true, then applying | operator tit results ino a fase. Vice versa if the expression evaluates to fase, then applying! to it makes it true, Here isan example showing use of ! operator. hy <10) IF yis less than 10, the result vil be false, since (y < 10)is true ‘The NOT operator is often used to reverse the logical value of a single variable, asin the expression it (1 Rag) “This another way of saying if(fag ) Figure 4.2 summaries the working ofall the three logical operators. Figure 4.2 Hierarchy of Operators Revises ‘Since wo have now added the logical operators tothe list of operators wo knows its time to revi these operators and thr priolos. Figure 4.3, summarizes the operators we have seen 60 fr. The higher the posion of an operator isi the table, higher is its priority. (A ful-edged precedence table of operators is given in Append.) Figure 4:3 “The Conditonal Operators ‘The conditional operators ? and: are sometimes calles ternary operators since they take three arguments. in fact, they forma kind of {oreshortaned i-tnen-else, Thee general form, expression 1 ? expression 2: expression 3What this expression says is “if expression 1is tru, then the value returned ull be expression 2. cthernise the value returned willbe expression 3°, Letus understand this win the help ofa few examples. (aint y: scant (ar, 8x K>5734), “This statement wl store 3in yf xis greater than 5, otherwise i wil store 4iny (0) chara, int scant Ye’, 8a) jo>s65 aa 90:0} Hore 1 would be assigned toy 'a>=65 && a <=90 avaluates tottus, cherie O would be assigned. ‘The following points may be noted about the conditional operators: (@) ts not necessary tat the statement after ? or: be ony anthmeti statements. This ilstrated in the following examples: es int scant (4d, Bi): 2 print ("Amt"): printf Aland sun’) Becara= 2: print (40 (a Pain) (0) The conditional operators can be nested as shown below. int big, a, 9, cr (a>? (a>c73:4):(0>076 8) (6) Check cut the folowing concitional expression: aebigeazyet: This wil give you an error ‘Lvalue Required’. The error can be overcome by enclosing the statement in the : part within a par of parentheses. This 's shown below. a>b2g=a:g In absonce of parentneses, the compiler Boloves thal bis boing assigned to the result ofthe expression to tho lft of second = . Honco It reports (4) The tnitaton of tne conditional operators i that aftr the ? or after the :, only one C statemont can occur. Problem 4.1 A year's entered through the keyboard, write 2 program to determine whether the year I leap or not. Use the logical operators 88 and | Program check wnetnor a year is leap or not“include int ring t int year: printf (“\nEnter year") scant CY, year Ie (year 96 40 Of year % 100 88 yoar % 4 printf ("Leap yearn’ else Print ("Not leap yearn’); return o; > Output Entor year: 1900 Nota leap year Problem 4.2 Ira character is entered through the keyboard, wt a program to determine whather the characters @ capital eter, smal case later, a dig or fa special symbol ‘The following table shows the renge of ASCilvalues for various characters: Program /* Check type of character entered from the keys / include Int maint) char chy printf \nEnter a character fom the keyboard”); scant (*%e", ch) if (ch >= 65 8& ch <= 80) print ("The characters an uppercase lettern");It (ch >= 97 88 ch <= 122) Print ("The characteris lowercase letter’ If (on >= 48 88 on <= 57) print ("The charactaris a digtn") if (ch >= 0 88 ch < 48) | (ch > 57 8B ch <65) Il(ch > 90 88 ch <7) 10n> 122) print ("The charactor is special symbotin") roturn 0; > output Enter a charactor from the keyboard: A ‘The characteris an uppercase leter Problem 4.3, Ifthe three sides ofa triangle are entered through tno keyboard, wita a program to check wnethor the tianglo is vald or not, The tangle is valid ifthe sum of two sides s greater than the largest of the three sides, Program /* Check whether a triangle is valid or not include intmaind C Inside, 2, sided, argos, su print (“MEnta thee sides of he angie scant (Yd Ma a, Aaaet,Asie?, Aside} i sot» sida) ( (eos > se) C sum= sided + side largeside = sid , aise ( sum=sicet + sited anges = se , ,c if sid > idea) fot + sido argeside = sided: it (oum> largeside) ht ie edna - printf ("The triangle is an invalid triangle\n"); -_ & ‘Output uo nie wang 348 The taylan ea c Xam a 10, b= 12,651 find the values ofthe expressions inthe folowing table: [B} What wil be the output of the following programe: (@)#inctude int main() inth=4,2= 125 if=5|2>50)Print ‘Dean of students affarsin"); oe Print (‘Dosen’) return 0: > (oy ncude int main() c loti j= eka Om x YZ wer iilitk: x21 88 88 y= iN) 88K 22188) Dini (w= ed x= Bed y = Yad 2= Hei", WK YZ return 0; > (6) # incuae int main() int i> y 8x22) Print (bigges olsoit(y >x88y >2) Print (*bigges ba, elseif (2> x882>y) print bigget > ab’, 2); return 0; (a incase int main(y int i= 4, cum J (rum<0 7 0: num num); print (4d): return 0> (o)# incade int main() c Int k, sum = 30; k= (oum> 5 2 (num <= 10? 100: 200): 509) print (4a, num return 0; > [C] Point out the errors, if any, inthe folowing programs: (a) # inctude int main(y char spy = a, passwor If (spy =="@ or password == 2) Print ("All the birds are sate inthe nestn’); return 0; > ()#inciade int main() c inti= 10, j=20; iF(=5) 8a G= 10) print ("Have a nice dayin") return 0; > (oF incude int main() cl intx= 10, y=20; If (o=2 anay <= 50) Print (A, return 0; > (@)# inctudeint main() c intx=2, if cme 2 88 x1 OF Print (“Halon”): else print ("Bye") return 0; y (o)#inctude int main() c int) = 65 Print (>= 65 7 0: Sein") return 0; > (0 #incude int main() int i= 10,5, 2s 10:)= 18; print (id Sen return: > (@)# mete int main() b= 6; 2 prt (kn 2) return 0; y (ry inode int main() cintn=9: c 97 pif ("Correct print (Wreng\n)) return > [P} Atop the fotoving questions: (a) tno three sides of a triangle aro entared through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalone orright angle trang, (©) In digital word colors ae specified in Rad-Green-Blue (RGB) formal, with values of R, G, B varying on an integer scale from 0 fo 255. In print publishing the colors aro mentioned in Cyan-Magenta-Vollow-Black (CMYK) format, wih values of CM, Y, and K varying on a real scale from 0.0 to 1.0. Wrte a program that converts RGB colar to CMYK color as por the foloning formulae: White = Max(Red /255,Green /255, Blue /255) White —Red / 255 aon -( White ) White — Green 255 Magee (Oe) White Black =1—White Yelow ={Mhie= Bite 285) Noe that if the RGB values are allO, then the CMY values are al!O and the K value is 1 (6) A certain grade of steels graded according tothe folowing conditions: (0) Hareness must be greater than 50 (@) Carbon contont must be loss than 0.7 (i) Tensile svength must be greater than 5600 ‘The grades are as folows: Grade is 101 al tee conditions are met Grade is 9 # conditions (i) and (i) are mot Grade is 8 # conations (i) and (i) are met Grade is 7 # conatons (i) and (i) are met Grade is 6 only one condition is met Grade is 5 # none ofthe conditions are met White @ program ubich wil require the user to give values of hardness, carbon contant and tensile strength ofthe steel under consideration and output the grade ofthe steal. (d) The Body Mass index (Bk) is defined as rato ofthe weight of a person (in kilograms) to the square ofthe height (meters). Write @ program that receives weight and height, calculates the BM, and reports the BI category as per the following table:IE] Attempt the folowing questions: (@) Using concitional operators cetermne: (1) Whether the character entered through the keyboard isa loner ase alphabet or not (2) Wether a charactor entored through the Keyboard isa special symbol or not. (©) Wire a program using condtional operators ta datermine whether a year entered thraugh the keyboard is a leap year or not (6) Write a program to find the greatest ofthe three numbers entered through the keyboard. Use conditional operators. (@) Wie 3 program to receive value of an angle in degrees snd check whether sum of squares of sine and cosine ofthis angle is equal 1. (€) Rewrite the folowing program using condtional operators, include int main() c fost sa Print (‘Enter the salary’) scant (*%6t, sal) (sal 5000 && sal <= 40000) Print ("Menagerin’) it (sal>= 15000 88 sal < 25000) printf “Aecountant’) se print Corn" return 0; , kgm More complex decision making can be done using logical operators Logical operators are 8, and !Logeal operator aro vot in2 stuatons +) Ceckingcanges 2) Slvng yesno probom Ce ore fomof decison contol nstucon i (condition) statement! else if (condition?) statementZ 5 else if ( condition’) statement 5 else. © dse goes to work if all 3 ifs fail statement4 ; Herarony: P+ -<> coe 88 = Unary operator - needs only 1 operand. Ex I sizof Binary operator -naeds 2 operands. Ex + BI) - "98> size isan operate. gives numberof bytes occupies by an entty sage of 20 operator a= stvof (it) = stot (num) 1 (@
b).! (a>=b) is same as (a
CGivon below the intoraction wih his program on its exacution Entar values of p, mand r 1000.5 13.5 ‘Simple interest = Rs. 675.000000 Enter values of p, mand r 20005 13.5 ‘Simpl interest = Rs. 1950,000000 Enter values ofp, mand r 3500 5 3.5 ‘Simpl interest = Rs, 612.500000 “The program executes al statoments aftr the while 3 tives. The logic for calculating the simple interest is writen in these statements and they are enclosed whin a pair of braces. These statements form the ‘ody’ ofthe while loop. The parentheses after the while contain 3 condition. So long as tis condition remains true, he statements the Body ofthe while loop keep getting executed repeatedly. To bogin wih, the variable count is Intialized to 1 and everytime the simple interest logics executed, the value of counts incremented by one, The variable countis often called citer a oop counter or an ‘index variablo “The operation af the while loop is strated in Figure 5.1 Figure 5.1 ‘Tips and Traps Note the folowing points about while, +The statements within the ule loop would Keep geting executed tithe condition being tested remains true. When the conditon becomes {alze, tie contol passes tote fest statement that follows the body af the vino loop. + Almost ainays, the while must test @ condition that will eventually become false, otherwise the loop would Keep geting executed Forever, Indefinite, inthie (<= 10), print ("4a ‘This is an indefrite loop, since i aways remains equal to 1, The correct form would increment inthe body ofthe loop. + Instead of incrementing a loop counter, we can decrement it and stil manage to get the body ofthe loop executed repeatedly. This is shown below. inti 5 bile (i>= 1) c Drintf ("Make the computer itertetin) + Ris not necessary tnata loop counter must only be an int. can even be a float float a= 100 hie (a <= 10.5) printf (‘Raindrops on roses...) print (..and whiskors on ktens\n") azato. > + Even floating point loop counters can be decremented. Once again, the increment and decrement could be by any value, not necessary 1. +The condition being tested may use relational or logical operators as shown inthe folowing examples: hie (<= 10) while (i>= 1088 <= 15) while > 10 88 (b < 15} 20)) + ere le only one statement within the loop then () are optional + What wil be the output ofthe folowing program: include int main() cl inti while (<= 10), c Print ("4a +return o; ’ ‘This s an indefinite loop, and it doesnt give any output at al. The reason is, we have carelessly put after the while. t would make the loop work tke ths... ile (<= 10) c int Hd > ‘Since the value of isnot geting incremented, the contol would kaop rotting within the loop eternal. Noto that enclosing pint) and |= +4 within a pair of braces isnot an error. n fact, we can put 2 pair of braces around any individual statement or set of statements without affecting the ‘execution of the program. More Operators ‘There are several operators that are frequently used wth while. Ta dlustrate their use, let us considera problem wherein numbers from 1 to 10 fare to be printed onthe screen. The program for performing this task can be written using while in following cfferent ways: (a) #inctude Int main(y c inti vuhie (<= 10) c print (4a lets This is the most straight-formard way of printing numbers from 1 t0 10. (oy# ince int maint) inti while (/<= 10) Print (hae,return 0; ) Note thatthe increment operator ++ increments the value of by 1, every time the statement i++ gets executed. Simlaly, to reduce the value of @ Varale by 1, a decrement operator ~ is also avaiable, However, naver use n+ to increment the value of n by 2, since there doesn't exist an operator +++ in C. (6) # include int main() c int hie (<= 30) Print (M4, leet > return 0; > Noe that +=is @ compound assignment operator. inerements the value of by 1. Similarly, j=]+ 10 can also be written as j+= 10 . Other ‘compound assignment operators ares, "=, /= an x . (@) # inctude int main() inti=0; hie (i++ < 10) Print (940): return 0; > ln the statement hile (1+ < 10) frst the comparison of value of wh 10 fs performad, and then the inremantaton of takes place. Since the inctementation of happens after the comparison, here the ++ operator is called a post-inerementation operator. When the control reaches print) «has already been incremented, hence i must be inalzed to 0, not 1 (©) #inctude int main() c inti=0; hile (++i <= 10)Print (94a): return o; ’ Inthe statement while (+i <= 10), fret incrementation of takes place, then the comparison of value of iw 10 is performed. Since the Incremontation of happens before the comparison, here the ++ operator is eal a pre-incremantation operator. P= 40) ctpay = (nour = 40) *12; else otpa Print (‘Hours = dl Overtime pay = Rs. Sin", hour, otpay) y roturn 0; > output Enter no, of hours worked: 45 Hours = 45 Overtime pay = Rs.60.000000 Enter no, of hours worked: 50 Hours = 50 Overtime pay = Rs.120.000000Enter no, of hours worked: 20 Hours = 20 Overtime pay = Rs.0.000000, Problem 5.2 \Write 8 program to find the factorial value of any number entered through the keyboard Program /* Calculation o factorial value of @ number *) include int main) c Int num, fac print (“Enter a number: scant (*%e", Anum); factzi=1 while (<= num) cl fact= fact": ey > Print (‘Factorial val of Yl = Yen’ num, act; return 0; > Output Enter a number: 14 Factorial value of 14 '27e045280 Problem 53 “Two numbors are entered through the keyboard. Write program find the value of one numba raisad to the power of ancthor. Progrem /* Compute value of one number risad to another */ include int maint) c foat x pover intyprintf AnEnter two numbers") Scant (%6t Ma, x, 8) power: while (<= y) c ower = power», > Print ("tothe power Sd is iin, x y, power), return 0; » Output Enter two numbers: 25.3 2,500000 tothe power 3 is 16.625000 Xam TA| What wi be the output ofthe folowing programe: (2) # ince int main() inti= shite (<= 10) c Print (4, » return o: > (yA inctude int main() int (he ad Sei" x y, 2return 0: > (e)# includ int main() c intx=4,y=3.z int ("9 ad Say, 2 return 0; » (@)# ince int maint) cl sila (a"<'b) Print (‘malayalam s 9 palinérometn"y return 0; > (@)#inctude Int main() inti while (i= 10) c Print (4) (0 #incude int maint) float x= hile (x Print (96f,xox Ot return 0: > [Bj Attemot the folowing questions: (@) Wrte a program to print al the ASCII vaives and ther equivalent characters using a while oop. The ASCII values vary from Oto 256, (©) Weitea program to rit out all Armstrong numbers between 1 and 500. sum of cubes of each digit ofthe number is equal o the number ise, then the number is caled an Armstrong number. For example, 153 = (1*1* 1) +(5°5*5)+(3*3*3), (6) Wits a program for 3 matchstick game being played between the computer and a user. Your program should ensure tha the computer akways wins. Rules fr the game ara as follow: + There aco 21 matchsticks. +The computer asks the player to pick 1, 2,8, or4 matchsticks + Aer the person picks, the computer does ts picking. + Whoever is forced to pick up the last matchstick loses the game. (6) Wirt a programe enter numbers ihe user wants. Athe end it shoul display the count of postive, negative andl zeros entered (6) Wite a program to receive an integer and in ts octal equivalent (tnt: To obtain octal equivalent ofan intager, cide It continuously by 8 tl avidond doesr't become 2oro, then vet the remainders obtained in reverse direction.) (0 Write a program to find the range of a set of numbers entered through the keyboard. Range isthe diference between the smallest and biggest umber in the Et. knoe Sateen eine pets chet an nase cn ane i + [* initialization of loop counter */ aan * testing of loop counter */ statement! ‘statement 5 ists [* incrementation of loop counter */ 3 i incromonts vale by 1 decrements value of by 4 ‘There are no, JFand %% operatorsTho expressions i=1 +4, i++ and ++i are all samo -+ fst increments}, ten assigns tne incremented value to} +5 st assigns currant value of taj, then ineremenis bile (+¥1< 10) festincrements i, then checks condition hie (i++ < 10) fst checks concttion, then increments | l=1+5issomeasit= 5 nd So Compound assignment operators: + Running sum and products aro implemontod using folowing: $05 pels while (condition) IP calculate term */ seseterm; rept term; More Complex Repetitions Te ea xtakes values from 1 to 10. For every y takes values from 0.5 102.25 in steps of 0.5 and for every y, 2908s from 100 to 55 in decrements of 2, and for every , mincroases in muliples of 4 starting vith 4. Lostin the hoops? Wel this chapter wil show you how such complex repetitions can be implemented in C. CO The for Loop Nesting of Loops Mutipelialzatons in the for Loop The break Statement The continue Statement The do-ubile Loop “The 04d Loop ProgramsBerclses KanNotes ‘The programs in the ast chapter showed how instructions in @ program can be repeated using @ while loop. This chapter explores the other two loops—for and do-whlo. Thora is more to looping than just repeating instructions. For example, what if we wish to terminate the loop abruptly, or skip some instructions as the loop executes, or repeat something infrite times, unknown numberof times or anly ence. Allthese scenatis are handled in this chapter. The for Loop “The fr loop allows us to specty three things about the loop in a single tne: (@) Setting a toap counter o an tal value (©) Testing the loop counter to determine whether its value has reached the numberof repetitions desired (6) increasing he value of oop counter each time the body of the lop has been executed, ‘The general form of for loop is as under: for (hittin counter test counter; incremont countor) cl do this: and this > LLetus now write down the simple interest program using for. Compare ths program vith the one that we wrote using while /* Calculation of simple intorest fo 3sots ofp, n and include int main() cl Int p.m, count fat for (coun ‘count <= 3; count = count + 1) c Print ("Enter values ofp, n, andr”) scant (a Ska %P, Bo, Bn, Br) si=ptnrr/100: Print (“Simple inorest= Rs." si y return 0; > ‘You can observe tnat the ree steps—nialzation, testing and incrementaton—requied forthe loop construct nave now been incorporated in ‘one single ine of for statement.Lotus now examine how the for statement gets exocutod: + Won for statement is executed forthe fst ime, tha Value of count is otto an inal value 4. + Next the condition count = 3 is tested. Sinoe counts 1, the condition is stisied andthe body ofthe loops executed for the frst ime. + Upon reaching the closing brace of for controls sent backto for statment. here the value of count gets incremented by 1. ‘+ Again the testi performed to check whether the new value of count exceeds 3. + tftne value of counts less than or equal to 3, the statements within the braces of fo ae executed again. + The body of for loop continues to got executed ti count dossrit exceed the final value 8, “+ When count reaches the value 4, the contro exs fom the loop and is transferred t he statement (i any) immediately afer the body of for [tis important to note thatthe inalztion, testing and incrementation part of for loop can be replaced by any valid expression. Thus the folowing {or loops are perfectly ok for (= 10: (1) print ("1 for (i<4;)=5:) Print (i for (= 15 1-<=10; print ("94d *,64)) for (scant (dBi) i<= 10; i++) print (4 Let us now write down the program to print numbers from 1 to 10 in diferent ways. This tine we would use a for loop instoad of awhile op. (a) #inctade int main() bee 0; + Print (4a, return 0 , Instead of = #1, the statements itor += 1 can also be used, Since there is only one statement in the body ofthe for oop, the pair of braces, have been dropped. As wth the while, the default scope of for isthe immediately next statement after for ()#inctude int main() cl inti lee 10)Print (94a): Hore, the inccementation is done wlhin tha body of the for loop. In spite of his, the semicolon (: after the condon is necessary. (c)#incudo int main() inti for Gie=10)1214) Print (4a, return o; ’ Here the iniiatzation is done inthe declaration statement itself, but stilthe semicolon before the condition is necessary. (oy ince int main() c inti for (<= 10) c print (a) Here, neither the initalzation nor the incrementation is done inthe for statement but fl the wo semicolons are necessary. (@) #inctude int maint) c int for ite < 10) print (a) return 0: >Here, the comparison as well as the ncrementation is done through the same expression, i++ < 10 . Smice the ++ operator comes after, comparison is done first, foloved by incrementaton. Note thet tis necessary to infalize 100, (9 #incude int main(y i inti for @=0; 441 print (4a return 0; > Here again, both, the comparison and the inrementation are done through the same exoression, ++i <= 10. Since ++ precedes ifrsty Incrementation is done, folowed by comparison. Note that its necessary to intialize ito 0. Nesting of Loops ‘The way if statements can be nasted, similarly while s and for scan alsa be nested. The fllwing program shows how nested loops work. /m Demonstration of nested loops include intmaind ‘ inte, sum, for 3: r##) outer loop “/ for (e= 1: <= 2; er) "inner lop“! Print (1 = Sed © id sum= hn, ,c, sum) > ’ return 0; » \Wmen you run thi program, you wil get the following output: o= tsum=2 c= 2sum=3 re2cetsum=3 =2¢=2sum=4c= tsum=4 o=20um=5 Here, for each value of the inner loop is cycled through twice, withthe variable c taking values from 1 to2. The inner loop terminates when the Value ofc exceeds 2, and tne outer loop terminates when the value ofr exceeds 3 ‘As you can 509, the body ofthe outer fr loop is indented, and the body ofthe iner for loops further indented. These multiple indentations make the program easier to understand, Instead of using two statements, ons to calculate sum and another to printit out, we can compact them into one single statement by saying rn (r= Sad © 94d sum = Shen, F 6, Fe ‘The way for loops have been nested here, siarly, two while loops can also be nested. Not ony this, a for loop can occur vin @ while loop, oF 8 ‘wie within a for "Mutipl hitalzations inthe for Loop “The intiaization expression in the for loop can contain more than one statsment separated by a comma, For example, for (i= 4,j=2:)<= 10,9) "Muttpleinccementations can also be cone ina for loop. Simiary, mutiple conditions are alowed in the test expression. These conditions should be inked together using logical aparators && andr | The break Statement \We often come across situations where we wnt 1 jump out of 2 loop instant, without waling to get back to the condition. The keyword break allows us todo tis. Wen breakis encountered inside any loop, control automaticaly passes tothe frst statement after the loop. A break is Usuay associated vith an. Lets consider the fllowng example to understand it Bxampic 6.1: Write a program o determine whether a number is prime or not, A prime number is said to be prime fits divisible only by 1 oF ise ‘Alwe havo to do to tost whothor @ numbers prime or no, to divide it successively by al numbers from to one less than to. remainder of any of ese divisions is 2ro, the number isnot a prime. ino dvision yields a 2270 then the number i a prime number. Fotowing program implements tis logic: include int main() c int num i printf "Enter a number”) scant (4d, Bur); while (<= num 1) if (num %1 == 0) Print (‘Nota primo numbor\ break >> ing rum) printf (‘Prime number) » ln this progeam, the moment num % turns outta be ero, (Le, num is exactly divsbe by |), the message “Nota prime number” printed and the control breaks out ofthe while loop, Why does the program require the f statement after the while loop at all? Wel, there are two possbities the control could have reached outside the while oop: (@)tjumpes out because the number proved to be note prime. (©) The loop came to an end because ne value of necarne equal fo num \When the loop terminates in the sacond case, i means that there was no number between 2 to num 1 that could exactly clive num. Tat is, am is indeed a prime. this is tre, the program should printout the message "Prime number’ ‘The keyword break, breaks the control only from the while in which its placed. Conder the following program, which illustrates this fact include int main(y inti=4.) uhie (i++ <= 100) c suite ++ <= 200) c itya= 150) break: ise Print (94d an) > y return 0; > In this progcam when | equals 150, break takes the contol ouside the inner while only, since itis placed inside the inner wale ‘The continue Statement In some programming situations, ve want Io take the contralto the beginning of the loop, bypassing the stalemens inside the loop, which have not yet been executed, The keyword continue allows us to do this, When continue is encountered inside any oop, Control automatically passes tothe beginning ofthe loop. ‘continue is usualy associated wih an f. As an example, It's consider the folowing programinclude int main() c tae continue Print (an ) > return 0 y Tho output ofthe above program would be 12 2 Note that when the value off aquals that of, the continue statement takes the control othe for loop (inner) bypassing the rest ofthe statements pending execution inthe for oop (ie). The do - while Loop “The do-uhio loop looks ike ths: do this, and this ) while (this condition is tue): hore is a minor diffrence between tho working of while and do-wnile loops. This diference asin tha place where the condition is tested. The while tests the condition before executing any ofthe statements within the vite loop. As agains his, the do-while tests the condition afer having fxeeutad the statements wthin the loop. This moans that do-whe would execute its stalomenis atleast once, even if the conditon fails forthe first ime. The while, onthe othor hand wil not execute its statements if the condition fais forthe fst time. This difference is brought about more clearly by the foloxing program: include int main() cwhile (41) Print (‘Helo thar in return 0; ) Here, since the condition fas the fst time tse, the print) will not get executed at all Lets now write the same program using @ do-whie loop. include int main() c Print (‘Holo thar in Dail (4 <2; return 0; y In this program, the print) would be exacuted once, since fst the body ofthe loop is executed and than the condition i tested. broak and continue can also bo usod with do-while loop. A break takes control out ofthe do-uhile bypassing the conditional tes. A continue sonds control straight to the test at the end ofthe loop. The Odd Loop ‘The loops used so far executed the statements within them a finte number of times. However a times one comes across a situation when it snot known beforehand, now many tines the statemants inthe loop are to be executed. This station can be programmed as shown below. /* Execution ofa loop an unknown number of times */ include int maint) char another; int rum to c print (“Enter a number"); scant (6d, Anum); Print (‘square of Yes Yn", num, num * mum): print ("Want o enter another number yin") Mush (stain: scant (*%ée", Sanather}return o; ’ And here is the sample output Enter a number 5 square of Sis 25 Want to enter another number yin y Enter a number 7 square of 7 is 49 Want to enter another number yin a In this progcam, the do-nhile loop would keep getting executed til the usor continues to answer y. The moment user answers. the loop terminates, since the condition ( another == Vy’ falls. Not that this loop ensures that statomonts wathin tare executed atleast once. Perhaps you are wondering why have we used the function flush() fr. The reason i to get rid of pecullarity f scant). After supplying = number wtten we hit the Enter key, scanf() assigns the number to variable num and keeps the Enter key unread inthe Keyboard buffer. So when It time to supply ¥ or N for the question ‘Want io entar another numbar (yn). scant) will read the Entor key from the buffer thinking that user has entered the Enter key. To avoid this problem, ve use the function ffush) . tis designed to remove or lush out any data remaining inthe buffer. ‘The argument to flush) must be the buffer uhich we want to flush out, Here ve have used ‘sci, which means buffer related with standard input device, Le. keyboard ‘Though itis simpler to program such a requirement using a do-while loop, the seme functionally, required, can also be accomplished using for ‘and while oops. You can try doing this as an exerose. P > return 0; Output an att aitXam [A Answer the followng questions: (a) The break statements used to ext rom: ‘An if staloment Afor nop A program “The main( function (©) Gosntileto0p is useful when we want that the statemens within the loop must be executed Only once Atleast once More than once None of the above (6) n what sequence the intiaizaton, testing and execution of body is done in a do-wne loop? Inazation, execution of body, testing Exccuton of body, initialization, testing Inlalzation, testing, execution of body ‘None of he above (@) Which ofthe folowing isnot an infinite loop? 1 2. fort 3. intt=0,f; 4. inty,x=0; while (t) do { ri Fit y ) white (x (€) Which ofthe folowng statements is tue forthe folowing program? include int main() int xe10, y = 100 % 90; for 0: itu ai Print (x Mal y= Man, x yh return 0;> “Tho print) function is called 10 tos. ‘The program wi produce the output x= 10 y 0. “The; after the if (d=) would net produce an error. ‘The program wil not produce any output ‘The print) function is caled infinite times (0 Wich of the folowing statomentis rue about a for loop used in a C program? for loop works faster than a whis loop. ‘Althings that can be done using a for lop ean also be done using a whit op. for () implements an infrite loop. for loop can be used i we want statements in a loop to get executed atleast once, Tor loop works faster than a do-whie oop, [By Attempt the folowing questions: (2) Wete a program to print the multiplication table ofthe number antared by the user. The table should get displayed in the following form: zart=29 29°2=58 (©) According to a study, the approximate lel of intoligence of a person can be calculated using the folowing formula: l=2+y+05% \Write a program that wal produce @ table of values of |, y and x, where y vares from 1 to 6, and, for each value of y,xvarles trom 6.5 10 12.5 in steps of 05, (6) When interest compounds « tines per year at an annual rate ofr % for n years, the principal p compounds to an amount a as per the Following formuiaa=p (1+ /q) nq \Write 8 program o reed 10 sets ofp, r,n & q and calulate the corresponding & s (d) The natural logarithm can be approximated by the folowing series. x-1 (zt), (act, ape zoey et) et ee. e wal aed al & IFxis input through the keyboaro, write a program to calculate the sum of irs seven terms ofthis series (@) Wit a program to generate all Pyagarean Taplets with side length lass than or equal to 30. (1 Population of a town today fs 100000. The population has increased steadily atthe rate of 10 % per year for last 10 yaars. Write a program to
return 0; > “The output ofthis program would be: amin case 2 lamin case 3 amin default Tho output is defintely not what we expected! We didnt expect the second and tid lines in the above output. We got them because once the ‘matching case was found all he subsequent case s and the default slso got executed, IF you want that only case 2 should get executed, itis up to you te get out ofthe switch then and there by using a break statement. The following program shows how this s done. Note that there is no need for a break statement ater the default, since.on reaching the default case, the control ‘comes out of the avitch anyway. include
You might also like
Let Us Python by Yashavant Kanetkar
PDF
88% (26)
Let Us Python by Yashavant Kanetkar
429 pages
(Ebook) Programming in ANSI C by E Balagurusamy ISBN 9789351343202, 9789353165130, 935316513X, 9351343200, B07TSQN91S
PDF
No ratings yet
(Ebook) Programming in ANSI C by E Balagurusamy ISBN 9789351343202, 9789353165130, 935316513X, 9351343200, B07TSQN91S
78 pages
Brief C Late Objects 3rd Edition Cay Horstmann Download PDF
PDF
100% (2)
Brief C Late Objects 3rd Edition Cay Horstmann Download PDF
49 pages
Learning C++ (MEAP V05) - Michael Haephrati and Ruth Haephrati - Chapters 1 To 8 of 17, 2023 - Manning Publications Co. - 9781617298509 - Anna's Archive
PDF
100% (1)
Learning C++ (MEAP V05) - Michael Haephrati and Ruth Haephrati - Chapters 1 To 8 of 17, 2023 - Manning Publications Co. - 9781617298509 - Anna's Archive
589 pages
C in Depth (2nd Ed.) (Srivastava 2009-06-30) PDF
PDF
75% (16)
C in Depth (2nd Ed.) (Srivastava 2009-06-30) PDF
550 pages
100 Pattern Programs in C
PDF
100% (3)
100 Pattern Programs in C
121 pages
CP Text
PDF
No ratings yet
CP Text
546 pages
LetUsC YashwantKanetkar
PDF
No ratings yet
LetUsC YashwantKanetkar
728 pages
GATE Data Structure & Algorithm Book
PDF
No ratings yet
GATE Data Structure & Algorithm Book
12 pages
NPTEL Java Lecture Book
PDF
100% (3)
NPTEL Java Lecture Book
1,373 pages
C Balaguruswamy Ebook Free PDF
PDF
No ratings yet
C Balaguruswamy Ebook Free PDF
2 pages
C by Ashok Kamthane
PDF
100% (3)
C by Ashok Kamthane
154 pages
1000 C Programming Questions
PDF
67% (6)
1000 C Programming Questions
123 pages
Data Structures Algorithms and Software Principles in C
PDF
89% (9)
Data Structures Algorithms and Software Principles in C
774 pages
DS Through C
PDF
100% (1)
DS Through C
542 pages
Let Us C Yashwant Kanetkar PDF
PDF
100% (1)
Let Us C Yashwant Kanetkar PDF
107 pages
Complete C Programming Notes According To Syllbus
PDF
100% (8)
Complete C Programming Notes According To Syllbus
39 pages
Computer Fundamentals and Programming in C by Reema Thareja
PDF
34% (29)
Computer Fundamentals and Programming in C by Reema Thareja
2 pages
NareshIT C Language Training Notes01 Balu
PDF
No ratings yet
NareshIT C Language Training Notes01 Balu
143 pages
Programming in C
PDF
No ratings yet
Programming in C
689 pages
Relational Database Management System: Self Learning Material
PDF
No ratings yet
Relational Database Management System: Self Learning Material
213 pages
Java Handwritten Notes
PDF
No ratings yet
Java Handwritten Notes
86 pages
C Programming Notes
PDF
100% (1)
C Programming Notes
83 pages
C Programming Complete Notes
PDF
100% (6)
C Programming Complete Notes
147 pages
C Programming Notes
PDF
No ratings yet
C Programming Notes
52 pages
Syllabus BCA
PDF
No ratings yet
Syllabus BCA
59 pages
Python Programming
PDF
No ratings yet
Python Programming
97 pages
Computer Science - Class 11 Notes
PDF
100% (3)
Computer Science - Class 11 Notes
134 pages
Sumita Arora Class Xi Computer Science With Python PDF
PDF
No ratings yet
Sumita Arora Class Xi Computer Science With Python PDF
305 pages
Data Structures Using C and C++ - Y. Langsam, M. Augenstein and A. M. Tenenbaum
PDF
No ratings yet
Data Structures Using C and C++ - Y. Langsam, M. Augenstein and A. M. Tenenbaum
99 pages
Rdbms & SQL Basics
PDF
100% (1)
Rdbms & SQL Basics
33 pages
Python HandWritten Notes
PDF
No ratings yet
Python HandWritten Notes
52 pages
GQB CS PDF
PDF
100% (8)
GQB CS PDF
426 pages
12 Computerscience Eng SM 2024
PDF
No ratings yet
12 Computerscience Eng SM 2024
291 pages
C Interview Qeustions
PDF
100% (3)
C Interview Qeustions
627 pages
15MA302 Discrete Mathematics PDF
PDF
100% (1)
15MA302 Discrete Mathematics PDF
3 pages
Gate Question Bank Cs
PDF
No ratings yet
Gate Question Bank Cs
426 pages
Higher Engineering Mathematics-BS Grewal
PDF
29% (31)
Higher Engineering Mathematics-BS Grewal
1 page
C Program by Best Author
PDF
No ratings yet
C Program by Best Author
358 pages
Let Us C Y Kanitkar 01 - First Few Pages
PDF
No ratings yet
Let Us C Y Kanitkar 01 - First Few Pages
7 pages
TextBook C Programming
PDF
No ratings yet
TextBook C Programming
15 pages
TextBook C Programming PDF
PDF
No ratings yet
TextBook C Programming PDF
15 pages
Preview-9789387284678 A34429030
PDF
No ratings yet
Preview-9789387284678 A34429030
26 pages
CH 01
PDF
No ratings yet
CH 01
3 pages
Adobe Scan Jul 26, 2024
PDF
No ratings yet
Adobe Scan Jul 26, 2024
1 page
Computer Programming in C For Beginners
PDF
100% (1)
Computer Programming in C For Beginners
199 pages
C语言的科学与艺术 (英文版)
PDF
No ratings yet
C语言的科学与艺术 (英文版)
596 pages
Computer Science One
PDF
No ratings yet
Computer Science One
615 pages
Let Us C
PDF
100% (1)
Let Us C
729 pages
Computer Science
PDF
No ratings yet
Computer Science
130 pages
Om.c.to - Cpp.1992.Scan Darkcrown
PDF
No ratings yet
Om.c.to - Cpp.1992.Scan Darkcrown
436 pages
(Ebook PDF) Absolute C++ 6th Edition by Walter Savitch Download
PDF
100% (6)
(Ebook PDF) Absolute C++ 6th Edition by Walter Savitch Download
48 pages
CP Text Book
PDF
No ratings yet
CP Text Book
546 pages
Test Your Skills in C 9780070145856 Compress
PDF
No ratings yet
Test Your Skills in C 9780070145856 Compress
322 pages
Let Us Python
PDF
0% (2)
Let Us Python
429 pages
(Ebook) Programming in ANSI C by E. Balagurusamy ISBN 9781259004612, 1259004619 All Chapters Instant Download
PDF
No ratings yet
(Ebook) Programming in ANSI C by E. Balagurusamy ISBN 9781259004612, 1259004619 All Chapters Instant Download
65 pages
Computer Science I
PDF
No ratings yet
Computer Science I
200 pages
Computer Science One
PDF
No ratings yet
Computer Science One
625 pages
AtoZ of C
PDF
No ratings yet
AtoZ of C
861 pages
Himanshu PTLN
PDF
No ratings yet
Himanshu PTLN
31 pages