rev='made'/> name='keywords'/> name='author'/> ANURANAN: Control Structure

Welcome Note

Hi,
I'm Anisuzzaman Babla . I am a full stack Android Application Developer. I am working with Android for more than two years. I have completed my graduation from IIT, Jahangirnagar University. I have developed a series of commercially successful apps on Android. Moreover, 10+ of my Apps are live at Google play store. .
Thank You

Control Structure



Control Structure
Algorithm Development
So far, we considered very simple programs (read, compute, print)
Top-down Design
Start from the big picture
Use a process called divide-and-conquer
Keep dividing the problem until steps are detailed enough to convert to a program
Refinement with Pseudo-code (English like statements) and Flowchart (diagram, graph)
Pseudo-code Notation and Flowchart Symbols
Structured Programming
Sequence
Selection
Repetition
Sequence
Selection
Repetition
Extras   
Evaluation of alternative solution
A problem can be solved in many different ways
Which is the best (e.g, faster, less memory req)
Error condition
Do not trust user! Check the data. A=b/c;
Be clear about specifications
Generation of Test Data
Test each of the error conditions
Program validation and verification
Program walkthrough
Conditional Expressions
Selection and repetition structures use conditions, so we will first discuss them
A condition is an expression (e.g., x= a > b) that can be evaluated to be
TRUE (any value > 0) or
FALSE (value of 0)
Conditional Expression is composed of expressions combined with relational and/or logical operators
Relational Operators
==                           equality                                                (x == 3)
!=                            non equality                       (y != 0)
<                             less than                                              (x < y)
>                             greater than                       (y > 10)
<=                           less than equal to            (x <= 0)
>=                           greater than equal to   (x >= y)
!!! a==b  vs.  a=b !!!
Examples
A < B
D= b > c;
If (D)
                                A=b+c;
Mixing with arithmetic op
X+Y >= K/3
Logical Operators
!                             not              !(x==0)
&&                         and        (x>=0) && (x<=10)
||                           or          (x>0) || (x<0)
Examples
A<B && C>=5
A+B * 2 < 5 && 4>=A/2 || T-2 < 10
A < B < C  ????
A<B<C  is not the same as 
(A<B) && (B<C)
Precedence for Arithmetic, Relational, and Logical Operators
Exercise
Assume that following variables are declared
a = 5.5   b = 1.5    k = -3
Are the following true or false
a < 10.0 + k
a + b >= 6.5
k != a-b
!(a == 3*b)
a<10 && a>5
Selection Statements
if
if else
switch
if statement
if(Boolean expression) 
                                statement;         /* single statement */
if(Boolean expression) {
                /* more than one statement */
                                statement1;
                                               
                                statement n;
   }
if statement - examples
if else statement
if(Boolean expression)
                                statement;
                else
                                statement;
if(Boolean expression) {
                                statement block
                } else {
                                statement block
                }
if else statement
What does the following program do?
Assume that x, y, temp are declared.
                int x=10, y=20, temp;
   if (x > y)
                  temp = x;
                else
                  temp = y;
if else statement
if (x>y)
                temp = x;
else
                temp = y;
Exercise
Write an if-else statement to find both the maximum and minimum of two numbers.
Assume that x, y, min, max are declared.
if (x>y) {                                               Ex:           x = 10, y = 5
  max = x;                                                             x = 3,   y = 4
  min = y;                                                              x = 6,   y = 6
} else {                                                 
   max = y;
   min = x;
}
nested if-else
Exercise
Exercise
Given a score and the following grading scale write a program to find the corresponding grade.
                90-100                   A
                80-89                     B
                70-79                     C
                60-69                     D
   0-59                    F
Solution-1
   if ((score >= 90) && (score <=100))
    grade = 'A';
  else if ((score >= 80) && (score <= 89))
    grade = 'B';
  else if ((score >= 70) && (score <= 79))
    grade = 'C';
  else if ((score >= 60) && (score <= 69))
    grade = ‘D';
  else if ((score >= 0) && (score <= 59))
    grade = ‘F';
  else
    printf("Invalide Score\n");
Exercise: Find the value of a
Exercise: Find the value of a
Exercise: which task takes more time
Suppose we have two tasks A and B
A takes Ah hours, Am minutes, and As seconds
B takes Bh hours, Bm minutes, and Bs seconds
Write if-else statements to print out which task takes more time?
Indentation
Exercise
What is the output of the following program
 int a = 5, b = 3;
More selection examples
Max, Min, Median
Write a program that reads 3 numbers a, b and c from user and computes minimum, median and maximum of the numbers.
Example:
a = 2, b = 5, c = 3
minimum = 2, maximum = 5, median = 3
a = 2, b = 2, c = 3
minimum = 2, maximum = 3, median = 2
Region in a plane
Write a program that reads a point 
                (x, y) from user and prints its region
Write if-else  statement
if (score > 70) {
                printf(“You Pass\n”);
                if (age > 18) {
                                 printf(“Good job \n”);
                } else {
                                 printf(“Excellent job\n”);
                }
} else {
                printf(“You Fail\n”);
                if (age > 18) {
                                 printf(“ Very bad \n”);
                } else {
                                 printf(“ Don’t worry \n”);
                }
    printf(“ Good luck next time \n”);
}
Another if-else à flowchart
Triangle inequality
Suppose we want to check if we can make a triangle using a, b, c
Charge for money transfer
Suppose you transfer $N and bank’s charge occurs as follows.
Write a program that reads N and computes cost
Spell out a number in text
using if-else and switch
Write a program that reads a number between 1 and 999 from user and spells out it in English.
For example:
453         à Four hundred fifty three
37                           à Thirty seven
204         à Two hundred four
Loop (Repetition) Structures
Problem: Conversion table
degrees à radians
Degrees to Radians
    0                          0.000000
    10                       0.174533
    20       0.349066
    30       0.523599
               
                340         5.934120
   350      6.108653
   360      6.283186
Sequential Solution
#include <stdio.h>
#define PI 3.141593
int main(void)
{
   int degrees=0;
   double radians;
   printf("Degrees to Radians \n");
 
  degrees = 0;
  radians = degrees*PI/180;
  printf("%d %f \n", degrees, radians);
  degrees = 10;
  radians = degrees*PI/180;
  printf(“%d %f \n", degrees, radians);
  degrees = 20;
  radians = degrees*PI/180;
  printf(“%d %f \n", degrees, radians);
  degrees = 360;
  radians = degrees*PI/180;
  printf(“%d %f \n", degrees, radians);
}
Loop Solution
#include <stdio.h>
#define PI 3.141593
int main(void)
{
   int degrees=0;
   double radians;
   printf("Degrees to Radians \n");
 
   while (degrees <= 360)   {
      radians = degrees*PI/180;
      printf(“%d %f \n", degrees, radians);
      degrees += 10;
   }
 }
Loop (Repetition) Structures
while statement
do while statement
for statement
Two new statements used with loops
 break and continue
while statement
while(expression)
                                statement;
while(expression) {
                                statement;
                                statement;
                                                .
                }
The while Control Structure
Example: 
x = 1;     i = 2;     
while (i <= 9) {
                x = x * i;              
                i = i + 1;               
}                                                             
Example
#include <stdio.h>
#define PI 3.141593
int main(void)
{
   int degrees=0;
   double radians;
   printf("Degrees to Radians \n");
   while (degrees <= 360)
   {
      radians = degrees*PI/180;
      printf("%6i %9.6f \n", degrees, radians);
      degrees += 10;
   }
return 0;
}
do while
do
                                statement;
                while(expression);
do {
                                statement1;
                                statement2;
                                                .
                } while(expression);
S        note - the expression is tested after the statement(s) are executed, so statements are executed at least once.
4.8          The do…while Repetition Statement
Flowchart of the do…while repetition statement
Example
#include <stdio.h>
#define PI 3.141593
int main(void)
{
  int degrees=0;
   double radians;
   printf("Degrees to Radians \n");
   do
   {
      radians = degrees*PI/180;
      printf("%6i %9.6f \n",degrees,radians);
      degrees += 10;
   } while (degrees <= 360);
   return 0;
}
for statement
for(initialization; test; increment or decrement)
                                statement;
for(initialization; test; increment or decrement)
                {
                                statement;
                                statement;
                                                .
                }
Example
#include <stdio.h>
#define PI 3.141593
int main(void)
{
   int degrees;
   double radians;
   printf("Degrees to Radians \n");
   for (degrees=0; degrees<=360; degrees+=10)
   {
      radians = degrees*PI/180;
      printf("%6i %9.6f \n", degrees, radians);
   }
   return 0;
}
4.4          The for Repetition Statement
4.4          The for Repetition Statement
Format when using for loops
for ( initialization; loopContinuationTest; increment )
   statement
Example: 
for(counter = 1; counter <= 10; counter++ )
   printf( "%d\n", counter );
Prints the integers from one to ten
Flow Chart of the Example for Loop        
The for Repetition Statement
For loops can usually be rewritten as while loops:
                initialization;
while ( loopContinuationTest ) {
   statement;
   increment;
}
Initialization and increment
Can be more than one, comma-separated lists of statements
Can even add the counter variable declaration in initialization
Example:
for (int i = 0, j = 0;  j + i <= 10; j++, i++)
   printf( "%d\n", j + i );
Examples
Exercise
                Determine the number of times that each of the following for loops are executed.
                                for (k=3; k<=10; k++) {
                                    statements;
                                }
                                for (k=3; k<=10; ++k) {
                                    statements;
                                }
                                for(count=-2;count<=5; count++) {
                                    statements;
                                }
               
Example
What will be the output of the following program, also show how values of variables change in the memory.
int sum1, sum2, k;
sum1 = 0;
sum2 = 0;
for( k = 1; k < 5; k++) {
    if( k % 2 == 0)
      sum1 =sum1 + k;
    else
      sum2 = sum2 + k;
}
printf(“sum1 is %d\n”, sum1);
printf(“sum2 is %d\n”, sum2);
break statement
break;
terminates loop
execution continues with the first statement following the loop
sum = 0;
for (k=1; k<=5; k++) {
                scanf(“%lf”,&x);
    if (x > 10.0)
        break;
    sum +=x;
}
printf(“Sum = %f \n”,sum);

continue statement
continue;
forces next iteration of the loop, skipping any remaining statements in the loop
sum = 0;
for (k=1; k<=5; k++) {
                scanf(“%lf”,&x);
    if (x > 10.0)
        continue;
    sum +=x;
}
printf(“Sum = %f \n”,sum);
Example: A man walks
Suppose a man (say, A) stands at (0, 0) and waits for user to give him the direction and distance to go.
User may enter N E W S for north, east, west, south, and any value for distance.
When user enters 0 as direction, stop and print out the location where the man stopped
Example: what will be the output
int main()
{
  int a, b, c;
  a=5;
  while(a > 2) {
    for (b = a ; b < 2 * a ; b++ ) {
         c = a + b;
         if (c < 8) continue;
         if (c > 11) break;
         printf( “a = %d   b = %d    c = %d \n”, a, b, c);
    } /* end of for-loop */
    a--;
  } /* end of while loop */
}
More loop examples
Exercise
What is the output of the following program?
for (i=1; i<=5; i++) {
      for (j=1; j<=4; j++){
          printf(“*”);
                                  }
      printf(“\n”);
}
Exercise
What is the output of the following program?
for (i=1; i<=5; i++) {
      for (j=1; j<=i; j++){
           printf(“*”);
      }
      printf(“\n”);
}
Example: nested loops to generate the following output
i=1 * 
i=2 + +
i=3 * * *
i=4 + + + +
i=5 * * * * *
Exercise: Modify the following program to produce the output.
for (i=A; i<=B; i++) {
      for (j=C; j<=D; j++) {
          printf(“*”);
      }
      printf(“\n”);
}
Exercise
Write a program using loop statements to produce the output.
For vs. while loop
Convert the following for loop to while loop
                                for( i=5; i<10; i++) {
                   pritntf(“ i = %d \n”, i);
                                }
                                i=5;
                                while(i<10){
                                   pritntf(“ i = %d \n”, i);
                                   i++;                    
     }
For vs. while loop : Convert the following for loop to while loop
                for( i=5; i<10; i++) {
                   printf(“AAA %d \n”, i);
                   if (i % 2==0) continue;
     pritntf(“BBB %d \n”, i);
                }
Compute xy when y is integer
Suppose we don’t have pow(x,y) and y is integer, write a loop to compute xy
Exercise: sum
Write a program to compute the following
Exercise: sum
Write a program to compute the following
Exercise: ln 2
Write a program to compute the following
Exercise: ex
Write C program that reads the value of x and n from the keyboard and then approximately computes the value of  using the following formula:
Then compare your approximate result to the one returned by exp(x) in C library, and print out whether your approximation is higher or lower.
Exercise: sin x
Compute sin x using
Example
Write a program that prints in two columns n even numbers starting from 2, and a running sum of those values. For example suppose user enters 5 for n, then the program should generate the following table:
Enter  n (the number of even numbers): 5
Value   Sum
  2         2
  4         6
  6        12
  8        20
10        30

No comments:

Post a Comment