Previous Next

Let Us C (17th Ed.) (Yashavant Kanetkar) (z-library.sk, 1lib.sk, z-lib.sk)

Author: Yashavant Kanetkar

C/C++/C#

Learn the hand-crafted notes on C programming Key Features Strengthens the foundations, as a detailed explanation of programming language concepts are given Lucid explanation of the concept Well thought-out, fully working programming examples End-of-chapter exercises that would help you practice the skills learned in the chapter Hand-crafted "KanNotes" at the end of the each chapter that would help the reader remember and revise the concepts covered in the chapter Focuses on how to think logically to solve a problem Description The new edition of this classic book has been thoroughly revamped, but remains faithful to the principles that have established it as a favourite amongst students, teachers and software professionals round the world. "Simplicity"- that has been the hallmark of this book in not only its previous sixteen English editions, but also in the Hindi, Gujrati, Japanese, Korean, Chinese and US editions. This book doesn't assume any programming background. It begins with the basics and steadily builds the pace so that the reader finds it easy to handle advanced topics towards the end of the book. Who this book is for Students, Programmers, researchers, and software developers who wish to learn the basics of C++ programming language. Table of Contents 1. Getting Started 2. C Instructions 3. Decision Control Instruction 4. More Complex Decision Making 5. Loop Control Instruction 6. More Complex Repetitions 7. Case Control Instruction 8. Functions 9. Pointers 10. Recursion 11. Data Types Revisited 12. The C Preprocessor 13. Arrays 14. Multidimensional Arrays 15. Strings 16. Handling Multiple Strings 17. Structures 18. Console Input/Output 19. File Input/Output 20. More Issues In Input/Output 21. Operations On Bits…

📄 File Format: PDF
💾 File Size: 5.4 MB
8
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
Let Us C Seventeenth Edition Yashavant Kanetkar SEVENTEENTH REVISED AND UPDATED EDITION 2020 FIRST EDITION 2007 Reprinted 2019 Copyright © BPB Publications, India © Let Us C is a registered trademark of BPB Publications, New Delhi, under Registration No: 1135514 ISBN: 978-93-89845-686 All Rights Reserved. No part of this publication may be reproduced or distributed in any form or by any means or stored in a database or retrieval system, without the prior written permission of the publisher. LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY The Author and Publisher of this book have tried their best to ensure that the programmes, procedures and functions described in the book arc correct. However, the author and the publishers make no warranty, of any kind, expressed or implied, with regard to these programmes or the documentation contained in the book. The author and publisher shall not be liable in any event of any damages, incidental or consequential, in connection with, or arising out of the furnishing, performance or use of these programmes, procedures and functions. Produce name mentioned are used for identification purposes only and may be trademarks of their respective companies. All trademarks referred to in the book are acknowledged as properties of their respective owners. Distributors: BPB PUBLICATIONS 20, Ansari Road, Darya Ganj New Delhi-110002 Ph: 23254990/23254991 MICRO MEDIA Shop No. 5, Mahendra Chambers, 150 DN Rd. Next to Capital Cinema, V.T. (C.S.T.) Station, MUMBAI-400 001 Ph: 22078296/22078297 DECCAN AGENCIES 4-3-329, Bank Street, Hyderabad-500195 Ph: 24756967/24756400 BPB BOOK CENTRE 376 Old Lajpat Rai Market,
📄 Page 3
Delhi-110006 Ph: 23861747 Published by Manish Jain for BPB Publications, 20Ansari Road, Darya Ganj, New Delhi-110002 and Printed at Repro India Ltd, Mumbai Dedicated to baba Who couldn't be here to see this 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 in the last two and half decades. Yashavant's books and online courses have made a significant contribution in creating top-notch IT manpower in India and abroad. Yashavant's books are globally recognized and millions of students / professionals have benefitted from them. His books have been translated into Hindi, Gujarati, Japanese, Korean and Chinese languages. Many of his books are published in India, USA, Japan, Singapore, Korea and China. Yashavant is a much sought after speaker in the IT field and has conducted seminars/workshops at TedEx, IITs, NITs, IIITs and global software companies. Yashavant has been honored with the prestigious “Distinguished Alumnus Award” by IIT Kanpur for his entrepreneurial, professional and academic excellence. This award was given to top 50 alumni of IIT Kanpur who have made significant contribution towards their profession and betterment of society in the last 50 years. In recognition of his immense contribution to IT education in India, he has been awarded the “Best .NET Technical Contributor” and “Most Valuable Professional” awards by Microsoft for 5 successive years. Yashavant holds a BE from VJTI Mumbai and M.Tech. from IIT Kanpur. His current affiliations include being a Director of KICIT Pvt. Ltd. He can be reached at kanetkar@kicit.com or through http://www.kicit.com. Acknowledgments Let Us C has become an important part of my life. I have created and nurtured it for last two decades. While doing so, I have received, in addition to the compliments, a lot of suggestions from students, developers, professors, publishers and authors. So much have their inputs helped me in taking this book up to its seventeenth edition that ideally I should put their names too on the cover page. In particular, I am indebted to Manish Jain who had a faith in this book idea, believed in my writing ability, whispered the words of encouragement and made helpful suggestions from time to time. I hope every author gets a publisher who is as cooperative, knowledgeable and supportive as Manish. The previous editions of this book saw several changes and facelifts. During this course many people helped in executing programs and spotting bugs. I trust that with their collective acumen, all the programs in this book would run correctly. I value the work that they did a lot. Any errors, omissions or inconsistencies that remain are, alas, my responsibility. I thank all my family members for enduring the late nights, the clicking keyboard, and mostly for putting up with a marathon book effort. Thinking of a book cover idea is one thing, putting it into action is a different cup of tea. This edition's cover idea has been implemented by Vinay Indoria. Many thanks to him! And finally my heartfelt gratitude to the countless students who made me look into every nook and cranny of C. I want to remain in their debt. It is only because of them that Let Us C is now published from India, Singapore, USA, Japan, Dubai, Korea and China in multiple languages. Preface Let Us C has been part of learning and teaching material in most Engineering and Science Institutes round the country for years now. From last year or so, I received several suggestions that its size be pruned a bit, as many learners who learn C language in their Engineering or Science curriculum have some familiarity with it. I am happy to fulfill this request. I hope the readers would appreciate the lean look of the current edition. In one of the previous edition I had realigned the chapters in such a manner that if a C programming course is taught using Let Us C, it can be finished in 22 lectures of one hour each, with one chapter’s contents devoted to one lecture. I am happy that many readers liked this idea and reported that this has made their learning path trouble-free. A more rational reorganization of end-of-chapter Exercises in the book has also been well-received. Riding on that feedback I had introduced one more feature in the fifteenth edition—KanNotes. These are hand-crafted notes on C
📄 Page 4
programming. From the reader's emails I gather that they have turned out to be very useful to help revise their concepts on the day before the examination, viva-voce or interview. Many readers also told me that they have immensely benefitted from the inclusion of the chapter on Interview FAQs. I have improved this chapter further. The rationale behind this chapter is simple—ultimately all the readers of Let Us C sooner or later end up in an interview room where they are required to take questions on C programming. I now have a proof that this chapter has helped to make that journey smooth and fruitful. In this edition I have added a separate section titled ‘Programs’ in each chapter. It contains interesting programs based on the topics covered in the chapter. All the programs present in the book are available in source code form at www.kicit.com/books/letusc/sourcecode. You are free to download them, improve them, change them, do whatever with them. If you wish to get solutions for the Exercises in the book they are available in another book titled ‘Let Us C Solutions’. If you want some more problems for practice they are available in the book titled ‘Exploring C’. As usual, new editions of these two books have also been launched along with 17th edition of Let Us C. If you like ‘Let Us C’ and want to hear the complete video-recorded lectures created by me on C language (and other subjects like C++, VC++, C#, Java, .NET, Embedded Systems, etc.), then you can visit http://quest.ksetindia.com for more details. ‘Let Us C’ is as much your book as it is mine. So if you feel that I could have done certain job better than what I have, or you have any suggestions about what you would like to see in the next edition, please drop a line to kanetkar@kicit.com or sales@bpbonline.com Countless Indians have relentlessly worked for close to three decades to successfully establish “India” as a software brand. At times, I take secret pleasure in seeing that Let Us C has contributed in its own small little way in shaping so many careers that have made the “India” brand acceptable. Recently I was presented with “Distinguished Alumnus Award” by IIT Kanpur. It was great to figure in a list that contained Narayan Murthy, Chief Mentor, Infosys, Dr. D. Subbarao, former Governor, Reserve Bank of India, Dr. Rajeev Motwani of Stanford University, Prof. H. C. Verma, Mr. Som Mittal President of NASSCOM, Prof. Minwalla of Harvard University, Dr. Sanjay Dhande former Director of IIT Kanpur, Prof. Arvind and Prof. Sur of MIT USA and Prof. Ashok Jhunjhunwala of IIT Chennai. I think Let Us C amongst my other books has been primarily responsible for helping me get the “Distinguished Alumnus” award. What was a bit surprising was that almost all who were present knew about the book already and wanted to know from me what it takes to write a book that sells in millions of copies. My reply was—make an honest effort to make the reader understand what you have to say and keep it simple. I don't know how convincing was this answer, but well, that is what I have been doing with this book in all its previous sixteen editions. I have followed the same principle with this edition too. All the best and happy programming! Yashavant Kanetkar Table of Contents 1. Getting Started What is C? Getting Started with C Alphabets, Digits and Special Symbols Constants, Variables and Keywords Types of Constants Rules for Constructing Integer Constants Rules for Constructing Real Constants Rules for Constructing Character Constants Types of C Variables Rules for Constructing Variable Names C Keywords The First C Program
📄 Page 5
Form of a C Program Comments in a C Program What is main() ? Variables and their Usage printf() and its Purpose Compilation and Execution Receiving Input Programs Exercises KanNotes 1. C Instructions Types of Instructions Type Declaration Instruction Arithmetic Instruction Integer and Float Conversions Type Conversion in Assignments Hierarchy of Operations Associativity of Operators Control Instructions Programs Exercises KanNotes 1. Decision Control Instruction The if - else Statement Multiple Statements within if - else Nested if-else s A Word of Caution Programs Exercises KanNotes 1. More Complex Decision Making Use of Logical Operators - Checking Ranges The else if Clause Use of Logical Operators - Yes / No Problem
📄 Page 6
The ! Operator Hierarchy of Operators Revisited The Conditional Operators Programs Exercises KanNotes 1. Loop Control Instruction Loops The while Loop Tips and Traps More Operators Programs Exercises KanNotes 1. More Complex Repetitions The for Loop Nesting of Loops Multiple Initializations in the for Loop The break Statement The continue Statement The do-while Loop The Odd Loop Programs Exercises KanNotes 1. Case Control Instruction Decisions using switch The Tips and Traps switch versus if-else Ladder The goto Keyword Programs Exercises KanNotes 1. Functions What is a Function?
📄 Page 7
Why use Functions? Passing Values between Functions Order of Passing Arguments Using Library Functions One Dicey Issue Return Type of Function Programs Exercises KanNotes 1. Pointers Call by Value and Call by Reference An Introduction to Pointers Back to Function Calls Conclusions Programs Exercises KanNotes 1. Recursion Recursion Programs Exercises KanNotes 1. Data Types Revisited Integers— long, short, signed , unsigned Chars— signed, unsigned Reals— float , double, long double A Few More Issues… Storage Classes in C Automatic Storage Class Register Storage Class Static Storage Class External Storage Class A Few Subtle Issues Which to Use When
📄 Page 8
Exercises KanNotes 1. The C Preprocessor Features of C Preprocessor Macro Expansion Macros with Arguments Macros versus Functions File Inclusion Conditional Compilation if and #elif Directives Miscellaneous Directives undef Directive pragma Directive The Build Process Programs Exercises KanNotes 1. Arrays What are Arrays? A Simple Program using Array More on Arrays Array Initialization Array Elements in Memory Bounds Checking Passing Array Elements to a Function Pointers and Arrays Accessing Array Elements using Pointers Passing an Array to a Function Flexible Arrays Programs Exercises KanNotes 1. Multidimensional Arrays
📄 Page 9
Two-Dimensional Arrays Initializing a 2-D Array Memory Map of a 2-D Array Pointers and 2-D Arrays Pointer to an Array Passing 2-D Array to a Function Array of Pointers 3-D Array Programs Exercises KanNotes 1. Strings What are Strings More about Strings Pointers and Strings Standard Library String Functions strlen() strcpy() strcat() strcmp() Programs Exercises KanNotes 1. Handling Multiple Strings 2-D Array of Characters Array of Pointers to Strings Limitation of Array of Pointers to Strings Programs Exercises KanNotes 1. Structures Why use Structures? Array of Structures Intricacies of Structures
📄 Page 10
Structure Declaration Storage of Structure Elements Copying of Structure Elements Nested Structures Passing Structure Elements / Structure Variables Packing Structure Elements Uses of Structures Programs Exercises KanNotes 1. Console Input/Output Types of I/O Console I/O Functions Formatted Console I/O Functions sprintf() and sscanf() Functions Unformatted Console I/O Functions Exercises KanNotes 1. File Input/Output File Operations Opening a File Reading from a File Closing the File Counting Characters, Tabs, Spaces, … A File-Copy Program File Opening Modes String (Line) I/O in Files Text Files and Binary Files Record I/O in Files Modifying Records Low-Level File I/O A Low-Level File-Copy Program Programs Exercises KanNotes
📄 Page 11
1. More Issues In Input/Output Using argc and argv Detecting Errors in Reading/Writing Standard File Pointers I/O Redirection Redirecting the Output Redirecting the Input Both Ways at Once Exercises KanNotes 1. Operations On Bits Bit Numbering and Conversion Bit Operations One's Complement Operator Right Shift and Left Shift Operators A Word of Caution Utility of << Operator Bitwise AND, OR and XOR Operators Utility of & Operator Utility of | Operator Utility of ̂Operator The showbits() Function Bitwise Compound Assignment Operators Programs Exercises KanNotes 1. Miscellaneous Features Enumerated Data Type Uses of Enumerated Data Type Are Enums Necessary? Renaming Data Types with typedef Typecasting Bit Fields Pointers to Functions
📄 Page 12
Functions Returning Pointers Functions with Variable Number of Arguments Unions Utility of Unions The volatile Qualifier Programs Exercises KanNotes 1. Interview FAQs Appendix A - Compilation and Execution Appendix B - Precedence Table Appendix C - Chasing the Bugs Appendix D - ASCII Chart Periodic Tests I to IV, Course Tests I, II Index You cannot be great at the start, but you have to start to be great. So making a beginning is important. This chapter will help you wet your feet, before beginning a more arduous C journey… What is C? Getting Started with C Alphabets, Digits and Special Symbols Constants, Variables and Keywords Types of C Constants Rules for Constructing Integer Constants Rules for Constructing Real Constants Rules for Constructing Character Constants
📄 Page 13
Types of C Variables Rules for Constructing Variable Names C Keywords The First C Program Form of a C Program Comments in a C Program What is main() ? Variables and their Usage printf() and its Purpose Compilation and Execution Receiving Input Programs Exercises KanNotes Before we can begin to write serious programs in C, it would be interesting to find out what really is C, how it came into existence and how does it compare with other programming languages. In this chapter, we would briefly outline these issues. Four important aspects of any language are—the way it stores data, the way it operates upon this data, how it accomplishes input and output, and how it lets you control the sequence of execution of instructions in a program. We would discuss the first three of these building blocks in this chapter. What is C? C is a programming language developed at AT & T's Bell Laboratories of USA in 1972 by Dennis Ritchie. C became popular because it is simple and easy to use. An opinion that is often heard today is—“C has been already superseded by languages like C++, C# and Java, so why bother to learn C today”. I seriously beg to differ with this opinion. There are several reasons for this. These are as follows: (a) C++, C# or Java make use of a principle called Object Oriented Programming (OOP) to organize programs which offers many advantages. While using this organizing principle, you need basic programming skills. So it makes more sense to first learn C and then migrate to C++, C# or Java. Though this two-step learning process may take more time, but at the end of it, you will definitely find it worth the trouble. (b) Major parts of popular operating systems like Windows, UNIX, Linux and Android are written in C. Moreover, if one is to extend the operating system to work with new devices, one needs to write device driver programs. These programs are written exclusively in C. (c) Common consumer devices like microwave ovens, washing machines and digital cameras are getting smarter by the day. This smartness comes from a microprocessor, an operating system and a program embedded in these devices. These programs have to run fast and work in limited amount of memory. C is the language of choice while building such operating systems and programs. (d) You must have seen several professional 3D computer games where the user navigates some object, like say a spaceship and fires bullets at invaders. The essence of all such games is speed. To match this expectation of speed, the game has to react fast to the user inputs. The popular gaming frameworks (like DirectX) that are used for creating such games are written in C. I hope that these are very convincing reasons why you should adopt C as the first step in your quest for learning programming. Getting Started with C There is a close analogy between learning English language and learning C language. This is illustrated in the Figure 1.1 .
📄 Page 14
Figure 1.1 Alphabets, Digits and Special Symbols Figure 1.2 shows the valid alphabets, numbers and special symbols allowed in C. Figure 1.2 Constants, Variables and Keywords The alphabets, digits and special symbols when properly combined form constants, variables and keywords. A constant is an entity that doesn't change, whereas, a variable is an entity that may change. A keyword is a word that carries special meaning. In programming languages, constants are often called literals, whereas variables are called identifiers. Let us now see what different types of constants and variables exist in C. Types of C Constants Constants in C can be divided into two major categories: (a) Primary Constants (b) Secondary Constants These constants are further categorized as shown in Figure 1.3 . Figure 1.3 At this stage, we would restrict our discussion to only Primary constants, namely, Integer, Real and Character constants. Following Rules have been laid down for constructing these different types of constants: Rules for Constructing Integer Constants
📄 Page 15
(a) An integer constant must have at least one digit. (b) It must not have a decimal point. (c) It can be any of zero, positive or negative. If no sign precedes an integer constant, it is assumed to be positive. (d) No commas or blanks are allowed within an integer constant. (e) The allowable range for integer constants is -2147483648 to +2147483647. Ex.: +325.34 426.0 -32.76 -48.5792 Truly speaking, the range of an Integer constant depends upon the compiler. For compilers like Visual Studio, GCC, it is -2147483648 to +2147483647, whereas for compilers like Turbo C or Turbo C++, the range is -32768 to +32767. Rules for Constructing Real Constants Real constants are often called Floating Point constants. Real constants could be written in two forms—Fractional form and Exponential form. Following rules must be observed while constructing real constants expressed in fractional form: (a) A real constant must have at least one digit. (b) It must have a decimal point. (c) It can be either positive or negative. Default sign is positive. (d) No commas or blanks are allowed within a real constant. Ex.: +325.34 426.0 -32.76 -48.5792 The exponential form is usually used if the value of the constant is either too small or too large. It, however, doesn't restrict us in any way from using exponential form for other real constants. In exponential form, the real constant is represented in two parts. The part appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called exponent. Thus 0.000342 can be written in exponential form as 3.42e-4 (which in normal arithmetic means 3.42 x 10-4). Following rules must be observed while constructing real constants expressed in exponential form: (a) The mantissa part and the exponential part should be separated by a letter e or E. (b) The mantissa part may have a positive or negative sign. Default sign is positive. (c) The exponent must have at least one digit, which may be a positive or negative integer. Default sign is positive. (d) Range of real constants expressed in exponential form is -3.4e38 to 3.4e38. Ex.: +3.2e-5 4.1e8 -0.2E+3 -3.2e-5 Rules for Constructing Character Constants (a) A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. (b) Both the inverted commas should point to the left. For example, ‘A’ is a valid character constant, whereas ‘A’ is not. Ex.: ’A’ ’I’ ’5’ ’=’ Types of C Variables A particular type of variable can hold only the same type of constant. For example, an integer variable can hold only an integer constant, a real variable can hold only a real constant and a character variable can hold only a character constant. Hence there are as many types of variables in C, as the types of constants in it. In any C program many calculations are done. The results of these calculations are stored in some cells (locations) of computer’s memory. To make the retrieval and usage of these values easy, the memory cells are given names. Since the value stored in each location may change, the names given to these locations are called variable names.
📄 Page 16
The rules for constructing different types of constants are different. However, for constructing variable names of all types, the same set of rules applies. These rules are given below. Rules for Constructing Variable Names (a) A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some compilers allow variable names whose length could be up to 247 characters. Do not create unnecessarily long variable names as it adds to your typing effort. (b) The first character in the variable name must be an alphabet or underscore (_). Ex.: siint pope89 avg basicsalary We should always create meaningful variable names. For example, while calculating simple interest, we should construct variable names like prin , roi , noy to represent Principle, Rate of interest and Number of years, rather than arbitrary variables like a , b , c . Rules for creating variable names remain same for all the types of primary and secondary variables. So to help differentiate between variables, it is compulsory to declare the type of any variable that we wish to use in a program. This type declaration is done as shown below. Ex.: int si, m_hra; float bassal; char code; C Keywords Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). There are only 32 keywords available in C. Figure 1.4 gives a list of these keywords. Figure 1.4 The keywords should not be used as variable names. However, some C compilers allow you to construct variable names that exactly resemble the keywords. Compiler vendors provide more keywords apart from the ones given in Figure 1.5. Though it has been suggested by the ANSI committee that every such compiler-specific keyword should be preceded by two underscores (as in _ asm ), not every vendor follows this rule. The First C Program Once armed with the knowledge of variables, constants and keywords, the next logical step is to combine them to form instructions. However, instead of this, we would write our first C program now. Once we have done that we would see in detail the instructions that it made use of. The first program is very simple. It calculates simple interest for a set of values representing principal, number of years and rate of interest. /* Calculation of simple interest */ /* Author: gekay Date: 25/03/2020 */ include int main() {
📄 Page 17
int p, n; float r, si; p = 1000; n = 3; r = 8.5; /* formula for simple interest */ si = p * n * r / 100; printf (“%f\n”, si); return 0; } Let us now understand this program in detail. Form of a C Program Form of a C program indicates how it has to be written. There are certain rules about the form of a C program that are applicable to all C programs. These are as under: (a) Each instruction in a C program is written as a separate statement. (b) The statements in a program must appear in the same order in which we wish them to be executed. (c) Blank spaces may be inserted between two words to improve the readability of the statement. (d) All statements should be in lower case letters. (e) Every C statement must end with a semicolon ( ;) . Thus ; acts as a statement terminator. (f) A C statement can be written anywhere in a given line. That's why it is often called a free-form language. (g) Usually each line contains one statement. However, you can write multiple statements in one line, provided each statement is terminated with a;. Comments in a C Program Comments are used in a C program to clarify either the purpose of the program or the purpose of some statement in the program. It is a good practice to begin a program with a comment indicating the purpose of the program, its author and the date on which the program was written. Here are a few tips for writing comments in a C program: (a) Comments can be in small case, capital or a combination. They should be enclosed within /* */. Thus, the first two statements in our program are comments. (b) Sometimes it is not very obvious as to what a particular statement in a program accomplishes. At such times, a comment can be used to mention the purpose of the statement(s). For example, /* formula for simple interest */ si = p * n * r / 100; (c) Any number of comments can be written at any place in the program. So a comment can be written before the statement, after the statement or within the statement as shown below. /* formula */ si = p * n * r / 100; si = p * n * r / 100; /* formula */ si = p * n * r / /* formula */ 100; (d) Comments cannot be nested. This means one comment cannot be written inside another comment. So following comment is invalid.
📄 Page 18
/* Cal of SI /* Author: gekay date: 25/03/2020 */ */ (e) A comment can be split over more than one line, as in, /* This comment has three lines in it */ (f) ANSI C permits comments to be written in another way as follows: // Calculation of simple interest // Formula What is main() ? main() forms a crucial part of any C program. Let us understand its purpose as well as its intricacies. (a) main() is a function. It is a container for a set of statements. A C program may have multiple functions. If it contains only one function its name has to be main() . All statements that belong to main() are enclosed within a pair of braces {}. (b) Like functions in a calculator, functions in C also return a value. main() function always returns an integer value, hence there is an int before main() . It is known as return type of the function. The integer value that we are returning is 0. 0 indicates success. If statements in main() fail to do their intended work, we can return a non-zero number from main() . This would indicate failure. (c) The way to watch the value returned by main() varies from one compiler to another, as shown below. Turbo C, Turbo C++ - Alt C | Information Visual Studio - $ReturnValue in Watch Window of Debugger Linux - echo $? at command prompt after execution of the program (d) Some compilers like Turbo C/C++ even permit us to return nothing from main() . In such a case we should precede it with the keyword void . But this is the non-standard way of writing the main() function. We would discuss functions and their working in detail in Chapter 8 . Variables and their Usage Let us understand the significance of constants and variables with reference to our program. (a) Any variable used in the program must be declared before it is used. For example, int p, n; /* declaration */ float r, si; /* declaration */ si = p * n * r / 100; /* usage */ (b) In the statement, si = p * n * r / 100; and / are the arithmetic operators. The arithmetic operators available in C are + , - , * and / . printf() and its Purpose C does not contain any keyword to display output on the screen. All output to screen is achieved using readymade library functions like printf() . Let us understand this function with respect to our program. (a) Once the value of si is calculated it needs to be displayed on the screen. We have used printf() to do so. (b) To be able to use the printf() function, it is necessary to use #include at the beginning of the program. #include is a preprocessor directive. Its purpose will be clarified in Chapter 8 . (c) The general form of printf() function is,
📄 Page 19
(c) The general form of printf() function is, printf (“”, ); can contain, %f for printing real values %d for printing integer values %c for printing character values In addition to format specifiers like %f , %d and %c , the format string may also contain any other characters. These characters are printed as they are when printf() is executed. (d) Given below are some more examples of usage of printf() function: printf (“%f”, si); printf (“%d %d %f %f”, p, n, r, si); printf (“Simple interest = Rs. %f”, si); printf (“Principal = %d\nRate = %f”, p, r); The output of the last statement would look like this… Principal = 1000 Rate = 8.500000 The output is split over two lines because of newline character ‘\n’. It sends the cursor to next line. It is one of the several Escape Sequences available in C. These are discussed in detail in Chapter 18 . (e) printf() can print values of variables as well as result of an expressions like 3, 3 + 2, c and a + b * c - d as shown below. printf (“%d %d %d %d”, 3, 3 + 2, c, a + b * c - d); Note that 3 and c also represent valid expressions. Compilation and Execution Once you have written the program, you need to type it and instruct the machine to execute it. Two other programs are needed to do this— Editor and Compiler. Editor 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 from these two, there are other programs which you may need to improve your programming efficiency—Preprocessor, Linker and Debugger. Working with each one of them individually is a tedious job. Hence, often all these are bundled together with a layer of GUI on top of them. GUI makes using these programs easier for you. This bundle is often called Integrated Development Environment (IDE). There are many IDEs available. Each is targeted towards different operating systems and microprocessors. Details of which IDE to use, from where to download it, how to install and use it are given in Appendix A. Please go through this appendix and install the right IDE on your machine before you try any program in this book. Receiving Input In our first C program we assumed the values of p , n and r to be 1000, 3 and 8.5. Every time we run the program, we would get the same value for simple interest. If we want to calculate simple interest 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 is not general enough to calculate simple interest for any set of values without being required to make changes in the program. This is not a good practice. To make the program general, the program itself should ask the user to supply the values of p , n and r through the keyboard during execution. This can be achieved using a function called scanf() . It helps us receive input values them from the keyboard. This is illustrated in the program given below. /* Calculation of simple interest */
📄 Page 20
/* Author gekay Date 25/03/2020 */ include int main() { int p, n; float r, si; printf (“Enter values of p, n, r”); scanf (“%d %d %f”, &p, &n, &r); si = p * n * r / 100; printf (“%f\n”, si); return 0; } The first printf() outputs the message ‘Enter values of p, n, r’ on the screen. Here we have not used any expression in printf() which means that using expressions in printf() is optional. Note the use of ampersand ( & ) before the variables in the scanf() function is necessary. & is the ‘Address of’ operator. It gives the location number (address) used by the variable in memory. When we say &a , we are telling scanf() at which memory location should it store the value supplied by the user from the keyboard. The detailed working of the & operator would be taken up in Chapter 9 . Note that a blank, a tab or a new line must separate the values supplied to scanf() . A blank is created using a spacebar, tab using the Tab key and new line using the Enter key. This is shown below. Ex.: Three values separated by blank: 1000 5 15.5 Ex.: Three values separated by tab: 1000 5 15.5 Ex.: Three values separated by newline: 1000 5 15.5 Problem 1.1 Ramesh's basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary. Program /* Calculate Ramesh’s gross salary */ include int main()
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now

Recommended for You

Loading recommended books...
Failed to load, please try again later
Back to List