branching and looping

Upload: dahiyahunny

Post on 07-Apr-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Branching and Looping

    1/34

  • 8/6/2019 Branching and Looping

    2/34

    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 theswitch statement is terminated.The case default is executed, when the value of an expression is not matched with any of the case labels.The semicolons should not be placed at the end of switch (expression).goto-statement an unconditional control 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 beavoided. Use if and only if it is unavoidable.The goto statement may create an infinite loop where the computer enters a permanent 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:DileepLooping is a powerful programing technique through which a group of statements is 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 ofthe loop and other is known as the control statement.The control statement performs a logical test whose result is either true or false. If the result of this logical test is true, then the statements contained inthe 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 entry-controlled loop.If the control statement is written after the body of the loop, it is called the

  • 8/6/2019 Branching and Looping

    3/34

    exit-controlled loop.If the logical test condition is carelessly designed, then there may be a possibility of formation of an infinite loop which keeps executing the statements overand over again.while-statement This is used to execute a set of statements repeatedly as long as 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 untilthe logical test results in false.this is called the post-test loop. Because the test for repetition is made at the 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 to modify the variable involved in the logexp.for-statement This statement is used when the programmer knows how many times aset of statements is executed.Syntax -for (expression1;expression2;expression3){

    statement;}

    Nested-for statement If there are many data items to be processed against a setof elements repeatedly, then a single for statement is not adequate. Then, we must use the nested-for loop.If one for statement is completely placed within the other, it is known as the nested-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 switch case label.continue statement This is used as the bypasser. The control does not come out of the loop, instead it skips the remaining statements within the body of that loop and transfers to the beginning of the loop

  • 8/6/2019 Branching and Looping

    4/34

    Decision Making and BranchingWritten by AdministratorSunday, 03 August 2008 15:05If you have two options and want to perform some action for each option, this branching is to be used. For example, if marks>35 grade is pass otherwise grade isfail. 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 instructions. These statements are called control statements. These statements help to jump 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 conditional 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 in decision making.

    Syntax:

    if (condition)statement;

    The statement is any valid C language statement and the condition is any valid Clanguage expression, frequently logical operators are used in the condition statement. The condition part should not end with a semicolon, since the conditionand statement should be put together as a single statement. The command says ifthe condition is true then perform the following statement or if the condition is false the computer skips the statement and moves on to the next instruction inthe program.

    --------------------------------------------------------------------------------Calculate the absolute value of an integer

    --------------------------------------------------------------------------------# include //Include the stdio.h filevoid main () // start of the program{

    int numbers; // declare the variablesprintf ("Type a number:"); // message to the userscanf ("%d", &number); // read the number from standard inputif (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

  • 8/6/2019 Branching and Looping

    5/34

    }--------------------------------------------------------------------------------

    The above program checks the value of the input number to see if it is less thanzero. If it is then the following program statement which negates the value ofthe number is executed. If the value of the number is not less than zero, we donot 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 of the condition is true, then program statement 1 is executed, otherwise programstatement 2 will be executed. If any case either program statement 1 is executed or program statement 2 is executed but not both.

    Syntax:

    if (condition)statement1;

    elsestatement2;

    --------------------------------------------------------------------------------Program to find whether a number is negative or positive

    --------------------------------------------------------------------------------#include //include the stdio.h header file in your programvoid main () // start of the main{

    int num; // declare variable num as integerprintf ("Enter the number"); // message to the userscanf ("%d", &num); // read the input number from keyboardif (num < 0) // check whether number is less than zero

    printf ("The number is negative"); // if it is less than zero thenit is negative

    else // else statementprintf ("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 than 0. If it is less than zero then it is negative therefore the condition becomes true then the statement The number is negative will be printed on the screen. Ifthe number is not 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 tests. A compound relational test is simple one or more simple relational tests joined together by either the logical AND or the logical OR operators. These operators are represented by the character pairs && // respectively. The compound opera

    tors can be used to form complex expressions in C.

    Syntax:

  • 8/6/2019 Branching and Looping

    6/34

    a> if (condition1 && condition2 && condition3)b> if (condition1 // condition2 // condition3)

    The syntax in the statement a represents a complex if statement which combines different conditions using the and operator (&&), in this case if all the conditionsare true only then the whole statement is considered to be true. Even if one con

    dition is false the whole if statement is considered to be false.

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

    Nested if Statement:

    The if statement may itself contain another if statement is known as nested if statement.

    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 code will only be executed if two conditions are true. Condition 1 is tested firstand 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 the program flow will skip to the corresponding else statement.

    --------------------------------------------------------------------------------To find biggest number among 3 numbers

    --------------------------------------------------------------------------------#include //includes the stdio.h file to your programmain () //start of main function{

    int a,b,c,big; //declaration of variablesprintf ("Enter three numbers"); //message to the userscanf ("%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 cbig = a ; // assign a to big

    elsebig = c ; // assign c to big

    }else if (b > c) // if the condition (a > b) fails check whether b is grea

    ter than cbig = b; // assign b to big

    else

    big = c; // assign c to big//print the given numbers along with the largest numberprintf ("Largest of %d, %d & %d = %d", a,b,c,big);

  • 8/6/2019 Branching and Looping

    7/34

    }

    --------------------------------------------------------------------------------In the above program the statement if (a>c) is nested within the if (a>b). If the 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 program 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 //Includes stdio.h file to your programvoid main () // start of the program{

    int year, rem_4, rem_100, rem_400; // variable declarationprintf ("Enter the year to be tested"); // message for userscanf ("%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 100rem_400 = year % 400; //find the remainder of year by 400//apply if condition to check whether remainder is zeroif ((rem_4 == 0 && rem_100 != 0) rem_400 == 0)

    printf ("It is a leap year. \n"); // print true conditionelse

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

    --------------------------------------------------------------------------------The above program checks whether the given year is a leap year or not. The yeargiven 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 whether 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 if statement.

    Syntax:

    if (condition1)statement1;

    else if (condition2)statement2;

    else if (condition3)statement3;

    elsestatement4; //default statement

    statement x;

    This construct is known as if else construct or ladder. The conditions are evaluated 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 transferred to the statement x (skipping the rest of the ladder. When all the condition becomes false, the final else containing the default statement will be executed.

  • 8/6/2019 Branching and Looping

    8/34

    Example:

    Marks Grade70 to 10060 to 69

    50 to 5940 to 490 to 39 DISTINCTIONIST CLASSIIND CLASSPASS CLASSFAIL

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

    Program to determine if a year is a leap year using compound if else construct

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

    #include //Includes stdio.h file to your programvoid main () // start of the program{

    int year, rem_4, rem_100, rem_400; // variable declarationprintf ("Enter the year to be tested"); // message for userscanf ("%d", &year); // Read the year from standard input.rem_4 = year % 4; //find the remainder of year by 4rem_100 = year % 100; //find the remainder of year by 100rem_400 = year % 400; //find the remainder of year by 400

    //apply if condition to check whether remainder is zeroif ((rem_4 == 0 && rem_100 != 0) rem_400 == 0)

    printf ("It is a leap year. \n"); // print true conditionelse

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

    --------------------------------------------------------------------------------The above program checks a series of conditions. The program begins from the first if statement and then checks the series of conditions. It stops the executionof remaining if statements whenever a condition becomes true.

    In the first If condition statement it checks whether the input value is lesserthan 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 next if statement through the else statement and now it checks whether the next condition given is whether the marks value is greater than 60, if the condition is true it prints first class and comes out of the If else chain to the end of the program. On the other hand if this condition also fails the control is transferred to next if statements, program execution continues till the end of the loopand 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 switchstatement allows a program to select one statement for execution out of a set of

  • 8/6/2019 Branching and Looping

    9/34

    alternatives. During the execution of the switch statement only one of the possible statements will be executed the remaining statements will be skipped. The usage of multiple If else statement increases the complexity of the program because when the number of If else statements increase, it affects the readability ofthe program and makes it difficult to follow the program. The switch statementremoves 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 firstand the value is compared with the case label values in the given order. If thelabel matches with the value of the expression then the control is transferred directly to the group of statements which follow the label. If none of the statements matches then the statement against the default is executed. The default statement is optional in switch statement in case if any default statement is not given and if none of the condition matches then no action takes place in this case the control transfers to the next statement of the if else statement.

    --------------------------------------------------------------------------------A program to stimulate the four arithmetic operations using switch

    --------------------------------------------------------------------------------#include 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;

  • 8/6/2019 Branching and Looping

    10/34

    }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 beexecuted consecutively.

    Rules:

    Space cant be used as case label. Only integers and characters can be used as case labels (floats and strings arenot 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 transfer the program control unconditionally from one statement to another statement. Although it might not be essential to use the goto statement in a highly structured language like C, there may be occasions when the use of goto is desirable.

    Syntax

    goto label; label:Label: StatementsStatements. goto label;

    The goto requires a label in order to identify the place where the branch is tobe made. A label is a valid name followed by a colon. Reserved words should notbe used as a label.

    The label is placed immediately before the statement where the control is to betransformed. A program may contain several goto statements that transferred to the same place in a program. The label must be unique. Control can be transferredout of or within a compound statement, and control can be transferred to the beginning of a compound statement. However the control cannot be transferred intoa compound statement. The goto statement is discouraged in C as it is error prone.

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

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

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

  • 8/6/2019 Branching and Looping

    11/34

    #include //include stdio.h header file to your programmain () //start of main{

    int n, sum = 0, i = 0; // variable declarationprintf ("Enter a number"); // message to the userscanf ("%d", &n); //Read and store the numberloop: i++; //Label of goto statement

    sum += i; //the sum value in stored and I is added to sumif (i < n)

    goto loop; //If value of I is less than n pass control to loop//print the sum of the numbers & value of nprintf ("\n sum of %d natural numbers = %d", n, sum);

    }

    --------------------------------------------------------------------------------C Programming - Decision Making - BranchingPage 1 of 2C Programming - Decision Making - BranchingIn 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

    BranchingThe 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 ofinstructions. C language provides statements that can alter the flow of a sequence of instructions. These statements are called control statements. These statements help to jump from one part of the program to another. The control transfermay be conditional or unconditional.

    if Statement:The simplest form of the control statement is the If statement. It is very frequently 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 language expression, frequently logical operators are used in the condition statement. 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 is

    fake the computer skips the statement and moves on to the next instruction in the program.

  • 8/6/2019 Branching and Looping

    12/34

    Example program

    Sample Code

    # include //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 thanzero. If it is then the following program statement which negates the value ofthe number is executed. If the value of the number is not less than zero, we donot want to negate it then this statement is automatically skipped. The absolutenumber 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, otherwise program statement 2 will be executed. If any case either program statement 1 is executed or program statement 2 is executed but not both when writing programs this else statement is so frequently required that almost all programming languages provide a special construct to handle this situation.

  • 8/6/2019 Branching and Looping

    13/34

    Sample Code

    #include //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 isnegative

    else // else statement

    printf ("The number is positive") // if it is more than zero then the given number is positive

    }

    Copyright exforsys.com

    In the above program the If statement checks whether the given number is less than 0. If it is less than zero then it is negative therefore the condition becomes true then the statement The number is negative is executed. If the number is not less than zero the If else construct skips the first statement and prints thesecond statement declaring that the number is positive.

    Compound Relational tests:C language provides the mechanisms necessary to perform compound relational tests. A compound relational test is simple one or more simple relational tests joined together by either the logical AND or the logical OR operators. These operators are represented by the character pairs && // respectively. The compound operators 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 different conditions using the and operator in this case if all the conditions aretrue only then the whole statement is considered to be true. Even if one conditi

  • 8/6/2019 Branching and Looping

    14/34

    on is false the whole if statement is considered to be false.

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

    Nested if StatementThe if statement may itself contain another if statement is known as nested if statement.

    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 code will only be executed if two conditions are true. Condition 1 is tested firstand 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 the program flow will skip to the corresponding else statement.

    Sample Code

    #include //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 greater than c

  • 8/6/2019 Branching and Looping

    15/34

    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 numbersalong 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 thefirst if condition is executed to be false then the program control shifts to the statement after corresponding else statement.

    Sample Code

    #include //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

  • 8/6/2019 Branching and Looping

    16/34

    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 yeargiven is divided by 4,100 and 400 respectively and its remainder is collected inthe variables rem_4, rem_100 and rem_400. A if condition statements checks whether 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 hasto 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 executed sequentially in the order in which they appear. This happens when no repetitions of certain calculations are necessary . However, in practice, we have a number of situations where we may have to change the order of execution of statementsbased on certain conditions are met.

    C language possesses such decision making capabilities and supports the following statements known as control or decision-making statements.

    1. if statementswitch statement

  • 8/6/2019 Branching and Looping

    17/34

    Conditional operator statementgoto statementThis article will focus on the if statement. Rest all will be discussed in the next article.

    Decision making if statement

    The if statement is a powerful decision making statement and is used to controlthe flow of execution of statements. It is basically a two-way decision statement 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 onwhether the value of the expression (relation or condition) is ' true ' (non-zero) or ' false ' (zero), it transfers the control to a particular statement. Thispoint of program has two paths to follow , one for the true condition and the other for the false condition.

    The if statement may be implemented in different forms depending on the complexity of the conditions to be tested.

    Simple if statementif...else statementNested if...else statementelse if ladder.Simple if statementThe 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 test expression is true, the statement-block will be executed; otherwise the statement-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 executed 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. Ifx is 1 then y gets incremented by 1 else it is not incremented if x is not equalto 1. Then the value of y gets printed.

    The ifelse statementThe if....else statement is an extension of the simple if statement. The general

    form is

    if (test expression)

  • 8/6/2019 Branching and Looping

    18/34

    {True-block statement(s)}else{False-block statement(s)}

    statement-x

    If the test expression is true , then the true-block statement(s), immediately following the if statement are executed; otherwise the false-block statement(s) are executed. In either case, either true-block or false-block will be executed,not both.

    Example:

    ........if (c == 'm')male = male +1;

    elsefem = fem +1;.......

    Nesting of ifelse statementsWhen 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 continuesto perform the second test. If the condition-2 is true, the statement-1 will beevaluated; otherwise the statement-2 will be evaluated and then the control istransferred to the statement-x.

    The else if ladderThere is another way of putting ifs together when multipath decisions are involved. A multipath decision is a chain of ifs in which the statement associated with 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;

  • 8/6/2019 Branching and Looping

    19/34

    else if (condition n)statement n;elsedefault 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 statement associated with is executed and the control is transferred to the 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.

    Example :Let us consider an example of grading the students in an academic institution. The grading is done according to the following rules:

    Average marks Grade

    80-100 Honours60- 79 First Division50- 59 Second Division40- 49 Third Division0- 39 Fail

    This grading can be done using the else if ladder follows:

    if (marks > 79)grade = "Honours";

    elseif (marks >59)

    grade = "First Division";elseif (marks > 49)

    grade = "Second Division";elseif (marks > 39)

    grade = "Third division";else

    grade = "Fail";

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

    C Programming - Decision Making - Looping

  • 8/6/2019 Branching and Looping

    20/34

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

    Ads

    During looping a set of statements are executed until some conditions for termination of the loop is encountered. A program loop therefore consists of two segments one known as body of the loop and other is the control statement. The control statement tests certain conditions and then directs the repeated execution ofthe statements contained in the body of the loop.

    In looping process in general would include the following four steps1. Setting and initialization of a counter2. Exertion of the statements in the loop3. Test for a specified conditions for the execution of the loop4. Incrementing the counter

    The test may be either to determine whether the loop has repeated the specifiednumber 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 thebody of the loop is executed. After the 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 conditionfinally 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 only if the body contained two are more statements

    Example program for generating N Natural numbers using while loop:

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

  • 8/6/2019 Branching and Looping

    21/34

    {int n, i=0; //Declare and initialize the variablesprintf(Enter the upper limit number); //Message to the userscanf(%d, &n); //read and store the numberwhile(I < = n) // While statement with condition{ // Body of the loopprintf(\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 zero. A message is given to the user to enter the natural number till where he wants to generate the numbers. The entered number is read and stored by the scanf statement. 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 to the next natural number this process repeats till the value of I becomes equalto 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 incontrast to while loop, the do while loop tests at the bottom of the loop afterexecuting the body of the loop. Since the body of the loop is executed first andthen the loop condition is checked we can be assured that the body of the loopis 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 expression is true then the body is executed again and this process continues till the conditional expression becomes false. When the expression becomes false. When the expression becomes false the loop terminates.

    To realize the usefulness of the do while construct consider the following problem. The user must be prompted to press Y or N. In reality the user can press anykey other than y or n. IN such case the message must be shown again and the user 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 illustratesthe solution.

  • 8/6/2019 Branching and Looping

    22/34

    /* Program to illustrate the do while loop*/#include < stdio.h > //include stdio.h file to your programvoid 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 userscanf(%c, &inchar); // read and store the character}while(inchar!=y && inchar != n); //while loop endsif(inchar==y) // checks whther entered character is yprintf(you pressed u\n); // message for the userelseprintf(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 loopor quit the loop as soon as certain condition occurs, for example consider searching a particular number in a set of 100 numbers as soon as the search number is found it is desirable to terminate the loop. C language 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. A break statement provides an early exit from for, while, do and switch constructs. A break causes the innermostenclosing 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 programvoid main() // Start of the program{int I, num=0; //declare the variables and initializefloat sum=0,average; //declare the variables and initializeprintf(Input the marks, -1 to end\n); // Message to the userwhile(1) // While loop starts{scanf(%d,&I); // read and store the input numberif(I==-1) // check whether input number is -1break; //if number 1 is input skip the loopsum+=I; //else add the value of I to sumnum++ // 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 statement called continue statement. The continue statement causes the loop to be continued with the next iteration after skipping any statement in between. The continu

  • 8/6/2019 Branching and Looping

    23/34

    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. Ifa negative number is entered, the sum is not performed since the remaining partof the loop is skipped using continue statement.

    #include < stdio.h > //Include stdio.h filevoid main() //start of the program{int I=1, num, sum=0; // declare and initialize the variablesfor (I = 0; I < 5; I++) // for loop

    {printf(Enter the integer); //Message to the userscanf(%I, &num); //read and store the numberif(num < 0) //check whether the number is less than zero{printf(You have entered a negative number); // message to the usercontinue; // starts with the beginning of the loop} // end of for loopsum+=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 ofthe 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 with the starting value such as I=0,count=0. The value which was initialized is then checked with the given test condition. The test condition is a relational expression, such as I < 5 that checks whether the given condition is satisfied ornot if the given condition is satisfied the control enters the body of the loopor else it will exit the loop. The body of the loop is entered only if the testcondition is satisfied and after the completion of the execution of the loop thecontrol is transferred back to the increment part of the loop. The control variable is incremented using an assignment statement such as I=I+1 or simply I++ and 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 the body of the loop is again executed. The process goes on till the control variable fails to satisfy the condition.

  • 8/6/2019 Branching and Looping

    24/34

    Additional features of the for loop:

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

    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 latter 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 by 10.

    Just as the need may arise to include more than one expression in a particular field of the for statement, so too may the need arise to omit on or more fields from the for statement. This can be done simply by omitting the desired filed, but by marking its place with a semicolon. The init_expression field can simply beleft 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 before the loop was entered. A for loop that has its looping condition field omitted effectively sets up an infinite loop, that is a loop that theoretically willbe executed for ever.

    For loop example program:

    /* The following is an example that finds the sum of the first fifteen positivenatural numbers*/#include < stdio.h > //Include stdio.h filevoid main() //start main program{

    int I; //declare variableint sum=0,sum_of_squares=0; //declare and initialize variable.for(I=0;I < = 30; I+=2) //for loop

  • 8/6/2019 Branching and Looping

    25/34

    {sum+=I; //add the value of I and store it to sumsum_of_squares+=I*I; //find the square value and add it to sum_of_squares} //end of for loopprintf(Sum of first 15 positive even numbers=%d\n,sum); //Print sumprintf(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 engineering problems is realized when decision-making becomes formalized and possible,and when complex operations and calculations can be done repetitively. Coupled with flexible visualization tools these features of MATLAB make it one of the mos

    t commonly adopted computational environments for solving engineering design problems. MATLAB has built-in commands and functions for logical operations and conditional branching that make it possible to execute different code segments in different cases. In addition, different commands are available to structure looping operations that execute code segments repetitively either deterministically or coupled to condition statements.

    Relational Operators and Functions

    The usual relational and logical tests associated with mathematical inequality statements (which Im sure youve all seen before) can be accomplished in MATLAB. MATLAB typically executes the required test and returns a true result (1) or falseresult (0) to a workspace variable. These logical tests can be combined to makefairly complex decisions, and tables of both relational and logical operators are provided on pgs. 249 and 250. Some simple examples illustrate the idea I think.

    a=2;b=7;

    c=(a==b)

    c=ab

    c=(ad)

  • 8/6/2019 Branching and Looping

    26/34

    c=(a>b)(b>d)

    These logical operators also accept array arguments and work in much the same way. Thus,

    a=[2 3 5 9];;b=[0 3 7 6];

    c=(a==b)

    c=(a

  • 8/6/2019 Branching and Looping

    27/34

    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 error message if x>1.

    Specify the data to be used by the program. This is the input.

    x a real, scalar variable

    q a real, scalar integer

    Specify the information to be generated by the program. This is the output.

    th an angle in degrees

    Work through the solution steps by hand or with a calculator; use a simpler 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.

  • 8/6/2019 Branching and Looping

    28/34

    Looping the Loop in MATLAB

    If is fortuitous that MATLAB, like most other computer languages, provides several mechanisms for repetitively executing code segments. Weve seen already how useful this might prove to be when we need to repeat the same calculation for a variety 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 ofthe different MATLAB commands that enable this type of program structure. Thereare 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 file. Basically, a loop variable (usually an integer) is established that increments from a defined minimum value to a defined maximum. For each value of the loopvariable, a defined code segment is executed. The calculated results for each pass through the loop are easily stored in array variables, either as successive columns 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 displayed 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

  • 8/6/2019 Branching and Looping

    29/34

    While loops are used when the termination of a looping process terminates when aparticular condition is satisfied. The syntax of the loop is similar to the forloop except that the termination condition is provided in a logical expressionassociated with the while loop. The help file for the while statement is provided in the handout but a simple example will suffice to illustrate the idea. The example above can be reformulated to use a while statement as:

    Example 3:

    x=1;

    while (x

  • 8/6/2019 Branching and Looping

    30/34

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

    Long loops are more memory efficient when the colon expression appears in the 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 non-zero elements. The expression is usually the result of expr rop expr where ropis ==, , =, 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

  • 8/6/2019 Branching and Looping

    31/34

    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 executed sequentially in the order in which they appear. This happens when no repetitions of certain calculations are necessary . However, in practice, we have a number of situations where we may have to change the order of execution of statementsbased on certain conditions are met.

    C language possesses such decision making capabilities and supports the following statements known as control or decision-making statements.

    1. if statementswitch statementConditional operator statementgoto statementThis article will focus on the if statement. Rest all will be discussed in the next article.

    Decision making if statement

    The if statement is a powerful decision making statement and is used to controlthe flow of execution of statements. It is basically a two-way decision statement 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 onwhether the value of the expression (relation or condition) is ' true ' (non-zero) or ' false ' (zero), it transfers the control to a particular statement. Thispoint of program has two paths to follow , one for the true condition and the other 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

  • 8/6/2019 Branching and Looping

    32/34

    if...else statementNested if...else statementelse if ladder.Simple if statementThe 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 test expression is true, the statement-block will be executed; otherwise the statement-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 executed 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. Ifx is 1 then y gets incremented by 1 else it is not incremented if x is not equalto 1. Then the value of y gets printed.

    The ifelse statementThe if....else statement is an extension of the simple if statement. The generalform 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 following the if statement are executed; otherwise the false-block statement(s) are 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;.......

  • 8/6/2019 Branching and Looping

    33/34

    Nesting of ifelse statementsWhen 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 continuesto perform the second test. If the condition-2 is true, the statement-1 will beevaluated; otherwise the statement-2 will be evaluated and then the control istransferred to the statement-x.

    The else if ladderThere is another way of putting ifs together when multipath decisions are involved. A multipath decision is a chain of ifs in which the statement associated with 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;elsedefault statement;statement x;

    This construct is known as the else if ladder. The conditions are evaluated fromthe top (of the ladder), downwards. As soon as a true condition is found, the statement associated with is executed and the control is transferred to the 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.

    Example :Let us consider an example of grading the students in an academic institution. The grading is done according to the following rules:

    Average marks Grade

    80-100 Honours60- 79 First Division50- 59 Second Division

  • 8/6/2019 Branching and Looping

    34/34

    40- 49 Third Division0- 39 Fail

    This grading can be done using the else if ladder follows:

    if (marks > 79)grade = "Honours";

    elseif (marks >59)

    grade = "First Division";elseif (marks > 49)

    grade = "Second Division";elseif (marks > 39)

    grade = "Third division";else

    grade = "Fail";

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