0% found this document useful (0 votes)
17 views24 pages

Module 3 A

Two c language

Uploaded by

Shaheena Begum
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)
17 views24 pages

Module 3 A

Two c language

Uploaded by

Shaheena Begum
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
You are on page 1/ 24
thai il. Leste bectean e toalc wean choses sh eee y=56; amt = 50000; ‘© Second method is to use the input function seanf (meaning scan formatted) ‘hich can read data from a keyboard. Output function printf (meaning print formatted) is used to show results in the terminal. ‘© These functions are collectively known as the standard 1/0 library. If we use these functions in a program then we must include the statement include at the beginning of the program. ‘© The statement include should be written in the beginning, if we use mathematical functions like cos(x), sin(x) in the program. READING A CHARACTER Reading a single character can be done by using the function getchar. This can also be done with the help of scanf function. The getchar takes the form variable_name = getchar(); ‘The variable_name is a valid C name that has been declared as char type. When this statement is ‘encountered, the computer waits until a key is pressed and then assigns that character as the value to the getchar function. Since the getchar function Is used on the RHS of an assignment statement, the character value of getchar is in turn assigned to the variable name on the LHS. For example char name; name = getchar(); The above statement will assign the character ‘N’ to the variable name when we press the key N on the keyboard. The getchar function may be called successively to read the characters contained in a line of text. For example: Scanned with CamScanner Scanned with CamScanner Scanned with CamScanner as 123 454 789 then value 123 assigns to variable a, 454 is 789 assigns to variable b. Unlike integer numbers, the field width of real numbers is not to be specified and therefore ‘Simple specification is Xf for both decimal point notation and exponential notation. For example Scanfl"™ Xf Xf%8x, By, Bx); accepts input data 475.67 23.678 87.56E-2 assigns value 475,67 ‘to, value 23.678 to y and value 87.56E-2 to z. For double data type the specification should be Sif ell) ‘A number may be skipped using %*f specification. INPUTTING CHARACTER STRINGS To read a single character from the keyboard we know to use the getchar function. The same ‘can be achieved using the scanf function. The field specification Nws or %we reads character strf}gs. Se may be used to read a single character. Some version of C supports the specification %[characters] means that only the characters specified within the brackets are permissible inthe input string, The specification %[Achararacters} ‘does exactly the reverse ie, the characters specified afte circumflex (*) are not permitted in the input. READING MIXED DATA TYPES ‘none scanf statement more than one data type values can be read by giving specifications in order and. ‘type. When an attempt is made to read an item that does not match the type expected, the scanf function does not read any further and immediately returns the values read. The statement scanf{"%d Ke Kf Ks", count, Bcode, Brotio, name); will read the data 15 p 1.343 coffee correctly and _2ssigns the value to the variables in the same order as they appear. When & scanf function completes reading its lst, It returns the value of number of items that are Scanned with CamScanner etl elle POINTS TO REMEMBER ‘¢ Allfunction arguments, except the control string, must be pointers to variables ‘* Format specifications contained in the control string should match the arguments in order. ‘¢ Input data items. must be separated by spaces and must match the variables receiving the input in the same order. = ‘The reading will be terminated, when scanf encounters a mismatch of data ora invalid character for the value being read. aoe ‘scanf ignores line boundaries and simply looks for the | Scanned with CamScanner enough to contain the | cl there must be a variable address of proper type. ce character used in the format string must have a matching character in the lever end the format string with whitespace. Ris a ror. ‘©The scant reads until: 1. Awhite space characters found in @ numeric specification, oF 2. The maximum number of characters have been read or 3. Anerror is detected or 4. Theend of files reached. FORMATTED OUTPUT ‘We have seen the use of printf function for printing captions and numerical results. The printf statement provides certain features that can be effectively used to control the alignment and spacing of print-outs on the terminals. The general form of printf statement is prinef"control string’, arg, org2, , argn); Control string consists of three types of items: 1. Characters that willbe printed on the screen as they appear. 2, Format specifications that define the output format for display of each item. 3. Escape sequence characters such as \n, \t and \b. The control string indicates how many arguments follow and what their types are. The arguments arg, 2182, .... argn are the variables whose values are formatted and printed according to the specifications of ‘the control string. The arguments should match in number, order and type with the format ‘specifications. Asimple format specification has the following form: wp type-specifier ‘Where w is an integer number that specifies the total number of columns for the output value and p is ‘nother integer number that specifies the number of digits to the right of the decimal point (of a real ‘pumber) or the number of characters to be printed from a string. Both w and p are optional. Some ‘examples of printf statements are rintf(“programming in c“) pring" printh("\0"); printf A x); printg{"a = ¥f\n b= %f', ab); Scanned with CamScanner tobe read must havea fleld specification. |For each feld specification, there must bea variable address of proper type. _ Any non-whitespace character used in the format string must have a matching character in the "ger input. © Never end the format string with whitespace. It is a error, © The scanf reads until: 1. Awhite space character is found in a numeric specification, or 2. The maximum numberof characters have been read or 3. Anerroris detected or 4. The end of files reached. FORMATTED OUTPUT ‘We have seen the use of printf function for printing captions and numerical results. The prinf statement Provides certain features that can be effectively used to control the alignment and spacing of print-outs ‘on the terminals. The general form of printf statement is print{{“conteol string”, argl, arg2, ., argn); i Control string consists of three types of items: a 1. Characters that wil be printed on the screen as they appear. 2. Format specifications that define the output format for display of each item. 3. Escape sequence characters such as\n, \t and \b. The control string snicabes bout many garments follow arid whatthek types are. The arguments ag], ‘2192, .. argn are the variables whose values are formatted and printed according to the specifications of ‘the control string. The arguments should match in number, order and type with the format specifications. : A simple format specification has the following form: wp type-specifier ‘Where w is an integer number that specifies the total number of columns for the output value and p is ‘another integer number that specifies the number of digits to the right of the decimal point (of a real umber) or the number of characters to be printed from a string. Both w and p are optional. Some ‘examples of printf statements are rintft“programming In <"); print"; printf“); Print We x); primfi"a = %f\n b= %f%, ab); rintf("sum = Kd", 1234); F INTEGERS, Tat specification for printing an integer number is we where w specifies the minimum field "width forthe output. However if a number is greater than the specified feld width, it wil be printed in ‘ull, overriding the minimum specification. d specifies that the datatype of the variable to be printed is + an integer. ‘The number is written right-ustfed in the given fleld width. Leading blank space will appear _asnecessary. The following examples ilustrate the output of the number 1256 under different formats. ‘The minus sign in the control string “%-6d" prints the number lef-ustiied. The control string “MO6d" ‘Prints zero before the number (if the number of digits is less than the specified field width). The minus (9) 2nd zero (0) are known as flags. ‘Long integers may be printed by specifying Id in the place of din the format specification. Short integers ‘may be printed by specifying hd in the place of d inthe format specification. ‘Program to illustrate the output of integer numbers under various formats. Scanned with CamScanner ‘OUTPUT OF REAL NUMBERS: The output of a real number may be displayed in decimal notation using the following specification: pf The integer w indicates the minimum number of positions that are to be used for the display the value "and the integer p indicates the number of digits to be displayed after the decimal point (precision). The value when displayed is rounded to p decimal places and printed right justified in the field of w columns. blank spaces and zeros will appear as necessary. The default precision is 6 decimal places. The ‘Negative numbers will be printed with the minus sign. The number will-be displayed in the form -98.456. ‘We can also display a real number in exponential notation by the specification: wpe width w should satisfy the condition w > p+7. The value will be rounded off and printed right-justfied in the field if w columns. Using flag 0 before the field width specifier w we have zeros before digits and by using the flag - we have the numbers _leftjustfied. The following table gives output for different format strings if variable y= 98.7654 4 special field specification character that lets the user define the field following form: printf{"¥*.°f7 width, precision, number); P *f, 7, 2, number); is equivalent to printf{"%7.2", number); The advantage ofthis format is thatthe values for with and precsion may be elven during running the “program, thus making the format a dynamic one. PRINTING A SINGLE CHARACTER Asingle character can be displayed in a desired position using the format: we fl The character will be displayed right-justfied in the field of w columns. We can make the display left justified by placing a minus sign before the integer w. The default value for wis 1. PRINTING OF STRINGS ‘The format specification for outputting strings is similar to that of real numbers. itis ofthe form Kwips where w specifies the field width for display and p instructs that only the fist p characters of the string are to be displayed. The display is right justified. ‘The following table gives the variety of specifications in printing a string ‘NEW DELHI 110001 containing 16 characters (including blanks) ‘SPECIFICATION T ‘OUTPUT xs" Cd EE =2057 lee TH] |a]1folojoja Niel] [olelepale (MIXED DATA OUTPUT i It Is permitted to mix data types in one printf statement. For example, the statement of the type Prints {"%d %f %s %c", 0, b, c,d); valid. Printf uses its control string to decide how many variables to bbe printed and what their data types are. The format specifications should match the variables in ‘number, order and type. If there are not enough variables or if they are of the wrong type, the output results will be incorrect. Commonly used printf format codes Masai Code He Print a single character eet T er oe ele ied urerc ian ‘Causes leading zer0s to appear # (with oor x) _| Causes octal and hex items to be preceded by O and Ox, respectively Causes @ decimal point to be present in all loating point numbers, even if ‘tis whole number. Also prevents the truncation of trailing zeros in g-type conversion. [ENHANCING THE READABILITY OF OUTPUT Computer outputs are useful for various calculations and for making decisions. Therefore clarity of coututs are of utmost importance, to improve the dary, eadabilty and understn{ pity of outputs ‘we can write the printf statements in following form. 1. Provide enough blank space between two numbers. 2. Introduce appropriate headings and variable names inthe output. 3._ Print special messages whenever a peculiar condition occurs in the output. 4, Introduce blank lines between the important sections of the output. ‘The system usually provides two blank spaces between the numbers. But if we use “\t’ tab character we ‘get 4 blank space between two numbers and if we use “\n’ next line character we get the second number ‘In C program the set of statements will be executed from first to last line in order which they appear, In ‘Some situations we need to change the order by checking certain conditions or in some cases we need 10 repeat the group of statements until certain conditions are met. This involves a kind of decision ‘making to see whether a particular condition has occurred or not and then direct the computer Scanned with CamScanner nt is @ powerful decision-making statement and is used to control the flow of execution of {two-way decision statement and is used in conjunction with an expression. “The test ‘expression is either relational expression or conditional expression whose value connie ‘zero (false). eo Some examples are if(code==1) Person = male | Alege >55) Person = retired | | ‘hei atemens yb rete ner forms uch 1. simple if statement i 2. favelsestatement 3. Nested if. else statement 4. Else ifladder ‘SIMPLE IF STATEMENT: The genera form of simple lf statement i ck may be sole cae Oe el sine tia tn gk o.oo oe ee oo ‘The program tests the type of category of the student. if the student belongs to sports category, then he gets a additional bonus_marks to his marks before they are printed. For others bonus_marks are not added. Another example for simple if statement int a,b, ¢ d; float ratio; rintf(“enter four integer values\n"); scanf{"Sd 56d 56d Xa, Bo, Bb, Bc, Bd); if(e-d t=0) { ratio = (float) (a+b) / (float) (e-d); printf “ratio = f\n" ratio); } } output Astrun enter four integer values 12 23 34 45 ratio = -3,181818 In first run of the above program e-d is not equal to zero therefore It gives the result ratio. But during the second run of the program e-d is equal to zero therefore the statement bock of if statement i skipped and the program stops without producing any output. Note that here we used float conversion to evaluate ratio. This Is necessary to avoid truncation due to imeger division, 1. ELSE STATEMENT: Theif ele statements an extension ofthe simple if statement, The general frm is | Scanned with CamScanner false-block statements t } else t } statement-x; I the test expression is true then the true-block statements are executed otherwise the false-block statements are executed. In either case either true-black or false-black will be executed not both. Then ‘the controls transferred subsequently to the statement-x. The flow-chartis given below Consider the example of counting the number of boys and girs In a class. We use code 1 for boy and ode 2 for girl, The program to count number of boys and gris using If. else statement is given below. if (code == 1) boy = boy +1; else ‘lel = gle +1; statement-x; | Here if the code is equal to 1, the statement boy = boy + 1; is executed and the control is transferred to. BS the statement-x, after skipping else par. Ifthe code isnot equal tothe statement gil = gil +115 | executed and control reaches the statement x Scanned with CamScanner ‘Another program to find the ratio between (a+b) and (c~d) where a, b, ¢, d are integers. The ratio Is. calculated only if (cd) is not equal to zero. e-ana { ratio = (Nat) (a+b) / (oat) (¢ ~d); f print{("ratio = Nf\n’, ratio); [NESTING OF IF ELSE STATEMENTS when 2 series of decisions are involved, we may have to use more than one if. else statement in nested form and its general format is, W (test condition — 1) ‘ (test condition - 2) t Statement block = 1; frst test canadien ~ 3 9 evehasted. 4 4 w nue test condition = 2 bs eyaluated and if ffs ako true then Maemert Ud ~ 1. evalonted H Lei conbeon ~ 154 Use but test sondition ~ 2 false then statement Dlocd = 3 evahuated M test conticn 1 tale Matar thor’ ~ 3 is evaluated. In either cave the ‘tarot traatones to the tatesueit 6 The Mow chasis goa bans Scanned with CamScanner In a commercial bank, an incentive policy of giving bonus to all its deposit holders. For female depo: holders with balance greater than S000, $% of balance Is added to the original balance as bonus a nd ‘other deposit holders will get 2% of balance is added to the original balance as bonus. if (balance > 5000) bbonus = 0.05 * balance; else ‘bonus = 0.02 * balance; THe ese F LADDER There is another way of puting If together when multpath decslons are involved. The es If ladder consis ofa chain of isin which the statement associated with each ele an Is general form s Weondlion 1) ‘Statement - Else if (condition 2) Statement-2; i Else if (condition 3) ‘Statement-3; Else if (condition n) Statement; Scanned with CamScanner Else Default-statement; Statementx; This construct is known as the elseif ladder. The conditions are evaluated from the firs fof the ladder, downwards. As soon as true condition is found the statement associated with it is executed and the ‘control Is transferred to statement-x (skipping the rest of the ladder). When all the n conditions become false then the final else containing the default-statement will be executed. Consider the example of grading the students according to the range of marks. Average Grade marks 80 to 100 Distinction 601079 First class 50 to 59 Second Less than 49 | class ‘Third class Program to grade the students using else if ladder is given below it (marks > 79) grade = “distinction”; else if (marks > 59) grade = “first class”; else if (marks > 49) grade = “second class"; “else grade = “third class”; Printt(“%s\n", grade); ‘The flow chart for else if ladder is given below in an academic institution, The grading is done Scanned with CamScanner Le aes RULES FOR INDENTATION ‘When using control structures, a statement often controls many ather statoments that foiow it. In such situations it Is good practice to use proper indentation (alignment) to understand the rogram coatly, 1. Indent statements that are dependant on the previous statements; provide at least three spaces of indentation, ‘Aga vertically else clauso with ther matching if clause. Ute braces on separate Ines to entity a block of statoments, {edent the statements in the tock by atleast three spaces 10 the right ofthe braces, ‘Alga the opening and closing braces. Use appropiate comments 1a signify tba beginning and ond of blocks, lncent the nested statements ag per the above rules. Code only one dauso or statement on each time. puppaeD et Santon startet \Wimen cre of many shernates i 1 be selected, we ean ute ani satement ower the tomolen contol the seleton, ft ich a program increas dramatically when the number of aernatwes ‘4 grogra tcomes tet 1 te4d and follow Same tel may conhane te parson ene ewer & tertantety C has» battin matomey dein rent now 484 sted. The stn Metemert Wes th oan Wf the exgtensn oF vate, when match W four 4 Bch Of satementn, Scanned with CamScanner ‘The expression is an integer expression or characters. Value-1, value-2, .. are constant expressions or constants (integral constant) and are known as case labels. Each of these values should be unique within 2 switch statement. Block, block-2, .. are statement lists and may contain zero or more statements. ‘There is no need to put braces around these blocks. The case labels must end with a colon (). When switch statement is executed, the value of the expression is successfully compared against the valves value-t, value-2, .. if 2 mstch i found then the block of statements that follows the case are: ‘executed. The break statement at the end of each block signals the end of a particular case and causes ‘an ext from the switch statement and transfers the contro! to the statement-x following the switch. ‘The default is an optional case, when present it will be executed if the value of the expression does not ‘match with any of the case values. If not present, no action takes place when no match found between ‘expression and case values. And the control goes to the statement-x. ANSI C permits the use of as many '28 257 case labels. The flow chart of switch statement is as follows: Scanned with CamScanner ‘The switch statement can be used to grade the students as given below Average marks | Grade. ] 800 100 Distinction b 601079 Fret lass 50 to 59 Second dass Less than 49 “Third dase Scanned with CamScanner grade = “third class"; break; } rint{(“grode = %s\n", grade); f "Note that we have used conversion statement avg = marks / 10; where avg is defined as an integer. The. fi variable avg takes the following integer values 1,2, .. 10, Here the first two cases uses empty block which ‘means it will execute the statement grade = “ distinction”; which Is corresponding to case 8. Same way f ‘cases 6 and 7. Also cases 0,1,2,3,4 executes the statement grade = “third class’ [RULES FOR SWITCH STATEMENT © THESWITCH expression must be an integral type. Case labels must be constants or constant expressions. Case labels must be unique. No two labels can have the same value. f Case labels must end with semicolon, f ‘The break statement transfers the control out ofthe switch statement. ‘The break statement is optional. That is two or more case labels may belong to the same statements. ‘+ The defautt label is optional. f present it will be executed when the expression does not find @ matching case label, ‘+ There can be at most one default label, The default may be placed anywhere but usvally placed atthe end, ‘© is permined to nest switeh statements, ‘THE CONOMONAL OPERATOR(? : ) The € language has an usual operator useful for making two-way decisions. This operator is a ‘combination of ? and : and takes three operands. This operator is popularly known asthe conditional ‘operator. The general form of conditional operator is 2s fllows: Conditional expression ?expressiont :expresiion2; ‘The conditonal exprevtion evaluated Rat. W the result fs nonzero (rue, expression! fs evaluated 20d this value the value of the conditional expression, Otherwite expression? is evaluated and its value isthe value of the conditional expression, For example flog = (1 <0)? Inthis evample d= then fag = 4 Scanned with CamScanner Ifx=-8 then flag =o, ‘Another example of conditional operator for the equation 15x+3forxs22x+$ forx>2] y= (x>2)2[2*x+5):(15%x 43); ‘Another example Is to calculate the weekly salary of the employee by the formula salary = (4x +100 for x<40300 for x=4045r+150 for x>40} where x is the number of products sold by the employee. Salary = (x t= 40) ? ((x < 40) ? (4 * x + 100) : (4.5 * x + 150}} : 300; ‘THE GOTO STATEMENT Uke many other languages C supports the goto statement to branch unconditionally from one point to another in the program. The goto requires a /abel in order to identify the place where the branch \s tobe made. A Jabel is any valid variable name and must be followed by a colon, The label is placed immediately before the statement where the control is to be transferred. The general format of goto and label statements are as given below. goto label; The label can be anywhere in the program either before or after the goto label; statement. During the execution of the program when 2 statement like goto begin; is met the flow of control will jump to the statement immediately following the fabel begin: . This happens unconditionally. The goto statement breaks the normal sequential execution of the program, if the labef is before the statement goto label; a loop willbe formed and some statements will be executed repeatedly. Such a jump Is known as a backward jump. If the label: is placed after the goto label; it skips some of the statements and jumps to the statement next to fabel: This jump Is known as forward jump. Goto is often used at the end of the program to direct the control to the input statement to read further | data, Consider the example Scanned with CamScanner ‘main() f double x,y; read: soanf(*%f", &x); if (x >0) y= sqrttx); print{(“number = %f its squareroot is %f\n", &x,&y); goto read; else print{{"The squareroot of this number is imaginery”}; } This program evaluates the square root of a series of numbers read from the terminal, The program uses. goto statement after printing the square raot and the control again goes to read label and gets a new number using scanf statement. If the number given Is less than zero It prints “ The squareroot of this number Is Imaginery”. Thus goto statement transfers control to any part of the program. Scanned with CamScanner

You might also like