0% found this document useful (0 votes)
8 views27 pages

computer methods c programming

Lecture 5 covers decision making and logical operations in C programming, focusing on relational and logical operators, selection statements, and examples of their usage. It explains how to use relational operators to evaluate conditions and how to implement decision-making structures like if statements and switch statements. The lecture also includes exercises and solutions to reinforce the concepts discussed.

Uploaded by

Thabiso Kyle
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)
8 views27 pages

computer methods c programming

Lecture 5 covers decision making and logical operations in C programming, focusing on relational and logical operators, selection statements, and examples of their usage. It explains how to use relational operators to evaluate conditions and how to implement decision-making structures like if statements and switch statements. The lecture also includes exercises and solutions to reinforce the concepts discussed.

Uploaded by

Thabiso Kyle
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/ 27

COMPUTER METHODS 1

LECTURE 5

Decision Making and Logical Operations

1 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Relational operators

A relational operator is a symbol that


indicates a relationship between two quantities.
The quantities maybe variables, constants or
functions.
The important point about these relations is
that they are either TRUE or FALSE

2 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Relational Operators used in C

Symbol Meaning TRUE examples FALSE examples


> Greater than 5>1 7<3
(8 + 1) > (2 − 1) 15/3 < 3
>= Greater than or equal 6 >= 6 4 >= 7
(2 + 4) >= (12/3) (1 − 3) >= (24 ∗ 2)
< Less than 4<5 1>6
(2 + 3) < (23 − 3) (2 + 14) < (1 + 3)
<= Less than or equal to (15/5) <= (2 + 3) (3 ∗ 5) <= (1 + 2)
4 <= 6 7 >= 12
== Equal to 5 == 5 6 == 7
(4 ∗ 5) == (40/2) (7 + 8) == (12 − 13)
!= Not equal to (1! = 3) (6! = 6)
(56/7) == 8 (12 − 6)! = (18/3)

For relational operators, the value returned for a TRUE Condition


is 1, and the value returned for a FALSE condition is a 0.

3 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


example
The following program shows the numerical values returned by relational expressions.

/* Values returned by some relational expressions */


#include <stdio.h>
int main()
{
float logic_value; /* Numeric value of relational expression */
printf("Logic values of the following relation:\n\n");

logic_value = (5>1);
printf("(5>1) is %f\n", logic_value);

logic_value = (7>3);
printf("(7>3) is %f\n", logic_value);

logic_value = ((2+4)>=(12/3));
printf("((2+4)>=(12/3)) is %f\n", logic_value);

logic_value = (4 <5);
printf("(4 <5) is %f\n", logic_value);

logic_value = (4<=6);
printf("(4<=6) is %f\n", logic_value);

logic_value = ((56/7)!= 8);


printf("((56/7)!= 8) is %f\n", logic_value);

logic_value = (5==5);
printf("((5==5) is %f\n", logic_value);

return 0;
}

4 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


The output is

Logic values of the following relation:

(5>1) is 1.000000
(7>3) is 1.000000
((2+4)>=(12/3)) is 1.000000
(4 <5) is 1.000000
(4<=6) is 1.000000
((56/7)!= 8) is 0.000000
((5==5) is 1.000000

5 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Logical operators and expressions

The logical operators are:

logical and: &&


logical or : ||
(unary) negation: !
The logical and and the logical or are binary, both act on two expressions and
yield either the logical true or logical false. both treat their operands as logical
values.
the logical negation operator is a unary operator.

The effect of applying these operators is shown below:

P Q P&&Q P||Q P !P

false false false false false true


false true false true false true
true false false true
true true true true

6 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Some expression involving negation operator

!5 evaluates to 0
!0 evaluates to 1
!’t’ evaluates to 0
3+!x evaluates 3 if x is non zero, and
evaluates to 4 if x is zero
!!5 evaluates to 1
!!0 evaluates to 0
-5 && !10 evaluates to 0
10 || -10 evaluates to 1

7 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Selection Statements

The syntax of the conditional operator is the following:


expresssion1 ? expression2 : expression3

The first operand is used to determine which of the other two operands should
be evaluated. If the first expression delivers logical true(non-zero) the the result
of the expression is expression2; if the first expression delivers logical
false(zero) the the result of the expression is expression3.
Exercise: define a C function to compute the absolute value of a floating point
number.
( The absolute value is mathematically defined by
x, if x ≥ 0
|x| =
−x, if x < 0

Solution:
double absolute(double x)
{
return (x<0 ? -x:x);
}

8 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Selection Statements

They select statements to execute based on the


value of an expression
The expression is sometimes called the
controlling expression
Selection statements:
if statement
switch statement

9 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


if statement

if (expression)
statement
A statement if is used to execute
conditionally a statement or block
of code.
If expression is true, statement is
executed (what is true?).
statement can be replaced by a
block of statements, enclosed in
curly braces.

10 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Example 1

/* cm11_4_2.c --This program displays the *


* absolute value of a number entered by the user */
#include <stdio.h>

int main()
{
double num;

printf("Please enter a real number: ");


scanf("%lf", &num);
if (num<0)
num = -num;

printf("The absolute value is %g\n", num);

return 0;
}

11 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Example 2

/* cm11_4_3.c -- repeat the previous example using a *


* ternary operation to return the absolute value *
*/
#include <stdio.h>
main()
{
double num; /* input number */
double absv; /* variable to receive the result */

printf("Please enter a real number: ");


scanf("%lf", &num);
absv = (num > 0)?num:-num;/* use ternary operation to *
return absolute value */
printf("The absolute value is %g\n",absv);
}

12 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


if-else statement1

if (expression)
statement2
else
statement3

if expression is true, statement1


is executed.
if expression is false, statement2
is executed
both statements can be (and
very often are) replaced by
blocks of statements
(’compound statements’)

13 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Example 1
/* cm11_4_4.c-Giving two numbers first and second the *
following code finds and displays the smaller min */
#include <stdio.h>
main()
{
int first, second; /* inputs */
int min; /* output the smaller of the 2 numbers */
printf("\nPlease enter first number: ");
scanf("%d", &first);
printf("\nPlease enter second number: ");
scanf("%d", &second);
if (first < second)
{
min = first;
printf ("The first number is smaller than the second.\n");
}
else
{
min = second;
printf ("The second number is smaller than the first\n");
}

printf("The smaller number is equal to %d\n", min);


}
14 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1
Example 2

/*******************************************************
* cm11_4_5.c- The following program receives as input *
* a number and checks if it is a valid grade means *
* it is between 0 and 100 *
*******************************************************/

#include <stdio.h>
int main(void)
{
int grade;

printf("Please enter your grade: ");


scanf("%d", &grade);

if (grade < 0 || grade > 100)


printf("This is not a valid grade!\n");
else
printf("This is a valid grade.\n");

return 0;
}

15 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


else if

if statements distinguish if (expression1)


between exactly 2 cases and statement1
execute different code in else if (expression2)
each case statement2
The else if construction else if (expression3)
allows for a multi-way statement3
decision else
statement 4

16 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Example
/* *************************************************
* cm11_4_6.c -- Given a mark between 0 and 100 *
* this program defines the corresponding symbol *
* the equivalent number of seconds and printed *
***************************************************/
#include <stdio.h>
main()
{
int grade;

printf("Please enter your grade: ");


scanf("%d", &grade);

if (grade >= 75)


printf ("A\n");
else if (grade >= 70)
printf ("B\n");
else if (grade >= 60)
printf ("C\n");
else if (grade >= 50)
printf ("D\n");
else
printf ("F\n");
}
17 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1
Exercise

Write a program that receives as Input:


Two integers, A and B

and returns as Output:


Their relation (i.e. displays A == B, A < B or A > B)

18 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Solution
/***************************************************
* cm11_4_7.c -- This program reads two integers *
* and displays their relation *
***************************************************/
#include <stdio.h>
int main()
{
int A, B;

printf("Enter two Numbers\n");


scanf("%d%d", &A, &B);
if (A == B)
printf("A==B\n");
else if (A > B)
printf("A>B\n");
else
printf("A<B\n");

return 0;
}

19 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


The switch statement

switch (expression)
{
The switch statement is a multiway
case const expr1 :
conditional statement similar to
statement1
if-else if-else
case const expr2 :
It allows the selection of an arbitrary statement2
number of choices based on a given ...
value default:
statementn
}

expression is any legal C expression


” {” and ”}” define respectively the beginning and the end of the switch body
When the switch statement is executed:
The expression is evaluated if a case matches the value of the expression,
the program jumps to the first statement after that case label
Otherwise, the default case is selected
The default is optional

20 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Solution
/******************************************************
* cm11_4_8.c -- Program to choose the form of ohm’s *
* needed to compute Voltage, Current and resistance *
* ****************************************************/
#include <stdio.h>
int main()
{
char selection; /* item to be selected by the program user */
printf("\n\nSelect the ohm’s form needed by letter:\n");
printf("\nA] Voltage\n B] Current\n C] Resistance\n");
printf("Enter your selection [A, B, or C]===> ");
scanf("%c",&selection);
switch(selection)
{
case ’A’ : printf("V = I*R");
break;
case ’B’ : printf("I = V/R");
break;
case ’C’ : printf("R = V/I");
break;
default :printf("That was an invalid entry.");
}
return 0;
}
21 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1
break statement
The break statement is used to alter the flow of control inside
loops and switch statements
For switch statements, when the switch transfers to the
chosen case, it starts executing statements at that point, it
will ’fall through’ to the next case unless you ’break out’.
break causes the program to immediately jump to the next
statement after the switch statement
for do, for and while statements, execution of the break
statement causes immediate termination of the innermost
enclosing loop.
A break statement in loops is normally used in conjunction
with an if statement. First, a loop is established to repeat
some specified number of times or until some expected
condition occurs. If, at any time, some abnormal situation
occurs, the loop is terminated. The later is achieved with a
combination of if and break.
22 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1
Exercise

Given a, b , and c three real numbers and the following equation:

ax 2 + bx + c = 0

where x is the unknown.


Write a program that finds the solutions of the above equation in
the set of real numbers (R)

23 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Solution
/*********************************************************
* cm11_4_9.c -- Program to solve an equation of second *
* with one unknown x: a*x*x +b*x+c =0 *
* *******************************************************/
#include <stdio.h>
#include <math.h>
int main()
{
double a,b,c; /* the three parameters of the equation */
double delta; /* determinant of the equation */
printf("\n\n Solve the equation a*x*x+b*x+c=0:\n");
printf("\n Enter a ====>"); scanf("%lf",&a);
printf("\n Enter b ====>"); scanf("%lf",&b);
printf("\n Enter c ====>"); scanf("%lf",&c);
if(a!=0)
{ delta = b*b -4*a*c;
if ( delta < 0)
printf("\n\n There is no real solution to this equation");
else {
printf("\n\nThe solutions of this equation are:\n");
printf("x1 = %lf\n",(-b-sqrt(delta))/(2*a));
printf("x2 = %lf\n",(-b+sqrt(delta))/(2*a));
}
}
else if(b!=0)
{
printf("\n\nThe solution is\n");
printf("x1 = %lf\n",(-c)/b);
}
else if (c!=0) printf("\n\nThis is impossible\n");
else printf("\n\nAny real number is a solution\n");
return 0;
}
24 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1
Exercise

Write a program that accepts a number between 1 and 500


from the user. If there is a coin of that value in cents, it
should display its name. Otherwise, it should report that there
is no such coin
We assume that the following coins exist : 2 cent, 5 cent , 10
cent, 20 cent, 50 cent , R1 ( 100 cent), R2 (200 cent),
R5 ( 500 cent)
Remember to check for the validity of the input!

25 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1


Solution
/***********************************************************************
* cm11_4_10.c -- Determination of existence of coin of certain value *
* *********************************************************************/
/#include <stdio.h>
int main()
{ int num;
printf("Please enter a number from 1 to 100: "); scanf("%d", &num);

/* Make sure the input is valid */


if (num<1 || num>500) { printf("Invalid input!\n");
return 1;
}
/* Display the correct coin name, or a default message if there’s no such coin */
switch (num) {
case 2:
printf("It’s 2 cent!\n"); break;
case 5:
printf("It’s 5 cent!\n"); break;
case 10:
printf("It’s 10 cent!\n"); break;
case 20:
printf("It’s 20 cent!\n"); break;
case 100:
printf("It’s 1 rand !\n"); break;
case 200:
printf("It’s 2 rand !\n"); break;
case 500:
printf("It’s 5 rand !\n"); break;
default:
printf("It’s not a coin!\n");
}
return 0;
}
26 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1
Your To Do work

1 Read your lecture 5


2 Complete Practical 3

27 / 27 Lecture 4: Decision Making and Logical Operations Computer Methods 1

You might also like