Class Lec 03

You might also like

You are on page 1of 25

CSE 201

Structured Programming Language


Arithmetic Operators
Operators in C
• Operators are those signs used to manipulate or change a
data type to get the desirable result.
• Most common operators in C are + (Addition), -
(Subtraction), * (Multiplication), / (Division) and %
(Modulus).
• First three of these operators are very straightforward, we
will concentrate more on % .
• For calculations with operators only use first parentheses ( )
and not { } and [].
Modulus operator ( % )
• Modulus gives the remainder when one number is divided by
another.
• For example 16 % 3 = 1, 17 % 5 = 2.
• Getting the modulus will be very useful in many of
programming problems.
Example

Write a C code to take two inputs from the user and give output the sum
of them.
Example

Write a C code to take two integers and display the sum,


difference, product, division and modulus. Assume first
number is greater
Suppose in the previous example value of x is
given 24 and value of y is 3. Can you predict
the output of the code ?
Mathematical Problems
Now let us solve some simple mathematical problems by code.
1. Take the radius of a circle as input from the user and give output the
area of the circle.
2. Take the length and breadth of a rectangle as input from user and
give output the perimeter of the rectangle.
3. Take two inputs (integer) from the user and change the values in
the variables.
4. Repeat problem 3 without using another variable.
1. Take the radius of a circle as input from the user and give output the
area of the circle.
Problem 1
2. Take the length and breadth of a rectangle as input from user and
give output the perimeter of the rectangle.
Problem 2
3. Take two inputs (integer) from the user and change the values in the
variables.
Problem 3
Observations
• As you can see that in problem 3 we had to take another integer
c.

• Can you solve that problem without using that extra integer c ?

• That is the problem 4.


4. Repeat problem 3 without using another variable.
Problem 4
Class Task
• Take 5 integer from an user and give the average of the 5 integers as
the output.

N.B
• You are expected to let the user know that he has to input 5 integers.
• Remember that the average may not be an integer. Are you clear
about it ?
Solve
Additional Information
• Most of the times using more variables than necessary is inefficient.
• Writing complex equation is perfectly right in C. Some example are
given below:
• z= x+y+p/q;
• a= (b % c) + b + a;
• a= a * a * a;
• When you are writing lines like x=5*x then the value of x is changed
now and it becomes 5 times the previous value.
• Similarly writing x=x-3 reduces the value by 3.
Example

• Take an integer input and give the cube of it as the output.


Class Work

Solve

You might also like