Computer Programming.pdf
Document Details
Uploaded by CongenialPanFlute
2020
Tags
Full Transcript
CP15 SEMESTER 3 COMPUTER PROGRAMMING SME: SELVA...
CP15 SEMESTER 3 COMPUTER PROGRAMMING SME: SELVA JEEVITHA V A Revised in 2013 by: Mr.VIJAY S SOUNDAR (DTC) & Mr. PRASANTH CHANDRAN P K (ONTC) Prepared in 2020 by : Mrs.SELVA JEEVITHA VA (SNTC) Modified in 2020 by: Mr.SHANKAR M G (Head E Learning) Verified in 2020 by: Mr.SHANKAR M G (Head E Learning) Approved in 2020 by: Mr.SHANKAR M G (Head E Learning) Rev No : 04 Released Date : 01/07/2020 ` Table of Content UNIT 1. INTRODUCTION TO COMPUTER PROGRAMMING.......................................................................... 3 1.1 COMPUTER PROGRAMMING............................................................................................................ 3 1.2 HOW COMPUTER UNDERSTANDS OUR INSTRUCTIONS?................................................................. 4 UNIT 2. INTRODUCTION TO C PROGRAMMING LANGUAGE........................................................................9 2.1 INTRODUCTION TO C PROGRAMMING LANGUAGE............................................................................ 9 2.2 C PROGRAM BUILDING AND ITS COMPARISON WITH ENGLISH LANGUAGE:................................... 11 2.3 THE ‘C’ CHARACTER SET..................................................................................................................... 11 2.4 TOKENS in C....................................................................................................................................... 13 2.5 DATA TYPES, ENUMERATION & FORMAT SPECIFIERS....................................................................... 19 2.6 VARIABLES AND STORAGE CLASSES................................................................................................... 23 2.7 HEADER FILES..................................................................................................................................... 27 2.8 STRUCTURE OF C PROGRAM.............................................................................................................. 28 UNIT 3. OPERATORS AND EXPRESSIONS.................................................................................................... 33 3.1 ARITHMETIC, RELATIONAL AND LOGICAL OPERATORS..................................................................... 33 3.2 BITWISE OPERATORS, INCREMENT AND DECREMENT OPERATORS.................................................. 37 3.3 ASSIGNMENT OPERATORS, SPECIAL OPERATORS, CONDITIONAL OPERATOR.................................. 43 3.4 HIERARCHY OF OPERATIONS............................................................................................................. 45 3.5 DATATYPE CONVERSION AND MIXED MODE OPERATIONS.............................................................. 47 UNIT 4. CONTROL STATEMENTS................................................................................................................ 54 4.1 FORMATTED INPUT/ OUTPUT FUNCTIONS........................................................................................ 55 4.2 UN - FORMATTED INPUT/ OUTPUT FUNCTIONS............................................................................... 59 4.3 DECISION MAKING STATEMENT – IF …ELSE....................................................................................... 61 4.4 DECISION MAKING STATEMENT – SWITCH........................................................................................ 66 4.5 LOOPING STATEMENTS - FOR, WHILE, DO-WHILE............................................................................. 70 4.6 BREAK, CONTINUE, GOTO STATEMENTS........................................................................................... 77 4.7 INFINITE LOOP.................................................................................................................................... 80 UNIT 5. ARRAYS........................................................................................................................................... 86 5.1 SINGLE DIMENSIONAL ARRAY............................................................................................................ 88 5.2 MULTI DIMENSIONAL ARRAY............................................................................................................. 91 5.3 STRINGS IN C...................................................................................................................................... 94 UNIT 6. FUNCTIONS.................................................................................................................................... 98 6.1 FUNCTION - LIBRARY AND USER DEFINED FUNCTIONS, ELEMENTS OF FUNCTION.......................... 98 6.2 FOUR CATEGORIES OF FUNCTIONS................................................................................................. 102 6.3 SCOPE OF VARIABLES - LOCAL AND GLOBAL VARIABLES................................................................. 106 NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 1 ` 6.4 RECURSION...................................................................................................................................... 108 6.5 STRING FUNCTIONS......................................................................................................................... 111 UNIT 7. POINTERS...................................................................................................................................... 115 7.1 POINTER - DECLARATION & DEFINITION……………............................................................................ 115 7.2 POINTER & ARRAYS.......................................................................................................................... 120 7.3 CALL BY VALUE & CALL BY REFERENCE............................................................................................ 125 7.4 WRITING TO AND READING FROM FILE........................................................................................... 130 7.5 C - PREPROCESSOR , MEMORY ALLOCATION IN C...........................................................................138 UNIT 8. STRUCTURE AND UNION.............................................................................................................. 151 8.1 STRUCTURE - DECLARATION & ACCESSING STRUCTURE MEMBERS............................................... 151 8.2 UNION - DECLARATION & ACCESSING UNION MEMBERS............................................................... 159 Unit 9. C++ INTRODUCTION AND OOPS CONCEPTS................................................................................. 165 9.1 OBJECT ORIENTED PROGRAMMING PARADIGM............................................................................. 165 9.2 BENEFITS AND APPLICATIONS OF OOP............................................................................................170 9.3 STRUCTURE OF C++ PROGRAM........................................................................................................ 171 9.4 SPECIFYING A CLASS: DATA MEMBERS & MEMBER FUNCTIONS, ACCESS SPECIFIERS.................... 173 9.5 OBJECT CREATION AND ITS MEMORY ALLOCATION........................................................................ 174 9.6 ACCESSING THE CLASS MEMBERS WITH OBJECTS........................................................................... 176 9.7 USING SCOPE RESOLUTION OPERATOR - MEMBER FUNCTION & DATA MEMBER ACCESS............ 177 9.8 POLYMORPHISM, DYNAMIC BINDING, MESSAGE PASSING............................................................ 180 9.9 CONSTRUCTOR & DESTRUCTOR...................................................................................................... 183 9.10 SIMPLE INTRO - OPERATOR OVERLOADING & INHERITANCE CONCEPTS.......................................191 NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 2 ` UNIT - 1 INTRODUCTION TO COMPUTER PROGRAMMING 1.1 COMPUTER PROGRAMMING Computer programming is the process of developing and implementing various set of instructions given to the computer to perform a certain predefined task. There are many computer programming languages. Language English is one of the most popular and well-known Human Language. The English language has its own set of grammar rules, which has to be followed to write in the English language correctly. Likewise, any other Human Languages (Hindi, kannada, Tamil, etc.) are made of several elements like nouns, adjective, adverbs, propositions, and conjunctions, etc. So, just like English, Hindi or other human languages, programming languages are also made of different elements. Programming Language Just like human languages, programming languages also follow grammar called syntax. There are certain basic program code elements which are common for all the programming languages. We write set of instruction for the computer to execute a given task, using predefined language words in a logical sequence. The process writing these instructions in a logical sequence is called computer programming. These instructions written in a logical sequence is called as Coding. One such programming language that gives instructions to the computer to do some task is “C” Programming language. Computer Programming is easy if it is appropriately managed. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 3 ` Most important basic elements for programming languages are: Programming Environment Data Types Variables Keywords Logical and Arithmetical Operators If else conditions Loops Numbers, Characters and Arrays Functions Input and Output Operations 1.2 HOW COMPUTER UNDERSTANDS OUR INSTRUCTIONS? Imagine a situation in which an English speaking master calls, his Hindi speaking servant and gives instructions to him, in Hindi to complete a task. Now this Hindi speaking servant is unable to understand what his master is asking for. He remains in confused state. Let’s imagine the same situation, but with a translator present in between the master and the servant. This translator is capable of translating English instructions in to Hindi. Now the servant can understand the master’s command received through the translator and completes the given task as the master wanted. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 4 ` Computer is an electronic machine. It has its own programming language called Machine language. Any communication with computer must be in its machine language. Computer interprets and executes a set of binary coded instructions called machine language instructions. Machine Language Machine language consists of series of binary code patterns consisting 0's and 1's. So, if we want to give instructions to a computer, it must be fed in the form of Machine language. Example: 01010 => Load data into register. 01001 => Add the contents. Practically, it is very difficult job to remember all these binary patterns representing machine language. Assembly Language To make it easy to program, all machine codes are represented by mnemonic codes. For example the mnemonic ADD is used to represent a binary operation code (machine code) 01100 for an add operation. Assembly language is designed to replace each and every binary machine code with an easy understandable mnemonic code. Assembly language is Machine-Dependent language and thus known as Low level language. High Level Language It is comparatively easier to program using assembly language compared to using machine language. But it is not user friendly. We need a language which resembles with our spoken language. Thus ‘c’ language was designed to write programs for the computers. Later c++, Java, FORTRAN, Pascal, Basic etc were designed. These are called High Level Languages. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 5 ` The programs written in high level language are converted into machine language by translators through a series of steps. These translators are: a. Assemblers. b. Interpreters c. Compiler. HLL Program Translator Machine Language C language uses compiler as a translator. Compiler A compiler is a computer program which transforms source code written in a high-level language into low-level machine language. The compiler also makes the end code efficient which is optimized for execution time and memory space. The compiling process includes basic translation mechanisms and error detection. Let us now look at how c language compiler works. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 6 ` FEW TOOLS THAT WORK WITH COMPILER: a. Pre-processor: The pre-processor is considered as a part of the Compiler. It is a tool which produces input for Compiler. It deals with macro processing, augmentation, language extension, etc. b. Assembler: It translates assembly language code into machine understandable language. The output result of assembler is known as an object file which is a combination of machine instruction as well as the data required to store these instructions in memory. c. Linker: The linker helps you to link and merge various object files to create an executable file. All these files might have been compiled with separate assemblers. The main task of a linker is to search for called modules in a program and to find out the memory location where all modules are stored. d. Loader: The loader is a part of the OS, which performs the tasks of loading executable files into memory and run them. It also calculates the size of a program which creates additional memory space. Watch & Learn : “Various Stages of program execution” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/cJDRShqtTbk Various Compilers of C Programming Language: Borland Turbo C GNU compiler collection Microsoft Visual C++ Min GW Compiler Portable C Compiler (PCC) GCC Compiler CLANG NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 7 ` Time to recall 1. Explain what you understand by computer programming. 2. What do you understand by syntax of a programming language? 3. Why translators are required for high level languages? 4. Assemblers, Interpreters and Compilers are three types of translators. How interpreters differ from compilers? 5. What type of translator does c language use? 6. Name any three programming languages. 7. Identify which of the following languages use interpretors and which use compilers. C, Matlab, Perl, Pascal, Python, c++, Visual Basic 8. Which of the following programming languages uses compiler to get intermediate form and then uses interpreter to get machine code? Python, Java, Perl, c# NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 8 ` UNIT - 2 INTRODUCTION TO C PROGRAMMING LANGUAGE Programming Languages are used to give instructions to the computer in order to do a task. This we learnt in the previous unit. In this Unit we will study more about a Computer programming language called “C”. 2.1 INTRODUCTION TO C PROGRAMMING LANGUAGE C is a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix operating system. It was first implemented on the Digital Equipment Corporation PDP-11 computer in 1972. C has now become a widely used professional language for various reasons. Easy to learn Structured language It produces efficient programs. It can handle low-level activities. It can be compiled on a variety of computers. Facts about C C was invented to write an operating system called UNIX. C is a successor of B language which was introduced around 1970 The language was formalized in 1988 by the American National Standard Institute (ANSI). By 1973 UNIX OS almost totally written in C. Today C is the most widely used System Programming Language. Most of the state of the art software have been implemented using C Where C programming is used? (Applications) C was initially used for system development work, in particular the programs that make-up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C are: Operating Systems Text Editors Modern Programs Language Compilers Print Spoolers Data Bases Assemblers Network Drivers Language Interpreters NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 9 ` FEATURES OF C Simple: C is a simple language in the sense that it provides structured approach (to break the problem into parts), rich set of library functions, data types etc. Machine Independent or Portable: Unlike assembly language, c programs can be complied for execution on different types of operating systems with little or no change. C is platform-dependent. Mid-level programming language: C is also used to do middle-level programming. It is used to develop system utilities such as kernel (interacting with hardware), device drivers etc. It can also be used to develop high level utilities and applications. That is why it is known as mid-level language. Structured programming language: C is a structured programming language in the sense that we can organise the program using re-usable functions. So, it is easy to understand and modify. Rich Library: C provides a lot of inbuilt functions that make the development fast. Memory Management: It supports the feature of dynamic memory allocation and de- allocation. So pragrams can be written with less memory for data. Speed: The compilation and execution time of C language is fast. Pointer: C provides the feature of pointers. We can directly interact with the memory by using the pointers. We can use pointers for memory, structures, functions, array etc. Recursion: In c, we can call the function within the same function. Extensible : C language is extensible because it can easily adopt new features. Key Thought: “Understand the features by their meaning. Once the entire C programming topics are over, come back here and read once more the features of C. You would understand better” NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 10 ` Watch & Learn : “Introduction – C Programming” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/lJ4dRc_mn0w 2.2 C PROGRAM BUILDING AND ITS COMPARISON WITH ENGLISH LANGUAGE: Let us first know what alphabets, numbers and special symbols are used in C. We will then learn how these are used to construct and define constants, variables, and keywords. Finally learn how these are combined to form instructions. A group of instructions are combined to form a program. 2.3 THE ‘C’ CHARACTER SET Character: It denotes any alphabet, digit or special symbol used to represent information. Use of Character: Characters can be combined to form variables. C uses constants, variables, operators, keywords and expressions as building blocks to form a basic C program. Character Set: The character set is the fundamental raw material for any language and they are used to represent information. Similarly, computer language also have a well- defined character set, which is useful write statements. These statements written in a logical sequence will form a C program. The characters in C are grouped into the following two categories: NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 11 ` a. Source character set 1. Alphabets 2. Digits 3. Special Characters 4. White Spaces b. Execution character sets Escape Sequences (Back slash characters) Names Symbols A, B, ….., Y, Z Alphabets a, b, ……, y, z Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ~‘!@#%^&*()_-+=|\{} Special symbols []:;"',.?/ White Spaces Tab Or New line Or Space Meaningful Special Characters are listed below. Each of these characters have special meaning in c language. Symbol Name Symbol Name ~ Tilde – Minus sign ! Exclamation mark = Equal to sign # Number sign { Left brace % Percent sign } Right brace ^ Caret [ Left bracket & Ampersand ] Right bracket * Asterisk : Colon ( Left parenthesis ” Quotation mark ) Right parenthesis ; Semicolon _ Underscore < Opening angle bracket + Plus sign > Closing angle bracket | Vertical bar ? Question mark \ Backslash , Comma ` Apostrophe. Period $ Doller sign / Slash NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 12 ` Backslash Character Constants are as follows: These constants are used with backslash character to give a special meaning. Constant Meaning Constant Meaning \a Audible Alert (Bell) \v Vertical Tab \b Back Space \’ Single Quote \f Form Feed \” Double Quote \n New Line \? Question Mark \r Carriage Return \\ Backslash \t Horizontal Tab \0 Null Watch & Learn : “Escape Sequences” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/ULXZlskzR84 2.4 TOKENS in c In C programs, each word and punctuation is referred to as a token. C Tokens are the smallest building block or smallest unit of a C program. The compiler breaks a program into the smallest possible units and proceeds to the various stages of the compilation, which is called token. We can say that C program is also a collection of tokens, comments, and whitespaces. In C, Programming tokens are of six types. They are: Keyword Each keyword is meant to perform a specific function in a program. a. Keywords are predefined reserved words whose meaning is special and it is already described to the compiler b. These meanings cannot be changed c. They are fixed and cannot be used as identifiers (Variable names, function names, structure names) d. All keywords are written in lower case letters. (C is case sensitive) e. There are 32 keywords in C Keywords are written in lowercase letters. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 13 ` There are 63 keywords in C++. We will study these later. Constants The term constants refers to the fixed value. A Constant is that whose value is never changed at the end of the program. For example: 3x+2y=10 Here 3, 2 and 10 are constants. Their value never be change but here x and y are the variables and may be they vary their value NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 14 ` a. Constants are also called as literals. b. Constants are the memory locations in which the values cannot be changed during the execution of a program. c. They are declared with the keyword ‘const’. (Declaration will be discussed in the later parts of the subject) d. There are 5 types of constants. Constant Type of Value Stored Integer Literals Literals which stores integer value. eg 8, 10, -40 Floating Literals Literals which stores decimal value. eg 9.56, 8.9909, -2.14 Character Literals Literals which stores character value. eg ‘A’, ‘B’, ‘a’, ‘1’, ‘%’ String Literals Literals which stores character array. eg. “My name” Boolean Literals Literals which stores true or false value in terms of 1 and 0 All character constants are internally stored as integer values.There are 256 characters. All alphabets, numbers, symbols, space are stored in the form of equivalent numbers (values) internally by the computer. Since one byte (8 bits) is used for storing each character, therefore computer supports 256 characters. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 15 ` Watch & Learn : “Constants In C” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/KAvK4b_8POA Identifiers In C other programming languages, an identifier is a name that is assigned by the user for a program element such as variable, type, template, function or namespace. a. Identifiers are the names of variables, union, function name, structure names. b. Identifier must follow some rules. Here are the rules: All identifiers can have letters (both uppercase and lowercase letters), digits and underscore only. First character in a variable name must be an alphabet or an underscore Few compilers allow currency character($) Commas, blanks or special symbols are not allowed within a variable name. After the first character, an identifier can have any combination of characters (alphanumerical). c. C keywords cannot be used as an identifier. d. Identifiers in C are case sensitive, M2A and m2a are two different identifiers. e. A variable name can be up to 8 characters in length, but some compilers allow variable names up to 31 characters. f. Two identifiers cannot have the same name. g. It has to be declared before it is referred. The following are the examples of legal identifiers: MyVariable myvariable MYVARIABLE x1 a _myvariable $myvariable _9pins nttf NTtf The following are not legal identifiers: My Variable // Contains a space 9pins // Begins with a digit a+c // The plus sign is not an alphanumeric character testing1-2-3 // The hyphen is not an alphanumeric character NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 16 ` N'Ttf // Apostrophe is not an alphanumeric character NTTF_&_Associates // ampersand (&) is not an alphanumeric character String a. A String is a collection of Characters. It is a sequence of characters terminated with a null character \0. b. Strings are always enclosed within double quotes. c. When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default. d. Example: “c string”. Special Symbols The following special symbols are used in C having some special meaning and thus, cannot be used for some other purpose. [] () {}, ; * = # a. Brackets[]: Opening and closing brackets are used as array element reference. These indicate single and multidimensional subscripts. int name, marks; b. Parentheses(): The parentheses are used to indicate function calls and function parameters. calculate( ); average( int a, int b) ; c. Braces{}: These opening and ending curly braces mark the start and end of a block of code containing more than one executable statement. if (x==10){ ……… ……… } d. Semicolon (; ): It is used to separate each statement. In English we end each sentence with full stop. In c the stements end with semicolon. x = a + b; for ( x=0; x Multiply and Divide -> addition and subtraction. Example: 5 * 2 – 2 /2 = 9 5 * (2 - 2) / 2 = 0 (5 * (3 – 1)) / 2 = 5 Example: Program to perform arithmetic operations – Addition & Subtraction #include void main() { int a=20, b=10, c; c=a + b; printf("\nThe sum of %d and %d is %d",a, b, c); c = a - b; printf("\nThe difference between %d and %d is %d",a, b, c); NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 33 ` printf("\n 5 * 2 – 2 / 2=%d",5*2-2/2); printf("\n 5 * ( 2 - 2 ) / 2=%d",5*(2-2)/2); printf("\n (5 *( 3 – 1 ) / 2 )=%d",(5*(3-1)/2)); getchar(); // wait for a key press } // end of main function Output: The sum of 20 and 10 is 30 The difference between 20 and 10 is 10 5 * 2 – 2 /2 = 9 5 * (2 - 2) / 2 = 0 (5 * (3 – 1)) / 2 = 5 #include void main() { int a = 25, b = 4, c; float d=25, e = 4, f; c = a/b; printf("\nc is integer = %d",c); f = d/e; printf("\n f is float = %f", f); printf("\n a%b =%d", a%b); getchar(); // wait for a key press } // end of main function Output: c is integer = 6 f is float = 6.25 a%b =1 Watch & Learn : “Arithmetic Operators” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/SY9OTe-0k8w Relational Operators Relational operators are used to comparing two quantities or values. These are used with the if condition evaluator. The logic is : if (condition true) { Execute statements in this block } else // if not true { Execute statements in this block } NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 34 ` Operator Description == Is equal to != Is not equal to > Greater than < Less than >= Greater than or equal to b) { printf("\n %d is greater",a); } else { printf("\n %d is greater",b); } getchar(); } // end of main function Output: 20 is greater Put different values for a and b and try out. Watch & Learn : “Relational Operators in C” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/IVb3EwXo5N8 NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 35 ` Logical Operators C provides three logical operators when we test more than one condition to make decisions. These are: && (meaning logical AND), || (meaning logical OR) and ! (meaning logical NOT). Operator Description And operator. It performs logical conjunction of two expressions. (if both && expressions evaluate to True, result is True. If either expression evaluates to False, the result is False) Or operator. It performs a logical disjunction on two expressions. (if || either or both expressions evaluate to True, the result is True) ! Not operator. It performs logical negation on an expression. Example: Program to compare three values #include void main() { int a=10, b=10,c=0; if(a==b && a==c) //if (a equals b and also a equals c) { printf("a, b and c are equal"); } else if ((a==b) || (a==c)) // if (a equals b or a equals c) { printf("Two of them are equal"); } else // above conditions are false { printf("all are different"); } // end of if getchar(); } We can also put if inside another if Example #include void main() { int a=10,b=30,c=5; if( ! (a==b && a==c)) //if NOT (a equals b and a equals c) { NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 36 ` if(a>b && a>c) // is a greater than b and c { printf("\n %d is greater",a); } else if(b>c) // is b greater than c { printf("\n %d is greater",b); } else { printf("\n %d is greater",c); } } else { printf("all the values are equal"); } getchar(); } Output: 30 is greater Modify the above program to clearly understand where if- else if- start and end. Watch & Learn : “Logical Operators in C” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/o3rd_RMD7Ss 3.2 BITWISE OPERATORS, INCREMENT AND DECREMENT OPERATORS Bitwise Operators The data is always stored in computer in the form of bytes (8 bits). C provides a special operator for bit operation between two variables. In arithmetic-logic unit (which is inside the CPU), mathematical operations like: addition, subtraction, multiplication and division are done at bit-level. To perform bit- level operations in C programming, bitwise operators are used. Note: && and || are used for logical testing. The output is True or False NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 37 ` Operator Description & Bitwise AND Operator | Bitwise OR Operator ~ Bitwise Ones Complement Operator ^ Bitwise XOR Operator > Bitwise Right Shift Operator Know More about bitwise operators…. which is ignored mostly! This operator is very useful in embedded systems, where each bit represents a data, such position of a switch. Bitwise AND operator The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0. Let us suppose the bitwise AND operation of two integers 12 and 25. 28 = 00011100 (In Binary) 25 = 00011001 (In Binary) Bit Operation of 28 and 25 00011100 & 00011001 -------------- 00011000 = 24 (In decimal) Example: #include void main() { int a = 28, b = 25; printf("Output = %d", a&b); getchar(); } Output: Output = 24 Watch & Learn : “Bitwise AND Operator” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/OFzbCdCwPH8 NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 38 ` Bitwise OR operator The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C Programming, bitwise OR operator is denoted by |. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise OR Operation of 12 and 25 00001100 | 00011001 ------------- 00011101 = 29 (In decimal) Example: #include void main() { int a = 12, b = 25; printf("Output = %d", a|b); getchar(); } Output: Output = 29 Watch & Learn : “Bitwise OR Operator” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/9qYD12jws8g Bitwise one’s Complement operator Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. It is denoted by ~. 35 = 00100011 (In Binary) Bitwise complement Operation of 35 ~ 00100011 ------------- 11011100 = 220 (in decimal) Twist in bitwise complement operator in C Programming The bitwise complement of 35 (~35) is -36 instead of 220, but why? In computer complement of n = ~n = -(n+1). To understand this, you should have the knowledge of 2's complement. 2's Complement Two's complement is an operation on binary numbers. The 2's complement of a number is equal to the complement of that number plus 1. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 39 ` For example: Decimal Binary 2's complement 0 00000000 -(11111111+1) = -00000000 = -0(decimal) 1 00000001 -(11111110+1) = -11111111 = -256(decimal) 12 00001100 -(11110011+1) = -11110100 = -244(decimal) 220 11011100 -00100011+1) = -00100100 = -36(decimal) Note: Overflow is ignored while computing 2's complement. The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36. Hence, the output is -36 instead of 220. Bitwise complement of any number N is -(N+1). Here's how: bitwise complement of N = ~N (represented in 2's complement form) 2'complement of ~N= -(~(~N)+1) = -(N+1) Example: #include void main() { printf("Output = %d\n",~35); printf("Output = %d\n",~ -12); getchar(); } Output: Output = -36 Output = 11 Bitwise XOR operator The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise XOR Operation of 12 and 25 00001100 ^ 00011001 --------------- 00010101 = 21 (In decimal) Example: #include void main() { int a = 12, b = 25; NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 40 ` printf("Output = %d", a^b); getchar(); } Output: Output = 21 Bitwise Right & Left Shift Operators Right Shift Operator Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>. 212 = 11010100 (In binary) 212>>2 = 00110101 (In binary) [Right shift by two bits] 212>>7 = 00000001 (In binary) Right shift by 7 bits 212>>8 = 00000000 212>>0 = 11010100 (No Shift) Left Shift Operator Left shift operator shifts all bits towards left by certain number of specified bits. It is denoted by >2 &= Bitwise AND , then assign a&=b => a = a & b ^= Bitwise exclusive OR and assign a^=b => a = a + b |= Bitwise inclusive OR and assign a|=b => a = a | b Example: #include void main() { int a=5, b=5; a+=b; // this statement is equivalent to a=a+b printf("\n%d",a); a-=b; // this statement is equivalent to a=a-b printf("\n%d",a); a*=b; // this statement is equivalent to a=a*b printf("\n%d",a); getchar(); } Output: 10 5 25 Watch & Learn : “Assignment Operator” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/Xdiqd1SpXiw Special Operators C supports some special operators Operator Description NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 43 ` sizeof() Returns the size of a memory location. & Returns the address of a memory location. * Pointer to a variable. Here &, * are used as unary operators. We will learn more about them when we study Pointers. Example: #include void main() { int i=10; printf("integer: %d\n", sizeof(i)); getchar(); } Output: 2 Modify the program an d cerify the sizeof float, char and double Conditional Operator C offers a ternary operator which is the conditional operator to construct conditional expressions. ?: is the conditional operator Syntax: ConditionExpression ? True statement or value : False statement or value; The above syntax can be interpreted as follows: Example: #include void main() { int a=30,b=20,c; c=a>b?a:b; printf("The greatest value is: %d\n",c); printf("Conditional answer: %d\n", (a==b)? a + b: a - b); getchar(); } Output: The greatest value is: 20 Conditional answer: 10 Watch & Learn : “Ternary Operator” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/At5aVksyCCU NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 44 ` 3.4 HIERARCHY OF OPERATIONS When more than one arithmetic operator appears in an arithmetic expression then it is important to note which operator is evaluated first, which is operated second and which operator has the last priority. The order in which the arithmetic operators are executed is called the hierarchy of operations. C operators in order of precedence (highest to lowest). Their associatively indicates in what order operators of equal precedence in an expression are applied. Operator Description Associativity () Parentheses (function call) (see Note 1) [] Brackets (array subscript). Member selection via object name -> Member selection via pointer left-to-right ++ -- Postfix increment/decrement (see Note 2) ++ -- Prefix increment/decrement +- Unary plus/minus !~ Logical negation/bitwise complement (type) Cast (convert value to temporary value of type) * Dereference right-to-left & Address (of operand) sizeof Determine size in bytes on this implementation * / % Multiplication/division/modulus left-to-right + - Addition/subtraction left-to-right > Bitwise shift left, Bitwise shift right left-to-right < >= Relational greater than/greater than or equal to left-to-right == != Relational is equal to/is not equal to left-to-right & Bitwise AND left-to-right ^ Bitwise exclusive OR left-to-right | Bitwise inclusive OR left-to-right && Logical AND left-to-right || Logical OR left-to-right ?: Ternary conditional right-to-left = Assignment += -= Addition/subtraction assignment *= /= Multiplication/division assignment %= &= Modulus/bitwise AND assignment right-to-left ^= |= Bitwise exclusive/inclusive OR assignment = Bitwise shift left/right assignment , Comma (separate expressions) left-to-right Note 1: Parentheses are also used to group sub-expressions to force a different precedence; such parenthetical expressions can be nested and are evaluated from inner to outer. Note 2: Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the statement completes execution). So in the statement y = x * z++; the current value of z is used to evaluate the expression (i.e., z++ evaluates to z) and z only incremented after all else is done. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 45 ` For Example: Arithmetic expression a - b / c * d is equivalent to a - (b/c) * d because ‘/’ has higher precedence. The natural order of evaluation can be altered, through the use of parentheses (highest precedence). If the given arithmetic expression has many pairs of parentheses then the contents of inner most parentheses is evaluated first, the next innermost pair is evaluated as second step and so on to the outer most parentheses. For example: (a - b) / (c*d) expression gives a different result compared to the above expression. Example: Determine the hierarchy of operations and evaluate the following k=3/2*4+3/8+3 Stepwise evaluation of this expression is shown below: k=3/2*4+3/8+3 k=1*4+3/8+3 operation 1: 3/2 (from left to right) k=4+3/8+3 operation 2: 1*4 (from left to right) k=4+0+3 operation 3: 3/8 (from left to right) k=4+3 operation 4: 4+0 (from left to right) k=7 operation 5: 4+3 Note: The result of 3/2 = 1, 3/8 = 0 because these numbers have been used as integers. #include int main() { int k1_int; float k_float; k1_int = 5 / 3 * 4 + 3 / 8 + 3; printf("\n 5 / 3 * 4 + 3 / 8 + 3 = %d", k1_int); k_float = 5 / 3 * 4 + 3 / 8 + 3; printf("\n 5 / 3 * 4 + 3 / 8 + 3 = %f", k_float); k_float = 5.0 / 3 * 4 + 3 / 8 + 3; printf("\n 5.0 / 3 * 4 + 3 / 8 + 3 = %f", k_float); k_float = 5.0 / 3 * 4 + 3.0 / 8 + 3; printf("\n 5.0 / 3 * 4 + 3.0 / 8 + 3 = %f", k_float); getchar(); return 0; } Output: 5/2*4+3/8+3=7 5 / 2 * 4 + 3 / 8 + 3 = 7.000000 5.0 / 3 * 4 + 3 / 8 + 3 = 9.666667 5.0 / 3 * 4 + 3.0 / 8 + 3 = 10.041667 NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 46 ` Answers are different because: In integers 5/2 = 2 Where as 5.0/2 = 2.5. Because 5.0 is taken as decimal number. a. In 5 / 2 * 4 + 3 / 8 + 3 all numbers are taken as integers. b. In 5.0 / 3 * 4 + 3 / 8 + 3 => 5.0 is taken as decimal number c. In 5.0 / 3 * 4 + 3.0 / 8 + 3 => 5.0 and 3.0 are taken as decimal numbers. These aspects are explained in the next section. Watch & Learn : “Operator Precedence in C” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/t1_MK1Rc67g 3.5 DATATYPE CONVERSION AND MIXED MODE OPERATIONS C permits mixing of constants and variables of different types in an expression. In these types of operations, data type of one operand is converted into data type of another operand to get a uniform type. This is known as type conversion. There are two types of type conversion: a. Implicit type conversion. b. Explicit type conversion. Implicit type conversions are done by the compiler while the explicit type conversions are user defined conversions. Implicit type conversions When one data type is converted to another data type, automatically by the compiler, then it is called as Implicit Conversion. This type of conversion usually occurs when there is a mixed mode of operation, ie, more than one data type elements involved in an expression. For Example, assume in our program, we have the following elements/ data. int i = 90; float f = 3.5; char c = ’A’; double d = 2.3456; double result = (f*i) + (i/c) - (d*i); Now, we’ll examine the expression (f*i) + (i/c) - (d*i) and its assignment to the variable result. Step 1: (f * i), where, f is float and i is an integer. This is a mixed mode operation. Now, the lower data type ‘integer’ will be converted to the higher data type ‘float’, automatically by the compiler. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 47 ` Therefore, i will be converted to float data type by the compiler and is multiplied with the value of f. The resultant value will be float. (f*i) 3.5*90 3.5*90.0 315.000000 Step 2: (i / c) where, i is an integer and c is char. This is a mixed mode operation. Now, the lower data type ‘char’ will be converted to the higher data type ‘int’, automatically by the compiler. Therefore, c will be converted to int data type by the compiler and is divided with the value of i. The resultant value will be int. (i/c) 90*’A’ 90/651 (ASCII CODE of ‘A’ is 65) Step 3: (d * i) where, d is double and i is integer. This is a mixed mode operation. Now, the lower data type ‘integer’ will be converted to the higher data type ‘double’, automatically by the compiler. Therefore, i will be converted to double data type by the compiler and is multiplied with the value of d. The resultant value will be double. (d*i) 2.3456*90 2.3456*90.000211.104000 Step 4: (f + i) float is added with (i/c) integer. So, the resultant value is obviously float value. This float value is subtracted with (d * i) double. So, the resultant will be a double value. 315.000000+1 315.000000+1.000000 316.000000 316.000000- 211.104000 104.896000 (The following program is run under Turbo C++ environment) NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 48 ` Output: All the above-mentioned rules can be simplified by assigning a rank to each data type. When the expression contains different types of data items, the operand with a lower rank will be converted to the type of higher rank operand. This is called promotion of data type. ___________________________________________________________________ Type Conversion in Assignment If the types of the two operands in an assignment expression are different, then the type of the right hand side operand is converted to the type of left hand operand according to the following rules. Rule 1: If the right hand operand is of lower rank then it will be promoted to the rank of left hand operand. For example, float b; b = 30; Here right operand 30 is of type int and the left-hand operand is of type float. According to rule lower rank operand (in this case int) will be promoted to a higher rank (in this case float). So before assignment 30 will be promoted to float and then assigned to b. Hence what gets stored in b is 30.000000. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 49 ` Rule 2: If right-hand operand is of higher rank then it will be demoted to the rank of left-hand operand. For Example: int i; i = 3.5; Here right operand 3.5 is of type float and the left-hand operand is of type int. According to rule higher rank operand (in this case float) will be demoted to the lower rank (in this case int). So before assignment 3.5 will be demoted to int and then assigned to i. Hence what gets stored in i is 3. Some consequences of these promotions and demotions are: a. Some high order bits may be dropped when long int is converted to int, or int is converted to short int or char. b. Fractional part will be truncated during conversion of float type to int type. c. When double type is converted to float type, digits are rounded off. d. When a signed type is changed to unsigned type, the sign may be dropped. e. When an int is converted to float, or float to double there will be no increase in accuracy or precision. Example: #include void main() { char ch1, ch2; int i1, i2; float f1, f2; ch1 = 'A'; i1 = 70.56; f1 = 10.6; ch2 = i1; i2 = f1; printf("ch2 = %c \n", ch2); NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 50 ` printf("i2 = %d \n\n", i2); f2 = i1; i2 = ch1; printf("f2 = %.2f \n", f2); printf("i2 = %d \n", i2); getchar(); } Output: ch2 = F i2 = 10 f2 = 70.00 i2 = 65 Explicit type conversions: (Otherwise known as Type Casting) We have just discussed how C performs type conversion automatically. However, it is always good idea to force a type conversion in a way that is different from the automatic conversion. For example: float z; int x = 40, y = 3; z = x/y; The value of z will be 13.000000 instead of 13.333333 because operation between two integers yields an integer value. In these types of cases we can specify our own conversions known as type casting. This is done with the help of type cast operator. The type cast operator is a unary operator that is used for converting an expression to a particular data type temporarily. The syntax of cast operator is: (datatype)expression Here the datatype along with the parentheses is called the type cast operator. If we write the above statement as: z = (float)x/y; The value of z will come out to be 13.333333. This happens because the type cast operator (float) temporarily converted the int variable x into float type and so mixed mode arithmetic took place and fractional part was not lost. Note: The type cast operator changes the data type of variable x only temporarily for the evaluation of this expression, everywhere else in the program it will be an int variable only. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 51 ` The following program demonstrates this example. #include void main() { float z, r; int x = 40, y = 3; z = x / y; printf("z = %f\n", z); r = (float)x / y; printf("r = %f", r); getchar(); } Output: z = 13.000000 r = 13.333333 NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 52 ` Time to recall & Test yourself! 1. Evaluate the following expressions and show their hierarchy. (a) g = b / 2 + b * 4 / b - b + a / 3 ; (a = 2.5, b = 2, assume g to be a float) (b) x = i * a / 2 + 3 / 2 * a + 2 + t ; (i = 4, a = 1, t = 3.2, assume x to be an int) (c) s = q * a / 4 - 6 / 2 + 2 / 3 * 6 / g ; (q = 4, a = 2, g = 2, assume s to be an int) (d) r = 1 / 3 * a / 4 - 6 / 2 + 2 / 3 * 6 / b ; (a = 4, b = 3, assume r to be an int) 2. Convert the following equations into corresponding C statements. 3. Which of the following statement is wrong (a) mes = 123.56 ; (b) con = 'T' * 'A' ; (c) this = 'T' * 20 ; (d) 3 + a = b ; 4. If a is an integer variable, a = 5 / 2 ; will return a value (a) 2.5 (b) 3 (c) 2 (d) 0 5. What will be the value of d if d is a float after the operation d = 2 / 7.0? (a) 0 (b) 0.2857 (c) Cannot be determined (d) infinity 6. In C, Arithmetic instruction/expression cannot contain (a) variables (b) constants (c) variable names on right side of = (d) constants on left side of = 7. What is the result of the statement - printf(“%d”, 13%4); 8. What is hierarchy of operators? 9. x = (10 > 15)? 1 : 0; What is stored in x? 10. x = sizeof (char); What is stored in x? 11. x =10; y = 5 + ++x; What is stored in y? 12. x =10; y = 5 + x++; What is stored in y? 13. x=10; y = 7; a = x && 0; b = x && 1; k = x & y; What values are stored in a, b and k? 14. x =10; x % = 6; What is stored in y? 15. What symbol is used to end every statement in ‘C’ program? NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 53 ` UNIT - 4 CONTROL STATEMENTS Before we move in depth into the control statements, let us begin this unit, with Input and Output functions of C. Input Output Functions The developers of C compilers wrote several standard I/O functions and put them in libraries. These libraries are available with all C compilers. Whichever C compiler you are using it’s almost certain that you have access to a library of I/O functions. (header files) I/O facilities for different operating systems would be different. The way one OS displays output on screen may be different than the way another OS does it. There are many library functions available for Input Output operations. They are broadly classified as follows: a. Console IO functions - Functions to receive input from keyboard and write output to VDU. (Visual Display Unit) b. File IO functions - Functions to perform I/O operations on a hard disk or other external storage. (This will be discussed in Unit 7 Chapter 7.4) Console IO Functions: The screen and keyboard together are called a console. Console I/O functions can be further classified into two categories—formatted and unformatted console I/O functions. Console I/O Functions Formatted I/O functions Un-Formatted I/O funtions The basic difference between them is that the formatted functions allow the input read from the keyboard or the output displayed on the VDU to be formatted as per our requirements. For example, if values of average marks or percentage marks are to be displayed on the screen, then the details like where this output should appear on the screen, number of spaces between the two values, the number of places after the decimal point, etc. can be controlled using formatted functions. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 54 ` 4.1 FORMATTED INPUT/ OUTPUT FUNCTIONS Formatted Console – Output Function: printf() The general syntax of it: printf ( "format string", list of variables ) ; The format string can contain: a. Characters that are simply printed as they are b. Conversion specifications or format specifications that begin with a % sign c. Escape sequences (Backslash characters) that begin with a \ sign For example, #include void main() { int ave = 346; float per=69.2; printf(“AVERAGE = %d \n PERCENTAGE = %f”,ave,per); getchar(); } Output: AVERAGE = 346 PERCENTAGE = 69.200000 Interpretation of the printf() statement: The printf() statement, examines the format string from left to right. So long as it doesn’t come across either a % or a \ it continues to dump the characters that it encounters, on to the screen. In this example Average = is dumped on the screen. The moment it comes across a conversion specification in the format string it picks up the first variable in the list of variables and prints its value in the specified format. In this example, the moment %d is picked, the variable avg is picked up and its value is printed. Similarly, when an escape sequence is picked, it takes the appropriate action. In this example, the moment \n (new line) is picked it places the cursor at the beginning of the next line. This process continues till the end of format string is not reached. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 55 ` Format Specifications The %d and %f used in the printf( ) are called format specifiers. They tell printf( ) to print the value of avg as a decimal integer and the value of per as a float. The various format specifiers were discussed in the Unit 2 Chapter 2.5. To have a quick look, refer the following table: We can also provide optional specifiers in the format specification: dd - Digits specifying the field width & - Minus sign for left justification: We’ll execute the following program in the Turbo C++ compiler and see the output. void main() { int w=65; printf(“%d”,w); printf(“\n%4d”,w); // field width of 4 and right justified printf(“\n%6d”,w); // field width of 6 and right justified printf(“\n%-6d”,w); // field width of and left justified getchar(); } NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 56 ` The output as follows: To interpret this output, the following table is framed. Consider the table as the output console window. Each column specifies each character space. Field Width 1 2 3 4 5 6 7 8 6 5 6 5 6 5 6 5. – Decimal point separating the field width from precision & dd – Digits specifying the precision. We’ll execute the following program in the Turbo C++ compiler and see the output. void main() { float w=65.55; printf(“%f”,w); printf(“\n%10.3f”,w); // field width of 10,right justified, 3 digits after decimal. printf(“\n%-10.3f”,w); // field width of 10,left justified, 3 digits after decimal. getchar(); } The output as follows: To interpret this output, the following table is framed. Consider the table as the output console window. Each column specifies each character space. Field Width 1 2 3 4 5 6 7 8 9 10 6 5. 5 5 0 0 0 3 6 5. 5 5 0 6 5. 5 5 0 NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 57 ` Escape Sequences (Backslash characters) (already dealt in Unit 2 2.3) To have a quick look about Escape sequence, the following table would explain that in detail. In a printf() statement, we use these escape sequences for the about said purposes to be effected on the output screen. Example: printf(“Hello \n NTTF”); The output will introduce a new line between Hello and NTTF. Output: Hello NTTF Watch & Learn : “Printf Function In C” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/53UzOVLWXsc Formatted Console – Input Function: scanf() The general form of scanf( ) statement is as follows: scanf ( "format string", list of addresses of variables ) ; For example: scanf ( "%d %f %c", &c, &a, &ch ) ; Note that we are sending addresses of variables (addresses are obtained by using ‘&’ the ‘address of’ operator) to scanf( ) function. This is necessary because the values received from keyboard must be dropped into variables corresponding to these addresses. The values that are supplied through the keyboard must be separated by either blank(s), tab(s), or newline(s). Do not include these escape sequences in the format string. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 58 ` All the format specifications that we learnt in printf( ) function are applicable to scanf( ) function as well. Watch & Learn : “Scanf Function In C” Click the following link or else just select the link, copy & paste the link in your browser https://youtu.be/wedZlcsd8b4 4.2 UN - FORMATTED INPUT/ OUTPUT FUNCTIONS There are many library functions under this category. We are going to learn few of them. Un – Formatted I/O Functions This function will read a single character, the instant it is typed getch() without waiting for the Enter key to be hit. This function will read a single character and also, it will be getche() displayed on the screen, without waiting for the Enter key to be hit This will read a single character and also, it will be displayed on the getchar() screen. But it needs Enter Key to be hit. This function will read a single character, and also, it will be displayed on the screen. It also needs Enter Key to be hit. It looks fgetchar() similar to getchar(), but getchar() is a macro, whereas fgetchar() is a function. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 59 ` gets() receives string form the keyboard till enter is pressed putch() putchar() These functions will print a character on the screen. fputchar() puts() displays string on the output console. Example 1: (single character - I/O) void main() { char ch; printf(“enter a character”); ch=getchar(); // The character read is stored in ch. putchar(ch); getchar(); } Output: Example 2: (string of characters - I/O) (Note the difference of scanf & gets) void main() { char ch1, ch2; //Array / string of 20 characters. printf(“Enter the second string (through gets)”); gets(ch2); //reads all characters till enter is pressed. puts(ch2); printf(“Enter the first string (through scanf)”); scanf(“%s”,ch1); // will read all characters till a blank space only puts(ch1); getchar(); } Output: The moment the blank was typed after “Selva” scanf( ) assumed that the name being entered has ended. scanf( ) does not take multi word string. The solution to this problem is to use gets( ) function. The function gets() is terminated when an Enter key is hit. Thus, spaces and tabs are perfectly acceptable as part of the input string. More exactly, gets( ) gets a newline (\n) terminated string of characters from the keyboard and replaces the \n with a \0. NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 60 ` Every string is terminated with \0. This is put by the compiler. Unlike printf( ), puts( ) can output only one string at a time. If we attempt to print two strings using puts( ), only the first one gets printed. Similarly, unlike scanf( ), gets( ) can be used to read only one string at a time. Control Statements: Now let us move to the topic – Control statements. The statements which we are going to learn now, have control over the flow of execution of a program, that is why they are called as “Control Statements”. These are of 4 types: a. Sequence Control Instruction b. Selection or Decision Control Instruction c. Repetition or Loop Control Instruction d. Case Control Instruction The Sequence control instruction ensures that the instructions are executed in the same order in which they appear in the program. Decision and Case control instructions allow the computer to take a decision as to which instruction is to be executed next. The Loop control instruction helps computer to execute a group of statements repeatedly. 4.3 DECISION MAKING STATEMENT – IF …ELSE. This is the picture of MS Dhoni tossing a coin, with Virat Kohli. Before IPL 20-20 match starts, in order to decide, which team needs to bat / bowl, the captains will toss a coin. We’ll interpret this situation as follows: Conditional Action: Tossing a coin. Output of the Action: a. Head (or) b. Tail Decided Action to Proceed: a. if the tossed coin landed with “Head”, Dhoni’s team will proceed to bat b. else, (otherwise) if the coin landed with “Tail”, Kohli’s team will proceed to bat. Such decision making conditions exist in C Programs. They control the flow of execution of the program. There are 2 decision making statements in C. They are: NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 61 ` a. If statements – (bidirectional control statement) b. Switch Case Statements. – (multi directional control statement) First we’ll discuss about the “if” statement and its types. “if “statement can be of the following types: a. if b. if…else c. if…. else if….else d. nested if if Syntax Explanation if (condition) if the condition returns true, then the { statements inside if block will be executed and _____statements___; then Next statement. } If false then the block is skipped and the Next Next statement statement is executed. Flow Chart Example: void main() { int a; printf(“enter a value”) scanf(“%d”,&a); if(a>b; //Similar to scanf } }; //notice the semicolon void M2A :: display() //member function definition outside the class { //Notice the :: operator to indicate member function cout