0% found this document useful (0 votes)
23 views43 pages

Lecture #6

The document is a programming lecture focused on selection structures and boolean expressions in programming. It covers boolean and relational operators, logical operators, and the use of if statements for decision-making in code. Additionally, it includes examples and exercises to illustrate the concepts of conditional logic and structured programming.

Uploaded by

umit.gumus.mgm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views43 pages

Lecture #6

The document is a programming lecture focused on selection structures and boolean expressions in programming. It covers boolean and relational operators, logical operators, and the use of if statements for decision-making in code. Additionally, it includes examples and exercises to illustrate the concepts of conditional logic and structured programming.

Uploaded by

umit.gumus.mgm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Mühendi sl i k ve Mi marl ı k Fakül tesi

BİL1102
Programlamaya Giriş
Ders #5

Doç.Dr. Gonca Gökçe MENEKŞE DALVEREN

2024 Güz
Content

• Selection Structures
Boolean operators

•In order to write conditions, we make use of


boolean expressions.
•A boolean expression is an expression that
gives one of two results 1 or 0.
•1 means the condition is true, 0 means false

1-3
Relational operators
• As you know, in arithmetics, numbers can be compared using operators
as =, ,, , , .
• All programming languages provide for the comparison of numbers and
values of variables.
• The operators used for comparison are called as relational operators.
• The symbols used for relational operators differ depending on the
programming language you use. The following symbols are used in C
language:

1-4
Relational operators
• Notice that, to check the equality two equal signs are used, rather than
one.
• You know that in C one equal sign is used to make an assignment.
Remember that x = y; means “x becomes equal to y”,
• but the expression x == y is a test to see whether x is equal to y.
• When you make a comparison using a single relational operator, the
expression is referred to as a relational (or simple boolean) expression.
• Each relational expression has a result 1 or 0 according to the
arithmetic validity of the comparison. Therefore, you can assign the
result of a boolean expression to an integer variable.

1-5
Example
int test1, test2, test3;
int num1, num2;
double num3;

num1 = 8;
num2 = 15;
test1 = num2 > num1;
test2 = num1 <= 5;
test3 = num2 == 0;

== is the relational operator


= is the assignment symbol which checks whether the
value of num2 is zero

1-6
How to check whether a number is within a
certain range?
• For instance, is num1 between 10 and 15?
• As in this case, in our programs, we often need to test two
things at once.
• In such cases, we should use a logical
operator to combine two tests
• There are three logical operators:
and or not.
• An expression which contains logical operators is referred to
as a compound boolean expression or logical expression.
• The resulting value of a logical expression is either 1 or 0
(thus true or false)
• The result depends on the values of the simple boolean
expressions and the logical operators used to combine them.
1-10
Truth Table

• If && is used to connect two simple boolean expressions E1


and E2, the resulting logical expression is true (results 1) only
when both E1 and E2 are true (non-zero). Otherwise it is false
(results 0).

• If || is used to connect two simple boolean expressions E1 and


E2, the resulting logical expression is false (results 0) only
when both E1 and E2 are false (zero). Otherwise it is true
(results 1).

• ! produces the logical complement


of a boolean expression. 1-11
Short circuit evaluation
• The logical AND and logical OR operators (&& and ||, respectively)
exhibit "short-circuit" property. That is, the second and other operands
are not evaluated if the result can be deduced solely by evaluating the
first operand. If A is a relational expression that evaluates to false there
is no need to evaluate B and C. What about A || B|| C ?

if ( A && B && C )
{
// do something;
}

1-13
Practice with Relational Expressions

int a = 1, b = 2, c = 3 ;

Expression Value Expression Value


a < c a + b >= c
b <= c a + b == c
c <= a a != b
a>b a + b != c
b >= c
Practice with Relational Expressions

int a = 1, b = 2, c = 3 ;

Expression Value Expression Value


a < c a + b >= c
b <= c a + b == c
c <= a a != b
a>b a + b != c
b >= c
Arithmetic Expressions: True or False

•Arithmetic expressions evaluate to numeric values.

•An arithmetic expression that has a value of zero is


false.

•An arithmetic expression that has a value other than


zero is true.
Practice with Arithmetic Expressions
int a = 1, b = 2, c = 3 ;
float x = 3.33, y = 6.66 ;
Expression Numeric Value True/False
a+b
b-2*a
c-b-a
c-a
y-x
y-2*x
Practice with Arithmetic Expressions
int a = 1, b = 2, c = 3 ;
float x = 3.33, y = 6.66 ;
Expression Numeric Value True/False
a+b
b-2*a
c-b-a
c-a
y-x
y-2*x
Review: Structured Programming

•All programs can be written in terms of


only three control structures
• The sequence structure
• Unless otherwise directed, the statements are
executed in the order in which they are written.
• The selection structure
• Used to choose among alternative courses of
action.
• The repetition structure
• Allows an action to be repeated while some
condition remains true.
Selection (Decision Statements)
Selection statements
• Statements that permit a computer to make decisions are called as decision (or
selection) statements.
• The if statement is one of the selection statements. It is used to make a computer
do something only when a certain condition is true.
• Syntax:

• The computer tests the condition.


• If the condition is true, the statement that follows is performed.
• If the condition is false, the statement is skipped, and the computer performs the
next statement after the if statement.
• The statement should be indented, so that the people who read your program
can understand it easily.

1-23
Example
•Trace the code below with a is 10, b is 2→ c=5
•Trace with values a=10 and b=0 → division is
not performed

1-24
Example

•Write a program that gets one integer from user


and decides whether that number is positive or
not

1-25
Example
•Write a program that gets one integer from user
and decides whether that number is positive or
not
int number;
printf("Enter a number");
scanf("%d", & number);
if (number>0)
printf(" %d is a positive number\n",number);

1-26
Example

• Write a program taking two grades and display unsuccessful if the


average of two grades is less than 50

1-27
Example
• Write a program taking two
grades and display
unsuccessful if the average
of two grades is less than
50

1-28
Solution
/* Display Unsuccessful if the average of two grades is less than 50.
*/ • The computer checks
whether average is less
#include <stdio.h> than 50.
int main(void)
{ double grade1, grade2, /* (input) two grades */ • If it is true, it displays the
average; /* average of two grades */ message.
// Get the grades
• Otherwise, i.e., if
printf ("Enter two grades: "); average is greater than
scanf ("%lf %lf", &grade1, &grade2); or equal to 50, nothing is
displayed on the screen.
// Calculate their average
average = (grade1 + grade2) / 2.0;

// Check if the student is unsuccessful


if (average < 50)
printf("\nUnsuccessful\n");

return(0);
}

1-29
if … else statement

• if statement is used to make a one-way selection,


• if … else statement is used to make a two-way selection.
• It makes the computer do something if a certain condition is
true, do something else if that condition is false.
• Syntax:

if (condition)
statement1; /* statement to be executed if condition is true */
else
statement2; /* statement to be executed if condition is false */

1-30
Example
• Write a program that takes one integer from user and decides whether
that number is divisible by 3.

1-31
Example
• Write a program that takes one integer from user and decides whether
that number is divisible by 3.

1-32
Example
• Consider our previous example. What about if you wanted to display the
message “Successful” if the average is 50 or more?

1-33
/* Display Unsuccessful if the average of two grades is less than 50. */

#include <stdio.h>
int main(void)
{ double grade1, grade2, /* (input) two grades */
average; /* average of two grades */

// Get the grades


printf ("Enter two grades: ");
scanf ("%lf %lf", &grade1, &grade2);

// Calculate their average


average = (grade1 + grade2) / 2.0;

// Check if the student is unsuccessful


if (average < 50)
printf("\nUnsuccessful\n");
else
printf("\nSuccessful\n");

return(0);
}

1-34
Compound statements
• Simple C statements:

• It is sometimes necessary to perform several simple statements when


some condition is true.
• In such cases, it is possible to write several simple statements as a
single compound statement using the symbols { and } at the beginning
and at the end of a sequence of simple statements.

1-35
Compound statements
• Compound statements are frequently used as part of a selection statement. For
example:
if (b != 0)
{
c = a / b;
printf (“%d / %d = %d\n”, a, b, c);
}

• Trace the code with a=10 and b=2


• However, if b is 0, no division will be made, and nothing will be displayed, because the
condition is false
• If you forget the curly braces, then only the assignment statement will belong to the if
statement.
• The printf statement will be executed no matter what the condition is, and this will
cause a problem since c will be unknown when b is 0.

1-36
Example
• What is the output of the following code?

1-37
Example
• What is the output of the following code?

2 6
2 6

1-38
Exercise
Write a program, which, given two numbers, divides the first number to the
second number. Notice that we have to check whether the second number is 0,
not to cause a division by zero error.
Exercise
Write a program,
which, given two
numbers, divides the
first number to the
second number. Notice
that we have to check
whether the second
number is 0, not to
cause a division by
zero error.
Exercise
Write a program,
which, given two
numbers, divides the
first number to the
second number. Notice
that we have to check
whether the second
number is 0, not to
cause a division by
zero error.
Exercise
• Nested If Statements
Nested if statements
* Here, this program displays the
second number even if the
numbers are equal, because else
means if num1 is greater than or
equal to num2.
// Display the smaller of two numbers
#include <stdio.h> * If we want to display a different
int main(void) message when the numbers are
{ double num1, num2; // input – given numbers equal, we need to write a nested
if statement, and change the if
// Get the numbers statement as follows:
printf ("Enter two numbers: ");
scanf ("%lf %lf", &num1, &num2);

// Display the smaller one


if (num1 < num2)
// Display the smaller one
printf ("%0.2f\n", num1); if (num1 < num2)
else printf ("%0.2f is smaller than %0.2f\n", num1, num2);
printf ("%0.2f\n", num2); else if (num2 < num1)
return(0); printf ("%0.2f is smaller than %0.2f\n", num2, num1);
} else
printf ("They are equal.\n");
Exercise
• Problem: Given the speed of the wind in mph, display its category,
based on the following table:

Wind Speed (mph) Category


Below 25 Not a strong wind
[25, 39) Strong wind
[39, 55) Gale
[55, 72] Whole Gale
Above 72 Hurricane
Exercise (cont.) • Let’s trace both programs with
different values of the speed:
22, 30, 39, 63, 80
• How could we write the same
program as a sequence of if • You can easily notice that, a
statements? Since each if selection made by a nested if
would be independent from the statement is always more
others, we would need to use efficient than a selection made
logical expressions to test the by many separate if
ranges statements.
Example
• In a university, a PhD student must pass the Qualification exam to be
able to go on his/her education.
• The Qualification exam consists of two parts: a written exam and an oral
one.
• A student is considered as unsuccessful if the average of his/her grades
from these two exams is less than 50, successful otherwise.
• However, an unsuccessful student has one more chance to take the
next exam, if he/she did not take the exam before.
• Display the proper message for a student who has taken the exam.

1-47
Solution
Solution (cont.)

• Notice that in the if


part we need one
more selection, thus,
we need to use a
nested if statement in
our program.

You might also like