0% found this document useful (0 votes)
25 views

module32

One C Program 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)
25 views

module32

One C Program 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/ 17
UNIT IIL ‘umber of times, this can be done using looping stat itements like while, do and for statements. In looping a sequence of statements are execut ioe then directs the repeated execution of the statements contained in the body of the loop. Depending on the position of the control statement in the loop, a control structure may be classified either a5 the entry-controlied oop or as the exit controlled loop. The entry-controlled loop and exit-controlled loops are also known as pre-test and post-test loops respectively. Re See ‘The test conditions should be carefully stated in order to perform the desired number of loop executions. It is assumed that the test condition will eventually transfer the control out of the loop. ‘Sometimes the control sets up an infinite loop and the body is executed over and over again. Allooping process in general would include the following four steps: 1. Setting and initialization of a condition variable. 2. Execution of the statements in the loop. 3. Test for a specified value of the condition variable for execution of the loop. 4. incrementing or updating the condition variable. C provides three loop operations such as 1. The while statement Scanned with CamScanner 2. The do statement } 3. The for statement, ‘THE WHILE STATEMENT f | j while (test condition) | body of the loop loop. j ‘true, then the body of the loop is ‘statement. The test-condition i evaluated and ifthe condition le ‘agaln evaluated and If it is true, th } axecuted. After execution of the body, the testcondition Is once 1 body Is executed once again. Ths process of repeated execution ot The body of the loop may have on '€ OF more statements. The braces are n ‘contains two or more statements. weeded only if the body However, it ls a good practice to use braces even ifthe body hes ‘only one statement. Example program 1 nea; ) while (<= 10) sum = sum+n*n; \ nana; ) i Brlntf(“sum = Sl\n", sum); { ‘The body of the loop is executed 10 times for n = 1,2, 10 each ime adding the square of he value i ‘fn, which Is incremented Inside the loop. The test condition may also be written as n< 11; the result i ‘would be the same. This is a typical example of counter-controlied loops. The variable nis called iy ‘counter or control variable. . iy ‘Another example of while statement which uses the keyboard input is shown below 4 Scanned with CamScanner while ( character I= ‘y') character = getchar{ ); 0000, First the character is initialized to ‘. The while statement then begins by testing whether character is ‘not equal toy, since the character was initialized to “’, the test Is true and the loop statement character = getchar (}; Is executed. Each time a letter Is keyed in, the tests carried out and the loop statement executed until the letter y is pressed. When y is pressed, the condition becomes false because character equals y and the loop terminates thus transferring the control to the statement so000x;. This is a typical example of sentinel-controlled loops. ‘THE DO STATEMENT; ‘The while loop tests the condition before the loop Is executed. But in some occasions itis necessary to execute the body of the loop before the test is performed. Such situations can be handled with the help of the do statement. The general form Is do, t body of the loop } While (test-condition); On seeing the do statement, the program proceeds to evaluate the body of the loop fist. Then the test condition near while statement is evaluated. If the condition Is true, the program continues to | evaluate the body of the loop once again. This process continues as long as the condition is true. i ‘When the condition becomes false, the loop will be terminated and the control goes to the statement } that appears immediately after the while statement. The do... while statement is a exit-controlled { loop. For example ao t Print{("Input a number\n"); ‘number = getnum{ }; , while (number > 0); t Scanned with CamScanner ‘This segment of 2 program reads a number from the keyboard until a zero or a negative number is ‘keyed in and assigned to the sentinel variable number. The test conditions may have compound relations as well. For Instance the statement while (number > 0 && number < 100); the loop will be ‘executed as jong as the number keyed in lies between 0 and 100. THE FOR STATEMENT: Simple ‘for’ loops The for loop is another entry-controlled loop that provides a more concise loop control structure. The general format of for loop is {for (Initialization ; test-condition ; increment ) { body of the loop. } ‘The execution of the for statement is as follows: 1 Initialization of the control variable is done first, using assignment statements such as I= 1. and count = 0. The varlables | and count are known as loop-control variables. 2. The value of the control variable Is tested using the test-condition. The test-condition Is a relational expression, such as |< 10 that determines when the loop will exit. For example: for(n=, m=50;n<=mjn=n+i,m=m-—1) t pam/n; prints %6d d\n’ n,m, Ble 3 \s perfectly valid. The multiple arguments in the increment section are separated by commas. The ‘third feature is that the test-condition may have any compound relation and the testing need not be limited only to the loop control variable. NESTING OF for LOOPS "Nesting of loops, that is one for statement within another for statement, fs allowed in C. for example, ‘two loops can be nested as follows: Scanned with CamScanner ree ots “0 fon (¥ = 15 1 < 10; +64) ———_+_ { t igue outer Va6p. if ‘The nesting may continue up to any desired level. The loops should be properly indented so as to ‘enable the reader to easily determine which statements as contained within each for statement. For example Tow <= ROWMAX ; +#row) for (column:=.1; column <= COLMAX 4° ++column) {. : y = row * column; co “printf ("s4d", y); © printf (*\n' : as } { JUMPS IN LOOPS, Loops pertorm a set of operations repeatedly until the control variable fails to satisty the test-condition. The number of times a loop Is repeated Is decided in advance and tha test condition Is written to achleve this. Sometimes, when executing a loo, it becomes desirable to skip a part of the Joop or to leave the loop as soon as a certain condition occurs. C permits a jump fram one statement to another within a loop as well as a jump out of a loop. JUMPING OUT OF A LOOP Scanned with CamScanner TEAMS LOMA LETT q i ‘As early exit from a loop can be accomplished by using the break statement or the goto statement. ‘These statements can also be used within while, do or for loops. For example UNIT I DECISION MAKING AND LOOPING In decision making statements like if statement, switch, goto statements branches the control to ‘another statement by the result of the relational expression associated with the decision making statements. In some occasions the same set of statements needs to be executed repeatedly for certain ‘number of times, this can be done using looping statements like while, do ond for statements. i In looping a sequence of statements are executed until some conditions for termination of the loop are satisfied. A program loop therefore consists of two segments, one known as the body of the loop and the other known as the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. Depending on the position of the control statement in the loop, a control structure may be classified either as the entry-controlled loop or as the exit controlled loop. The entry-controlled loop and exit-controlled loops are also known as pre-test and post-test loops respectively. The test conditions should be carefully stated In order to perform the desired number of loop ‘executions. It Is assumed that the test condition will eventually transfer the control out of the loop. ‘Sometimes the control sets up an Infinite loop and the body Is executed over and over again. A looping process in general would include the following four steps: 1. Sting andinitazation of codon valle : 2. Execution ofthe statements Inthe oop. A 2. Tertforaspecfed vate ofthe cononvalbefor xeon of he lop ff 4. tncrementng or updating the condton varie Scanned with CamScanner C provides three loop operations such as 1. The while statement 2. The do statement 3. The for statement. ‘THE WHILE STATEMENT ‘The simplest of all the looping structures in Cis the while statement. The general format of the while statement is while (test condition) { body of the loop a , ‘The while Is an entry controlled loop statement. The test-condition Is evaluated and If the condition Is ‘true, then the body of the loop Is executed. After execution of the body, the test-condition is once ‘again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test-condition finally becomes false and the control is transferred out of ‘the loop. On exit, the program continues with the statement immediately after the body of the loop. ‘The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements. However, it is a good practice ta use braces even if the body has ‘only one statement. Example program while (11<= 10) f t sum = sum+n*n; nent; a) f print{(“sum = %d\n", sum); f ‘The body of the loop is executed 20 times for n = 1,2, .., 10 each time adding the square of the value Cf n, which is incremented Inside the loop. The test condition may also be written asin < 14; the result ‘would be the same. This Is a typical example of counter-controlled loops. The variable n is called } counter or control variable. Another example of while statement whlch uses the keyboard Input is shown Scanned with CamScanner First the character is initialized to “™ The while statement then begins by testing whether character is not equal to y. since the character was initialized to the testis true and the loop statement character = getchor {); is executed. Each time a letter is keyed In, the test is carried out and the loop statement executed until the letter y Is pressed. When y Is pressed, the condition becomes false because character equals y and the loop terminates thus transferring the control to the statement 200006. This Is a typical example of sentinel-controlled loops. ‘THE DO STATEMENT: ‘The while loop tests the condition before the loop is executed. But in some occasions it is necessary to ‘execute the body of the loop hefore the test is performed. Such situations can be handled with the help of the do statement. The general form is do t A body of the loop while (test-condition); ‘On seeing the do statement, the program proceeds to evaluate the body of the loop first. Then the test condition near while statement is evaluated. If the condition Is true, the program continues to ‘evaluate the body of the loop once a . Ths process continues as long as the condition Is true. ‘When the condition becomes false, the loop will be terminated and the control goes to the statement ‘that appears immediately after the while statement. The do ... while statement Is a exit-controlled oop. For example ‘do t rint{("input a number\n"}; ‘umber = getnum( }; , while (number > 0); Scanned with CamScanner ‘This segment of a program reads a number from the keyboard until a zero or a negative number Is ‘keyed In and assigned to the sentinel variable number. The test conditions may have compound ‘relations as well. For instance the statement — while (number > 0 && number < 100); the loop will be ‘executed as long as the number keyed in lies between 0 and 100. ‘THE FOR STATEMENT: Simple ‘for’ loops ‘The for loop is another entry-controlled loop that provides a more concise loop control structure. The general format of for loop is. for {initialization ; test-condition ; Increment ) t body ofthe loop } ‘The execution of the for statement is as follows: ‘1. Initialization of the control variable Is done first, using assignment statements such as = 1.and count = 0. The variables | and count are known as loop-control variables. 2, The value of the control variable is tested using the rel test-condition. The test-condition is a lational expression, such as |< 10 that determines when the loop will exit, For example: for(n=4, m=50;n<=mn=nvi,m=m-4) C p=m/n; Drint{("%d 9d d\n", n, m, p): b \s perfectly valid. The multiple arguments in the increment section are separated by commas. The ‘third feature Is that the test-condition may have any compound relation and the testing need not be limited only to the loop control variable. NESTING OF for Loops. "Nesting of loops, that is one for statement within another for sta two loops can be nested as follows: tement, is allowed In C. for example, Scanned with CamScanner Alp eee fo (sae ea ) Outer oop The nesting may continue up to any desired level. The loops should be properly indented so as to ‘enable the reader to easily determine which statements as contained within each for statement. For wample for (row = { for (column'= 15" colunn <= COLMAX +’ ++column) 5. ; "oy = row eblumns ©!» © co printé "4d", y); SUMS IN LOOPS, Loops perform a set of operations repeatedly until the control variable falls to satisfy the test-condition. The number of times loop Is repeated Is decided In advance and the test condition is Umrisien to achleve ths, Sometimes, whan executing a loop it becomes desirable to skip a part af the {009 oF te leave the oop as soon a8 a certain condition occurs, C permits a ump rom one statement to another within a loop as well as» jump out of a laop. JUMPING OUT OF A LOOP The Break Statement: '* Clanguage permits a jump from one statement to another within a loop as well as to jump out of the loop. The break statement allows us to accomplish this task. Abreak statement provides an early exit from for, while, do and switch constructs. '* break causes the innermost enclosing loop or switch to be exite Example program to illustrate the use of break statement. /* A program to find the average of the marks*/ include < stdio.h > //include the stdio.h file to your program void main() // Start of the program| { int, num: );//dectare the variables and initialize float sum=0,average; //declare the variables and initialize printf{“input the marks, -1 to end\n"); // Message to the user while(1) // While loop starts { scanf"%d", 8); // read and store the input number )// check whether input number is-1 number -1 is input skip the loop sum=I; /Jelse add the value of Ito sum num#+ // increment num value by 1 }Jend of the program During loop operations it may be necessary to skipa part of the body of the loop under certain conditions. Like the break statement C supports similar statement called continue statement. The continue statement causes the loop to be continued with the next iteration after skipping any statement in between. The continue with the next iteration the format of the continue statement is simply: Continue; Consider the following program that finds the sum of five positive integers. If a negative number is entered, the sum is not performed since the remaining part of the loop is skipped using continue statement. include //include stdio.h file void main() //start of the program Scanned with CamScanner During loop operations it may be necessary to skip a part of the body of the loop under certain conditions. Like the break statement C supports similar statement called continue statement. The continue statement causes the loop to be continued wit in between. The continue with the next iteration the for ith the next iteration after skipping any statement Continue; rmat of the continue statement is simply: Consider the following program that finds the sum of five positive integers. If a negative number is entered, the sum is not performed since the remaining part of the loop is skipped using continue statement. #include //Include stdio.h file ) /Istart of the program { int =1, num, sum=0; // declare and for { printi(“Enter the integer”); //Message to the user scanf(“%41", &num); //read and store the number if{num < 0} //check whether the number is less than zero { printf(“You have entered a negative number"); // message to the user continue; // starts with the beginning of the loop. Mend of for loop sum+=num; // add and store sum to num ) printi(“The sum of positive numbers entered » 9éd";sum);// print thte sur. Vl end af the nenacarn Scanned with CamScanner scanf("%I”, &num); //read and store the number if(num < 0) //check whether the number is less than zero { printf("You have entered a negative number”); // message to the user continue; // starts with the beginning of the loop 1 end of for loop sum+=num; // add and store sum to num } Printf("The sum of positive numbers entered = 9%d",sum); // print thte sum. Vl end of the program. ee Conditional Operathr The conditional operator, often referred to as the "ternary operator" allows you to perform a conditional operation in a concise way. I's the only ternary operator in C and takes three operands: a condition, a value to return if the condition is true, and a value to return ifthe conditionis false. Syntax: ' is a special operator in C that condition ? value_i true : value_i false; Explanation: ‘+ condition: This is the expre: otherwise, it returns value_i ion to be evaluated. If itis true, the operator returns value_j false. value_if_true: This is the value returned if the condition evaluates to true. + _value_if_false: This is the value returned if the condition evaluates to false. int a= 10,b=5; int max= (a >b) 2a: f true; In this example: (a> b) is the condition, tue if tue, bis value if fale. restr that e value of a; otherwise, it will be assigned the value of b. Scanned with CamScanner Exit EXIT CONTROL LOOP INC. an exit control foop in Cto examine the teri body of the loop if the evaluation for the tert control makes another entry inside the loop. ‘ation condition for an exit. Control would leave the main mination condition yielded a true result. Otherwise, the This kind of loop often deals with the loop's exit control statement. DO WHILE Loop: ‘The most applicable illustration of an exit control loop is the do-while loop. The while loop has been modified to become the de-while loop. ‘The do-while loop is the most appropriate loop when it is necessary to run the program and do certain activities at least once, oe ‘The do-while loop cannot be executed again if the evaluation of the termination condition or test expression returns false. Since the do-while loopanalyzes the termination condition at the conclusion, it is the most Scanned with CamScanner DO WHILE Loop: ‘The most applicable illustration of an certain activities at least once. ‘The do-while loop cannot be executed aj test expression returns false. Since the do-whil loop analyzes the tert important exit control loop and will therefore The do-while loop will probably be ended if the exit loop yields true. If this doesn’t happen, it ‘Syntax: ‘The do-whilelloop's syntax is provided below: iv examples for each: 1 1 for(i O;i+) Zz 3. printh(“%d i); 4 itl 5. break; 6 2, 1 2. i a s, 6 2 exit control loop is the do-while loop. ‘The while loop has been modified to become the do-while loop. ‘The do-while loop is the most appro} riate loop when it is necessary to run the program and do gain if the evaluation of the termination condition or ‘ation condition at the conclusion, it is the most initially execute unconditionally for the first time. the examination of the termination condition for ill be put into practise once more. Scanned with CamScanner gu pen oy aenp 1 2. 3. 4 5. 6. goto out; + 7. out: note: ‘xit(0) statement not only takes you take you out of loop butalso it comple Of loop but also it completely takes you out of the Program you can also use peel eles of Scanned with CamScanner Tetum ; statement also to comes out of loop or directly out of main function in C., this works exactly like exit(0); Scanned with CamScanner

You might also like