0% found this document useful (0 votes)
20 views34 pages

UNIT 1 Programming in C

This document serves as an introduction to the C programming language, detailing its history, key features, and structure of a C program. It covers the evolution of C from earlier languages, its characteristics, and its applications in system programming and software development. The document also provides guidance on writing and compiling a simple C program, including the use of header files and the importance of functions.

Uploaded by

muzainakhanum24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
20 views34 pages

UNIT 1 Programming in C

This document serves as an introduction to the C programming language, detailing its history, key features, and structure of a C program. It covers the evolution of C from earlier languages, its characteristics, and its applications in system programming and software development. The document also provides guidance on writing and compiling a simple C program, including the use of header files and the importance of functions.

Uploaded by

muzainakhanum24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
ONLINE SALA LIBRARY i Introduction to C This chapter aims at acquainting students with writing programs in C. To sen with we will read about the background of C language, its key features, anc Uses in the real world. Then we will gradually move forward to understand the structure of a C program and the types of files that will be used to execute the program. Then moving a step further, we will learn about data types, EBM ntropuction The programming language C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories to be used by the UNIX operating system. It was named ‘C” because many of its features were derived from an earlier language called ‘B’. Although C was designed for implementing system software, it was later on widely used for developing portable application software. Cis one ofthe most popular programming languages. It is being used on several different software platforms. In a nutshell, there are a few computer architectures for which aC compiler does not exist. It is @ good idea to lear C because it for a long time which means there is available on it. Quite a few other has been around @ lot of information identifiers, constants, variables, and operators available in C language. 2.1.1 Background Like many other modem languages, C is derived from ALGOL (the first language to use a block structure). Although ALGOL was not accepted widely in the United States but it was widely used in Europe. ALGOL's introduction in the 1960s led the way for the development of structured programming concepts. Before C, several other programming languages were developed. For example, in 1967 Martin Richards developed a language called BCPL (Basic Combined Programming Language). BCPL was basically atype-less (had no concept of data types) language which facilitated the user with direct access of memory. This made it useful for system Programmers. Then in 1970, Ken Thompson developed a language called B. B was used to develop the first version of UNIX. C was developed by Dennis Ritchie in 1972 that ‘ook concepts from ALGOL, BCPL, and B. In addition to the concepts of these languages, C also supports the concept of data types. Since UNIX operating system was also developed at Bell Laboratories along with C language, C and UNIX are strongly associated with each other, For many years, C was mainly used in academic institutions, but with the release of different C compilers mmercial use and popularity of UNIX, C was widely secepted by computer professionals, € (also known as Traditional C) was documented and popularized in the book The C Programming Language by Brian W) Kernighan and Dennis Ritchie in 1978, This book was so popular that the language came to be known, as *K & RC’, The tremendous growth of C language resulted in the development of different versions of the Janguage that were similar but incompatible with each other. Therefore, in the year 1983, the American National Standards Institute (ANSI) started working on defining the standard for C. This standard was approved in December 1989 and came to be known as ANSI C. In 1990, the International Standards Organization (ISO) adopted the ANSI standard, This version of C came to be known as C89, In 1995, some minor changes were made to C89, the ‘new modified version was known as C95. Figure 2.1 which ~ {ior ALGOL BCPL ‘raditional C KaRC ANSIC ANSI/iSO C 8 98 Taxonomy of C language nifat Introduction toe \ 43} shows the taxonomy of C language. During 1M ¢ and Java programming languages becarne perpilar annem the users so the standardi a few features of C-/h wrod erence its usefulness. So, in 1999 when some significant changes were made to C95, the modified version care to be knwrwn as C99. Some of the changes made in the C79 versiom are as follows: sion committee of © felt that a if added to ¢ © Extension to the character types, so that they ¢an support even non-English characters © Boolean data type ‘© Extension to the integer data type + Including type definitions in the for staternent ‘Inclusion of imaginary and complex types «© Addition of /, better known as C+ style line corranent 2.1.2 Characteristics of C C isa robust language whose rich set of built-in functions and operators can be used to write complex programs. The C compiler combines the features of assembly languaze ‘and high-level language which makes it best suited for writing system software as well as business packages ‘Some basic characteristics of C language that defines the language and have lead to its popularity as programming language are listed below. In this book we will learn all these aspects. © A high level programming language enables the programmer to concentrate on the problem at hand and not worry about the machine code on which the program would be run. # Small size—C has only 32 keywords. This makes it relatively easy to leam as compared to other languages. fe Makes extensive use of function calls. # Cis well suited for structured programming. In this programming approach, C enables the users to think of problem in terms of functions/modules where the collection of all the modules makes up a complete program. This feature facilitates easiness in program debugging, testing, and maintenance « Unlike PASCALitsupportsloose typing asacharacte can be treated as an integer and vice versa. | 14 |_Programmingin¢_ «Structured language as the code can be organized a a collection of one or more functions. «Stable language. ANSI C. was created in 1983 and since then it has not been revised # Quick language: asa well written C program is likely to be as quick as or quicker than a program written in any other language. Since C programs make use of operators and data types, they are fast and efficient. For example, a program written to increment a value from 0-15000 using BASIC would take 50 seconds whereas a C program would do the same in just | second. «© Facilitates low level (bitwise) programming, © Supports pointers to refer computer memory, array, structures, and functions. © Core language. C is a core language as many other programming languages (like C++, Java,Perl, etc.)are based on C. If you know C, learning other computer languages becomes much easier © C isa portable language, i, aC program written for one computer can be run on another computer with little or no modification. © C is an extensible language as it enables the user to add his own funetions to the C library. Cis often treated as the second best language for any given programming task. While the best language depends on the particular task to be performed, the ‘second best language, on the other hand, will always be C. 2.1.3 Uses of C isa very simple language that is widely used by software professionals around the globe. The uses of C language can be summarized as follows. + C language is primarily used for system program ‘ming. The portability, efficiency, the ability to access specific hardware addresses and low runtime ‘demand on system resources makes it a good choice for implementing operating systems and embedded system applications. © C has been so widely accepted by professionals ‘that compilers, libraries, and interpreters of other programming languages are often implemented in C. _ es and convenience reasons, C is ran intermediate language for of other languages. Examples of C this way are BitC, Gambit, the ‘Squeak, and Vala. imple vy pilers who Use CGamaow Haskell Compiler SUS programmin wee. was desiane 8 Basically. Ts was not meant to be used as a compiler language and Wer erefore, although C can be used tage ane ge language it snot an ideal option This ied to the development of C-based intermediate nguages such as C™ 5 EER structure OFAC PROGRAM | program is composed of preprocessor commands, & global declaration section, and one or more functions (Figure 2.2). ae eee Preprocessor directives The preprocessor directives contain special instructions that indicate how to prepare the program for compilation. One of the most important and commonly used preproces- sor commands is include which tells the compiler that to execute the program, some information is needed from the specified header file, In this section we will omit the global declaration part and will revisit it in the chapter on Functions. AC program contains one of more functions, where a function is defined as a group of C statements that are executed together, The statements in a C program are written in a logical sequence to perform a specific task. The main() function is the most important function and is a part of every C program. The execution of a C program begins at this function, ‘All functions (including main ()) are divided into two parts—the declaration section and the statement section, The declaration section precedes the statements section and is used to describe the data that will be used in the function, Note that data declared within a function are known as local declaration as that data will be visible only within that function. Stated in other terms, the life-time of the data will be only till the function ends. The statement section in a function contains the code that manipulates the data to perform a specified task. From the structure given above we can conclude that a c program can have any number of functions depending on the tasks that have to be performed and each function can have any number of statements arranged according to specific meaningful sequence. Programmers can choose any name for the functions. Its not mandatory to write Function, Function2,ete,, but with an exception that every program must contain one function that has its name as main() wy EER writine THE FIRST C PROGRAM To write a C program, we first need to write the code. For this, open a text editor. If you are a Windows user youmay Use Notepad and if you prefer working on UNIX/Linuyj you can use emacs or vi. Once the text editor is opened on your Screen, type the following statements Introduction toc | 15 | Hinclude int main() { print€("\n Welcome to the world of ¢"); return 0; ) Output Welcome to the world of c #include This is a preprocessor command that comes as the first statement in our code. All preprocessor commands start, with symbol hash (#). The #include statement tells the compiler to include the standard input/output library or header file (stdio.h) in the program. This file has some in-built functions, So simply by including this file in our code we can use these functions directly. The standard input/output header file contains functions for input and output of data like reading values from the keyboard and printing the results on the screen. int main() int is the retum value of the main function. After all the statements in the program have been written, the last statement of the program will return an integer value to the operating system.) The concepts will be clear to us when we read | the chapter on Functions. So even if you do not understand certain things, do not worry. Programming Tip: If you will not place ‘a parenthesis after ‘main’, a compiler error will be generater {} The two curly brackets are used to group all the related statements of the function nain. All the statements between the braces form the function body. The function body contains a set of instructions to perform the given task printf("\n Welcome to the world of C"); ‘The printé function is defined in the staio.h file and is, used to print text on the screen."The message that has to be displayed on the screen is enclosed within double quotes ‘and put inside brackets. Programming Tip: Placing a semi- colon after the nthesis of main will generate compiler erro ‘The message is quoted because in Ca text (also known as a string or a sequence of characters) is always putbetween inverted commas. The *\n" is an escape sequence and represents @ newline character It is used to print the message on | 16 | Programming inc ‘a new line on the screen. Like the newline character, the other escape sequences supported by C language are shown in Table 2.1 Escape seqiences Escape Escape eee sequence | PUPP | sequence ja [Audible \? | Question mark signal Yb | Backspace \W_ [Backlash \t_ [Tab V__ [single quote \n__| Newline \"___ [Double quote Ww [Vertical tab \o__[ octal constant New page\ Hexadecimal NM lctearsereen |__| constant Carriage M [return Note Escape sequences are actually non- © firienccnmatoncise begin with a backslash (\ return 0; This is a retum command that is used to retum the value © to the operating system to give an indication that there ‘were no errors during the execution of the program, yy Now that you have written all the statements using the text editor, save the text fle as first..c. Ifyou are Windows user then open the command prompt by clicking Start->Run and typing ‘command’ and clicking ox Using the command prompt, change to the ditectory in which you had saved your file and then type: Ci\ste fixate In case you are working on UNIX/Lin system, then exit the text editor and type Sco first.c -ofiret WX operating The -0iis forthe output file name, If ~o then the file name [Link] is used This command is used t0 compile your C program, If there are any mistakes in the program then the compiles ‘you leave out the will tell you the mistake you have made and on which ling ‘you made it. In case of errors you need to re-open your ¢ file and correct those mistakes. However, if everything is right then no error(s) will be reported and the compiler will create an exe file for your program. This .exe file can be directly run by typing [Link]’ for Windows and * UNIX/Linux operating system /hello’ for When you run the exe file, the output of the program will be displayed on screen. That is, Welcome to the world of C ¥ The printf and return statements have been indented or moved away from the left side. This is done to make the code more readable, FILES USED IN A C PROGRAM Every C program has four kinds of files associated with it (Figure 2.3). These include: Files ina C program Header Object Executable file file file ina C program. Source file 2.4.1 Source Code File The source code file contai Program. The file extension *-c'. This file contains c ins the source code of the of any c source code file is Source code that defines the eto the program, There also may ease that the same subroutine iusto be used in dit anton sto copy the cade of the desired sub-routi nt programs, In the later eae, ONE © from But copying the cade is often fedious as well as error prone more difficult Pejnother option is to make subroutines and store them ar different file Known as header file, The avantans of header ites can be realized in the following 8 fone programm fo anothe andl makes maintainability «The programmer wants to use the same subroutines in different programs. For this compile the source code of the ‘and then link to the resultin he simply has 10 ubroutines once. object file in any other program in which the funetionafities of these sub- routines are required. «The programmer wants to change of add subrouti and have those changes reflected in all the other programs. In this case, be jy programming TIP! needs to change the source f ee chan the sarc fle Se wsteate ¢ subroutines, recompile its ae source code, and then recompile enon and re-link programs that Use em poeom ray em THis WAY enormous time Seepleburthe linker | canbe saved 8S compared (0 Ga ge. an ,error editing the subrowtines every vires ast wil not individual program that USES be able to find the | them. functions used in the program. ‘Thus, we see that using a header file produces the same results a8 copying the header file into each source file that needs it Atowben a header fileis included, the related declarations appear in only one place. If in future WE need to modify veer outines, we just need to make the chankes in ‘one place, and programs that include tNe header file will automatically use the new version when recompiled later. There is no need to find and change all the copies of the subroutine that has to be changed Conventionally, header files names ends with a ‘dot hh’ (ch) extension and its name can US only letters, digits, dashes, and underscores. Although some standard header files are automatically available t0 C programmers but in addition to those header files. the programmer ™ay have his own user defined header files. Introductionto€ | 17 | Standard Header Files all our peograms that we ha vet compares wo stings. We just fase sting arguments es nmiee the result. We do not know the details of how these fetions work. Such functions that are provide Mtn standart head files TPaamples af these standard hear files inet by all C compilers are ine « atring-h : for string handling functions ‘@Lin.h- for some miscellaneous functions atdio.h = for standardized input and output fi fior mathemati © nath.h 1 functions J anloc.t = for dynamic memory allocation fe conio.h for clearing the sereen Allthe header fil cede fie that uses one or more functions from tak file. re referenced atthe start of the souree 2.4.3 Object Files Object files are of processing the source code file, OFIESt fil Sompact binary code of the function defn one Linker omnis object file 10 produce an executable fle (1S fi by combining the of object files together ORY files peso to? extension, although some operating SSS including Windows and MS-DO for the object file snerated by the compiler as a result contain havea *.cb}’ extension 2.4.4 Binary Executable File ‘The binary exceutable ile is generated by the ihe The Tinker fink the various abject files t prosuss ¢ binary fie that can be directly executed. On Windows open system, the executable files have *-e8= extension. COMPILING AND EXECUTING C PROGRAMS C is a compiled language. So once the € BREAN \t can Cen. you mst run it through aC compiles eats an executable file 4 be rn By the COMPLY while eA program is human-readable, the SSUES file on the other hand, isa machine-readable le available 8 executable form ———— | 18 |_Programmin ‘The mechanical part of runnin with one or more program source files, 2 recutable file, which ean be run on 8 cOmPUIEE “The programming process starts with creating sou fle thateoneists ofthe statements ofthe rogram Wien tanguage. This source ile usualy contains. ASCII characters rane be produced witha text editor, such as Windows notepad, or in an Integrated Design Environment “The source file is then processed by a special program called a compiler. “The compiler translates the source code into an object code. “The object code contains the machine instructions for the CPU, and calls to the operating system API. (Application Programming Interface). However, even the object file is not an executable file. ‘Therefore, in the next step, the object file is processed with another special program called a linker. While there is a different compiler for every individual language, the same linker is used for object files regardless of the original language in which the new program was written. The ‘output of the linker is an executable or runnable file. The process is shown in Figure 2.4. g aC program besine mnd ends with an Every programming language has its own compiler. Brecutable files DERIEEY ei esata eon prices Compiler}. Object files Linker there are two Kinds of source Inc ae tin. (.c) source file, which files. Im adie gatements there ate also Realy (1) contain ge since all input and output in C programs source Fer ugh library functions, every CC program is done mee standard header files. THESe header files C programs a re compilation process shown im FIBVEE 2.5 is done in two steps. In the first step, the preprocessor program reads the source file as text, and produces another text fie as output. Source code Hines which begin with the # symbol are actualy not written in ¢ Buti the preprocessor language. The output of the preprocessor is text file saath does not contain any preprocessor statements, This fle is veady to be processed by the compiler. The linker combines the object file with library routines (supplied ‘with the compiler) to produce the final executable file. In modular programming the source code is divided into two or more source files. All these source files are compiled separately thereby producing multiple object files. These object files are combined by the linker to produce an executable file (Figure 2.6). EGG usine comments Many a time the meaning or the purpose of the program code is not clear to the reader. Therefore, it is a good programming practice to place some comments in the code tohetp the reader understand the code clearly. Comments tre Just « way of explaining what @ program does. Its merely an intemal program documentation, The compiler ares the omments when forming the object ile. This ‘means that the comments are non- a executable statements. C supports two types of commenting, |< a Executable files Library files i Source Pre- file Processor Compiler brary files Compiler eduction tC | 19 | files Library flles Unker Object files Executable files ‘Modular programming—the complete compilation and execution process + // is used to comment a single statement. This is known as a line comment. A line comment can be placed anywhere on the line and it does not require to be specifically ended as the end of the line automatically ends the line. « /+ isused to comment multiple statements. A /* is fended with */ and all statements that lie within these characters are commented. This type of comment is known as block comment. Note that commented statements are not executed by ‘the compiler. Rather, they are 4 ees ignored by the compiler as they Nee gn aze simply added inthe program Gftheblockcomment., 9 make the code understandable ‘acompilererror.. | by the programmer as well as other people who read it, It is a good habit to always put a comment atthe top of & program that tells you what the program does. This will help in defining the usage of the program the moment you open it ‘Commented statements can be used anywhere in the rogram. You can also use comments in between Your code to explain a piece of code that is @ ‘The code given below shows the way in which we can make use of comments in our first program /* author: Reema Thareja Description: To print ‘Welcome to the world of C’ on the screen */ include int main() { printf ("\n Welcome to the world of C ") // prints message return 0; // returns a value 0 to the operating system } Output Welcome to the world of C Since comments are not executed by the compiler, they do not affect the execution speed and the size of the compiled program. Therefore, use comments liberally in your programs so that other users can understand the operations of the program and will serve as an aid to debugging and testing. PERM KEYWORDS Like every computer language, C has a set of reserved words often known as keywords that cannot be used as ‘an identifier. All keywords are basically a sequence of characters that have a fixed meaning. By convention all ————————E_———-~S-rti‘ at the beginning of the program, 2.12.3 printf() ‘The printé function (stands for print formatting) is used to display information required by the user and also prints the values of the variables. For this, the print£ function takes data values, converts them to a text stream using formatting functions specified in a control string and passes the resulting text stream to the standard output. The control string may contain zero or more conversion specifications, textual data, and control characters to be displayed (Figure 2.11). Each data value to be formatted into the text stream is described using a separate conversion specification in the control string, The specification in the control string describes the data value’s type size and specific format information as shown in Figure 2.11. The syntax of printé function can be given as printf ("control string", variable The function accepts two parameters—control string and variable list. The contro! string may also contain text to be printed like instructions to the user, captions identifiers, or any other text to make the output readable In some printf statements you may find only a text string that has to be displayed on screen (as seen in the firs program that prints hello world). The control characters can also be included in the printf statement. These control characters include \n, \t, \r, \a, ete. After the control string, the function can have as many additional arguments as specified in the control string. The parameter control string in the print () is nothing but a C string that contains the text that has to be written on to the standard output device, Note that there must be enough arguments otherwise, the result will be come completely unpredictable. However by mistake you specify more number of arguments, the excess arguments will simply be ignored. The prototype of the control string can be as given below. 4 (£lags] {width] [precision] [length] specifier Each control string must begin with a sign. The + character specifies how the next variable in the list of variables has to be printed. After & sign follows. Flags specify output justification such as decimal point, numerical sign, trailing zeros or octal, decimal, ot hexadecimal prefixes. Table 2.5 shows the different types of flags with their decription. printfin a C program == Control string Data value's PEEEEEY Fe sincoinc Data value’s Specific format type size information Textual data Escape sequence characters: —_—_—_—_——— [= [etestty within the dat given field with —___“se"arh | + [Displays the data with its numeric sign (either + or) # | Used to provide additional specifiers lke o, x, X 0, 0x. or 0X for octal and hexadecimal values, respectively, for values different than zero, L#H#—_=—>S»»F*+F@r——venET, | ‘The number is left-padded with zeros (0) instead of |__| spaces Note that when data is shorter than the spe then by default the data is right justified. To left justify the data use minus sign (-) in the flags field. When the data value to be printed is smaller than the width specified; then padding is used to fill the unused spaces. By default, the data is padded with blank spaces. If zero is used in the flag field then the data is padded ith zeros. One thing to remember here is that zero flag is ignored when used with left justification because adding zeros after a number changes its value. Width specifies the minimum number of characters to print after being padded with zeros or blank spaces, ie. it specifies the minimum number of positions in the output. If data needs more space than specified, then printf overrides the width specified by the user. Width is a very important field especially when you have to align output in columns. However, if the user does not mention any width then the output will take just enough room for data Precision specifies the maximum number of characters to print. « Forintegerspecifiers (4, 1,0, u, x, ) : precision flag specifies the minimum number of digits to be written. However, ifthe value to be written is shorter than this number, the result is padded with leading zeros. Otherwise, if the value is longer, it is not truncated. * For character strings, precision specifies the ‘maximum number of characters to be printed. * For floating point numbers, the precision flag specifies the number of decimal places to be Printed, Introduetiontoc | 217 | Its format can be given as .m, where m specifies number of decimal digits. When no precision modifier is specified, print £ prints six decimal positions ‘When both width and precision fields are used, width ‘must be large enough to contain the integral value of the number, the decimal point and the number of digits after the decimal point. Therefore, a conversion specification ¥7.3£ means print a floating point value of maximum 7 digits where 3 digits are allotted for the digits after the decimal point. Length field can be explained as given in Table 2.6 Ed Description ny | When the argument isa short int or unsigned short int 1 | When the argument isa long int or unsigned long int for integer specifiers. 1, _ | When the argument isa long double (used for floating point specifiers) Specifier is used to define the type and the interpretation, of the value of the corresponding argument (Table 2.7), Type Qualifying input cc __| Forsingle character @__| Fordecimal values F __| Forfloating point numbers sie E, e_| Floating point numbers in exponential format Floating point numbers in the shorter of e SS | format anna 7 © _| Foroctal namber 8 __| Forasequence of (string of) characters u___|Forunsigned decimalvalue xX _| For hexadecimal value re Note that if the user specifies a wrong specifier then some strange things will be seen on the screen and the error might propagate to other values in the print) list SS | 28 | Programming in © ‘The most simple print statement is printf ("Welcome to the world of C Language") : ‘When executed, the function prompts the message enclosed in the quotation to be displayed on the screen. printé(*\n Result: Adtctf", 12, Recult:12a2.3 Printé(*\n Result: td te $f", 12, Result:12 a 2.3 Printf(*\n Result: td\ttc\tat", 12, 1 2.3)5 Result:12 a 2.3 print£(*\n Result: 44\t¥c\tt6.2€", 12, ‘a’ 245.37154) Result:12 a 245.37 printé(*\n Result: 454 \t &x \t tix", 234, 234, 234); Result: 234 EA oxEA printf(*\n The number is $64", 12); ‘The number is 2 print€(*\n The number is $24", 1234); ‘The number is 1234 Print€(*\n The mumber is ¥6d", 1234); wumber is 1234 printf(*\n The number is $-6d", 1234); number is 1234 // 2 _ indicates 2 white space Print£("\n The number is $06d", 1234); The numb x is 001234 tar, 2.307 ar, 2.3) Print£("\n The price of this item is $09.2£ rupee: 123.456); ‘The price of this item is 0123.45 rupees Printf(*\n This Programming Tip: Not placing a Ae \’e0\" beautiful); ‘This is ‘so’ beautiful Print€(*\n This is \"so\" beautifuie); This is m9 beautiful Printf(*\n This is \\ 20 beautifu *); This is \ eo beautitur printé (*\na=|%-+7.2£|b=%0+7.2£c= %-048.26", 1.2, 1.2, 1-207 a= 41,20 b = 0001.20 ¢ = 1.20 (Note that in this example, ~ means left justify, + means display the sign, 7 specifies the width, and 2 specifies the precision.) printé(*\n 97.4£ \n 47.2€ \n 4-7.28 \n 8€ \n $10.2e \n $i1.4e \n ¥-10.2e \n 98.7654, 98.7654, 98.7654, 99.7654, 98.7654, 98.7654, 98.7654, 98.7654) 98.7654 98.77 98.77 98.7654 9.88e+01 9.8765e+01 9.88e+02, 9.876540e+01 char ch = ‘A"; printf (*\n tc \n 43c \n $c", ch, ch, ch); A a a ProgrammingTip: char str{] = "Good Morning"; Placing an address prines(*\n 4s", str); operatorwitha —printe(*\n $200", str); variable in the print€(*\n 20.108", str); Prinf statement | prines(*\n ¥.78", etx); willgeneratearun- | prints (*\n ¥-20.100", ste); time error. Print£("\n 478", str); Good Morning Good Morning Good Morni Good Mo Good Mori Good Morning (Note that in the last Printf statement the complete string “Good Morning” is printed. This is because if data needs more space than specified, then printf overrides the width specified by the user.) 2.12.4 scanf() The function scant () stands for scan formatting and is Uused to read formatted data from the keyboard. The scant a PY funetion takes a text stream from the ke he keyboard, extracts and formats data from the stream according to'a format control string and then stores the data in specified program variables. The syntax of the scanf{) can be given as, scant ("control string", argl, arg2, arg3, —-aran) ; ere, The minimum field width and precision {2 specifiers are usually constants. However, they may also be provided by arguments to printf(). This is done by using the * modifier as shown in the printf statement below. Print ("8*.*£", 10, 4, 1234.34); Here, the minimum field width is 10, the precision is4, and the value to be displayed is 1234.34, ‘The contro! string specifies the type and format of the data that has to be obtained from the keyboard and stored in the memory locations pointed by the arguments arg, arg2,.., argn,i.e. the arguments are actually the variable addresses where each piece of data are to be stored. ‘The prototype of the control string can be give as: [+] (width) [modi fiers] type=) Here isan optional argument that suppresses assignment of the input field)i.e., it indicates that data should be read from the stream but ignored (not stored in the memory location). With isan optional argument that specifies the maximum Aner fcturatens to be read, However, fewer characters will be read ifthe scanf function encounters a white space or an inconvertible character because the moment scant encounters a white space character it wll stop processing further fiers is an optional argument that can be b, 1, of fields1, for the data pointed by the corresponding additional arguments, Modifier his used for short. int or unsigned short int, 1isused for long int, unsigned long int, or double values. Finally, Lis used for Long double data values. joe specifies the type of data that has to be read. It also indicates how this data is expected to be read from the Introduction toc | 29 | user. The (ype speiis for scant fiction ae given i Table 2.8. . ? ‘Type specifiers for scanf() type | Qualifying input ] € _| Forsingle character a For decimal values Di | F | Forfloating point numbers | 8, € | Floating point numbers in ponential format &, 6 | Floating point numbers in the shorter of e format © | Foroctal number 2 | Fora sequence of (string of) characters u__| Forunsigned decimal value x [Forteadecial ae | Give scant function ignores any blank spaces, tabs and newlines entered by the user. The function simply returns the number of input fields successfully scanned and stored. ) ‘We will not discuss functions in detial in this chapter. So understanding scanf function in depth will be abit difficult here, but for now just understand thatthe scanf function is used to store values in memory locations associated with variables. For thi, the function should have the address of the variables. The address of the variable is denoted by an *& sign followed by the name of the variable. ‘Whenever data is read from the keyboard, GY there always a return character trom a previous read operation. So we should always code at least one white space character in the conversion specification in order to flush that whitespace characte. For example, to read two or more data values together ina single scanf statement, we must inserta white space between two fields as shown below: scanf ("td te", &i, Gch) ; Now let us quickly summarize the rules to use a scanf function in our € programs. | 80 | Programminginc Rule 1: The scanf function works until: (@) the maximum number of characters has been processed, (b)_a white space character is encountered, or (©) an error is detected. Rule 2: Every variable that has to be processed must have 1 conversion specification associated with it, Therefore, the following scanf statement will generate an error as rnum3_has no conversion specification associated with i scang ("td ¥4", gnuml, &nun2, num) ; Rule 3: There must be a variable address for each conversion specification. Therefore, the following scant statement will generate an error as no variable address is given for the third conversion specification. scan€("¥d 8d $a", Smumt, énum2) ; Remember that the ampersand operator (&) before each variable name specifies the address of that variable name. Rule 4: A fatal error would be generated if the format string is ended with a white space character. Rule 5: The data entered by the user must match the character specified in the control string (except white space ot a conversion specification), otherwise an error will be generated and scan will stop its processing. For example, consider the scant statement given below. scant ("8d / $4", smumt, gmuna); Here, the slashes in the control string are neither white space characters nor a part of conversion specification, so the users must enter data of the form 21/46. Rulle 6: Input data values must be separated by spaces. Rule 7: Any unread data value will be considered as a part of the data input in the next call to scanf. Rule 8: When the field width specifier is used, it should be large enough to contain the input data size. Look at the code given below that shows how we input values in variables of different data types. int num; scant (" ¥4", gnum) ; The scanf function reads an integer value (because the type specifier is ¥a) into the address’ or the memory location pointed by num. float salary; scanf(" $£", ésalary); The scanf function reads a floating point number (because the type specifier is. ¥£) into the address or the memory location pointed by salary. char chs scant (" 8e", &eh): ‘The scanf function reads a single character (because the type specifier is $c) into the address or the memory location pointed by ch. char str (201; acanf(* $8", ete) ‘The scanf function reads a string or a sequence of characters (because the type specifier is ¥s) into the address or the memory location pointed by str. Note that in case of reading string, we do not use the « sign in the scanf function. This will be discussed in the chapter on Strings. Look at the code given below which combines reading of variables of different data types in one single statement, Programming Tip: ‘Acompiler error will be generated if the read and write parameters are not separated by commas. int nun; float fnum; char ch; char str (201; scant ("td $f to 5", Enum, efnum, ech, str); Look at the scanf statement given below for the same code, The statement ignores the character variable and does not store it (as it is preceded by *). scanf("td tf $#c ts", gmum, gfnum, sch, str); Remember that iff an attempt is made to read a value that does not match the expected data type, the scant function will not read any further and would immediately return the values read, 2.12.5 Examples printf/scanf Look at the code given of below that shows how we output values of variables of different data types. int num; scang(* $4", snum); printé(*ka", num); The print function prints an integer value (because the type specifier is $a) pointed by num on the screen, float salary; scanf(" ¥£ ", &salary); printé(".28f", salary); ‘The printé function prints the floating point number (because the type specifier is ¥£) pointed by salary on the screen, Here, the control string specifies that only two is must be displayed after the decimal point. char ch; Programming Tip!) scanf(* %c ", &ch); ‘Afloat specifier print£("¥c", ch); cannot be used The printé function prints a single character (because the type specifier is $c) pointed by ch on the screen, char str [10]; scanf(" $5", str); The print function prints a string or a sequence of characters (because the type specifier is ¥s) pointed by str ‘on the screen. scanf(*A24 854", enum, &num2); The scanf statement will read two integer numbers. The first integer number will have two digits while the second can have maximum of 5 digits. Look at the code given below which combines printing * all these variables of different data types in one single statement, int num; float foun; char ch; char str [10]; double dnum; short enum; Jong int Inum; Printf(*\n Enter the values : ") scant ("kd S£ Ac %o %e hd $14", Gnum, Gfnum, eh, str, Gdnum, genum, &lnum); Printf(*\n num = td \n fnum = ¥£ \n ch = ¥c \B str = %o \n dnum = te \n enum = thd \n inun = 1d", num, fnum, ch, str, dum, snum, num) ; Introductiontoc_| 31 | Inthe print £ statement, * \n’, is called YE the newline character and is used to print the succeding text on the new line. The following output will be generated on execution of the print function. Enter the values 2 3456.443 a abcde 24.321E-2 1 12345678 num = 2 fnum = 3456.44 chea str = abcde num = 0.24321 snum = 1 Anum = 12345678 Remember one thing that scanf terminates as soon as it encounters a white space character so if your enter the string as abe def, then only abc is assigned to str. 1. Find out the output of the following program. include main() { int a, b; printé("\n Enter two four digit numbers scanf ("82d 44d", ba, eb); printf ("\n The two nunbers are: ¥d and sa", a,b); return 0; , Output Enter two four digit numbers : ‘The two numbers are : 12 and 34 1234 5678 Here, the variable a is assigned Programming Tip: the value 12 because itis specified Using anincorrect as 2d, so it will accept only the specifier for the cept only first two digits. The rest of the number will be assigned to b. The Value 5678 that is unread will be assigned to the first variable in the next call to the scanf function. data type being read or written will “generate a run-time error new, The $n specifier is used to assign the 92 umber of characters read till the point at which the $nwas encountered to the variable pointed to by the corresponding argument. The code fragment given below illustrates its usage. Ant count; printé ("Hello $nWorld!", scount) ; printé ("$a", count); The output would be—Hello World! 6 because 6(H, e, |, |, 0) is the number of characters read before the %n modifier. 2. Write a program to demonstrate the use of printf Statement to print values of variables of different data types. #inchude main() { // Declare and initialize variables int mum = 7; float amt = 123.45; char code = ‘A’; double pi = 3.1415926536; Jong int population of india = 0000000000, a char msg[] = "Hin; // Print the values of variables printf(*\n NOM = ta \t ANT = 4£ \t CODE = $c \n PI = Ye \t POPULATION OF INDIA Sid \n MESSAGE = $5", mim, ant, code, pi, population of india, meg) ; return 0; , Output MM = 7 aw - 123.4500 CODE = A PI = 3.1415906+00 POPULATION OF INDIA ~ 10000000000 MESSAGE = Hi 3. Write a program to demonstrate the use of printf and scanf statements to read and print values of variables of different data types. 4. Write a program finclude main() { int num; float amt; char code; double pi; long int population_of_india; char msg(10] ; printf ("\n Enter the value of num : scanf("¥d", &num) ; print£("\n Enter the value of amt : "); scant ("8E", game); print£("\n Enter the value of pi ; "); scant ("te", epi); print €(*\n Enter the population of india : "); scanf("¥1d", gpopulation_of_india) ; printf ("\n Enter the value of code : "); scant ("tc", scode) ; print£("\n Enter the message : "); scanf("te", meg); printé("\n NUM = $d \n AMT = $f \n Pr = ‘$e \n POPULATION OF INDIA = %1d \n CODE = *c \n MESSAGE = $5", num, amt, code, Pi, population of_india, msg) ; return 0; } Output Bnter the value of num ; 5 Enter the value of amt : 123.45 Enter the value of pi : 3.14159 Enter the population of india ; 12345 Enter the value of code ; ¢ Enter the message : Hello 5 23.4500 PI = 3.141590e+00 POPULATION OF INDIA = 12345 CODE = & MESSAGE = Helio to calculate th i Hert ore fe area of a triangle using Winclude <[Link] include #include include int main() { int xt, x2, yl, y2; float distance; print£("\n Enter the x and y coordinates of the first point: "); scant ("$d 8d", Sxl, &y1); print£("\n Enter the x and y coordinates of the second point :"); scanf("td $d", 6x2, &y2); // sqrt and pow are mathematical functions defined in math.h header file distance = sqrt (pow (x2-x1) , 2) spow( (y2- 1, 2))5 Printé("\n Distance = $f", distance) ; return 0; } Output Enter the x and y coordinates of the first Point : 25 Enter the x and y coordinates of the second Point : 37 Distance « 2.236068 _Intreduetion toc | 33 | 2.12.6 Detecting Errors During Data Input When the scanf function completes reading all the data values, it returns number of values that are successfully read. This return value can be used to determine whether there was any error while reading the input. For example, the statement, scanf("td $f to", ba, Gb, bc); will retum 3 ifthe user enters, say, a2 12.34 a It will return 1 ifthe user enters erroneous data like 22 ABC 12.34 This is because a string was entered while the user was expecting a floating point value. So, the scant reads only first data value correctly and then terminates as soon as it encounters a mismatch between the type of data expected and the type of data entered OPERATORS IN C An operator is defined as a symbol that specifies the ‘mathematical, logical, or relational operation to be performed. C language supports a lot of operators to be used in expressions. These operators can be categorized into the following major groups: * Arithmetic operators « * Relational operators ° ‘© Equality operators , * Logical operators # Unary operators * Conditional operators * Bitwise operators ‘© Assignment operators ‘* Comma operator # Sizeof operator’ In this section, we will discuss about all these operators. 2.13.1 Arithmetic Operators Consider three variables declared as, We will use these variables to explain arithmetic operators. Table 2.9 shows the arithmetic operators, their syntax, and usage in C language. be3, result, | 84. | Programming in c - » Arithmetic operators Operation | Operator | Syntax | Comment _| Result Multiply 7 atb |result=a*b| 27 ide / a/b | result=a/b 3 Addition + a+b |result=a+b| 12 Subtraction | — amb |result=a—b Modulus % a%b [result=a%b In Table 2.9, a and b (on which the operator is applied) are called operands. Arithmetic operators can be applied to any integer or floating-point number. The addition, subtraction, and multiplication (+, -, and *) operators perform the usual arithmetic operations in C programs, so you are already familiar with these operators, However, the operator + must be new to you, The ‘modulus operator (8) finds the remainder of an integer division. This operator can be applied only to integer operands and cannot be used on float or double operands.) Therefore, the code given below generates a compiler error, #include int main() { float ¢ = 20.0; printf ("\n Result = $£", ¢ $5); // WRONG. Modulus operator is being applied to a float operand return 0;. } While performing modulo division, the sign of the result is always the sign ofthe first operand (the. dividend), Therefore, 16% 3=1-16%3=. 16%-3=1-16%3=4 When both operands of the divisi integers, the division is performed as a Integer division always results in an in result is always rounded-off by ign Therefore, 914 and 9/4 = 3 From the above observation, we car things. If op1_ and op2 are integers and t an integer, then we have two cas Operator (/) are in integer division, teger result. So, the loring the remainder, 1 conclude two the quotient is not * If opi and op2 have the same sign, then op1/o is the largest integer less than the true quotient. © If opi and op2 have opposite signs, then op1/op2 the smallest integer greater than the true quotient. Note that it is not possible to divide any number by zer This isan illegal operation that results in a run-time divisio by-zero exception, thereby terminating the program. Except for modulus operator, all other arithmet ‘operators can accept a mix of integer and floating poit numbers. If both operands are integers, the result will be a integer. If one or both operands are floating point number then the result would also be a floating point number, All the arithmetic operators bind from left to right. A: in mathematics the multiplication, division, and modulu: ‘operators have higher precedence over the addition an¢ subtraction operators, i.e., if an arithmetic expression consists of a mix of operators, then multiplication, division, and modulus will be carried out first in a left to right order, before any addition and subtraction could be performed. For example, 3447 = 3428 = 31 § Write a program to perform addition, subtraction, division, integer division, multiplication, and module division on two integer numbers. #include #include int main() + mul_reseo, float fdiv resa0.0; elrser(); Printf(*\n Enter the first number Seanf("¥a", enum) ; Brinef ("\n Enter the second mumber ; +); Scanf("¥a", gnuma) ; B"); add_ress numa + numa; Sub_res=numi ~ numa; mul_res = numt + nung; Adiv_res = numa /numa; modiv_res = numitnun2; *tv_x08 = (float) nant /nuna, Enter the first number : Enter the second nunber printf ("\n td + $d = 4d", num, numa, add_res) ; printt("\n td- td = td", num, num2, eub_res) : printf (*\n td x $d = td", num, num2, mul_res) ; printf ("\n 8d / 8d = td (Integer Division)", numi, num2, idiv res); printf("\n 84 8% 8d = td (Moduluo Division)", numi, num2, modiv res) ; printf("\n td / td = %.2£ (Normal Division)", numi, num2, fdiv res) ; +7 = 16 ~702 +7263 /7 21 (Integer division) $7 = 2 (Moduluo division) 1/7 = 1.29 (Normal division) Write a program to perform addition, subtraction, division, and multiplication on two floating point numbers. include #include int main() { float num, numa; clrser(); printf ("\n Enter the first munber: "); scanf("¥f", gum); Print£("\n Enter the second number: "); scang("8£", gnum2) ; Printf("\n 4£ + 4f = 8£", mum, num2, umd + numa) ; Print ("\n $£ - $£ = $£", numl, num2, mum = numa) ; PEinté("\n $€ X $€ = $£", numl, num2, uml * num2) ; Printé("\n $€ / $£ = $f ", numl, muna, uml / num2) ; return 0; Introductionto® | 35 | Output Enter the firet number : 4.5 Enter the second number + 1.2 3.5 + 1.2 = 4.700000 2.300000 4.200000 = 2.196667 1.2 +12 1.2 8. Write a program to subtract two long integers. Hinclude include int main() ( Jong int num clrscr(); 1224567, num2, ditto; printé(*\n Enter the number: "); scanf("¥1d", anum2) ; iff = numt - numa; print£("\n Difference = $14", return 0; } Output Enter the number: 1234 Difference = 1233333 2.13.2 Relational Operators aife); K , ‘A relational operator, also known as a comparison operator, is an operator that compares two values. Expressions that contain relational operators are called relational expressions, Relational operators return true or false value, depending on whether the conditional relationship between the two operands holds or not. For example, to test the expression, if x is less than y, relational operator < is used as x < y. This expression will return TRUE if x is less than y; otherwise the value of the expression will be FALSE. ? Relational operators can be used to determine the relationships between the operands. These relationships are illustrated in Table 2.10. SETTER) Relational operators Operator Meaning Example < Less than 3 Greater than 7> 9 gives 0 >= ___| Less than or equalto_| 100 >= 100 gives 1 <= _|_ Greater than equal to | 50 >= 100 gives 0 —.- !Ullloe | 36 | Programming inc The relational operators are evaluated from left to right ‘The operands of a relational operator must evaluate to a ‘number. Characters are considered valid operands since they are represented by numeric values in the computer system, So, if we say, “A” < °B’, where A is 65 and B is 6 then the result would be 1 as 65 < 66. ‘When arithmetic expressions are used on either side of a relational operator, then first the arithmetic expression will be evaluated and then the result will be compared. This is because arithmetic operators have a higher priority over relational operators However, relational operators should not be used for comparing strings as this will result in comparing the address of the string and not their contents. You must be wondering why so? The answer to this question will be clear to you in the later chapters. A few examples of relational operators are given below. If xei, y=2, andz = 3, then Expressions that evaluate | Expressions that evaluate fo TRUE fo FALSE Note tha these expressions | Note that these are true because their | expressions are false value is not zero. because their value is ze. &) wey) +5) (2410-5 +a) Crincuiy) (x=) (ay) Although blank spaces are allowed between an operand and an operator, ‘No space is permitted between the ‘components of an operator (like > = is ‘ot allowed, it should be >=). Therefore, writing, x=zy is correct but writing x {is not acceptable in C language. © @ program to show the use of relational operators. include main () ( int x610, y=20; printf ("\n $d < td = ya" 1 oY, ey) Print (*\n Ad == td = a, oe, y, tery, printé("\n td I= td = 4", x,y ry)! printe(*\n td > $d yey); printf (*\n 4 y. printé("\n 84 < ” return 0 } Output 10 < 20-0 10 == 20-1 10 te 20-3 10 > 20-0 10 >= 20 = 0 10 «= 20 +1 2.13.3 Equality Operators C language supports two kinds of equality operators to compare their operands for strict equality or inequality. They are equal to (==) and not equal to (1=) operators. The equality operators have lower precedence than the relational operators. The equal-to operator (==) returns tue (1) if operands on both the sides of the operator have the same value; otherwise, it returns fase (0). On the contrary, the not equal-to operator (1) returns true (1) if the operands do not have the same value; else it returns false (0) . Table 2.11 summarizes equality operators. Eaialty dpratrs . Meaning Returns 1 if both operands are equal, 0 otherwise Returns 1 if operands do not have the same value, 0 otherwise “_{213.4 Logical Operators ‘ Ctansuage supports three logical operators-—logical AND ‘aa, logical OR (|), and logical NOT (:).)As in Case of arithmetic expressions, the logical expressions are evaluated from left to right. Logical AND oical AND operator is used to simultaneously evaluate Trogcettltions or expressions with relational operators the eecssORS on both the sides (Ie and right side) of ‘sical operator is true then the whole expression is ——- true, The truth table of logical AND operator is given in Table 2.12 ena ‘ruth table of logical AND A B A&&B e oO 0 0 Sa For example, (a ) ‘The expression to the left is (a < b) and that on the right is (b > c). The whole expression is true only if both expressions are true, i.e., if b is greater than a and c. Logical OR Logical OR operator is used to simultaneously evaluate two conditions or expressions with relational operators)If one or both the expressions on the left side and right side of the logical operator is true then the whole expression is true, The truth table of logical OR operator is given in Table 2.13. ‘Truth table of logical OR be A B ALB : 0 0 \ 0 1 1 ars i z Ise ar Pet ge eater For example, ( ey The expression to the left is (a c). The whole expression is true if either b is "er than a or bis greater than c Logical NoT The logi negate gel NOT operator takes a single expression and the value of the expression. That is, logical NOT Introduction toc | 37 | produces a zero if the expression evaluates to a non-zero value and produces a 1 if the expression produces a zero. In other words, it just reverses the value of the expression, The truth table of logical NOT operator is given in Table 2.14. Truth table of Logical NOT A 1A 1 1 o | For example, int a = 10, b; be ta; Now the value of b = 0. This is because value of a = 10. 1a = 0. The value of ta is assigned to , hence, the result. Logical expressions operate in a short cut fashion and stop the evaluation when it knows for sure what the final ‘outcome would be. For example, in a logical expression involving logical AND, if the first operand is false, then the second operand is not evaluated as it is for sure that the result will be false. Similarly, for a logical expression involving logical OR, if the first operand is true, then the second operand is not evaluated as itis for sure that the result will be true. But this approach has a side effect. For example, consider the following expression: (x > 9) && (y > 0 OR tx > 9) I] ty > 0 In the above logical AND expression ifthe first operand is false then the entire expression will not be evaluated and thus the value of y will never be incremented. Same is the case with the logical OR expression. If the first expression js true then the second will never be evaluated and value of y will never be incremented. 2.13.5 Unary Operators Unary operators act on single operands. C language supports three unary operators unary minus, increment, and decrement operators. | 88 |_Programmingin ¢ Tt Unary Minus Unary minus (-) operator is strikingly different from the ‘binary arithmetic operator that operates on two operands ‘and subtracts the second operand from the first operand. When an operand is preceded by a minus sign, the unary operator negates its value. For example, if a number is positive then it becomes negative when preceded with a ‘unary minus operator, Similarly, if the number is negative, it becomes positive after applying the unary operator. Fr example, : int a, b= 10; as =); ‘The result of this expression is a = -10, because a variable bhas a positive value. After applying unary minus ‘operator (-) on the operand b, the value becomes —10, which indicates it as a negative value, Increment Operator (++) and Decrement Operator (--) The increment operator is a unary operator that increases the value of its operand by 1. Similarly, the decrement ‘operator decreases the value of its operand by 1. For example, --2 is equi lent to writing x = x ~ 1. The increment/decrement operators have two variants— refix and postfix. in a prefix expression (++% or x), the operator is applied before an operand is fetched for computation and thus, the altered value is used for the computation of the expression in which it occurs. On the contrary, in a postfix expression (x++ or x-~) an operator is applied after an operand is fetched for computation, ‘Therefore, the unaltered value is used for the computation of the expression in which it occurs. Therefore, an important point to note about unary increment and decrement operators is that +4x is not the same as x++. Similarly, --x is not the same as x-~. Both +exand x++ increment the value of x by T)In the former cease, the value of x is returned before it is ineremented ‘whereas, in the latter ease, the value of x is retumed after itis incremented, For example, Lime x= 10, y2 y= xe; is equivalent to writing a yak xexed whereas, ye tem: is equivalent to writing xe vex; The same principle applies to unary decrement operators. The unary operators have a higher precedence than the binary operators. If in an expression we have more than one unary operator then unlike arithmetic operators, they are evaluated from right to left. When applying the increment or decrement operator, the operand must be a variable. This operator can never be applied to a constant or an expression. Therefore the following codes will generate a compiler error. Netey When postfix ++ or ——is used with we variable in an expression, then the expression is evaluated first using the ‘Original value of the variable and then the variable is incremented or decremented byone, ‘Similarly, when prefix ++ or ~~ is used with a variable in an expression, then the variable is fr 10. Write a program to illustrat increment and decrement include <[Link] main() { int num te the use of unary prefix operators. (1 sing unaty prefix increment operator Print£(*\n The value of print e(" printe(" um = ta", num); \n The value of +snum= ea \n The new value of mum = $d", num) // Using unary prefix decrement operator PFint£("\n\n The value of num = $d", num) ; be printf (*"\n The value of --rum= a", ~-num) j printf ("\n The new value of num = return 0, sae, num); ) Output ‘The value of num = 3 ‘The value of +snum = 4 ‘The new value of mum = 4 The value of num = 4 The value of --num = 3 The new value of num = 3 11) Write a program to illustrate the use of unary postfix inerement and decrement operators. #include nain() { int mum = 3; // Using unary postfix increnent operator print £ ("\n The value of num= $a", nun) ; Print £ ("\n The value of nun++ = $a", mum++) printf ("\n Thenewvalue of num= $d", nun) ; // Using unaxy postfix decrement operator print ("\n\n The value of mum $4", num); print ("\n The value of mum= td", mum--) Print ("\n The new value of num= ta", mum) ; return 0; ) Output ‘The value of num = 3 The value of nume+ = 3 The new value of num = 4 The value of num = 4 ‘The value of nun-- = 4 ‘The new value of num = 3 2.13.6 Conditional Operator The conditional operator or the temary (2+) isjust ike an if-else statement that can be within expressions. Such Introduetiontoc | 39 | ‘4n operator is useful in situations i enon Which there are two alternatives for an expression. The syntax of th conditional operator is expl ? expa + exp exp1 is evaluated first fit is true, then exp2 is evaluated and becomes the result of the expression, otherwise exps is evaluated and becomes the result of the expression, For example, large = (a>b) ?a:b The conditional operator is used to find largest of two given numbers. First exp1, that is (a > b) is evaluated. If a is greater than b, then large = a, else large = b. Hence, Large is equal to either a or b but not both, Hence, conditional operator is used in certain situations, replacing condition phrases. Conditional ‘operators make the program code more compact, more readable, and safer to use, as it is easier to check any error (present) in one single line itself. Conditional operator is also known as ternary operator as itis neither a unary nor a binary operator; it takes three operands Since a conditional operator is itself an expression, it can be used as an operand of another conditional operation. That means C allows you to have nested conditional expressions. Consider the expression given below which illustrates this concept. if-else int a= 5, b= 3, ce 7, small; snall acb?(acc?a:c): (bee?b: Ds 12, Write a program two find the largest of two numbers using ternary operator. #include include int main() { int numL, mum2, large: elrscr() print£("\n Enter the first munber: "); scan€ (*8d", &muml) ; printf("\n Enter the second number: ")/ scan ("¥a", Gnum2) ; Large = nunisnum2?numi :nun2; glan; dacaab' printé ("\nThe largest number is: td", Large | 40. | Programming inc ) Output Rnter the {iret number: 23 Rnter the second number: 34 The largest nunber ia: 34 > 1 ) Write a program two find the largest of three numbers \/ using ternary operator Winclude int main 0) { int num, num2, num3, large; elrscr ( printf ("\n Enter the first number: "); scanf("ta", &numd) ; printf("\n Enter the second number: "); scant ("¥d", gnum2) ; printf ("\n Enter the third number: scanf ("8d", snum3) ; Large = numl>nun2? (numl>num3 ?num} :num3) 3 (mum2snum3 ?mum2 smum3) 5 print€("\n The largest nunber is: td" large) ; return 0; Output Enter the first number: 12 Enter the second number: 34 Enter the third number: 23 ‘The largest number is: 34 2.13.7 Bitwise Operators As the name suggests, bitwise operators are those operators that perform operations at bit level. These operators include: bitwise AND, bitwise OR, bitwise XOR, and shift operators. The bitwise operators expect their operands to be integers and treat them as a sequence of bits. Bitwise AND ‘The bitwise AND operator (8) is a small version of the boolean AND (&&) as it performs operation on bits instead of bytes, chars, integers, etc. When we use the bitwise ‘AND operator, the bt inthe first operand is ANDed with the corresponding bit in the second operand. The truth table is same as we had seen in logical AND operation, ie, the bitwise AND operator compares each bit of ts first operand withthe corresponding bit of its second operand, If both bits are I, the corresponding bit in the result is 1 and 0 otherwise. For example, 10101010 & 01010101 = 00000000 Ina C program, the & operator is used as follows. int a c= ash, Bitwise OR The bitwise OR operator (|) is a small version of the boolean OR (\) as it performs operation on bits instead of bytes, chars, integers, etc. When we use the bitwise OR operator, the bit in the first operand is ORed with the corresponding bit in the second operand. The truth table is same as we had seen in logical OR operation, i.e., the bitwise-OR operator compares each bit of its first operand with the corresponding bit of its second operand. If one or both bits are 1, the corresponding bit in the result is 1 and 0 otherwise. For example, 30202010 & ovo10101 = 11231211 InaC program, the | operator is used as follows. int a= 10, b = 20, cx0; c= alb Bitwise XOR- The bitwise XOR operator (*) performs operation on individual bits of the operands. When we use the bitwise XOR operator, the bit in the first operand is XORed with the corresponding bit in the second operand. The truth table of bitwise XOR operator is as shown in Table 2.15, The bitwise XOR operator compares each bit of its first ‘operand with the corresponding bit of its second operand. Ifone of the bits is 1, the corresponding bit in the result is Tand 0 otherwise. For example, 0101020 * oio20101 = 12212222 ESSER EY uth table of bitwise XOR { A 8 | ° [nies | 1 fie at 1 ag 1 [ease Stiqunibhony [olor egy Ina C program, the * operator is used as follows: int a = 10, b = 20, c=0; a’b Bitwise NOT The bitwise NOT, or complement, is a unary operation that performs logical negation on each bit of the operand, By performing negation of each bit, it actually produces the 1s complement of the given binary value. Bitwise NOT operator sets the bit to 1 if it was initially 0 and sets it to 0 if it was initially 1, For example, ~10101011 = 01010100 Bitwise operators are used for testing the 2 _ bits or shifting them left or right. Always remember that bitwise operators cannot be applied to float or double variables. Shift Operator C supports two bitwise shift operators. They are shiftleft (<<) and shift-right (>>). These operations are simple and are responsible for shifting bits either to the left or to the right. The syntax for a shift operation can be given as operand op num Where the bits in operand are shifted left or right depending on the operator (left if the operator is << and Fight ithe operator is >>) by the number of places denoted by num, For example, if we have x = 0001 1101, then X ce 2 produces 0012 1010 ‘When we apply a left-shift, every bit in x is shifted to the left by one place. So, the MSB (most significant bit) of Xis lost, the LSB of x is set to 0. Inteoducton toc | 41 | Therefore, if we wave x = 0002 1102, then x << 4 produces 1010 0000 If you observe carefully, you will notice that shifting once to the left multiplies the number by 2. Hence multiple shifls of 1 to the left, results in multiplying the number by 2 over and over again, On the contrary, when we apply a shift-right operator, every bit in x is shifted to the right by one place. So, the LSB (least significant bit) of x is lost, the MSB of x is set 100. For example, if' we have x = 0001 1201, then X >> 1 produces = 0000 1110 Similarly, if we have x = 0001 1202, then X << 4 produces 0000 0002 If you observe carefully, you will notice that shifting once to the right divides the number by 2. Hence, multiple shifis of | to the right, results in dividing the number by 2 over and over again. 2.13.8 Assignment Operators In C, the assignment operator is responsible for assigning values to the variables. While the equal sign (=) is the fundamental assignment operator, C language also supports other assignment operators that provide shorthand ways to represent common variable assignments. ‘When an equal sign is encountered in an expression, the compiler processes the statement on the right side of the sign and assigns the result to the variable on the left side. For example, int x; x= 10; assigns the value 10 to variable x. If we have, int x= 2, y= 3, sum = sum = x + ys then sum = 5 The assignment operator has right-to-left associativity, so the expression asb-c= 10; is evaluated as (a = (b= (c= 10))); First 10 is assigned to c, then the value of c is assigned to b. Finally, the value of b is assigned to a. | 42. | Programming inc The operand to the left of the must always be a variable name. signment operator C does not allow any expression, constant, o function to be placed to the left of the assignment operator. Therefore, the statement a +b = 0, is invalid in C language To the right of the assignment operator you may have {an arbitrary expression, In that case, the expression would be evaluated and the result would be stored in the location denoted by the variable name. Other Assignment Operators C language supports a set of shorthand assignment operators of the form variable op = expression where op is a binary arithmetic operator. Table 2.16 contains a list of other assignment operators that are supported by C. ‘The advantage of using shorthand assignment operators are as follows: ‘* Shorthand expressions are easier to write as the expression on the left side need not be repeated. ‘* The statement involving shorthand operators are easier to read as they are more concise. ‘© The statement involving shorthand operators are more efficient and easy to understand. ‘14, Write a program to demonstrate the use of assignment ~~ operators. #include main() { int num = 3, nun = 5; printé("\n Initial value of mumi = td and nung = td", num, num2); uml += nun2 * 4-7; printé("\n After the evaluation of the expression numl = td and num2 = td", uml, numa) ; return 0; } Output Initial value of numl = 3 and mung = 5 After the evaluation of the expression num = 16 and num? = 5 2.13.9 Comma Operator ‘The comma operator in C takes two operands. It works by evaluating the first and discarding its value, and then evaluates the second and returns the value as the result of the expression. Comma separated operands when chained together are evaluated in left-to-right sequence with the right most value yielding the result of the expression, ‘Among all the operators, the comma operator has the lowest precedence. Therefore, when a comma operator is used, the entire ‘expression evaluates to the value of the right expression For example, the following statement assigns the value of to x, then increments a, and then increments b. int a2, be3, x20; x = (+a, brea); Now, the value of x = 6. 2.13.10 Sizeof Operator ‘The operator sizeof is a unary operator used to calculate the size of data types. This operator can be applied to all data types. When using this operator, the keyword sizeof is followed by a type name, variable, or expression. The operator retums the size of the variable, data type, or expression in bytes, i.e., the sizeof operator is used to determine the amount of memory space that the variable! expression/data type will take., When a type name is used, it is enclosed in parentheses, but in case of variable names and expressions they can be specified with or without parentheses. sizeof expression returns an unsigned value that specifies the space in bytes required by the data type, variable, or expression. For example, sizeof (char) retums 1, ie,, the size of a character data type. If we have, int a= 10; unsigned int result; result = sizeof(a); then zesult = 2, which is the space required to store the variable a in memory. Since a is an integer, it requires 2bytes of storage space. 2.13.11 Operator Precedence Chart C operators have two properties: priority and associatvi. When an expression has more than one operator then it 3 | Introduetiontoc | 4 uereyo i" yunowe sce aqqeuen | =< = ayaenen =a jae jo anjen See | aqruo pau wunowe) ys yor ouaungue ue stwioyag | qunowe>>aygeuen=ayqeuen | wnowe=>>aigeuen | >> ane aver occa: | auzulainsay au uisse pu uossaudra ayn amen oe pus smauenje anenain uum Yox asin an uso}ag | uosseud® yajgeuerayeuen | verso =yataeuen | =v “ase ayaeuen occais: | s4zulaynso/ aun ulsse pueuojssasdxa ajo anjenpue erg | MPS deuenosnrenoquaam any asimg ay wojag | vossoidre w ajgeuens genes | vosovsra -paeuen | = -aygeuen ayy on ynsos ou suflsse pue axgenen on joanennin uns oprandio age aren astern | uossxéro —ajqeuenaygeuen | wossevdra=—aygenen | = aa | caw! ayqeuen uy on ynsos aun suaisse pu uotssxcho ‘exe wi Sarr omar ant aygeuenejoonten an sppy | wosseuha + oqevensajgenen | votseidra =v aygenen | =+ ‘q=.e ‘esau -ajgeten ayy on 9591 ays suBlse pue uossaxda Toa cseomenaun Ag ageuene yoann ayisaydainn | vosaudo ajeuensayaeuen | uopsoxdea, orgeuen | =+ ye cela | ajgeven ag ose borin suse pe vse See ree joann oun Agageuenefoaren ain sama | uosseeo/amsuenajgeven | umoseias/ even | °/ ‘aze ‘ot= 43204 ayqeven ayy on nso ayy suasse pueUOIssauex 106 =e 1204 | te jo anjen aya Aq geen ejo anjen aya sapinia | uovssaudra / ayqeten = aiaeuen uolssasdxa =/ ajqeuen 2/ auueaw ‘03 quayeninby, xewhs 40ye10d0 SAS SE jo | 44 | Programming inc ___— ct to each the relative priorities of the operators with respect to €a< other that determine the order in which the expression will be evaluated, Associativity defines the direction in which the operator having the same precedence acts on the [Fos It can be either left-to-right or right-to- left Priority is given precedence over associativity t0 detérmine the order in which the expressions are evaluated. Associativity js then applied, if the need arises. Table 2.1 7flists the operators that C language supports in the order of their precedence (highest to ive Te ‘associativity indicates the order in which the operatots of ‘equal precedence in an expression are evaluated. EESTERTA Oerstor precedence’ © Operator | Associativity | Operator | Associativity 0 left-to-right left-to-right 0 | 4 right-to-left left-to-right (type) & | sizeot | + 1% —_|lefttoright | && left-to-right + left-to-right | 11 left-to-right <<>> |[lefttoright | ?: right-to-left left-to-right right-to-left left-to-right left-to-right & left-to-right You must be wondering why the priority of the assignment operator is so low. This is because the action of assignment is performed only when the entire computation is done. It is not uncommon fora programmer to forget the of the operators while writing any program, s, rnded that you use the parentheses opera” seo default priorities. From Table 2.17 you eg 10 oat the parenthesis operator has the highest pig, ae a spentor placed within the parenthesis wi evaluated before any other operator EIDE oressions usin the Precedence car ge445 ee w+5t6 12 +30 = 42 Rxn3* 445) 46 =3496 276 162 34445 /2 wes /2 2/2 1 3* (445) /2 3e4/2 w/2 6 3+ 4% (5/2) Be4ae2 wee priority itis recomme 3 * (4% 5) / 2) * 4/2) +2 26 Take the following variable declaration, it aso, bea, float x= 2.5, y see nay = 0.0; TE we write, asba e=7; Sing ce the a 2 ‘ssignment operator works from Sohe-to-tett, eherenen So 7. then:a: a! Now ae pn Sine’ B= c, therefore b= 7- 1 80a = 7 asey “=e #10 This is expanded as Bras wey (ccs mare ne 10)) 2 (-20)

You might also like