0% found this document useful (0 votes)
52 views

Lab Module Chapter 5

This document discusses selection statements in C programming. It covers relational operators and if/else conditional statements for one-way, two-way, and nested selection. It also discusses switch statements, conditional expressions, and boolean values. Examples are provided to illustrate different selection statements and how to write code for conditional logic.

Uploaded by

Ariq Naufal R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Lab Module Chapter 5

This document discusses selection statements in C programming. It covers relational operators and if/else conditional statements for one-way, two-way, and nested selection. It also discusses switch statements, conditional expressions, and boolean values. Examples are provided to illustrate different selection statements and how to write code for conditional logic.

Uploaded by

Ariq Naufal R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

ENGR 1303: Chapter 5 Module

Exercise 1: Selection Statements – Relational Operators


1. Evaluate the following expressions. Determine whether they are valid and whether they are true or false
Expression Valid/Invalid True/False
5 < 10 Valid True
-5 <= 0 Valid True
-6 >= 0 Valid False
7 > 1 Valid True
5 + 1 > 4 – 5 Valid True
-1 < 4 – 11 Valid False
1 == -1 Valid False
1 != -1 Valid True
2 < 3 == 1 < 10 Valid True
1 < 2 == 2 < 3 Valid True

2. Suppose I want to check if my variable p is in between the value of -1 and 1. Which of the following
expressions can be used to test p?
A. -1 < p < 1
B. -1 < p && < 1
C. -1 < p && p < 1
D. -1 < p && p > 1
E. -1 < p || p < 1
3. Explain the difference of =, !=, and ==

=
To assign a certain point to a certain variable
Means an expression isn’t equal to other expression
!=

Means an expression is equal to other expression


==
Exercise 2: Selection Statements – if Statement
1. One way selection statement
Flowchart for one way selection statement:

Below is an example of a one way selection if statement


if (age <= 17)
printf(“You may not apply to this program.”);

Note that the example here can only hold one single statement. If we want to have multiple statements in one
if statement, we need to use what we call as a compound statement.
Compound Statement: a group of statements inside a set of { and } braces
Example:
if (age <= 17)
{
printf(“You may not apply to this program.”);
continue = 0;
}
//the compiler will treat these two statements as a single statement

Write appropriate statement(s) to do the following tasks:


If A is more than B, assign A to max and assign B to min
if(a>b);
{
max=a; min=b;
printf("max=%d, min=%d", max, min);
}
2. Two way selection statement
Flowchart for two way selection statement:

Below is an example of a two way if statement


if (age <= 17)
{
printf(“You may not apply to this program.”);
continue = 0;
}
else
{
printf(“Welcome, please continue to the next step.”);
continue = 1;
}

Write down statement(s) that will perform the following action:


Let num, denom, and dec be float variables. If denom is equal to zero, print out “Error: division by
zero!”. Otherwise, dec is equal to num divided by denom .
If (denom>0)
{
Dec=num/denom;
}
Else
{
Printf(“Error: division by zero!”)
}
3. Nested if statement
Flowchart for one way selection statement:

Nested if statement is when an if


statement is placed inside another if
statement
Below is an example of a nested if
statement
if (pass == 1)
if (toefl >= 71)
printf(“Full Admission”);
else
printf(“Conditional Admission”)
else
printf(“Unqualified”);

Be careful with the logical sequence when using nested if statements. It is always safe to put braces around if
statements to avoid confusion:
if (pass == 1)
{
if (toefl >= 71)
{
printf(“Full Admission”);
}
else
{
printf(“Conditional Admission”);
}
}
else
{
printf(“Unqualified”);
}
4. Multi way selection statement (cascaded)
Flowchart for multi selection statement:

Below is an example of a multi selection if statement (cascaded):


if (grade == 4)
printf(“A”);
else if (grade == 3)
printf(“B”);
else if (grade == 2)
printf(“C”);
else if (grade == 1)
printf(“D”);
else
printf(“Failed”);

Program: Calculating a Broker’s Commission (from ch05 ppt – Norton, 2008)


The broker.c program asks the user to enter the amount of the trade, and then displays the amount of the
commission. Sample output will be:
Enter value of trade: 30000
Commission: $166.00
The heart of the program is a cascaded if statement that determines which range the trade falls into. Take a
look at the program below:
/* Calculates a broker's commission */
 
#include <stdio.h>
 
int main(void)
{
float commission, value;
 
printf("Enter value of trade: ");
scanf("%f", &value);
 
//calculating the commission based on trade value
if (value < 2500.00f)
commission = 30.00f + .017f * value;
else if (value < 6250.00f)
commission = 56.00f + .0066f * value;
else if (value < 20000.00f)
commission = 76.00f + .0034f * value;
else if (value < 50000.00f)
commission = 100.00f + .0022f * value;
else if (value < 500000.00f)
commission = 155.00f + .0011f * value;
else
commission = 255.00f + .0009f * value;

//the minimum total commission is 39.00


if (commission < 39.00f)
commission = 39.00f;
 
printf("Commission: $%.2f\n", commission);
 
return 0;
}
The decision table below shows fines imposed for speeding violations. Write a code segment that assigns the
correct fine to a type double variable fine based on the value of type int variable speed.

(EKT 120 Lab 3 Module, Universiti Malaysia Perlis)


Write down your solution into the space provided below:
#include<stdio.h>

int main(void)
{
int speed;
printf("Input speed:");
scanf("%d", &speed);
if(speed<=65)
printf("You must pay: $0 ");
else if(66<speed&&speed<70)
printf("You must pay: $15.00 ");
else if(71<speed&&speed<75)
printf("You must pay: $30.00 ");
else if(76<speed&&speed<80)
printf("You must pay: $75.00 ");
else if(speed>=80)
printf("You must pay: $100.00 ");
else
printf("Input Error");
return 0;
}
Exercise 3: Selection Statements – Conditional Expressions and Boolean Values
1. Conditional Expressions
Below is the general syntax of conditional expressions:
expression1?expression2:expression3
meaning: if expression1, then expression2, else expression3

Example: Here, the expression i>j?i:j is the same


with (i>j)?i:j
The compiler will evaluate i>j. If the
int i, j, k;
value is 1, then k=i. If the value is 0,
then k=j
i = 1;
j = 2;
k = i > j ? i : j; /* k is now 2 */
k = (i >= 0 ? i : 0) + j; /* k is now 3 */

Conditional expressions can make the code shorter, but might be harder to understand, so be wise in using
them.
Example of conditional expression in return statement:

return i > j ? i : j;

Example of conditional expression in printf statement:

if (i > j)
printf("%d\n", i);
else
printf("%d\n", j); //The if statement will look like this
------------------------------------------------------------------------------------------------------------------------------------
-

//by using conditional expression, the code is much shorter

printf("%d\n", i > j ? i : j);


2. Boolean Values
In C99, the header <stdbool.h> defines a macro bool which defines _Bool type of data (1 and 0).
The header also provides macro true and false which stands for 1 and 0 respectively.
#include <stdio.h>
#include <stdbool.h>

.............................
bool flag; //defining a _Bool type variable flag
.............................
flag = true; //assign the value 1 to flag
.............................
flag = false; // assign the value 0 to flag
.............................
flag = 5;
/*attempting to store a nonzero value will cause the variable to be
assigned 1. Here the value of flag will be 1*/
.............................
if(flag) //check whether the value of flag is 1
.............................
if(!flag) //check whether the value of flag is 0
.............................

Exercise 4: Selection Statements – switch statement


1. The multi way if statements can be replaced with what we call as switch statement:
switch statement can accommodate integers and characters, but not floating point numbers and string.
if (grade == 4) Switch (grade)
{
printf(“A”);
case 4: printf(“A”);
else if (grade == 3) break;
case 3: printf(“B”);
printf(“B”);
break;
else if (grade == 2) case 2: printf(“C”);
break;
printf(“C”);
case 1: printf(“D”);
else if (grade == 1) break;
default: printf(“Failed”);
printf(“D”);
break;
else }
/*switch statement may be easier to
printf(“Failed”);
read than multi way if statements,
and is often faster.*/
Below is the most common form of the switch statement:
Switch (expression)
{
case constant-expression : statements
...
case constant-expression : statements
default : statements
}

/*Notes:
- constant expressions: an expression that has a constant value. It
cannot contain variables or function calls
- the constant expressions must evaluate to integers (characters are
acceptable
- duplicate case labels are not allowed
- the order of the cases doesn’t matter
- default doesn’t need to come last
- if the default case is missing and the controlling expression’s
value doesn’t match any case label, control will pass to the next
statement after switch*/

Several case labels can be put on the same line preceding a group of statements:

switch (grade)
{
case 4: case 3: case 2: case 1: //grade 4,3,2, or 1, is Passing
printf("Passing");
break;
case 0: printf("Failing");
break;
default: printf("Illegal grade");
break;
}

2. Executing break statement causes the program to break out of the switch statement. Execution will
continue to the statement after switch. Take a look at the code below:
#include <stdio.h>

int main (void)


{
int grade;
printf(“Please input your grade (0-4): “);
scanf(“%d”, &grade);
switch (grade)
{
case 4: printf(“Excellent”);
case 3: printf(“Good”);
case 2: printf(“Average”);
case 1: printf(“Poor”);
case 0: printf(“Failing”);
default: printf(“Illegal Grade”);
}
return 0;
}

Run the program and record the output of the following input:
Input Output
0 FailingIllegal Grade
1 PoorFailingIllegal Grade
2 AveragePoorFailingIllegal Grade
3 GoodAveragePoorFailingIllegal Grade
4 ExcellentGoodAveragePoorFailingIllegal Grade
A Illegal Grade

Suppose I want the output to be as follow:


Input Output
0 Failing
1 Poor
2 Average
3 Good
4 Excellent
A Illegal Grade

Fix the code below to get the desired outputs:


#include <stdio.h>

int main (void)


{
int grade;
printf(“Please input your grade (0-4): “);
scanf(“%d”, &grade);
switch (grade)
{
case 4: printf(“Excellent”);break;
case 3: printf(“Good”);break;
case 2: printf(“Average”);break;
case 1: printf(“Poor”);break;
case 0: printf(“Failing”);break;
default: printf(“Illegal Grade”);break;
}
return 0;
}

Note:
The last case label (or default if placed last) doesn’t need a break statement. However, adding one
makes it easy to add cases in the future.

3. Program: Printing a Date in Legal Form (from ch05 ppt – Norton, 2008)
Contracts and other legal documents are often dated in the following way:
Dated this __________ day of __________ , 20__ .

The date.c program will display a date in this form after the user enters the date in month/day/year form:
Enter date (mm/dd/yy): 7/19/14
Dated this 19th day of July, 2014.

The program uses switch statements to add “th” (or “st” or “nd” or “rd”) to the day, and to print the month
as a word instead of a number:
/* Prints a date in legal form */
 
#include <stdio.h>
 
int main(void)
{
int month, day, year;
 
printf("Enter date (mm/dd/yyyy): ");
scanf("%d /%d /%d", &month, &day, &year);
 
printf("Dated this %d", day);
switch (day)
{
case 1: case 21: case 31:
printf("st"); break;
case 2: case 22:
printf("nd"); break;
case 3: case 23:
printf("rd"); break;
default: printf("th"); break;
}
printf(" day of ");
switch (month)
{
case 1: printf("January"); break;
case 2: printf("February"); break;
case 3: printf("March"); break;
case 4: printf("April"); break;
case 5: printf("May"); break;
case 6: printf("June"); break;
case 7: printf("July"); break;
case 8: printf("August"); break;
case 9: printf("September"); break;
case 10: printf("October"); break;
case 11: printf("November"); break;
case 12: printf("December"); break;
}
 
printf(", %d.\n", year);
return 0;
}
Run the program and give a sample output (indicate any input with underlined character/number)
Dated this 23rd day of December, 1999.

Exercise 5: Make your own program


1. Write an interactive program that contains an if statement that may be used to compute the area of square
(area = side2 ) or a triangle (area = ½ x base x height ) after prompting the user to type the first character of the
figure names (S or T). The following flowchart is provided for you. Write your program by following the
flowchart.
2. Write a program for the National Earthquake Information center implementing the following decision table to
characterize an earthquake based on its Richter scale number.

Your program will display the characterization of the earthquake based on the scale number provided by user.
a. Write down the flowchart for the program.
b. Can you handle this problem with a switch statement? If so, use a switch statement; if not, explain
why.
c. Write a program based on flowchart in (a).
3. Write a code segment that assigns to the variable lumens the expected brightness of a standard light bulb
whose power has been stored in watts. Use the following table:

a. Write down the flowchart of your code segment


b. Use switch statement to write your code segment
(exercise 5:1-3 is adapted frm EKT 120 lab module Universiti Malaysia Perlis)

You might also like