Share
C Programming

Course Outline

Week 1
Week 2
Week 3
Week 4

SELECTION STRUCTURES: IF AND SWITCH STATEMENTS

  • Conditional statements (If statements)
  • Relational and Equality Operators
  • Logical Operators
  • If statement with one Alternative
  • If statement with two Alternatives
  • If statement with Compound Alternatives
  • Nested if statements
  • The Switch statement
Week 5

SponsoredAdvertise

Explanations to week content

Conditions

 

A program chooses among alternative statements by testing the value of key variables.

For example, one indicator of the health of a person’s heart is the resting heart rate. Generally a resting rate of 75 beats per minute or less indicates a healthy heart, but a resting heart rate over 75 indicates a potential problem. A program that gets a person’s resting heart rate as data should compare that value to 75 and display a warning message if the rate is over 75.

 

If rest_heart_rate is a type int variable, the expression

 

rest_heart_rate > 75

 

performs the necessary comparison and evaluates to 1(true) when rest_heart_rate is over 75; the expression evaluates to 0 (false)if rest_heart_rate is not greater than 75. Such an expression is called a condition because it establishes a criterion for either executing or skipping a group of statements.

 

Relational Operators

 

Operator Meaning
== Equal to
!= Not equal to
Less than
<= Less than or equal to
Greater than
>= Greater than or equal to
|| Or
&& And

 

Logical Operators

 

With the three logical operators— && (and), ||(or), ! (not)—we can form more

complicated conditions or logical expressions. Examples of logical expressions

formed with these operators are

salary < MIN_SALARY || dependents > 5

temperature > 90.0 && humidity > 0.90

n >= 0 && n <= 100

0 <= n && n <= 100

 

The first logical expression determines whether an employee is eligible for special scholarship funds. It evaluates to 1 (true) if either the condition

salary < MIN_SALARY

or the condition

dependents > 5 is true.

 

The second logical expression describes an unbearable summer day, with temperature and humidity both in the nineties. The expression evaluates to true only when both conditions are true.

 

The last two expressions are equivalent and evaluate to true if n lies between 0 and 100 inclusive.

 

The third logical operator, ! (not), has a single operand and yields the logical complement, or negation , of its operand (that is, if the variable positive is nonzero (true), !positive is 0 (false) and vice versa).

 

The logical expression

!(0 <= n && n <= 100) is the complement of the last expression in the list above. It evaluates to 1 (true) when n does not lie between 0 and 100 inclusive.

 

 

The if Statement

 

In C, the

if statement is the primary selection control structure.

 

if Statement with One Alternative

 

Syntax:

 

if(condition is true){

            //Run this block of statements

}

 

Example

 

Write a program that checks if the age of a user is 18 years or more. If 18 or more years, print on the screen, You are an adult

 

Sample Code

 

#include

#include

int main()

{

    int age;

   printf("Enter your age> ");

   scanf("%d",&age);

   if(age>=18){

       printf("You are an adult");

    }

    return 0;

}

 

 

if Statement with Two Alternatives

 

Syntax:

 

if(condition is true){

    //Run this block of code

}else{

     // if the top condition is false, run this block of code

}

 

Example

 

Write a program that checks if the age of a user is 18 years or more. If 18 or more years, print on the screen, You are an adult but if not, print on the screen, You are under age

 

Sample Code

 

#include

#include

int main()

{

    int age;

   printf("Enter your age> ");

   scanf("%d",&age);

   if(age>=18){

       printf("You are an adult");

    }else{

       printf("You are under age");

    }

    return 0;

}

 

if Statements with Compound Statements

 

Syntax:

 

if(condition is true){

            //run this block of statement(s)

}else if(condition is true){

          // if the top condition is false but this condition is true, run this block of statement(s)

} else if(condition is true){

          // if the top condition is false but this condition is true, run this block of statement(s)

}

.

.

.

else if(condition is true){

          // if the top condition is false but this condition is true, run this block of statement(s)

}else{

         // if none of the above conditions is true, run this block of statement(s)

}

 

The if statement is being tested at the top, if the top condition is true, the statement(s) in that block is executed but if not,the next if condition is tested and so on until one of the statements is true.If none is true, the last else{} statement(s) is run since none of the above conditions is true.

 

Example

 

The following is the grading system of a school. Write an application to ask a user to enter the score. Your application should then compute the grade and output it to the user.

 

Grading System

 

80 - 100 A
75 - 79 B+
70 - 74 B
65 - 69 C+
60 - 64 C
55 - 59 D+
50 - 54 D
Below 50 E

 

Sample Code

 

#include

#include

int main()

{

    double score;

   printf("Enter your score> ");

   scanf("%lf",&score);

   if(score>=80){

       printf("%.2f percent is a grade A",score);

    }elseif(score>=75){

       printf("%.2f percent is a grade B+",score);

    }elseif(score>=70){

       printf("%.2f percent is a grade B",score);

    }elseif(score>=65){

        printf("%.2f percent is a grade C+",score);

    }elseif(score>=60){

       printf("%.2f percent is a grade C",score);

    }elseif(score>=55){

       printf("%.2f percent is a grade D+",score);

    }elseif(score>=50){

       printf("%.2f percent is a grade D",score);

    }else{

       printf("%.2f percent is a grade E",score);

    }

    return 0;

}

 

Nested if Statements and Multiple-Alternative Decisions

 

One if statement inside another.

 

Example

 

For example, suppose you want to pay a Ghc 50 bonus to a salesperson only if the salesperson sells at least three items that total at least Ghc1,000 in value during a specified time. Write a program that ask a salesperson to enter number of items sold and the total amount of the items sold and inform the salesperson whether qualified for the Ghc 50 bonus or not.

 

Sample Code

 

#include

#include

#define MIN_ITEMS 3

#define MIN_VALUE 1000

int main()

{

    double sales;

    int items_sold;

    //Ask the salesperson to enter total items sold

    printf("Enter total items sold >");

   scanf("%d",&items_sold);

    if(items_sold>=MIN_ITEMS){

        //Now get the total sales

       printf("Enter the total sales for the %d items sold >",items_sold);

       scanf("%lf",&sales);

        //if sales is 1000 or more, salesperson is qualified to be given a bonus

        //Nested if

        if(sales>=MIN_VALUE){

           printf("You are qualified for a bonus of GHC 50.00");

        }else{

           printf("You are not qualified for a bonus");

        }

    }else{

       printf("You are not qualified for a bonus");

    }

    return 0;

}

 

The switch Statement

 

The switch statement may also be used in C to select one of several alternatives.

The switch statement is especially useful when the selection is based on the value

of a single variable or of a simple expression (called the controlling expression ). The

value of this expression may be of type int or char ,but not of type double .

 

The switch structure uses four keywords:

 

  • switch starts the structure and is followed immediately by a test expression enclosed in parentheses.
  • case is followed by one of the possible values for the test expression and a colon.
  • break optionally terminates a switch structure at the end of each case.
  • default optionally is used prior to any action that should occur if the test variable does not match any case.


Syntax:

 

switch(comparator){

        case value_1:

        //Statement of code to run

        break;

        case value_2:

        //Statement of code to run

        break;

        case value_3:

       //Statement of code to run

        break;

 

        .

        .

        .

        case value_n:

       //Statement of code to run

        break;

       default:

       //Statement of code to run in case none of the above values match

}

 

Example

 

Write a program which asks a student to enter the level of year of his studies (1, 2, 3 or 4).

If a user enters 1, print on the screen, You are a fresher

If a user enters 2, print on the screen, You are in Level 200

If a user enters 3, print on the screen, You are in Level 300

If a user enters 4, print on the screen, You are in your final year

Any other input, print on the screen, Invalid year

 

Sample Code

 

#include <stdio.h>

#include <stdlib.h>

int main()

{

    int year;

    //Ask the student to enter the year

   printf("Enter your year (1,2,3 or 4) > ");

   scanf("%d",&year);

   switch(year){

    case 1:

    printf("You are a fresher");

    break;

    case 2:

    printf("You are in Level 200");

    break;

    case 3:

    printf("You are in Level 300");

    break;

    case 4:

    printf("You are in your final year");

    break;

    default:

    printf("Invalid year");

    }

    return 0;

}

 

ASSIGNMENT

 

Write a program which asks a user to enter an integer number. The program should output if the number is an even number or odd.

 

Program Design

 

Enter a number > 5

5 is an odd number

 

Enter a number > 4

4 is an even number

 

SOLUTION

#include <stdio.h>

#include <stdlib.h>

int main()

{

    int number;

   printf("Enter a number >");

   scanf("%d",&number);

   if(number%2==0){

       printf("%d is an even number",number);

    }else{

       printf("%d is an odd number",number);

    }

    return 0;

}

SponsoredAdvertise

Kuulchat Premium