You are on page 1of 17

Programming for

Engineers I
Mohammad Shahid Qureshi
NU-FAST

Week 3&4

Explicit Type casting


2

Example
int total = 1100;
int acquired_marks = 860;
float percentage = acquired_marks/
(float)total * 100;

Octal Number System


3

In the octal (base 8) number system, the


digits range from 0 to 7.
In the octal number 425, 5 is written in
the ones position, the 2 is written in the
eights position, and the 4 is written in
the sixty-fours position

Hexadecimal Number
4

The hexadecimal (base 16) number system


requires sixteen digits
Lowest is 0 and a highest digit with a value
equivalent to decimal 15 (one less than the
base of 16)
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
Why use HEXADECIMAL?

Representation for
Hexadecimal
Binary
0000
0001
0010
0011
0100
0101
0110
0111

Hex
0
1
2
3
4
5
6
7

Binary
1000
1001
1010
1011
1100
1101
1110
1111

Hex
8
9
A
B
C
D
E
F

Binary to Hexadecimal
6

Format specifier
7

%x

%o

To input or output a number in hexadecimal


format
To input or output a number in octal format

Printing \ and % with printf


Add the same character before these, e.g.,
printf(\\n inserts new line);
printf(he got 80%% marks);

Decision Making

if structure

Make decision based on truth or falsity of


some condition
If

condition met, body executed otherwise not

Use of if in C
if (condition)
{
.
.
}

Body of if

A program can have multiple if structures in a program

Condition

To find whether a condition occurs or not,


we need to compare and relate two things

For this we use relational operators

Following relational operators are used:


x
x
x
x
x
x

== y
!= y
<y
>y
<= y
>= y

(x
(x
(x
(x
(x
(x

is
is
is
is
is
is

equal to y)
not equal to y)
less than y)
greater than y)
less than and equal to y)
greater than and equal to y)

Where x and y can be a value or a variable

11

Grade calculatoin based on


percentage
Demo
Show use of if
Show use of if-else if-else

Mapping numbers to grades

Logical operators

Sometimes we need to group two (or


more) relational conditions like:

x > 5 AND x < 10


x < 5 OR x > 10
x is NOT < 10

In language construct we write as:

(x > 5 && x < 10)


(x < 5 || x > 10)
!(x < 10)

Priority of Operators
Operators

Type

Logical NOT

*/%

Arithmetic and
modulus

+-

Arithmetic

< > <= >=

Relational

== !=

Relational

&&

Logical AND

||

Logical OR

Assignment

Different forms of if
15

Different forms of if
16

Example
17

What will be the output if:


a=1 and b=2
or a=1 and b=1
or a=2 and b=1

The rule is that an else


attaches to the nearest if

You might also like