You are on page 1of 34
Basics of C Programming Basic Input output = Introduction to C : History of 'C’, General Structure ol a ‘C’ program : Header files, ‘main’ function. Data Concepts : Character set, tokens, keywords, Identifiers, Variables, Constant, data types, C : : les; 5. © operators, ‘Arhmetic operators, Arithmetic expression, dectaring variables, and data type conversion. Input and Output statements, usit rintf() and. scant(), character ing Siemens, Inpwoutput formatting, Use ot comments Pn Me seria 4 History of Languages ” | C++ Programming _(c programming language was developed by Denni Ritchie at the Bell Laboratories of AT & T. He developed 2 complier that can convert the HLL namely C to the machine language that can be understood by the processor or the computer. But his compiler could understand only if certain rules were followed while writing the program. We need to understand and know these rules to program our computers using this programming language. C was the most popular programming language. ) Some other languages had become popular after some time of evolution of C. This was because these other Programming languages were object oriented i.e. more Significance was given to object. While ‘C was a Procedure oriented language i.e. more significance was Given to the procedure to perform a task, ~ C+ which is an object oriented programming language Was then developed again at Bell Laboratories by 8)ame Stroustrup. Earlier, this language was called as C With classes, but was later renamed as C++ in 1983. 2.2 Procedure Oriented Programming G ‘A procedure oriented programming language is one in which procedure i.e, method or functions are given ‘more significance. Here, one function calls another. There can be global vari each function. les and local variables to Fig 2.2.1 shows how a programming operation. procedure oriented aii typ OF ani wakes teaee scaeeoes wee eee tasks or sub tasks called as procedures or functions or methods. Any function can be called at any instant. There are global and local variables as seen in the Fig. 2.2.1. The global variables can be accessed by all the functions, while the local variables are local to the corresponding function. ‘A procedure oriented programming language follows top bottom approach. Top bottom approach refers to approaching to a problem as a big task or as a whole. Then dividing this task into small instructions or operations. Hence, initially the task is broken into small tasks and then these smaller tasks are written in detail. and also error correction is ofl ple of procedure = programming language Is an €x3IM oriented language. Fig. 22:1 : Structure of a procedure oriented ‘Programming language 2.3 Object Oriented Programming (OOP) — Object oriented programming as the name says, it gives more significance to the objects which has data ‘and functions built around it. ~The data of the object can be accessed by the functions associated with it. The functions of one object can access the data of another object through the functions of that object ~ Object oriented programming uses bottom up approach wherein the smaller tasks are first dealt in etal and gradually creating the entre huge system, Fig: 23.1 shows the stricture: of & object orignted Programming language, C++ and Jaya are examples of object oriented programming languages. ~ € programming language as already major feature of being a structu language and hence it is very easy for the pro itis procedure oriented language C programming language has become popular ‘of its major features like reliable, simple and use. 2.5 Tokens of C — Before going for programming, let us see a important thing required for programming i.e. ‘tokens of a programming language. ~The C programs are made up of different things’ as tokens. ~The different tokens of Care its © character set © keywords © identifiers © constants and variables © data types © operators 25.1 Character Set of C 23 lalphabets (Upper case and lower case) [Digits (numbers) ‘special symbols (all those seen on a] <>(I()[],.i:1?/"/+*=%&R@I\~ 9% — keyboard, nothing besides that) {the rames used fr these symbols are given inthe Table 252) lother special characters Blank pace, Tab, Carriage Return (Enter Key) Table 2.5.2 : Special Symbols and their names 5 Comma & ‘Ampersand, Period or dot : Asterisk $ Semicolon e Minus Sign Colon * Plus Sign ? ‘Question Mark |< | Opening Angle (Less than sign) 1 | Exclamation Mark | > | Closing Angle (Greater than sign) ke Pipe iF Left Parenthesis: f Forward Slash ) Right Parenthesis \ Back Slash T Left Square Bracket ¢ Single Quotes |_| Aidt Square Backes | * | Double quotes | Left Brace ~ Tilde } Right Brace Zz Underscore # Hash » Caret $ Dollar % Percentage 4 be discussed inthe forthcoming chapters. Each of these special symbols may have some significance which will 25.2 Keywords a predefined jords that have These are some special word See meaning for the ¢ compiler, Hence, cannot be used as identifiers are reserved for the: These are a set of words which eee certain operations and hence are also, sometine referred as reserved words. All keywords are in lower case. ‘These rules are stated as follows: ‘the identifier can consist of alphabets, digits special symbol Le.’ (underscore). ‘an identifier cannot start with a digit. It can either with an alphabet or underscore. it cannot contain any special symbol underscore. Blank spaces are also not allowed. ~The keywords usd in Careas follows fepezalit cabrect Be 2 kevivond [ auo | else | tong | switch 5, tt Is case sensitive Le. an alphabet capital in ie =" in another identifier raqisea CNBR identifier with same mame in an Sreak Hf enurn | ires) ve that alphabet small case will be considered dif case [extern | return | union Cae Sere 6 _ Earlier; there was a limit of the length of the id Sales perl ee | to be 32 characters, but now this limit is remo ote 5 Hence, an identifier can be as long as required continue | goto | sizeof | volatile minimum of one character. ~ _ [/eetaure | it [statis | white = int | struct | _Packed Ex. 2.5.1: A list of valid and invaiid identifiers is given ba aaa pb with reasons wheraver required. cag 1. simple_interest 1. for: This keywords is used to implement loops Fieenen int: This keyword is used for declaring variables of Steue integer type 4. _Stiends 3. struct : This keywords isused for making structure i.e, 5. Simple interest user defined data type A 6. #3triends Static : This keyword is used to cn eate ee variables of 7. void = 8. Void These keywords will be used in different places in Beeremming. Ther significance and use will be studied Wherever required in the forthcoming chapters, ‘These keywords include dedlared by Ans; Institute) C. This instit all those keywords also as (American National Standards ute has published the standards ramming language, things lke variables, ERETSs unions, etc need to follow some rules, Soin. : ssimple_interest : Valid 2, char: Invalid, because itis a keyword 3 7 3friends : Invalid, because starts with a digit 4 _3ftiends : Valid, 5: Simple interest: i s Invalid, ane ‘because blank ‘SPaCes are 8. W3friends : | + Invalid, bea, a oe ‘USE NO special symbol 7 8 — ——— | programming in °C’ (MSBTE) 154 Scalar Data Types in C qne data type decides the type of data and the memory locations required for storing that type of data inthe memory. 1 ‘re data types of C can be divided into three types: primitive data types : The different primitive types of data that can be used in C are integer, character, fraction type numbers, etc, Sy ape (ii) Basics of C Programming The Table 2.5.3 shows the different primitive data types and the memory space required for storing them, Derived data types : Pointers, arrays and strings are derived data types. We will study these in Chapter 4 and 6, User defined data types : Structures and unions are examples of user defined data types. We will study these in Chapter 4. 2 Datatype No. ‘ | a. | char Acharacter in ASCII form | - 128 to 127 1 oa | sinedchar |_| A.character in asciitorm | —128t0 127 1 (3. | unsigned char "| acharacterin ascilform | 0t0255 1 4. | int Integer nos. = 32768 to 32767 2 5 | signed int Integer nos. = 32768 to 32767 2 6 _| unsigned int Integer nos. 0 to 65535 2 7._| short int Integer nos. = 32768 to 32767 2 8 | longint Integer nos. — 2147483648 to 2147483647 4 3,_| signed short int Integer nos. — 32768 to 32767 2 signed long int Integer nos. — 2147483648 to 2147483647 4 unsigned shortint | Integer nos. Oto 65535 2 22. | unsigned long int | integer nos. Oto 4294967296 4 3. | float Fraction nos. 3de *to3.4e" 4 14. | double Fraction nos. 1.76 to 1.76 8 ies Fraction nos. ade“ to ite 410, Fuasa: Some examples of data to be stored are listed below with 1, Age in years e 4, 3. Alphabet 6. 5. Runs made by a batsman 8 7. Radius of a circle 9. User input as "Y’ or 'N the data types that will be best suited for them Rate of interest Programming in ‘C’(MSBTE) ‘as years a ‘Age in years : int type data must be used Rate of interest : float data must be used = asa chara abet : char type of data Is to be used, wie data must be used 5 : ye used, Principal amount : float tv must b Runs made by a batsman : int type data must os Factorial of a number: int type data must Be user : ist be used, 2s ra Radlus ofa circle: float type data must b ‘Area of a circle : float ‘nt: char type data must be used, -3 may also be used for this. 2PM Pe ew User input as ‘Y'oF ‘no. Boolean type of dat ‘The arithmetic operations can |) (Ainerican Standard Code for I 2.5.4(A) Strings When a data as 2 word is to be stored or a sentence Js to be stored, we require a string. It is a collection of multiple characters. We will see Strings in detail in a later Chapter 4. 5.5 Declaring Constants and Variables Constants are values given to the identifiers that do. ‘not change their values throughout the execution. of ‘he program. ~ Constants can be defined either by writing the ki const before the data type or by using define, ~ Constants are used to dedlare the values that remain Constant, for e.g. value of pi. ~The use of constants in program will be discussed later wherever required ~ Variables are values given to Identifiers that can ~ change their values during the execution of the program. Ex. 25.3: Define the variables for the following: 1. For declaring age as an integer type data the 8yntax (grammar or mettod of writing) is 2. For declaring rate of interest as float data type the syntax is: 3, For declaring a character data type element the syntax is: erate of interest is fr ter is to ieipal isin rupee and Pats. the factorial Is alwa) pe data must be used, as reais radi as there integer value: ction type valu bbe stored. eno, of runs will always be INtEBT- ys an integer. wus will mostly be a fraction number. 3.14, which has to be fraction number. is only a character to be taken from the user as For declaring age as an integer type data the: (grammar or method of writing) is : int age; 2. For declaring rate of interest as float data ty syntax is : float rate; 3. For declaring a character data type syntax is : char x: 2.5.5(A) Types of Constants Constants are values given to the identifiers not change and can be declared by the keyword: ‘There are three types of constants : | (1) int type constant: This is for integer variable | (i) single char type constant: This is to declare. constants. iti)" float or real type constant: These are used to dec real constant values, '. For declaring age as an integer Cares Se ee feria walt ‘syntax (grammar or method of writing) is: const int age=18; 2. For declaring real data type with the value of “pi” the syntax is : const float pi-3.14; 3 For declaring a constant character data type element ‘with the value ‘H’, the syntax is : const char x='H 2.5.6 Escape Sequences arhracnve) L — scape sequence is #”-character followed by +o mere vip — They are used especially to perform some_ special operations Mike going to new line, providing a horizontal tab, vertical tab etc. = The following isa list of escape sequences. 1 Wn Newline ze Horizontal Tab BW, Vertical Tab 4 \b Backspace \r Carriage Retum \F Formfeed \e Audible Alert (belt) /,\9%"" [beep Sou) WW Backslash \? Question mark Nt Single quote Double quote — Operators are different special symbols used for indicating an operation to bse performed. — We will discuss operators in more detail in a later section. 2.5.8 Errors in Program ‘errors in the program namely : There are two types of 2.6 _ General Structure of a ‘C’ Program — ri Basics of OP ‘Syntactical errors These are the erors in_ writing the statement. “Gniceton, of spelling, mistake of case ‘These errors can be detected and spec TeesSier When compiling, the complet {hose error and the programmer needs t0 rec ‘same before compiling and ‘executing the same- 2. Semantic errors ‘These ae errors in the ogi. the ot seen, although the program i thei there Is some logical error in the program. This aibe rectified by debueging the program. There are two methods of debugging the program i.e. single Stepping debug or breakpoint _debu ing statements one by one and checks whether the tapected output is obtained or not. In case of breakpoint debug, there are breakpoints Inserted in the program where the processor waits for the programmer to check the status of the registers. 1. Syntactical errors \ the system Iibe27: ition Section aefines 2 section: The El sym constants s joval variables ration te Gobel Del reece ee jon cv CE ain fc: 27 ml egos section ‘ ion and executable part sm mst have one main ee contains two parts, i daa unan pure dcres athe varies US cetble pa. spew should be at Teast one statement in the Fecrbl part which contains instructions to perform certain task ed in the ~The declaration and executable part must appear | Program 2.6.1: Write a simple program to d between fel ore and ee Lien All statement “Hello Friend”. statements in the declaration pa fend with the ae Step-form Algorithm ~The Subprogram Section contains all the user defined | Step! + Display the sentence "Hello Fi funcions that recalled in the main function. printf() Function ~ Tobegin with a very simple program in C, to display the 4 3 "Hel rien” onthe standard output device ie, |“? + Walt for user to press a key the monitor ofa computer. function. ~ We will then understand the meaning of each word | StePM ©: Stop written in the program and also hi i ieee ow to execute this | Pseudo code Algorithm 26:1 Header File Se esate - systema ‘hat begins with the‘W sign is meantfor | nell? PRINT "Hello Friend pre Re) statemem tie, | 2PM 2 esron cHindludecstdion>, indicates the ee Preprocessor to | Flowchart 6 oe have included this header file | ts OF Of the | hence We i intormation ne tt of ‘main’ Function cae sructions © the PE | 9.6.2 ‘main’ Ful section rows ne functions (2 a ‘any program of C should have a main processor 12 3 : am 26-4, (function is a set of statements to perform, task). In the statement void main(), the word indicates that this function is not going to return data to its caller function. The word “main” is which identifies the function. The brackets of this statement, is a place where paramete passed to this function. The curly braces ({ and }) indicate the start a ‘the function, The “{*indicates beginning of while the “)” indicates end of the functio The first line that starts with *//", indicates that this is ‘a comment line. The comments are written ina program for future reference of 2 programmer. The comments are neglected by the compiler (compileris 2 software tool that converts the C program to the machine language). In comments you can write anything, it may be helpful to understand your program by somebody else or by yourself after you see the program after a long period. intf{J" function is used to display 2 data on the standard output device ie, the monitor. The statements given inside the brackets are displayed on ‘the monitor. Ifthe data written inside the brackets isin double quotes, then the data will be displayed as itis. ‘The getch() function is an inbuilt function used to accept an input ‘the_user, This makes the computer to wait for the user and hence, makes to output screen available for the user until he presses @ key. 2.6.3 Enumerated Data Type These are used to contain values that are not limited to the values that are possible for fundamental date ff there could be a data type February, March, ctober, types. For example if months, its values can be January, Febr ‘April, May, June, July, August, September, November or December. ifthere could be a data type cal Similarly, vyellow, pik. jed as colors), Basics of C Programmin “Thus, such special things can be created using the enum", The syntax of creating a enum is as follows Syntax: [7 coun Chm Rane Sylluel > pcwalee ds ‘An enum of the week days.can be as follows Example : Gam WeekDays (Sinday, Monday, Tae Wednesday, ‘Thursday, Friday, Saturday. “The syntax of declaring a variable of enum is as follows syntax (ra pane enumvanablegoso j to create a variable of above declared enum = we want of weekdays, “Jo asssign a value to a variable of enum, the syntax is ‘as shown below : Syntax : If the value "sunday" is to be assigned to the above created enum _variable we need to write, Example: Integrated Development Environment (IDE) e Preprocessor, Compiler, Linker and Loader IDE ig a toolkit to write and execute a The ‘most widely used IDE with the C programs is the Turbo is IDE contains of five tools namely : Editor, 27 IDE, Thi Preprocessor, Compiler, Linker and Loader. = Editor Its used to type and edit the program. Preprocessor i it is i ‘operations before the compiling, like including header the values could be red, blue, greeny 2» lack etc. files, declaring constants, etc. it always begins with the san wert the C program vy ‘ot understand ine js used to, com ge. As the processor conn! need to convert into ma ie machine languaee- (connecting) the different functions in @ ‘we may write rmuftiple functions in the Progr’ onditional/ooP peratins in our program. These kinds of operations are to be handled by the linker. toeder : It loads the binary file from. th memory and gets is executed by the processor The binary file that the loader Joads is the machine language program understood by the processor. Program execution steps are 2s follows : — Compiier : It # machine languat the language of G We understandable language Step: Double dick TC.exe to get the editor window. step 2: step 3: proglOlepe. / Step4: Compile the program by pressing Alt + F9 Le press the Alt and F9 key together. StepS: _Exeaute the program by pressing Ctr + F9 Step: See the output on the screen and press enter ‘to come back to editor window. 28 Operators eae oe SPUN The Operators are one of the tokens of C, There are different types of o a perators classified based on their Many of these operators alt be underond in the listed here, but will Shen ns sss ean sory, and mM. SO you may Sperators and YY Just go through th 8 understand them later a These are operators that require OF one hese operators one By one Let us discuss t 4. Unary minus (-) ‘The symbol shown in the bracket. is used as un minus operator. tereturns the negative value of the variable to ispreceded. Example : if x=3 and y=6 then y will make the value of y as — 3. 2. Casting Operator (()) or Type Conversion tis many times required to convert one data type. ‘another. ‘The casting operator is used for type conversion can be used to convert a data of one type to « data type, oe Example : ifwehave int x=3; float y=5.6; then the statement, x=fint) yj. will result in the value of xas 5. We will see the Programming, Fa 9 ss ore 3. Logical Not operator (} Programming in ©" (MB ‘Example: if x=1, then y=bc will result with y having the value 0. 4, Address of operator (&) This operator returns the address of the variable associated with it, Example : if we write y=8x; then the memory address allocated to the variable x will be copied into the variable y. For this the variable y must be a pointer variable, 5, Indirection operator or value of operator (*) ‘This operator returns the value of the data at the given address. Example = =*y; will give the value of the data stored at the address given by y. 6. Scope Resolution operator ( — it resolves the scope of a variable to be inside the function or outside the function. This operator will also be studied in a later chapter. Example = — if an external variable x is to be accessed then the same can be accessed using the scope resolution ‘operator by the statement, y=i3x; 7. Sizeof operator ~ This operator is used to know the size of a variable as required to store its value in memory. It can also be used to find the size of a data type. ~The space required to store different data type Is different ranging from 1 byte to 10 bytes. Example : The statement sizeoflint); will return the value 2, as int requires 2 bytes. 9, Increment Operator (+ +) = This “x+4;" “pitwise not operator (-) This operat operation. ‘The bitwise NOT operator

33=1 ‘Assuming the data to be char i.e. 8 bit data (23)o= (00001011), After shifting left once (00000101) ‘After shifting left for the second time (00000010, ‘After shifting for the third time (00000001);= (tho tor Programming in‘: (MSBTE) =< Sa Temary/Conditional OPerat fhe ORefSand9uI3 = : The EXOR ofS and9is12 0 = onaltional operator with The NOT Sis—6 aoe . [The NOT of 9 is — 10 2.8.2(C) Logical operators ~ _{peical operators follow the same truth table as forthe bitwise operators; but they are used to check Conditions instead of performing operations on a data. — The logical operators are AND and OR. The a used for these operators in C are && and | respectively. For example a statement yPS&RKy<10; will result in “true” ie. 1 if the value of Vis greater than 5 AND less than 10, else it will result infalsei.eo. Another example a statement W511 y=2; will result in “true” ie. 1 if the value of y is greater than 5 OR equal to 2, else it will result in false ie. 0. 28.2(D) Relational operators — The relational operators are used to test the relation ‘between two variables or a variable and constant. ~The operators like ‘< (less than) and ‘>’ (greater than) Used in the above examples are relational operators. We have seen the example also of the “==” (equality ‘perator) in the above logical operators, Allist ofall the relational operators is as follows : + == used to check if the two things are equal, 2 I= used to check ifthe two things are not equal, 3 < Used to check ifthe first data is less than the second one. 4, > Used to check if the fist data 's greater than the second one, < tsed to check if the first data is less than or equal to the second one, fh? t0 check ifthe first data is greater than or equal to the second one’ The examples of these relational operators are aq m with the logical operators above, 6. erator that requires three operand i calle ‘An op ternary operator: in C. This 9 nly one ternary operator is oneck a condition and accordingly do the two things based on the condition being false : ‘The syntax(way of writing) of this operator is a fg He — Hence; as shown in the syntax, first the condition be written in brackets followed by a question be performed if the condition is false. Example : given condition i.e. x > y is true. Else; the will be put into z. Hence, the value of the variable will be put into z. ~ Aslightly complicated use of this operator is to greatest of three numbers as shown in the exa This statement will the variable g. 2.8.4 Assignment Operators and State i ~ These operators are used to assign the value expression or variable on the right of the Operator to the variable on its left. The simple assignment operator is ‘<'. But some more assignment. Operators called as com assignment operators, ‘expression or vay the variable on its left. Example: yaxs, 4= 4 This operator adds. ie is opaator nds halve Wefan oa, ans thi pseton anD> the VaR: its left right and the result is put into the v ue put into the variable on and right. and the result #5 put into ed variable on its left. Example : yB=x; Is same as Y=VE% Example : y+=x; Is same as y=¥+X; variables on its! This operator ORs the jeft and = : This operator subtracts the variable on its 8. right from the variable on its left. and right and the result is putinto the variable of the result is put into the variable on its left. ae Example : =x (5. same asy=y—%) Example :y|=%; is same a5 ¥-¥) 4g. me This operator ©xORs the variables on GF uit into the and right and the result isp! variable on its left. Example : y*=x; is same as Y=¥"% 1 shifts in left direction the 1e number of times ‘or value on right the variable on its 2: This operator multiplies the variable on its left ‘and right and the result is put into the variable on its left. i 10, () +. Thisis called as a fun + The comma (,) operator Is used to separate the different values ete. Precedence and Associativity of Operators ‘The precedence of the operators means the sequence ‘which the operators will be operated on, in case of multiple: vinigh operator wil be executed fist and which operator wil be executed later. operators in a statement |e, The associativity of operators refers to the direction in which the operation will be performed in case of equal precedence operators. f multiple additions 3 ‘there in astatement then it will be performed from left to right. | The precedence and associativity table Is 25, jgiven in the Table 2.9.1. Function call 0 ‘Array element select ‘structure element select Structure element select __{ sue Right to left a 5 inary plus = | Unary minus 4+ | increment operator =~ _ | Decrement operator 1 Logical NOT ~ | aitwise NoT + | Pointervalue of operator & Pointer address of operator sizeof Size of a variable or data type (| Type cast operator 3. Ee Multiply 7 Divide and get quotient % Divide and get remainder Aad) Left to right i Subtract, Es << _| Left shift operator Left to right >>__| Right shift operator & < | Lessthan Left to right <= | Less than or equal to > | Greater than >= _| Greater than or equal to Equality eae 1s _| Inequality & | Bitwise AND nae 9. | * [bitwise exor Left to right = i Bitwise OR Left to right (1) Determine the value of the lowing a7, b=3 and c=4; a 1 a%b Left to right 2.10 Expressions in C : Arithmetic and Boolean Expressions let us see some examples of how the Processor Performs operations when some statements are given to us in the following examples, We will also see some examples wherein an expression is to be written in he : so how are they =7/4 = Usince the quotient after dividing 7 | (since; the associativity of arithmetic =2/4 to right first operation is *) ‘operations is left “55 (since; quotient is 5) aricxd) =7*(6%3) = 7.1 (since; bracket opening Is to be done first, ‘and remainder of 4 divided by 31s 1) =7 2ebe3*(a-9 =2*3+3*(7-4) =6+3°(3) = 6 +9 (since precedence of multiply is more than ‘add, first multiplication is done) =15 atexb =7°4K3 =28%3 =1 atb-< =74+3-4 =6 ‘Suppose the following statements are written; Int i=9, j=6; float x=0.5, y=0.1; char a='a', b="b’; Find ‘1¢ values of the following expressions (371-2*))%(2*a-b) =(27 ~ 12) % (2 * 97 ~ 98) ....(since; the ASCII values stored in char type variables is 97 for a & 98 for b), = (15) % (96) #15, 2* (/5)-+(4* V-3)) % (14-2) =2*(6/5)+(4* (6-3))% (9+ 6-2) =2"(1) + (4*(3))%(13) =2+(12)%13 =14 (ey) @& (> 0) && (> 5) = 1881881... 4 {if condition is true its result is 1 else its 9) ee 4. ((x0)) 11 (173) = (088 1) {| (2) = (0) 11 (2) =1 5. as09 (since; condition given is false, the value of ais 97) 6H = 10 .. (since; it is pre increment it will return the value after incrementing i.e. 10) oe (since; this is post increment it will return the value before incrementing i.e. 9) 8 Mfb==98) 41) ..(since; the condition given is true ie. b=98) (since; after performing NOT operation the value becomes 0) (MM) Write the C assignment expressions for the following = 1. Ais greater than B and greater than C {A>B)8& (A> C) 2. _Aiseither less than B or greater than C (aC) 3, Side is equal to square root of a° + b* 2ab Side = pow((a*a+ b*b+2*%a*b),05) 4 3 = aay gy qeysenta/yee yi etT 2) 3) xe we ‘ pepowecbey 4enee) 05) Mana podeate),05) O° a) (-b-pow((d* a+ geat pales 1 z= atifre(kea)/2) 2:11_ Basic inpuoutput statements _ — inbuilt 10 functions are available in C for displaying data on the standard output device i.e. monitor and ‘2ccepting the input from the standard input device i.e. keyboard. — These JO functions are classified as formatted and unformatted functions based on the formatting permitted or not. 2.11.1 input/output Formatting } Marks) | "wo formatted 10 funct ) 3 data on monitor ang nin € namely Scanfl) to accept contain the following : mat string ©" 0-9, all The fo (a) 2, et (AZ 97 character Tr keyboard) symbols 0" lank spaces ences = The width of a value ca ing the field width. Examp in this section (b) (©) (d) escape sea! Field width : T fixed by specifying the such cases are given! rormat specifiers : Format specifiers the format of the variable data whose to be displayed. The format speci different types of data is given it Table 2.11.1. fe) Format specifiers a For integer type of data 2 | xe For float type of data 3 | %e For char type of data 4a | MF For double type of data 5. | %6Lf For long double type of d 6 | %s For string or characters 7. | %& For hexadecimal data 0) (i) (ia) Printf("The number of buildings is 9d”,b) This statement will 4 Print the output specifier replaced with thevalue othe Printf("The simple interest i agp si); This statement wilt where Specifier %f wit) eee nets of the variable si, past Printf("The simple inte The format est is %5,2F" si, Specifier in this statement is a tere, format string can contain format specifier, field width and assignment suppression character. The Sesignment suppression character (*) Is used to iscard one of the user entered value. ‘The address of the variable is obtained with the help ‘ofthe address of operator (8) sseanf{"3%d",8X); his statement is used to accept a int type value from user in the variable x sscanf{"36d 96d XP" 8x, Sy, 82); ‘This statement is used to accept two int type data into ‘variables x and y. It also accepts a float type data into the variable 2. 11.2 Character input/output Statements The unformatted 10 functions do not have any format Specifier. They are mostly used to accept and display only one character or a string (string is a set of Characters to make a word or sentence). The different unformatted 10 functions are listed as follows : getch() This function is user. 2. getche() ‘This function is used accept one character from the user and echo it (display it on the screen). 3. getchar() ‘This function is used to accept one character from the User and echo it (display it on the screen) and also wait after that for the user to press the enter key. 4. gets() ‘This function is used to accept a string from the user. 5. putch() or putchar() ‘These functions are used to display a character on the monitor. 6. puts() This function is used to display a string on the monitor. used accept one character from the 2.12 Program Examples Program 2.12.1: Write a G program to accept a number and display its square. ‘Step-form Algorithm ‘Step! : Declare the required variables. Step Il Indicate the user to enter the input number by displaying suitable sentence using printf() function. Step I ‘Wait using the scanf() function for the user to enter the number. Step IV Calculate the square of the user entered number. ‘Step V Display the calculated result using printf() statement, StepVi : Wait for user to press a key using getch() function. Step Vil: Stop Pseudo code Algorithm Step! : START Step it: PRINT "Enter a number". Step ill = INPUTx. StepIV : y=x*x = StepV —: PRINTy. aid StepVI: STOP r Flowchart : (Rafer Flowchart 7) GD ok header file Is Included le, canioch for the two functions used in the program namely cirscr() and getch(). The function cirserl) Is used to clear the user screen and the function getch() as already discussed accepts a character from user. Here, we use this function, so that the pr ass for us to enter the character before closing the output window after displaying the result. ry fast it displays the he output cnie sereen and doses t a see the output. Hence, to make Yor us to see the result we give a ver processor operation If | before we cat te to walt geteh() furction: the variables xand y are declared cing the fst printf) statement the user Is asked to prowase a umber whose square sto be found. scanf{) function is used to accept the input from the user. The format string In the double quotes is sed", thus indicating a integer type data to be accepted. The Input (5 taken from the standard input device Le. keyboard. “The next statement assigns the value of x multiplied by Itself to provide the square in the variable y. _ The next printf) statement is used to display 8 data on the monitor. The format string used in it is used to as integer type data. the ‘Step VI indicate the two numbers i.e. x’ and 'y’ gram 2.12.2: Write a C program to accept two numbers and display its product. ‘Step-form Algorithm ae + Declare the required variables. Step Indicate the user to enter the numbers by displaying sultable sentencs using printf() function. Seepill + Wait using the ow Se ee Step 1v Calculate: pate Gx thes ree armel ‘numbers. x 4 ae eee ee StepVl : Stop Pseudo code Algorithm Ben) STARR a, Step li + PRINT “Enter two mumbers*, . “4 Smit 1 INPUT ae mw rexty, 7 Stepv Punt: : ‘The two numbers are accepted in the variables x and y ‘by scant) function in a single statement. The product is calculated using the multiply perator (*), Indicate the user to enter the principal amount, rate of Interest and period by displaying suitable sentence using printf() function. Wait using the scanf() function for the user to enter the data. Calculate the simple interest using the formula. Dishes loi reat va ct) statement. ef wp yg function. stop Step | ‘Step I Step iit START. PRINT “Enter principal amount, rate of interest and no. of years". INPUT Fn. sis(p?r*n) /100. PRINT si. eS All the variables are taken as float 2s the, fw mien parameters are normally with fraction part included ji, etc. Program 2.125: principal has rupees and paisa; rate of interest is fracis Write a ‘C’ program to enter basi salary. Calculate gross salary with 5 | DA and 15% TA on basic salay Display calculated gross salary Programming (MSBTE) Step-form Algorithm step | Declare the required variables. stepil = _ indicate the user to enter the length and breadth of the rectangle as input from User by displaying suitable sentence using printf) function, Stepill = Wait using the scanf{) function for the User to enter the input StepIV = Calculate the area and perimeter using the corresponding formulae stepV = Display the calculated area and perimeter using print{() statement, StepVl Wall for user to press a key using getch() function, Step Vil Stop Pseudo code Algorithm Step! 2 START Step = _—-~PRINT “Enter the length and breadth of the rectangle”. Stepil = = INPUT/,b. StepIV =: a=/*b stepvV = p=2(/tb) step VI PRINT a, p. Stepvil : STOP ee ee 23 Basics of C Programmin, Program { Pinehude Seidioh> #include void main () "float Length, breadth, area, perimeter; perimeter= 2° (length + breadth); elrser(): printf("Enter the length and breadth ofthe tectangle!”), Cae scanf("f901", &length, &breadth); ANS ‘urea= length * breadth; - z printf("The area of rectangle is= ef and its perimeter is = Jl", area, perimeter); geteh()s t : = Step V ‘Step til Stepiv i Program 2127: Write a program to separate the digits of a three digit number and display the three digits separately. Step form Algorithm Step | Declare the required variables. Step tt Indicate the user to enter a three digit number by displaying suitable sentence using printf() function. Wait using the scanf{) function for the ser to enter the input. Get the last digit of the user entered number into a variable using the modulus ‘operator (‘%'). And by the quotient operator ('/') get the remaining part of the number into the same variable as that cof the original number. Repeat the Step IV to get the remaining two digits. ‘tepVI__:_Display the separated digits using printfl) statement. ‘Step Vil Wait for user to press a Key using getch) function. step vill: Stop Pseudo code Algorithm Step! : START Stepll PRINT “Enter a three digit number". Step) = INPUT. SteplV : di=nmod10 eevee 130) mod 10 ‘Stepvi : d3=n/100 aot PRINT di, d2, d3 When a number is divided by 10 and its remainder i; taken, you get the last digit of the number. When the same number is divided by 10 and the quotient is taken then the last digit is discarded ani ‘the remaining digits are obtained as a result. Tis logic is used to get the remaining digits of the W_ Programming i (MSBTE) 2.25 Basics of C Programming Pseudo code Algorithm step START. step! PRINT “Enter two numbers", step Il INPUT a,b step IV IFa>b, THENx=a ELSEx=b. step V PRINT x step VI stop Flowchart : (Refer Flowchart 12) PRINT “Eniora two numbers greater=(n >n2)?n1in23 rintf("The larger number is + ed" greater); chy Output: ter two number (The larger: nim Program 2.12.9: Write a program to accept three numbers from user and display the (greatest of three using the conditional ‘operator. Step form Algorithm. Step! Declare the required variables, Step 1 Indicate the user to enter three numbers by displaying suitable sentence using printf() function. Step i Wait using the scanfl) function for the User to enter the input. Stepiv Using the proper syntax of the conditional or ternary operator. find the largest of the three numbers and store in another variable, StepV : Display the greatest number using printf() statement, ‘Step Vi Wait for user to press a key using getch() function. Step Vil Stop Pseudo code Algorithm Step! ‘START Stepi PRINT “Enter three numbers". StepIN—: INPUT, b,c Step IV [Pa>bANDa>cTHENx=a EISEb >¢THENX=b ELSExe6, StepV PRINT x Stepvi : STOP wait using tht ser to enter te INPUT ‘haa the three numbers and divide th, sum by three. pisplay the average calculated “vin, printf() statement. Wait for user to press 2 Key using getchy function. fetep il oes = SUP) Pseudo code Algorithm Step! ‘START. Step It PRINT “Enter three numbers". Step Il INPUTa, b, © Step V avg=(atb+0)/3 Step V PRINT avg. Step VI ‘sToP . : (Refer Flowchart 14) ¥_Programming in‘C’ (MSBTE) The avg is given as sum/3.0, because sum is a int data type variable and if we write 3 instead of 3.0 then this will also be int data type; thus while performing the operation we will get only the quotient neglecting the fraction part of the result. - By writing 3.0, one of the data type becomes float and hence the result is also float thereafter ie. automatically upgraded to the data type of higher size, float in this case. Program 2.12.1 Write a program to swap two integers. OR Write an algorithm and flowchart to swap the contents of two variables. Step form Algorithm Step! -:_Declare the required variables. Step Il : Indicate the user to enter two numbers by displaying suitable sentence using printf{) function. Step ill: Wait using the scanf() function for the user to enter the input. StepIV Using a temporary variable swap the two numbers. The logic to swap the numbers using the following logic (i) Put the first number in the temporary variable. Put the second number in the first number (il) Put the temporary variable in the second number 27 Basics of C mimi StepV _:_ Display the two numbers indicating the two numbers are swapped using printf() statement. StepVI_—-:_ Walt for user to press a key using getch() function. Stepvil Stop Pseudo code Algorithm Step! START Step: _-PRINT"Enter two numbers". Step INPUTa,b. SteplV :_ temp=a. StepV 9: a=b StepVi =: b=temp Stepvil = PRINTa, b. Step vill: STOP Flowchart : (Refer Flowchart 15) Per rs i... mS MSSTE) 2.2 Basics of G Programm Flowchart : (Refer Flowchart 16) ‘A Special use of the ternary operator. if the remainder after dividing the number by 2 sO, it is an even number else odd, Write @ C program to check whether Program 2:12:13 : : ‘glven number is positive or negative 2 7 (Refer Flowchart 17) Flowchart ‘Step Declare the required variables, Step Indicate the user to enter two numbers {rom user by displaying suitable sentence using printf() function, ‘Step itt Wait using the scant) function for the: User to enter the input. Step iv Using the bitwise ‘Operators calculate the “esults according to the said operation, SPRY cir api othe acts calculated using Printf() statement. : Step VL walt for user-t0 press a key using etch) function. ‘Step Vil Stop. Pseudo Code. Algorithm Step i START. Step ut PRINT “Enter two numbers”, Step mi INPUT 9, b. StepWV : x=aANDL, Stepv V+OORb, ‘Step Vi Fa EXORb Stepvi : p= Nora. sep Ti a=NoTb Scop ix PRINT 2B, amie na Programming in ‘C (MS! Eaene Flowchart : (Refer Flowchart 18) Program 2.12.15: Write a program that calculates the roots of quadratic equation. Step form Algorithm ‘Step! Declare the required variables. ‘Step I Indicate the user to enter the coefficients of the quadratic equation by displaying suitable sentence using printf{) function. Step il Wait using the scanf{) function for the user to enter the input. StepiV_: _ Calculate the roots of quadratic equation using the proper formulae. stepV = _ Display the result Le. the roots calculated using printf() statement. stepVI_ = Wait for user to press a key using getch() function. — Stepvil = Stop. Pseudo code Algorithm Step! : START. Step it + PRINT “Enter the coefficients of the quadratic equation” Step = INPUTa,b, c. ‘Step IV ® xi=(-btpow ( (btb~4*2%),0.5))/(2"a) x2=(-b-pow ( (b*b-4*a"e),0.5))/(2"2) in this program the value of dis stored as 4, since ‘d" is 2 int data type variable, In the calculation statement of x, the operations are Grtied out inthe sequence of precedence Le. first pre increment, the multiplication, then MOD, then addition ‘and finally post increment operators, Hence the value of x=++a+bit* +40% dex #242°4%4=2+8% 4224022, Also the values of a, b,c and d after the statements are Ineemented to be2,3, 4 and 5 respectively, Pome 227; fede oa wo GG rogram. Program 2.12.18 : Write a © program to accep , integer numbers from user any , the result of addition and subtaciy 2.13 Data Type Conversion = The casting operator{ {) ] is many times required to convert one data type to another. — The casting operator Is used for type conversion i.e, # ‘can be used to convert a data of one type to another data type. Example: ‘Hf we have: int x=3; float y=5.6; then the staternent, x=(int) yz will result in the value of x a8 5. Program 2.13.4: Write a program to accept a number ‘and display its equivalent ASCII using type casting. ‘Step form Aigorithm ‘Step = Declare the required variables. from + Indicate the user to enter @ number ou user by displaying sutable sentence using printf) function. Wait using the scanfi) function for the User to enter the input. Step Iv Using the type casting operator find the char equivalent of the user entered number. Step V Display the char type data calculated Using printf) statement, Step VI ‘Wait for user to press a key using getch() function, Step Vil Stop, Pseudo code Algorithm ‘Step | START. Step PRINT “Enter an integer number". Step it INPUT Stepiv x= type casting to character of n, StepV PRINT x Stepvl STOP, Flowchart : (Refer Flowchart 19) ole Explanation : This program also uses type casting oe '@ lower data type size 214 Use of c Comments are useful for a new user to oes the logic and purpose ofthe program and each eon = Types of comments oon 7. Single line comment ‘Single line comment start with the double forward Stash // Ss for the entire remaining tine, 2. Muttline comment Multiline comments starts with /* and ends wit, i

You might also like