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

Lab Manual 04 - Arithmetic Operators, Expressions and Math Functions.

The Lab Manual for Programming Fundamentals at the University of Management and Technology covers arithmetic operators, expressions, and math functions in C++. It includes objectives, useful concepts, examples, and exercises to help students understand key programming structures and type casting. The manual also provides lab rubrics for assessing problem understanding, programming structures, and solution development.

Uploaded by

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

Lab Manual 04 - Arithmetic Operators, Expressions and Math Functions.

The Lab Manual for Programming Fundamentals at the University of Management and Technology covers arithmetic operators, expressions, and math functions in C++. It includes objectives, useful concepts, examples, and exercises to help students understand key programming structures and type casting. The manual also provides lab rubrics for assessing problem understanding, programming structures, and solution development.

Uploaded by

rajabfan555
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Lab Manual: Programming Fundamentals

University of Management and Technology,


Lahore Campus

Lab- 04 Manual
Lab Instructor: Awais Amin
Department of Computer Science
Email: [email protected]
Lab 04: Arithmetic Operators, Arithmetic Expressions and Math
Functions

Table of Content

s
4.1 Objective................................................................................................................................................2
4.2 Scope......................................................................................................................................................2
4.3 Useful Concepts....................................................................................................................................2
4.4 Arithmetic Expressions:..........................................................................................................................2
4.5 Math function:.........................................................................................................................................3
4.7 Type Casting in C++...................................................................................................................8
4.8 Examples:............................................................................................................................................10
4.9 Exercise for Lab..................................................................................................................................13
4.10 Home Task...........................................................................................................................................14

Department of Computer Science, UMT, Lahore. 1 Awais Amin


Lab Manual: Programming Fundamentals

Lab Rubrics

Identify key programming


Areas Problem Understanding structures such as Design/ Development of Solutions
Assessed variables, loops, and
functions.
(CLO 1) (CLO 2) (CLO 3)
No able to identify key
Not able to understand Not able to Model a solution for a given
Poor programming structures such
Problem problem
as variables, loops, and
functions.

Partially able identify Modeled an average solution for


Able to partially understand
Average key programming a given problem using
the problem
structures such as programming principles
variables, loops, and
functions.

Thoroughly identify key


Modeled a proper solution for a given
Very Good Fully Understand the problem programming structures
problem using programming principles
such as variables, loops,
and functions.

4.1 Objective
Learn using operators, expressions and math functions.

4.2 Scope
The student should know the following at the end of this lab:
1. Arithmetic Operators

2. Arithmetic Expressions

3. Math Functions

4. Writing Complete Programs

4.3 Useful Concepts

4.4 Arithmetic Expressions:

Department of Computer Science, UMT, Lahore. 2 Awais Amin


Lab Manual: Programming Fundamentals

Arithmetic expressions contain a combination of the arithmetic operations including


brackets: x = z – (a + b / 2) + w * -y
To evaluate the expression, we need to follow the precedence rule which is as follows:

1. ( ) expression within parentheses


2. +, - unary operators (plus and minus sign)
3. *, /, % multiplication, division and remainder are evaluated from left to right
4. +, - addition and subtraction are evaluated from left to right

4.5 Math function:


To do some advanced mathematical functions in C, there is a header file called <cmath > that has different
trigonometric and algebraic functions. Here are some frequently used functions:
pow(x,y) xy pow(5,3) = 53 = 125

sqrt(x) x (x > 0) sqrt(4) = 4 =2


log(x) ln x (x > 0) log(5) = 1.6094

log10(x) log10 x
(x > 0) log10(5) = 0.698970
exp(x) ex exp(2) = 7.3891
sin(x) sin x (x in radian) sin(90) = 0.893997

cos(x) cos x (x in radian) cos(90) = -0.448074


tan(x) tan x (x in radian) tan(90) = -1.9952
-1
asin(x) sin x ( x in [-1,1]) asin (0) = 0
acos(x) cos-1 x (x in [-1,1]) acos(0) = 1.570796
-1
atan(x) tan x atan(0) = 0
Note that you have to include the header file cmath before you use any of these functions. Also, the return
type of these functions is double.

4.6. OPERATORS
Operators are in C++ to perform operations on variables and constants. Operators in C++ are:
 Arithmetic Operators
 Relation Operators
 Logical Operators
 Assignment Operators
 Compound Operators

1) Arithmetic Operator:
To solve most programming problems, you will need to write arithmetic expressions that manipulate type
int and double data. In C language, these are the basic arithmetic operators: addition (+), subtraction (-),
multiplication (*), division (/), and remainder (%).
If the operands are of different types, the one with weaker type will be raised to the level of the other type,

Department of Computer Science, UMT, Lahore. 3 Awais Amin


Lab Manual: Programming Fundamentals

then the operation will be performed. The order is char, int, long, float, double.
The division between two integer numbers results in an integer result (as you can see 5/2 gives 2 not 2.5). The
division by zero is undefined. Either you get a compilation warning or a run time error.
The remainder operator % is related to the division one. This operator will give the remainder produced by
dividing the two numbers (5 % 2 = 1). Therefore, this operator is not used with double values. If one of the
operand or both are double, you will get an error message from the compiler saying: illegal use of floating
point
Basic arithmetic operators in C++ are: *, /, -, +, ++, -- are the arithmetic operators.

Example:
Suppose X and Y are two variables with X=5, Y=10

OPERATORS DESCRIPTION EXAMPLE


+ Adds both operands X + Y = 15
- Subtracts both operands Y-X=5
* Multiply both operands X * Y = 150
/ Divide both operands Y/X=2
% Remainder after division Y/X=0
of numbers
++ Increase operator by 1 X++ = 6
-- Decrease operator by 1 Y-- = 9

2) Relational Operators
Relational Operators perform comparison between the
variables. It gives Boolean values, if the condition is fulfilled
it becomes true otherwise false.

Example
Suppose A=5 and B=10.

OPERATORS DESCRIPTION EXAMPLE


> Checks which operand is (A>B) False
greater than the other. (B>A) True
< Checks which operand is (A<B) True
smaller. (A<B) False
>= Checks whether the operand is (A>=B) False
greater than or equal to the other (B>=A) True
operand.
<= Checks whether the operand is (A<=B) True
smaller than or equal to the other (B>=A) False
operand.
!= Checks whether both the (A!=B) True
operands are not equal.
== Checks whether both the (A==B) False
operands values is equal.

Department of Computer Science, UMT, Lahore. 4 Awais Amin


Lab Manual: Programming Fundamentals

3) Logical Operators
Logical operators check whether the condition is true or false.
Example:
Suppose if X=10 and Y=5
OPERATORS DESCRIPTION EXAMPLE
AND TRUE: If both the conditions (X==10 && Y==5) TRUE
are true.
|| True: If only one condition is (X==10 && Y==8) TRUE
true.
! It reverses the state of its !(X==Y) TRUE
operand.

4) Assignment Operators
The assignment operator is used to assign a value to a variable. x=5. It means, 5 is
assigned to variable to x. x=y; It means, the value of y is assigned to x.

5) Compound Operators
They modify the variable by performing an operation on it.

Department of Computer Science, UMT, Lahore. 5 Awais Amin


Lab Manual: Programming Fundamentals

Example:
#include <iostream>
using namespace std;
void main(){
int a=0,b=1,c=2,d=4,e=8;
a+=2;
cout<<"Value of a is "<<a; b-
=8;
cout<<"Value of b is "<<b;
c*=4;
cout<<"Value of c is "<<c;
d/=2;
cout<<"Value of d is "<<d; e
%=4;
cout<<"Value of e is "<<e;
}

Output:
Value of a is 2
Value of b is -7 Value of c is 8 Value
of d is 2 Value of e is 0

NAMED CONSTANT
A named constant is like a variable, but its content is read-only, and cannot be changed while the program is
running. Here is a definition of a named constant:
const double INTEREST_RATE = 0.129;
It looks just like a regular variable definition except that the word const appears before the data type name, and
the name of the variable is written in all uppercase characters. The key word const is a qualifier that tells the
compiler to make the variable read-only. Its value will remain constant throughout the program’s execution. It is
not required that the variable name be written in all uppercase characters, but many programmers prefer to write
them this way so they are easily distinguishable from regular variable names.
Example:

This program calculates the area of a circle.


// The formula for the area of a circle is PI times
// The radius squared. PI is 3.14159. #include <iostream>
#include <math.h> // needed for pow function (See Book Page 127 for
more information) using namespace std;
int main()
{
const double PI = 3.14159;
double area, radius;
cout << "This program calculates the area of a circle.\n";
cout << "What is the radius of the circle? ";

Department of Computer Science, UMT, Lahore. 6 Awais Amin


Lab Manual: Programming Fundamentals

cin >> radius;


area = PI * pow(radius, 2.0);
cout << "The area is " << area << endl; return 0;}

Output:
This program calculates the area of a circle. What is the radius of the
circle? 2
The area is 12.56

1. Variable Declaration and Initialization:


Declare an integer variable called `age` and initialize it with your age. Then, declare a string variable called
`name` and initialize it with your name. Finally, display a message that includes both your name and age.

2. Data Type Conversion:


Create a program that calculates the area of a rectangle. Prompt the user to input the length and width of the
rectangle as floating-point numbers. Calculate the area (length * width) and display it as a floating-point
number.

3. Constants and Data Types:

Department of Computer Science, UMT, Lahore. 7 Awais Amin


Lab Manual: Programming Fundamentals

Declare a constant integer named `MAX_SCORE` and set it to 100. Then, declare a variable named
`playerScore` and initialize it with a score between 0 and `MAX_SCORE`. Display the player's score and the
maximum possible score.

4. String Manipulation:
Declare two string variables, `firstName` and `lastName`, and initialize them with your first and last name,
respectively. Concatenate these two strings to form your full name and display it.

5. Print a line on the console:


Write a program to display a line using getline.

4.7 Type Casting in C++


Type casting refers to the conversion of one data type to another in a program. Typecasting can
be done in two ways: automatically by the compiler and manually by the programmer or user.
Type Casting is also known as Type Conversion.

Type Conversion or Explicit Type Casting.

Department of Computer Science, UMT, Lahore. 8 Awais Amin


Lab Manual: Programming Fundamentals

Implicit Type Casting or Implicit Type Conversion

 It is known as the automatic type casting.


 It automatically converted from one data type to another without any external intervention such as
programmer or user. It means the compiler automatically converts one data type to another.
 All data type is automatically upgraded to the largest type without losing any information.
 It can only apply in a program if both variables are compatible with each other.

Code:
#include <iostream>
using namespace std;
int main ()
{
short x = 200;
int y;
y = x;
cout << " Implicit Type Casting " << endl;
cout << " The value of x: " << x << endl;
cout << " The value of y: " << y << endl;

int num = 20;


char ch = 'a';
int res = 20 + 'a';
cout << " Type casting char to int data type ('a' to 20): " << res << endl;

float val = num + 'A';


cout << " Type casting from int data to float type: " << val << endl;
return 0;
}

Explicit Type Casting or Explicit Type Conversion

 It is also known as the manual type casting in a program.


 It is manually cast by the programmer or user to change from one data type to another type in a
program. It means a user can easily cast one data to another according to the requirement in a program.
 It does not require checking the compatibility of the variables.
 In this casting, we can upgrade or downgrade the data type of one variable to another in a program.

Department of Computer Science, UMT, Lahore. 9 Awais Amin


Lab Manual: Programming Fundamentals

Code:
#include <iostream>
using namespace std;
int main ()
{
// declaration of the variables
int a, b;
float res;
a = 21;
b = 5;
cout << " Implicit Type Casting: " << endl;
cout << " Result: " << a / b << endl; // it loses some information

cout << " \n Explicit Type Casting: " << endl;


// use cast () operator to convert int data to float
res = (float) 21 / 5;
cout << " The value of float variable (res): " << res << endl;
return 0;
}

4.8Examples:

Example 4.1: This program illustrates some arithmetic properties of integer (int) variables.
Trace through the program to make sure you understand the values of each variable in all
stages of the program.

#include <iostream>
using namespace std; int
main()
{
int a=4, b=0, c=0;
cout<<"a = "<<a<<" b = "<<b<<" c = "<<c<<endl; b=6;
c=a+b;
cout<<"a = "<<a<<" b = "<<b<<" c = "<<c<<endl;

Department of Computer Science, UMT, Lahore. 10 Awais Amin


Lab Manual: Programming Fundamentals

a++; //this statement is similar to a=a+1;


b -= 2; //this statement is similar to b= b-2;
--c; //this statement is similar to c=c-1; cout<<"a =
"<<a<<" b = "<<b<<" c = "<<c<<endl;
b *= ++a; //a=a+1;, b=b*a;
cout<<"a = "<<a<<" b = "<<b<<" c = "<<c<<endl; c /= a+
+; //c=c/a;, a=a+1; cout<<"a =
"<<a<<" b = "<<b<<" c = "<<c<<endl;
a = (b+c)*4; //First (b+c) then multiply the result with 4. c = b+c*4;
//First c*4 then result is added with b. cout<<"a = "<<a<<"
b = "<<b<<" c = "<<c<<endl;
return 0;
}

Department of Computer Science, UMT, Lahore. 11 Awais Amin


Lab Manual: Programming Fundamentals

The output for the above program is

Example 4.2: Input a 3-digit value from the user (for example 521) and display it
in reverse order (i.e. 125).
#include <iostream>
using namespace std; int
main()
{
int n,a,b;
cout<<"Enter the 3 digit value to be reversed:"; cin>>n;
a=n/
100;
n=n
%100;
b=n/
10;
n=n
%10;
cout<<"The reverse order is:"<<n<<b<<a<<endl; return 0;
}

The output of this program is shown below

Department of Computer Science, UMT, Lahore. 12 Awais Amin


Lab Manual: Programming Fundamentals

Example 4.3: Input the values for base and exponent and calculate its power using the
pow(x,y) built in function.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int expo;
double base, result=0;
cout<<"enter the value for the base:";
cin>>base;
cout<<"enter the value for the exponent:"; cin>>expo;
result = pow(base,expo);
cout<<"The result is: "<<result<<endl; return
0;
}

The output for the given program is

4.9 Exercise for Lab

Exercise 4.1: Write a program that finds the area of a triangle given the length of its sides: a, b, c.
area  s  s  a   s  b s  c
abc
s 2

Exercise 4.2: Write a program taking two values as inputs from the user and display the results for
all the basic arithmetic operations performed on them
Addition
Subtraction
Multiplicatio
n Division
Modulus
Exercise 4.3: Write a program that inputs a 4 digit value from the user (for example 6382) and

Department of Computer Science, UMT, Lahore. 13 Awais Amin


Lab Manual: Programming Fundamentals

displays a result with an increment of 1 in each digit (i.e. 7493)

Department of Computer Science, UMT, Lahore. 14 Awais Amin


Lab Manual: Programming Fundamentals

4.10 Home Task


1. Write a program that takes any ASCII value from user and display next five char after
that ASCII value.
2. Write a program that reads a four digit number from user, then the program separates
digits of the number e.g. 4567 to be displayed as:
4
5
6
7

Department of Computer Science, UMT, Lahore. 15 Awais Amin

You might also like