Co101-Lecture Notes Part 1
Co101-Lecture Notes Part 1
MISCONCEPTION 1:
Computer science is the study of computers.
MISCONCEPTION 2:
Computer science is the study of how to write computer programs.
MISCONCEPTION 3:
Computer science is the study of the uses and applications of
computers and software.
2
What is computer science?
Computer science is the study of
algorithms including
3
An example of a very simple
algorithm
1. Wet your hair. Observe:
2. Lather your hair.
Operations need not be
3. Rinse your hair.
executed by a computer
4. Stop.
only, but by any entity
capable of carrying out the
operations listed.
4
A more complex example
Searching for a word in a dictionary
1. Start with page 1
2. Start with the first word on the page
3. If this word is the same as the target word, then
read its meaning
go to step 7
4. If more words on this page
move to the next word on this page
go to step 3
5. If reached the end of this page and more pages remain
move to next page
go to step 2
6. Declare target word as not found
7. Stop.
5
A more efficient algorithm
https://www.youtube.com/watch?v=OUP-
F5Oeng8
6
Formal and mathematical
properties of algorithms
Properties of an algorithm:
How efficient is it?
What kinds of resources must be used to
execute it?
How does it compare to other algorithms
that solve the same problem?
7
Linguistic realizations to
express algorithms
How do we represent algorithms?
Pseudocode, high level programming
languages, low level programming
languages
8
Course Materials
Additional books:
1. Programming with C, by Byron Gottfried
2. The C Programming Language, by Brian W Kernighan, Dennis
M Ritchie
10
Linguistic realizations to
express algorithms
Algorithms operate on data. Closely
intertwined is the representation of data
12
Simple data structure example
Find correlations
between interests,
use this to “pre fill” the
UxI matrix or to
reduce the interest
dimensions
At heart: Matrix
operations on very
large matrices.
More challenges:
Efficient search given
many ads to choose
from? 13
Hardware realizations to
execute algorithms
Algorithms need not execute on machines. All
we really need are computing entities.
Anything that can compute – e.g., a human.
But, ultimately, most of our interest will lie with
algorithms that execute on computing entities
called "computers".
How are these entities constructed?
14
Applications of algorithms
What are some of the many important
and popular applications of computers
in current use including:
modeling and simulation
information retrieval
numerical problem solving
data analysis
artificial intelligence
networking
graphics
15
What is computer science?
Computer science is the study of
algorithms including
16
Algorithm and Flowchart
ALGORITHMS AND
FLOWCHARTS
A typical programming task can be divided into
two phases:
Problem solving phase
◦ produce an ordered sequence of steps that describe
solution of problem
◦ this sequence of steps is called an algorithm
Implementation phase
◦ implement the program in some programming
language
Steps in Problem Solving
First produce a general algorithm (one can use
pseudocode)
Refine the algorithm successively to get step by
step detailed algorithm that is very close to a
computer language.
Pseudocode is an artificial and informal language
that helps programmers develop algorithms.
Pseudocode is very similar to everyday English.
Pseudocode & Algorithm
Example 1: Write an algorithm to
determine a student’s final grade and
indicate whether it is passing or failing. The
final grade is calculated as the average of
four marks.
Pseudocode & Algorithm
Pseudocode:
Input a set of 4 marks
Calculate their average by summing and dividing by
4
if average is below 50
Print “FAIL”
else
Print “PASS”
Pseudocode & Algorithm
Detailed Algorithm
Step 1: Input M1,M2,M3,M4
Step 2: GRADE ¬ (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
The Flowchart
(Dictionary) A schematic representation of a sequence of
operations, as in a manufacturing process or computer
program.
(Technical) A graphical representation of the sequence
of operations in an information system or program.
Program flowcharts show the sequence of instructions in
a single program or subroutine.
STOP
Example 2
Write an algorithm and draw a flowchart to
convert the length in feet to centimeter.
Pseudocode:
Input the length in feet (Lft)
Calculate the length in cm (Lcm) by multiplying LFT with 30
Print length in cm (LCM)
Example 2
Algorithm
START
Step 1: Input Lft
Step 2: Lcm ¬ Lft x 30 Input
Lft
Step 3: Print Lcm
Lcm ¬ Lft x 30
Print
Lcm
Flowchart
STOP
Example 3
Write an algorithm and draw a flowchart that
will read the two sides of a rectangle and
calculate its area.
Pseudocode
Input the width (W) and Length (L) of a rectangle
Calculate the area (A) by multiplying L with W
Print A
Example 3
Algorithm START
Step 3: Print A
A¬LxW
Print
A
STOP
Example 4
Write an algorithm and draw a flowchart that will
calculate the roots of a quadratic equation
ax 2 + bx + c = 0
Hint: d = sqrt (b 2 - 4ac ), and the roots are: x1 = (–b
+ d)/2a and x2 = (–b – d)/2a
Example 4
Pseudocode:
Input the coefficients (a, b, c) of the quadratic equation
Calculate d
Calculate x1
Calculate x2
Print x1 and x2
START
Example 4 Input
a, b, c
Algorithm:
d ¬ sqrt(b x b – 4 x a x c)
Step 1: Input a, b, c
Step 2: d ¬ sqrt ( b ´ b - 4 ´ a ´)c x1 ¬(–b + d) / (2 x a)
Step 3: x1 ¬ (–b + d) / (2 x a)
X2 ¬ (–b – d) / (2 x a)
Step 4: x2 ¬ (–b – d) / (2 x a)
Step 5: Print x1, x2 Print
x1 ,x2
STOP
Number
Representation
1
Number System :: The Basics
We are accustomed to using the so-called
decimal number system
Ten digits :: 0,1,2,3,4,5,6,7,8,9
Every digit position has a weight which is a
power of 10
Base or radix is 10
Example:
234 = 2 x 102 + 3 x 101 + 4 x 100
250.67 = 2 x 102 + 5 x 101 + 0 x 100 + 6 x
10-1 + 7 x 10-2 2
Binary Number System
Two digits:
0 and 1
Every digit position has a weight which is a
power of 2
Base or radix is 2
Example:
110 = 1 x 22 + 1 x 21 + 0 x 20
101.01 = 1 x 22 + 0 x 21 + 1 x 20 + 0 x 2-1 +
1 x 2-2
3
Positional Number Systems (General)
Decimal Numbers:
10 Symbols {0,1,2,3,4,5,6,7,8,9}, Base or Radix is 10
136.25 = 1 102 + 3 101 + 6 100 + 2 10–1 + 3 10–2
4
Positional Number Systems (General)
Decimal Numbers:
10 Symbols {0,1,2,3,4,5,6,7,8,9}, Base or Radix is 10
136.25 = 1 102 + 3 101 + 6 100 + 2 10–1 + 3 10–2
Binary Numbers:
2 Symbols {0,1}, Base or Radix is 2
101.01 = 1 22 + 0 21 + 1 20 + 0 2–1 + 1 2–2
5
Positional Number Systems (General)
Decimal Numbers:
10 Symbols {0,1,2,3,4,5,6,7,8,9}, Base or Radix is 10
136.25 = 1 102 + 3 101 + 6 100 + 2 10–1 + 5 10–2
Binary Numbers:
2 Symbols {0,1}, Base or Radix is 2
101.01 = 1 22 + 0 21 + 1 20 + 0 2–1 + 1 2–2
Octal Numbers:
8 Symbols {0,1,2,3,4,5,6,7}, Base or Radix is 8
621.03 = 6 82 + 2 81 + 1 80 + 0 8–1 + 3 8–2
6
Positional Number Systems (General)
Decimal Numbers:
10 Symbols {0,1,2,3,4,5,6,7,8,9}, Base or Radix is 10
136.25 = 1 102 + 3 101 + 6 100 + 2 10–1 + 3 10–2
Binary Numbers:
2 Symbols {0,1}, Base or Radix is 2
101.01 = 1 22 + 0 21 + 1 20 + 0 2–1 + 1 2–2
Octal Numbers:
8 Symbols {0,1,2,3,4,5,6,7}, Base or Radix is 8
621.03 = 6 82 + 2 81 + 1 80 + 0 8–1 + 3 8–2
Hexadecimal Numbers:
16 Symbols {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F}, Base is 16
6AF.3C = 6 162 + 10 161 + 15 160 + 3 16–1 + 12 16–2
7
Binary-to-Decimal Conversion
Each digit position of a binary number has
a weight
Some power of 2
A binary number:
B = bn-1 bn-2 …..b1 b0 . b-1 b-2 ….. b-m
Corresponding value in decimal:
n-1
D= bi 2i
i = -m
8
Examples
101011 1x25 + 0x24 + 1x23 + 0x22 + 1x21 + 1x20
= 43
(101011)2 = (43)10
(101.11)2 = (5.75)10
9
Decimal to Binary: Integer Part
Consider the integer and fractional parts separately.
For the integer part:
Repeatedly divide the given number by 2, and go on
accumulating the remainders, until the number becomes zero.
Arrange the remainders in reverse order.
Base NumbRem
2 89
2 44 1
2 22 0
2 11 0
2 5 1
2 2 1
2 1 0
0 1
(89)10 = (1011001)2
10
Decimal to Binary: Integer Part
Consider the integer and fractional parts separately.
For the integer part:
Repeatedly divide the given number by 2, and go on
accumulating the remainders, until the number becomes zero.
Arrange the remainders in reverse order.
Base NumbRem
2 66
2 89 2 33 0
2 44 1 2 16 1
2 22 0 2 8 0
2 11 0 2 4 0
2 5 1 2 2 0
2 2 1 2 1 0
2 1 0 0 1
0 1
(66)10 = (1000010)2
(89)10 = (1011001)2
11
Decimal to Binary: Integer Part
Consider the integer and fractional parts separately.
For the integer part:
Repeatedly divide the given number by 2, and go on
accumulating the remainders, until the number becomes zero.
Arrange the remainders in reverse order.
Base NumbRem 2 239
2 66 2 119 1
2 89 2 33 0 2 59 1
2 44 1 2 16 1 2 29 1
2 22 0 2 8 0 2 14 1
2 11 0 2 4 0 2 7 0
2 5 1 2 2 0 2 3 1
2 2 1 2 1 0 2 1 1
2 1 0 0 1 0 1
0 1
(66)10 = (1000010)2
(89)10 = (1011001)2 (239)10 = (11101111)2
12
Decimal to Binary: Fraction Part
Repeatedly multiply the given fraction by 2.
Accumulate the integer part (0 or 1).
If the integer part is 1, chop it off.
Arrange the integer parts in the order they are obtained.
Example: 0.634
.634 x 2 = 1.268
.268 x 2 = 0.536
.536 x 2 = 1.072
.072 x 2 = 0.144
.144 x 2 = 0.288
:
:
(.634)10 = (.10100……)2
13
Decimal to Binary: Fraction Part
Repeatedly multiply the given fraction by 2.
Accumulate the integer part (0 or 1).
If the integer part is 1, chop it off.
Arrange the integer parts in the order they are obtained.
0 0000 8 1000
1 0001 9 1001
2 0010 A 1010
3 0011 B 1011
4 0100 C 1100
5 0101 D 1101
6 0110 E 1110
7 0111 F 1111
16
Binary-to-Hexadecimal
Conversion
For the integer part,
Scan the binary number from right to left
Translate each group of four bits into the
corresponding hexadecimal digit
Add leading zeros if necessary
18
Hexadecimal-to-Binary
Conversion
Translate every hexadecimal digit into its
4-bit binary equivalent
Examples:
(3A5)16 = (0011 1010 0101)2
(12.3D)16 = (0001 0010 . 0011 1101)2
(1.8)16 = (0001 . 1000)2
19
Unsigned Binary Numbers
An n-bit binary number
B = bn-1bn-2 …. b2b1b0
2n distinct combinations are possible, 0 to 2n-1.
For example, for n = 3, there are 8 distinct
combinations
000, 001, 010, 011, 100, 101, 110, 111
Range of numbers that can be represented
n=8 0 to 28-1 (255)
n=16 0 to 216-1 (65535)
n=32 0 to 232-1 (4294967295)
20
Signed Integer Representation
Many of the numerical data items that are used
in a program are signed (positive or negative)
Question:: How to represent sign?
bn-1 bn-2 b1 b0
Sign
Magnitude
22
Contd.
Range of numbers that can be
represented:
Maximum :: + (2n-1 – 1)
Minimum :: (2n-1 – 1)
A problem:
Two different representations of zero
+0 0 000….0
-0 1 000….0
23
One’s Complement
Representation
Basic idea:
Positive numbers are represented exactly as in
sign-magnitude form
Negative numbers are represented in 1’s
complement form
How to compute the 1’s complement of a number?
Complement every bit of the number (1 0 and
0 1)
MSB will indicate the sign of the number
0 positive
1 negative
24
Example :: n=4
0000 +0 1000 -7
0001 +1 1001 -6
0010 +2 1010 -5
0011 +3 1011 -4
0100 +4 1100 -3
0101 +5 1101 -2
0110 +6 1110 -1
0111 +7 1111 -0
29
Contd.
In C
short int
16 bits + (215-1) to -215
int or long int
32 bits + (231-1) to -231
long long int
64 bits + (263-1) to -263
30
31
Adding Binary Numbers
Basic Rules: Example:
0+0=0
0+1=1 01101001
1+0=1 00110100
1+1=0 (carry 1) -------------
10011101
32
Subtraction Using Addition :: 1’s
Complement
How to compute A – B ?
Compute the 1’s complement of B (say, B1).
Compute R = A + B1
If the carry obtained after addition is ‘1’
Add the carry back to R (called end-around carry)
That is, R = R + 1
The result is a positive number
Else
The result is negative, and is in 1’s complement
form
33
Example 1 :: 6 – 2
1’s complement of 2 = 1101
Assume 4-bit
6 :: 0110 A representations
-2 :: 1101 B1 Since there is a carry, it is
1 0011 R added back to the result
1 The result is positive
0100 +4
End-around
carry
34
Example 2 :: 3 – 5
1’s complement of 5 = 1010
3 :: 0011 A
-5 :: 1010 B1
Assume 4-bit representations
1101 R
Since there is no carry, the
result is negative
1101 is the 1’s complement of
0010, that is, it represents –2
-2
35
Subtraction Using Addition :: 2’s
Complement
How to compute A – B ?
Compute the 2’s complement of B (say, B2)
Compute R = A + B2
If the carry obtained after addition is ‘1’
Ignore the carry
The result is a positive number
Else
The result is negative, and is in 2’s complement
form
36
Example 1 :: 6 – 2
2’s complement of 2 = 1101 + 1 = 1110
37
Example 2 :: 3 – 5
2’s complement of 5 = 1010 + 1 = 1011
3 :: 0011 A
-5 :: 1011 B2 Assume 4-bit representations
38
2’s complement arithmetic: More
Examples
Example 1: 18-11 = ?
18 is represented as 00010010
11 is represented as 00001011
1’s complement of 11 is 11110100
2’s complement of 11 is 11110101
Add 18 to 2’s complement of 11
00010010
+ 11110101 00000111 is 7
----------------
00000111 (with a carry of 1
which is ignored) 39
Example 2: 7 - 9 = ?
7 is represented as 00000111
9 is represented as 00001001
1’s complement of 9 is 11110110
2’s complement of 9 is 11110111
Add 7 to 2’s complement of 9
00000111
+ 11110111 11111110 is -2
----------------
11111110 (with a carry of 0
which is ignored) 40
Overflow/Underflow:
Adding two +ve (-ve) numbers should not produce a
–ve (+ve) number. If it does, overflow (underflow) occurs
41
Overflow/Underflow:
Adding two +ve (-ve) numbers should not produce a
–ve (+ve) number. If it does, overflow (underflow) occurs
42
Overflow/Underflow:
Adding two +ve (-ve) numbers should not produce a
–ve (+ve) number. If it does, overflow (underflow) occurs
(64) 01000000
( 4) 00000100
--------------
(68) 01000100
carry (out)(in)
0 0
43
Overflow/Underflow:
Adding two +ve (-ve) numbers should not produce a
–ve (+ve) number. If it does, overflow (underflow) occurs
48
IEEE 754 Floating-Point Format
(Single Precision)
S E (Exponent) M (Mantissa)
(31) (30 … 23) (22 … 0)
1 10001100 11011000000000000000000
50
Representing 0.3
S E (Exponent) M (Mantissa)
(31) (30 … 23) (22 … 0)
0.3 (decimal)
= 0.0100100100100100100100100…
= 1.00100100100100100100100100… 2 2
= 1.00100100100100100100100100… 2 125 127
0 01111101 00100100100100100100100
0 00000000 00000000000000000000000
1 00000000 00000000000000000000000
Representing Inf ( )
0 11111111 00000000000000000000000
1 11111111 00000000000000000000000
78
First C program – print on screen
#include <stdio.h>
void main()
{
printf ("Hello, World! \n") ;
}
79
More printing … (code and see)
#include <stdio.h>
void main()
{
printf ("Hello, World! ") ;
printf ("Hello \n World! \n") ;
}
80
Some more printing
#include <stdio.h>
void main()
{
printf ("Hello, World! \n") ;
printf ("Hello \n World! \n") ;
printf ("Hell\no \t World! \n") ;
}
81
Reading values from keyboard
#include <stdio.h>
void main()
{
int num ;
scanf ("%d", &num) ;
printf (“No. of students is %d\n”, num) ;
}
82
Centigrade to Fahrenheit
#include <stdio.h>
void main()
{
float cent, fahr;
scanf(“%f”,¢);
fahr = cent*(9.0/5.0) + 32;
printf( “%f C equals %f F\n”, cent, fahr);
}
83
Largest of two numbers
#include <stdio.h>
void main()
{
int x, y;
scanf(“%d%d”,&x,&y);
if (x>y) printf(“Largest is %d\n”,x);
else printf(“Largest is %d\n”,y);
}
largest-1.c 84
What does this do?
#include <stdio.h>
void main()
{
int x, y;
scanf(“%d%d”,&x,&y);
if (x>y) printf(“Largest is %d\n”,x);
printf(“Largest is %d\n”,y);
}
largest-2.c 85
The C Character Set
The C language alphabet
Uppercase letters ‘A’ to ‘Z’
Lowercase letters ‘a’ to ‘z’
Digits ‘0’ to ‘9’
Certain special characters:
! # % ^ & * ( )
- _ + = ~ [ ] \
| ; : ‘ “ { } ,
. < > / ? blank
87
Variables
Very important concept for programming
An entity that has a value and is known to the
program by a name
Can store any temporary result while executing a
program
Can have only one value assigned to it at any given
time during the execution of the program
The value of a variable can be changed during the
execution of the program
88
Contd.
Variables stored in memory
Remember that memory is a list of storage
locations, each having a unique address
A variable is like a bin
The contents of the bin is the value of the variable
The variable name is used to refer to the value of
the variable
A variable is mapped to a location of the memory,
called its address
89
Example
#include <stdio.h>
void main( )
{
int x;
int y;
x=1;
y=3;
printf("x = %d, y= %d\n", x, y);
}
90
Variables in Memory
Instruction executed Memory location allocated
to a variable X
X = 10
T
i X = 20 10
m
e
X = X +1
X = X*5
91
Variables in Memory
Instruction executed Memory location allocated
to a variable X
X = 10
T
i X = 20 20
m
e
X = X +1
X = X*5
92
Variables in Memory
Instruction executed Memory location allocated
to a variable X
X = 10
T
i X = 20 21
m
e
X = X +1
X = X*5
93
Variables in Memory
Instruction executed
Memory location allocated
to a variable X
X = 10
T
i X = 20 105
m
e
X = X +1
X = X*5
94
Variables (contd.)
X = 20
X
Y=15 20
X = Y+3 ? Y
Y=X/6
95
Variables (contd.)
X = 20
X
Y=15 20
X = Y+3 15 Y
Y=X/6
96
Variables (contd.)
X = 20
X
Y=15 18
X = Y+3 15 Y
Y=X/6
97
Variables (contd.)
X = 20
X
Y=15 18
X = Y+3 3 Y
Y=X/6
98
Data Types
Each variable has a type, indicates what
type of values the variable can hold
Four common data types in C
int - can store integers (usually 4 bytes)
float - can store single-precision floating
point numbers (usually 4 bytes)
double - can store double-precision floating
point numbers (usually 8 bytes)
char - can store a character (1 byte)
99
Contd.
Must declare a variable (specify its type and
name) before using it anywhere in your program
All variable declarations should be at the
beginning of the main() or other functions
A value can also be assigned to a variable at the
time the variable is declared.
int speed = 30;
char flag = ‘y’;
100
More Data Types in C
Some of the basic data types can be augmented
by using certain data type qualifiers:
short size qualifier
long
signed
unsigned sign qualifier
Typical examples:
short int (usually 2 bytes)
long int (usually 4 bytes)
unsigned int (usually 4 bytes, but no way to store + or
-)
101
Some typical sizes (some of these can vary
depending on type of machine)
Integer data Bit
Minimum value Maximum value
type size
char 8 -27=-128 27-1=127
short int 16 -215=-32768 215-1=32767
int 32 -231=-2147483648 231-1=2147483647
long int 32 -231=-2147483648 231-1=2147483647
-263=- 263-
long long int 64
9223372036854775808 1=9223372036854775807
unsigned char 8 0 28-1=255
unsigned short int 16 0 216-1=65535
unsigned int 32 0 232-1=4294967295
unsigned long int 32 0 232-1=4294967295
unsigned long lon 264-
g int
64 0
1=18446744073709551615
102
Variable Names
Sequence of letters and digits
First character must be a letter or ‘_’
No special characters other than ‘_’
No blank in between
Names are case-sensitive (max and Max are two
different names)
Examples of valid names:
i rank1 MAX max Min class_rank
Examples of invalid names:
a’s fact rec 2sqroot class,rank
103
More Valid and Invalid Identifiers
int x, y, sum;
scanf(“%d%d”,&x,&y); Values assigned
sum = x + y;
printf( “%d plus %d is %d\n”, x, y, sum );
}
106
Example - 2
#include <stdio.h>
void main()
{ Assigns an initial value to d2,
can be changed later
float x, y;
int d1, d2 = 10;
scanf(“%f%f%d”,&x, &y, &d1);
printf( “%f plus %f is %f\n”, x, y, x+y);
printf( “%d minus %d is %d\n”, d1, d2, d1-d2);
}
107
Read-only variables
Variables whose values can be initialized during
declaration, but cannot be changed after that
Declared by putting the const keyword in front of
the declaration
Storage allocated just like any variable
Used for variables whose values need not be
changed
108
Correct
void main() {
const int LIMIT = 10;
int n;
scanf(“%d”, &n); Incorrect: Limit changed
if (n > LIMIT)
printf(“Out of limit”); void main() {
const int Limit = 10;
}
int n;
scanf(“%d”, &n);
Limit = Limit + n;
printf(“New limit is %d”, Limit);
}
109
Constants
Integer constants
Consists of a sequence of digits, with possibly a plus
or a minus sign before it
Embedded spaces, commas and non-digit characters
are not permitted between digits
Floating point constants
Two different notations:
Decimal notation: 25.0, 0.0034, .84, -2.234
Exponential (scientific) notation
3.45e23, 0.123e-12, 123e2
e means “10 to the power of”
110
Contd.
Character constants
Contains a single character enclosed within a pair of
single quote marks.
Examples :: ‘2’, ‘+’, ‘Z’
Some special backslash characters
‘\n’ new line
‘\t’ horizontal tab
‘\’’ single quote
‘\”’ double quote
‘\\’ backslash
‘\0’ null 111
Input: scanf function
Performs input from keyboard
It requires a format string and a list of variables into
which the value received from the keyboard will be
stored
format string = individual groups of characters
(usually ‘%’ sign, followed by a conversion
character), with one character group for each
variable in the list
Examples
scanf ("%d", &size) ;
scanf ("%c", &nextchar) ;
scanf ("%f", &length) ;
scanf (“%d%d”, &a, &b);
113
Reading a single character
A single character can be read using scanf with
%c
It can also be read using the getchar() function
char c;
c = getchar();
1
Expressions
Variables and constants linked with operators
Arithmetic expressions
Uses arithmetic operators
Can evaluate to any value
Logical expressions
Uses relational and logical operators
Evaluates to 1 or 0 (true or false) only
Assignment expression
Uses assignment operators
Evaluates to value depending on assignment
2
Arithmetic Operators
Binary operators
Addition: +
Subtraction: – Examples
Division: /
2*3 + 5 – 10/3
Multiplication: * –1 + 3*25/5 – 7
Modulus: % distance / time
Unary operators 3.14* radius * radius
a * x * x + b*x + c
Plus:+
dividend / divisor
Minus: – 37 % 10
3
Contd.
Suppose x and y are two integer variables,
whose values are 13 and 5 respectively
x+y 18
x–y 8
x*y 65
x/y 2
x%y 3
4
All operators except % can be used with
operands of all of the data types int, float,
double, char (yes! char also! We will see
what it means later)
% can be used only with integer operands
5
Operator Precedence
In decreasing order of priority
1. Parentheses :: ( )
2. Unary minus :: –5
3. Multiplication, Division, and Modulus
4. Addition and Subtraction
For operators of the same priority, evaluation is
from left to right as they appear
Parenthesis may be used to change the
precedence of operator evaluation
6
Examples:
Arithmetic expressions
a+b*c–d/e a + (b * c) – (d / e)
a*–b+d%e–f a * (– b) + (d % e) – f
a–b+c+d (((a – b) + c) + d)
x*y*z ((x * y) * z)
a+b+c*d*e (a + b) + ((c * d) * e)
7
Type of Value of an Arithmetic
Expression
If all operands of an operator are integer
(int variables or integer constants), the
value is always integer
Example: 9/5 will be 1, not 1.8
Example:
int a=9, b=5;
printf(“%d”, a/b)
will print 1 and not 1.8
8
If at least one operand is real, the value is real
Caution: Since floating-point values are rounded to
the number of significant digits permissible, the final
value is an approximation of the final result
Example: 1/ 3.0 * 3.0 may have the value 0.99999
and not 1.0
So checking if 1/ 3.0 * 3.0 is equal to 1.0 may
return false!!
9
The type of the final value of the
expression can be found by applying these
rules again and again as the expression is
evaluated following operator precedence
10
We have a problem!!
int a=10, b=4, c;
float x;
c = a / b;
x = a / b;
11
Solution: Typecasting
Changing the type of a variable during its use
General form
(type_name) variable_name
Example
x = ((float) a)/ b;
13
Example: Finding Average of 2
Integers int a, b;
float avg;
scanf(“%d%d”, &a, &b);
avg = ((float) (a + b))/2;
Wrong program
printf(“%f\n”, avg);
int a, b;
float avg; Correct programs
scanf(“%d%d”, &a, &b);
avg = (a + b)/2; int a, b;
printf(“%f\n”, avg); float avg;
scanf(“%d%d”, &a, &b);
average-1.c avg = (a + b)/2.0;
printf(“%f\n”, avg);
average-2.c 14
Assignment Expression
Uses the assignment operator (=)
General syntax:
variable_name = expression
Left of = is called l-value, must be a modifiable
variable
Right of = is called r-value, can be any expression
Examples:
velocity = 20
b = 15; temp = 12.5
A = A + 10
v=u+f*t
s = u * t + 0.5 * f * t * t 15
Contd.
An assignment expression evaluates to a
value same as any other expression
Value of an assignment expression is the
value assigned to the l-value
Example: value of
a = 3 is 3
b = 2*4 – 6 is 2
n = 2*u + 3*v – w is whatever the arithmetic
expression 2*u + 3*v – w evaluates to given
the current values stored in variables u, v, w
16
Contd.
Several variables can be assigned the same
value using multiple assignment operators
a = b = c = 5;
flag1 = flag2 = ‘y’;
speed = flow = 0.0;
Easy to understand if you remember that
theassignment expression has a value
Multiple assignment operators are right-to-left
associative
17
Example
Consider a= b = c = 5
Three assignment operators
Rightmost assignment expression is c=5, evaluates
to value 5
Now you have a = b = 5
Rightmost assignment expression is b=5, evaluates
to value 5
Now you have a = 5
Evaluates to value 5
So all three variables store 5, the final value the
assignment expression evaluates to is 5
18
Types of l-value and r-value
Usually should be the same
If not, the type of the r-value will be internally
converted to the type of the l-value, and then
assigned to it
Example:
double a;
a = 2*3;
Type of r-value is int and the value is 6
Type of l-value is double, so stores 6.0
19
This can cause strange problems
int a;
a = 2*3.2;
Type of r-value is float/double and the value is
6.4
Type of l-value is int, so internally converted to 6
So a stores 6, not the correct result
But an int cannot store fractional part anyway
So just badly written program
Be careful about the types on both sides
20
More Assignment Operators
+=, -=, *=, /=, %=
Operators for special type of assignments
a += b is the same as a = a + b
Same for -=, *=, /=, and %=
Exact same rules apply for multiple
assignment operators
21
Contd.
Suppose x and y are two integer variables,
whose values are 5 and 10 respectively.
x += y Stores 15 in x
Evaluates to 15
x –= y Stores -5 in x
Evaluates to -5
x *= y Stores 50 in x
Evaluates to 50
x /= y Stores 0 in x
Evaluates to 0
22
Logical Expressions
Uses relational and logical operators in
addition
Informally, specifies a condition which can
be true or false
Evaluates to value 0 or 1
0 implies the condition is false
1 implies the condition is true
23
Logical Expressions
(count <= 100)
((math+phys+chem)/3 >= 60)
((sex == ’M’) && (age >= 21))
((marks >== 80) && (marks < 90))
((balance > 5000) | | (no_of_trans > 25))
(! (grade == ’A’))
24
Relational Operators
Used to compare two quantities.
25
Examples
10 > 20 is false, so value is 0
25 < 35.5 is true, so value is 1
12 > (7 + 5) is false, so value is 0
32 != 21 is true, so value is 1
When arithmetic expressions are used on either
side of a relational operator, the arithmetic
expressions will be evaluated first and then the
results compared
a + b > c – d is the same as (a+b) > (c+d)
26
Logical Operators
Logical AND (&&)
Evalutes to 1 if both the operands are non-zero
Logical OR (||)
Result is true if at least one of the operands is
non-zero
X Y X && Y X || Y
0 0 0 0
0 non-0 0 non-0
non-0 0 0 non-0
non-0 non-0 non-0 non-0
27
Contd
Unary negation operator (!)
Single operand
Value is 0 if operand is non-zero
Value is 1 if operand is 0
28
Example
(4 > 3) && (100 != 200)
4 > 3 is true, so value 1
100 != 200 is true so value 1
Both operands 1 for &&, so final value 1
30
Example: Use of Logical Expressions
void main () {
int i, j;
scanf(“%d%d”,&i,&j);
printf (“%d AND %d = %d, %d OR %d=%d\n”,
i,j,i&&j, i,j, i||j) ;
}
3 AND 0 = 0, 3 OR 0 = 1
31
A Special Operator: AddressOf (&)
Remember that each variable is stored at a
location with an unique address
Putting & before a variable name gives the
address of the variable (where it is stored, not
the value)
Can be put before any variable (with no blank in
between)
int a =10;
printf(“Value of a is %d, and address of a is
%d\n”, a, &a);
32
More on Arithmetic Expressions
33
More Operators: Increment (++)
and Decrement (--)
Both of these are unary operators; they
operate on a single operand
The increment operator causes its operand
to be increased by 1
Example: a++, ++count
The decrement operator causes its operand
to be decreased by 1.
Example: i--, --distance
34
Pre-increment versus post-
increment
Operator written before the operand (++i, --i))
Called pre-increment operator (also sometimes
called prefix ++ and prefix --)
Operand will be altered in value before it is utilized
in the program
Operator written after the operand (i++, i--)
Called post-increment operator (also sometimes
called postfix ++ and postfix --)
Operand will be altered in value after it is utilized in
the program
35
Examples
Initial values :: a = 10; b = 20;
x = 50 + ++a; a = 11, x = 61
x = 50 + a++; x = 60, a = 11
x = a++ + --b; b = 19, x = 29, a = 11
x = a++ – ++a; ??
36
Operator Class Operators Associativity
Unary postfix++, -- Left to Right
prefix ++, --
Unary Right to Left
─ ! &
Precedence Binary * / % Left to Right
among different Binary + ─ Left to Right
operators (there
are many other Binary < <= > >= Left to Right
operators in C,
some of which we Binary == != Left to Right
will see later)
Binary && Left to Right
Binary || Left to Right
= += ─ =
Assignment Right to Left
*= /= &=
37
Statements in a C program
Parts of C program that tell the computer what to do
Different types
Declaration statements
Declares variables etc.
Assignment statement
Assignment expression, followed by a ;
Control statements
For branching and looping, like if-else, for, while, do-
while (to be seen later)
Input/Output
Read/print, like printf/scanf
38
Example
Declaration statement
int a, b, larger;
scanf(“%d %d”, &a, &b);
larger = b;
Control Assignment
if (a > b) statement statement
larger = a; Input/Output
statement
printf(“Larger number is %d\n”, larger);
39
Compound statements
A sequence of statements enclosed within {
and }
Each statement can be an assignment
statement, control statement, input/output
statement, or another compound statement
We will also call it block of statements
sometimes informally
40
Example
int n;
scanf(“%d”, &n);
while(1) {
if (n > 0) break;
Compound statement
scanf(“%d”, &n);
}
41
Conditional Statement
1
Conditional Statements
Allow different sets of instructions to be
executed depending on truth or falsity of a
logical condition
Also called Branching
How do we specify conditions?
Using expressions
non-zero value means condition is true
value 0 means condition is false
Usually logical expressions, but can be any
expression
The value of the expression will be used
2
Branching: if Statement
if (expression)
statement;
if (expression) {
Block of statements;
}
3
Branching: if Statement
if (expression)
statement;
if (expression) {
Block of statements;
}
false
5
A decision can be
made on any
print “Passed” expression.
true print “Good luck”
marks >= 40 zero - false
nonzero - true
false
6
A decision can be
made on any
print “Passed” expression.
true print “Good luck”
marks >= 40 zero - false
nonzero - true
false
7
Branching: if-else Statement
if (expression) { if (expression) {
Block of Block of statements;
statements; }
} else if (expression) {
else { Block of statements;
Block of }
statements; else {
} Block of statements;
}
8
Grade Computation
void main() {
int marks;
scanf(“%d”, &marks);
if (marks >= 80)
printf (”A”) ;
else if (marks >= 70)
printf (”B”) ;
else if (marks >= 60)
printf (”C”) ;
else printf (”Failed”) ;
}
9
void main () {
int marks;
scanf (“%d”, &marks) ;
if (marks>= 80) {
printf (“A: ”) ;
printf (“Good Job!”) ;
}
else if (marks >= 70)
printf (“B ”) ;
else if (marks >= 60)
printf (“C ”) ;
else {
printf (“Failed: ”) ;
printf (“Study hard for the supplementary”) ;
}
} 10
Find the larger of two numbers
START
READ X, Y
YES IS NO
X>Y?
OUTPUT X OUTPUT Y
STOP STOP
11
Find the larger of two numbers
void main () {
START
int x, y;
scanf (“%d%d”, &x,
READ X, Y &y) ;
if (x > y)
YES IS NO printf (“%d\n”, x);
X>Y?
else
printf (“%d\n”, y);
OUTPUT Y
OUTPUT X }
STOP STOP
12
Largest of three numbers
START
READ X, Y, Z
YES IS NO
X > Y?
Max = X Max = Y
YES IS NO
Max > Z?
OUTPUT Max OUTPUT Z
STOP STOP
13
START
READ X, Y, Z
YES IS NO
X > Y?
Max = X Max = Y
YES IS NO
Max > Z?
OUTPUT Max OUTPUT Z
STOP STOP
14
void main () {
START int x, y, z, max;
scanf (“%d%d%d”,&x,&y,&z);
READ X, Y, Z
if (x > y)
max = x;
YES IS NO else max = y;
X > Y?
if (max > z)
Max = X Max = Y printf (“%d”, max) ;
else printf (“%d”,z);
YES IS NO }
Max > Z?
OUTPUT Max OUTPUT Z
STOP STOP
15
Another version
void main() {
int a,b,c;
scanf (“%d%d%d”, &a, &b, &c);
if ((a >= b) && (a >= c))
printf (“\n The largest number is: %d”, a);
if ((b >= a) && (b >= c))
printf (“\n The largest number is: %d”, b);
if ((c >= a) && (c >= b))
printf (“\n The largest number is: %d”, c);
} 16
Confusing Equality (==) and
Assignment (=) Operators
Dangerous error
Does not ordinarily cause syntax errors
Any expression that produces a value can be
used in control structures
Nonzero values are true, zero values are
false
Example: WRONG! Will always print the line
if ( payCode = 4 )
printf( "You get a bonus!\n" );
17
Nesting of if-else Structures
It is possible to nest if-else statements, one
within another
All “if” statements may not be having the “else”
part
Confusion??
Rule to be remembered:
An “else” clause is associated with the closest
preceding unmatched “if”
18
Dangling else problem
if (exp1) if (exp2) stmta else stmtb
if (exp1) { if (exp1) {
if (exp2) if (exp2)
else
stmta OR
}
stmta ?
stmtb else
} stmtb
if e1 s1
else if e2 s2
else s3
?
if e1 if e2 s1
else s2
else s3
20
Answers
if e1 s1 if e1 s1
else if e2 s2 else { if e2 s2 }
if e1 s1 if e1 s1
else if e2 s2 else { if e2 s2
else s3 else s3 }
if e1 if e2 s1 if e1 { if e2 s1
else s2 else s2 }
else s3 else s3
21
The Conditional Operator ?:
This makes use of an expression that is either non-
0 or 0. An appropriate value is selected, depending
on the value of the expression
Example: instead of writing
if (balance > 5000)
interest = balance * 0.2;
else interest = balance * 0.1;
We can just write
interest = (balance > 5000) ? balance * 0.2 : balance * 0.1;
22
More Examples
if (((a >10) && (b < 5))
x = a + b;
else x = 0;
23
The switch Statement
24
Syntax
switch (expression) {
case const-expr-1: S-1
case const-expr-2: S-2
:
case const-expr-m: S-m
default: S
}
expression is any integer-valued expression
const-expr-1, const-expr-2,…are any constant integer-
valued expressions
Values must be distinct
S-1, S-2, …,S-m, S are statements/compound
statements
Default is optional, and can come anywhere (not
necessarily at the end as shown) 25
Behavior of switch
expression is first evaluated
It is then compared with const-expr-1, const-
expr-2,…for equality in order
If it matches any one, all statements from that
point till the end of the switch are executed
(including statements for default, if present)
Use break statements if you do not want this (see
example)
Statements corresponding to default, if present,
are executed if no other expression matches
26
Example
int x;
scanf(“%d”, &x);
switch (x) {
case 1: printf(“One\n”);
case 2: printf(“Two\n”);
default: printf(“Not one or two\n”);
};
One
Two
Not one or two
switch-1.c
Not what we want 27
Correct Program
int x;
scanf(“%d”, &x);
switch (x) {
case 1: printf(“One\n”);
break;
case 2: printf(“Two\n”);
break;
default: printf(“Not one or two\n”);
};
One
switch-2.c 28
Rounding a Digit
switch (digit) {
Since there isn’t a break statement
case 0: here, the control passes to the next
case 1: statement without checking
the next condition.
case 2:
case 3:
case 4: result = 0; printf (“Round down\n”); break;
case 5:
case 6:
case 7:
case 8:
case 9: result = 10; printf(“Round up\n”); break;
29
}
The break Statement
Used to exit from a switch or terminate from a
loop
With respect to “switch”, the “break” statement
causes a transfer of control out of the entire
“switch” statement, to the first statement
following the “switch” statement
Can be used with other statements also
…(will show later)
30
Looping
1
Loops
Group of statements that are executed
repeatedly while some condition
remains true
Each execution of the group of
statements is called an iteration of the
loop
2
Example
counter ← 1, sum ← 0
false
counter < 6
Read 5 integers true
and display the input n
their sum
sum ← sum + n
counter = counter + 1
output sum
3
Example
Given an exam marks as input, display the
appropriate message based on the rules
below:
If marks is greater than 49, display
“PASS”, otherwise display “FAIL”
However, for input outside the 0-100
range, display “WRONG INPUT” and
prompt the user to input again until a
valid input is entered
4
input m
false
m<0 || m>100
true
“WRONG INPUT”
input m
true
m>49 “PASS”
false
“FAIL”
5
input m
false
m<0 || m>100
true
“WRONG INPUT”
input m
true
m>49 “PASS”
false
“FAIL”
6
Looping: while statement
while (expression)
statement;
while (expression) {
Block of statements;
}
True
while (expression) {
statement
Block of statements; (loop body)
}
8
Looping: while statement
while (expression)
False
statement; expression
True
while (expression) {
statement
Block of statements; (loop body)
}
10
Example
int weight;
scanf(“%d”, &weight);
while ( weight > 65 ) {
printf ("Go, exercise, ");
printf ("then come back. \n");
printf ("Enter your weight: ");
scanf ("%d", &weight);
}
11
Sum of first N natural numbers
void main() {
int N, count, sum;
scanf (“%d”, &N) ;
sum = 0;
count = 1;
while (count <= N) {
sum = sum + count;
count = count + 1;
}
printf (“Sum = %d\n”, sum) ;
}
12
SUM = 12 + 22 + 32 + …+ N2
void main() {
int N, count, sum;
scanf (“%d”, &N) ;
sum = 0;
count = 1;
while (count <= N) {
sum = sum + count count;
count = count + 1;
}
printf (“Sum = %d\n”, sum) ;
return 0;
}
13
Compute GCD of two numbers
12 ) 45 ( 3
void main() {
int A, B, temp; 36
scanf (“%d %d”, &A, &B); 9 ) 12 ( 1
if (A > B) { 9
temp = A; A = B; B = temp; 3 ) 9 ( 3
} 9
while ((B % A) != 0) {
0
temp = B % A;
B = A;
A = temp; Initial: A=12, B=45
Iteration 1: temp=9, B=12,A=9
}
Iteration 2: temp=3, B=9, A=3
printf (“The GCD is %d”, A); B % A = 0 GCD is 3
}
gcd.c 14
Double your money
Suppose your Rs 10000 is earning interest at
1% per month. How many months until you
double your money ?
void main() {
double my_money = 10000.0;
int n=0;
while (my_money < 20000.0) {
my_money = my_money * 1.01;
n++;
}
printf (“My money will double in %d months.\n”,n);
}
15
Maximum of positive Numbers
void main() {
double max = 0.0, next;
printf (“Enter positive numbers, end with 0 or a
negative number\n”);
scanf(“%lf”, &next);
while (next > 0) {
if (next > max) max = next;
scanf(“%lf”, &next);
}
printf (“The maximum number is %lf\n”, max) ;
}
16
Find the sum of digits of a number
void main()
{
int n, sum=0;
scanf (“%d”, &n);
while (n != 0) {
sum = sum + (n % 10);
n = n / 10;
}
printf (“The sum of digits of the number is %d \n”, sum);
}
digit-sum.c 17
Looping: for Statement
Most commonly used looping structure in C
expr2 False
(test)
True
statement
(body)
expr3
(update)
19
Example: Computing Factorial
void main () {
int N, count, prod;
scanf (“%d”, &N) ;
prod = 1;
for (count = 1;count <= N; ++count)
prod = prod * count;
printf (“Factorial = %d\n”, prod) ;
}
20
Computing ex series up to N terms
void main () {
float x, term, sum;
int n, count;
scanf (“%f”, &x);
scanf (“%d”, &n);
term = 1.0; sum = 0;
for (count = 1; count <= n; ++count) {
sum += term;
term = x/count;
}
printf (“%f\n”, sum);
}
eseries-1.c 21
Computing ex series up to 4 decimal
places
void main () {
float x, term, sum;
int cnt;
scanf (“%f”, &x) ;
term = 1.0; sum = 0;
for (cnt = 1; term >= 0.0001; ++cnt) {
sum += term;
term *= x/cnt;
}
printf (“%f\n”, sum) ;
}
eseries-2.c 22
Equivalence of for and while
for ( expr1; expr2; expr3)
statement;
expr1;
Same as
while (expr2) {
statement
expr3;
}
23
void main () {
int N, count, sum;
Sum of first N Natural
scanf (“%d”, &N) ; Numbers
sum = 0;
count = 1;
while (count <= N) {
sum = sum + count;
count = count + 1; void main () {
} int N, count, sum;
printf (“%d\n”, sum) ; scanf (“%d”, &N) ;
} sum = 0;
for (count=1; count <= N; ++count)
sum = sum + count;
printf (“%d\n”, sum) ;
}
24
Some observations on for
Initialization, loop-continuation test, and update
can contain arithmetic expressions
for ( k = x; k <= 4 * x * y; k += y / x )
Update may be negative (decrement)
for (digit = 9; digit >= 0; --digit)
If loop continuation test is initially 0 (false)
Body of for structure not performed
No statement executed
False
do { expression
Block of statements;
} while (expression);
True
26
Example
Problem: Prompt user to input “month” value, keep
prompting until a correct value of month is given
as input
do {
printf (“Please input month {1-12}”);
scanf (“%d”, &month);
} while ((month < 1) || (month > 12));
27
Decimal to binary conversion
(prints binary in reverse order)
void main() {
int dec;
scanf (“%d”, &dec);
do
{
printf (“%2d”, (dec % 2));
dec = dec / 2;
} while (dec != 0);
printf (“\n”);
}
28
Echo characters typed on screen
until end of line
void main () {
char echo ;
do {
scanf (“%c”, &echo);
printf (“%c”,echo);
} while (echo != ‘\n’) ;
}
29
Specifying “Infinite Loop”
do {
statements
} while (1);
30
The break Statement
31
An Example
void main() {
int fact, i;
fact = 1; i = 1;
while ( i<10 ) {/* run loop –break when fact >100*/
fact = fact * i;
if ( fact > 100 ) {
printf ("Factorial of %d above 100", i);
break; /* break out of the while loop */
}
++i;
}
}
32
Test if a number is prime or not
void main() {
int n, i=2;
scanf (“%d”, &n);
while (i < n) {
if (n % i == 0) {
printf (“%d is not a prime \n”, n);
break;
}
++i;
}
if (i == n) printf (“%d is a prime \n”, n);
33
}
More efficient??
void main() {
int n, i = 2, flag = 0;
double limit;
scanf (“%d”, &n);
limit = sqrt(n);
while (i <= limit) {
if (n % i == 0) {
printf (“%d is not a prime \n”, n);
flag = 1; break;
}
i = i + 1;
}
if (flag == 0) printf (“%d is a prime \n”, n);
} 34
The continue Statement
Skips the remaining statements in the body of
a while, for or do/while structure
Proceeds with the next iteration of the loop
while and do/while loop
Loop-continuation test is evaluated
immediately after the continue statement is
executed
for loop
expr3 is evaluated, then expr2 is evaluated
35
An Example with break and
continue
void main() {
int fact = 1, i = 1;
while (1) {
fact = fact * i;
++i;
if ( i <=10 )
continue; /* not done yet ! Go to loop and
perform next iteration*/
break;
}
36
}
Some Loop Pitfalls
while (sum <= NUM) ; for (i=0; i<=NUM; ++i);
sum = sum+2; sum = sum+i;
double x;
for (x=0.0; x<2.0; x=x+0.2)
printf(“%.18f\n”, x);
37
Nested Loops: Printing a 2-D
Figure
How would you print the following
diagram?
*****
*****
*****
repeat 3 times
repeat 5 times
print a row of 5 *’s
print *
38
Nested Loops
const int ROWS = 3; row = 1;
const int COLS = 5; while (row <= ROWS) {
... /* print a row of 5 *’s */ outer
loop
row = 1; col = 1;
while (row <= ROWS) { while (col <= COLS) {
/* print a row of 5 *’s printf (“* “);
inner
*/ col++; loop
... }
++row; printf(“\n”);
} ++row;
}
39
2-D Figure: with for loop
Print const int ROWS = 3;
***** const int COLS = 5;
....
***** for (row=1; row<=ROWS; ++row) {
***** for (col=1; col<=COLS; ++col) {
printf(“* ”);
}
printf(“\n”);
}
40
Another 2-D Figure
Print const int ROWS = 5;
* ....
** int row, col;
for (row=1; row<=ROWS; ++row) {
*** for (col=1; col<=row; ++col) {
**** printf(“* ”);
***** }
printf(“\n”);
}
2d-figure.c 41
Yet Another One
43
Example
void main()
{
int low, high, desired, i, flag = 0;
scanf(“%d %d %d”, &low, &high, &desired);
i = low;
while (i < high) {
for (j = i+1; j <= high; ++j) {
if (j % i == desired) {
flag = 1;
break;
} Breaks here
}
if (flag == 1) break;
i = i + 1;
} Breaks here
} 44
The comma operator
Separates expressions
Syntax
expr-1, expr-2, …,expr-n
expr-1, expr-2,…are all expressions
Is itself an expression, which evaluates to the value of
the last expression in the sequence
Since all but last expression values are discarded, not
of much general use
But useful in for loops, by using side effects of the
expressions
45
Example
We can give several expressions separated by
commas in place of expr1 and expr3 in a for
loop to do multiple assignments for example