C Language : Write the Algorithm for Decision Structures and Looping Structures


Algorithm for Decision Structures & Looping Structures

Decision Structures : Two - Way Selection

If - Else :

    if condition
      True alternative
    else
      False alternative
    end if

Example :

      if A > B then
        Write ( A )
      else 
        Write ( B )
      end if

Nested - If :

    if condition
      True alternative
    else
      False alternative
    end if

    else
      False alternative
    end if

Example : Finding the maximum of three numbers using Nested - If

    Read (A, B, C)
    If A > B then 
      if A > C then
        max <- A
      else
        max <- C
      end if   else if B > C then
      max <- B
    else
      max <- C
    end if
  end if
  Write("Largest value is ", max)
  Halt

Decision Structure : Multi - Way Selection

  Switch - Case :
    select (expression) from
      {
        case val1 :
          statements;
          break;
        case val2 :
          statements;
          break;
        --------
        --------
        default;
      }

Looping Structure : repeat....while

repeat through step Sn while condition.
  -The steps specified in the repeat through statement is the range of loop.
  -Sn - steps from repeat statement up to and including step Sn.
Example : Read numbers fro keyboard & print total.

  1. Start
  2. Sum <- 0
  3. Read (num)
  4. repeat thru step 6 while num > 0
  5. Sum <- Sum + num
  6. Read (num)
  7. Write (Sum)
  8. Stop

Looping Structure : for

  • used if number of repetitions are known before.
  • repeat range of loop for values of loop_control_variable.

Example :

  1. Repeat through step n for i <- 1 to 10
  2. Repeat for val <- 1 to N
    ------------
    ------------
    End repeat
  3. Repeat thru step 10 for index -9 to -3 by 3
  4. Repeat for count <- 2 to 18 by 2

Example : Factorial of a Given Number

  1. Start
  2. Read ( N )
  3. Fact <- 1
  4. Repeat for i <- N to 1 by -1
    fact <- fact * 1
    End repeat
  5. Write ("factorial of N is ", fact)
  6. Stop

Looping Structure : Do - While

Used when the loop need to be executed at least once.
the loop repeat until the condition is satisfied.

Repeat for i <- 1 to N
      ------
      ------
     if condition then
      end repeat until condition
      Exit loop
      End if
       ------
       ------
      End repeat
0 Komentar untuk "C Language : Write the Algorithm for Decision Structures and Looping Structures"

Back To Top