Programming and Data Structure: Sujoy Ghose Sudeshna Sarkar AND Jayanta Mukhopadhyay
Programming and Data Structure: Sujoy Ghose Sudeshna Sarkar AND Jayanta Mukhopadhyay
Programming and Data Structure: Sujoy Ghose Sudeshna Sarkar AND Jayanta Mukhopadhyay
Sujoy Ghose
Sudeshna Sarkar
AND
Jayanta Mukhopadhyay
Dept. of Computer Science & Engineering.
Indian Institute of Technology
Kharagpur
30%
50%
20%
3
Course Materials
The slides for the lectures will be made
available on the web (in PDF form).
http://144.16.192.60/~pds
Text/Reference Books
Introduction
What is a Computer?
It is a machine which can accept data, process them,
and output results.
Input
Device
Central
Processing
Unit
(CPU)
Output
Device
Main Memory
Storage Peripherals
Spring Semester 2012
CPU
All computations take place here in order for the
computer to perform a designated task.
It has a large number of registers which temporarily
store data and programs (instructions).
It has circuitry to carry out arithmetic and logic
operations, take decisions, etc.
It retrieves instructions from the memory, interprets
(decodes) them, and perform the requested
operation.
Spring Semester 2012
Main Memory
Uses semiconductor technology
Allows direct access
10
Input Device
Keyboard, Mouse, Scanner, Digital Camera
Output Device
Monitor, Printer
Storage Peripherals
Magnetic Disks: hard disk, floppy disk
Allows direct (semi-random) access
11
Typical Configuration of a PC
CPU:
Main Memory:
Hard Disk:
Floppy Disk:
CDROM:
Input Device:
Output Device:
Ports:
12
What is a program?
Set of instructions for carrying out a specific task.
13
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
Spring Semester 2012
14
Contd.
A digital computer is built out of tiny
electronic switches.
From the viewpoint of ease of manufacturing and
reliability, such switches can be in one of two
states, ON and OFF.
A switch can represent a digit in the so-called
binary number system, 0 and 1.
15
Nibble
A collection of four bits (say, 0110).
Byte
A collection of eight bits (say, 01000111).
Word
Depends on the computer.
Typically 4 or 8 bytes (that is, 32 or 64 bits).
Spring Semester 2012
16
Contd.
A k-bit decimal number
Can express unsigned integers in the range
0 to 10k 1
For k=3, from 0 to 999.
17
Classification of Software
Two categories:
1. Application Software
Used to solve a particular problem.
Editor, financial accounting, weather forecasting, etc.
2. System Software
Helps in running other programs.
Compiler, operating system, etc.
18
Computer Languages
Machine Language
Expressed in binary.
Directly understood by the computer.
Not portable; varies from one machine type to
another.
Program written for one type of machine will not run
on another type of machine.
19
Contd.
Assembly Language
Mnemonic form of machine language.
Easier to use as compared to machine language.
For example, use ADD instead of 10110100.
Assembler
Machine
language
program
20
Contd.
Assembly language is also difficult to use in
writing programs.
Requires many instructions to solve a problem.
A,X
A,Y
A,Z
A,3
RES,A
;
;
;
;
;
A=X
A=A+Y
A=A+Z
A=A/3
RES = A
Programming and Data Structure
In C,
RES = (X + Y + Z) / 3
21
High-Level Language
Machine language and assembly language are
called low-level languages.
They are closer to the machine.
Difficult to use.
22
Contd.
HLL
program
Executable
code
Compiler
Object code
Linker
Library
23
To Summarize
Assembler
Translates a program written in assembly language
to machine language.
Compiler
Translates a program written in high-level
language to machine language.
24
Operating Systems
Makes the computer easy to use.
Basically the computer is very difficult to use.
Understands only machine language.
25
Contd.
Popular operating systems:
DOS:
Windows 2000/XP:
Unix:
Linux:
single-user
single-user multitasking
multi-user
a free version of Unix
26
Contd.
Computers connected in a network.
Many users may work on a computer.
Over the network.
At the same time.
CPU and other resources are shared among the
different programs.
Called time sharing.
One program executes at a time.
27
Multiuser Environment
Computer Network
User 1
User 2
User 3
User 4
User 4
Printer
28
29
Some Terminologies
Algorithm / Flowchart
A step-by-step procedure for solving a particular
problem.
Should be independent of the programming
language.
Program
A translation of the algorithm/flowchart into a
form that can be processed by a computer.
Typically written in a high-level language like C,
C++, Java, etc.
Spring Semester 2012
30
31
Contd.
How does memory look like (logically)?
As a list of storage locations, each having a unique
address.
Variables and constants are stored in these
storage locations.
Variable is like a house, and the name of a variable
is like the address of the house.
Different people may reside in the house, which is like
the contents of a variable.
Spring Semester 2012
32
Memory map
Address
Address
Address
Address
Address
Address
Address
0
1
2
3
4
5
6
Every variable is
mapped to a
particular memory
address
Address N-1
33
Variables in Memory
Instruction executed
T
i
m
e
Memory location
allocated to a variable X
X = 10
10
X = 20
20
X=X+1
21
X=X*5
105
34
Instruction executed
T
i
m
e
X = 20
20
Y = 15
20
15
X=Y+3
18
15
Y=X/6
18
35
Data types
Three common data types used:
Integer :: can store only whole numbers
Examples: 25, -56, 1, 0
36
Float ::
32 bits
64 bits
Char ::
8 bits (ASCII code)
16 bits (UNICODE, used in Java)
Spring Semester 2012
37
Problem solving
Step 1:
Clearly specify the problem to be solved.
Step 2:
Draw flowchart or write algorithm.
Step 3:
Convert flowchart (algorithm) into program code.
Step 4:
Compile the program into object code.
Step 5:
Execute the program.
Spring Semester 2012
38
Input / Output
Decision Box
Start / Stop
Spring Semester 2012
39
Contd.
Flow of
control
Connector
40
READ A, B, C
S=A+B+C
OUTPUT S
STOP
Spring Semester 2012
41
READ X, Y
YES
NO
IS
X>Y?
OUTPUT X
OUTPUT Y
STOP
STOP
Programming and Data Structure
42
READ X, Y, Z
YES
IS
X > Y?
LAR = X
YES
NO
LAR = Y
IS
LAR > Z?
OUTPUT LAR
OUTPUT Z
STOP
Spring Semester 2012
NO
STOP
Programming and Data Structure
43
SUM = 0
COUNT = 1
SUM = SUM + COUNT
COUNT = COUNT + 1
NO
IS
COUNT > N?
YES
OUTPUT SUM
STOP
44
Example 5: SUM = 12 + 22 + 32 + N2
START
READ N
SUM = 0
COUNT = 1
SUM = SUM + COUNT*COUNT
COUNT = COUNT + 1
NO
IS
COUNT > N?
YES
OUTPUT SUM
STOP
45
SUM = 0
COUNT = 1
SUM = SUM + COUNT * (COUNT+1)
COUNT = COUNT + 1
NO
IS
COUNT > N?
YES
OUTPUT SUM
STOP
46
PROD = 1
COUNT = 1
PROD = PROD * COUNT
COUNT = COUNT + 1
NO
IS
COUNT > N?
YES
OUTPUT PROD
STOP
47
NO
IS
COUNT > N?
YES
OUTPUT SUM
STOP
48
NO
IS
TERM < 0.0001?
YES
OUTPUT SUM
STOP
49
TRY YOURSELF
50
Ex
A
B
C
D
P
F
51
READ MARKS
MARKS 90?
YES
OUTPUT Ex
STOP
NO
MARKS 80?
YES
OUTPUT A
NO
MARKS 70?
NO
YES
OUTPUT B
STOP
STOP
52
NO
MARKS 60?
YES
MARKS 50?
NO
YES
MARKS 35?
NO
YES
OUTPUT C
OUTPUT D
OUTPUT P
OUTPUT F
STOP
STOP
STOP
STOP
53
Programming in C
54
Introduction to C
C is a general-purpose, structured programming language.
Resembles other high-level structured programming languages, such
as Pascal and Fortran-77.
Also contains additional features which allow it to be used at a lower
level.
55
History of C
Originally developed in the 1970s by Dennis Ritchie at AT&T
Bell Laboratories.
Outgrowth of two earlier languages BCPL and B.
56
Structure of a C program
Every C program consists of one or more
functions.
57
Contd.
Each compound statement is enclosed within
a pair of braces: { and }
The braces may contain combinations of
elementary statements and other compound
statements.
58
Sample C program #1
#include <stdio.h>
main()
{
Statement for
printing the sentence
within double quotes
(..). \n denotes end
of line.
59
Sample C program #2
#include <stdio.h>
main()
Integers variables declared
{
before their usage.
int
a, b, c;
a = 10;
b = 20;
c = a + b;
printf (\n The sum of %d and %d is %d\n,
a,b,c);
}
Control character for printing
value of a in decimal digits.
The sum of 10 and 20 is 30
Spring Semester 2012
60
Sample C program #3
#include <stdio.h>
/* FIND THE LARGEST OF THREE NUMBERS */
main()
{
Comments within /* .. */
int
a, b, c;
scanf (%d %d %d, &a, &b, &c);
if ((a>b) && (a>c))
/* Composite condition check */
Conditional
printf (\n Largest is %d, a);
statement else
if (b>c)
/* Simple condition check */
printf (\n Largest is %d, b);
else
printf (\n Largest is %d, c);
}
61
Sample C program #4
Preprocessor statement.
Replace PI by 3.1415926
before compilation.
Example of a function
Called as per need from
Main programme.
#include <stdio.h>
#define PI 3.1415926
Function called.
}
Spring Semester 2012
62
a = 10;
b = 20;
c = a + b;
printf (\n The sum of %d and %d is %d\n,
a,b,c);
}
63
Program documentation
Insert comments in the program to make it easy to understand.
Never use too many comments.
64
Contd.
Program indentation
Use proper indentation.
Structure of the program should be immediately
visible.
65
66
67
68
69
<
>
blank
70
Case sensitive
area, AREA and Area are all different.
Spring Semester 2012
71
Contd.
Keywords
Reserved words that have standard, predefined
meanings in C.
Cannot be used as identifiers.
OK within comments.
auto Standard
break case
char const
continue default do
C keywords:
double else
enum
int
long
struct
extern float
for
goto
if
signed
sizeof
static
volatile
while
unsigned void
72
Invalid identifiers
10abc
my-name
hello
simple interest
(area)
%rate
73
Data Types in C
int :: integer quantity
Typically occupies 4 bytes (32 bits) in memory.
74
Contd.
Some of the basic data types can be augmented
by using certain data type qualifiers:
short
long
signed
unsigned
Typical examples:
short int
long int
unsigned int
Spring Semester 2012
75
char
a, A, *, /,
float
23.54, 0.00345, 25.0
2.5E12, 1.234e-5
E or e means 10 to
the power of
76
Constants
Constants
Numeric
Constants
integer
Character
Constants
floatingpoint
single
character
string
77
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.
78
Floating-point Constants
Can contain fractional parts.
Very large or very small numbers can be
represented.
23000000 can be represented as 2.3e7
the power of
79
new line
horizontal tab
single quote
double quote
backslash
null
Programming and Data Structure
80
String Constants
Sequence of characters enclosed in double
quotes.
The characters may be letters, numbers, special
characters and blank spaces.
Examples:
nice, Good Morning, 3+6, 3, C
81
Variables
It is a data name that can be used to store a
data value.
Unlike constants, a variable may take different
values in memory during execution.
Variable names follow the naming convention
for identifiers.
Examples :: temp, speed, name2, current
82
Example
int a, b, c;
char x;
Variables
a = 3;
b = 50;
c = a b;
x = d;
Constants
b = 20;
a = a + 1;
x = G;
Spring Semester 2012
83
Declaration of Variables
General syntax:
data-type variable-list;
Examples:
int velocity, distance;
int a, b, c, d;
float temp;
char flag, option;
84
85
int speed;
speed=100;
1349
1350
100
1351
speed
100
1352
&speed
1350
86
Contd.
In C terminology, in an expression
speed refers to the contents of the memory
location.
&speed refers to the address of the memory
location.
Examples:
printf (%f %f %f, speed, time, distance);
scanf (%f %f, &speed, &time);
Spring Semester 2012
87
An Example
#include <stdio.h>
main()
{
float speed, time, distance;
Address of speed
Content of speed
88
Assignment Statement
Used to assign values to variables, using the
assignment operator (=).
General syntax:
variable_name = expression;
Examples:
velocity = 20;
b = 15; temp = 12.5;
A = A + 10;
v = u + f * t;
s = u * t + 0.5 * f * t * t;
Spring Semester 2012
89
Contd.
A value can be assigned to a variable at the
time the variable is declared.
int speed = 30;
char flag = y;
90
Operators in Expressions
Operators
Arithmetic
Operators
Relational
Operators
Logical
Operators
91
Arithmetic Operators
Addition ::
Subtraction ::
Division ::
Multiplication ::
Modulus ::
/
*
%
92
Examples
distance = rate * time ;
netIncome = income - tax ;
speed = distance / time ;
area = PI * radius * radius;
y = a * x * x + b*x + c;
quotient = dividend / divisor;
remain =dividend % divisor;
93
Contd.
Suppose x and y are two integer variables,
whose values are 13 and 5 respectively.
x+y
18
xy
x*y
65
x/y
x%y
94
Operator Precedence
In decreasing order of priority
1.
2.
3.
4.
Parentheses :: ( )
Unary minus :: 5
Multiplication, Division, and Modulus
Addition and Subtraction
95
a + (b * c) (d / e)
a * ( b) + (d % e) f
(((a b) + c) + d)
((x * y) * z)
(a + b) + ((c * d) * e)
96
Integer Arithmetic
When the operands in an arithmetic
expression are integers, the expression is
called integer expression, and the operation is
called integer arithmetic.
Integer arithmetic always yields integer
values.
97
Real Arithmetic
Arithmetic operations involving only real or
floating-point operands.
Since floating-point values are rounded to the
number of significant digits permissible, the final
value is an approximation of the final result.
1.0 / 3.0 * 3.0 will have the value 0.99999 and not 1.0
98
Mixed-mode Arithmetic
When one of the operands is integer and the
other is real, the expression is called a mixedmode arithmetic expression.
If either operand is of the real type, then only
real arithmetic is performed, and the result is
a real number.
25 / 10 2
25 / 10.0 2.5
99
100
Type Casting
int x;
float r=3.0;
x= (int)(2*r);
double perimeter;
float pi=3.14;
int r=3;
Type casting
to double
101
Relational Operators
Used to compare two quantities.
<
is less than
>
is greater than
<=
>=
==
is equal to
!=
is not equal to
Programming and Data Structure
102
Examples
10 > 20
25 < 35.5
12 > (7 + 5)
is false
is true
is false
103
Examples
Sample code segment in C
if (x > y)
printf (%d is larger\n, x);
else
printf (%d is larger\n, y);
104
Logical Operators
There are two logical operators in C (also called
logical connectives).
&& Logical AND
| | Logical OR
105
Logical AND
Result is true if both the operands are true.
Logical OR
ResultXis true if at least
one Xof &&
the Yoperands
Y
X | |are
Y true.
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
TRUE
TRUE
FALSE
FALSE
TRUE
TRUE
TRUE
TRUE
TRUE
106
Input / Output
printf
Performs output to the standard output device
(typically defined to be the screen).
It requires a format string in which we can specify:
The text to be printed out.
Specifications on how to print the values.
printf ("The number is %d.\n", num) ;
The format specification %d causes the value listed
after the format string to be embedded in the output as
a decimal number in place of %d.
Output will appear as: The number is 125.
Spring Semester 2012
107
scanf
Performs input from the standard input device, which
is the keyboard by default.
It requires a format string and a list of variables into
which the value received from the input device will be
stored.
It is required to put an ampersand (&) before the
names of the variables.
scanf ("%d", &size) ;
scanf ("%c", &nextchar) ;
scanf ("%f", &length) ;
scanf (%d %d, &a, &b);
Spring Semester 2012
108