Академический Документы
Профессиональный Документы
Культура Документы
Lab 4
Objectives
Learning rules of expressions evaluation.
Learning some of the C mathematical functions.
If‐conditional and relational operators.
Warming Up! (15 min)
You will be required to write a program that tests your understanding of the previous 2 labs.
Study well!
1) Arithmetic Operators
‐ Unary Plus (+) +x
‐ Unary Minus (‐) ‐x
‐ Addition (+) x + y
‐ Subtraction (‐) x ‐ y
‐ Multiplication (*) x * y
‐ Division (/) x / y
Integer division: the result of dividing two integer variables or integer literals results in the
truncation of the fractional part of the result. For example 1/2 = 0.
‐ Modulo/Remainder (%) x % y
The modulo operation finds the remainder of division of one number by another. Given two
positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n) can
be thought of as the remainder, on division of a by n. For instance, the expression "7 mod 3"
would evaluate to 1, while "9 mod 3" would evaluate to 0.
Modulo is an operation that can be applied on integers only!
The general equation for calculating the remainder is (where n and m are two integers):
,
2) C‐Operators Precedence Table
Two operator characteristics determine how operands group with operators: precedence and
associativity. Precedence is the priority for grouping different types of operators with their
operands (i.e. Precedence determines the order of evaluation of operations). Associativity is the
left‐to‐right or right‐to‐left order for grouping operands to operators that have the same
precedence (i.e. Associativity determines the order of evaluation of operations that have the
same precedence). An operator's precedence is meaningful only if other operators with higher
or lower precedence are present. Expressions with higher‐precedence operators are evaluated
first. The grouping of operands can be forced by using parentheses.
For example: How can the following expression be evaluated?
2 3 4
Is the addition evaluated first or the multiplication?? There has to be some rules to govern such
situations and to guarantee the uniqueness of the results. These rules are called the Precedence
of operators.
Furthermore: For the following expression:
1 2 3
Which subtraction is performed first? The rules that determine this are called the Associativity
of operators.
The following is a subset of the C Operators Precedence Table (as we study more operators we
will add them in this table): Upper rows have higher precedence and operators in the same row
have the same precedence.
Operator Associativity
Parentheses ( ) Left – to – right
Unary plus + Right – to – left
Unary minus ‐
Multiplication * Left – to – right
Division /
Mod %
Addition + Left – to – right
Subtraction ‐
Examples
1) 2 3 4 14
Because multiplication has a higher precedence than addition; therefore, 3 * 4 is evaluation
first to 12 and then the addition is performed 2 + 12.
2) 1 2 3 4
Both operations have the same precedence; therefore, rules of associativity govern the
order of evaluation. Subtraction is evaluated “Left‐to‐right”. 1 – 2 is evaluation first to ‐1 and
then ‐1 – 3 is evaluated to ‐4.
3) is written in C as: 1 2 ⁄ 3 4 . Addition is forced first by the use of the
parentheses.
4) is written in C as 1 2 3 / 1 3/ 4 5 .
3) C Numeric Library
cmath declares a set of functions to compute common mathematical operations and
transformations. You have to include math.h in order to be able to use these functions!
a) Trigonometric functions:
Function Description Arguments Return Example
cos Computes the cosine of double: Angle in double: Cosine of the cos(0)
an angle radians argument
sin Computes the sine of an double: Angle in double: Sine of the sin(0)
angle radians argument
tan Computes the tangent double: Angle in double: Tangent of the tan(0)
of an angle radians argument
acos Computes the arc cosine double: Cosine of double: Angle in radians acos(1.0)
the angle whose cosine is the
argument
asin Computes the arc sine double: Sine of the double: Angle in radians asin(0)
angle whose sine is the
argument
atan Computes the arc double: Tangent of double: Angle in radians atan(0)
tangent the angle whose tangent is the
argument
b) Exponential and logarithmic functions:
Function Description Arguments Return Example
exp Computes the exponential double double: exp(2.0)
function e^argument
log Computes the ln function double double: ln of the log(4.0)
argument
log10 Computes log to the base double double: log to the log10(100.0)
10 base 10 of the
argument
c) Power functions
Function Description Arguments Return Example
pow Raise to power double, double double: first pow(2.0, 2)
argument ^ second
argument
sqrt Computes square root double double: squre root sqrt(4.0)
of the argument
d) Rounding, absolute value and remainder functions:
Function Description Arguments Return Example
ceil Rounds up value double double: smallest ceil(2.3)
integer greater
than or equal the
argument
floor Rounds down value double double: largest floor(2.3)
integer less than or
equal the
argument
fabs Computes absolute value double double: absolute fabs(‐1.5)
value of the
argument
fmod Computes remainder of double, double double: remainder fmod(5.5,
division of divider first 2.5)
argument by the
second argument
Illustrative Examples
a) A program that raises an input integer to the powers from 2 to 4 and calculates its square
root.
#include <iostream>
#include <math.h>
int main() {
int x, xp2, xp3, xp4;
float xsqrt;
return 0;
}
b) A program that calculates the Sine, Cosine, and Tangent of an input angle in degrees.
#include <iostream>
#include <math.h>
int main() {
double xdegree, xradian;
double xsin, xcos, xtan;
cout << "Sin(" << xdegree << ") = " << xsin << endl;
cout << "Cos(" << xdegree << ") = " << xcos << endl;
cout << "Tan(" << xdegree << ") = " << xtan << endl;
return 0;
}
4) Relational Operators
Relational operators are used to test some kind of relation between two numbers. These include
numerical equality (e.g. 5 = 5) and inequalities (e.g. 4 ≥ 3). They return either true if the relation
holds or false if the relation doesn’t hold.
‐ Equals ( == ):
Example:
int x = 1;
int y = 0;
y = y + 1;
In this case the result of x == y is true because both of them equal 1.
‐ Not Equal ( != ):
Example:
int x = 1;
int y = 0;
y = y + 1;
In this case the result of x != y is false because both of them equal 1.
‐ Less than ( < ):
Example:
int x = 1;
int y = 0;
In this case the result of x < y is false because x is greater than y.
‐ Less than or Equal ( ≤ ):
Example:
int x = 1;
int y = 0;
y = y + 1;
In this case the result of x ≤ y is true because both of them equal 1.
‐ Greater than ( > ):
Example:
int x = 1;
int y = 0;
In this case the result of x > y is true because x is greater than y.
‐ Greater than or Equal (≥ ):
Example:
int x = 1;
int y = 0;
In this case the result of x ≥ y is true because x is greater than y.
5) IF‐Conditional
IF is used when you need to check on some kind of condition; if the condition is satisfied you
execute some code, if not you don’t execute that code (possibly execute some other code).
For example, assume we want to determine whether a number is divisible by 4 or not. A number
is divisible by 4 if when divided by 4, it gives a 0 remainder (i.e. number % 4 = 0).
Thus in order for a number to be divisible by 4 the following should be true:
number % 4 == 0
Now that we have determined the condition, we need a tool that enables us to check on the
condition. That tool is IF‐conditional.
The syntax of if‐condition is simple:
if(condition) {
//code block
}
When the condition is true, the enclosed code block is executed.
Our program can be written as:
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
if(x % 4 == 0) {
cout << "Number is divisible by 4";
}
return 0;
}
Now assume we want to print something when the number is not divisible by 4. Here comes the
“else” keyword.
The syntax becomes:
if(condition) {
//code block
} else {
//code block
}
And our program becomes:
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
if(x % 4 == 0) {
cout << "Number is divisible by 4";
} else {
cout << "Number is not divisible by 4";
}
return 0;
}
NOTE that ONLY ONE of the two code blocks is executed, either the one associated to the if or
the one associated to the else.
Let us further imagine that we want to distinguish the numbers that give a remainder 1 when
divided by 4 from the rest of the numbers that are not divisible by 4.
Using our current knowledge we can do this by:
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
if(x % 4 == 0) {
//number is divisible by 4
cout << "Number is divisible by 4";
} else {
//number is not divisible by 4
if(x % 4 == 1) {
cout << "Number gives a remainder 1 when divided by 4";
} else {
cout << "Number is not divisible by 4 and remainder is not 1";
}
}
return 0;
}
However, there is another simpler way that enables us to check different conditions. This
method is using “else if” keyword.
The syntax is:
if(condition) {
//code block
} else if(another condition) {
//code block
} else if(another condition) {
//code block
.. any number of else if’s
} else {
//code block
}
Note that the final else is optional.
Our program becomes
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
if(x % 4 == 0) {
cout << "Number is divisible by 4";
} else if(x % 4 == 1) {
cout << "Number gives 1 remainder when divided by 4";
} else {
cout << "Number is not divisible by 4 and remainder is not 1";
}
return 0;
}
We emphasize on the fact that only one code block is executed; thus only one print statement
appears.
Illustrative Examples
a) A program that determines whether an input integer is even or odd.
#include <iostream>
int main() {
int x;
if(x % 2 == 0) {
cout << "Even" << endl;
} else {
cout << "Odd" << endl;
}
return 0;
}
b) A program that finds the solution of a quadratic equation and prints a message if there are
no real roots for this equation.
#include <iostream>
#include <math.h>
int main() {
float a, b, c;
float d, root1, root2;
d = b * b - 4 * a * c;
if(d >= 0) {
root1 = (-b + sqrt(d)) / (2 * a);
root2 = (-b - sqrt(d)) / (2 * a);
cout << "Root1 = " << root1 << " , Root2 = " << root2 <<
endl;
} else {
cout << "No real roots for this equation" << endl;
}
return 0;
}
Homework
1) Write a program that takes two points (x1, y1) & (x2, y2) and prints the equation of the straight
line joining them. In addition, after the program outputs the equation, it should ask for an input
x and prints the value of y obtained by substituting in the straight line equation.
2) Write a program that takes three integers and prints the maximum integer among the three. Try
different inputs to make sure of the correctness of the program.
3) Write a program that takes two points (x1, y1) & (x2, y2) and prints the distance between them
(using Euclidean distance).
4) Write a program that takes a character from the user. If the user entered ‘a’, the program prints
“apple”. If the user entered ‘b’, the program prints “banana”. If the user entered any other
letter, the program prints “Unknown letter”.
5) Write a program to evaluate each of the following expressions: (all parameters are input to the
programs)
a)
.
b) 5
c)
d) sin
Homework Policy
You should deliver a report containing the source code and at least 3 sample runs for each program
such as the ones in this lab.
You should solve this lab individually. If any copy is detected, both students will be given ZERO. If a
student repeats this another time, negative marks will be given.