0% found this document useful (0 votes)
5 views15 pages

Unit 2

Bsc cs 1st sem
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)
5 views15 pages

Unit 2

Bsc cs 1st sem
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/ 15
languages C language does not have any built-in input-output wo) Unlike other programming \ stements 05 & of its syntax. wr 0 and mers ‘There are several other functions, which are also used for I/O operations in C. These function calls are collectively called as Standard 1/O library. In this chapter, we shall deal with the common V/O functions that are widely used, . All 1/0 operations are carried out through function calls such as 3.1 Input data ‘The input data has to be arranged in a particular format. ‘The input data may: contain a mixed mode data, such as 101.75 225 R ; The above line contains three pieces of data arranged ina particular format, The first part of this data is read as ‘float’, the second part as ‘int’ and the third part as ‘char’. To make this possible, we will be using a function. called scanf () - 3.4 Output operations This the wish of any programmer to get the output results in a most understandable form. Hence ‘any output format has to be user friendly. \ ‘The output format will be similar to the input one and printf function is used for this purpose, calling it so is that it has rich e branched as Conditional ments it has if and switch. and do-while. Cis considered as a structured language, and one of the reasons for 1 statements. The control statements can bi and varied program contro: and Unconditional control Statements. Under conditional control state! The Unconditional statement is goto. The loop constructs are while, for, The control statements are widely used to support decision-making processes. They largely rely upon a conditional test that determines the decision. 4.1 IF statement . This is the most powerful conditional control statement. The if statement can be used in different forms, depending upon the nature of the conditional test, and the main forms are: + Simpleif + Blockif + Nested if ‘We shall discuss different “if” constructs in the following sections. 4.2. Simple if statement The general form of simple if statement is + ifftest expression) | | : | {e.g.) : : if («> y) | * prinif(* x is greater than y \n"); i if soles >1000 && sales <= 2000 ) d first. Mit Tetums truc then the statement followed by it ntro eae to the next statement. 42. © Programming inc Calculate the sales commission for the data given below: Sales value(Rs) Less than 1000 /= Above 1000 but below 2000 Above 2000 but below $000 Above 5000 Solution First let us solve it by using simple if ‘construct, Commission % No commission 5% of sales 8% of sakes 10% of sales /* Example Program ~ Using’ simple if construct W include vold main() { float sales, com; Printf(*Enter sales value \n’); scant("%F*,&sales); U(sales <= 1000) coma; if ( soles > 1000 ag soles <= com = soles * 0.05; 2000) If (sales > 2000 && soles <=5000) com = sales * 0.08; i¥ (ales > 5000) com = gales * 0,10; ‘} Output Enter sales value 1000 Commission Rs 0.00 Enter sales value 2500 Commission Rs 200,09 Expla nation Here, the sales ig Biven as {s 200, and ifthe sates ae in the float variable com: Ad its etored fn the vag st es le com: a5 10% of len? Analy if theo Printf(*\n Commission Re 7.26", ‘nd ifthe sales ia Hes between 109] St Fintan oF equal les scOm); and 5000, then 896 of sates is caleulst? exceeds 5000 then the commniasion ¥ | | Control Statements © 4.3 4.3 simple if-else statement Here an optional clause ‘else’ is used along with the simple if statement. The general form is if(test_ expression) stotement; else statement; (e.9.) if (total >= 250 ) prinif(* result is pass \n"): else printf(* result is foil \n"); her the given number is odd or even we use “simple-else-if” For example to check whetl onstruct. The complete program is as follows. /* Program to check odd or even */ #include void moin() { int no,m; print ("Enter number to check : “); seant(*%d" ,&n0); m=no%2; if(m==1) print{(’\n Given number is odd”); else print{(*\n Given number is even"); } Output Enter number to check : 6 Given number is even Enter number to check : 10 Given number is even ee program by using miodulo operator the remainder value is find out for the given Testa na based on that value, program displays whether it is ‘odd or even. This construct is efull when the else part is having only one statement. ae Block if statement it a a block or a group of statements follows the test expression. The general form is ~ifftest expression) staiements; 4.7 Looping Chas powerful looping constructs in it, and this is one form of control statements where we tready know the number of repetitions. In C there are three looping constructs. They are for, yhile and do-while. Let us discuss in the following sections, the looping form of control statements. Please do member conditional control statements. 4.8 © Programming in C 4.8 For loop , The general form of a for loop is, for {expression 1; expression 2 ; expréssion 3) « { } sequence of statements ; here expression | is the initial value expression 2 is the testing value expression 3 is the increment(step) value e.g.) for (i=0;i<=100; i++) sum +=; It may be observed that the following steps are involved, namely: 1. Initialisation 2. Condition checking 3. Body of the loop 4, Increment 5. (again) Conditional Pleasé note that there is no semicolon after for loop; if there is a semicolon after the for loop then the loop is said to be a ‘time delay loop’ or ‘software delay ‘ and the construct is given below. for(i=0;i<100;+ +i) ; Also by using the comma operator, more than one variable can be initialised as seen below. B . for{ fact=i=1; i<10; i++) fact *= i; Here, both fact and i are variables that are initialised to 1. Similarly we can have two action statements as third part of the for loop; one is to calculate the ‘fact’ value and the other is used to increment the ‘i’ value. The code snippet for the above one is given below forlfact=i=1; i <=5; fact*=i, i++); Without the comma operator, the same will be seen as, foct =1; ~ : forli=1;i<10;++i) fact * = j; Thus, the coding got teduced by using the comma operator, Insteail of initialising the value inside the for loop, then the construct is ifwe have the option to initialise it before, Control Statements @ 4.9 already defined outside for foct* =i . Bere, the first semicolon in for loop reveals that the initial value is simarly we can also i amet the index, inside for Loop. Hr Such cases there is noneed for Tre expression that is used to increment the values within the for loop construct, and the resultant code isas follows: fact =i=1; for (i i<=5;) fact* =H; itt: } | ; Here, the index value gets incremented inside the for loop as said before. Consider the last form of for” construct in which the initial value, final value and also increment value are not given for (i 73 statements; } : ; : The above for loop executes infinitely, and the only way to exit the for loop 1 by using the vchas goto) inside the for loop. abnormal exit (sus ping using while led loop statement i.e. the test condition is evaluate .s repeated until the test condition ral form of ‘while’ is: 4.9 Loo! ed and if itis true the becomes false; then “While” isan entry controll: body of the loop is evaluated. This process i the control is transferred out of ‘the loop. The gene! while ( test expression ) { sequence of statements; } In flow chart form statements pee ee eee ee ato Progremming in e following while loop helps us to sum the numbers between land 100 The fol sum = 0; i=l; while (i <=100) { ; sum+ =i itt; ! i gets initiali i é loop. Now, the test 7 variables sum and i gets initialised before entering the loop. Now, expression 7 ae it returns true then the statements within braces will execute, Note that i gets eeaeiel inside the loop, ifit is missing then the loop is infinite one since the variable ialways Jess than 100. se Consider the following while-loop construct in which the loop is executed infinitely while. (1} { statements ; } Again where want to exit from such a loop, we have to use some unconditional statement, andthe above formis similar to the for loop where we have all the three expressions missing. Also, note that in C other than 0 all numbers are considered as positive. 4.10Looping using do-while “do-while” is an exit controlled loop statement i.e. condition is tested only after executing a loop. Onsome occasions, itmay be necessary to execute the body of the loop, before the testis performed. Such‘occasion can be handled using do-while. The general form is: : * do { sequence of statements; } while ( test expression ); Tn flow chart form [stotements] Control Statements © 4.14 “The following do-while constructs o find the sum of odd mumbers that ae lying between 1 and 100, sum = 0; i isl; do ecuted first and then, the test condition is evaluated. even if the test expression returns false. This is jo-while construct. Here the statements within the ‘braces are ex Thus the statements are executed at least once, the fundamental difference between while and d 4.11 Comparative study of the I Itis upto the programmer's choice to choose the type of the loop. But before choosing the particular type, the following points should be considered. If the loop is simple one, we can use “for” loop control and itis very useful in Arrays. If we want fo execute the Joop atleast once even though the condition is false then definitely we have to use ‘do-while’ loop structure. If the statements are ased on certain condition before being executed then ‘while’ loop ‘structure is preferred. 4.12 Break statement ‘An early exit from the loop is possible by a ‘break’ encountered, the loop is immediately exited and the program continues with the following the loop. The general form is, while ( test expression } joop statement! When a ‘break’ statement is .e statement immediately { } ‘To illustrate the above statement let us consider an example program. In this case we want toadd only positive integers and neglecting negative values. And when negative numbers are keyed, the loop should terminate by using break statement and print the sum of all the entered positive integer values. /* Example program to illustrate break */ #include void main() if something break; int no,sum=0; prinif("\n Enter no and negative no to exit \n”); while (1) scani{?%d",8n0)}; if (no <0) break; 4.12 @ Programming in C Output Enter no and negative no to exit 5 6 8 2 The sum is 19 Here break will terminate the loop when the entered number is less than 0 and print the value of sum. Thus the break statement will cause program execution to continue after enclosing for, while, do or switch statement. 4.13 Continue statement Unlike break statement, which causes the loop to be terminated, the ‘continue’ causes the loop to be continued with the next iteration after skipping the statements in between, thus by passing the rest of the loop: The general form is: for ( expression T ; expression 2 ; expression 3) if something continue; } The following program segment will illustrate the use of continue statement. Consider the programming situation where we are going to give 5 numbers, and the program has to add only positive numbers thus neglecting the negative number. /* Example program to illustrate “continue” */ #include void main() { int i,no,sum=0; printf(“ \n Enter 5 numbers \n"); for(i=0;i<5;i+ +) { scanf("%d",&no); if (no < 0 ) continue;. else ‘ sum+=no; Conch travemerts © 4.13 Output Enter § numbers 4 $ 4 al ¥. Sum of positive numbers 15 Here, the statement “continue” will by-pass all the negative numbers from summning up. The example program reveals that, continue statement will result in the next iteration of the enclosing do, while, or for loop to execute, 4.15 Switch statement This isa multiple branching control statement, and this one is very useful for decision making Whey more than one case is involved. The general form of the switch statement is switch (expression) “ case label 1 : statement sequence; break; case label 2 statement sequence; 7 break; . case label 3 statement sequence; breok; default statement sequence; } ‘Switch statement differs from an ‘if’ statement in the way that ‘switch’ can only test for equality whereas ‘if’ can evaluate for entire given range. ‘When the switch statement is executed, the value of expression is compared against the label 1, label 2, label 3 etc. If a case is found whose value matches with the expression, then the Sequence of statements that follows the case is executed. The ‘break’ statement at the end of each block indicates the end of the particular case and Causes an exit from ‘switch’ statement, thus transferring the control outside switch statement. The ‘default’ statement is.executed if no matches are found and it is optional. (€.g.) Rewrite the following program using ‘switch’ statement if (score >= 90) grade ='q'; else if (score >= 80 ) grade = ‘b’; e grade = ‘e; Control Statements © 4.15 solution ve can use 2 conversion statement sc = — : ie ore = score /10. The score is an integer and it takes Marks index 100 10 90-99 2 80-89 8 70-79 7 The program will look like /* Example program using switch construct Wh #include void moin() { int marks,index,score ; printf(*Enter your score“); sconi(*%d",&score); score = score /10; switch (score) case 10 : index = 10; break; cose9 : index = 9; break ; cose 8 =: index = 87 break; case 7: index =.7; y print” \n Your index value is %d index); } Output Enter your score 75 Your index value is 7 Enter your score 100 Your index value is 10 re Goto statement isto aa unconditional statement available in C. Our main aim in the structured programming eee goto, which may lead to confusion. But, goto statement may be used to exi layers of nesting. The general form of goto statement is goto label; here, label is . label is an alphanumeric one. 4.16 @ Programming in C /* Example - goto s: #include id main() { int x; printf(“\n. Enter number : “); scanf("%d",&x}; if (x> 100) goto err; printf(“\a Valid input *); exit{0); err: printf(“\n Invalid. input’); } Output Enter number : 56 ‘Valid input Enter number : 123 Invalid input The use of ‘gots’ is not encouraged since more numb er of ‘goto’ means more confusion

You might also like