Вы находитесь на странице: 1из 34

Control Statements(Decision Making & Branching) 20 July 2009 No Comments Posted By:Dileep Normally, the statements in a program are

executed in the order in which they ap pear in the program. This type of execution is called sequential execution. Control structures define the order of execution of statements. Conditional control statements involves both decision making and branching. if-statement. if-else statement. Nested-if-statement. switch statement. if-statement used to execute a statement or a set of statements conditionally. Also called a one-way branching. Syntax if (condition) { statement; } if-else statement The if statement is used to execute only one action. If there are two statements to be executed alternatively, then if-else statement is used. Two-way branching. Syntax if (condition) { statement1; } else { statement2; } Nested-if statement If there are more than two alternatives to select, then the nested-if statements are used. Enclosing an if statement within another if statement is called the nested-if st atement. Syntax if (condition1) { if (condition2) { statement1; } else { statement2; } } else if (condition3) { statement3; } else { statement4; } There are many ways to nest one if-else within the other. switch statement The switch statement provides a multiple way of branching. It allows the user to select any one of the several alternatives, depending on t

he value of an expression. Syntax switch (expression) { case label1 : block1; break; case label2 : block2; break; . . . case labelmax : blockmax; break; case default : dblock; break; } The expression is of type int or char. Depending on the value of an expression, execution branches to a particular case label and then all the statements belonging to that case label are executed. The break statement indicates the end of a particular case label and thereby the switch statement is terminated. The case default is executed, when the value of an expression is not matched wit h any of the case labels. The semicolons should not be placed at the end of switch (expression). an unconditional control statement. goto-statement To transfer the control from one point to another in a C program. Syntax goto label; Forward jump and backward jump. Bachward jump will form a loop. The use of goto statement in a structured programming language like C should be avoided. Use if and only if it is unavoidable. The goto statement may create an infinite loop where the computer enters a perma nent loop. The careful and cautious design would resolve such situations. A program may contain any number of goto statements. No two statements can have the same label.

Loop Control Structures(Decision Making & Looping) 23 July 2009 No Comments Posted By:Dileep Looping is a powerful programing technique through which a group of statements i s executed repeatedly, until certain specified condition is satisfied. Looping is also called a repetitive or an iterative control mechanism. A loop in a program essentially consists of two parts, one is called the body of the loop and other is known as the control statement. The control statement performs a logical test whose result is either true or fal se. If the result of this logical test is true, then the statements contained in the body of the loop are executed. Otherwise, the loop is terminated. The control statement can be placed either before or after the body of the loop. If the control statement is placed before the body of the loop, it is called ent ry-controlled loop. If the control statement is written after the body of the loop, it is called the

exit-controlled loop. If the logical test condition is carelessly designed, then there may be a possib ility of formation of an infinite loop which keeps executing the statements over and over again. while-statement This is used to execute a set of statements repeatedly as long a s the specified condition is true. Referred to as pretest loop. Syntax while (logexp) { statement; } do-while statement This is used to execute a set of statements repeatedly until the logical test results in false. this is called the post-test loop. Because the test for repetition is made at th e end of each pass. Syntax do { statement; } while (logexp); At least once, the body of do-while is executed. The body of do-while must contain either implicitely or explicitely statements t o modify the variable involved in the logexp. for-statement This statement is used when the programmer knows how many times a set of statements is executed. Syntax for (expression1;expression2;expression3) { statement; } Nested-for statement If there are many data items to be processed against a set of elements repeatedly, then a single for statement is not adequate. Then, we mu st use the nested-for loop. If one for statement is completely placed within the other, it is known as the n ested-for statement. Syntax for(exp11;exp12;exp13) { for(exp21;exp22;exp23) { statement1; statement2; } } Jumps in loops break statement This is used to teminate a loop and exit from a particular switc h case label. continue statement This is used as the bypasser. The control does not come out o f the loop, instead it skips the remaining statements within the body of that lo op and transfers to the beginning of the loop

Decision Making and Branching Written by Administrator Sunday, 03 August 2008 15:05 If you have two options and want to perform some action for each option, this br anching is to be used. For example, if marks>35 grade is pass otherwise grade is fail. To program this sort of situations, you have to use branching concept. C Language provides statements that can alter the flow of a sequence of instruct ions. These statements are called control statements. These statements help to j ump from one part of the program to another. The control transfer may be conditi onal or unconditional. if statements and switch-case expressions can be used for con ditional control transfer and goto statements can be used for unconditional contro l transfer. Conditional control transfer: if statement: This is the simplest form of the control statement. It is very frequently used i n decision making. Syntax:

if (condition) statement; The statement is any valid C language statement and the condition is any valid C language expression, frequently logical operators are used in the condition sta tement. The condition part should not end with a semicolon, since the condition and statement should be put together as a single statement. The command says if the condition is true then perform the following statement or if the condition i s false the computer skips the statement and moves on to the next instruction in the program. -------------------------------------------------------------------------------Calculate the absolute value of an integer -------------------------------------------------------------------------------# include <stdio.h> //Include the stdio.h file void main () // start of the program { int numbers; // declare the variables printf ("Type a number:"); // message to the user scanf ("%d", &number); // read the number from standard input if (number < 0) // check whether the number is a negative number number = -number; // if it is negative then convert it into positiv e printf ("The absolute value is %d \n", number); // print the value

} -------------------------------------------------------------------------------The above program checks the value of the input number to see if it is less than zero. If it is then the following program statement which negates the value of the number is executed. If the value of the number is not less than zero, we do not want to negate it then this statement is automatically skipped. The absolute number is then displayed by the program, and program execution ends. The if else construct: This is just on extension of the general format of if statement. If the result o f the condition is true, then program statement 1 is executed, otherwise program statement 2 will be executed. If any case either program statement 1 is execute d or program statement 2 is executed but not both. Syntax:

if (condition) statement1; else statement2; -------------------------------------------------------------------------------Program to find whether a number is negative or positive -------------------------------------------------------------------------------#include <stdio.h> //include the stdio.h header file in your program void main () // start of the main { int num; // declare variable num as integer printf ("Enter the number"); // message to the user scanf ("%d", &num); // read the input number from keyboard if (num < 0) // check whether number is less than zero printf ("The number is negative"); // if it is less than zero then it is negative else // else statement printf ("The number is positive"); // if it is more than zero then the given number is positive } -------------------------------------------------------------------------------In the above program the If statement checks whether the given number is less th an 0. If it is less than zero then it is negative therefore the condition become s true then the statement The number is negative will be printed on the screen. If the number is not less than zero the If else construct skips the first statemen t and prints the second statement declaring that the number is positive. Compound Relational tests: C language provides the mechanisms necessary to perform compound relational test s. A compound relational test is simple one or more simple relational tests join ed together by either the logical AND or the logical OR operators. These operato rs are represented by the character pairs && // respectively. The compound opera tors can be used to form complex expressions in C. Syntax:

a> if (condition1 && condition2 && condition3) b> if (condition1 // condition2 // condition3) The syntax in the statement ferent conditions using the are true only then the whole dition is false the whole if a represents a complex if statement which combines dif and operator (&&) , in this case if all the conditions statement is considered to be true. Even if one con statement is considered to be false.

The statement b uses the logical operator or (//) to group different expression to be checked. In this case if any one of the expression is found to be true the w hole expression considered to be true, we can also uses the mixed expressions us ing logical operators and and or together. Nested if Statement: The if statement may itself contain another if statement is known as nested if s tatement. Syntax: if (condition1) if (condition2) statement1; else statement2; else statement3; The if statement may be nested as deeply as you need to nest it. One block of co de will only be executed if two conditions are true. Condition 1 is tested first and then condition 2 is tested. The second if condition is nested in the first. The second if condition is tested only when the first condition is true else th e program flow will skip to the corresponding else statement. -------------------------------------------------------------------------------To find biggest number among 3 numbers -------------------------------------------------------------------------------#include <stdio.h> //includes the stdio.h file to your program main () //start of main function { int a,b,c,big; //declaration of variables printf ("Enter three numbers"); //message to the user scanf ("%d %d %d", &a, &b, &c); //Read variables a,b,c, if (a > b) // check whether a is greater than b if true then { if (a > c) // check whether a is greater than c big = a ; // assign a to big else big = c ; // assign c to big } else if (b > c) // if the condition (a > b) fails check whether b is grea ter than c big = b; // assign b to big else big = c; // assign c to big //print the given numbers along with the largest number printf ("Largest of %d, %d & %d = %d", a,b,c,big);

-------------------------------------------------------------------------------In the above program the statement if (a>c) is nested within the if (a>b). If th e first If condition if (a>b) is true, only then the second if statement if (a>b ) is executed. If the first if condition is executed to be false then the progra m control shifts to the statement after corresponding else statement. -------------------------------------------------------------------------------Program to determine if a year is a leap year using compound if else construct -------------------------------------------------------------------------------#include <stdio.h> //Includes stdio.h file to your program void main () // start of the program { int year, rem_4, rem_100, rem_400; // variable declaration printf ("Enter the year to be tested"); // message for user scanf ("%d", &year); // Read the year from standard input. rem_4 = year % 4; //find the remainder of year by 4 rem_100 = year % 100; //find the remainder of year by 100 rem_400 = year % 400; //find the remainder of year by 400 //apply if condition to check whether remainder is zero if ((rem_4 == 0 && rem_100 != 0) rem_400 == 0) printf ("It is a leap year. \n"); // print true condition else printf ("No. It is not a leap year. \n"); //print the false c ondition } -------------------------------------------------------------------------------The above program checks whether the given year is a leap year or not. The year given is divided by 4,100 and 400 respectively and its remainder is collected in the variables rem_4, rem_100 and rem_400. A if condition statements checks whet her the remainders are zero. If remainder is zero then the year is a leap year. The ELSE If Ladder: When a series of many conditions have to be checked we may use the ladder else i f statement. Syntax:

if (condition1) statement1; else if (condition2) statement2; else if (condition3) statement3; else statement4; //default statement statement x; This construct is known as if else construct or ladder. The conditions are evalu ated from the top of the ladder to downwards. As soon on the true condition is f ound, the statement associated with it is executed and the control is transferre d to the statement x (skipping the rest of the ladder. When all the condition be comes false, the final else containing the default statement will be executed.

Example: Marks Grade 70 to 100 60 to 69 50 to 59 40 to 49 0 to 39 DISTINCTION IST CLASS IIND CLASS PASS CLASS FAIL -------------------------------------------------------------------------------Program to determine if a year is a leap year using compound if else construct

-------------------------------------------------------------------------------#include <stdio.h> //Includes stdio.h file to your program void main () // start of the program { int year, rem_4, rem_100, rem_400; // variable declaration printf ("Enter the year to be tested"); // message for user scanf ("%d", &year); // Read the year from standard input. rem_4 = year % 4; //find the remainder of year by 4 rem_100 = year % 100; //find the remainder of year by 100 rem_400 = year % 400; //find the remainder of year by 400 //apply if condition to check whether remainder is zero if ((rem_4 == 0 && rem_100 != 0) rem_400 == 0) printf ("It is a leap year. \n"); // print true condition else printf ("No. It is not a leap year. \n"); //print the false co ndition } -------------------------------------------------------------------------------The above program checks a series of conditions. The program begins from the fir st if statement and then checks the series of conditions. It stops the execution of remaining if statements whenever a condition becomes true. In the first If condition statement it checks whether the input value is lesser than 100 and greater than 70. If both conditions are true it prints distinction. Instead if the condition fails then the program control is transferred to the n ext if statement through the else statement and now it checks whether the next c ondition given is whether the marks value is greater than 60, if the condition i s true it prints first class and comes out of the If else chain to the end of th e program. On the other hand if this condition also fails the control is transfe rred to next if statements, program execution continues till the end of the loop and executes the default else statement fail and stops the program. The Switch Statement: Unlike the If statement which allows a selection of two alternatives the switch statement allows a program to select one statement for execution out of a set of

alternatives. During the execution of the switch statement only one of the poss ible statements will be executed the remaining statements will be skipped. The u sage of multiple If else statement increases the complexity of the program becau se when the number of If else statements increase, it affects the readability of the program and makes it difficult to follow the program. The switch statement removes these disadvantages by using a simple and straight forward approach. Syntax: Switch (expression) { case case-label-1: case case-label-2: case case-label-n: default: } When the switch statement is executed the control expression is evaluated first and the value is compared with the case label values in the given order. If the label matches with the value of the expression then the control is transferred d irectly to the group of statements which follow the label. If none of the statem ents matches then the statement against the default is executed. The default sta tement is optional in switch statement in case if any default statement is not g iven and if none of the condition matches then no action takes place in this cas e the control transfers to the next statement of the if else statement. -------------------------------------------------------------------------------A program to stimulate the four arithmetic operations using switch -------------------------------------------------------------------------------#include <stdio.h> void main () { int num1, num2, result; char operator; printf ("Enter two numbers"); scanf ("%d %d", &num1, &num2); printf ("Enter an operator"); scanf ("%c", &operator); switch (operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': if (num2 != 0) result = num1 / num2; else { printf ("warning : division by zero \n"); result = 0;

} break; default: printf ("\n unknown operator"); result = 0; break; } printf ("%d", result); } -------------------------------------------------------------------------------In the above program if the break statement is not there, all the cases will be executed consecutively. Rules: Space can t be used as case label. Only integers and characters can be used as case labels (floats and strings are not allowed) NULL character can be used as case label. Unconditional control transfer: GOTO statement: This is an unconditional control statement. This is simple statement used to tra nsfer the program control unconditionally from one statement to another statemen t. Although it might not be essential to use the goto statement in a highly stru ctured language like C, there may be occasions when the use of goto is desirable . Syntax goto label; Label: Statements . label: Statements goto label;

The goto requires a label in order to identify the place where the branch is to be made. A label is a valid name followed by a colon. Reserved words should not be used as a label. The label is placed immediately before the statement where the control is to be transformed. A program may contain several goto statements that transferred to t he same place in a program. The label must be unique. Control can be transferred out of or within a compound statement, and control can be transferred to the be ginning of a compound statement. However the control cannot be transferred into a compound statement. The goto statement is discouraged in C as it is error pron e.

-------------------------------------------------------------------------------A program to find the sum of n natural numbers using goto statement

--------------------------------------------------------------------------------

#include <stdio.h> //include stdio.h header file to your program main () //start of main { int n, sum = 0, i = 0; // variable declaration printf ("Enter a number"); // message to the user scanf ("%d", &n); //Read and store the number loop: i++; //Label of goto statement sum += i; //the sum value in stored and I is added to sum if (i < n) goto loop; //If value of I is less than n pass control to loop //print the sum of the numbers & value of n printf ("\n sum of %d natural numbers = %d", n, sum); } -------------------------------------------------------------------------------C Programming - Decision Making - BranchingPage 1 of 2C Programming - Decision M aking - Branching In this tutorial you will learn about C Programming - Decision Making, Branching , if Statement, The If else construct, Compound Relational tests, Nested if Stat ement, The ELSE If Ladder, The Switch Statement and The GOTO statement.

Ads

Branching The C language programs presented until now follows a sequential form of executi on of statements. Many times it is required to alter the flow of the sequence of instructions. C language provides statements that can alter the flow of a seque nce of instructions. These statements are called control statements. These state ments help to jump from one part of the program to another. The control transfer may be conditional or unconditional.

if Statement: The simplest form of the control statement is the If statement. It is very frequ ently used in decision making and allowing the flow of program execution.

The If structure has the following syntax if (condition) statement; The statement is any valid C language statement and the condition is any valid C l anguage expression, frequently logical operators are used in the condition state ment. The condition part should not end with a semicolon, since the condition an d statement should be put together as a single statement. The command says if th e condition is true then perform the following statement or If the condition is fake the computer skips the statement and moves on to the next instruction in th e program.

Example program

Sample Code # include <stdio.h> //Include the stdio.h file void main () // start of the program { int numbers // declare the variables

printf ("Type a number:") // message to the user scanf ("%d", &number) // read the number from standard input if (number < 0) // check whether the number is a negative number number = -number // if it is negative then convert it into positive

printf ("The absolute value is %d \n", number) // print the value } Copyright exforsys.com

The above program checks the value of the input number to see if it is less than zero. If it is then the following program statement which negates the value of the number is executed. If the value of the number is not less than zero, we do not want to negate it then this statement is automatically skipped. The absolute number is then displayed by the program, and program execution ends.

The If else construct: The syntax of the If else construct is as follows:-

The if else is actually just on extension of the general format of if statement. If the result of the condition is true, then program statement 1 is executed, o therwise program statement 2 will be executed. If any case either program statem ent 1 is executed or program statement 2 is executed but not both when writing p rograms this else statement is so frequently required that almost all programmin g languages provide a special construct to handle this situation.

Sample Code #include <stdio.h> //include the stdio.h header file in your program void main () { int num // declare variable num as integer printf ("Enter the number") // message to the user scanf ("%d", &num) if (num < 0) // read the input number from keyboard // start of the main

// check whether number is less than zero // if it is less than zero then it is

printf ("The number is negative") negative else // else statement

printf ("The number is positive") // if it is more than zero then the gi ven number is positive } Copyright exforsys.com

In the above program the If statement checks whether the given number is less th an 0. If it is less than zero then it is negative therefore the condition become s true then the statement The number is negative is executed. If the number is n ot less than zero the If else construct skips the first statement and prints the second statement declaring that the number is positive.

Compound Relational tests: C language provides the mechanisms necessary to perform compound relational test s. A compound relational test is simple one or more simple relational tests join ed together by either the logical AND or the logical OR operators. These operato rs are represented by the character pairs && // respectively. The compound opera tors can be used to form complex expressions in C. Syntax a> if (condition1 && condition2 && condition3) b> if (condition1 // condition2 // condition3) The syntax in the statement a represents a complex if statement which combines dif ferent conditions using the and operator in this case if all the conditions are true only then the whole statement is considered to be true. Even if one conditi

on is false the whole if statement is considered to be false. The statement b uses the logical operator or (//) to group different expression to be checked. In this case if any one of the expression if found to be true the w hole expression considered to be true, we can also uses the mixed expressions us ing logical operators and and or together.

Nested if Statement The if statement may itself contain another if statement is known as nested if s tatement.

Syntax: if (condition1) if (condition2) statement-1; else statement-2; else statement-3; The if statement may be nested as deeply as you need to nest it. One block of co de will only be executed if two conditions are true. Condition 1 is tested first and then condition 2 is tested. The second if condition is nested in the first. The second if condition is tested only when the first condition is true else th e program flow will skip to the corresponding else statement.

Sample Code #include <stdio.h> //includes the stdio.h file to your program main () //start of main function { int a,b,c,big //declaration of variables printf ("Enter three numbers") //message to the user scanf ("%d %d %d", &a, &b, &c) //Read variables a,b,c, if (a > b) // check whether a is greater than b if true then if (a > c) // check whether a is greater than c big = a // assign a to big else big = c // assign c to big else if (b > c) // if the condition (a > b) fails check whether b is greate r than c

big = b // assign b to big else big = c // assign c to big printf ("Largest of %d, %d & %d = %d", a,b,c,big) //print the given numbers along with the largest number } Copyright exforsys.com

In the above program the statement if (a>c) is nested within the if (a>b). If th e first If condition if (a>b) If (a>b) is true only then the second if statement if (a>b) is executed. If the first if condition is executed to be false then the program control shifts to th e statement after corresponding else statement.

Sample Code #include <stdio.h> //Includes stdio.h file to your program void main () // start of the program { int year, rem_4, rem_100, rem_400 // variable declaration

printf ("Enter the year to be tested") // message for user scanf ("%d", &year) // Read the year from standard input.

rem_4 = year % 4 //find the remainder of year by 4 rem_100 = year % 100 //find the remainder of year by 100 rem_400 = year % 400 //find the remainder of year by 400

if ((rem_4 == 0 && rem_100 != 0) rem_400 == 0) //apply if condition 5 check whether remainder is zero printf ("It is a leap year. \n") // print true condition

else printf ("No. It is not a leap year. \n") //print the false condition } Copyright exforsys.com

Ads

The above program checks whether the given year is a leap year or not. The year given is divided by 4,100 and 400 respectively and its remainder is collected in the variables rem_4, rem_100 and rem_400. A if condition statements checks whet her the remainders are zero. If remainder is zero then the year is a leap year. Here either the year y 400 is to be zero or both the year 4 and year by 100 has to be zero, then the year is a leap year.

Decision Making and Branching (if statement) by Sachin Mehta We have seen that a C program is a set of statements, which are normally execute d sequentially in the order in which they appear. This happens when no repetitio ns of certain calculations are necessary . However, in practice, we have a numbe r of situations where we may have to change the order of execution of statements based on certain conditions are met. C language possesses such decision making capabilities and supports the followin g statements known as control or decision-making statements. 1. if statement switch statement

Conditional operator statement goto statement This article will focus on the if statement. Rest all will be discussed in the n ext article. Decision making if statement The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two-way decision statemen t and is used in conjunction with an expression. It takes the following form: if (test expression) It allows the computer to evaluate the expression first and then , depending on whether the value of the expression (relation or condition) is ' true ' (non-zer o) or ' false ' (zero), it transfers the control to a particular statement. This point of program has two paths to follow , one for the true condition and the o ther for the false condition. The if statement may be implemented in different forms depending on the complexi ty of the conditions to be tested. Simple if statement if...else statement Nested if...else statement else if ladder. Simple if statement The general form of a simple if statement is if (test expression) { statement-block; } statement-x; The statement-block may be a single statement or a group of statements. If the t est expression is true, the statement-block will be executed; otherwise the stat ement-block will be skipped and the execution will jump to statement-x. remember , when the condition is true both the statement-block and the statement-x are ex ecuted in sequence. Example: .......... if (x == 1) { y = y +10; } printf("%d", y); ......... The program tests the value of x and accordingly calculates y and prints it. If x is 1 then y gets incremented by 1 else it is not incremented if x is not equal to 1. Then the value of y gets printed. The if else statement The if....else statement is an extension of the simple if statement. The general form is if (test expression)

{ True-block statement(s) } else { False-block statement(s) } statement-x If the test expression is true , then the true-block statement(s), immediately f ollowing the if statement are executed; otherwise the false-block statement(s) a re executed. In either case, either true-block or false-block will be executed, not both. Example: ........ if (c == 'm') male = male +1; else fem = fem +1; ....... Nesting of if else statements When a series of decisions are involved, we may have to use more than one if.... .else statement in nested form as follows: if (test condition1) { if (test condition 2) { statement-1; } else { statement-2; } } else { statement-3; } statement-x; If the condition-1 is false statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 is true, the statement-1 will be evaluated; otherwise the statement-2 will be evaluated and then the control is transferred to the statement-x. The else if ladder There is another way of putting ifs together when multipath decisions are involv ed. A multipath decision is a chain of ifs in which the statement associated wit h each else is an if. It takes the following general form: if (condition 1) statement 1 ; else if (condition 2) statement 2; else if (condition 3) statement 3;

else if (condition n) statement n; else default statement; statement x; This construct is known as the else if ladder. The conditions are evaluated from the top (of the ladder), downwards. As soon as a true condition is found, the s tatement associated with is executed and the control is transferred to the state ment x (skipping the rest of the ladder). When all the n conditions become false, then the final else containing the defau lt statement will be executed. Example : Let us consider an example of grading the students in an academic institution. T he grading is done according to the following rules: Average marks Grade 80-100 Honours 60- 79 First Division 50- 59 Second Division 40- 49 Third Division 0- 39 Fail This grading can be done using the else if ladder follows: if (marks > 79) grade = else if (marks >59) grade = else if (marks > 49) grade = else if (marks > 39) grade = else grade = "Honours"; "First Division"; "Second Division"; "Third division"; "Fail";

Don't underestimate the power of if statement. It finds place in almost all prog ramming language with similar cause and effect. Learn to use it carefully and pr operly to give your program that professional look.

C Programming - Decision Making - Looping

In this tutorial you will learn about C Programming - Decision Making - Looping, The While Statement, The Do while statement, The Break Statement, Continue stat ement and For Loop.

Ads

During looping a set of statements are executed until some conditions for termin ation of the loop is encountered. A program loop therefore consists of two segme nts one known as body of the loop and other is the control statement. The contro l statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. In 1. 2. 3. 4. looping process in general would include the following four steps Setting and initialization of a counter Exertion of the statements in the loop Test for a specified conditions for the execution of the loop Incrementing the counter

The test may be either to determine whether the loop has repeated the specified number of times or to determine whether the particular condition has been met.

The While Statement: The simplest of all looping structure in C is the while statement. The general f ormat of the while statement is:

while (test condition) { body of the loop }

Here the given test condition is evaluated and if the condition is true then the body of the loop is executed. After the execution of the body, the test conditi on is once again evaluated and if it is true, the body is executed once again. T his 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 statements immediately after the body of the loop . The body of the loop may have one or more statements. The braces are needed on ly if the body contained two are more statements

Example program for generating

Natural numbers using while loop:

# include < stdio.h > //include the stdio.h file void main() // Start of your program

{ int n, i=0; //Declare and initialize the variables printf( Enter the upper limit number ); //Message to the user scanf( %d , &n); //read and store the number while(I < = n) // While statement with condition { // Body of the loop printf( \t%d ,I); // print the value of i I++; increment I to the next natural number. } }

In the above program the looping concept is used to generate n natural numbers. Here n and I are declared as integer variables and I is initialized to value zer o. A message is given to the user to enter the natural number till where he want s to generate the numbers. The entered number is read and stored by the scanf st atement. The while loop then checks whether the value of I is less than n i.e., the user entered number if it is true then the control enters the loop body and prints the value of I using the printf statement and increments the value of I t o the next natural number this process repeats till the value of I becomes equal to or greater than the number given by the user.

The Do while statement: The do while loop is also a kind of loop, which is similar to the while loop in contrast to while loop, the do while loop tests at the bottom of the loop after executing the body of the loop. Since the body of the loop is executed first and then the loop condition is checked we can be assured that the body of the loop is executed at least once.

The syntax of the do while loop is:

Do { statement; } while(expression);

Here the statement is executed, then expression is evaluated. If the condition e xpression is true then the body is executed again and this process continues til l the conditional expression becomes false. When the expression becomes false. W hen the expression becomes false the loop terminates.

To realize the usefulness of the do while construct consider the following probl em. The user must be prompted to press Y or N. In reality the user can press any key other than y or n. IN such case the message must be shown again and the use r should be allowed to enter one of the two keys, clearly this is a loop constru ct. Also it has to be executed at least once. The following program illustrates the solution.

/* Program to illustrate the do while loop*/ #include < stdio.h > //include stdio.h file to your program void main() // start of your program { char inchar; // declaration of the character do // start of the do loop { printf( Input Y or N ); //message for the user scanf( %c , &inchar); // read and store the character } while(inchar!= y && inchar != n ); //while loop ends if(inchar== y ) // checks whther entered character is y printf( you pressed u\n ); // message for the user else printf( You pressed n\n ); } //end of for loop

The Break Statement: Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as soon as certain condition occurs, for example consider sear ching a particular number in a set of 100 numbers as soon as the search number i s found it is desirable to terminate the loop. C language permits a jump from on e statement to another within a loop as well as to jump out of the loop. The bre ak statement allows us to accomplish this task. A break statement provides an ea rly exit from for, while, do and switch constructs. A break causes the innermost enclosing loop or switch to be exited immediately.

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 I, num=0; //declare 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 ,&I); // read and store the input number if(I==-1) // check whether input number is -1 break; //if number 1 is input skip the loop sum+=I; //else add the value of I to sum num++ // increment num value by 1 }} end of the program

Continue statement: During loop operations it may be necessary to skip a part of the body of the loo p under certain conditions. Like the break statement C supports similar statemen t called continue statement. The continue statement causes the loop to be contin ued with the next iteration after skipping any statement in between. The continu

e 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 < stdio.h > //Include stdio.h file void main() //start of the program { int I=1, num, sum=0; // declare and initialize the variables for (I = 0; I < 5; I++) // for loop { printf( Enter the integer ); //Message to the user 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 } // end of for loop sum+=num; // add and store sum to num } printf( The sum of positive numbers entered = %d ,sum); // print thte sum. } // end of the program.

For Loop: The for loop provides a more concise loop control structure. The general form of the for loop is:

for (initialization; test condition; increment) { body of the loop }

When the control enters for loop the variables used in for loop is initialized w ith the starting value such as I=0,count=0. The value which was initialized is t hen checked with the given test condition. The test condition is a relational ex pression, such as I < 5 that checks whether the given condition is satisfied or not if the given condition is satisfied the control enters the body of the loop or else it will exit the loop. The body of the loop is entered only if the test condition is satisfied and after the completion of the execution of the loop the control is transferred back to the increment part of the loop. The control vari able is incremented using an assignment statement such as I=I+1 or simply I++ an d the new value of the control variable is again tested to check whether it sati sfies the loop condition. If the value of the control variable satisfies then th e body of the loop is again executed. The process goes on till the control varia ble fails to satisfy the condition.

Additional features of the for loop:

We can include multiple expressions in any of the fields of for loop provided th at we separate such expressions by commas. For example in the for statement that begins

For( I = 0; j = 0; I < 10, j=j-10)

Sets up two index variables I and j the former initialized to zero and the latte r to 100 before the loop begins. Each time after the body of the loop is execute d, the value of I will be incremented by 1 while the value of j is decremented b y 10.

Just as the need may arise to include more than one expression in a particular f ield of the for statement, so too may the need arise to omit on or more fields f rom the for statement. This can be done simply by omitting the desired filed, bu t by marking its place with a semicolon. The init_expression field can simply be left blank in such a case as long as the semicolon is still included:

For(;j!=100;++j)

Ads

The above statement might be used if j were already set to some initial value be fore the loop was entered. A for loop that has its looping condition field omitt ed effectively sets up an infinite loop, that is a loop that theoretically will be executed for ever. For loop example program:

/* The following is an example that finds the sum of the first fifteen positive natural numbers*/ #include < stdio.h > //Include stdio.h file void main() //start main program { int I; //declare variable int sum=0,sum_of_squares=0; //declare and initialize variable. for(I=0;I < = 30; I+=2) //for loop

{ sum+=I; //add the value of I and store it to sum sum_of_squares+=I*I; //find the square value and add it to sum_of_squares } //end of for loop printf( Sum of first 15 positive even numbers=%d\n ,sum); //Print sum printf( Sum of their squares=%d\n ,sum_of_squares); //print sum_of_square }

Decision-Making in MATLAB

The inherent potential of programming (in any language) to solve complex enginee ring problems is realized when decision-making becomes formalized and possible, and when complex operations and calculations can be done repetitively. Coupled w ith flexible visualization tools these features of MATLAB make it one of the mos t commonly adopted computational environments for solving engineering design pro blems. MATLAB has built-in commands and functions for logical operations and con ditional branching that make it possible to execute different code segments in d ifferent cases. In addition, different commands are available to structure loopi ng operations that execute code segments repetitively either deterministically o r coupled to condition statements.

Relational Operators and Functions The usual relational and logical tests associated with mathematical inequality s tatements (which I m sure you ve all seen before) can be accomplished in MATLAB. MAT LAB typically executes the required test and returns a true result (1) or false result (0) to a workspace variable. These logical tests can be combined to make fairly complex decisions, and tables of both relational and logical operators ar e provided on pgs. 249 and 250. Some simple examples illustrate the idea I thin k. a=2;b=7; c=(a==b) c=a<b c=a>b c=(a<d)&(b>d)

c=(a>b) (b>d) These logical operators also accept array arguments and work in much the same wa y. Thus, a=[2 3 5 9];;b=[0 3 7 6]; c=(a==b) c=(a<b)

Conditional statements Conditional statements enable us to write programs that are structured into code segments that are each executed when particular conditions are determined to ex ist. These conditions are typically formalized, as a logical test on data calcul ated by MATLAB and execution of the MATLAB code is made conditional on the resul t of this logical test. This implements what is commonly referred to as branchin g. The most common way to make this happen is to use the if-elseif statement. An abbreviated copy of the help file is provided in accompanying handout for you. To illustrate how this is used, we ll write a program to complete problem T6.3-1 o n page 263.

help if IF statement condition. The general form of the IF statement is

IF expression statements ELSEIF expression statements ELSE statements END The statements are executed if the real part of the expression has all non-z ero elements. The ELSE and ELSEIF parts are optional. Zero or more ELSEIF parts can be used as well as nested IF's. The expression is usually of the form expr rop expr where rop is ==, <, >, <=, >=, or ~=.

Example if I == J

A(I,J) = 2; elseif abs(I-J) == 1 A(I,J) = -1; else A(I,J) = 0; end

See also RELOP, ELSE, ELSEIF, END, FOR, WHILE, SWITCH.

Example T6.3-1 (Pg. 263). Writing an arcsin function. State the problem concisely.

Given a number x and a quadrant q (q=1,2,3,4), write a program to compute sin-1( x) in degrees, taking into account the quadrant. The program should display an e rror message if x >1. x q t . th Specify the data to be used by the program. This is the input . a real, scalar variable a real, scalar integer Specify the information to be generated by the program. This is the outpu an angle in degrees

Work through the solution steps by hand or with a calculator; use a simp ler data set if necessary. sin(50)=0.766, sin(-50)=-0.766, sin(130)=0.766, sin(-130)=-0.766 Write and run the program.

A pseudocode description: Given x and q, calculate th=sin-1(x) in degrees. If x >1 print an error message. Else if q corresponds to the second or third quadrant, adjust th accordingly and return the result in degrees. Else if x and q are not in agreement, display an error message.

Looping the Loop in MATLAB If is fortuitous that MATLAB, like most other computer languages, provides sever al mechanisms for repetitively executing code segments. We ve seen already how use ful this might prove to be when we need to repeat the same calculation for a var iety of different conditions (i.e. in the vibration frequency problem we conside red a few weeks ago.) All that remains is to understand and apply the syntax of the different MATLAB commands that enable this type of program structure. There are basically two ways to do this: using a for loop and using a while loop. The for loop The basic syntax for a for loop is provided in the corresponding MATLAB help fil e. Basically, a loop variable (usually an integer) is established that increment s from a defined minimum value to a defined maximum. For each value of the loop variable, a defined code segment is executed. The calculated results for each pas s through the loop are easily stored in array variables, either as successive col umns or successive rows. The calculated data can either be output each time the loop is executed (although this is very time consuming), or can be output or dis played after the loop has terminated.

Example 1: x=[1:.1:2]; [m,n]=size(x); for k=1:n y(k)=x(k)^2; end plot(x,y)

Example 2: sum=0;N=24 for k=1:N sum(k+1)=sum(k)+k; end stairs(sum) title( Cumulative sum )

The while loop

While loops are used when the termination of a looping process terminates when a particular condition is satisfied. The syntax of the loop is similar to the for loop except that the termination condition is provided in a logical expression associated with the while loop. The help file for the while statement is provide d in the handout but a simple example will suffice to illustrate the idea. The e xample above can be reformulated to use a while statement as: Example 3: x=1; while (x<=2) y=x^2; x=x+.1; end The main difference between these two approaches is that it is probably easier t o index and save the results in an array if a loop variable such as that in the for loop, is available.

help for

FOR

Repeat statements a specific number of times. The general form of a FOR statement is:

FOR variable = expr, statement, ..., statement END

The columns of the expression are stored one at a time in the variable and t hen the following statements, up to the END, are executed. The expression is oft en of the form X:Y, in which case its columns are simply scalars. Some examples (assume N has already been assigned a value).

FOR I = 1:N, FOR J = 1:N, A(I,J) = 1/(I+J-1); END END

FOR S = 1.0: -0.1: 0.0, END steps S with increments of -0.1

FOR E = EYE(N), ... END sets E to the unit N-vectors.

Long loops are more memory efficient when the colon expression appears in th e FOR statement since the index vector is never created.

The BREAK statement can be used to terminate the loop prematurely.

See also IF, WHILE, SWITCH, BREAK, END.

help while

WHILE Repeat statements an indefinite number of times. The general form of a WHILE statement is:

WHILE expression statements END

The statements are executed while the real part of the expression has all no n-zero elements. The expression is usually the result of expr rop expr where rop is ==, <, >, <=, >=, or ~=.

The BREAK statement can be used to terminate the loop prematurely.

For example (assuming A already defined):

E = 0*A; F = E + eye(size(E)); N = 1; while norm(E+F-E,1) > 0, E = E + F; F = A*F/N; N = N + 1; end

See also FOR, IF, SWITCH, BREAK, END.

Decision Making and Branching (if statement) by Sachin Mehta We have seen that a C program is a set of statements, which are normally execute d sequentially in the order in which they appear. This happens when no repetitio ns of certain calculations are necessary . However, in practice, we have a numbe r of situations where we may have to change the order of execution of statements based on certain conditions are met. C language possesses such decision making capabilities and supports the followin g statements known as control or decision-making statements. 1. if statement switch statement Conditional operator statement goto statement This article will focus on the if statement. Rest all will be discussed in the n ext article. Decision making if statement The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two-way decision statemen t and is used in conjunction with an expression. It takes the following form: if (test expression) It allows the computer to evaluate the expression first and then , depending on whether the value of the expression (relation or condition) is ' true ' (non-zer o) or ' false ' (zero), it transfers the control to a particular statement. This point of program has two paths to follow , one for the true condition and the o ther for the false condition. The if statement may be implemented in different forms depending on the complexi ty of the conditions to be tested. Simple if statement

if...else statement Nested if...else statement else if ladder. Simple if statement The general form of a simple if statement is if (test expression) { statement-block; } statement-x; The statement-block may be a single statement or a group of statements. If the t est expression is true, the statement-block will be executed; otherwise the stat ement-block will be skipped and the execution will jump to statement-x. remember , when the condition is true both the statement-block and the statement-x are ex ecuted in sequence. Example: .......... if (x == 1) { y = y +10; } printf("%d", y); ......... The program tests the value of x and accordingly calculates y and prints it. If x is 1 then y gets incremented by 1 else it is not incremented if x is not equal to 1. Then the value of y gets printed. The if else statement The if....else statement is an extension of the simple if statement. The general form is if (test expression) { True-block statement(s) } else { False-block statement(s) } statement-x If the test expression is true , then the true-block statement(s), immediately f ollowing the if statement are executed; otherwise the false-block statement(s) a re executed. In either case, either true-block or false-block will be executed, not both. Example: ........ if (c == 'm') male = male +1; else fem = fem +1; .......

Nesting of if else statements When a series of decisions are involved, we may have to use more than one if.... .else statement in nested form as follows: if (test condition1) { if (test condition 2) { statement-1; } else { statement-2; } } else { statement-3; } statement-x; If the condition-1 is false statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 is true, the statement-1 will be evaluated; otherwise the statement-2 will be evaluated and then the control is transferred to the statement-x. The else if ladder There is another way of putting ifs together when multipath decisions are involv ed. A multipath decision is a chain of ifs in which the statement associated wit h each else is an if. It takes the following general form: if (condition 1) statement 1 ; else if (condition 2) statement 2; else if (condition 3) statement 3; else if (condition n) statement n; else default statement; statement x; This construct is known as the else if ladder. The conditions are evaluated from the top (of the ladder), downwards. As soon as a true condition is found, the s tatement associated with is executed and the control is transferred to the state ment x (skipping the rest of the ladder). When all the n conditions become false, then the final else containing the defau lt statement will be executed. Example : Let us consider an example of grading the students in an academic institution. T he grading is done according to the following rules: Average marks Grade 80-100 Honours 60- 79 First Division 50- 59 Second Division

40- 49 Third Division 0- 39 Fail This grading can be done using the else if ladder follows: if (marks > 79) grade = else if (marks >59) grade = else if (marks > 49) grade = else if (marks > 39) grade = else grade = "Honours"; "First Division"; "Second Division"; "Third division"; "Fail";

Don't underestimate the power of if statement. It finds place in almost all prog ramming language with similar cause and effect. Learn to use it carefully and pr operly to give your program that professional look

Вам также может понравиться