C-Family 1 Preface & Index A Complete Material on C-Language Programming This book softcopy is available in pdfhost.io website, to download the file, search through keyword ‘cfamily1999’, along with this book, you get 500 exercise programs list on C,C++, Java programming. This pdf file(s) designed for 2-sided print-copy (Xerox copy). I request you to rate the C-Family on Google review. C-Family 2 Preface & Index Chapter Index Page No Number Systems Decimal to binary 5 Binary to decimal 6 Sample programs 11 Introduction to C 13 history of C, evolution of languages 13 features of C language 14 assembler, compiler, interpreter 15 keywords, tokens, data types, expressions 17 Operators 19 garbage values, comment lines 24 Introduction to Programming 25 library-functions, user-functions, proto-type of function 26 about main() 27 first C program 28 compiling and running a program 29 escape sequence characters 34 type casting 35 representation of constants in C 36 flow chart, algorithm, pseudo code 38-42 Decision Control Structures 43 if, if-else 43-47 nested-if 52 If-else-if ladder 56 If-else linking, about Boolean value, null instruction 60, 62, 69 switch statement, conditional operator, goto statement 70, 77 Looping Control Structures 78 while loop 111 for loop 113 do-while loop 115 break, continue 117 nested loop 118 One Dimensional Arrays 127 accessing & initialization of arrays 127 about array size , array boundaries 128 C-Family 3 Preface & Index Functions 138 types of functions, library functions, user functions 138,139 function body & its call syntax 141 more about functions 142 Pointers 157 operators in pointers 158 arrays & pointers, passing array to function 167,170 call-by-value vs call-by-reference 175 Sorting & Searching 178 Storage Classes 186 Preprocessor Directives 192 2D Arrays 197 Characters & Strings 206-209 initialization of strings 210 pointer to string, passing array to function 213, 214 array of strings 225 Recursion 230 Dynamic Memory Allocation 242 Command Line Arguments 249 User Defined Data types 250 structures, array of structures 251, 252 different declaration structures, typedef, advantages of structures 254, 255 union, enumeration 256, 257 File Handling 266 text files, binary files 268 IO operations on files 270 C-Family 4 Preface & Index C by Examples A complete reference material on C-language programming About C C-language is an ideal programming language and a perfect combination of power and flexibility. Though it is a high-level language, it has low level features as well as easy interaction with hardware and OS. Even assembly language code can be mixed in it. It is accepted as a good system programming language. Powerful OS like UNIX was developed using C. ‘C’ is widely used in the software industry for both system and application side development. C is the primary subject in computer science. It lays good foundation in programming and eases the learning of any advanced courses that are to follow. So, it has been added in every branch of arts, science, and engineering as part of curriculum. Every graduate student is going to face C, C++, DS, Java, Python and Oracle in the first & second academic years. About C-Family Computers C-Family is a premier institute in Vijayawada training the students in C, C++, DS, Java, Python, Oracle, WebDesign courses since 1999. C-family was not setup by any business men instead it was setup and run by a group of eminent programmers. We provide hands on training to ambitious students in right proportions to their passion for knowledge. Needless to say, taking individual care of each student is the hallmark of our institution. Our courses are designed in such a way that student get best foundation in logic and programming skills. [The languages C, C++, VC, VC++, JAVA are called C-Family Languages, as we teach all these courses, we named this institute C-Family Computer Education] I am grateful to all the students, friends, staff who helped me making this material. This book is advisable to learn the logic and programming skills for beginners. For any suggestions contact me on srihari.vijayawada@gmail.com by Srihari Bezawada since 1999 C-Family Computer Education, #40-9/1-26, Vasayva Complex, Dr. Samaram Hospital Lane, Benz Circle, Vijayawada-10, 9440-030405, 8500-117118. C-Family 5 Computer Basics Number systems and its conversion We have mainly four number systems in the computer science. 1. Decimal Number System 2. Binary Number System 3. Octal Number System 4. Hexadecimal Number System Decimal to Binary Conversion The word decimal means 10, the base of decimal system is 10, here we have symbols 0, 1, 2, …9. The word binary means 2, the base of binary system is 2, here we have symbols 0,1. We know, computer follow binary number system, where it manages the data and instructions in the form of binary numbers (0/1), and this binary numbers managed as two voltages, for example 3volts for 0, and 7volts for 1. So computers follow binary system for storing the data and also for processing the data. We know, humans follow Decimal system, and this system is also used by the computer while showing data in visible form. It uses graphical conversion to show binary values in decimal/text format (pixels/dots) Following example shows how to convert number 13 into binary form. Continuously divide N with 2 and collect the remainders, the collection of remainder forms a binary number, this is as given below. N Remainders 13 / 2 1 6 / 2 0 3 / 2 1 1 / 2 1 0 Thus collection of these remainders from bottom-to-top forms a binary number ( 1310 11012 ) Binary to Decimal Conversion Multiply all digits(bits) of N with 20,21,22,23,24… from right-to-left, the sum of all such products forms a decimal number. Following example explains how to convert binary number 1101 to its decimal 13. 1 1 0 1 1*23 + 1*22 + 0*21 + 1*20 13 23 22 21 20 8 + 4 + 0 + 1 Example2 for converting binary number 11001 to its decimal 21. 1 1 0 0 1 1*24 + 1*23 + 0*22 + 0*22 + 1*20 21 24 23 22 21 20 16 + 4 + 0 + 0 + 1 Hexadecimal Number conversion This system base is 16, and we have 16 symbols from 0 to 15, the symbols are 0,1,2,3,….9,A,B,C,D,E,F (10A, 11B, 12C, 13D, 14E, 15F). This system mainly used to represent binary number in simple readable form of digits & alphabets. As we know, binary system is very difficult to follow, because everything is in 1 or 0. So we represent binary numbers in hexadecimal system for simplicity. Actually, Hexadecimal system resembles the binary values. Here we divide a binary number into several groups, where each group contains exactly 4bits and each group represented in hexadecimal value. C-Family 6 Computer Basics Let us see, how the binary number 1101-1001-1100-0011 is taken in hexadecimal system as D9C3. In Binary 1101 1001 1100 0011 In decimal 13 9 12 3 In Hexadecimal D 9 C 3 In the above example explained how to convert/represent binary into hexadecimal system. Following example explains, how decimal value directly be converted into hexadecimal. Here we repeatedly divide the N with 16, and we collect the remainders, this collection of remainders forms hexadecimal number. Let us see how to convert decimal value 370359 to hexadecimal 5A6B7 16 370359 16 23147 7 16 1446 11 (B) 16 90 6 16 5 10(A) 5 By collecting remainders from bottom to top, the hexadecimal value formed as: 5A6B7 Hexadecimal to decimal Multiply all digits of N with 160, 161, 162, 163, 164… from right-to-left, the sum of all such products forms a decimal number. Eg: (5A6B7)₁₆ = (5×16´) + (10×16³) + (6×16²) + (11×16¹) + (7×16⁰) = (370359)₁₀ Memory Measurements Memory constituted in the form of bytes, where each byte consists of 8bits and the measurements are 1 bit = 1 cell the cell can hold either 1/0 8 bits = 1 byte 1024 bytes = 1 kilo byte (1kb) 1024 kilo bytes = 1 mega byte (1mb) 1024 mega bytes = 1 giga byte (1gb) 1024 giga bytes = 1 tera byte (1tb) 1024 tera bytes = 1 peta byte (1pb) The binary value 1101 is stored in a byte as 0 0 0 0 1 1 0 1 th th th th th rd nd st 8 bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit The binary value 1001101 is stored in a byte as 0 1 0 0 1 1 0 1 th th th th th rd nd st 8 bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit Note: we can’t store more than 8bit value in 1byte memory, it causes over-flow error. Here leftmost bits are omitted (truncated). eg: if we put 12bit value 1100-1101-1001 in 1byte, then it holds only 1101-1001 and 1100 is trunctated. C-Family 7 Computer Basics Memory and its Min and Max value capacity 9 9 9 9 4 This value 9999 is equal to 10 -1 in decimal system th rd nd st 4 bit 3 bit 2 bit 1 bit This is maximum value that we can store in 4bits of decimal system 1 1 1 1 4 This value 1111 is equal to 2 -1 in binary system th rd nd st 4 bit 3 bit 2 bit 1 bit This is maximum value that we can store in 4bits of binary system We know, how to convert binary value to decimal, so by converting 1111 into decimal, we get 24-1. Let’s see 1*23 + 1*22 + 1*21 + 1*20 24 + 23 + 22 + 20 24-1 So in 8bits (1byte) memory, we can store value 0 to 28-1 (0 to 255), in 16bits(2byte) memory, we can store value 0 to 216-1 (0 to 65,535). Representing –ve values For signed types, the leftmost bit is used to represent sign (+ve/-ve). This bit is called sign bit, If this bit contained 0 then it is said to be +ve value, or else –ve value, For example, the value +13(1101) is stored in one byte as follows +ve sign 0 0 0 0 1 1 0 1 th th th th th rd nd st 8 bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit The value -13 is stored as follows -ve sign 1 0 0 0 1 1 0 1 th th th th th rd nd st 8 bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit Note: This kind of value representation is called “signed magnitude representation”. So in 8bits (1+7 bits) memory, we can store value in the range of -27 to +27-1 (-128 to 127). Actually, for negative values 2’s complement method is used, here extra +1 is added to the given number, so we get -128 instead 127 in negative side. (in next topic, we will see what 2’s is Complement) Binary addition Addition of binary values X 0 0 1 1 Y 0 1 0 1 X+Y 0 1 1 10 When we add 1+1 we get sum 0, and carry is 1, so result is 10 don’t call this result as ten, call it as one---zero. C-Family 8 Computer Basics X 1 Y 1 Z 1 X+Y+Z 1 1 carry is 1 , sum is 1 carry 1 1 carry 1 1 1 1 X 1 1 0 1 X 1 1 0 1 Y 1 1 1 0 Y 1 1 1 1 X+Y 1 1 0 1 1 X+Y 1 1 1 1 0 Binary subtraction In computer, subtraction is done like addition using 2’s complement method, this is truly simple and fast. The normal subtraction of two values takes much time; here we may need to check & barrow from next digits. For example, subtraction of 3456 - 0999. Here first, we try to subtract last digits 6-9, but here 6<9, so we need to barrow from next digits. In this way, we have to look-up and barrow from next position digits. This process takes much time and complex. The best solution is, 2’s complement method. People often say, 2’s complement value is nothing but negative form of given value 2’s complement is 1’s complement + 1 1’s complement is reverse of a given number (replace 1 by 0, and 0 by 1) If X=1001, then 1’s complement of X is 0110 If X=0001, then 1’s complement of X is 1110 1’s complement of 1 is 0, 1’s complement of 0 is 1 2’s complement is 1’s complement + 1 If X=1001, then 2’s complement of X is 0110+1 0111 Procedure for subtraction X - Y using 2’s complement method. 1. Let X,Y are two values 2. Let Y is small 3. find 2’s Complement of Y 4. Now add X + 2’s Complement of Y 5. In the result of addition, remove leftmost bit 6. Hence we get subtracted value. (note: if X<Y then add –ve sign to the result) 1. Let X=1101 (13), Y=1001(9) 2. The 2’s complement of Y is 0110+1 0111 3. Addition of 1101 + 0111 10100 (this is addition of X + 2’s Complement of Y) 4. Remove left most bit from 10100 is 0100 5. The result of X-Y is 0100 (4) 6. This logic works for all binary values. 7. This is truly faster than traditional method. C-Family 9 Computer Basics Instructions & program Instruction is a command that is given to the computer processor to perform a certain elementary task. For example, consider a simple addition instruction 10+20, when this instruction executes, we get 30. Statement is a meaningful combination of one or more instructions that solves a complex task. For example, consider calculating area of a circle “area=22/7*radius*radius“ Program is an organized collection of such related instructions/statements to solve a specified problem. Software can be defined as collection of one or more programs. The programs look like the following example; this calculates the sum of two numbers step1. input(a,b) step2. c=a+b step3. print(c) What is Programming Language? Language means communication between two people; likewise, programming language is a communication between user and the computer. The user communicates with the computer by giving instructions to it, the instructions are written based on the language’s syntax structure provided by the language manufactures. We have several languages such as Fortran, Pascal, COBOL, C, etc; out of all, C is a rich, simple, elegant, powerful, and structured language. Now a day’s C became primer language for advanced languages like C++, Java, C#, VC, VC++, as they all adopted C syntax. All these languages are also called C-Family languages. Evolution of languages We have three types of languages 1.machine language, 2.Assembly language, 3.high level language. Programs are written using these languages. A) Machine Language (binary/low level language) It is treated as first generation language, used during development of computer in 19th century. In this language, the data and instruction of programs were written in terms of binary symbols (1&0’s), even input and output were given in binary codes, as the computer understands the instructions only in ones and zeros. For example, the instruction 9+13 is in binary form like 0010 1001 1101. Here, the first 4 bits represents addition(+) code and remaining 8 bits are 9 & 13. This language is also called binary or low level language. Actually, this language is difficult to understand, remember and writing programs in binary codes, it leads to a lot of typing mistakes, because everything is 1&0s. This problem led to the invention of assembly language. B) Assembly Language this is somewhat better than binary language. Here, symbolic names were provided for every binary codes of machine language. The names such as add, sub, mul, div, cmp, etc. So programmers can easily understand and write instructions using these names instead of binary 1&0’s. For example adding 4 & 6 in 8088 assembly language as mov ax,4; mov bx,6; add ax,bx However, the main drawback of assembly language is, a large set of instructions are needed to be written for simple tasks like addition of two numbers. It supports only small programs if the code is <1000 lines, otherwise difficult to manage the code. Moreover, assembly differs from one to another machine. Some people consider Assembly language also a machine language since the assembly codes resembles the machine codes. C-Family 10 Computer Basics C) High Level Language this is English and mathematical oriented language. Here data and instructions composed in terms of English words and mathematical expressions. For example c=a+b, c=a-b , if(a<b), …etc. So one can easily learn and apply high level language code. One can write the programs without the knowledge of computer hardware and operating system, i.e, it hides(abstract) the underlying details about the instructions how they are being processed in the machine. So programmers can easily code the programs without bothering about hardware and O.S. The 8085, 8086 are known as Assembly languages whereas C,C++, JAVA are high level languages. Assembler & Compiler Neither assembly nor high-level language programs can be understood by the computer directly. Before executing them, they have to be converted into binary codes, because, the computer is electronic device, it can understand and process only binary codes in voltages. The assembler is a translation-software, which translates assembly language program into equivalent machine code. Similarly compiler translates high-level language code into equivalent machine understandable code. We have several operating systems and several C compilers. All most all compilers follow the same rules except for a few modifications. Classification of Data (Data types) Data means a value or a set of values that represent attributes like age, experience, address, salary, …etc; for example, the “employee record” contains data like idno, name, age, experience, address, salary…etc; The computer hardware (processor) designed to process only two types of data 1. integral (also called integer values) 2.floating point (also called real numbers or precisions) The integral data are rounded values like 10, 20, -343, etc, whereas floating points are 15.44, -45.56, etc. So, in the real world, any kind of data comes under these two types, for example, the employee number, age are integral types. Whereas the basic salary, net salary are stored in floating point format. The name, address are collection of alphabets and other symbols, these are also integer type values. Because in computer alphabets are recorded in its ASCII codes, for eg: ‘A’ as 65, ‘B’ as 66, ‘a’ as 97. “int” is a short-cut name of “integer”, actually it occupies 2-bytes memory, where we can store value with range -32768 to +32767 ( -215 to +215 ). Remember, in modern compilers “int” occupies 4 bytes. Similarly “float” occupies 4 bytes where we can store value with fractions. Note: Actually, these two data types again classified into 9 types, we will see in next chapter. First Demo Program // this program written by Srihari, dated on 9-3-2021 Line 1: // demo program for sum of 2 numbers Line 2: #include <stdio.h> Line 3: void main() Line 4: { Line 5: int a, b, c; Line 6: a=100; Line 7: b=200; Line 8: c=a+b; Line 9: printf(“output = %d”, c); Line 10: } } C-Family 11 Computer Basics Line1: generally, at first line of program, the comments are added about purpose & author of program. It is good programming practice adding comments at first line. These are not instructions to be executed in the program; these are just documentation purpose, and these lines are ignored by the compiler. The comment line must be followed by the symbol “//” , ( this is comment symbol) we can have any number of comment lines and also we can add anywhere in the program. Line2: #include it includes library function’s header files and other code files to our program, here the printf() syntax provided in stdio.h file, hence, it included here. (We will see later in detailed) Line 3: void main() it is starting point of the program, every program starts with this line. Line 4: the open and close braces { } defines a block. As per C-Language syntax, the executable instruction must be given inside braces. ( ‘C’ is a block structured programming language) Line5: int a, b, c; this instruction creates memory space for each variable with 2-bytes in RAM. Where we can store value -215 to +215 RAM a b C 100 200 300 Line6: a=100; this instruction puts 100 in ‘a’ Line7: b=200; this instruction puts 200 in ‘b’ Line8: c=a+b; this instruction puts a+b value 300 in ‘c’ Line9: printf(“output = %d”,c) this statement shows output on the screen as: “output = 300” printf() this statement displays message or variable values on the screen, whatever we put in quotations(“ ”), it displays as it is on the screen. The ‘c’ value 300 is substituted in place of %d. We will see more about this printf() statement in next chapter. Line10: ‘}’ this closing braces tells the end of program. We will see in next chapter, how to compile and run the program on the computer. Finding sum and product of given two input values This program scans two values from keyboard and prints the sum and product of two values. ip: 10 20 op: sum is 30, product is 200 void main() { int a, b, sum, product; printf("Enter two values for a , b:"); keyboard scanf("%d%d", &a, &b); 10 20 ⤶ sum=a+b; product=a*b; printf("sum is %d , product is %d", sum , product); } printf("enter two values for a , b:") this statement asks/displays to the user to feed 2 values for a,b scanf("%d%d", &a, &b); this statement reads two values from keyboard(KB) and inserts into given variables (a,b). For two values, we have to use two %d%d, we will see later why %d used. printf("sum is %d, product is %d", sum , product); this display result as: sum is 30, product is 200 C-Family 12 Computer Basics Finding sum of equation 5x2 + 2x + 10, here ‘x’ is input value ip: x=3 op: 5*3*3+2*3+10 45 + 6 + 10 61 void main() { int x,y; printf(“enter x value :”); scanf(“%d”, &x); y=5*x*x+2*x+10; printf(“output is: %d”, y); } output is: 61 Finding Fahrenheit from given Celsius. (formula is: F=9/5*C+32) This program scans Celsius from keyboard and prints Fahrenheit as output. ip: enter Celsius: 10 op: Fahrenheit is: 50 void main() { int C,F; printf("Enter Celsius:"); scanf("%d", &C); F=9/5*C+32; printf("Fahrenheit is: %d", F); } Fahrenheit is: 50 Converting time(H:M:S) into seconds format This program accepts a time in H:M:S format as input and prints output in seconds format. ip: 2 40 50 (2-hr , 40-min , 50-sec) ip: 0 2 50 (0-hr , 2-min, 50-sec) op: 9650 seconds op: 170 seconds logic: total seconds is N=H*3600 + M*60 + S // each hour has 3600 seconds, each minutes has 60 seconds. void main() { int H,M,S,N; printf("Enter time as hours minutes seconds format:"); scanf("%d%d%d", &H, &M, &S); N=H*3600+M*60+S; printf("output time in seconds is: %d", N); } Enter time as hours minutes seconds format: 2 40 50 ⤶ output time in seconds is: 9650 C-Family 13 Introduction to C Introduction to C Brief History of C In 1960’s, there was a need for general purpose programming language and the available ones were of specific-purpose only. For example, COBOL was meant for business applications; similarly FORTRAN was extremely small and suitable only for scientific applications. Instead of being small, simple and specific, the CPL was intended to support wide range of applications in all sectors; thus, the demand for a general- purpose language led to the invention of CPL (Combined Programming Language). However, its heavy specific features made it difficult to program. Its drawbacks were eliminated, simplified and further developed by Martin Richards and named as BCPL (Basic CPL). Still it had some complex & difficult features of CPL and these difficulties were simplified by ken Thompson and named it as ‘B’. Later while developing UNIX operating system in 1969, ken Thomson faced several problems with the B language; here B was used for programming while making UNIX software. Dennis Ritchie modified the B language to overcome its limitations to suit all needs and renamed it as C. Of course, the development of UNIX using C language made it uniquely portable and improvable; Finally, C was released in 1972. Dennis Ritchie is a research scientist at Bell Telephone Laboratories in U.S.A. Brian Kernighan also participated while making the definitive description of the language. Therefore, the C is also referred as ‘K&R-C’. Features of C-Language A) C is a small & compact language: It has small number of keywords and symbols. Therefore, it provides easy & compact programming. The size of software is also less compared to other language and it has good library functions. B) C is a high-level language with low-level features: Although C is technically a high-level language, it has good syntax, features (pointer) and library functions to interact directly with hardware of the computer. C linked closely with the machine, so one can directly access the components like hard disk drive, optical drives, printers, operating system…etc; besides, it supports assembly language instructions within the C program. That is, one can mix up assembly language instructions within the C program; hence it is well suited for writing both system software and business packages. C) C is a structured programming language: Previously, the languages were influenced by ‘if’, ‘goto’, ‘repeat’, etc; writing code using such statements makes the program unreadable and complex. If there are no ideal structural tools to force the programmer to write the code in uniform style then everybody writes one’s own style and makes the program complex and un-readable to others. For example, if there are no predefined traffic rules in city roads, everyone travels as per one’s convenience and makes traffic disordered and cause inconvenience to others; so the traffic structures such as signals, dividers, zebra lines and indicators force the traveler to follow rules in order not to cause confusion. Now, the word structured means a predefined logical model (uniform syntax) and structured programming means, writing instructions in a predefined structured manner, thereby every programmer writes instruction in uniform style and made easy to understand by others. Structured programming was first suggested by Corrado Bohm and Guiseppe Jacopini. The two mathematicians demonstrated that any computer program can be written with just three structures: sequence, decision, and looping. ie, the logic of any program can be expressed in terms of these structures. A program of any complexity can be solved by the appropriate combinations (mixture) of these three basic constructs. These structures are constructed with one entry and one exit style, so that one can easily C-Family 14 Introduction to C understand the execution flow of a program. Thus structured programming greatly reduces the complexity of programs. So every structured language supports the following constructs Conditional execution of statements (i.e., "if" statements). Case selection. Looping. Subroutine (functions/sub programs) Subroutine: The features of function provide the facility to divide the big program into several reusable segments called sub-programs, each with the all necessary data and related instructions to perform a certain task and hide (independent) from the rest of the program. Thus, this collection of sub-programs made up the entire program. D) C is a portable language: The word portable means easy to carry or transfer, here the portability refers to the ability of a program to run on different environments (hardware or operating systems). As ‘C’ became powerful, it had provided different version of C-compilers for different operating systems. A C-program written in one platform can be portable to any other platform with few/negligible modifications. For example, a program written in UNIX operating system can be easily converted to run in WINDOWS or DOS and vice versa. E) C has flexible coding style: Unlike other languages (COBOL, FORTRAN), C provides freedom to the programmer while coding the program. We can write the code without bothering about the alignment of the program. The C compiler can recognize the code even when the program is not aligned or typed properly. In other words, we can use more spaces, empty lines in between instructions (tokens), or we can type several instructions in one line. F) Widely Acceptable: It is suitable for both system and application side programming. It frees the programmer from traditional programming limitations. It empowers the programmer to develop any kind of applications. Thus, accepted by almost all users and became the most popular language in the world. In fact, many of the software available in the market are written in C. G) C is a case sensitive language: In C, an upper case alphabet is never treated equal to the lower case alphabet and vice versa. All most all keywords and predefined routines of C languages use only lower case alphabets. Therefore, it is very simple to type in only one case. Of course, some user defined symbols (identifiers) can be typed in upper case to identify them uniquely. Operating System The term O.S refers to a set of programs that manages the resources of a computer. The resources of computer includes processor, main-memory, disks, and other devices such as keyboard, monitor, printer that are connected to it. It also provides a good interface to the user. The interface provided by the O.S enables the user to use the computer without knowing the details of the hardware. So interface hides the underlying working of a computer. The main jobs of O.S are memory management, process management, disk management, I/O management, security, and providing interface to the user …etc. Currently, the widely used operating systems are MS-DOS, UNIX, and WINDOWS. DOS is a simple operating system largely used in PCs. Unix, Linux, Mac, Windows on the other hand used variety of computers such as mainframes, servers, graphics workstations, supercomputers, and also in PCs. When a user runs a particular program (application) in the computer, the operating system loads the program into main memory (RAM) from the hard-disk, and then executes the instruction by instruction with C-Family 15 Introduction to C the help of processor. The processor can take & execute only one instruction at a time. So this loading and executing instructions is done under the control of OS. Thus OS executes our programs with the help of hardware. OS is the main responsible for all these things and also makes the computer in working for other tasks. The relation between hardware, operating system, user-program, and user can simulate with a banking- system such as bank, employee, transaction and customer. The hardware as a bank and O.S as a bank employee, who works dedicatedly to organize all transactions of a bank, whereas the user as a customer and user-program as a transaction, the user submit his program just by giving a command to the computer; the responder, the O.S, takes up the program into main memory and process the instructions on the hardware under its control. The following picture shows the layers of interaction between user and the computer. User Customer User program Transaction Operating system Bank employee Computer hardware Bank Character set of C It is a set of symbols called characters, which are supported by the C-language. C supports all most all symbols which are provided in the keyboard Lower case alphabets (a-z), Upper case alphabets (A-Z) Digits (0-9) White space (‘ ‘) Math symbols ( + , - , * , / , % < > = …etc ) Special symbols like {} [] () ! & , “ \ …etc ) Keywords Like English language vocabulary, C has its own vocabulary called keywords; thus Keyword is a reserved word, which has specific meaning in C, and it cannot be used for other purpose, using these keywords the programs are constructed. C has the following standard set of 32 keywords. if, else, switch, for, while, break, continue, goto, auto, register, extern, static, volatile, return, enum, void, char, int, long, short, float, double, signed, unsigned, case, const, default, do, union, sizeof, typedef, struct; Note: All keywords should be written in lower case. Depending on the compiler/vendor, few additional keywords may also exist. Tokens Let the expression ‘x+y’. It has three tokens ‘x’, ’y’ and ‘+’. Here x, y are called operands, and ‘+’ is called an operator. The compiler splits all the instructions into individual tokens for checking syntax errors. Splitting expression into tokens and checking is known as parsing. Now token can be defined as an elementary item in the program, which is parsed by the compiler. Token can be a keyword, operator, identifier, constant, or any other symbol; For example, a+b // ‘a’, ’b’ and ‘+’ are 3 individual tokens. a<=b // ‘a’, ‘b’, and ‘<=’ are 3 tokens (not 4) c++ // ‘c’ and ‘++’ are 2 tokens if(a<b) // it has 6 token Note: Here the token ‘<=’ misunderstand as two tokens(< , = ) but it is single token. Similarly, the token ++ is a single token. C-Family 16 Introduction to C Classification of Data (Data types) Data means a value or a set of values that represent attributes like age, experience, address, salary, …etc; for example, the “employee record” contains data like idno, name, age, experience, address, salary…etc; The computer hardware (processor) designed to process only two types of data 1.integral (also called integer values) 2.floating point (also called real numbers or precisions) The integral data are rounded values like 10, 20, -343, etc, whereas floating points are 15.44, -45.56, etc; so, in the real world, any kind of data comes under these two types, for example, the employee number, name, address are integral types; [the name & address are stored as array of ASCII values of integral types]; the basic salary, net salary and other values are stored in floating point format; In C, these data are classified into nine types based on the application’s requirement and hardware support; these are known as built-in or primitive or basic types. data Integral Floating point 1 byte 2 byte 4 byte 4 byte 8 byte 10 byte (char) (int) (long int) (float) (double) (long double) signed unsigned signed unsigned signed unsigned char char int int long int long int Type Bytes occupied Range singed char 1 -128 to 127 unsigned char 1 0 to 255 signed int 2 -32768 to 32767 unsigned int 2 0 to 65,535 signed short int 2 -32768 to 32767 unsigned short int 2 0 to 65,535 signed long int 4 -2147483648 to 2147483647 unsigned long int 4 0 to 4294967295 float 4 3.4 e-38 to 3.4 e+38 double 8 1.7e-308 to 1.7e+308 long double 10 3.4 e-4932 to 3.4 e+4932 signed int or unsigned int are system dependents, for example, in 16-bit DOS, it occupies 16 bits of memory, whereas in 32-bit Unix/Windows, it occupies 32 bits of memory. So they occupy 2/4 bytes based on system. The keyword signed is an optional word for signed types. That means, even if we do not mention the keyword ‘signed’, the compiler by default takes as signed types. For example, the ‘int’ is equal to ‘signed int’ in the C-language. int a, b, c; is equal to signed int a, b , c; C-Family 17 Introduction to C Operators Operator is a symbol or keyword used to compute mathematical or logical calculations in a program. C provides rich set of operators for making flexible and simple expressions. Operators are classified primarily into four categories: arithmetic, relational, logical, and bitwise. Assignment, referencing, de-referencing are called special operators. Each operator comes under one of the following types. Unary Operators: These operators are associated with only one operand. Binary Operators: These operators are associated with two operands. Ternary Operators: These take three operands to perform an operation. Note: just go through these operators briefly, we can learn in detailed in rest of the chapters. Unary Binary Ternary Sign + ve sign , -ve sign + Addition ++ (increment) - Subtraction Arithmetic * Multiplication -- (decrement) / Division % Modulo division < Less than ?: > Greater than Conditional >= greater than equal to operator Relational <= less than or equal to == equal to != not equal to ! (NOT) && AND Logical || OR & Bitwise AND | Bitwise OR Bitwise ~ (1’s compliment) ^ Bitwise exclusive OR >> Right shifting << Left shifting = Simple Assignment += Addition Assignment Assignment -= Subtraction Assignment /= Division Assignment *= %= …etc sizeof . direct selection miscellaneous * (dereferencing) -> Indirect selection & (Referencing) , expression separator A) Arithmetic operators These operators are used to calculate arithmetical sums such as addition(+), subtraction(-), multiplication (*), division(/) for quotient and modulus division(%) for remainder. Let us see some of arithmetic expressions. Here a & b are operands a + b, a - b, a * b, a / b, a%b Integer division gives only the integer part of the result, that is, the fraction part is truncated (ignored). For example, the result of 15/2 is 7 (not 7.5). The floating point division gives fractions also (15.0/27.5) The modulus-division gives the remainder of a division, for example 17%32. Notice that, we cannot apply modulus-division on floating point values as the division goes on and on, till the remainder becomes zero, so it is meaningless applying ‘%’ on float values. For example the instruction 15.0%2.0 is an error statement. (In some cases like 10.0%3.0 divisions goes endlessly) C-Family 18 Introduction to C Observe the result of following expressions 15/2 7 // decimal part is truncated, because 15 & 7 are integers 15.0/2 7.5 // because 15.0 is floating point 15.0/2.0 7.5 4/5 0 15%4 3 // remainder of division 4%6 4 // it goes zero times and remainder is 4 -15%6 -3 10%-3 1 // in modulo division, sign of result is, sign of numerator 2.5%5 error B) Relational operators These operators are used to find the relation between two values. If relation is found to be true then the result is 1, otherwise it is 0. (The result of this 1 or 0 value is also said to be BOOLEAN values). The operators such as: < > <= >= == != a>b // greater than comparison a<b // less than comparison a <= b // less than or equal comparison a >= b // greater than or equal comparison a == b // equality comparison a != b // non equality comparison Observe the result of relational operators 2 == 5 0 2 != 5 1 5 < 10 1 10 < 5 0 C) Logical Operators These operators are used to combine two or more relations to form a single compound relation. These operators also give the result either 1 or 0 (Boolean value) && Logical AND operator || Logical OR operator ! Logical NOT operator The operator ‘&&’ works just like the word ‘AND’ in English language. The operator ‘||’ works just like the word ‘OR’ in English language. syntax1: relation1 && relation2 eg: if marks1>50 && marks2>50 then student passed syntax2: relation1 || relation2 eg: if marks1<50 || marks2<50) then student failed syntax3: ! relation ! true false 1) When we want two or more relations to be true for one action then we use AND operator(&&), for example if A>B and A>C are true, then ‘A’ is said to be bigger than B,C. In C-lang, it is written as: if(A>B && A>C) here if both conditions A>B and A>C are satisfied, then the operator && gives the result 1 (true). If anyone of them is false, the result is 0 (false). C-Family 19 Introduction to C 2) When we want either of relations to be true for one action, then we use OR operator(||), for example, If any marks1<35 or marks2<35 or marks3<35 are true, then student is “failed”. in C program, it is written as if( marks1<35 || marks2<35 || marks3<35) if anyone relation is satisfied, the operator || gives the result true. If all are false, then result is false The following truth table gives result of logical operators A B A &&B A||B !A 1 1 1 1 0 1 0 0 1 0 0 1 0 1 1 0 0 0 0 1 D) Assignment operator (=) If you are new to the programming, you definitely misunderstand it as an “equal” comparison operator which we use in mathematics. But in C, it is used differently to copy one location value to another location. It is used to assign(copy) right hand side expression’s value to left hand side variable; i.e, it copies RHS expression’s value to LHS variable; Syntax1: variable=expression; Syntax 2: variable1 = variable2 = variable3 =... variableN = expression; a a = 10; //assigns 10 to ‘a’ (puts 10 in a’s memory) 10 b = a; //assigns ‘a’ value to ’b’, after this instruction both b a a , b contains 10 10 10 e f g h e=f=g=h=100; // assigns 100 to all e, f, g, h 100 100 100 100 c=a+b; // the addition value of a,b assigned to c a+b=c; // error, not following syntax rules 10=a; // error, not following syntax rules E) Arithmetic assignment operators (shortcut operators) These shortcut operators are used when left hand side operand is repeated in right hand side at assignment operation. For example ‘salary = salary + 1000’, this can be taken in short form as ‘salary += 1000’ The operators are : +=, -=, *=, /=, %= ……etc. a = a + 10; a += 10 a = a - 10; a -= 10 a = a * 200; a=a* 100; note: these short operators somewhat confusion as a result discouraged in modern programming. C-Family 20 Introduction to C F) Increment or decrement operators (++ , --) in programming, it is often needed to increment/decrement variable values by 1. for this, C provides a very important and versatile operators called ‘++’ and ‘- -‘. these are very famous operators and almost all languages following in computer science.. ++ is an increment by one operator -- is a decrement by one operator Let us take one example k=5; // sets 5 to k k++; // this instruction increments ‘k’ value by 1, so it becomes 6 so this ‘k++’ is a short form of k=k+1 These two operators are again classified into pre & post increment/decrements 1) ++variable; // pre increment 2) --variable; // pre decrement 3) variable ++; // post increment 4) variable --; // post decrement Pre increment/decrement has highest priority than any other operator. Hence, this operator is evaluated before any other operator, whereas post increment/decrement has lowest priority than any other operator. Hence, this is evaluated after all other operators are evaluated; (for clarity sees the operator priority table) Note: the parenthesis ( ) has no effect on these operators. For example: 2*(a++) is equal to 2*a++; Let us take some examples, Let a=5, b=10; 1) a++; // this is equal to a=a+1; here ‘a’ becomes 6 b--; // this is equal to b=b-1; here ‘b’ becomes 9 2) b = ++a; this is equal to given below, first pre-increment and then assignment ++a; b=a; result is: a gains 6, b is gains 6 3) b = a++; this is equal to given below, first assignment and then post-increment b=a; a++; result is: b gains 5, a gains 6 4) b = ++a + ++a + a++; this is equal to given below, we have two pre-increments, and one post-increment) ++a; // pre increment, so do first ( here ‘a’ becomes 6) ++a; // pre increment, so do first (here ‘a’ becomes 7) b=a + a + a; // add all values (b=7+7+7) a++; // post increment, so do last (here ‘a’ becomes 8) Result of a, b are: a is 8, b is 21 note: So first do all pre increments, next process normal expressions, at last do all post increments. 5) b = a++*3 + ++a + 5*++a; this is equal to given below ++a; ++a; b=a*3+a+5*a; a++; C-Family 21 Introduction to C G) sizeof():operator gives the size of memory which is occupied by the variable or constant or data type sizeof(int) 2 sizeof(long int) 4 sizeof(k) 2 // let k is int type variable sizeof(10) 2 // 10 is int type value H) Comma operator(,) : It is used to separate two or more instructions in the program. It is used in several contexts in the programming. The actual behavior of comma operator is that, it returns the right hand side operand value as the result of the expression. a=2, b=3, c=10; // Here comma works as separator c=a , b; // it is combination of two instructions “c=a and b”, but ‘b’ does nothing a = (b, c); // it is also a combination of two instructions, “b and a=c” Operator precedence In general, complex expressions are formed with the combination of mathematical or logical operators. While evaluating such expressions, initially the sub expressions are evaluated according to the precedence. For example, the expression 5+2*4 evaluated as 5+813. Observe the following table showing the relative precedence of operators in c. Just look once about this precedence, we can learn in detailed in next chapters. Priority 1 () [] -> . Priority 2 ! ~ +(sign) -(sign) ++ -- (pre incr/decr) Priority 3 sizeof &(reference) *(de-reference) Priority 4 * / % Priority 5 + - Priority 6 << >> Priority 7 < <= > >= Priority 8 == != Priority 9 ^ | & ( ORing, ANDing) Priority 10 && || Priority 11 ?: (conditional operator) Priority 12 = *= /= %= += -= &= Priority 13 ^= |= <<= >>= Priority 14 Comma operator (,) Priority 15 ++ -- (post increment/ decrement) In the above table, Operators in the same row have the same precedence. Among same precedence operators, the evaluation takes place from left-to-right side in the expression. Only the assignment & unary operators are performed from right-to-left. For example a=b=c=d, here first c=d is performed later b=c …. Consider the expression: 1+ 2*3-4+5*6 //left to right performed 1+6-4+5*6 1+6-4+30 7-4+30 3+30 33 C-Family 22 Introduction to C How to write expressions in C An expression is a systematic combination of operands and operators to specify the relation among the values. However, any single constant, variable is also called an expression. For example 1+2 4*5 22/7 10%3 10>5 a a+b 1==0 4<<1 55<=100 -10 10 b a<c C language allows us to use complex expressions, wherein such expressions should be cautiously handled; otherwise it leads to logical errors. Let us see, how an expression should be typed in correct syntax. For example: 1. ax3 + bx2 + c x + d : Answer a*x*x*x + b*x*x + c*x + d 2. -b+ √b2- 4ac : Answer (-b+sqrt(b*b-4*a*c))/(2*a) 2*a 3. ax45 + 6x5 : Answer ( a*pow(x,45)+6*pow(x,5)/(c*x+7)) cx+7 Here pow() and sqrt () are functions, finds power and square root of a given value. Variable and its Naming rules Program means collection of data and instructions, the data is represented in terms of names such as age, experience, salary …etc; these names are called variables, which denote a value of a particular instance in the program; Thus, variable is said to be a name given to the memory location in computer main memory, wherein constants are stored; these constants may vary during execution of program. Rules for naming variables, While naming a variable, we should follow rules as explained below First letter must be an alphabet Only alphabets, digits and underscore are allowed in variable names We cannot use any other symbols like comma, hyphen, period…etc. Spaces are strictly not allowed. Should not be a keyword like ‘if’, ‘else’, ‘while’ …etc. The variable name can contain a maximum length of 32 characters. some valid names Some invalid names basic_salary 123pq // digits not allowed as first net_ salary ab,cd // comma not allowed age first-person // hyphen not allowed weight double // keyword name i and j // spaces marks1 int // keyword basicSalary units/month // other symbols not allowed for1 basic salary // space C-Family 23 Introduction to C Declaration of variables The declaration specifies name, size, type and other characteristics of a variable. Before using any variable, it must be introduced to the compiler about the name, size and type of data it is going to hold. This introduction is called variable declaration; it involves creation of memory in the RAM and substitution of logical address (binding) where ever it is used in the program. Syntax: <data type> <variable1>, *<variable2>, <variable3> … <variable n>+; Here in the syntax, the symbols “< >” represent user-defined and are compulsory, whereas square brackets [] represent optional. [This is old style syntax, now a days nobody following this syntax] The above syntax can be written as: dataType variable1, variable2, variable3…; For example: int k1, k2=10; K1 k2 Garbage value 10 2 bytes 2 bytes This declaration creates 2 bytes of memory space for k1, k2 in RAM; Here k1 has not been assigned with any value, so by default, it contains garbage value (un-known value), whereas K2 has been initialized with 10; Let us see more examples: int age, experience; // holds person age and experience char day, month; // holds day, month of a date int year; // year of date float salary; // salary of employee Initialization of variables We can set a value to the variables at the time of declaration ie, at the time of creation of memory. This is called initialization of variable. eg1: int k1=10; // this is called initialization, not an assignment, here k1 initialized with 10; eg2: int k2; ---- K2=20; // this is not initialization, it is called assignment. Note: here above 2 examples initialization & assignment affects the same result, we can follow either. Garbage value At the time of declaration, when a variable is not initialized with any value, then by default it holds an unknown value called garbage value. This value may be +ve, or -ve or sometimes zero. After completion of execution of one program, the program’s binary code or data will not be cleaned automatically from the memory by the O.S, it exists until the next program is loaded into the same memory; when a new program is loaded into this same memory, the old program’s code & data gets overwritten (replaced). But when just space is allocated for new program variables, in this space, the previous program’s binary values found or collected to these variables, which are anyway garbage to the new program. This garbage exists until any new values scanned or assigned to this variables. For example, int X=100, Y; // here X contains 100, but Y contains garbage value. Note: Some times, this garbage may belong to our current running program itself. When a function is terminated, its variable’s space is freed and reallocated for another function’s variable. So in this way the garbage values come into picture. C-Family 24 Introduction to C ‘C’ comment line Comment lines are simply a passage of meaningful text, to give a brief idea about author of program, purpose of program, and other details. It is a good programming practice giving comments to increase the readability of a program. Programmers always add comments at instructions wherever complexity is seen. Thus, the logic of program can be understood by studying comments. We can write our comments anywhere in the program by enclosing the comment text within a pair of /* … */ This is as /* ……….. comment line 1 …………… ………… comment line 2 …………… ………… comment line 3 …………… */ for eg: /* this program is written by Srihari, dated on 16-9-2020 this takes two input values and finds sum of them */ This comment lines are ignored (skipped) while compiling a program, and hence they are not executed. Comments are not a part of the program, they are for documentation purpose. This is ‘C’ comment line and can be used as single line or multi-line in the program. C++ comment line: C++ supports single line comment, the syntax is // ……………………………..comment line……………………………………. The C++ is a superset of C, hence, we can compile C programs on C++ compiler, hence, we can use C++ comment lines in C programs (of course I myself used this comments during explanation of things). C-Family 25 Introduction to Programming Introduction to programming Functions In general speaking, in our real life, several people are required to accomplish one task with each one of them doing one’s specialized sub task. Similar to this, a programmer cannot develop the entire code of one application; instead many programmers contribute the code in terms of sub programs called functions. Function is a sub-program that performs a given sub task in a program. Here each function is designed and written for specific purpose such as calculating power, square root, logarithms …etc; thus collection of such functions makes a C-program. For example, sqrt() is a function, it gives square root value. eg: sqrt(16)4 The functions are classified into ① library functions, ② user–defined functions Library functions These are ready-made functions, designed and written by the C manufactures to provide solutions for basic and routine tasks in the programming. For example, the mathematical functions pow() & sqrt(), and I/O functions scanf() & printf (),etc. The vendor of C, supply these predefined functions in compiled form with C software. There is huge collection of such compiled functions available in C, hence, these collections are called functions Library. The library functions-body placed in separate files with name “xxxx.lib” in compiled format and they are automatically linked to our program at the time of compilation, and these are hidden to the programmer. (We will see about user-defined functions in functions chapter) 1) Math library functions The familiar math functions are pow(), sqrt(), sin(), cos(), tan(), log(), log10(),etc. 1) pow(x,y) is a function calculates xy, where x is base and y is exponent. 3 k=pow(2,3); // k=8; here 2 is calculated and assigned to ‘k’ 2) sqrt(x) is a function calculates square root of x. K=sqrt(16); // k=4; 3) log() is a function, finds the log2 value The syntax of these functions are defined in ‘math.h’ file and any function is used in the program, it should be included at the beginning of program as: #include<math.h> 2) Terminal I/O library functions Generally, all programs are needed to interact with keyboard or monitor devices to accept and print values. Input is taken from the keyboard and the output is displayed on the screen. The printf() and scanf() are familiar I/O functions defined in ‘stdio.h’ file printf(): displays message or output values on the screen, the programs are stored permanently in secondary storage devices like hard disk and when they get executed, loaded from hard disk to RAM and then instruction by instruction is executed by the processor. Here nothing is displayed on the screen while executing a program in the memory, if something need to be shown on the screen, we must add an instruction called “printf()”, which displays data/message on the screen. For example inside program On the screen printf(“hello”); hello Syntax: printf(“format string”, list of values); here the “Format string” represents, what format we want to display on the screen for the list of values; the format strings are C-Family 26 Introduction to Programming %d for printing integer value . (In this context ‘%’ is not a modulus operator) %05d for printing integer in 5-digit format by padding with zeros. %f for printing float value %.2f for printing with fraction values like 123.45 %5.2f for printing float in 5.2 decimal formats Let us have some examples, how printf() shows output on the screen 1. printf(“%d”,123); 123 2. printf(“%5d”,123); BB123 // B means blank space 3. printf(“%05d”, 123); 00123 4. printf(“%02d”, 123); 123 5. printf(“%5.2f”, 323.4); BB323.40 6. printf(“%.2f”, 1323.4256); 1323.42 7. printf(“%8s”, “Hai”); HaiBBBBB // B means blank space 8. printf(“%-8s”, “Hai”); BBBBBHai // right justification 9. let w=10, c=29.50; printf(“weight = %d, cost = %f”, w, c); weight = 10, cost = 20.50 10. let x=500; printf(“ hello %d world”, x); hello 500 world 11. printf(“hello world”); hello world // notice that, the values are not specified. 12. prinf(“10+20=30”); 10+20=30 // here + , = doesn’t work like operator, they are just to print on screen so the printf() showoff as it is whatever message defined inside quotes(““) except %d, %f, … List of all format strings The following list specifies valid format characters %c It denotes single character (signed/unsigned char) %d or %i It denotes signed decimal integer (signed int) %f single precision floating point number (float) %u unsigned decimal integer (unsigned int) %ld signed long decimal integer %lu unsigned long decimal integer %If double precision floating point number (double) %Lf high precision floating point number (long double) %% single % symbol %x unsigned hexadecimal integer %o unsigned octal integer scanf(): used to read input values from the keyboard, here user has to feed/enter values in the keyboard while running a program, based on input values, the output is displayed. The scanf() waits for user response until he/she enters some values from the keyboard. ie, pauses the program execution until he enters input values in the keyboard with the end of input “enter-key”. For example, C-Family 27 Introduction to Programming program keyboard scanf(“%d%d”, &a, &b); 10 20 ⤶ syntax: scanf(“format string”, list of variable addresses); eg. scanf(“%d %f”, &age, &salary); Here ‘&’ is called address operator, it must be prefixed before every variable at scanf(). [We will see in pointer topic why this address operator is required in the scanf(), until then just follow it] 1. scanf(“%d%d”, &x, &y); // accepts two values from keyboard and assigns into x , y; 2. scanf(“%d,%d”, &x, &y); // the input values must be separated by coma(,) 10,20⤶ 3. scanf(“%d-%d-%d”, &day,&month,&year); //the date input must be separated by hypen(-) 10-2-3002⤶ 4. scanf(“%d/%d/%d”, &day,&month,&year); //the date input must be separated by slash(/) 10/2/3002⤶ 5. scanf(“%d%d”, &x, &y); //the default is space between two values 10 12⤶ Adding library function’s signature (proto-type/declaration) Compiling and generating machine code has 2 stages(compiling+linking), compiler generates machine code of each function separately in object code format(semi executable code), later linker links all such semi executable functions into single executable file(machine code format). If any library function is used in the program, then how the compiler finds whether it is used (called) properly or not? Because they were already in compiled form and linked directly at linking time. So the compiler does not show if any errors exist; if we do so, then the linker may show linker-error or sometimes it may leads to run-time error. For example, by mistake if pow() function is called with ‘k=pow(3,4,5) to find 34 then the linker may show error, because the actual function takes only two values like K=pow(3,4); To solve this problem, the original proto-type of function should be added to our program to check out syntax errors and to raise them; the functions original proto-type is provided by C-manufacturers in separate files with name “xxxx.h”. So if any library function is used in the program, then related header file should be included. So that, it compares our function-call statements with the original proto-type and if both are not matched then compiler raises an error. (The word proto-type is also called function declaration/signature.) Syntax to include file is #incldue<file name .h> #inclue<math.h> // to check syntax errors at math functions calls #include<stdio.h> // for all I/O function signatures #include<graphics.h> // for graphics functions #incldue<string.h> // for string functions At beginning, these files name were stdio, math, string.. etc, the extension “.h” was not given then, but overtime, when they appears as program header, gradually start calling them as header files, so added “.h” C-Family 28 Introduction to Programming About main() function The main() works like a start & end point of the program, the execution starts at “void main()” and ends at last closing braces; Actually, the main() is also a function; among all the functions, main() is an important and reserved function, it tells to the compiler the starting & ending point of program. The main() can be written in any of the following ways, and all of them have the same meaning & works in similar way; (of course different vendors of C, suggested in different ways to this) void main () int main () main() { -------- { -------- { ---- -------- -------- ----- -------- return(0); ----- } } } Now, in C program, at least one function must be there, that is main(); its execution starts by operating system when user runs the program. The main function is called by the operating system, that is indirectly by the user [ by pressing command control+f9 in turbo C++ editor or typing .exe file name at DOS prompt, or double click on icon of .exe file in windows]; General Structure of C program The C program looks like following way Line1 // Comment line about program Line2 file inclusion statements Line3 void main() { Line4 variable declaration Line 5 input statements Line 6 process statements Line 7 output statements } line1: we already discussed in previous chapter, now I am repeating same with more clarity. In this line, the comments are added about program, ie, the purpose of program, input/output of program, who & when has written, etc, are specified. Writing comments is a good programming practice. However, this is optional. Compiler ignores comment lines. line2: Here header files of library functions and other files are included. For example “#include<math.h> for math functions, #include<stdio.h> for I/O functions ….etc; line3: “void main ()” represents starting point of program, the execution starts at this point. line4: variables are declared at the beginning of program block, and when this line is executed, space is allocated for variables in the RAM. line5: the input statements are used to accept values from the keyboard and other terminals. line6: Here process statements specify the processing of input data line7: here the output statements are used to show output on the screen or other terminals Note: the opening and subsequent closing braces {} defines a block; as per C syntax rules, the instruction must be given inside block; all instructions must be terminated by “;” C-Family 29 Introduction to Programming Coding style of C program Unlike some other programming languages (COBOL, FORTRAN, etc), C grants a freedom to every programmer to follow his own style of coding. However, ensure that, the program should be readable and easy to debug by others. For example, see the following instructions a=10; b=20; c=a+b; k=100; the above sequence of instructions can be written in single line as: a=10; b=20; c=a+b; k=100; to increase readability, we can give more spaces or empty lines between expressions, that is, we can add spaces before and after of every token such as punctuation symbols, operators, variables and other places. For example: 1. a+b can be written as: a + b // spaces added before & after ‘+’ symbol 2. a+b<d*e can be written as: a + b < d * e // observe space added here 3. printf(“hello”); can be written as: printf ( “hello” ) ; Developing, compiling, running, and debugging a program A) Developing: Once a program has been designed and written, it must be entered before executing on the system. If one wants to feed the program into computer, he needs a software tool to type the instructions, and also allow modifying, deleting, copying, and other editing facilities. This is provided by the special software called Editor. We have several editors to feed (type) the program into computer. The editors like notepad, word pad, ms-word … etc, but today, every language supplier providing a special Editor along with compiling, debugging, running facilities. All these features are available in one editor therefore it is called “integrated development environment (IDE)”. Generally, the C++ editor is used instead of C, because C++ is a superset of C. the C++ editor is more convenient than C since as it is a newer version. note: we can use notepad editor to type the program code, but it does not provide to compile/run the programs. It is just editor to type and save the code. So IDE is the ultimate tool for programming. The following figure shows the turbo C++ IDE editor on DOS. File menu: this menu-driven facility used to handle file operations such as opening a new file, or opening an existing file, saving a file, etc. Edit menu: this is used to copy, cut, and paste a group of selected lines. Compile menu: to create object files, making executable files, linking a program…. C-Family 30 Introduction to Programming B) Compiling & Running: Irrespective of number of languages in the market, the computer processor understands only one language called machine language, this language designed with basic set of operations like addition, subtraction, multiplication, comparison, etc. These operations are designed in circuitry level in the form of 1’ and 0’s to execute directly by the processor, therefore this language is also called low level or binary language. The compiler is translation software, which translates high level program into machine code; the compiler generates machine code of each line and stores into another file called “exe” (executable) file; this file can be executed directly on the machine; once the exe file is generated then compiler and source file are not required. These are required when modification are needed in the source code; Thus, every high level language program must be translated to machine code; for this reason, every language must have its own compiler to translate it into machine code; for example, the C compiler for C programs, C++ compiler for C++ programs. if two same programs are written, one in C, and another in C++ then two compilers generates equivalent machine code; compilation process has two stages called compiling + linking In compilation stage, it checks the typing and syntax errors, after rectifying them, it creates object file, which is semi executable file. Here each function compiled independently and code is generated separately as they are in source file. Later linker links all library and user-defined functions together to form a single executable file. For example, main() function with printf() as shown in the above examples. The following figure shows how they are compiled and linked to the program. C program file. let file name is “sample.c” Compiler software Produce semi executable file Object file “sample.obj” Library functions Linker Software are attached here Executable file “sample.exe” C-Family 31 Introduction to Programming Procedure to execute C-program in turbo C++ IDE on DOS environment Open the Editor (tc) Open a new file (alt+fnew) Type the C program Save the program into disk (f2) Compile the program (f9) Run the program (ctrl+f9) Type the input values Watch the output values (alt+f5) To close lab(alt+x) (al(Alt+x) Close the program (alt+f3) To do one more program D) Compiler vs Interpreter Interpreter is a translator, which translates our ‘C’ program into machine code, here it translates one line at a time and then executes immediately on the machine. That is, it translates line by line and then executes instantly on the machine. So it also called instant compiler. Whenever we run the program, the interpreter translate and executes, if we run more times, more translations it takes. It seems to be unnecessary translating same program again & again in every use. This redundant translation leads to wastage of CPU time and other resources. Actually, interpreter is used for single-use applications like queries, commands, to check spellings in word processing, language translators, internet browsing, etc. The web-sites are coded in the form of html, css, etc and these files are downloaded and interpreted by the browsers, web browsers are nothing but interpreters. So for single use applications interpreter is the choice. Compiler translates line by line and stores into “.exe” file to execute later time, thus instead of executing each line instantly on the processor, it stores into .exe file. Now this file contains all machine code instructions of our C-program’s source file. This file can be executed directly on the machine whenever we want, while running this .exe file, the compiler is not required. So here, no translation takes place again & again in every use. The interpreter doesn’t create “.exe” file, so in every use translation is required. Some kind of applications needed to execute regularly like calculator, business accounting, games, etc. Here compiler is used to generate machine code file, so that, such file can be executed at any time without translating again and again. Conclusion: compiler is the choice for regular use applications, whereas interpreter is the choice for single use application. For single use applications, it is un-necessary creating machine code file. C program file Compiler : translates line by line File: ‘Sample.exe’ say ‘Sample.c’ sends to exe file all machine code instructions are collected here C program file Interpreter Processor say ‘Sample.c’ (translates one line at a time and executes given instruction sends to processor to exeucute) one at a time C-Family 32 Introduction to Programming Escape sequence characters The symbol back slash (\) is called escape character, used to represent some special keys or symbols like New Line, Carriage Return, Tab Spaces, etc. Escape sequence characters are 1. \n new line (new line) 2. \t horizontal tab space (4 gaps) 3. \\ single back slash (\), inserts slash in output. 4. \” double quotes character (differently with the string enclosure). 5. \’ single quote character (differently with the character enclosure). Let us see the following examples. 1. printf(“Hello\nHari”); shows “Hello” in one line and “Hari” in next line 2. printf(“Hello\tHai”); Hello Hai ( 4-gaps between Hello Hai ) 3. printf(“\”hello\””); “hello” 4. printf(“\\ hello\\”) \hello\ Finding area and circumference of circle The following program accepts radius from keyboard and prints area and circumference. Logic: based on input value radius, the output (area and circumference) is calculated; Process Program input: radius(r) void main() output: area ( ) { float radius, area, circum; circumference (2 printf("Enter radius of circle :"); scanf("%f", &radius); Input & output area=22/7.0 * radius * radius; ip: Enter radius of a circle: 5 circum=2*22/7.0*radius; op: Area = 78.57143 printf("the Area is %f\n", area); Circumference = 31.40 printf("\nthe Circumference is %f", circum); } Demo program for swapping two variable values The following program explains how 2 variable values are exchanged one with the other. This is common task in the programming and also known as swapping of data. Logic: Let the input values are 23 & 45 and assigned to X,Y. See what happens, if one has written as X=Y; Y=X; void main() Output { int x, y, temp; ip: enter 2 values: 23, 45 printf("enter 2 values :"); op: before swapping, the x , y are 23, 45 scanf("%d%d", &x , &y); after swapping, the x , y are 45, 23 printf("\n before swapping the x,y are %d,%d", x, y); temp=x; // saving ‘x’ value in temporary variable. x=y; // copying ‘y’ value to ‘x’ y=temp; // copying ‘x’ value to ‘y’ printf("\n after swapping the x,y are %d %d", x, y); } When ‘X=Y’ executes, the value of Y(45) is assigned to X and we lost the current value 23 of X. Now the X & Y contains same value 45. When the second instruction Y=X executes, the same value 45 copied back to Y. C-Family 33 Introduction to Programming Now both the variables hold same value and our purpose can’t be survived. Therefore, to exchange two values a third variable is required. This is explained in the following program. Accepting basic salary of employee and calculating net salary This program scans basic salary from keyboard and prints net-salary. The net is sum of BASIC+HRA+TA Process: HRA is 24% on basic ( HRA House Rent Allowance) TA is 7% on basic ( TA Travelling Allowance) net salary = basic + hra + ta; void main() { float basic, hra, da, ta, netSalary; printf("Enter basic salary :"); scanf("%f", &basic); hra=24*basic/100; // calculating 24% for house rent allowance ta=7*basic/100; // calculating 7% for travelling allowance netSalary=basic+ta+hra; printf("Net salary = %f", netSalary); } Printing sum of arithmetic, relational, and logical operations of two values void main() output { int a,b; printf("enter 2 values :"); ip: 11 4 scanf("%d%d", &a, &b); op: a+b=15 printf("\n a+b=%d", a+b); a-b=9 printf("\n a-b=%d", a-b); a%b=3 (remainder) printf("\n a%%b=%d", a%b); a>b=1 (true) printf("\n a>b=%d", a>b); a<b=0 (false) printf("\n a<b=%d", a<b); } Note: In condition place, the value non-zero is taken as true, whereas, zero is taken as false Finding reverse of 2-digit number This program accepts a two-digit number like 47 and prints the reverse of it (74). Logic: For example, the value 735 composed as 7*100 + 3*10 + 5*1. Similarly, the reverse of it is 5*100 + 3*10 + 7*1 In this way, we can find the reverse of two digit number void main() 10 ) 47 ( 4 n/10 { int n, reverse; 40 printf(“\n enter two digit single number :”); ---------- scanf(“%d”, &n); 7 n%10 reverse=n%10*10+n/10; printf(“\n reverse = %d”, reverse); } Let us substitute the value 47 in the expression “reverse = n%10*10+n/10” reverse = n%10*10 + n/10; = 47%10*10 + 47/10 = 7*10+4; = 74 C-Family 34 Introduction to Programming Printing size of different data types The following program shows memory occupied by each data type in C. The sizeof() is an operator, it gives the size of variable or data-type. main() Output { long int k; printf("\n size of int is %d byte",sizeof(int)); size of int is 2 byte printf("\n size of float is %d byte",sizeof(float)); size of float is 4 byte printf("\n size of k is %d bytes",sizeof(k)); size of k is 4 bytes printf("\n size of 10 is %d bytes",sizeof(10)); size of 10 is 2 bytes (10 is int-type) } Converting time(H:M:S) into seconds format This program accepts a time in H:M:S format as input and prints output in seconds format. ip: 2 40 50 (2-hr , 40-min , 50-sec) ip: 0 2 50 (0-hr , 2-min, 50-sec) op: 9650 seconds op: 170 seconds logic: total seconds is N=H*3600 + M*60 + S // each hour has 3600 seconds, each minutes has 60 seconds. void main() { int H,M,S,N; printf("Enter time as hours minutes seconds format:"); scanf("%d%d%d", &H, &M, &S); N=H*3600+M*60+S; printf("output time in seconds is: %d", N); } Converting seconds time into H:M:S format Code to accept a time(N) in seconds format and prints output in H:M:S format ip: 7270 op: 02:01:10 ( 2-hours, 1-minutes, 10-seconds ) logic: divide N with 3600 and take the quotient as hours, (1hour=3600seconds) divide N with 3600 and take the remainder(R=N%3600). This R is the remaining seconds left after taking hours from N. Again divide R with 60 and collect quotient and remainder. The quotient would be minutes and remainder would be seconds. void main() { int H,M,S,N,R; printf("Enter time in seconds format:"); scanf("%d", &N); H=N/3600; R=N%3600; M=R/60; S=R%60; printf("output time is %d : %d : %d", H, M, S); } C-Family 35 Type Casting Type casting Process of converting a value from one type to another type is called type casting. In C, the type casting is done in two ways. ①Implicit type casting (automatic casting) ②Explicit type casting (manual casting) ①Implicit Typecasting For example, the expression 10+20.54(int+float), here the operand 10 automatically converts into float-type as 10.00, because, we must hand over same size and type of data to the CPU before computing. So compiler automatically is done this conversion. So implicit type casting automatically is done by the complier when two operands are not same type with in the expression. Let us see some examples, eg1: void main() { int x=5; float y=12.33, z; z=x*y; // here ‘x‘ behaves like a float-type at this expression printf(“ z value = %f”, z); // z value = 61.65 } eg2: void main() { float k; int a=10, b=3; k=a/b+5; printf(“\n Result of K = %.2f”,k); // Result of K=8.00 } Here, the expression a/b gives the int type result(3 not 3.33) as both a&b are integer operands. Later, this result is added to 5, which is again int type; finally this result gets converted implicitly to float and assigned to k. Therefore the output ‘Result of K=8.00’ eg3: int x=10; float y; y=x; // Here ‘x’ value 10 is promoted to float-type, so 10.00 stored into ‘y’ eg4: int x; float y=29.34; x=y; //Here the integer part of ‘y’ value 29 is assigned to ‘x’ eg5: long int x=9023455L; int y; y=x; //here, as ‘x’ is int-type, the right most 2 bytes of ‘y’ is stored into ‘x’ and results loss of some bits. Let us see some expressions and its automatic type casting Expression After conversion Result int/int no conversion int float/int float/float float int * int no conversion int int * long int long int * long int long int int * float float * float float float * double double * double double C-Family 36 Type Casting ②Explicit typecasting Sometimes, we need to convert explicitly to get desired result from the expression. syntax: (conversion-type) expression eg1: (float) 15 15.00 (int) 2.6 2 In the above expression, 15 is int. But, upon prefixing (float)15, its type will be changed to float (as 15.00). eg2: void main() { int a=10, b=3; float k; k=a/b; printf(“\n Before type casting K=%f”,k); k=(float) a/b; // here ‘a’ converted by me, ‘b’ is converted by compiler. printf(“\n After type casting K= %f”,k); } Before type casting K=3.000000 after type casting K= 3.333333 eg3: void main() { int a=30, b=20000; long int k; k = 10 + a*b; printf(“\n Before type casting K=%ld”,k); k = 10 + (long int) a*b; printf(“\n After type casting k=%ld”,k); } Before type casting K=10186 (un-expected value) after type casting K= 600010 K=10 + a*b here first, the result of ‘a*b’ is calculated and stored into temporarily variable (say it is T), later 10 is added to T. Finally T value is assigned to K. The nameless variable T is automatically created by compiler and it is of type int; because a & b are int types, so T will be the int type. But the result of a*b is bigger than the integer range and it cannot hold by T, so some bits are truncated while storing into T. K=10+(long int) a*b here ‘a’ is long int, which we converted , and ‘b’ is converted by the compiler. so T will be the long int and it can hold the result of a*b; Representation of Constants in C In programming, Data is represented in two ways in terms of constants and variable data. Constants are represented in special manner by adding format string or other symbols to the value. For example, ‘10L’ is long int type. Automatically, compiler understands some types of constants in the program. For example, the constant ‘10’ is considered as int-type, 34.55 as double-type, ‘A’ as char-type. These are default types and automatically understand by the compiler. But some constant types are needed to specify explicitly along with format string. The following list explains about all constant types. Do not use other symbols like comma, spaces, quote, etc while specifying constants. C-Family 37 Type Casting integer Constants A collection of one or more digits with or without a sign referred to as singed int constants. This is the default type for integral values. eg. 5, 256, 9113, 6284, +25, -62, etc are valid signed integers. Similarly to represent unsigned int, the format string ‘u’ or ‘U’ is suffixed to the value. eg. 67U, 43U, 4399u, 45u are valid unsigned integers. Note that, -3428u is also a valid number. Here this -3428 is converted into equivalent unsigned integer 62108. Because, here the sign bit is also considered as data bit. (But this style is not recommended) Some invalid declaration of integer constants are: 15,467 $25,566 4546Rs long integer constants for the long integer constants, the format string ‘l’ or ‘L’ is suffixed to the value. eg: 2486384L –123456L 5434545l –34545l are valid long int constants 893434lu -3Lu … etc are valid unsigned long integers. Octal int/long integer constants for the octal integers, zero is prefixed before the value. (0 is like octal). eg: 0123, 0574, 01, 046342L etc are valid octal integers. 0181, 09, 12, etc are in-valid octal integers. (In octal system 0-7 digits are used) Hexadecimal int/long integer constants in the hexadecimal number system, the symbols 0, 1, 2, 3 … 9, A, B, C, D, E, F are used. (Total 16 symbols are used; because, the number system’s base is 16) The symbol “0x or 0X” is prefixed before the hexadecimal number. For example: 0x1, 0x123, 0xa5, 0xfldb, 0x0, 0xABC, 0xflc etc are valid hexadecimals. character constants To specify a character constant, we must enclose the character within the pair of single quotes. eg. ‘A’ ‘z’ ‘s’ ‘8’ ‘+’ ‘;’ etc string constants It is a collection of characters enclosed within double quotes, used to represent names, codes, abels, etc. eg: “Hello! Good morning!” “Magic mania” “A” “123” “A1” “#40-5-8A” “C-Family” float constants (Real numbers) We can specify the real numbers in two different notations, namely general and scientific notation. Here the format string ‘f’ is attached at the end of value. In normal representation: 3.1412f -25.62f 98.12f -045632.0f 1.f 9.13f In scientific exponential representation: the syntax is [-]d.dddde[+/-]ddd where d is any digit. 2.32e5f (means 2.32 x 10^5 i.e. 232000.0) 12.102e-3f (means 12.102 x 10^-3 i.e., 0.012102) -2. 165e6f (means -2.165 x 10^6 i.e., -2165000.0) 3.68e3f (means 3.68 x 10^3 i.e., 3680.0) double constants: This is the default type for real numbers (floating point values). eg: 1.2 45.3 4.39393 349.34899034 45.4e15 44.54e4 (‘l’ or ‘L’ is option for double) long double: for the long double, the format string ‘l’ or ‘L’ is used. eg: 3.14L 314.41 (Equivalent to 314. 0L) 3.68e3L (Means 3.68 x 103 i.e., 3680.0L) C-Family 38 flow charts Flow chart It is a pictorial representation of flow of a program, which illustrates the sequence of operations to be performed to get the solution of a problem. It is often used as a visual planning tool, how the control to be moved from one point to another point to get a solution. It is like drawing a building plan before constructing a building. Flowcharts are generally drawn in the early stages of formulating computer solutions. It facilitates communication between programmers and business people. It plays a vital role to understand the logic of complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write the program in any high level language. The following mathematical symbols are used to represent specifications with directions to indicate the flow of control. Start/stop a program Rectangle for processing general instructions Circle for connection Arrows for directions Rhombus for decision making Parallelogram for Input/output from terminal Cylinder for secondary Memory (external storage) RAM (internal storage) Predefined actions File Looping C-Family 39 flow charts Algorithm In mathematics and computer science, an algorithm is a finite set of computational instructions that carry out a particular task, which takes input and produces desired output. In simple words, it is step-by-step oral explanation of logic how to construct instructions in a program; here English & math symbols are used to explain logic in words Flowchart depicts how the control to be moved in the program from one point to another point to get a solution, whereas algorithm tells step-by-step explanation how to construct instructions in a program. This is an independent method to explain the logic regardless of programming language used by the programmer. Here English and math symbols are used to explain the logic. People write algorithm for complex and complicated tasks to explain the logic in words, for example, sorting algorithms, searching algorithms, shortest path in network …etc. Any algorithm follows, 1. Describes the input and output 2. Describes the data entities with purpose (variables) 3. Explains process in step by step using English and math symbols 4. Add comments at every step what it does, use square brackets [ ] for comments 5. Each instruction is clear and unambiguous (definiteness) 6. The algorithm terminates after finite number of steps Note: there are no standard rules and regulation to implement algorithm/flowchart, so one can implement one’s convenience but ensure that other must be understood it. The flowchart and algorithm to find big of two numbers Flow chart to find big of two numbers Algorithm to find big of two numbers Start step1: let us take a,b as type integer variables step2: let us take ‘big’ to store big value read(a,b) step3: [ scanning input from keyboard ] read(a,b) step4: [ finding big of 2 numbers ] if a>b if(a>b) big=a else big=b; true false step5: [ printing output ] big=a big=b print(big) step6: [ closing the program] stop Print(big) stop C-Family 40 flow charts Flowchart for finding big of three numbers Start read(a,b,c) true false if(a>c) if(a>b) if(b>c) true false true false print(a) print((c) print((b) print((c) stop Flowchart to Find sum of 1 to n numbers(1+2+3+4…+n) start print(“enter n:”); read(n) sum=0; i=1; false if(i<=n) true sum=sum+’i’; i++; print(sum) stop
Enter the password to open this PDF file:
-
-
-
-
-
-
-
-
-
-
-
-