SlideShare ist ein Scribd-Unternehmen logo
1 von 61
Control Statements




Autumn      Programming and   1
What do they do?

• Allow different sets of instructions to be
  executed depending on the outcome of a
  logical test.
  – Whether TRUE or FALSE.
  – This is called branching.
• Some applications may also require that a
  set of instructions be executed repeatedly,
  possibly again based on some condition.
  – This is called looping.



Autumn          Programming and    2
How do we specify the conditions?

• Using relational operators.
  – Four relation operators:     <, <=, >, >=
  – Two equality operations:     ==, !=
• Using logical operators / connectives.
  – Two logical connectives:     &&, | |
  – Unary negation operator:     !




Autumn         Programming and      3
Examples

  count <= 100
  (math+phys+chem)/3 >= 60
  (sex==‘M’) && (age>=21)
  (marks>=80) && (marks<90)
  (balance>5000) | | (no_of_trans>25)
  ! (grade==‘A’)
  ! ((x>20) && (y<16))




Autumn         Programming and          4
The conditions evaluate to …

• Zero
  – Indicates FALSE.
• Non-zero
  – Indicates TRUE.
  – Typically the condition TRUE is represented by
    the value ‘1’.




Autumn         Programming and        5
Branching: The if Statement

• Diamond symbol (decision symbol) -
  indicates decision is to be made.
  – Contains an expression that can be TRUE or
    FALSE.
  – Test the condition, and follow appropriate path.
• Single-entry / single-exit structure.
• General syntax:
     if (condition) { …….. }
  – If there is a single statement in the block, the
    braces can be omitted.


Autumn            Programming and        6
The if Selection Structure




                  true
    grade >= 60          print “Passed”

                                          A decision can be made on
                                          any expression.
                                          zero - false
     false
                                          nonzero - true


                                          if (grade>=60)
                                            printf(“Passed n”);

Autumn            Programming and               7
Example
  #include <stdio.h>
  main()
  {
     int a,b,c;
     scanf (“%d %d %d”, &a, &b, &c);
     if ((a>=b) && (a>=c))
         printf (“n The largest number is: %d”, a);
     if ((b>=a) && (b>=c))
         printf (“n The largest number is: %d”, b);
    if ((c>=a) && (c>=b))
         printf (“n The largest number is: %d”, c);
  }




Autumn               Programming and                   8
Branching: The if-else Statement

• Also a single-entry / single-exit structure.
• Allows us to specify two alternate blocks of
  statements, one of which is executed
  depending on the outcome of the condition.
• General syntax:
     if (condition) { …… block 1 ……. }
     else { …….. block 2 …….. }
  – If a block contains a single statement, the braces
    can be deleted.




Autumn          Programming and          11
The if/else Selection Structure




                 false                     true
                             grade >= 60


print “Failed”                                     print “Passed”




    if ( grade >= 60 )
          printf( "Passedn");
    else
           printf( "Failedn");


  Autumn                 Programming and          12
if-else syntax

  if ( expression )                  if ( expression )
     {                                  {
                                              statement_1;
          statement1;                         statement_2;
          statement2;                             .
              .                               statement_n;
          statement_n;                    }
       }                             else
                                     {
                                          Statement_1;
                                             .
if (grade>=60)                             Statement_m;
  printf(“Passed n”);                }
                                        if ( grade >= 60 )
                                              printf( "Passedn");
                                        else
                                               printf( "Failedn");
  Autumn                 Programming and             13
Nesting of if-else Structures

• It is possible to nest if-else statements,
  one within another.
• All if statements may not be having the
  “else” part.
  – Confusion??
• Rule to be remembered:
  – An “else” clause is associated with the closest
    preceding unmatched “if”.




Autumn          Programming and        14
if e1 s1
else if e2 s2

if e1 s1
else if e2 s2
else s3

if e1 if e2 s1
else s2
                         ?
else s3

if e1 if e2 s1
else s2

Autumn           Programming and   15
if e1 s1                       if e1 s1
else if e2 s2                  else if e2 s2

if e1 s1                       if e1 s1
else if e2 s2                  else if e2 s2
else s3                             else s3

if e1 if e2 s1                 if e1 if e2 s1
else s2                              else s2
else s3                        else s3

if e1 if e2 s1                 if e1 if e2 s1
else s2                               else s2

Autumn           Programming and         16
Example
  #include <stdio.h>
  main()
  {
     int a,b,c;
     scanf (“%d %d %d”, &a, &b, &c);
     if (a>=b)
         if (a>=c)
                 printf (“n The largest number is: %d”, a);
         else      printf (“n The largest number is: %d”, c);
    else
         if (b>=c)
                 printf (“n The largest number is: %d”, b);
         else      printf (“n The largest number is: %d”, c);
  }


Autumn               Programming and                   17
Example
  #include <stdio.h>
  main()
  {
     int a,b,c;
     scanf (“%d %d %d”, &a, &b, &c);
     if ((a>=b) && (a>=c))
         printf (“n The largest number is: %d”, a);
     else if (b>c)
         printf (“n The largest number is: %d”, b);
    else
         printf (“n The largest number is: %d”, c);
  }




Autumn               Programming and                   18
Confusing Equality (==) and Assignment (=) Operators


• Dangerous error
   – Does not ordinarily cause syntax errors
   – Any expression that produces a value can be used in control
     structures
   – Nonzero values are true, zero values are false
• Example:
     if ( payCode == 4 )
        printf( "You get a bonus!n" );

   Checks paycode, if it is 4 then a bonus is awarded


               Equality check improper
                Equality check proper
               if ( payCode = 4 )
                if ( payCode == 4 )
                  printf( "You get a bonus!n" );
                   printf( "You get a bonus!n" );
Autumn                Programming and           20
Generalization of expression evaluation in C

• Assignment (=) operation is also a part of
  expression.

                   i=3;                Returns the value 3
                                       after assigning it to i.

int i=4, j ;                                int i=4, j ;
                          j?
if(i=3)                                    if(i==3)
  j=0;                                       j=0;
               Whatever be the value of i,
else                                       else               j=1
               j is always 0.
  j=1;                                       j=1;

Autumn               Programming and            21
More about expressions

• Increment (++) and Decrement (--)Operations

  Prefix operation         ++i;                  --i;
    First increment / decrement and then used in evaluation
  Postfix operation           i++;               i--;
  increment / decrement operation after being used in evaluation

 int t,m=1;                             int t,m=1;
                    m=2;                                  m=2;
 t=++m;             t=2;                                  t=1;
                                        t=m++;


Autumn             Programming and                22
Some More Examples

Initial values :: a = 10; b = 20;

x = 50 + ++a;
                       a = 11, x = 61

x = 50 + a++;
                       x = 60, a = 11

x = a++ + --b;
                   b = 19, x = 29, a = 11

x = a++ – ++a;          Undefined value (implementation
                        dependent)

Autumn               Programming and            25
Ternary conditional operator (?:)


   – Takes three arguments (condition, value if
     true, value if false)
   – Returns the evaluated value
     accordingly.
     grade >= 60 ? printf( “Passedn” ) : printf( “Failedn” );

         (expr1)? (expr2): (expr3);

Example:
   interest = (balance>5000) ? balance*0.2 : balance*0.1;

                                          Returns a value
Autumn             Programming and           26
The switch Statement

• This causes a particular group of statements
  to be chosen from several available groups.
  – Uses “switch” statement and “case” labels.
  – Syntax of the “switch” statement:

     switch (expression) {
      case expression-1: { …….. }
      case expression-2: { …….. }

         case expression-m: { …….. }
         default: { ……… }
     }


Autumn             Programming and     28
The switch Multiple-Selection Structure



                      true
       case a                case a action(s)      break

              false

                      true
       case b                case b action(s)      break
              false


          .
          .
          .



                      true
       case z                case z action(s)      break
              false


  default action(s)




Autumn                   Programming and           29
Example

switch ( letter ) {
  case 'A':
        printf("First lettern");
        break;
  case 'Z':
        printf("Last lettern");
        break;
  default :
        printf("Middle lettern");
        break;
}




Autumn               Programming and   30
Example

switch (choice = toupper(getchar())) {

    case ‘R’:   printf (“RED n”);
                break;
    case ‘G’:   printf (“GREEN n”);
                break;
    case ‘B’:   printf (“BLUE n”);
                break;
    default:    printf (“Invalid choice n”);

}




Autumn               Programming and            31
Example

switch (choice = getchar()) {

    case ‘r’:
    case ‘R’:   printf (“RED n”);
                break;
    case ‘g’:
    case ‘G’:   printf (“GREEN n”);
                break;
    case ‘b’:
    case ‘B’:   printf (“BLUE n”);
                break;
    default:    printf (“Invalid choice n”);

}

Autumn               Programming and            33
The break Statement

• Used to exit from a switch or terminate
  from a loop.
  – Already illustrated in the switch examples.
• With respect to “switch”, the “break”
  statement causes a transfer of control out
  of the entire “switch” statement, to the
  first statement following the “switch”
  statement.




Autumn         Programming and         34
The Essentials of Repetition

• Loop
   – Group of instructions computer executes repeatedly while
     some condition remains true
• Counter-controlled repetition
   – Definite repetition - know how many times loop will execute
   – Control variable used to count repetitions


• Sentinel-controlled repetition
   – Indefinite repetition
   – Used when number of repetitions not known
   – Sentinel value indicates "end of data"




Autumn              Programming and                36
Counter-Controlled Repetition

• Counter-controlled repetition requires
   – name of a control variable (or loop counter).
   – initial value of the control variable.
   – condition that tests for the final value of the control
     variable (i.e., whether looping should continue).
   – increment (or decrement) by which the control variable
     is modified each time through the loop.

         int counter =1;           //initialization
             int counter;
         while (counter <= 10) {     //repetition condition
             for (counter=1;counter<=10;counter++)
                           printf( "%dn", counter );
               printf(“%dn”,counter);
                           ++counter;             //increment
                         }

Autumn               Programming and                  37
while Statement

while (condition)
  statement_to_repeat;
                                 /* Weight loss program */
                                 while ( weight > 65 ) {
while (condition) {                  printf("Go, exercise, ");
       statement_1;                  printf("then come back. n");
                                     printf("Enter your weight: ");
       ...
                                     scanf("%d", &weight);
       statement_N;                 }
} int digit = 0;

   while (digit <= 9)
    printf (“%d n”, digit++);

Autumn             Programming and               38
false
             C
                                Single-entry /
              true                single-exit
                                   structure
         statement(s)




Autumn        Programming and   39
do-while Statement


do {
                                     /* Weight loss program */
 statement-1                         do {
 statement-2                             printf("Go, exercise, ");
     .                                   printf("then come back. n");
                                         printf("Enter your weight: ");
     .
                                         scanf("%d", &weight);
 statement-n
                                        } while ( weight > 65 ) ;

            } while ( condition );

                                        At least one round
                                        of exercise ensured.

   Autumn              Programming and               40
statement(s)

                                           Single-entry /
                                             single-exit
                        false                 structure
              C
                                int digit = 0;
               true
                                do
                                  printf (“%d n”, digit++);
                                while (digit <= 9);
Autumn        Programming and               41
for Statement

for (initial; condition; iteration)
          statement_to_repeat;
                                                 All are expressions.
                                                 initial expr1
for (initial; condition; iteration) {
                                                 condition expr2
          statement_1;
                                                 iterationexpr3
          ...
          statement_N;
                                  fact = 1; /* Calculate 10 ! */
}
                                  for ( i = 1; i < =10; i++)
                                                                   No
                                      fact = fact * i;             semicolon
                                                                   after last
                                                                   expression




Autumn                   Programming and                    42
• How it works?
  – “expression1” is used to initialize some variable
    (called index) that controls the looping action.
  – “expression2” represents a condition that must
    be true for the loop to continue.
  – “expression3” is used to alter the value of the
    index initially assigned by “expression1”.

     int digit;

     for (digit=0; digit<=9; digit++)
             printf (“%d n”, digit);

Autumn            Programming and       43
• How it works?
  – “expression1” is used to initialize some variable
    (called index) that controls the looping action.
  – “expression2” represents a condition that must
    be true for the loop to continue.
  – “expression3” is used to alter the value of the
    index initially assigned by “expression1”.




Autumn         Programming and         44
int digit;

         expression1     for (digit=0; digit<=9; digit++)
                                 printf (“%d n”, digit);

                        false
         expression2                   Single-entry /
                                         single-exit
                true                      structure
         statement(s)


         expression3


Autumn        Programming and           45
The For Structure: Notes and Observations

• Arithmetic expressions
   – Initialization, loop-continuation, and increment can
      contain arithmetic expressions.
   – e.g. Let x = 2 and y = 10                        Increment
   for ( j = x; j <= 4 * x * y; j += y / x )

      is equivalent to    Initialization
                                              Loop continuation
   for ( j = 2; j <= 80; j += 5 )
• "Increment" may be negative (decrement)
• If loop continuation condition initially false
    – Body of for structure not performed
    – Control proceeds with statement after for structure



Autumn                   Programming and       46
for :: Examples

int fact = 1, i;                  int sum = 0, N, count;

for (i=1; i<=10; i++)             scanf (“%d”, &N);
   fact = fact * i;
                                  for (i=1; i<=N, i++)
                                     sum = sum + i * i;

                                  printf (“%d n”, sum);




Autumn                  Programming and           47
• The comma operator
  – We can give several statements separated by
    commas in place of “expression1”, “expression2”,
    and “expression3”.

     for (fact=1, i=1; i<=10; i++)
       fact = fact * i;

     for (sum=0, i=1; i<=N; i++)
       sum = sum + i * i;




Autumn            Programming and    48
Specifying “Infinite Loop”

     while (1) {                      for (; ;)
       statements                     {
     }                                   statements
                                      }




                      do {
                        statements
                      } while (1);




Autumn              Programming and     49
break Statement
 •   Break out of the loop { }
      – can use with
          • while
          • do while
          • for
          • switch
      – does not work with
          • if {}
          • else {}


Causes immediate exit from a while, for, do/while or switch structure

Program execution continues with the first statement after the
structure

Common uses of the break statement
   Escape early from a loop
   Skip the remainder of a switch structure

Autumn                   Programming and         50
A Complete Example

   #include <stdio.h>
   main()
   {
      int fact, i;
       fact = 1; i = 1;
       while ( i<10 ) {             /* run loop –break when fact >100*/
            fact = fact * i;
            if ( fact > 100 ) {
                       printf ("Factorial of %d above 100", i);
                       break;             /* break out of the while loop */
            }
            i ++ ;
       }
   }



Autumn                    Programming and                51
continue Statement

• continue
   – Skips the remaining statements in the body of a while,
     for or do/while structure
       • Proceeds with the next iteration of the loop
   – while and do/while
       • Loop-continuation test is evaluated immediately after the
         continue statement is executed
   – for structure
       • Increment expression is executed, then the loop-
         continuation test is evaluated.
         expression3 is evaluated, then expression2 is
         evaluated.




Autumn               Programming and                    52
An Example with “break” & “continue”

   fact = 1; i = 1;      /* a program to calculate 10 !
   while (1) {
      fact = fact * i;
      i ++ ;
      if ( i<10 )
            continue;    /* not done yet ! Go to loop and
                                 perform next iteration*/
       break;
   }




Autumn             Programming and            53
ANNOUNCEMENT REGARDING
          CLASS TEST 1




Autumn    Programming and   54
Time and Venue

• Date: February 8, 2007
• Time: 6 PM to 7 PM
  – Students must occupy seat within 5:45 PM,
    and carry identity card with them.
• Venue: VIKRAMSHILA COMPLEX
  –   Section 1 ::             Room V1
  –   Section 2 ::             Room V2
  –   Section 3 ::             Room V3
  –   Section 4 ::             Room V4
  –   Section 5 (AE to EG)::   Room V1
  –   Section 5 (Rest)::       Room V2

Autumn           Programming and     55
Syllabus

•   Variables and constants
•   Number system
•   Assignments
•   Conditional statements
•   Loops
•   Simple input/output




Autumn         Programming and   56
Some Examples




Autumn   Programming and   57
Example 1: Test if a number is prime or not

#include <stdio.h>
main()
{
   int n, i=2;
   scanf (“%d”, &n);
   while (i < n) {
         if (n % i == 0) {
                   printf (“%d is not a prime n”, n);
                   exit;
         }
         i++;
   }
   printf (“%d is a prime n”, n);
}




Autumn                  Programming and                  58
More efficient??
#include <stdio.h>
main()
{
   int n, i=3;
   scanf (“%d”, &n);
   while (i < sqrt(n)) {
         if (n % i == 0) {
                    printf (“%d is not a prime n”, n);
                    exit;
         }
         i = i + 2;
   }
   printf (“%d is a prime n”, n);
}


Autumn                   Programming and                  59
Example 2: Find the sum of digits of a number

#include <stdio.h>
main()
{
   int n, sum=0;
   scanf (“%d”, &n);
   while (n != 0) {
         sum = sum + (n % 10);
         n = n / 10;
   }
   printf (“The sum of digits of the number is %d n”, sum);
}




Autumn                Programming and                 60
Example 3: Decimal to binary conversion

#include <stdio.h>
main()
{
   int dec;
   scanf (“%d”, &dec);
   do
   {
         printf (“%2d”, (dec % 2));
         dec = dec / 2;
   } while (dec != 0);
   printf (“n”);
}




Autumn                 Programming and   61
Example 4: Compute GCD of two numbers

#include <stdio.h>                              12 ) 45 ( 3
main()
                                                     36
{
   int A, B, temp;                                    9 ) 12 ( 1
   scanf (%d %d”, &A, &B);
                                                           9
   if (A > B) { temp = A; A = B; B = temp; }
   while ((B % A) != 0) {                                  3 ) 9 ( 3
         temp = B % A;                                         9
         B = A;
                                                               0
         A = temp;
   }
   printf (“The GCD is %d”, A);        Initial:     A=12, B=45
}                                      Iteration 1: temp=9, B=12,A=9
                                  Iteration 2: temp=3, B=9, A=3
                                      B % A = 0  GCD is 3
   Autumn              Programming and             62
Shortcuts in Assignments

• Additional assignment operators:
     + =,   – =,   * =,   / =,   %=


  a += b is equivalent to a = a + b
  a *= (b+10) is equivalent to a = a * (b + 10)
                                           and so on.




Autumn             Programming and       63
More about scanf and printf




Autumn         Programming and   64
Entering input data :: scanf function

• General syntax:
      scanf (control string, arg1, arg2, …, argn);
   – “control string refers to a string typically
     containing data types of the arguments to be
     read in;
   – the arguments arg1, arg2, … represent pointers
     to data items in memory.
      Example: scanf (%d %f %c”, &a, &average, &type);
• The control string consists of individual groups of
  characters, with one character group for each input
  data item.
   – ‘%’ sign, followed by a conversion character.


Autumn           Programming and            65
– Commonly used conversion characters:
     c     single character
     d     decimal integer
     f     floating-point number
     s     string terminated by null character
     X     hexadecimal integer
  – We can also specify the maximum field-width
    of a data item, by specifying a number
    indicating the field width before the
    conversion character.
     Example:   scanf (“%3d %5d”, &a, &b);




Autumn          Programming and              66
Writing output data :: printf function

• General syntax:
     printf (control string, arg1, arg2, …, argn);
  – “control string refers to a string containing
    formatting information and data types of the
    arguments to be output;
  – the arguments arg1, arg2, … represent the
    individual output data items.
• The conversion characters are the same
  as in scanf.



Autumn          Programming and         67
• Examples:
     printf (“The average of %d and %d is %f”, a, b, avg);
     printf (“Hello nGood nMorning n”);
     printf (“%3d %3d %5d”, a, b, a*b+2);
     printf (“%7.2f %5.1f”, x, y);


• Many more options are available:
  – Read from the book.
  – Practice them in the lab.
• String I/O:
  – Will be covered later in the class.

Autumn           Programming and              68
CLASS TEST 1

   February 9, 2007 :: 6:00 to 7:00 PM
          Vikramshila Complex
Room V1 :       Section 1, Section 5 (AE to EG)
Room V2 :       Section 2, Section 5 (the rest)
Room V3 :       Section 3
Room V4 :       Section 4
     Students must occupy seat on or before
        5:45 PM, and carry their ID cards.
    Syllabus: Variables and constants, number system, assignment
   statements, conditional statements and loops, simple input/output.


Autumn              Programming and                69

Weitere ähnliche Inhalte

Was ist angesagt?

FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3 rohassanie
 
Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CChapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CBUBT
 
BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018
BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018
BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018musadoto
 
Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C BUBT
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3rohassanie
 
Control structuresin c
Control structuresin cControl structuresin c
Control structuresin cVikash Dhal
 
Chapter 5 exercises Balagurusamy Programming ANSI in c
Chapter 5 exercises Balagurusamy Programming ANSI  in cChapter 5 exercises Balagurusamy Programming ANSI  in c
Chapter 5 exercises Balagurusamy Programming ANSI in cBUBT
 
3. control statements
3. control statements3. control statements
3. control statementsamar kakde
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02Suhail Akraam
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariTHE NORTHCAP UNIVERSITY
 
TMPA-2017: The Quest for Average Response Time
TMPA-2017: The Quest for Average Response TimeTMPA-2017: The Quest for Average Response Time
TMPA-2017: The Quest for Average Response TimeIosif Itkin
 

Was ist angesagt? (20)

FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
 
Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CChapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in C
 
BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018
BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018
BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018
 
control statement
control statement control statement
control statement
 
Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C
 
Cprogramcontrolifelseselection3
Cprogramcontrolifelseselection3Cprogramcontrolifelseselection3
Cprogramcontrolifelseselection3
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
Control structuresin c
Control structuresin cControl structuresin c
Control structuresin c
 
Chapter 5 exercises Balagurusamy Programming ANSI in c
Chapter 5 exercises Balagurusamy Programming ANSI  in cChapter 5 exercises Balagurusamy Programming ANSI  in c
Chapter 5 exercises Balagurusamy Programming ANSI in c
 
C1 - Insertion Sort
C1 - Insertion SortC1 - Insertion Sort
C1 - Insertion Sort
 
3. control statements
3. control statements3. control statements
3. control statements
 
Ansi c
Ansi cAnsi c
Ansi c
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
Chapter 00 revision
Chapter 00 revisionChapter 00 revision
Chapter 00 revision
 
L05if
L05ifL05if
L05if
 
Unit 2
Unit 2Unit 2
Unit 2
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan Kumari
 
TMPA-2017: The Quest for Average Response Time
TMPA-2017: The Quest for Average Response TimeTMPA-2017: The Quest for Average Response Time
TMPA-2017: The Quest for Average Response Time
 
Decision Making and Looping
Decision Making and LoopingDecision Making and Looping
Decision Making and Looping
 
C aptitude
C aptitudeC aptitude
C aptitude
 

Andere mochten auch (9)

L2 number
L2 numberL2 number
L2 number
 
L4 functions
L4 functionsL4 functions
L4 functions
 
Struct examples
Struct examplesStruct examples
Struct examples
 
L11 tree
L11 treeL11 tree
L11 tree
 
Snns
SnnsSnns
Snns
 
Extra problem for 1st yr
Extra problem for 1st yrExtra problem for 1st yr
Extra problem for 1st yr
 
Elimination
EliminationElimination
Elimination
 
19 - Amines - Wade 7th
19 - Amines - Wade 7th19 - Amines - Wade 7th
19 - Amines - Wade 7th
 
Aminas
AminasAminas
Aminas
 

Ähnlich wie L3 control

Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions imtiazalijoono
 
COM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingCOM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingHemantha Kulathilake
 
Conditional statements
Conditional statementsConditional statements
Conditional statementsNabishaAK
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptSanjjaayyy
 
C programming
C programmingC programming
C programmingXad Kuain
 
Chap7_b Control Statement Looping (3).pptx
Chap7_b Control Statement Looping (3).pptxChap7_b Control Statement Looping (3).pptx
Chap7_b Control Statement Looping (3).pptxFakhriyArif
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptxeaglesniper008
 
CONTROL FLOW in C.pptx
CONTROL FLOW in C.pptxCONTROL FLOW in C.pptx
CONTROL FLOW in C.pptxSmitaAparadh
 
unit 2-Control Structures.pptx
unit 2-Control Structures.pptxunit 2-Control Structures.pptx
unit 2-Control Structures.pptxishaparte4
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
 
Selection & Making Decisions in c
Selection & Making Decisions in cSelection & Making Decisions in c
Selection & Making Decisions in cyndaravind
 
programming c language.
programming c language. programming c language.
programming c language. Abdul Rehman
 

Ähnlich wie L3 control (20)

Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
Decision Making and Branching
Decision Making and BranchingDecision Making and Branching
Decision Making and Branching
 
COM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingCOM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & Branching
 
Conditional statements
Conditional statementsConditional statements
Conditional statements
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.ppt
 
C programming
C programmingC programming
C programming
 
175035 cse lab-03
175035 cse lab-03175035 cse lab-03
175035 cse lab-03
 
Chap7_b Control Statement Looping (3).pptx
Chap7_b Control Statement Looping (3).pptxChap7_b Control Statement Looping (3).pptx
Chap7_b Control Statement Looping (3).pptx
 
C if else
C if elseC if else
C if else
 
3 flow
3 flow3 flow
3 flow
 
3 flow
3 flow3 flow
3 flow
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptx
 
CONTROL FLOW in C.pptx
CONTROL FLOW in C.pptxCONTROL FLOW in C.pptx
CONTROL FLOW in C.pptx
 
unit 2-Control Structures.pptx
unit 2-Control Structures.pptxunit 2-Control Structures.pptx
unit 2-Control Structures.pptx
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
Control flow in c
Control flow in cControl flow in c
Control flow in c
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
Selection & Making Decisions in c
Selection & Making Decisions in cSelection & Making Decisions in c
Selection & Making Decisions in c
 
programming c language.
programming c language. programming c language.
programming c language.
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 

Mehr von mondalakash2012 (6)

Sn reaction
Sn reactionSn reaction
Sn reaction
 
Part i
Part iPart i
Part i
 
L12 complexity
L12 complexityL12 complexity
L12 complexity
 
L10 sorting-searching
L10 sorting-searchingL10 sorting-searching
L10 sorting-searching
 
L8 file
L8 fileL8 file
L8 file
 
L6 structure
L6 structureL6 structure
L6 structure
 

L3 control

  • 1. Control Statements Autumn Programming and 1
  • 2. What do they do? • Allow different sets of instructions to be executed depending on the outcome of a logical test. – Whether TRUE or FALSE. – This is called branching. • Some applications may also require that a set of instructions be executed repeatedly, possibly again based on some condition. – This is called looping. Autumn Programming and 2
  • 3. How do we specify the conditions? • Using relational operators. – Four relation operators: <, <=, >, >= – Two equality operations: ==, != • Using logical operators / connectives. – Two logical connectives: &&, | | – Unary negation operator: ! Autumn Programming and 3
  • 4. Examples count <= 100 (math+phys+chem)/3 >= 60 (sex==‘M’) && (age>=21) (marks>=80) && (marks<90) (balance>5000) | | (no_of_trans>25) ! (grade==‘A’) ! ((x>20) && (y<16)) Autumn Programming and 4
  • 5. The conditions evaluate to … • Zero – Indicates FALSE. • Non-zero – Indicates TRUE. – Typically the condition TRUE is represented by the value ‘1’. Autumn Programming and 5
  • 6. Branching: The if Statement • Diamond symbol (decision symbol) - indicates decision is to be made. – Contains an expression that can be TRUE or FALSE. – Test the condition, and follow appropriate path. • Single-entry / single-exit structure. • General syntax: if (condition) { …….. } – If there is a single statement in the block, the braces can be omitted. Autumn Programming and 6
  • 7. The if Selection Structure true grade >= 60 print “Passed” A decision can be made on any expression. zero - false false nonzero - true if (grade>=60) printf(“Passed n”); Autumn Programming and 7
  • 8. Example #include <stdio.h> main() { int a,b,c; scanf (“%d %d %d”, &a, &b, &c); if ((a>=b) && (a>=c)) printf (“n The largest number is: %d”, a); if ((b>=a) && (b>=c)) printf (“n The largest number is: %d”, b); if ((c>=a) && (c>=b)) printf (“n The largest number is: %d”, c); } Autumn Programming and 8
  • 9. Branching: The if-else Statement • Also a single-entry / single-exit structure. • Allows us to specify two alternate blocks of statements, one of which is executed depending on the outcome of the condition. • General syntax: if (condition) { …… block 1 ……. } else { …….. block 2 …….. } – If a block contains a single statement, the braces can be deleted. Autumn Programming and 11
  • 10. The if/else Selection Structure false true grade >= 60 print “Failed” print “Passed” if ( grade >= 60 ) printf( "Passedn"); else printf( "Failedn"); Autumn Programming and 12
  • 11. if-else syntax if ( expression ) if ( expression ) { { statement_1; statement1; statement_2; statement2; . . statement_n; statement_n; } } else { Statement_1; . if (grade>=60) Statement_m; printf(“Passed n”); } if ( grade >= 60 ) printf( "Passedn"); else printf( "Failedn"); Autumn Programming and 13
  • 12. Nesting of if-else Structures • It is possible to nest if-else statements, one within another. • All if statements may not be having the “else” part. – Confusion?? • Rule to be remembered: – An “else” clause is associated with the closest preceding unmatched “if”. Autumn Programming and 14
  • 13. if e1 s1 else if e2 s2 if e1 s1 else if e2 s2 else s3 if e1 if e2 s1 else s2 ? else s3 if e1 if e2 s1 else s2 Autumn Programming and 15
  • 14. if e1 s1 if e1 s1 else if e2 s2 else if e2 s2 if e1 s1 if e1 s1 else if e2 s2 else if e2 s2 else s3 else s3 if e1 if e2 s1 if e1 if e2 s1 else s2 else s2 else s3 else s3 if e1 if e2 s1 if e1 if e2 s1 else s2 else s2 Autumn Programming and 16
  • 15. Example #include <stdio.h> main() { int a,b,c; scanf (“%d %d %d”, &a, &b, &c); if (a>=b) if (a>=c) printf (“n The largest number is: %d”, a); else printf (“n The largest number is: %d”, c); else if (b>=c) printf (“n The largest number is: %d”, b); else printf (“n The largest number is: %d”, c); } Autumn Programming and 17
  • 16. Example #include <stdio.h> main() { int a,b,c; scanf (“%d %d %d”, &a, &b, &c); if ((a>=b) && (a>=c)) printf (“n The largest number is: %d”, a); else if (b>c) printf (“n The largest number is: %d”, b); else printf (“n The largest number is: %d”, c); } Autumn Programming and 18
  • 17. Confusing Equality (==) and Assignment (=) Operators • Dangerous error – Does not ordinarily cause syntax errors – Any expression that produces a value can be used in control structures – Nonzero values are true, zero values are false • Example: if ( payCode == 4 ) printf( "You get a bonus!n" ); Checks paycode, if it is 4 then a bonus is awarded Equality check improper Equality check proper if ( payCode = 4 ) if ( payCode == 4 ) printf( "You get a bonus!n" ); printf( "You get a bonus!n" ); Autumn Programming and 20
  • 18. Generalization of expression evaluation in C • Assignment (=) operation is also a part of expression. i=3; Returns the value 3 after assigning it to i. int i=4, j ; int i=4, j ; j? if(i=3) if(i==3) j=0; j=0; Whatever be the value of i, else else j=1 j is always 0. j=1; j=1; Autumn Programming and 21
  • 19. More about expressions • Increment (++) and Decrement (--)Operations Prefix operation ++i; --i; First increment / decrement and then used in evaluation Postfix operation i++; i--; increment / decrement operation after being used in evaluation int t,m=1; int t,m=1; m=2; m=2; t=++m; t=2; t=1; t=m++; Autumn Programming and 22
  • 20. Some More Examples Initial values :: a = 10; b = 20; x = 50 + ++a; a = 11, x = 61 x = 50 + a++; x = 60, a = 11 x = a++ + --b; b = 19, x = 29, a = 11 x = a++ – ++a; Undefined value (implementation dependent) Autumn Programming and 25
  • 21. Ternary conditional operator (?:) – Takes three arguments (condition, value if true, value if false) – Returns the evaluated value accordingly. grade >= 60 ? printf( “Passedn” ) : printf( “Failedn” ); (expr1)? (expr2): (expr3); Example: interest = (balance>5000) ? balance*0.2 : balance*0.1; Returns a value Autumn Programming and 26
  • 22. The switch Statement • This causes a particular group of statements to be chosen from several available groups. – Uses “switch” statement and “case” labels. – Syntax of the “switch” statement: switch (expression) { case expression-1: { …….. } case expression-2: { …….. } case expression-m: { …….. } default: { ……… } } Autumn Programming and 28
  • 23. The switch Multiple-Selection Structure true case a case a action(s) break false true case b case b action(s) break false . . . true case z case z action(s) break false default action(s) Autumn Programming and 29
  • 24. Example switch ( letter ) { case 'A': printf("First lettern"); break; case 'Z': printf("Last lettern"); break; default : printf("Middle lettern"); break; } Autumn Programming and 30
  • 25. Example switch (choice = toupper(getchar())) { case ‘R’: printf (“RED n”); break; case ‘G’: printf (“GREEN n”); break; case ‘B’: printf (“BLUE n”); break; default: printf (“Invalid choice n”); } Autumn Programming and 31
  • 26. Example switch (choice = getchar()) { case ‘r’: case ‘R’: printf (“RED n”); break; case ‘g’: case ‘G’: printf (“GREEN n”); break; case ‘b’: case ‘B’: printf (“BLUE n”); break; default: printf (“Invalid choice n”); } Autumn Programming and 33
  • 27. The break Statement • Used to exit from a switch or terminate from a loop. – Already illustrated in the switch examples. • With respect to “switch”, the “break” statement causes a transfer of control out of the entire “switch” statement, to the first statement following the “switch” statement. Autumn Programming and 34
  • 28. The Essentials of Repetition • Loop – Group of instructions computer executes repeatedly while some condition remains true • Counter-controlled repetition – Definite repetition - know how many times loop will execute – Control variable used to count repetitions • Sentinel-controlled repetition – Indefinite repetition – Used when number of repetitions not known – Sentinel value indicates "end of data" Autumn Programming and 36
  • 29. Counter-Controlled Repetition • Counter-controlled repetition requires – name of a control variable (or loop counter). – initial value of the control variable. – condition that tests for the final value of the control variable (i.e., whether looping should continue). – increment (or decrement) by which the control variable is modified each time through the loop. int counter =1; //initialization int counter; while (counter <= 10) { //repetition condition for (counter=1;counter<=10;counter++) printf( "%dn", counter ); printf(“%dn”,counter); ++counter; //increment } Autumn Programming and 37
  • 30. while Statement while (condition) statement_to_repeat; /* Weight loss program */ while ( weight > 65 ) { while (condition) { printf("Go, exercise, "); statement_1; printf("then come back. n"); printf("Enter your weight: "); ... scanf("%d", &weight); statement_N; } } int digit = 0; while (digit <= 9) printf (“%d n”, digit++); Autumn Programming and 38
  • 31. false C Single-entry / true single-exit structure statement(s) Autumn Programming and 39
  • 32. do-while Statement do { /* Weight loss program */ statement-1 do { statement-2 printf("Go, exercise, "); . printf("then come back. n"); printf("Enter your weight: "); . scanf("%d", &weight); statement-n } while ( weight > 65 ) ; } while ( condition ); At least one round of exercise ensured. Autumn Programming and 40
  • 33. statement(s) Single-entry / single-exit false structure C int digit = 0; true do printf (“%d n”, digit++); while (digit <= 9); Autumn Programming and 41
  • 34. for Statement for (initial; condition; iteration) statement_to_repeat; All are expressions. initial expr1 for (initial; condition; iteration) { condition expr2 statement_1; iterationexpr3 ... statement_N; fact = 1; /* Calculate 10 ! */ } for ( i = 1; i < =10; i++) No fact = fact * i; semicolon after last expression Autumn Programming and 42
  • 35. • How it works? – “expression1” is used to initialize some variable (called index) that controls the looping action. – “expression2” represents a condition that must be true for the loop to continue. – “expression3” is used to alter the value of the index initially assigned by “expression1”. int digit; for (digit=0; digit<=9; digit++) printf (“%d n”, digit); Autumn Programming and 43
  • 36. • How it works? – “expression1” is used to initialize some variable (called index) that controls the looping action. – “expression2” represents a condition that must be true for the loop to continue. – “expression3” is used to alter the value of the index initially assigned by “expression1”. Autumn Programming and 44
  • 37. int digit; expression1 for (digit=0; digit<=9; digit++) printf (“%d n”, digit); false expression2 Single-entry / single-exit true structure statement(s) expression3 Autumn Programming and 45
  • 38. The For Structure: Notes and Observations • Arithmetic expressions – Initialization, loop-continuation, and increment can contain arithmetic expressions. – e.g. Let x = 2 and y = 10 Increment for ( j = x; j <= 4 * x * y; j += y / x ) is equivalent to Initialization Loop continuation for ( j = 2; j <= 80; j += 5 ) • "Increment" may be negative (decrement) • If loop continuation condition initially false – Body of for structure not performed – Control proceeds with statement after for structure Autumn Programming and 46
  • 39. for :: Examples int fact = 1, i; int sum = 0, N, count; for (i=1; i<=10; i++) scanf (“%d”, &N); fact = fact * i; for (i=1; i<=N, i++) sum = sum + i * i; printf (“%d n”, sum); Autumn Programming and 47
  • 40. • The comma operator – We can give several statements separated by commas in place of “expression1”, “expression2”, and “expression3”. for (fact=1, i=1; i<=10; i++) fact = fact * i; for (sum=0, i=1; i<=N; i++) sum = sum + i * i; Autumn Programming and 48
  • 41. Specifying “Infinite Loop” while (1) { for (; ;) statements { } statements } do { statements } while (1); Autumn Programming and 49
  • 42. break Statement • Break out of the loop { } – can use with • while • do while • for • switch – does not work with • if {} • else {} Causes immediate exit from a while, for, do/while or switch structure Program execution continues with the first statement after the structure Common uses of the break statement Escape early from a loop Skip the remainder of a switch structure Autumn Programming and 50
  • 43. A Complete Example #include <stdio.h> main() { int fact, i; fact = 1; i = 1; while ( i<10 ) { /* run loop –break when fact >100*/ fact = fact * i; if ( fact > 100 ) { printf ("Factorial of %d above 100", i); break; /* break out of the while loop */ } i ++ ; } } Autumn Programming and 51
  • 44. continue Statement • continue – Skips the remaining statements in the body of a while, for or do/while structure • Proceeds with the next iteration of the loop – while and do/while • Loop-continuation test is evaluated immediately after the continue statement is executed – for structure • Increment expression is executed, then the loop- continuation test is evaluated. expression3 is evaluated, then expression2 is evaluated. Autumn Programming and 52
  • 45. An Example with “break” & “continue” fact = 1; i = 1; /* a program to calculate 10 ! while (1) { fact = fact * i; i ++ ; if ( i<10 ) continue; /* not done yet ! Go to loop and perform next iteration*/ break; } Autumn Programming and 53
  • 46. ANNOUNCEMENT REGARDING CLASS TEST 1 Autumn Programming and 54
  • 47. Time and Venue • Date: February 8, 2007 • Time: 6 PM to 7 PM – Students must occupy seat within 5:45 PM, and carry identity card with them. • Venue: VIKRAMSHILA COMPLEX – Section 1 :: Room V1 – Section 2 :: Room V2 – Section 3 :: Room V3 – Section 4 :: Room V4 – Section 5 (AE to EG):: Room V1 – Section 5 (Rest):: Room V2 Autumn Programming and 55
  • 48. Syllabus • Variables and constants • Number system • Assignments • Conditional statements • Loops • Simple input/output Autumn Programming and 56
  • 49. Some Examples Autumn Programming and 57
  • 50. Example 1: Test if a number is prime or not #include <stdio.h> main() { int n, i=2; scanf (“%d”, &n); while (i < n) { if (n % i == 0) { printf (“%d is not a prime n”, n); exit; } i++; } printf (“%d is a prime n”, n); } Autumn Programming and 58
  • 51. More efficient?? #include <stdio.h> main() { int n, i=3; scanf (“%d”, &n); while (i < sqrt(n)) { if (n % i == 0) { printf (“%d is not a prime n”, n); exit; } i = i + 2; } printf (“%d is a prime n”, n); } Autumn Programming and 59
  • 52. Example 2: Find the sum of digits of a number #include <stdio.h> main() { int n, sum=0; scanf (“%d”, &n); while (n != 0) { sum = sum + (n % 10); n = n / 10; } printf (“The sum of digits of the number is %d n”, sum); } Autumn Programming and 60
  • 53. Example 3: Decimal to binary conversion #include <stdio.h> main() { int dec; scanf (“%d”, &dec); do { printf (“%2d”, (dec % 2)); dec = dec / 2; } while (dec != 0); printf (“n”); } Autumn Programming and 61
  • 54. Example 4: Compute GCD of two numbers #include <stdio.h> 12 ) 45 ( 3 main() 36 { int A, B, temp; 9 ) 12 ( 1 scanf (%d %d”, &A, &B); 9 if (A > B) { temp = A; A = B; B = temp; } while ((B % A) != 0) { 3 ) 9 ( 3 temp = B % A; 9 B = A; 0 A = temp; } printf (“The GCD is %d”, A); Initial: A=12, B=45 } Iteration 1: temp=9, B=12,A=9 Iteration 2: temp=3, B=9, A=3 B % A = 0  GCD is 3 Autumn Programming and 62
  • 55. Shortcuts in Assignments • Additional assignment operators: + =, – =, * =, / =, %= a += b is equivalent to a = a + b a *= (b+10) is equivalent to a = a * (b + 10) and so on. Autumn Programming and 63
  • 56. More about scanf and printf Autumn Programming and 64
  • 57. Entering input data :: scanf function • General syntax: scanf (control string, arg1, arg2, …, argn); – “control string refers to a string typically containing data types of the arguments to be read in; – the arguments arg1, arg2, … represent pointers to data items in memory. Example: scanf (%d %f %c”, &a, &average, &type); • The control string consists of individual groups of characters, with one character group for each input data item. – ‘%’ sign, followed by a conversion character. Autumn Programming and 65
  • 58. – Commonly used conversion characters: c single character d decimal integer f floating-point number s string terminated by null character X hexadecimal integer – We can also specify the maximum field-width of a data item, by specifying a number indicating the field width before the conversion character. Example: scanf (“%3d %5d”, &a, &b); Autumn Programming and 66
  • 59. Writing output data :: printf function • General syntax: printf (control string, arg1, arg2, …, argn); – “control string refers to a string containing formatting information and data types of the arguments to be output; – the arguments arg1, arg2, … represent the individual output data items. • The conversion characters are the same as in scanf. Autumn Programming and 67
  • 60. • Examples: printf (“The average of %d and %d is %f”, a, b, avg); printf (“Hello nGood nMorning n”); printf (“%3d %3d %5d”, a, b, a*b+2); printf (“%7.2f %5.1f”, x, y); • Many more options are available: – Read from the book. – Practice them in the lab. • String I/O: – Will be covered later in the class. Autumn Programming and 68
  • 61. CLASS TEST 1 February 9, 2007 :: 6:00 to 7:00 PM Vikramshila Complex Room V1 : Section 1, Section 5 (AE to EG) Room V2 : Section 2, Section 5 (the rest) Room V3 : Section 3 Room V4 : Section 4 Students must occupy seat on or before 5:45 PM, and carry their ID cards. Syllabus: Variables and constants, number system, assignment statements, conditional statements and loops, simple input/output. Autumn Programming and 69