[go: up one dir, main page]

0% found this document useful (0 votes)
21 views82 pages

Mek0101 - 04 - 25.10.2021

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 82

MEK0101:

Bilgisayar
Programlama I
2021-2022 Güz

Hafta 4

Dr. Selma YILMAZYILDIZ KAYAARMA


Plan for Today
• Recap of the last week
• Data Types – cont.
• Operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators

2
• printf() and scanf() in C
• Memory Concept and value assignment
Last Week • Variables in C
o Defining variables
o Types of variables (local, global, static, automatic, external)
• Data Types
o Basic data types
o Derived data types
o void

3
Plan for Today
• Recap of the last week
• Data Types - revisited
• Operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators

4
Data Types
Bits and Bytes; Numbers

• Most of us write numbers in:


• ie, 1, 2, 3,..., 9 form. Decimal (Base 10)
• or I, II, III, IV,..., IX form Roman numerals

• No matter what type of representation, most human beings can understand, at least the two types above.
➢ Unfortunately the computer doesn't.

5
Data Types
Bits and Bytes; Numbers
• Modern computers are built up with transistors.
• Whenever an electric current pass into the transistors either an ON or OFF status will be
established.
• Therefore the computer can only recognize two numbers, 0 for OFF, and 1 for
ON,
• which can be referred to as BIT.
• There is nothing in between Bit 0 and Bit 1
• eg Bit 0.5 doesn't exist.
• Hence computers can be said to be discrete machines.
• The number system consists only of two numbers is called Binary System. Binary (Base 2)
• And to distinguish the different numbering systems, the numbers human use,
ie 1,2,3,4..., will be called Decimals (since they are based 10 numbers)

6
Data Types
Bits and Bytes; Numbers

• How can computers understand numbers larger than 1?


• For example 2?
• 2 = 1+1 (like 10 = 9+1)
• the numbers are added, and overflow digit is carried over to the left position.
• So (decimal) 2 is represented in Binary as 10!
• See the table for the numbers 1 to 9 in both systems for comparison

7
Data Types
Bits and Bytes; Numbers

Why do we put 8 binary digits here?


8
Data Types
Bits and Bytes; Numbers

• The smallest unit in the computer's memory


to store data is called a BYTE
• 1 BYTE consists of 8 BITS!
• Computer memory is just a large array of
bytes! It is byte-addressable; you can’t
address (store location of) a bit; only a byte.

Why do we put 8 binary digits here?


9
Data Types
Bit Byte
• One byte = collection of 8 bits
• sA bit stores just a 0 or 1
• e.g. 0 1 0 1 1 0 1 0
• "In the computer it's all 0's and 1's" ... bits
• One byte can store one character, e.g. 'A' or 'x' or '$’
• In a chip: electric charge = 0/1
• "Byte" - unit of information storage
• In a hard drive: spots of North/South magnetism = 0/1
• A document, an image, a movie .. how many bytes?
• A bit is too small to be much use
• 1 byte is enough to hold about 1 typed character, e.g. 'b'
• Group 8 bits together to make 1 byte
or 'X' or '$'
• All storage is measured in bytes, despite being very
different hardware
• Kilobyte, KB, about 1 thousand bytes
• Megabyte, MB, about 1 million bytes
• Gigabyte, GB, about 1 billion bytes
• Terabyte, TB, about 1 trillion bytes (rare)

10
Data Types
Bits and Bytes; Numbers

Base 10

11
Data Types
Bits and Bytes; Numbers

Base 2

12
Data Types
Bits and Bytes; Numbers
Base 10 to Base 2
Question: What is 6 in base 2?

13
Data Types
Bits and Bytes; Numbers
Base 10 to Base 2
Question: What is 6 in base 2?
Calculation Result Remainder
6:2 3 0
3:2 1 1
1:2 1

14
Data Types
Bits and Bytes; Numbers
Base 10 to Base 2
Question: What is 6 in base 2?
Calculation Result Remainder
6:2 3 0
Result: 1 1 0
3:2 1 1
1:2 1

15
Data Types
Bits and Bytes; Numbers
Base 2 to Base 10
Question: What is the base-2 value of 1010 in base-10?

1 0 1 0

1*23 + 0*22 +1*21+0*20 = 8 + 0 + 2 + 0 = 10

16
Data Types
Bits and Bytes; Numbers

Question: What is the minimum and maximum base-10 value a single byte
(8 bits) can store?

17
Data Types
Bits and Bytes; Numbers

Question: What is the minimum and maximum base-10 value a single byte
(8 bits) can store?

Max:
Min: 0

18
Data Types
Bits and Bytes; Numbers
Hexadecimal (Base 16)
• When working with bits, oftentimes we have large numbers
• If we represent bits in base-16; this is called hexadecimal

19
Data Types
Bits and Bytes; Numbers
Hexadecimal (Base 16)
• Hexadecimal is base-16, so we need digits for 1-15. How do we do this?

20
Data Types
Bits and Bytes; Numbers
Hexadecimal (Base 16)

21
Data Types
Bits and Bytes; Numbers
Hexadecimal (Base 16)
• We distinguish hexadecimal numbers by prefixing them with 0x, and binary numbers
with 0b.
• E.g. 0xf5 is 0b11110101

22
Data Types
Bits and Bytes; Numbers
Hexadecimal to Binary
• What is 0x173A in binary?

23
Data Types
Bits and Bytes; Numbers
Binary to Hexadecimal
• What is 0b1111001010 in hexadecimal? (Hint: start from the right)

24
Data Types
Bits and Bytes; Numbers

Decimal (Base 10) Binary (Base 2) Octal (Base 8)

0 Start at 0 0 Start at 0 0 Start at 0

1 Then 1 1 Then 1 1 Then 1

2 Then 2 10 Start back at 0 again, but add 1 on the 2 Then 2


left 3 Then 3
3 Then 3
Bits11and Bytes; Numbers 4 Then 4
4 Then 4
100 start back at 0 again, and add one to the …. …
…. … number on the left...
... but that number is already at 1 so it …. ….
…. ….
also goes back to 0 ... 7 Up to 7
9 Up to 9 ... and 1 is added to the next position on
the left 10 Start back at 0
10 Start back at 0 again, again, but add 1 on
but add 1 on the left …. …
the left
11 …. …. 11
1001
25
Data Types
Bits and Bytes; Numbers

26
Data Types
Bits and Bytes; Numbers

Integer Representations

27
Data Types
Bits and Bytes; Numbers

Integer Representations

• Unsigned Integers: positive and 0 integers. (e.g. 0, 1, 2, … 99999…


• Signed Integers: negative, positive and 0 integers. (e.g. …-2, -1, 0, 1,… 9999…)

• Floating Point Numbers: real numbers. (e,g. 0.1, -12.2)

28
Data Types
Bits and Bytes; Numbers

Integer Representations

29
Data Types
Bits and Bytes; Numbers

Character Representations and ASCII format

30
Data Types
Bits and Bytes; Numbers

• As we have seen, the computers do not really understand the (decimal) numbers
we use, but only binary representations of them.

➢ They also don’t understand letters like "ABCDEFG...


• Whatever letters you input into the computer, the computer just saves it
there and delivers to you when you instruct it so.
• It saves these letters in the same Binary format as digits, in accordance to a
pattern.
• This pattern is called ASCII (pronounced ask-ee) which stands for American
Standard Code for Information Interchange.

31
Data Types
Bits and Bytes; Numbers

• ASCII is an encoding from common characters (letters, symbols, etc.) to bit


representations (chars).
• In ASCII format,
• the letter "A" is represented by "0100 0001"
• or most often, referred to decimal 65 in the ASCII Table.
• When performing comparison of characters, the computer actually looks up the
associated ASCII codes and compare the ASCII values instead of the characters.
• Therefore, the letter "B" which has ASCII value of 66 is greater than the letter "A"
with ASCII value of 65.

32
Data Types
Bits and Bytes; Numbers
ASCII Table:

33
Data Types
Bits and Bytes; Numbers

• Be careful!

34
Data Types
Bits and Bytes; Numbers

• Be careful!

Output:

35
Data Types
Bits and Bytes; Numbers

• Be careful!

Output: ?

36
Data Types
Bits and Bytes; Numbers

• Be careful!

Output:

37
Data Types
Formatting the output
• You can use more than the basic %f conversion character to format floating-point
values.

• here’s the format:

• The w sets the maximum width of the entire number, including the decimal
place. The p sets precision

• For example:

• This statement outputs four spaces and then 12.45.


• Those four spaces plus 12.45 (five characters total) equal the 9 in the width.

• It’s possible to specify the precision value without setting a width:


• Such as: %.2f
• When the output is greater than the width, the width is ignored.

38
Example

39
Data Types
Formatting the output (cont.)

• When the width value is specified for an integer, it can be used


to right-align the output.
• For example:
• This statement ensures that the output for value is right-
justified and at least four characters wide.
• If value is fewer than four characters wide, it’s padded with
spaces on the left.

• That is, unless you stick a 0 in there:
Output:
• In that case, the printf() function pads the width with zeros
to keep everything four characters wide.

40
Plan for Today
• Recap of the last week
• Data Types – cont.
• Operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators

42
Operators
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following
types of operators:

• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators

43
Arithmetic Operators
• Most C programs perform calculations using the C arithmetic operators
• The asterisk (*) indicates multiplication and the percent sign (%) denotes the
remainder operator
• In algebra, to multiply a times b, we simply place these single-letter variable
names side by side as in ab.
• In C, however, if we were to do this, ab would be interpreted as a single, two-
letter name (or identifier).
• Therefore, C requires that multiplication be explicitly denoted by using the *
operator as in a * b.
• The arithmetic operators are all binary operators.
• For example, the expression 3 + 7 contains the binary operator + and the
operands 3 and 7.

© 2016 Pearson Education, Ltd. All rights reserved.


44
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20 then

Details on
slide 75-78

45
Arithmetic Operators (cont.)

© 2016 Pearson Education, Ltd. All rights reserved.


46
Arithmetic Operators (cont.)
Integer Division and the Remainder Operator
• Integer division yields an integer result
• For example, the expression 7 / 4 evaluates to 1 and the
expression 17 / 5 evaluates to 3
• C provides the remainder operator, %, which yields the remainder
after integer division
• Can be used only with integer operands
• The expression x % y yields the remainder after x is divided by y
• Thus, 7 % 4 yields 3 and 17 % 5 yields 2

© 2016 Pearson Education, Ltd. All rights reserved.


47
Arithmetic Operators (cont.)
Rules of Operator Precedence
• C applies the operators in arithmetic expressions in a precise sequence determined
by the following rules of operator precedence, which are generally the same as
those in algebra:
• Operators in expressions contained within pairs of parentheses are evaluated first. Parentheses
are said to be at the “highest level of precedence.” In cases of nested, or embedded,
parentheses, such as
• ( ( a + b ) + c )
the operators in the innermost pair of parentheses are applied first.

© 2016 Pearson Education, Ltd. All rights reserved. 48


Arithmetic Operators (cont.)
• Multiplication, division and remainder operations are applied next. If an
expression contains several multiplication, division and remainder
operations, evaluation proceeds from left to right. Multiplication, division
and remainder are said to be on the same level of precedence.
• Addition and subtraction operations are evaluated next. If an expression
contains several addition and subtraction operations, evaluation proceeds
from left to right. Addition and subtraction also have the same level of
precedence, which is lower than the precedence of the multiplication,
division and remainder operations.
• The assignment operator (=) is evaluated last.

© 2016 Pearson Education, Ltd. All rights reserved.


49
Arithmetic Operators (cont.)

© 2016 Pearson Education, Ltd. All rights reserved.

50
Arithmetic Operators (cont.)

51
© 2016 Pearson Education, Ltd. All rights reserved.
#include
main() {
int a
<stdio.h>

= 21;
Example
int b = 10;
int c ;

c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}

52
Decision Making: Equality and Relational
Operators
• Executable C statements either perform actions (such as calculations or input
or output of data) or make decisions (we’ll soon see several examples of
these).
• We might make a decision in a program,
• for example, to determine whether a person’s grade on an exam is greater than or
equal to 60 and whether the program should print the message “Congratulations! You
passed.”
• This section introduces a simple version of C’s if statement that allows a
program to make a decision based on the truth or falsity of a statement of fact
called a condition.

© 2016 Pearson Education, Ltd. All rights reserved. 53


Decision Making: Equality and Relational
Operators
• If the condition is true (i.e., the condition is met) the statement in the body of
the if statement is executed.
• If the condition is false (i.e., the condition isn’t met) the body statement is not
executed.
• Whether the body statement is executed or not, after the if statement
completes, execution proceeds with the next statement after the if
statement.

© 2016 Pearson Education, Ltd. All rights reserved. 54


Decision Making: Equality and Relational
Operators
• The relational operators all have the same level of precedence and they
associate left to right.
• The equality operators have a lower level of precedence than the relational
operators and they also associate left to right.

© 2016 Pearson Education, Ltd. All rights reserved.


55
Decision Making: Equality and Relational
Operators

© 2016 Pearson Education, Ltd. All rights reserved. 56


Note: We’ll see if

Example statement in detail in the


coming weeks!

Output

57
Logical Operators
• C provides logical operators that may be used to form conditions, even more
complex conditions by combining simple conditions.
• Following table shows the logical operators supported by C language:

Operator Description
&& Logical AND operator
|| Logical OR Operator
! Logical NOT (negation) Operator

© 2016 Pearson Education, Ltd. All rights reserved.


58
Logical Operators (cont.)
Note: We’ll see if
Logical AND (&&) Operator statement in detail in the
coming weeks!
• Suppose we wish to ensure that two conditions are both true before we choose
a certain path of execution. In this case, we can use the logical operator && as
follows:
if (gender == 1 && age >= 65)
seniorFemales = seniorFemales + 1;
• This if statement contains two simple conditions:
• The condition gender == 1 might be evaluated, for example, to
determine if a person is a female.
• The condition age >= 65 is evaluated to determine whether a person
is a senior citizen.
• The two simple conditions are evaluated first because the precedences of ==
and >= are both higher than the precedence of &&.
59
© 2016 Pearson Education, Ltd. All rights reserved.
Logical Operators (cont.)
• The if statement then considers the combined condition
gender == 1 && age >= 65
Which is true if and only if both of the simple conditions are true.

• Finally, if this combined condition is true, then the count of seniorFemales is


incremented by 1.
• If either or both of the simple conditions are false, then the program skips the
incrementing and proceeds to the statement following the if.

© 2016 Pearson Education, Ltd. All rights reserved.


60
Logical Operators (cont.)
• NOTE: C evaluates all expressions that include relational operators, equality
operators, and/or logical operators to 0 or 1
• C sets a true value to 1, also it accepts any nonzero value as true.
• C sets a false value to 0

Truth table for the logical AND (&&) operator

© 2016 Pearson Education, Ltd. All rights reserved.


61
Logical Operators (cont.)
Logical OR (||) Operator

• Suppose that we wish to ensure at some point in a program that either or both
of two conditions are true before we choose a certain path of execution. In this
case, we use the || operator:
if (semesterAverage >= 90 || finalExam >= 90)
printf("Student grade is A");
• This statement also contains two simple conditions:
• The condition semesterAverage >= 90 is evaluated to determine
whether the student deserves an “A” in the course because of a solid
performance throughout the semester.
• The condition finalExam >= 90 is evaluated to determine whether
the student deserves an “A” in the course because of an outstanding
performance on the final exam.
62
© 2016 Pearson Education, Ltd. All rights reserved.
Logical Operators (cont.)
Logical OR (||) Operator

• The if statement then considers the combined condition:


semesterAverage >= 90 || finalExam >= 90
and awards the student an “A” if either or both of the simple conditions are true.

Truth table for the logical OR (||) operator

63
© 2016 Pearson Education, Ltd. All rights reserved.
Logical Operators (cont.)
• The && operator has a higher precedence than ||.
• Both operators associate from left to right.
• An expression containing && or || operators is evaluated only until truth or
falsehood is known.
• Thus, evaluation of the condition
gender == 1 && age >= 65
• will stop if gender is not equal to 1 (i.e., the entire expression is false), and continue if
gender is equal to 1 (i.e., the entire expression could still be true if age >= 65).
• This performance feature for the evaluation of logical AND and logical OR
expressions is called short-circuit evaluation.

© 2016 Pearson Education, Ltd. All rights reserved.

64
© 2016 Pearson Education, Ltd. All rights reserved.
Logical Operators (cont.)
Logical Negation (!) Operator

• C provides ! (logical negation) to enable you to “reverse” the meaning of a


condition.
• The logical negation operator has only a single condition as an operand (and is
therefore a unary operator).
• Placed before a condition when we’re interested in choosing a path of execution
if the original condition (without the logical negation operator) is false, such as:
if (!(grade == sentinelValue))
printf("The next grade is %f\n", grade);
• The parentheses around the condition grade == sentinelValue are needed
because the logical negation operator has a higher precedence than the equality
operator

65
© 2016 Pearson Education, Ltd. All rights reserved.
Logical Operators (cont.)

Truth table for the operator ! (logical negation)

66
© 2016 Pearson Education, Ltd. All rights reserved.
Logical Operators (cont.)
• In most cases, you can avoid using logical negation by expressing the condition
differently with an appropriate relational operator.
• For example, the preceding statement may also be written as follows:
if (grade != sentinelValue)
printf("The next grade is %f\n", grade);

67
© 2016 Pearson Education, Ltd. All rights reserved.
Example:
Logical Operators (cont.)

68
Assignment Operators
• We’ve already seen one assignment operator (=) several times.
= is a simple assignment operator and it assigns values from right
side operands to left side operand
• Additionally, C provides several assignment operators for abbreviating
assignment expressions.
• For example, the statement
c = c + 3;
• can be abbreviated with the addition assignment operator += as
c += 3;
• The += operator adds the value of the expression on the right of the
operator to the value of the variable on the left of the operator and
stores the result in the variable on the left of the operator.

© 2016 Pearson Education, Ltd. All rights reserved.


69
Assignment Operators
• Any statement of the form
variable = variable operator expression;
• where operator is one of the binary operators +, -, *, / or % (or
others), can be written in the form
variable operator= expression;
• Thus the assignment c += 3 adds 3 to c.

Arithmetic assignment operators


© 2016 Pearson Education, Ltd. All rights reserved.
70
Confusing Equality (==) and
Assignment (=) Operators
• There’s one type of error that C programmers, no matter how experienced, tend to
make so frequently.
• That error is accidentally swapping the operators == (equality) and = (assignment).
• What makes these swaps so damaging is the fact that:
• they do not ordinarily cause compilation errors.
• Rather, statements with these errors ordinarily compile correctly, allowing
programs to run to completion while likely generating incorrect results
through runtime logic errors.

71
© 2016 Pearson Education, Ltd. All rights reserved.
Confusing Equality (==) and
Assignment (=) Operators (cont.)
• Two aspects of C cause these problems:
• One is that any expression in C that produces a value can be used in the decision
portion of any control statement. If the value is 0, it’s treated as false, AND if the
value is nonzero, it’s treated as true.
• The second is that assignments in C produce a value, namely the value that’s
assigned to the variable on the left side of the assignment operator.

72
© 2016 Pearson Education, Ltd. All rights reserved.
Confusing Equality (==) and
Assignment (=) Operators (cont.)
• For example, suppose we intend to write: • This expression is a simple
if (payCode == 4) assignment whose value is the
printf(“%s“, "You get a bonus!"); constant 4.
but we accidentally write • Because any nonzero value is
if (payCode = 4) interpreted as “true,” the
printf(“%s“, "You get a bonus!"); condition in this if statement
• The first if statement properly awards a bonus to the is always true, and not only is
person whose paycode is equal to 4. the value of payCode
• The second if statement—the one with the error— inadvertantly set to 4, but the
evaluates the assignment expression in the if condition. person always receives a bonus
regardless of what the actual
paycode is!
73
© 2016 Pearson Education, Ltd. All rights reserved.
Confusing Equality (==) and
Assignment (=) Operators (cont.)
Confusing == and = in Standalone Statements • If x is equal to 1, the condition is true and
the expression returns the value 1.
• The other side of the coin can be equally • If x is not equal to 1, the condition is
unpleasant. false and the expression returns the
• Suppose you want to assign a value to a variable value 0.
with a simple statement such as • Regardless of what value is returned,
x = 1; there’s no assignment operator, so the
but instead write value is simply lost, and the value of x
x == 1; remains unaltered, probably causing an
• Here, too, this is not a syntax error. execution-time logic error.
• Rather the compiler simply evaluates the • Many compilers, however, will issue a
conditional expression. warning on such a statement.
74
© 2016 Pearson Education, Ltd. All rights reserved.
Increment and Decrement Operators
• C also provides the unary increment operator, ++, and the unary
decrement operator, --
• If a variable c is to be incremented by 1, the increment operator ++ can
be used rather than the expressions c = c + 1 or c += 1.
• If increment or decrement operators are placed before a variable (i.e.,
prefixed), they’re referred to as the preincrement or predecrement
operators, respectively.
• If increment or decrement operators are placed after a variable (i.e.,
postfixed), they’re referred to as the postincrement or postdecrement
operators, respectively.

© 2016 Pearson Education, Ltd. All rights reserved.


75
Increment and Decrement Operators
(cont.)
• Postincrementing the variable c causes it to be incremented after it’s
used in the printf statement.
• Preincrementing the variable c causes it to be incremented before it’s
used in the printf statement.

© 2016 Pearson Education, Ltd. All rights reserved.


76
Increment and Decrement Operators

Output

© 2016 Pearson Education, Ltd. All rights reserved.


77
Bitwise Operators
• Computers represent all data internally as sequences of bits.
• Each bit can assume the value 0 or the value 1.
• On most systems, a sequence of 8 bits forms a byte—the typical storage unit
for a variable of type char. Other data types are stored in larger numbers of
bytes.
• The bitwise operators are used to manipulate the bits of integral operands
both signed and unsigned.
• Unsigned integers are normally used with the bitwise operators.
• Bitwise operator works on bits and perform bit-by-bit operation.

© 2016 Pearson Education, Ltd. All rights reserved.


78
Bitwise Operators (cont.)

© 2016 Pearson Education, Ltd. All rights reserved.


79
Bitwise Operators (cont.)
Example:

• Assume A = 60 and B = 13 in decimal format. Their binary representations are:

© 2016 Pearson Education, Ltd. All rights reserved.


80
Bitwise Operators (cont.)
Example:

• Assume A = 60 and B = 13 in decimal format. Their binary representations are:


A = 0011 1100
B = 0000 1101
• A&B =
• A|B =
• A^B =
• ~A =

© 2016 Pearson Education, Ltd. All rights reserved.


81
Bitwise Operators (cont.)
Example:

• Assume A = 60 and B = 13 in decimal format. Their binary representations are:


A = 0011 1100
B = 0000 1101
• A&B = 0000 1100
• A|B = 0011 1101
• A^B = 0011 0001
• ~A = 1100 0011

© 2016 Pearson Education, Ltd. All rights reserved.


82
That’s it for today.
See you next week!

83

You might also like