Problem Solving: Algorithm design

From Wikibooks, open books for an open world
Jump to navigation Jump to search

UNIT 1 - ⇑ Problem Solving ⇑

← Finite state machines Algorithm design Trace tables →


Algorithm - a set of instructions independent of any programming language that calculates a function or solves a problem.


Express the solution to a simple problem as an algorithm using flowcharts, pseudo-code or structured English and the standard constructs:

Sequence[edit | edit source]

performing or operating each step consecutively in the order they arise

Console.writeline("This is line 1")
Console.writeline("This is line 2")
Console.writeline("This is line 3")
  1. include<stdio.h>

int main() {

   // Read n
   int n;
   printf("Enter number n : ");
   scanf("%d", &n);

   // Declare sum to 0 
   // counter variable i to 1
   int sum = 0;
   int i = 1;

   // loop to input n numbers
   // loop continues until i<=n
   for(i=1;i<=n;i++){
       // read num
       int num ;
       printf("Enter number %d: ", i);
       scanf("%d", &num);

       // update sum to sum + num
       sum = sum + num;
   }

   // print sum
   printf("Sum of given numbers is %d", sum);
   return 0;

}

Selection[edit | edit source]

Selection is choosing a step

If x > 0 then
   Console.writeline("x is positive")
End If
If x = 0 then
   Console.writeline("x equals 0")
End If
If x < 0 then
   Console.writeline("x is negative")
End If

Repetition[edit | edit source]

A sequence of steps that loop until a requirement is met

x = 0
y = 5
Do
   x = x + 1
Loop Until x = y


UNIT 1 - ⇑ Problem Solving ⇑

← Finite state machines Algorithm design Trace tables →