Page 1 :
Unit I-Planning the Computer Program, , Concept of Problem solving:Problem solving is the act of defining a problem; determining the cause of the, problem; identifying, prioritizing, and selecting alternatives for a solution; and, implementing a solution., , Define the problem, Diagnose the situation so that your focus is on the problem, not just its symptoms., Helpful problem-solving techniques include using flowcharts to identify the, expected steps of a process and cause-and-effect diagrams to define and, analyze root causes., The sections below help explain key problem-solving steps. These steps support, the involvement of interested parties, the use of factual information, comparison of, expectations to reality, and a focus on root causes of a problem. You should begin, by:, , , Reviewing and documenting how processes currently work (i.e., who does what,, with what information, using what tools, communicating with what organizations, and individuals, in what time frame, using what format).
Page 2 :
, , Evaluating the possible impact of new tools and revised policies in the development, of your "what should be" model., 2. Generate alternative solutions, Postpone the selection of one solution until several problem-solving alternatives, have been proposed. Considering multiple alternatives can significantly enhance, the value of your ideal solution. Once you have decided on the "what should be", model, this target standard becomes the basis for developing a road map for, investigating alternatives. Brainstorming and team problem-solving techniques are, both useful tools in this stage of problem solving., Many alternative solutions to the problem should be generated before final, evaluation. A common mistake in problem solving is that alternatives are evaluated, as they are proposed, so the first acceptable solution is chosen, even if it’s not the, best fit. If we focus on trying to get the results we want, we miss the potential for, learning something new that will allow for real improvement in the problemsolving process., 3. Evaluate and select an alternative, Skilled problem solvers use a series of considerations when selecting the best, alternative. They consider the extent to which:, , , , , , , A particular alternative will solve the problem without causing other unanticipated, problems., All the individuals involved will accept the alternative., Implementation of the alternative is likely., The alternative fits within the organizational constraints., 4. Implement and follow up on the solution, Leaders may be called upon to direct others to implement the solution, "sell" the, solution, or facilitate the implementation with the help of others. Involving others, in the implementation is an effective way to gain buy-in and support and minimize, resistance to subsequent changes., Regardless of how the solution is rolled out, feedback channels should be built into, the implementation. This allows for continuous monitoring and testing of actual, events against expectations. Problem solving, and the techniques used to gain, clarity, are most effective if the solution remains in place and is updated to respond, to future changes.
Page 3 :
Problem Definition:Any question or matter involving doubt, uncertainty, or difficulty. a question, proposed for solution or discussion., Problem analysis:Problem analysis therefore involves identifying the overriding problem and, establishing the causes and effects related to that problem., , Algorithm:, In mathematics and computer science, an algorithm is a finite sequence, of well-defined, computer-implementable instructions, typically to solve a class of, problems or to perform a computation. In general step by step solution of a given, problem., Algorithm is a step-by-step procedure, which defines a set of instructions to, be executed in a certain order to get the desired output. Algorithms are generally, created independent of underlying languages, i.e. an algorithm can be implemented, in more than one programming language. ALGORITHM: The word “algorithm”
Page 4 :
relates to the name of the mathematician Al-khowarizmi, which means a procedure, or a technique. Software Engineer commonly uses an algorithm for planning and, solving the problems. An algorithm is a sequence of steps to solve a particular, problem., e.g., Problem:To add two numbers., Step 1:Start, Step2:Take first number i.e. a, Step 3:Take second number i.e. b, Step4:Add both numbers i.e. c=a+b, Step5:Display value of c, Step 6:stop, Characteristics of an Algorithm, Not all procedures can be called an algorithm. An algorithm should have the, following characteristics −, , , , , , , , , Unambiguous − Algorithm should be clear and unambiguous. Each of its, steps (or phases), and their inputs/outputs should be clear and must lead to, only one meaning., Input − An algorithm should have 0 or more well-defined inputs., Output − An algorithm should have 1 or more well-defined outputs, and, should match the desired output., Finiteness − Algorithms must terminate after a finite number of steps., Feasibility − Should be feasible with the available resources., Independent − An algorithm should have step-by-step directions, which, should be independent of any programming code., , Advantages of algorithm, • It is a step-wise representation of a solution to a given problem, which makes it, easy to understand., • An algorithm uses a definite procedure., • It is not dependent on any programming language, so it is easy to understand for, anyone even without programming knowledge., • Every step in an algorithm has its own logical sequence so it is easy to debug
Page 5 :
FLOWCHART: The first design of flowchart goes back to 1945 which was, designed by John Von Neumann. Unlike an algorithm, Flowchart uses different, symbols to design a solution to a problem. It is another commonly used, programming tool., By looking at a Flowchart one can understand the operations and sequence of, operations performed in a system. Flowchart is often considered as a blueprint of a, design used for solving a specific problem., Advantages of flowchart:, • Flowchart is an excellent way of communicating the logic of a program., • Easy and efficient to analyze problem using flowchart., • During program development cycle, the flowchart plays the role of a blueprint,, which makes program development process easier., • After successful development of a program, it needs continuous timely, maintenance during the course of its operation. The flowchart makes program or, system maintenance easier., • It is easy to convert the flowchart into any programming language code.
Page 6 :
Flowchart is diagrammatic /Graphical representation of sequence of steps to solve, a problem. To draw a flowchart following standard symbols are use, Symbols Used In Flowchart, , Symbol, , Description, , Purpose, , Indicates the flow of logic by connecting, symbols., , Flow line, , Represents the start and the end of a, flowchart., , Terminal(Stop/Start), , Input/ Output, , Used for input and output operation., , Processing, , Used for arithmetic operations and datamanipulations., , Decision, , Used for decision making between two or, more alternatives., , On-page Connector, e.g, Draw flowchart to add two numbers., Start, , Take input, , Used to join different flowline
Page 7 :
What is a Bug?, The program contains a defect in the source code, either due to a design, misunderstanding or an implementation mistake. This defect is displayed as a, runtime failure. The program could: crash with a memory error or, “segmentation fault” return an incorrect result have unintended side-effects like, corrupting persistent storage., The art of debugging arises because defects do not arrive predictably. The, program may require specific inputs to trigger a bug Undefined or, implementation-defined behaviour may cause it to only crash on a particular, operating system or hardware architecture The issue may require separate runs, and many hours (or months!) of execution time to clear., What is Debugging?, Debugging is a methodical process of finding and reducing the number of bugs (or, defects) in a computer program, thus making it behave as originally expected., There are two main types of errors that need debugging:, 1) Compile-time: These occur due to misuse of language constructs, such as syntax, errors. Normally fairly easy to find by using compiler tools and warnings to fix, reported problems. gcc -Wall -pedantic -c main.c, 2) Run-time: These are much harder to figure out, as they cause the program to, generate incorrect output (or “crash”) during execution., The Runtime Debugging Process, A typical lifecycle for a C/C++ bug is:, 1.A program fails a unit test included with the source code, or a bug is, reported by a user, or observed by the programmer., 2. Given the failing input conditions, a programmer debugs the program until, the offending source code is located., 3.The program is recompiled with a source code fix and a regression test is, run to confirm that the behaviour is fixed.
Page 8 :
Types of errors in programming:1. Syntax Errors, Just like human languages, computer languages have grammar rules. But while, humans are able to communicate with less-than-perfect grammar, computers can’t, ignore mistakes, i.e. syntax errors., For example, let’s say the correct syntax for printing something, is print('hello') , and we accidentally forget one of the parentheses while, coding. A syntax error will happen, and this will stop the program from running., , 2. Logic Errors, Logic errors can be the hardest to track down. Everything looks like it is working;, you have just programmed the computer to do the wrong thing. Technically the, program is correct, but the results won’t be what you expected., A famous example happened in 1999 when NASA lost a spacecraft due to, miscalculations between English and American units. The software was coded one, way but needed to work another., 3. Compilation Errors, Some programming languages require a compilation step. Compilation is where, your high-level language converts into a lower-level language that the computer can, understand better. A compilation or compile-time error happens when the compiler, doesn’t know how to turn your code into the lower-level code., In our syntax error example, if we were compiling print('hello' , the, compiler would stop and tell us it doesn’t know how to convert this into a lowerlevel language because it expected a ) after the ' .
Page 9 :
4. Runtime Errors, Runtime errors happen as a user is executing your program. The code might work, correctly on your machine, but on the webserver, there might be a different, configuration, or it might be interacted with in a way that could cause a runtime, error., Runtime errors are particularly annoying because they directly impact your end user., A lot of these other errors will happen when you’re at your computer working on the, code. These errors occur when the system is running and can stop someone from, doing what they need to do., 5. Arithmetic Errors, An arithmetic error is a type of logic error but involves mathematics. A typical, example when performing a division equation is that you cannot divide by zero, without causing an issue. Very few people would write 5 / 0, but you might not, think that the size of something in your system might sometimes be zero, which, would lead to this type of error., , 6. Resource Errors, The computer that your program is on will allocate a fixed amount of resources to, the running of it. If something in your code forces the computer to try and allocate, more resources than it has, it can create a resource error., Resource errors can be hard to chase down because the machine you’re developing, on can often be higher quality than the servers running your code. Resource errors, are an example of a type of error in programming that might be something for the, operations team to fix rather than developers., Documentation:Any written text, illustrations or video that describe a software or program to its, users is called program or software document. User can be anyone from a, programmer, system analyst and administrator to end user. At various stages of, development multiple documents may be created for different users. In, fact, software documentation is a critical process in the overall software, development process.
Page 10 :
In modular programming documentation becomes even more important because, different modules of the software are developed by different teams. If anyone other, than the development team wants to or needs to understand a module, good and, detailed documentation will make the task easier., These are some guidelines for creating the documents −, , , Documentation should be from the point of view of the reader, , , , There should be no repetition, , , , Industry standards should be used, , , , Documents should always be updated, Advantages of Documentation, , These are some of the advantages of providing program documentation −, , , Keeps track of all parts of a software or program, , , , Maintenance is easier, , , , Programmers other than the developer can understand all aspects of software, , , , Improves overall quality of the software, , , , Assists in user training, Example Documents, , A software can have many types of documents associated with it. Some of the, important ones include −, , , User manual − It describes instructions and procedures for end users to use, the different features of the software., , , , Operational manual − It lists and describes all the operations being carried, out and their inter-dependencies., , , , Technical Documentation − It is a documentation of actual programming, components like algorithms, flowcharts, program codes, functional modules,, etc., , , , List of Known Bugs − Every software has bugs or errors that cannot be, removed because either they were discovered very late or are harmless or, will take more effort and time than necessary to rectify. These bugs are listed, with program documentation so that they may be removed at a later date., Also they help the users, implementers and maintenance people if the bug is, activated.
Page 11 :
Introduction to Linux Operating System, , Last Updated: 09-09-2020, Linux is a community of open-source Unix like operating systems that are based on, the Linux Kernel. It was initially released by Linus Torvalds on September 17, 1991., It is a free and open-source operating system and the source code can be modified and, distributed to anyone commercially or noncommercially under the GNU General, Public License., Initially, Linux was created for personal computers and gradually it was used in other, machines like servers, mainframe computers, supercomputers, etc. Nowadays, Linux, is also used in embedded systems like routers, automation controls, televisions, digital, video recorders, video game consoles, smartwatches, etc. The biggest success of, Linux is Android(operating system) it is based on the Linux kernel that is running on, smartphones and tablets. Due to android Linux has the largest installed base of all, general-purpose operating systems. Linux is generally packaged in a Linux, distribution., Architecture of Linux, Linux architecture has the following components:
Page 12 :
Kernel: Kernel is the core of the Linux based operating system. It virtualizes the, common hardware resources of the computer to provide each process with its, virtual resources. This makes the process seem as if it is the sole process running, on the machine. The kernel is also responsible for preventing and modifying, clashes between different processes., 1. System Library: Is the special types of functions that are used to implement, the functionality of the operating system., 2. Shell: It is an interface to the kernel which hides the complexity of the kernel’s, functions from the users. It takes commands from the user and executes the, kernel’s functions., 3. Hardware Layer: This layer consists all peripheral devices like RAM/ HDD/, CPU etc., 4. System Utility: It provides the functionalities of an operating system to the, user., Advantages of Linux, , , , , , , , , , , , , , , , , The main advantage of Linux, is it is an open-source operating system. This, means the source code is easily available for everyone and you are allowed to, contribute, modify and distribute the code to anyone without any permissions., In terms of security, Linux is more secure than any other operating system. It, does not mean that Linux is 100 percent secure it has some malware for it but is, less in danger than any other operating system. So, it does not require any antivirus software., The software updates in Linux are easy and frequent., Various Linux distributions are available so that you can use them according to, your requirements or according to your taste., Linux is freely available to use on the internet., It has large community support., It provides high stability. It rarely slows down or freezes and there is no need to, reboot it after a short time., It maintain the privacy of the user., The performance of the Linux system is much higher than other operating, systems. It allows a large number of people to work at the same time and it, handles them efficiently., It is network friendly., The flexibility of Linux is high. There is no need to install a complete Linux, suit; you are allowed to install only required components., Linux is compatible with a large number of file formats.
Page 13 :
, , , It is fast and easy to install from the web. It can also install on any hardware, even on your old computer system., It performs all tasks properly even if it has limited space on the hard disk., , Disadvantages of Linux, , , , It is not very user-friendly. So, it may be confusing for beginners., It has small peripheral hardware drivers as compared to windows., Introduction, , In order to communicate any idea, thought, instruction or information,, humans make use of spoken language. The fact is that you have just, understood the very first sentence of this chapter all due to that. However,, spoken languages are not understood by machines. Not only machines but, also other living creatures of this planet do not understand spoken, languages. Hence, they need some different kind of a language. As an, example, a ring master in circus uses the movement and sound of a whip to, control the beast. Similarly, machines like cars understand mechanical, motions such as the movement of steering wheel, brake pedal and so on, to, perform specific actions. This means whenever some instruction is to be, communicated to any living or non-living thing, we need some kind of a, specific language that is understood by it. As such, computer is not an, exception., In order to communicate instructions to a computer, humans need a, language which we call a programming language. Like we have a variety of, spoken languages, we also have a variety of programming languages., However, computers nowadays are digital and only understand the language, of 0‘s and 1‘s. Therefore, to instruct a computer to perform some specific, task we have to put these 0‘s and 1‘s in a particular sequence. This kind of a, programming language is called Machine Language. A set of these, instructions is called a Program like a set of dialogs in a spoken language is, called a Conversation. Communicating instructions to a digital computer in, machine language is difficult, error prone, non-portable and so on. To, overcome some of its drawbacks (specifically difficulty) an assembly, language can be used which actually uses mnemonics for these strings of, 1‘s and 0‘s. Indeed assembly language is not understood directly by a
Page 14 :
computer and hence a translator (which is called assembler) is required to, convert these mnemonics into binary strings. A translator converts a source, program written in some programming language into executable machine, code. Machine and Assembly language, both called low-level, programming languages, are highly machine dependent, error-prone,, difficult to understand and learn, and so on. A high-level programming, language is machine independent, less error-prone, easy to understand and, learn, and so on. In this language, the statements (or instructions) are, written using English words and a set of familiar mathematical symbols, which makes it easier to understand and learn, and is thus less error-prone., Furthermore, the language is machine independent and hence can be ported, to other machines. The high-level programming languages can be further, classified, , into, , procedural,, , non-procedural, , and, , problem, , oriented, , languages. This text discusses the vocabulary, grammatical rules and, technical aspects of a high-level procedural language called C. It must be, noted that all high-level languages also need a translator to convert it into, machine language. Depending upon whether the translation is made to, actual machine code or some intermediate code, the translator is called a, Compiler or an Interpreter respectively. C programming language uses a, compiler to convert the instructions into actual machine code. Some, researchers also classify C language as a middle level language. The reason, behind this is that assembly code can also be mixed with C code., This lesson will look into the motivation behind learning C language, unveil, its history of development, highlight its features, and point out advantages, and disadvantages of C programming language., 1.1, , Why learn C?, , One may argue that if there is plethora of programming languages available, then what makes C, language so special? There are two answers to this question. First, C language has been used by, programmers for past 30-40 years to develop every kind of utility. This means the language is, well understood, the issues with the language have been completed eradicated, a lot of the, principles used in C show up in a lot of other languages, and so on. Second, C combines, portability across various computer architectures as provided by any other high-level language, while retaining most of the control of the hardware as provided by assembly language. It is a, stable and mature language whose features are unlikely to disappear for a long time
Page 15 :
1.2, , History of C language, , In 1965, Bell Telephone Laboratories, General Electric Company and, Massachusetts Institute of Technology where working together to develop a, new operating system called MULTICS., In 1969, Bell Laboratories ended its participation in the project. However,, the participating members of Bell Labs, mainly Ken Thompson and Dennis, Ritchie, still had an intention to create such kind of an OS which finally, matured into UNIX operating system., After it early success in 1970, Ken Thompson set out to implement a, FORTRAN compiler for the new system, but instead came up with the, language B. B Language was influenced by Richard Martins BCPL language, which was type-less and interpretive. Hence, both BCPL and B language had, some performance drawbacks., In 1972, in an effort to add ―types‖ and definition of data structures to B, language and use compiler instead of interpreter, Dennis Ritchie came up, with a new B language called C language., Just like natural languages, programming languages also change. The, original specification of the C language (as devised by Dennis Richie), together with close variations is sometimes known as Old-style C or, Traditional C., , However, in 1988 ANSI (American National Standards, , Institute) published a new specification of the language which has become, an international standard which is accepted by all compilers. It is known as, ANSI C. ANSI C is mostly a superset (i.e. provides additional functionality), over Old-style C., 1.3, , Features of C language, , C language has a rich set of features. These include:, 1. There are a small, fixed number of keywords, including a full set of control flow, primitives. This means there is not much vocabulary to learn., 2. C is a powerful, flexible language that provides fast program execution and imposes few, constraints on the programmer.
Page 16 :
3. It allows low level access to information and commands while still retaining the, portability and syntax of a high level language. These qualities make it a useful language, for both systems programming and general purpose programs., 4. Another strong point of C is its use of modularity. Sections of code can be stored in, libraries for re-use in future programs., 5. There are a large number of arithmetical, relational, bitwise and logical operators., 6. All data has a type, but implicit conversions can be performed. User-defined and, compound data types are possible., 7. Complex functionality such as I/O, string manipulation, and mathematical functions are, consistently delegated to library routines., 8. C is a Structured Compiled language widely used in the development of system, software., 1.4, , Advantages of C language, , C language has in-numerous advantages. The important advantages of C language are described, as follows:, 1. Easy to Understand: C language is a structured programming language. The program, written in C language is easy to understand and modify., 2. Middle Level Language: C language has combined features of low level language (such as, assembly language) and some of high level language. It is, therefore, sometimes C, language is also referred to as middle level language. Most of the problems that can be, solved using assembly language can also be solved in C language., 3. Machine Independent: Program written in C language is machine independent. It means, that a program written on one type of Computer system can be executed on another, type of Computer., 4. Built in Functions: C language has a large number of built in functions. The programmer, uses most of these built in functions for writing source program, instead of writing its, own code., 5. Hardware Control: Like assembly language, the programmer can write programs in C to, directly access or control the hardware components of the computer system., 6. Easy to learn and use: C language is easy to learn and to write program as compared to, low level languages such as assembly language.
Page 17 :
7. Basis for C++: Today, the most popular programming is C+. C is the basis for C++. The, program structure of C is similar to C++. The statements, commands (or functions) and, methodologies used in C are also available in C++. Thus learning C is a first step towards, learning C++., 8. Modularity: C is a structured programming language. The programmer can divide the, logic of program into smaller units or modules. These modules can be written and, translated independently. Including, 1.5, , Disadvantages of C language, , Though C language has rich set of features and have enormous advantages, however it suffers, from some disadvantages. These include:, 1. C does not have OOPS feature., 2. There is no runtime checking in C language., 3. There is no strict type checking., 4. C doesn't have the concept of namespace., 5. C imposes few constraints on the programmer. The main area this shows up is in C's lack, of type checking. This can be a powerful advantage to an experienced programmer but a, dangerous disadvantage to a novice., 1.6 Turbo C Compiler, Though there exist many C compilers which follow standard specification of, C language, the most and commonly used C compiler is Turbo C compiler, (TC). Turbo C compiler is the product of Borland International Inc. and runs, on DOS and Windows platform. In addition to being widely used, the TC has, been fully understood and most of the C books have been written keeping, TC in view. This text also discusses the C programming language keeping in, view its implementation in Turbo C. Specifically; the text considers TC++, 3.0., TC++3.0 can be downloaded from web. By default, it gets installed in C:, drive of your computer under the name TC. Within this folder, many, subfolders and files exist. The most important sub-folder called BIN contains, all the necessary binaries (executable) of the TC. To start TC, we have to
Page 18 :
execute TC.EXE file in BIN subfolder. After execution, TC IDE pops up. The, IDE (Integrated Development Environment) is a tool that allows a C, programmer to write a program, compile it, execute and debug it. Figure 1.1, shows the screen shot of TC++3.0 IDE., , Figure 1.1: Screenshot of TC++3.0 IDE, We will assume that you know how to create, open, save, edit, etc. a file using an editor., However, it must be noted that C programs should be given extension .c while saving. IDE, provide various commands to compile, run and debug the program. Table 1.1 shows the most, important commands that you will be using., Command, , Shortcut Key, , Compile a program, , ALT + F9, , Run a program, , CTRL + F9, , Check previous output, , ALT + F5, , Save changes, , F2, , Trace Execution, , F7, , Table 1.1: Some commonly used commands of IDE.
Page 19 :
Introduction, Every language has a set of symbols that are used to create tokens or, words. These tokens are used to create statements. A statement is a, meaningful, , dialog., , Finally,, , these, , statements, , are, , used, , to, , create, , a, , conversation (Program). However, every language has a different set of, symbols and has some different set of rules to create tokens, statements, and conversation. As an example, English language has 26 lower-case and, 26 upper-case symbols called Alphabets. These alphabets are used to create, tokens like nouns, verbs and so on. These tokens are used to create, statements called Sentences using some grammatical rules. Similarly, every, programming language like C has a set of characters that are used to create, tokens which in turn are used to create meaningful statements. These, statements constitute a program. Note that certain rules are to be followed, to create tokens and compose statements using these tokens. These rules, are called Syntax Rules or Grammar. The character set, tokens and syntax, rules of a programming language together are called Language Constructs., In this lesson, we will discuss the language constructs of C programming, language., 2.1, , Character Set, , The character set of C comprises of wide range of symbols that can be used to create tokens., These symbols are available on all modern personal computers. These characters can be, grouped into following categories:, 1. Letters, 2. Digits, 3. Special Characters, 4. White Spaces, Table 2.1 shows the complete set of characters supported by C language., Letters, Upper Case A to Z, , Digits, 0 to 9, , White Spaces, Blank Space
Page 20 :
Lower Case a to z, , Tab, Carriage Return, Line Feed, Special Characters, , , Comma, , . Period, , ; Semicolon, , : Colon, , ? Question Mark, , ‘ Apostrophe, , “ Quotation Mark, , ! Exclamation Mark, , | Vertical Bar, , / Slash, , \ Backslash, , ~ Tilde, , _ Underscore, , $ Dollar Sign, , % Percent Sign, , # Number Sign, , & Ampersand, , ^ Caret, , * Asterisk, , - Minus Sign, , + Plus Sign, , < Opening Angle, , > Closing Angle, , ( Left Parenthesis, , ) Right Parenthesis, , [ Left Bracket, , ] Right Bracket, , { Left Brace, , } Right Brace, , Table 2.1, 2.2, , C Character Set, , Tokens, , In C language the smallest unit of a program is called Token. Tokens are, created using the C character set. These tokens are delimited from each, other by white spaces just like words in English language are delimited by
Page 21 :
white spaces. The Syntax Rule of the C language dictates how to create, tokens in C and how to use these tokens to create meaningful statements. C, language has 5 types of tokens as shown in Figure 2.1., , Figure 2.1: Classification of Tokens in C Language, 2.3, , Keywords, , Keywords are those tokens or words whose meaning are already defined, within the C language and cannot be changed. As an analogy, in English, language the meaning of verbs, adjectives, common nouns, and so on is, pre-defined and can‘t be changed. These tokens of English language are its, keywords. Similarly, in C language some tokens are reserved and have some, pre-defined meaning. These keywords serve as the basic building blocks for, program statements. The number of keywords present in C language is 32, as per ANSI standard. Table 2.2 shows this list of keywords., auto, , double, , int, , struct, , break, , Else, , long, , switch
Page 22 :
case, , Enum, , register, , typedef, , char, , Extern, , return, , union, , const, , float, , short, , unsigned, , continue, , for, , signed, , void, , default, , goto, , sizeof, , volatile, , do, , if, , static, , while, , Table 2.2: Keywords in C language, 2.4, , Identifiers, , Identifiers are user-defined tokens used to name variables, functions, etc., An identifier consists of a sequence of letters and digits. Underscore is also, used. However, the first character of the identifier should a letter or an, underscore. Though there is logically no restriction on the length of the, number of characters in an identifier, however for some compilers only 31, characters are significant to differentiate between 2 or more identifiers. It, should be noted that identifier is case sensitive. This means an identifier, ―test‖ is different from another identifier ―teSt‖. Table 2.3 shows some valid, and invalid identifiers along with the reason., Identifier Name, , Valid, , First_name, , Yes, , extern, , No, , Money$, , No, , extern_name, , Yes, , Reason, , extern is a keyword, Only Alphabets, Digits, and Underscore are, valid
Page 23 :
First name, , No, , No space is allowed, , Table 2.3: Examples of some valid and invalid identifiers, 2.5, , Constants, , Constants are those tokens in C language whose value is fixed and does not, change during the execution of a program. There are various types of, constants in C., 2.5.1 Integer Constants, These constants refer to a sequence of digits. Any representation can be, used to specify an integer constant. Table 2.4 shows ways to specify an, integer constant, whose value is 1234 in decimal number system, in, different number systems., Representation, , Value, , Decimal, , 1234, , Hexadecimal, , 0x4D2, , Octal, , 02322, , Table 2.4: Representation of an integer in different number systems, 2.5.2 Real Constants, These constants refer to those numbers which contain fractional parts like, 12.34. Such numbers are called real or floating point numbers. A real, constant can also be expressed in exponential or scientific notation. As an, example, 12.34 can also be expressed as 1234E-2. In this form, the real, number is expressed in terms of mantissa and exponent. The mantissa is, either a real number or an integer and exponent is an integer number. Both, can have an optional plus or minus sign. The letter E separating the, mantissa and the exponent can be written in lowercase also., 2.5.3 Character Constants
Page 24 :
These constants refer to those tokens which contain a single character, enclosed within a pair of single quotes like ‗W‘. The character may be a, letter, number, special character or blank space. As an example, ‗5‘ is a, character constant while as 5 is an integer constant. Similarly, 5.0 can be, treated as real constant., Character constants are printable characters which are stored in memory as, their ASCII (American Standard Code for Information Interchange) code., Figure 2.2 shows the complete ASCII table., 2.5.4 String Constants, These constants refer to those tokens which contain a string of characters, enclosed within a pair of double quotes. The characters may be letters,, numbers, special characters and blank space. Examples include ―Hello, World!‖, ―123‖, and so on. It should be noted ―123‖ is a string constant while, 123 is integer constant., 2.5.4 Backslash Character Constants, These constants refer to those special character constants which contain a, backslash and some character enclosed within a pair of single quotes. These, constants are used in output functions and are known as escape sequences., Table 2.5 shows the list of backslash character constants along with their, interpretation.
Page 25 :
Figure 2.2: ASCII Table, , Backslash Character, , Meaning, , \a, , alert (bell) character, , \b, , backspace, , \f, , form feed, , \n, , newline
Page 26 :
\r, , carriage return, , \t, , horizontal tab, , \v, , vertical tab, , \\, , backslash, , \?, , question mark, , \', , single quote, , \", , double quote, , Table 2.5: List of backslash character constants in C, 2.6, , Variables, , A Variable represents some memory location which is used to store some, value. Unlike constants, a variable may take different values at during times, during execution. In other words, the value within a variable can be, changed; hence the name. A Variable-name is an identifier token that, follows the syntax rules for creating identifier (refer to section 2.4), however, programmers choose variable names in such way so as to reflect its function, or nature in program. As an example, if length and breadth of a rectangle is, required to be stored in some variable, one can use srinagar and kashmir as, variable names. Though the names are legitimate but it would be better to, use length_rect and breadth_rect., , Variables and Data Types, 3.0, , Introduction, , A computer processes data according to the instructions specified in a, program and produces the output. This processing is done by Central, Processing Unit (CPU) of the computer which performs arithmetic operations
Page 27 :
such as addition, subtraction, multiplication and division, and logical, operations such as comparing two numbers. The data and programs are, stored in primary memory (RAM) of a computer where from it is fetched by, CPU. This computer memory is made up of cells which are capable of holding, information in the form of binary digits 0 and 1 (bits). This is the way, information is stored in a memory just like we memorize numbers using, digits 0 to 9. Every such cell of computer memory has a unique memory, address. In order to instruct CPU to process some data located in its memory, we have to specify the address of that location. However, it is very difficult, for humans to remember the memory addresses in numbers like 316976. So, instead of using some number to address any memory location which, contains data, we label that location by a Variable. This means using, variables a programmer no more needs to be concerned about the actual, location in memory where some data is stored, rather he/she can simply use, the label i.e. Variable name, to access it., In addition, the CPU does not access memory by individual bits; instead it, accesses data in a collection of bits, typically 8 bits, 16 bit, 32 bit or 64 bit., Furthermore, the data within that memory location may be of any type like, integer, floating point, character, and so on. To further qualify that memory, location, we associate the type of data it contains, which also includes the, width of data. C programming language provides a rich set of Data Types, which in association with variables can be used to label some memory, location, specify the type of data it contains and width of that data., In this lesson, we will look at various data types supported by C language,, syntax rules to declare, initialize and access a variable, classify data types, supported by C language, and so on., 3.1, , Variables and Data Types, , Variables are a way of reserving memory to hold some data and assign, names to them so that we don't have to remember the numbers like 316976, and instead we can use the memory location by simply referring to the, variable name. Every variable is mapped to a unique memory address., However, this is not enough. A variable can contain different types of data, and each type may have different space requirement. Thus as mentioned, earlier we also specify the data type of a variable which signifies the type of
Page 28 :
data it contains and the space it requires to hold it. Having a variety of data, types at the disposal of programmer allows him to make appropriate data, type selection as per the nature of computation and type of machine. In, addition, the operations legitimate for one type of data may be invalid for, some other type. Having specified the data type of a variable allows the, compiler to make compile time type checking in order to avoid run time, failures., 3.2, , Classification of Data Types, , The wide variety of data types supported by C language can be classified, into 3 classes:, 1. Primary Data Types, 2. User-defined Data Types, 3. Derived Data Types, C supports 4 primary data types which include integer, character, floating point and, doubleprecision floating point., C also supports creating user-defined data types using keywords typedef and enum., Both classes of these data-types will be discussed in this lesson however derived data types will, be discussed in lesson 9 and lesson 10., , 3.3, , Integer Data Type, , The Integer data type is used to specify a variable that will contain only, integer values, i.e. any positive or negative number without fractional part., The keyword used by C language to specify some variable as integer is int., The width of memory allocated to an integer variable is generally one word., However, the word length varies from machine to machine. For a 16-bit, machine, the word length is 16-bits. Also, Turbo C 3.0 is a 16-bit compiler, which means the size of an integer variable will be 2 bytes. Please note that, because we will be implementing all our programs on TC3.0, so we will, consider a 16-bit machine for here onwards. Furthermore, to represent both, positive and negative integers, one bit is reserved for sign. This means, only
Page 29 :
15-bits are used to store the magnitude of data while the remaining one bit, is used to store the sign of the data. Therefore, the range of integers that, can be stored in an integer variable can have a minimum value of -32768, and a maximum value of 32767 (-215 to +215 -1). The highest positive value, is one less than the highest negative value, because 0 is treated as positive, integer., By default int specifies the variable as signed integer variable with width, equal to machine word. However, C also provides certain qualifiers to further, qualify the integer data type. These qualifiers can be classified into 2, classes., 1. One class specifies whether the integer variable will hold signed, numbers (both positive and negative) or unsigned numbers (only, positive numbers). The keyword signed if prepended to int keyword, specifies that the integer variable will hold both positive and negative, numbers. Indeed, by default int is signed. As mentioned earlier, the, range of such a variable will be -32786 to +32767. If the keyword, unsigned is prepended to int keyword, the variable so declared will, only hold positive integers. This means no sign bit will be reserved and, full word (16-bit in our case) will contain the magnitude. This means, the variable can contain a range of integers with a minimum value of 0, to a maximum value of 65535 (0 to 216-1)., 2. The other class specifies the size of integer variable. By default its size, is one word (16-bits in our case). However, if short keyword is, prepended to int keyword then the variable occupies only 8 bits. In, contrast, if long keyword is prepended to int keyword then the, variable occupies double word (32-bits in our case)., It should be noted that both classes of qualifiers can be used simultaneously., Table 3.1 shows various variants of integer data type along with their width, and range on 16-bit machine., , Data Type, , Width (in bits), , Range
Page 30 :
int or signed int, , 16, , -32768 to 32767, , unsigned int, , 16, , 0 to 65535, , 8, , -128 to 127, , 8, , 0 to 255, , short, , int, , or, , signed short int, , unsigned short, int, 32, -2147483648 to, , signed long int, or long int, , 2147483647, 32, , unsigned, , 0 to 4294967295, , long, , int, Table 3.1: Various forms of Integer data type in C, 3.4, , Floating Point Data Type, , The Floating Point data type is used to specify a variable that will contain, real numbers, i.e. any positive or negative number with fractional part. The, keyword used by C language to specify some variable as real is float. The, width of memory allocated to floating point variable is 32 bits irrespective of, the word size of the machine. The float data type can store real numbers, with a precision of 6 digits. In order to store larger width floating point, numbers with more precision, C provides double and long double floating, point data types. The variable declared as double data type occupies 64 bits, while the one declared as long double occupies 80 bits. Both also provide
Page 31 :
more precision as compared to float. It should be noted that float, double, and long double only store signed real numbers. Table 3.2 shows various, variants of floating point data type along with their width and range., , Data Type, , Width (in bits), , float, , Range, , 32, , to, 3.4E-38, 3.4E+38, , double, , 64, , to, 1.7E-308, 1.7E+308, , long double, , 80, , to, 3.4E-4932, 1.1E+4932, , Table 3.2: Various forms of Floating Point data type in C, 3.5, , Character Data Type, , The Character data type is used to specify a variable that will contain, characters from ASCII table like ‗A‘, ‗%‘, and so on. The keyword used by C, language to specify some variable as character is char. The width of, memory allocated to a character variable is 8 bits. The char variable stores, the character internally as an integer which corresponds to its equivalent, ASCII code. This means a direct assignment of some valid 8-bit positive, integer is also possible. However, it will be interpreted as its equivalent, ASCII character in character manipulating functions. Consequently, negative, integer values are also possible though they do not have any representation, in ASCII code. By default, a char variable is signed. This means, only 7-bits, are used to store the magnitude of data while the remaining one bit is used, to store the sign of the data. Therefore, the range of character codes that, can be stored in character variable can have a minimum value of -128 and a
Page 32 :
maximum value of 127 (-27 to +27 -1). The highest positive value is one less, than the highest negative value, because 0 is treated as positive integer., Furthermore, C also provides keywords signed and unsigned to be, prepended to the char keyword to further qualify the variable so created as, one that will hold signed or unsigned integer values respectively. Table 3.3, shows various variants of character data type along with their width and, range., , Data Type, , Width (in bits), , Range, , 8, , -128 to 127, , 8, , 0 to 255, , char or signed, char, , unsigned char, , Table 3.3: Various forms of Character data type in C, 3.6, , Declaration of a Variable, , All the variables that are to be used in a program must be declared first. The, declaration of variable means specifying the identifier (i.e. variable name),, the type and width of data it will hold (i.e. data type) to the compiler. The, general syntax of declaring a variable in C is as follows:, Data-type Variable-name;, int x; float y;, abc is the variable, name, , int abc;, float def;, Also, multiple variable declaration of same data type in a single line is, possible. The general syntax for this is as follows:
Page 33 :
Data-type Variable-name1[, … Variable-nameN];, This means the above 4 statements can written in 2 statements as follows:, int x, abc;, float y, def;, Please note that as every sentence in English language ends with a period, (.), every statement in C language ends with a semi-colon (;) called, terminator. Table 3.4 shows some valid and invalid examples of variable, declaration in C language., , Declaration, , Status, , int x, y, z, abc, def, pgdca, qwert;, , Valid, Valid, , float x;, int y;, char c;, , float x, y;, int x, y;, , Invalid; because a, variable can‘t be of, two types, , int x; int, x, y, z;, , Invalid; because a, single variable can‘t, be declared twice, , int 123x;, Invalid variablename
Page 34 :
Table 3.4: Some valid and invalid examples of variable declaration in C, language, 3.7, , Initialization of a Variable, , After a variable is declared it may be required to initialize it. Initialization of, a variable means assigning some value to it. However, technically there is no, problem with using a variable without initializing it. But logically it is wrong., When a variable is declared but not initialized it contains some random, bogus but valid value. As an example, if a variable x is declared as int, then, x may contain say 1278 value before its initialization. The value is bogus but, valid. There are generally 2 ways to initialize a variable., 1. First, during declaration we can assign some value to it. As an, example,, int x = 1234;, This way variable x is initialized with value 1234 when it is declared as, integer., 2. Second, after the variable is declared we can assign it some value in a, separate statement. As an example,, int x; x =, 1234;
Page 35 :
C Statements, Introduction, The meaningful sentences are at the heart of every spoken language., Similarly, meaningful statements are at the heart of C programming, language. In addition, as in English language the idea that is being conveyed, by the text should follow a well-defined template. Consider the case of an, application which has a well-defined structure as follows:, 1. To whom it is addressed, 2. Subject, 3. Reason for application, 4. Justification for approval, 5. Request for approval, 6. Anticipatory thanks, and, 7. The details of applicant, Similarly, C programs have a well-defined structure. Also, programs do I/O, with devices, like reading key presses, displaying data on screen and so on., In this lesson, we will look at the structure of a C program, the types of C, statements, I/O facility in C language, and storage classes supported by it. It, should be noted that this lesson is very important and should be consulted in, following lessons to better understand the text., 4.1, , Structure of a C program, , C is a case sensitive programming language which means in C two variables, named x and X will have different meanings. However, it is a free-form, language which means any C statement can start in any column but end of, each C statement must be marked with a semicolon (;). In addition, multiple, statements can be on the same line, statements can continue over multiple, lines and white spaces (i.e. TAB and SPACE BAR) are ignored. In general, a, C program basically contains following elements:, 1. Preprocessor Commands
Page 36 :
2. Functions, 3. Variables, 4. Statements & Expressions, 5. Comments, Consider a simple program below:, , #include <stdio.h>, Pre-processor Command, required as, per the nature of a program, , void main(), {, , main() function required by every C program, Required opening brace of a function, , /* My first C program */, , Optional Comments; can appear anywhere, C Statement, , printf("Hello, World! \n");, Required closing brace of a function, , }, 4.1.1 Pre-Processor Commands, These commands tell the compiler to do some processing before doing actual, compilation. Like #include <stdio.h> is a preprocessor command which, tells a C compiler to include stdio.h header file before going to actual, compilation. stdio.h refers to a file supplied along with the C compiler which, contains definitions of many functions that perform input-output with, standard devices like keyword and screen. For example, one of the functions, in the file stdio.h is printf() which accepts a string of character enclosed in, double quotes to be displayed on the screen. This header file must be
Page 37 :
included in every program that reads some data from keyboard or displays, some data on screen. stdio.h is not the only header file available in C, language and to include other header files in a C program the same, preprocessor command with different header file name can be used., 4.1.2 Functions, Functions are main building blocks of any C Program. Every C Program will, have one or more functions and there is one mandatory function which is, called main() function. The main() function is the most important function, and must be present in every C program. The execution of a C program, begins in the main() function. The opening brace { indicates the beginning, of the function. The closing brace } indicates the end of the function. This, function is prefixed with keyword void which means this function returns, nothings when it exits. However, it can also be prefixed with int in which, case it means it will return some value. And to return that value return, keyword is used., The C Programming language provides a set of built-in functions. In the, above example printf() is a C built-in function which is used to print, anything on the screen., 4.1.3 Variables, Variables are used to hold numbers, strings and complex data for, manipulation., 4.1.4 Statements & Expressions, Expressions combine operators, variables and constants to create new, values. Statements are expressions, assignments, function calls, or control, flow statements which make up C programs., 4.1.5 Comments, Comments are used to give additional useful information inside a C Program., Comments are optional and are just used to increase the readability of the, program. All the comments are put inside /*...*/ as shown in the previous, example. However, this comment can span through multiple lines and may, appear anywhere in a C program. Single line comments can also entered by, just prefixing them with //. The program 4.1. shows the general template of, a C program that will used to create and test our programs.
Page 38 :
#include <stdio.h>, stdio.h header file provides fnctions to do, I/O with Keyboard and Screen, , void main(), main() function required by every C program, , {, , Required opening brace of a function, , C Statements, , Required closing brace of a function, , }, Program 4.1: General template of a C program, 4.2, , Errors in a C program, , Error is a condition either during compilation or execution of a program, which if not fixed can halt compilation or execution. There are three types of, errors — syntax, logical, and run-time errors., 4.2.1 Syntax Error, These errors occur because of wrongly typed statements, which are not, according to the syntax or grammatical rules of the language. For example,, in C, if you don‘t place a semi-colon after the statement it results in a syntax, error., , /* Syntatically wrong */, printf("Hello, World! \n")
Page 39 :
/* Syntatically Correct */, printf("Hello, World! \n");, These errors are caught by compiler during compilation and can be fixed by, correcting the syntax of the statement., 4.2.2 Logical Error, These errors occur because of logically incorrect instructions in the program., Let us assume that in a program which was supposed to do addition of 2, numbers, it was wrongly written to perform subtraction. This logically, incorrect instruction will produce wrong results. Detecting such errors is, difficult as they only surface during run-time that too occasionally., 4.2.3 Runtime Error, These errors occur during the execution of the programs though the program, is free from syntax and logical errors. Some of the most common reasons for, these errors are, 1. When you instruct your computer to divide a number by zero., 2. When you instruct your computer to find logarithm of a negative, number., 3. When you instruct your computer to find the square root of a negative, integer., 4.3, , Simple and Compound Statements, , A Statement is the smallest standalone element of a programming language, which in itself is collection of tokens of the language put in some proper, sequence as per the syntax rules or grammar of the language. A sequence of, one or more statements gives rise to a program. C language makes a, distinction between statements and definitions, with a statement only, containing executable code and a definition declaring an identifier.
Page 40 :
The body of C functions (including the main() function) are made up of, statements. These can either be Simple Statements or Compound, Statements., Simple Statements do not contain other statements and end with a, semicolon called Statement terminator. The simplest kind of statement in, C is an expression. The following statements are simple statements and, most of the statements in a typical C program are Simple Statements of this, form., , x = 2;, /* an assignment statement */, x = 2+3;, /* another assignment statement */, 2+3;, /* has no effect & will be discarded */, puts("hello, world");, /* a statement containing a function call */, root2 = sqrt(2);, /* an assignment statement with a function call */, Compound Statements have other statements inside them; may be simple or, other compound statements. The term Compound Statement (or Block), refers to a collection of statements (both Simple and Compound) that are, enclosed in braces to form a single unit. Compound statements are not, terminated with semicolons. The statement shown below is a compound, statement. Notice that it contains three simple statements enclosed in a pair, of curly braces. Also, though individual simple statements end with, semicolon, however the compound statement does not have one.
Page 41 :
{, x = 2;, y = 3;, z = x + y;, }, Compound, , statements, , generally, , form, , the, , body, , of, , functions,, , loops,, , conditional statements, and so on., 4.4, , Input / Output Statements, , Input/output is used for interfacing with outside world. Every programming, language must provide a means to input some data into a program. This can, be achieved by reading some input device, file, network, and so on., Similarly, every programming language must provide a means to output, some data of a program onto screen, printer, file, and so on. However, C, language does not provide any built-in input-output statements as part of its, syntax. Therefore, programmers rely extensively on libraries for support in, developing the user interface for a program. These libraries contain functions, to perform I/O and thus a call to some specific I/O function is made within, the main C program to accomplish I/O., To use any of the C library function, that library must be first included in our, program. Recall program 4.1 which shows the general template of a C, program. The first line of that program contains a pre-processor command to, include stdio.h header file. This command directs the compiler to include all, the functions within the library to be included in the program. Thus, with the, information of all the functions provided by it, one can now simply call those, functions within the main body of program., In fact, the header file stdio.h defines the standard input and output, operations. This file forms part of the larger C standard library defined in the, ANSI standard for the language. The standard input/output library is, by its, very nature, standard and must therefore be suited to any hardware, platform. Consequently the functions that it provides do not support color
Page 42 :
monitors because one cannot guarantee that the hardware platform has a, color monitor. Similarly, the functions do not support mouse input, high, resolution graphics output, or other ―non-standard‖ input and output, devices., Nevertheless, the I/O functionality provided by stdio.h is standard, well, documented, reliable and widely used. There are generally two classes of, input/output functions provided by stdio.h header file. These include, formatted, , I/O, , and, , non-formatted, , I/O, , functions., , This, , is, , worth, , mentioning here that to fully understand the functions within formatted and, non-formatted class, the rest of text should be read again in context of, lesson 12., 4.5, , Formatted I/O, , The functions which fall in this category provide a convenient way to format, the input and/or output data as per the requirements. The two main, functions within this category are printf() and scanf()., 4.5.1 printf(), printf() function writes to the standard output (monitor) a sequence of, data, formatted as per the format specifier. The general syntax of printf(), function is as follows, , int printf (, char * formatString, [,argument, ...], );, where formatString contains a list of format specifiers indicating the format, and type of data to be written to the screen. The data is stored in the, corresponding argument. The argument can be numeric values, strings of, characters, variables, expressions, and so on. formatString can contain any, mix of the following, 1. Literal text to be displayed on screen,, 2. Escape sequences used as carriage control,
Page 43 :
3. And, format specifiers for conversion of data in the arguments to a, display format., It should be noted that printf() function returns the number of characters, displayed. Also, after the formatString parameter, depending on the, formatString, the function may expect a sequence of additional arguments,, each containing one value to be inserted instead of each format specifier in, the formatString parameter., The format specifier follows this prototype:, , %[flags][width][.precision][length]specifier, Where specifier is the most important which defines the type and the, interpretation of the value of the corresponding argument. Table 4.1, enumerates various specifiers supported by printf() function along with the, interpretation and display format of the corresponding argument., Specifier, , Interpretation and Display Format, , c, , Character, , d or i, , Signed decimal integer, , e, , Scientific notation (mantissa/exponent) using e character, , E, , Scientific notation (mantissa/exponent) using E character
Page 44 :
f, , Decimal floating point, , g, , Use the shorter of %e or %f, , G, , Use the shorter of %E or %f, , stdou, t., , o, , Unsigned octal, , s, , String of characters, , u, , Unsigned decimal integer, , x, , Unsigned hexadecimal integer, , X, , Unsigned hexadecimal integer (capital letters), , p, , Pointer address, , n, , %, , Nothing printed. The argument must be a pointer to a signed int, where the number, of characters written so, A % followed by another % character will write % to, , Table 4.1: List of various specifiers supported by printf() function., The format Specifier can also contain flags, width, .precision and length, fields which are optional and follow these specifications:, Table, , 4.2:, , Lists, , and, , discusses, , the, , meaning, , of, , various, , fields, , of, , formatspecifier, Program 4.2 shows some of the format specifiers for printf() function in, action followed by the screenshot of the output., , #include <stdio.h>, void main(), {, printf ("Characters: %c %c \n", 'a', 65);, printf ("Decimals: %d %ld\n", 1977, 650000L);
Page 45 :
printf ("Preceding with blanks: %10d \n", 1977);, printf ("Preceding with zeros: %010d \n", 1977);, printf ("Some different radixes: %d %x %o %#x %#o \n",, 100, 100, 100, 100, 100);, printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416,, 3.1416);, printf ("Width trick: %*d \n", 5, 10);, printf ("%s \n", "A string");, }, Progam 4.2: Program shows some of the format specifiers of printf(), function in action, , 4.5.2 scanf()
Page 46 :
The scanf() function scans the data input through the keyboard and by, default delimits values by whitespace. Whitespace is defined as being a TAB,, a blank or the newline character ('\n'). Therefore, data that is input with the, intention of having embedded blanks as part of the data value will be broken, into several values and distributed among the input variables specified in the, scanf() statement. The general syntax of the function is as follows, , int scanf (, char * formatString, [,address, ...], );, where formatString is a list of format specifiers indicating the format and, type of data to be read from the keyboard and stored in the corresponding, address. There must be the same number of format specifiers and, addresses. scanf() returns the number of input fields successfully scanned,, converted, and stored. The return value does not include scanned fields that, were not stored., formatString contains one or more of the following items:, 1. Whitespace, , character:, , The, , function, , will, , read, , and, , ignore, , any, , whitespace characters (this includes blank spaces and the newline and, tab characters) which are encountered before the next non-whitespace, character. This includes any quantity of whitespace characters, or, none., 2. Non-whitespace character, except % sign: Any character that is not, either a whitespace character (blank, newline or tab) or part of a, format specifier (which begin with a % character) causes the function, to, , read, , the, , next, , character, , from, , stdin,, , compare, , it, , to, , this, , nonwhitespace character and if it matches, it is discarded and the, function continues with the next character of format. If the character, does not match, the function fails, returning and leaving subsequent, characters of stdin unread., 3. Format specifiers: A sequence formed by an initial percentage sign, (%) indicates a format specifier, which is used to specify the type and, format of the data to be retrieved from stdin and stored in the, locations pointed by the additional arguments.
Page 47 :
A format specifier follows this prototype:, , %[*][width][modifiers]type, where, *, , An optional starting asterisk indicates that the data, is to be retrieved from keyboard but ignored, i.e. it, is not stored in the corresponding argument., , width, , Specifies the maximum number of characters to be, read in the current reading operation, , modifiers, , Specifies a size different from int (in the case of d, i, and n), unsigned int (in the case of o, u and x) or, float (in the case of e, f and g) for the data pointed, by the corresponding additional argument:, , h : short int (for d, i and n), or unsigned short int, (for o, u and x), , l : long int (for d, i and n), or unsigned long int (for, o, u and x), or double (for e, f and g), , L : long double (for e, f and g), , type, , A character specifying the type of data to be read, and how it is expected to be read., , The type field can have following values:
Page 48 :
type, , Qualifying Input, , Type of argument, , c, , Single character: Reads char *, the next character. If a, width different from 1, is specified, the, function reads width, characters and stores, them in the successive, locations of the array, passed as argument., No null character is, appended at the end., , d, , Decimal integer:, Number optionally, preceded with a + or, sign., , int *, , e,E,f,g,G, , Floating point: Decimal, number containing a, decimal point,, optionally preceded by, a + or - sign and, optionally folowed by, the e or E character, and a decimal number., Two examples of valid, entries are -732.103, and 7.12e4, , float *, , o, , Octal integer., , int *
Page 49 :
s, , String of characters., This will read, subsequent characters, until a whitespace is, found (whitespace, characters are, considered to be blank,, , char *, , newline and tab)., , u, , Unsigned decimal, integer., , unsigned int *, , x,X, , Hexadecimal integer., , int *, , The function expects a sequence of references as additional arguments, each, one pointing to an object of the type specified by their corresponding, format-specifier within the formatString, in the same order. For each, format specifier in the formatString that retrieves data, an additional, argument should be specified. These arguments are expected to be, references (pointers); so to store data in a regular variable, it should be, precede with the reference operator, i.e. an ampersand sign (&), like as, follows:, , int n;, scanf ("%d",&n);, Program 4.3 shows some of the format specifiers of scanf() function in action, followed by the screenshot of the output., , #include <stdio.h>, void main (), {, char str [80];
Page 50 :
int i;, printf ("Enter your family name: ");, scanf ("%s",str);, printf ("Enter your age: ");, scanf ("%d",&i);, printf ("Mr. %s , %d years old.\n",str,i);, printf ("Enter a hexadecimal number: ");, scanf ("%x",&i);, printf ("You have entered %#x(%d).\n",, i,i);, }, Program 4.3: Program shows some of the format specifiers of scanf(), function in action.
Page 51 :
-, , Operators and Expressions, Introduction, An Operator is a symbol in C language that performs some mathematical,, logical, etc. operations on some data. The data items on which operators act, upon are called Operands. Some operators require two operands while, others require only one operand. A few operators permit only single variable, as operand. Operators form Expressions by joining individual operands, which can be constants, variables, etc. Most operators allow the individual, operands to be expressions., C programming language provides several operators to perform different, kind to operations. There are operators for assignment, arithmetic functions,, logical functions and many more. These operators generally work on many, types of variables or constants, though some are restricted to work on, certain data types. Most operators are binary, meaning they take two, operands. A few are unary and only take one operand. There is a single, ternary operator which operates on three operands. Operators can be, classified based on the type of operations they perform as follows:, 1. Arithmetic Operators, 2. Relational Operators
Page 52 :
3. Logical Operators, 4. Assignment Operators, 5. Bitwise Operators, 6. Miscellaneous Operators, In this lesson, we will discuss all the above enumerated classes of operators, available in C language. In addition, we will discuss the precedence and, associativity of these operators during expression evaluation. Furthermore,, data type conversions in expressions will be analyzed., 5.1, , Arithmetic Operators, , C language provides five main arithmetic operators which include the, addition (+), subtraction (-), multiplication (*) and division (/) operator., These operators are used to perform arithmetic operations on numeric, values. All these operators perform the function what is signified by their, name. In addition there is a modulus operator (%) which gives the, remainder left over from a division operation. For exponentiation there is no, specific operator in C. Operands can be constants or variables containing, integer quantities, floating-point quantities or characters. However, the, modulus operator requires that both operands be integers and the second, operand be non-zero. Similarly, the division operator (/) requires that the, second operand be non-zero, though the operands need not be integers., Division of one integer quantity by another is referred to as integer division., With this division the decimal portion of the quotient will be dropped. An, arithmetic operator along with its operand(s) gives rise to Arithmetic, Expression. The output of an arithmetic expression is a numeric value, decided by the nature of operation. Program 5.1 shows these operators in, action which is followed by the screenshot of the output., , #include <stdio.h>, void main(), {, int i, j, p, q, r;
Page 53 :
i, j, p, q, r, , =, =, =, =, =, , 12 + 3;, 12 – 3;, i / j;, i * j;, p % q;, , \, printf(“12 + 3 is %d n”,i);, printf(“12 - 3 is %d\n”,j);, \, printf(“i / j is %d n”,p);, \, printf(“i * j is %d n”,q);, \, printf(“p %% q is %d n”,r);, }, Program 5.1: Program shows binary arithmetic operators in action, , C also provides two unusual arithmetic operators called increment (++) and, decrement (--) operators. The operator ++ adds 1 to the operand while –, subtracts 1. It should be noted that all arithmetic operators are binary, operators, however these 2 operators (++ and --) are unary (Note that, addition [+] and subtraction [-] are both binary as well as unary operators).
Page 54 :
This means, they only operate on one operand. However, the operand can, only be a variable but no constant. To understand the working of these, operators, let‘s consider an arithmetic expression in which ++ operator is, used on some variable x. As such, the value of x after operation will be 1, greater than that what was before the operation. Therefore, the two, statements shown below will have same affect individually., , X ++;, X = X + 1;, X ++; or ++ X;, X --; or -X;, However, both unary operators take two forms as shown below., , –, Though ++X and X++ mean same thing, they behave differently when they, are used in an expression wherein their value is further processed., Specifically, ++X means increment the value of X by 1 and then substitute, the expression ++X by that value. In contrast, X++ means substitute the, expression by the current value of X and then increment the value by 1., Similarly postfix and prefix decrement operators behave. Program 5.2 shows, the difference in postfix and prefix operators followed by screenshot of the, output., , #include <stdio.h>, void main(), {, int i, j, p, q, r;, i = 12;, j = i++; // Postfix Increment, p = ++j; // Prefix Increment
Page 55 :
q = j--; // Postfix Decrement, r = --q; // Prefix Decrement, \, printf(“The value of i is %d n”,i);, \, printf(“The value of j is %d n”,j);, print, \, f(“The value of p is %d n”,p);, \, printf(“The value of q is %d n”,q);, \, printf(“The value of r is %d n”,r);, }, Program 5.2: Program shows postfix and prefix operators in action, , 5.2, , Relational Operators, , C language provides six relational operators which include the greater than, (>), greater or equal (>=), lesser than (<), lesser or equal (<=), equal, (==), and not equal (!=) operator. These operators are used to compare two
Page 56 :
numeric values and thus are binary operators. All these operators perform, the function what is signified by their name. Operands can be constants or, variables, , containing, , integer, , quantities,, , floating-point, , quantities, , or, , characters. In addition, the operands can be arithmetic expressions. A, relational operator along with its operand(s) gives rise to Relational, Expression. It is worth mentioning here that the equality operator is ―==‖, and not ―=‖, which is an assignment operator. The output of a relational, expression is a Boolean value (true=non-zero or false=0) decided by the, nature of operation. Table 5.1 enumerates the working of each relational, operator., Operator Example, , Meaning, , >, , 3>0, , True; output 1, , >=, , 3 >= 0, , True; output 1, , <, , 3<0, , False; output 0, , <=, , 3 <= 0, , False; output 0, , ==, , 3 == 0, , False; output 0, , !=, , 3 != 0, , True; output 1, , Table 5.1: Usage and meaning of Relational operators, Program 5.3 shows these operators in action which is followed by the, screenshot of the output.
Page 57 :
#include <stdio.h>, void main(), {, int i, j, k;, = 10;, j = 20;, k = i < j;, , \, printf(“i < j is %d n”,k);, k = i <= j;, , \, printf(“i <= j is %d n”,k);, k = i == j;, \, printf(“i == j is %d n”,k);, k = i != j;, , \, printf(“i != j is %d n”,k);, , k = i > j;, , \, printf(“i > j is %d n”,k);, k = i >= j;, \, printf(“i >= j is %d n”,k);, }, Program 5.3: Program shows binary relational operators in action
Page 58 :
5.3, , Logical Operators, , C language provides three logical operators which include the logical AND, (&&), logical OR (||) and logical NOT (!) operator. These operators are used, to perform logical operations on two operands and thus are binary operators., However, logical NOT (!) has only one operand and hence is a unary, operator. All these operators perform the function what is signified by their, name. Operands can be constants or variables containing integer quantities,, floating-point quantities or characters. In addition, the operands can be, relational expressions and/or arithmetic expressions. A logical operator along, with its operand(s) gives rise to Logical Expression. The output of a logical, expression is a Boolean value (true=non-zero or false=0) decided by the, nature of operation. Table 5.2 enumerates the working of each logical, operator., Operator Example, , Meaning, , &&, , 3 && 0, , Both operands are not non-zero, i.e. true. Hence the output will be, false i.e. 0., , ||, , Let x=1, , One of the operand is true (3>x, will be true), hence the output is, true i.e. 1.
Page 59 :
(3>x) | y, , !, , Let x=121 (x < 1) is false i.e. zero, and its, negation will be true i.e. 1., !(x < 1), , Table 5.2: Usage and meaning of Logical operators, Program 5.4 shows these operators in action which is followed by the, screenshot of the output., , #include <stdio.h>, void main(), {, int i, j, k;, i = 10;, j = 20;, k = (i < 11) && (j < 21);, , \, printf(“(i<11) && (j<21)is %d n”,k);, k = (i > 10) || (j > 20);, , \, printf(“(i>10) || (j>20)is %d n”,k);, k = !i;, \, printf(“!i is %d n”,k);, }, Program 5.4: Program shows logical operators in action
Page 60 :
5.4, , Bitwise Operators, , C language provides six bitwise operators which for manipulation of data at, bit level. These operators are used to perform shifting, complementing,, ANDing, ORing and so on, al at bit level. These include the bitwise AND (&),, bitwise OR (|), bitwise exclusive OR (^), shift left (<<), shift right (>>) and, one‘s complement (~) operator. All these operators perform the function, what is signified by their name. All bitwise operators are binary operators, except One‘s Complement (~) operator which is a unary operator. Operands, can be constants or variables containing integer quantities or characters but, not floating point. In addition, the operands can be logical expressions,, relational expressions and/or arithmetic expressions. The output of an, expression having bitwise operator is numeric. Table 5.3 enumerates the, working of each bitwise operator., Operator Example, , Meaning, , &, , Converts 3 and 2 to binary, number, and then performs AND, between corresponding bits. The, resulting binary number is the, outcome., , 3&2
Page 61 :
|, , 3|2, , Converts 3 and 2 to binary, number, and then performs OR, between corresponding bits. The, resulting binary number is the, outcome., , ^, , 3^2, , Converts 3 and 2 to binary, number,, and, then, performs, Exclusive, OR, between, corresponding bits. The resulting, binary number is the outcome., , <<, , 3 << 2, , Converts 3 to binary number and, shifts the bits towards left 2, times., The, resulting, binary, number is the outcome., , >>, , 3 >> 2, , Converts 3 to binary number and, shifts the bits towards right 2, times., The, resulting, binary, number is the outcome., , ~, , ~3, , Converts 3 to binary number and, complements, each, bit., The, resulting binary number is the, outcome., , Table 5.3: Usage and meaning of Bitwise operators, Program 5.5 shows these operators in action which is followed by the, screenshot of the output., , #include <stdio.h>, void main(), {, int i, j, k;, i = 10;, j = 20;
Page 62 :
k = i & j;, printf("i & j is %d\n",k);, k = i | j;, printf("i | j is %d\n",k);, k = i ^ j;, printf("i ^ j is %d\n",k);, k = i << j;, printf("i << j is %d\n",k);, k = i >> j;, printf("i >> j is %d\n",k);, k = ~ i;, printf("~i is %d\n",k);, }, Program 5.5: Program shows bitwise operators in action
Page 63 :
5.5, , Assignment Operators, , C language provides one main assignment operator (=) which assigns to a, variable on its LHS the outcome of some expression on its RHS. We have, been using this operator since program 5.1. It is a binary operator. In, addition, C language provides a set of shorthand assignment operators of, the form, variable arithmetic/bitwise-Operator = expression;, These operators are very useful when in an expression a variable on LHS is, repeated immediately on RHS. As an example, the statement below, , x = x + 22;, can be written as, , x += 22;, Table 5.4 lists all possible shorthand assignment operators along their, equivalent expressions., Shorthand Example, Operator, , Equivalent expression, , +=, , x += 2;, , x = x + 2;, , -=, , x -= 2;, , x = x - 2;, , *=, , x *= 2;, , x = x * 2;, , /=, , x /= 2;, , x = x / 2;, , %=, , x %= 2;, , x = x % 2;, , <<=, , x <<= 2;, , x = x << 2;, , >>=, , x >>= 2;, , x = x >> 2;, , &=, , x &= 2;, , x = x & 2;, , |=, , x |= 2;, , x = x | 2;, , ^=, , x ^= 2;, , x = x ^ 2;, , Table 5.4: Usage and meaning of Shorthand operators
Page 64 :
5.6, , Miscellaneous Operators, , C language some non-conventional operators like ternary conditional, operator (?:), sizeof operator, comma operator (,), pointer operators (& and, *) and member selection operators (. and ->). Here we will discuss first 3, operators while rest will be discussed later., Conditional operator (?:) is ternary operator whose first operand is the, conditional expression outcome of which will decide whether the second, operand expression will be executed or the third operand expression. As an, example, consider the following code snippet in which we want to assign, value of x to a if and only x > y; otherwise we will assign it some other, value., , x = 10;, y = 20;, a = ( x > y ) ? x : 0;, // This code will assign 0 to a, The sizeof() operator which return the number of bytes that are occupied, by the operand. The operand can be a constant, data type or variable., , printf(“The size of int = %d”, sizeof(int));, // This code will display 2 on the screen, The comma operator (,) is used to link related expressions together. The, expression so formed is evaluated from left-to-right and the value of, rightmost expression is the value of the combined expression., , x = 10;, y = 20;, z = (x = y + 1, y = x + 1, x + y);, //What is the value of z;
Page 65 :
There are two more operators in C language; unary plus (+) and unary, minus (-). Unary Plus is a unary operator which simply multiplies +1 to its, operand which can be any expression. Same way unary minus multiplies -1, to its operand. These operators are used to explicitly assign some sign to the, expression., 5.7, , Operator Precedence and Associativity, , Consider an expression below, , z = 5 + 4 * 3;, What will be the value of z? 27 or 17? To avoid the ambiguity during the, evaluation of expressions involving 2 or more operators in a C program, C, language has given precedence to each and every operator supported by it., Therefore, in C language the operators at higher level of precedence are, evaluated first. Table 5.5 shows the various precedence levels (Rank 1 being, the highest level) along with the operators which fall under this level. Using, this table we can solve the above mentioned problem. Because * has rank 3, and + has rank 4, so * has higher precedence than +. This means 4 * 3 will, be evaluated first yielding 12 which will be added to 5 to yield 17. Hence, z, will be assigned value 17., However, certain operators have been assigned same level of precedence as, shown in Table 5.5. Consider another expression below, , z = 8 * 3 / 2;, What will be the value of z? 12 or 8? To solve this problem, to every, precedence level associativity is assigned. The associativity of a precedence, level signifies the order in which same precedence level operators will be, evaluated. Means they will either be evaluated from left to right or from right, to left. So in the problem mentioned above, though both * and / have same, precedence level but they should be evaluated from left-to-right as per the, table 5.5. This means we have to start from left of the expression and, whichever operator is encountered first will be evaluated first. Hence, in this, case * will be evaluated first which will yield 24 and this will be divided by 2, to yield 12. Hence, z will be assigned 12.
Page 66 :
Rank, , Operator Type, , Associativity, , 1, , () [] member operators, (. ->) expr++ expr--, , left-to-right, , 2, , pointer operators (* &), , right-to-left, , unary plus (+), unary minus (-), ! ~, ++expr --expr, (typecast) sizeof, 3, , * / %, , left-to-right, , 4, , + -, , left-to-right, , 5, , >> <<, , left-to-right, , 6, , < > <= >=, , left-to-right, , 7, , == !=, , left-to-right, , 8, , &, , left-to-right, , 9, , ^, , left-to-right, , 10, , |, , left-to-right, , 11, , &&, , left-to-right, , 12, , ||, , left-to-right, , 13, , Ternary Operator, , right-to-left
Page 67 :
14, , Assignment Operators, , right-to-left, , 15, , Comma, , left-to-right, , Table 5.5: C Precedence and Associativity Chart, Table 5.6 lists some expressions and their evaluation in C programming, language., Expression, , C Evaluation, , 1+2*2, , 1+(2*2), , 1+2*2*4, , 1+((2*2)*4), , (1+2)*2*4, , ((1+2)*2)*4, , 1+4,c=2|3+5, , (1+4),(c=(2|(3+5))), , 1 + 5&4 == 3, , (1 + 5) & (4 == 3), , c=1,99, , (c=1),99, , !a++ + ~f, , (!(a++)) + (~f), , s == „w‟ || i < 9, , (s == „w‟) || (i <, 9), , r = s == „w‟, , r = (s == „w‟), , Table 5.5: Expression evaluation in C, 5.8, , Type Conversions in Expressions, , C expressions may contain many variables and constants which may be, having different data types. However, when they are evaluated they should, be raised or grounded to same common type for the sake of correct
Page 68 :
evaluation. Certain automatic type conversions are done by C compiler., In general, a narrower operand is converted into a wider one without losing, information if expression involves a wider variable or constant. Consider the, example below,, , int x = 10;, float y = 5.5;, double z;, z = x + y;, In this example, integer variable x will be first converted to float, (temporarily) and then the contents will added to real variable y. The result, will be raised to double that will be assigned to z. However, x will still be an, integer and y will still be a floating point. It should be noted that if z would, have be integer type, then the result would have been grounded to integer., Sometimes, due the complexity of an expression and nature of computation, required, explicit type conversions are needed. Consider an example, below, , int x = 10, y = 3;, float z;, z = x / y;, Because both x and y are integers, the fractional part will be dropped during, division. However, because z is floating point variable, the result (3) will be, raised to float (3.000). In explicit type conversions, any variable or constant, can be forced for a type conversion that is different from automatic, conversion. In order to achieve this, C language provides type-casting, operator which takes first argument as the data type to which the second, argument should be type casted temporarily. The general syntax of type, casting is as follows
Page 69 :
( data-type ) Expression;, So using explicit type casting, we can solve the above mentioned problem as, shown below., , int x = 10, y = 3;, float z;, z = (float) x / y;, In this case, x is type-casted to float. Thus, to evaluate the expression y is, also raised to float. Hence, the result is accurate and is assigned to z., , Control Flow – Decision Making, Introduction, Control Flow (or flow of control) refers to the order in which the individual, statements of a program are executed. In C language, statements are, executed sequentially i.e. one after another. However, sometimes the nature, of computation demands that the statements be executed out of order based, on some condition. In our daily life we make such decisions every second. As, an example, when a student leaves for the institute he makes a decision, whether to carry an umbrella or not based on the weather conditions. So, if, it is raining or is expected to rain, he may pick up one else he won‘t. Right, now, while you are reading this text, based on your comprehension you will, make a decision whether to read further or not. In both cases, you will make, a decision and will do things out of sequence. Same is true with computer, programs. This is very common in programs to execute certain statements, based on some condition. As an example, suppose you are asked to write a, simple program that will read a number from keyboard and will display on, screen whether the number is even or odd. How will you do that? The, answer is very simple. You will declare some variable as integer or float, call, scanf() function to read from keyboard, use some logic to decide whether, the number is even or odd. The logic to decide whether a number is even or, odd is simple: Divide the number by 2 and if there is some remainder then it, is odd else it is even. You can use modulus operator (%) to do that. Finally,, you will make a decision on run time whether to display ―The number is, even.‖ or ―The number is odd.‖. But what should you use in your C program
Page 70 :
to make a decision? In lesson 5 we have discussed one such operator (?:)., However, this operator is limited in its capability and thus, C language, provides certain Decision Making Flow Control statements., In this lesson, we will discuss types of flow control statements support by C, language and will discuss all the decision making flow control statements, provided by C programming language. The looping flow control statements, will be discussed in next lesson., 6.1, , Types of Flow Control Statements, , In general, C language supports 2 types of flow control statements:, 1. Decision Making, 2. Looping, Decision Making statements are those statements which execute a set of, other statements if and only some condition is true. In contrast, Looping, statements execute a specific set of statements multiple times as long as, some condition is true., The Branching statements supported by C language include, 1. if statement, 2. if…else statement, 3. if…else if ladder, 4. switch case statement, The Looping statements supported by C language include, 1. while statement, 2. do while statement, 3. for statement, 6.2, , if Statement
Page 71 :
if statement is one of the basic and primitive decision making statement, supported by C language. The general syntax of if statement is as follows:, , if ( condition ), statement;, This flow control construct first checks the condition and if it evaluates to, True then executes the statement. The condition can be any expression that, evaluates to True or False. It must be recalled that any non-zero numeric, value in C language is treated as True while as zero is treated as False. This, means, condition can be any of the following expressions:, 1. Any constant, 2., Any variable, and, 3. Any expression., However, in general Relational expressions and Logical expressions are used, to test any condition. Also, the statement can be a simple statement or a, compound statement. Recall that a compound statement is a set of simple, statements enclosed within a pair of curly braces. The following code, snippets shows various legitimate if statements.
Page 72 :
int x, y;, = 10;, y = 20;, /* Using Constant values */, if ( 10 ), \, printf(“I will be displayed n”);, if ( 0 ), \, printf(“I will NOT be displayed n”);, /* Using Variables values */, if ( x ), , \, printf(“I will be displayed n”);, , /* Using Arithmetic Expressions */, if ( x + y ), \, printf(“I will be displayed n”);, /* Using Relational Expressions */, if ( x < y ), \, printf(“I will be displayed n”);, if ( x > y ), , \, printf(“I will NOT be displayed n”);, , /* Using Logical Expressions values */, if ( x + y > 10 && y > 10), \, printf(“I will be displayed n”);, if ( x + y > 10 && 0 )
Page 73 :
printf(“I will NOT be, , displayed\, , n”);, , It should be noted that no matter whether a condition evaluates to True or, False, the rest of the statements which immediately follow the construct will, be executed normally. The following code snippet explains this., , if (0 ), printf(“I will NOT be displayed\n”);, \, printf(“I will be displayed n”);, It is sometimes required that execution of multiple statements be controlled, by the outcome of a condition. In that case, the statements are grouped into, a single compound statement. The following code snippet explains how a, compound statement can be used with if construct., , if ( 0 ), {, , \, printf(“I will NOT be displayed n”);, \, printf(“Me too NOT displayed n”);, \, printf(“Same here, NOT displayed n”);, }, , \, printf(“Oh! I will be displayed n”);, , 6.3, , if…else Statement, , if…else statement is an extension of if statement supported by C language., The statement is a two-way decision making statement in which the, condition is evaluated first and if it evaluates to true one set of statements is, executed and other set is not. Conversely, if the condition evaluates to false
Page 74 :
then the other set will be executed but the first set won‘t. The general, syntax of if else statement is as follows:, , if ( condition ), statement1;, else, statement2;, The condition can be any expression that evaluates to True or False. Also,, statement1 and statement2, both can be a simple statement or compound, statement. The following code snippet shows various legitimate if..else, statements., , int x, y;, x = 10;, y = 20;, /* Using Constant values */, if ( 10 ), , \, printf(“I will be displayed n”);, , else, \, printf(“I will NOT be displayed n”);, if ( 0 ), \, printf(“I will NOT be displayed n”);, else, , \, printf(“I will be displayed n”);
Page 75 :
/* Using Variables values */, if ( x ), \, printf(“I will be displayed n”);, else, , \, printf(“I will NOT be displayed n”);, , /* Using Arithmetic Expressions */, if ( x + y ), \, printf(“I will be displayed n”);, else, \, printf(“I will NOT be displayed n”);, /* Using Relational Expressions */, if ( x < y ), \, printf(“I will be displayed n”);, else, \, printf(“I will NOT be displayed n”);, if ( x > y ), printf(“I will NOT be displayed\n”);, \, printf(“I will be displayed n”);, /* Using Logical Expressions values */, if ( x + y > 10 && y > 10), \, printf(“I will be displayed n”);, else, \, printf(“I will NOT be displayed n”);, if ( x + y > 10 && 0 )
Page 76 :
printf(“I will NOT be displayed, , \n, ”);, , else, , \, printf(“I will be displayed n”);, In addition, no matter whether a condition evaluates to True or False, the, rest of the statements which immediately follow the construct will be, executed normally. The following code snippet explains this., , if (0 ), , \, printf(“I will NOT be displayed n”);, , else, \, printf(“I will be displayed n”);, \, printf(“I will be displayed n”);, , if ( 0 ), {, \, printf(“I will NOT be displayed n”);, \, printf(“Me too NOT displayed n”);, \, ;, printf(“Same her, NOT displayed n”), }, else, , \, printf(“I will be displayed n”);
Page 77 :
\, The following code snippet explains how a compound statement can be used, , with if..else construct. However, it should be noted that it is not necessary, , that compound statement when used should be used with both if and else., , printf(“Oh! I will be displayed n”);, , Now, let us write a simple program to check whether a number is even or, odd. Program 6.1 shows the code of program., , #include <stdio.h>, void main(), {, int number;, printf(“Please enter the number “);, scanf(“%d”, &number);, if (number % 2 == 0), printf(“The number %d is Even.”, number);, else
Page 78 :
printf(“The number %d is Odd.”, number);, }, Program 6.1: Program to check whether a number is even or odd, 6.4, , if…else if Ladder, , if…else if ladder is another extension of if statement supported by C, programming language. if statement checks a single condition and if True, executes one single statement (simple or compound). if else statement also, checks a single condition, however it executes one of the two statements, (both of which can be simple or compound). Sometimes, it is required to, check multiple conditions and accordingly decide the execution of a specific, statement (simple or compound) among multiple possible statements, (simple or compound)., One way to achieve this is to have multiple if statements. Consider a simple, problem in which depending upon the value of some integer we have to, display the day of week. The value can be entered by a user using a, keyboard and we have to display the corresponding weekday. The logic of, the program is very simple. We have to check whether the value of variable, is 1 then display ―Monday‖, or if 2 then display ―Tuesday‖, and so on. The, program 6.1 shows how this can be done using multiple if statements which, followed by the output. The program assumes that the user will only enter, number between 0 to 7., , #include <stdio.h>, void main(), {, int weekday;, printf(“please enter the weekday in number “);, scanf(“%d”, &weekday);
Page 79 :
if (weekday == 1), puts(“Monday”);, if (weekday == 2), puts(“Tuesday”);, if (weekday == 3), puts(“Wednesday”);, if (weekday == 4), puts(“Thursday”);, if (weekday == 5), puts(“Friday”);, if (weekday == 6), puts(“Saturday”);, if (weekday == 7), puts(“Sunday”);, }, Program 6.2: Program that uses multiple if statements
Page 80 :
This program will run fine. However, this program has an efficiency problem., If the user enters value 1 then as soon as ―Monday‖ will be displayed, the, next if statement will also checked; in this case weekday == 2. Indeed this, condition will fail but it will consume CPU time. The worst part of the, scenario is that all following conditions will be tested. To stop as soon, checking other condition as soon as some condition is met, we can use, if…else if statement. The general syntax of if..else if statement is as, follows:, , if ( condition1 ), statement1;, else if ( condition2 ), statement2;, ., ., ., else, statementn;, The condition can be any expression that evaluates to True or False. Also, all, statements, , can, , be, , a, , simple, , statement, , or, , compound, , statement., , Furthermore, there is no limit on number of else if constructs that can be
Page 81 :
used. Also, else construct is not mandatory. Program 6.2 recodes the, program 6.1 using else..if construct to achieve efficiency., , #include <stdio.h>, void main(), {, int weekday;, printf(“please enter the weekday in number “);, scanf(“%d”, &weekday);, if (weekday == 1), puts(“Monday”);, else if (weekday == 2), puts(“Tuesday”);, else if (weekday == 3), puts(“Wednesday”);, else if (weekday == 4), puts(“Thursday”);, else if (weekday == 5), puts(“Friday”);, else if (weekday == 6), puts(“Saturday”);, else if (weekday == 7), puts(“Sunday”);, }
Page 82 :
Program 6.3: Program that uses else...if statements, Now, if the user enters value 1 then as soon as ―Monday‖ will be displayed,, the next and all subsequent else if statements will not be checked and, control will come out of the construct. However, if the user enters value 2,, then first two conditions will be checked and rest will be skipped. Though, there will no difference in the output but this program will run faster as, compared to other one. It should be noted that if else is to be used it should, be the last statement., 6.5, , switch case Statement, , switch case statement is another control flow decision making statement, supported by C programming language. The general syntax of switch case, is as follows, , switch ( expression ), {, case value1:, statement1;, break;, case value2:, statement2;, break;, ., ., ., case valuen:, statementn;, break;
Page 83 :
default:, statementx;, }, The switch case construct first evaluates the expression and jumps to the, case which has the same value to execute the statement. After the, statement is executed, the break keyword transfers the control out from the, construct. Note that if break keyword is not used the control will execute all, the cases after matching ist choice., It should be noted that expression can be any expression that evaluates to, integer value. Therefore, the values associated with all cases should also be, integer., However, there may be a case wherein no case value matches to the, expression outcome. In that case, the statements of default case will be, executed and then control will be transferred out from the construct. It, should be noted that default is optional and needs no break. In case, the, outcome of expression matches no case value and there is no default case,, the control will be directly transferred out from the construct without, executing any statement., One can visualize switch case as a faster version of if…else if construct., Recall the program 6.3. in which if the user enters value 2, then first two, conditions will be checked and rest will be skipped. If the program is recoded, using switch case then the control will directly jump to second case without, evaluating first case. Program 6.4 shows how to recode it using switch case, construct.
Page 84 :
#include <stdio.h>, void main(), {, int weekday;, printf(“please enter the weekday in number “);, scanf(“%d”, &weekday);, switch (weekday), {, case 1:, puts(“Monday”);, case 2:, puts(“Tuesday”);, case 3:, puts(“Wednesday”);, case 4:, puts(“Thursday”);, case 5:, puts(“Friday”);, case 6:, puts(“Saturday”);, case 7:, puts(“Sunday”);, default:, puts(“Wrong weekday”);, }
Page 85 :
Program 6.3: Program that uses switch case statement
Page 86 :
Unit-II- Looping and Array, Introduction, Looping flow control statements in C programming language execute a, specific set of statements multiple times as long as some condition is true., The Looping statements supported by C language include, 1. while statement, 2. do while statement, 3. for statement, In a program written in any programming language it is common to repeat a, specific set of statements multiple times. As an example, consider that we, want to get a number from user, increment it by 1 and display it. We can, accomplish this by using scanf() function that will populate some variable,, increment it and then display it using printf(). Now, consider that we have, to perform this task 10 times. What should we do? Till now the only way we, can achieve this is to write these statements 10 times. Or another way can, be to execute the program 10 times. Well 10 is a very small number as, compared to 10,000 or so. You can argue that doing copy paste can solve, this. Indeed, yes., Let us modify the above program to display multiplication table of any, number entered by user. In this case, we will get some number from user, using scanf(), multiply it by 1, and display the result using printf(). Then,, multiply the same number by 2 and display the result. The procedure needs, to be repeated while the number is not multiplied by 10. You can see that we, are repeating a specific set of statements 10 times. These statements, include multiplying by an integer and displaying the result. This task can be, achieved easily and efficiently by using Looping statements in C language., In this lesson, we will discuss all the looping flow control statements, available in C language. In addition, we will discuss the goto, break and, continue statements.
Page 87 :
7.1, , while Statement, , The while-loop is an entry-controlled loop in which first the condition is, checked, and if it is True then the statements are executed. However, if the, condition is False, the control is transferred to the statement immediately, after the body of loop. The condition can be any constant, variable or, expression that evaluates to True or False., However, the general syntax of while-loop requires a counter variable to be, initialized before while statement. Then, within the condition, this counter, variable needs to be checked against some value. If the condition evaluates, to True, the statements within the body of loop will be executed. After this,, the control is transferred back to condition. If this time the condition is again, True, then the body of loop will be executed same way and control will be, transferred back to the condition. However, if the condition is False, then the, control will be transferred to the statement immediately following the loop, body. The general flow of an entry-controlled loop is shown in figure 7.1., , Figure 7.1: General flow of an entry-controlled loop, This means the while construct has a condition statement that decides, whether the statements of loop body will be executed or not. Also, it has a
Page 88 :
counter variable to keep the count of number of times the statements within, body of loop are executed. However, this counter variable needs to be, modified during iteration within the body of loop. The counter modification, statement should be the last statement of the body of the loop. The general, syntax of while looping statement is as follows, , counter-initialisation;, while ( condition ), {, statements;, counter-modification;, }, It should be noted that if the initialization of counter variable is skipped, then, there will be no syntax error but a logical error. This is because of the fact, that un-initialized variables contain bogus value which will be checked, against some value in condition. Depending upon bogus value, the condition, will evaluate to True or False., It is worth mentioning here that if the statement to modify counter variable, is skipped, there will be no syntax error. However, this may result into an, infinite loop. An infinite loop is a loop in which statements are executed, infinite number of times. This is true for all types of loops. Program 7.1, shows how to display a multiplication table of any number entered by a user, using while loop. It is followed by the output of the program., , #include <stdio.h>, void main(), {
Page 89 :
int number, count, mul;, printf(“Please enter the number? ”);, scanf(“%d”, &number);, count = 1;, while ( count <= 10 ), {, mul = number * count;, \, printf(“ n%d x %d = %d”,, number, count, mul);, count ++;, }, }, Program 7.1: Program to display multiplication table of a number using, while loop.
Page 90 :
7.2, , do while Statement, , The do-while loop is an exit-controlled loop in which first the body of a, loop is executed and then the condition is checked. Now, if the condition is, true then the statements are executed again. However, if the condition is, False, the control is transferred to statement immediately after the body of, loop. The condition can be any constant, variable or expression that, evaluates to True or False., The general syntax of do-while requires a counter variable to be initialized, before do-while statement. Then within the condition, this counter variable, needs to be checked against some value. The general flow of an, exitcontrolled loop is shown in figure 7.2., , Figure 7.2: General flow of an exit-controlled loop, This means the do-while construct has a condition part that decides whether, the statements will be executed or not. Also, it has a counter variable to
Page 91 :
keep the count of number of times the statements are executed. However,, this counter variable needs to be modified during iteration within the body of, loop. The counter modification statement should be last statement of the, body of the loop. The general syntax of while looping statement is as, follows:, , counter-initialisation;, do, {, statements;, counter-modification;, }, while ( condition );, One may argue why we should use such kind of a loop. The answer is, simple. There are certain situations wherein we need it. For example, we, want to get a number from user that is greater than 10. And if the number is, less than or equal to 10, we should again ask for the number. The code, snippet below shows how this can be done using a while loop., , int num;, printf(“Enter number? ”);, scanf(“%d”, &num);, while( num <= 10 ), {, printf(“Enter number? ”);, scanf(“%d”, &num);
Page 92 :
}, In contrast, we can do this with lesser number of statements using do-while, loop as shown in code snippet below., , int num;, do, {, printf(“Enter number? ”);, scanf(“%d”, &num);, }, while( num <= 10 ), It should be noted that the body of exit-controlled loops is executed, atleast once. Hence, even if the condition is False in first iteration, the body, of loop will be still executed at least once. In contrast, in entry controlled, loops the body in every iteration will only be executed if condition is True., The code snippet below explains this clearly., , int x = 1;, do, {, printf(“I will be printed”);, }, while ( x < 0);, , 7.3, , for Statement
Page 93 :
The for loop is an entry-controlled loop (like while) in which first the, condition is checked, and if it is True then the statements are executed., However, if the condition is False, the control will be transferred to the, statement immediately after the body of loop. The condition can be any, constant, variable or expression that evaluates to True or False., The general syntax of for loop requires a counter variable to be initialized, within the for statement. Then within the condition, this counter variable, needs to be checked against some value. If the condition evaluates to True,, the statements within the body of loop will be executed. After this, the, control is transferred to counter-modification part of the for loop, from where, the control is transferred back to condition. If this time the condition is again, True, the body of loop will be executed same way and control will be, transferred back to counter-modification and then to the condition. However,, if the condition is False, the control will be transferred to the statement, immediately following the loop body., , for (counter-initialisation;, condition;, counter-modification;, ), {, statements;, }, One may argue that if we have one entry controlled loop (while) then what, for we need another (for)? There are many explanations for existence of for, in C language., 1. Some argue that for is faster than while., 2. Most claim that for is used when we know in advance the number of, iterations that need to be performed.
Page 94 :
3. It is very common that initialization and modification of counter, variable is missed by a programmer in while loop. In lieu of this, observation, people believe that for-loop is more programmer friendly, as compared to while-loop., We believe first and last argument is acceptable., It should be noted that if the initialization of counter variable is skipped, then, there will be no syntax error but a logical error. Also, if the statement to, modify counter variable is skipped, there will be no syntax error. Program, 7.2 shows how to display a multiplication table of any number entered by a, , #include <stdio.h>, void main(), {, int number, count, mul;, , user using for loop., , printf(“Please enter the number? ”);, scanf(“%d”, &number);
Page 95 :
for (count = 1; count <= 10; count ++), {, mul = number * count;, \, printf(“ n%d x %d = %d”,, number, count, mul);, }, }, Program 7.2: Program to display multiplication table of a number using for, loop., This program will produce same output as that of program 7.1., 7.4, , break Statement, , The break statement is used to break the execution of body of loop. When, this statement is encountered, the control is directly transferred to the, statement immediately after the loop body. break is also used in switch-case, statement to transfer the control of execution from the statements of some, case to the statement immediately after the switch-case construct. Program, 7.3 shows the working of break statement followed by the output., , #include <stdio.h>, void main(), {, int num, count;, printf(“Enter the number? ”);, scanf(“%d”, &num);
Page 96 :
for( count=1; count < 10; count++), {, if (num == count), break;, \, printf(“Number %d/10 display n”,, count);, }, }, Program 7.3: Program to show the working of break statement., , 7.5, , continue Statement, , The continue statement when encountered, transfers the control to the, condition of the while loop or counter-modification statement of for loop., This means all the statements of loop body after the continue statement are, skipped and the control is directly transferred to the condition of the while, loop or counter-modification statement of for loop. Program 7.4 shows the, working of continue statement followed by the output.
Page 97 :
#include <stdio.h>, void main(), {, int num, count;, printf(“Enter the number? ”);, scanf(“%d”, &num);, for( count=1; count < 10; count++), {, if (num == count), continue;, printf(“Number %d/10, count);, , display\, , n”,, , }, }, Program 7.4: Program to show the working of continue statement.
Page 98 :
7.6, , goto Statement, , The goto statement is used to unconditionally transfer the control to any, location within the program whose address in the form of label follows the, statement. It should be noted that break and continue statements transfer, control to a fixed location; after loop body in case of break and to, , the, , condition of the while loop or counter-modification statement of for loop in, case of continue. However, goto can transfer control to any location., Program 7.4 shows how to display a multiplication table of any number, entered by a user using goto statement., , #include <stdio.h>, void main(), {, int number, count, mul;, printf(“Please enter the number? ”);, scanf(“%d”, &number);, count = 1;, myLoop: /* Label for if statement*/, if (count <= 10), {, mul = number * count;, \, printf(“ n%d x %d = %d”,, number, count, mul);
Page 99 :
count ++;, goto myLoop;, }, }, Program 7.2: Program to display multiplication table of a number using, goto statement., This program will produce same output as that of program 7.1., Introduction, There may be a situation when you want to check for another condition, within the body if or if-else statement. Also, it may be required to execute a, loop inside the body of another loop. Placing one construct inside the body of, another construct of same type is called Nesting., In this lesson, we will discuss Nesting of control flow statements in C, programming language., 8.1, , Nesting of Decision Making Statements, , Nesting if statement means placing if statement inside another if statement., The general syntax of nesting if statement is as follows:, , if ( condition1 ), {, statement1;, if ( conditionA ), {, statementA;
Page 100 :
}, statement2;, }, This means if condition1 evaluates to True, then statement1 will be, executed. After this, conditionA will be checked, if it also evaluates to True, then statementA will be executed, else not. However, in both cases, statement2 will be executed., It should be noted that same syntax applies to nesting of if-else construct. In, fact, within the body of if statement or else part of if-else statement, we can, have nested if statement or if-else statement as follows., , if ( condition1 ), {, statement1;, if ( conditionA ), {, statementA;, }, else, {, statementB;, }, statement2;, }, This means any variant of if statement can be nested inside another variant, of if statement. In fact, the else-if ladder is actually nested if-else statement., Consider the code snippet below.
Page 101 :
int x;, if ( x == 1 ), printf(“First one”);, else if ( x == 2 ), printf(“Second one”);, else if ( x == 3 ), printf(“Third one”);, else, printf(“Last one”);;, printf(“Done”);, In this code snippet we are using else-if ladder. Let us assume that x=1., Then, as the first condition evaluates to True, ―First one‖ will be displayed., Now, no other condition will be checked and control will be transferred to, ―Done‖. Now, consider that x=2, then first condition fails and second, condition will be checked. Thus, this time ―Second one‖ will be displayed as, x==2 evaluates to True. Now, no more checks will be made and control will, be transferred to ―Done‖., Ok. This code snippet can re-arranged as follows.
Page 102 :
int x;, if ( x == 1 ), printf(“First one”);, else, if ( x == 2 ), printf(“Second one”);, else, if ( x == 3 ), printf(“Third one”);, else, printf(“Last one”);;, , printf(“Done”);, , Yes. Actually, ―Last one‖ and ―Third one‖ are part of if-else statement which, is nested inside the else part of another if-else statement ―Second one‖., And, this ―Second one‖ if-else statement is actually nested into the else part, of ―First one‖ if-else statement. This is the only reason why all conditions, before the True condition in else-if ladder are evaluated and all conditions, after the True condition are never evaluated., It is worth mentioning here that logically there is no limit on the level of, nesting carried. However, if nesting is carried out to too deep a level and, indenting is not consistent then deeply nested if or if-else statements can be, confusing to read and interpret. Consider the code snippet below which is, actually the above code without indentation., , int x;, if ( x == 1 ), printf(“First one”);, else, if ( x == 2 ), printf(“Second one”);, else
Page 103 :
if ( x == 3 ), printf(“Third one”);, else, printf(“Last one”);;, printf(“Done”);, At first glance, it is very difficult to point out that this is nested if-else., Second, it is difficult to answer which construct is nested inside whom. One, simple rule can solve this. It is important to note that an else always belongs, to the closest if without an else., As per this rule,, 1. the ―Last one‖ else belongs to ―Third one‖ if,, 2. this construct belongs is a statement that belongs to else above it., 3. this else belongs to ―Second one‖ if statement., 4. this construct belongs is a statement that belongs to else above it., 5. this else belongs to ―First one‖ if statement., 8.2, , Nesting of Looping Statements, , Nesting loops means placing one loop inside the body of another loop. Any, variant of loop can be nested inside any other variant of loop just like any, variant of if-statement can be nested inside any other variant of ifstatement., Also, logically there is not limit on the level of nesting. However, to make, code readable and easily understood, proper indentation should be done., While all types of loops may be nested, the most commonly nested loops are, for loops. So, let us consider a for loop for explanation of nested loops., The general syntax of nested loops is as follows, , for ( ; condition1 ; ) /* Outer Loop */, {
Page 104 :
statement1;, for ( ; conditionA ; ) /* Inner Loop */, {, statementA;, }, statement2;, }, It is obvious from the syntax that during the first iteration of the outer loop,, the inner loop gets trigger and executes to completion. Then, during the, second iteration of the outer loop, the inner loop is again trigger and, executed to its completion. This repeats until the outer loop finishes. This, means the outer loop changes only after the inner loop is completely finished, and the outer loop takes control of the number of complete executions of the, inner loop. The program 8.1 explains the concept. In this program, the outer, loop is executed 5 times while during every iteration of outer loop, the inner, loop is also executed 3 times. This means, in total the inner loop will be, executed 15 times., , #include <stdio.h>, void main(), {, int i, j;, for (i=1; i<=5; i++), {, printf(“I will be displayed 5, times\n”);
Page 105 :
for (j=1; j <=3; j++), {, printf(“I will be displayed, 15 times\n”);, }, }, }, Program 8.1: Program to show working of nested loops, , 8.3, , Breaking Nested Loops, , It is sometimes required to break from the inner loop of nested loops. In this, a break statement can be used. However, the break statement will only exit, from the nested inner loop in which it is encountered and control will be, transferred to outer loop. In case we want to transfer control to some, statement after the outer most nested loop, we can use goto statement. The, code snippet below shows how to do that., , for (i=1; i<=10; i++)
Page 106 :
{, for (j=1; j <=10; j++), {, if ( i==j ), goto outside;, }, }, outside:, This code snippet transfers the control to the statement after the outermost, loop when inside the innermost loop the value of i and j are same., 8.4, , Some Examples, , Program 8.2 shows how to create multiplication table of first 10 natural, numbers using nested loops., , #include <stdio.h>, void main(), {, int i, j;, for (i=1; i<=10; i++), for (j=1; j <=10; j++), printf(“%d x %d = %d, i, j, i*j);, , \, n”,, , }, Program 8.2: Program to display multiplication table of first 10 natural, numbers., Program 8.3 shows how to print out pyramid of stars followed by screenshot, of output.
Page 107 :
#include <stiod.h>, void main(), {, int i, row, height=4;, for (row = 1; row <= height; row++), {, for (i = 1; i <= height - row; i++), printf(" ");, for (i = 1; i <= row * 2 - 1; i++), printf("*");, printf("\n");, }, }, Program 8.3: Program to display pyramid of stars
Page 109 :
Arrays, , Introduction, , Imagine that you have to store and later retrieve the unique ID of all of the, registered voters in your city. Yes, you can create and name hundreds of, thousands of distinct variable names to store the information. However, that, would scatter hundreds of thousands of names all over memory. In addition,, there is a good probability that same operation needs to be performed on, every variable. Let us assume that these variables are all populated with UID, and we need to display them. In C language, we have to use printf(), statement on every individual variable. Considering 100 voters and variables, names as number0, number1, number2…number99 to store 100 UIDs, then, , printf(“Voter 1 has UID %d”, number0);, printf(“Voter 2 has UID %d”, number1);, printf(“Voter 3 has UID %d”, number2);, ., ., the code to display them will be as follows:, , printf(“Voter 100 has UID %d”, number99);, , It is obvious that we are simply performing same operation on a set of, different data. This means it could be performed more efficiently by using a
Page 110 :
loop and an Array. Instead of declaring individual variables, such as, number0, number1,...number99, we can declare one array variable such as, numbers and use numbers[0], numbers[1],…numbers[99] to represent, individual variables. So, using arrays the program can rewritten as follows:, , int i;, for (i=0; i< 100; i++), printf(“Voter %d has UID %d”,, i+1, number[i]);, An array has the property that items stored in it are stored contiguously and, can be accessed randomly (by position or index). They are simple, fast and, can be used as the basis for more advanced data structures. Almost all, programming languages support the concept of Arrays., In this lesson, we will discuss the concept of arrays in C programming, language and will look at the various types of arrays supported by C, language. In each type, we will discuss the declaration, initialization and, accessing arrays., 9.1, , Concept of Array, , In C programming language, a derived data type which can store a collection, of elements of the same data type is possible. Such a derived data type is, called an Array. The data type of Array elements can be either primitive or, user-defined. An array in C programing language can be defined as a name, given to number of consecutive memory locations, each of which can store, the data of same data type. Thus, one can visualize an array as a collection, of variables of the same data type. All the individual variables (also called, elements) of Array can be referenced through the same Array name., However to make distinction between individual elements an index is used, to refer to a particular element in an array., The general syntax for declaring an array is as follows:
Page 111 :
<data-type> <Array-name> [<Element-Count>];, This means to declare an array of integers with 20 elements the valid C, statements will be, , int myArrayName [20];, where myArrayName is the name of the Array. It should be noted that this, will declare an integer array of size 20. Because the elements of an Array are, placed at consecutive memory locations, every element can be uniquely, accessed using the Array name and its index/location within the Array. The, general syntax to name any array element is as follows:, , <Array-name> [<index>], where index can have any value between 0 to ArraySize -1. It should be, noted that, the lowest address corresponds to the first element and the, highest address to the last element. This means the first element of an, integer array declared previously can be accessed by myArrayName[0] and, last element by myArrayName[19]. All other elements will have index, between 0 and 19. After naming an array element, it can be used in any C, expression wherein any other variable of same data type can be used., An array is a collective name given to a group of similar quantities. These, similar quantities could be percentage marks of 100 students, number of, chairs in home, or salaries of 300 employees or ages of 25 students. Thus an, array is a collection of similar elements. These similar elements could be all, integers or all floats or all characters etc. but mixture of different data types., All elements of any given array must be of the same type i.e we can‘t have, an array of 10 numbers, of which 5 are ints and 5 are floats. Usually, the, array of characters is called a ―string‖., Arrays are of two types; one dimension array and multi-dimension array., 9.2, , One Dimensional Array
Page 112 :
The array which is used to represent and store data in a linear form is called, as Single or One Dimensional Array. To declare One Dimensional Array in C,, the general syntax is as follows:, , <data-type> <Array-name> [<Array-Size>];, The Array-Size must be an integer constant greater than zero and data-type, can be any valid C data type; primary or user-defined. For example, to, declare a 3 element one dimensional array called StudentsMarks of type, double, we can use following statement:, , double StudentMarks [3];, In order to initialize this array, we have two ways:, 1. Initialize all elements at a time during declaration,, 2. Initialize elements individually after declaration, The first method can be used to declare and assign values to all elements of, 1D array as follows:, , double StudentMarks [3] = {1.1, 2.2, 3.3};, This means element StudentMarks[0], which is the first element will be, assigned value 1.1, StudentMarks[1] will be assigned value 2.2 and last, element StudentMarks[2] will be assigned value 3.3. It should be noted that, the number of values between braces { } can‘t be larger than the number of, elements that we declare for the array between square brackets [ ]. This, means the following statement is invalid., , double StudentMarks [2] = {1.1, 2.2, 3.3};, However, if we omit the size of the array during declaration, an array just, big enough to hold the values of initialization, is declared. Therefore, the, following statement has same effect as the first valid statement above has., , double StudentMarks [] = {1.1, 2.2, 3.3};, The second method is to assign values to every element individually. Recall, that to access any individual array element, the array name along with index, within square braces is used, and it can be used the same way any other, variable of same data type can be. Therefore, after declaration of, StudentMarks array, we can initialize it as follows:
Page 113 :
double StudentMarks [3];, StudentMarks[0] = 1.1;, StudentMarks[1] = 2.2;, StudentMarks[2] = 3.3;, The last statement above assigns element number 3rd in the array a value of, 3.3. Array with 2nd index will be 3rd i.e. last element because all arrays have, 0 as the index of their first element. Following is the pictorial representation, of the same array we discussed above:, , Program 9.1 explains the declaration, assignment, access, usage and, working of 1D array. It is followed by the output of the program., , #include <stdio.h>, void main (), {, int n[ 10 ];, /* n is an array of 10 integers */, int i, j;, for ( i = 0; i < 10; i++ ), {, n[ i ] = i + 100;
Page 114 :
/* set element at location i, to i + 100 */, }, /* output each array element's value */, for (j = 0; j < 10; j++ ), {, printf("Element[%d] = %d\n",, j, n[j] );, }, }, Program 9.1: Program shows the usage and working of 1D array, , 9.3, , Two-Dimensional Array, , The array which is used to represent and store data in a tabular form is, called as Two Dimensional Array. Such type of array specially used to, represent data in a matrix form. To declare Two Dimensional Array in C, the, general syntax is as follows:, , <data-type> <Array-name> [<rows>][<columns>];, The rows and columns, both must be integer constants greater than zero, and data-type can be any valid C data type; primary or user-defined. For
Page 115 :
example, to declare a two dimensional array called StudentsMarks of type, double and having 3 rows and 4 columns, we can use following statement:, , double StudentMarks [3][4];, In order to initialize this array, we have two ways:, 1. Initialize all elements at a time during declaration,, 2. Initialize elements individually after declaration, The first method can be used to declare and assign values to all elements of, 1D array as follows:, , double StudentMarks [3][2] =, {, {0.0, 0.1},, {1.0, 1.1},, {2.0, 2.1}, };, Recall that to access any individual array element, the array name along, with index within square braces is used, and it can be used the same way, any other variable of same data type can be. However, in case of 2-D arrays, we have use another dimensional also. This means element, StudentMarks[0][0], which is the first element will be assigned value 0.0,, second element StudentMarks[0][1] will be assigned value 0.1, third, element StudentMarks[1][0] will be assigned value 1.0, fourth element, StudentMarks[1][1], , will, , be, , assigned, , value, , 1.1,, , and, , last, , element, , StudentMarks[2][1] will be assigned value 2.1., It should be noted that the number of values between braces { } can‘t be, larger than the number of elements (rows x columns). However, if we omit, the size of the array during declaration, an array just big enough to hold the, values of initialization, is declared. Therefore, the following statement has, same effect as the first valid statement above has., , double StudentMarks [][] =, {, {0.0, 0.1},, {1.0, 1.1},, {2.0, 2.1}, };
Page 116 :
The second method is to assign values to every element individually. After, declaration of StudentMarks array, we can initialize it as follows:, , double StudentMarks [3][2];, StudentMarks[0][0], StudentMarks[0][1], StudentMarks[1][0], StudentMarks[1][1], StudentMarks[2][0], StudentMarks[2][1], , =, =, =, =, =, =, , 0.0;, 0.1;, 1.0;, 1.1;, 2.0;, 2.1;, , Following is the pictorial representation of the same array we discussed, above:, , Program 9.2 shows how to read and display a 3x3 matrix using 2D array. It, is followed by the output of the program., , #include <stdio.h>, void main(), {, int a[3][3], i, j;, printf("Enter matrix of 3*3 : ");
Page 117 :
for(i=0; i<3; i++), {, for(j=0; j<3; j++), {, scanf("%d",&a[i][j]);, }, }, printf("\nMatrix is : \n");, for(i=0; i<3; i++), {, for(j=0; j<3; j++), {, printf("\t %d",a[i][j]);, }, printf("\n");, }, }, Program 9.2: Program to read and display a 3x3 matrix using 2D array
Page 118 :
9.4, , Multi-Dimensional Array, , C does not have true multidimensional arrays. However, because of the, generality of C's type system; we can have arrays of arrays. This is what a, 2D Array is. Consider the example of 2D Array discussed in last section., , In this case, each row is one-dimensional array of 2 elements. Now, all these, rows are treated as single variables and are placed next to each other. This, gives rise to one dimensional Array of one-dimensional Arrays. In other, words, we have a multi-dimensional array., C allows array of two or more dimensions and maximum number of, dimensions an Array in a C program can have depends upon the compiler., Logically, there is no limit on the maximum number of dimensions. So in C, programming an array can have two or three or four or even ten or more, dimensions. More dimensions in an array means more data it can hold and of, course more difficulties to manage and understand these arrays. A, multidimensional array has following syntax:, , <data-type> <Array-Name> [d1][d2][d3]…[dn];, Where di is the size of ith dimension., Consider a 3D array declared and initialized as follows:, , int array_3d[3][3][3]=, {, {, {11, 12, 13},, {14, 15, 16},
Page 119 :
{17,, },, {, {21,, {24,, {27,, },, {, {31,, {34,, {37,, },, , 18, 19}, , 22, 23},, 25, 26},, 28, 29}, , 32, 33},, 35, 36},, 38, 39}, , };, This means the array_3d is one dimensional array of 2D arrays. On other, words, each element of this array is a 2D array. The pictorial representation, of array_3d is as follows.