Program Control Structures – Decision Making & Branching



1. if Statement:


  • General format: if (expression) program statement;
  • Block format: if (expression) { block of statements; }
  • Example:

                         if (count > COUNT_LIMIT)

                              printf("Count limit exceeded\n");


2. if-else Construct:


  • General format: if (expression) { program statement 1; } else { program statement 2; }
  • Example:

                      if (count > COUNT_LIMIT)

                           printf("Count limit exceeded\n");

                     else

                           printf("Count limit is not exceeded\n");


3. Compound Relational Test:


  • Combining simple relational tests using && (logical AND) and || (logical OR).
  • Example:

                    if (grade >= 70 && grade <= 79)

                           ++grades_70_to_79;

4. Nested if Statement:


  • Example:

                  if (score >= 40) {

                      if (age >= 18)

                          printf("Issue Ticket\n");

                 }

                  else {

                          printf("Not in age\n");

                 }


5. switch Statement:


  • General format:

                switch (expression) {

                      case value1: program statements; break;

                      case value2: program statements; break;

                      default: program statements; break;

               }

  • Example:

                switch (operator) {

                       case '+': printf("%.2f\n", value1 + value2); break;

                       case '-': printf("%.2f\n", value1 - value2); break;

                       default: printf("Unknown operator.\n"); break;

                }


6. The Conditional Operator:


  • Ternary operator format: condition ? expression1 : expression2
  • Example:

                  s = (x < 0) ? -1 : x * x;






Post a Comment

Previous Post Next Post