2
Course Materials
Books:
1. Programmingwith C (Second Edition)
Byron Gottfried, Third Edition, Schaum’s Outlines
Series,
2. The C Programming Language
Brian W Kernighan, Dennis M Ritchie
3. Data structures
S. Lipschutz, Schaum’s Outline Series
3.
3
About the Course
Section 8, 9, 10
Teacher: Prof. S Dey (SD)
Section 11, 12
Teacher: Prof. A Das (AD)
Section 13, 14
Mon (9:30-10:25), Wed (8:30-9:25), Thu (9:30-10:25)
In Classroom F-142 (in Main Building)
Teacher: Prof. B. Mitra (BM)
4.
Teachers’ officehours (meeting time outside class):
BM: Friday (5:30-6:30), Room 315, CSE Dept.
Homepage: http://cse.iitkgp.ac.in/~bivasm/
Tutorial classes (one hour per week) will be conducted
on a “per section” basis before Lab hours
Evaluation in the theory course:
Mid-semester 30%
End-semester 50%
Two class tests and attendance 20%
5.
5
Attendance
REALLY
matters
Important forunderstanding the course
Any student with low attendance may be
deregistered from the course
Leave due to medical reasons must be certified
by the B.C. Roy Technology Hospital
6.
6
Important Dates
ClassTest 1: Sept. 2, 2014 (18:30 – 19:30)
Class Test 2: Nov. 4, 2014 (18:30 – 19:30)
(Class test dates are tentative and may change. The
exact dates will be announced in the class)
Mid-semester: Sept 15 – Sep 23, 2014
End-semester: Nov 20 – 28, 2014
8
Computer is amachine that can perform computation
1.Input : User gives a set of Input
2.Processing : Input data is processed by a well defined
and finite sequence of steps
3.Output: Some data available from processing step and
output to the user
9.
9
A Computer (Level0 Version)
Central
Processing
Unit (CPU)
Storage
Peripherals
Output
Peripherals
Input
Peripherals
Main
Memory
10.
10
I/O and Peripherals:Examples
Input Devices
Keyboard, Mouse, Digital Camera
Output Devices
Monitor, Printer, Speaker
Storage Peripherals
Magnetic Disks: hard disk
Optical Disks: CDROM, CD-RW, DVD
Flash Memory: pen drives
15
C=A+B
Step 1: FetchOperand A from memory
Step 2: Store in Register R1
Step 3: Fetch Operand B from memory
Step 4: Store in Register R2
Step 5: Add content of R1 and R2
Step 6: Store the result in register R3
Step 7: Store the content of R3 in memory C
CPU
MAR
MDR
Memory
Control
Unit
Address Bus
Data Bus
Read
ALU
A
(2)
B
(5)
16.
16
C=A+B
Step 1: FetchOperand A from memory
Step 2: Store in Register R1
Step 3: Fetch Operand B from memory
Step 4: Store in Register R2
Step 5: Add content of R1 and R2
Step 6: Store the result in register R3
Step 7: Store the content of R3 in memory C
CPU
MAR
MDR
Memory
Control
Unit
Address Bus
Data Bus
Read
ALU
A
(2)
B
(5)
A
2
17.
17
C=A+B
Step 1: FetchOperand A from memory
Step 2: Store in Register R1
Step 3: Fetch Operand B from memory
Step 4: Store in Register R2
Step 5: Add content of R1 and R2
Step 6: Store the result in register R3
Step 7: Store the content of R3 in memory C
CPU
MAR
MDR
Memory
Control
Unit
Address Bus
Data Bus
Read
ALU
A
(2)
B
(5)
B
5
18.
18
C=A+B
Step 1: FetchOperand A from memory
Step 2: Store in Register R1
Step 3: Fetch Operand B from memory
Step 4: Store in Register R2
Step 5: Add content of R1 and R2
Step 6: Store the result in register R3
Step 7: Store the content of R3 in memory C
CPU
MAR
MDR
Memory
Control
Unit
Address Bus
Data Bus
Read
ALU
A
(2)
B
(5)
ALU
R1 R2
R3
19.
19
C=A+B
Step 1: FetchOperand A from memory
Step 2: Store in Register R1
Step 3: Fetch Operand B from memory
Step 4: Store in Register R2
Step 5: Add content of R1 and R2
Step 6: Store the result in register R3
Step 7: Store the content of R3 in memory C
CPU
MAR
MDR Memory
Control
Unit
Address Bus
Data Bus
Read
ALU
A
(2)
B
(5)
C
7 C
(7)
20.
20
What can acomputer do
Solve Types of Problem
1.Functional Problem (Matrix Inverse)
2.Decision Problem (Primality test)
3.Search Problem
4.Optimization problem
21.
21
What can acomputer do
Determining if a given integer is a prime number
Root finding
Read in airline route information as a matrix and determine the
shortest time journey between two airports
Telephone pole placement problem
Matrix multiplication
Finger-print recognition
Chess Player
Speech Recognition
Language Recognition
Discovering New Laws in Mathematics
Automatic drug discovery
…..
22.
22
Programming and Software
Computerneeds to be programmed to do such
tasks
Programming is the process of writing
instructions in a language that can be
understood by the computer so that a desired
task can be performed by it
Program: sequence of instructions to do a task,
computer processes the instructions
sequentially one after the other
Software: programs for doing tasks on computers
23.
23
Challenges
CPU understandsmachine language
Different strings of 0’s and 1’s only!!
Hard to remember and use
Instruction set of a CPU
Mnemonic names for this strings
CPU
MAR
MDR
Control
Unit
ALU
24.
24
Instruction Set
Start
Read M
Write M
Load Data, M
Copy M1, M2
Add M1, M2, M3
Sub M1, M2, M3
Compare M1, M2, M3
Jump L
J_Zero M, L
Halt
25.
25
Instruction Set
Start
Read M
Write M
Load Data, M
Copy M1, M2
Add M1, M2, M3
Sub M1, M2, M3
Compare M1, M2, M3
Jump L
J_Zero M, L
Halt
0: Start
1: Read 10
2: Read 11
3: Add 10, 11, 12
4: Write 12
5: Halt
Program
26.
26
Problems with programmingusing
instruction sets directly
Instruction sets of different types of CPUs
different
Need to write different programs for computers with
different types of CPUs even to do the same thing
Solution: High level languages (C, C++, Java,…)
CPU neutral, one program for many
Compiler to convert from high-level program to low
level program that CPU understands
28
High-Level Program
0: Start
1:Read 20
2: Read 21
3: Compare 20, 21, 22
4: J_Zero 22, 7
5: Write 20
6: Jump 8
7: Write 21
8: Halt
Variables x, y;
Begin
Read (x);
Read (y);
If (x >y) then Write (x)
else Write (y);
End.
Low-Level Program
29.
29
Three steps inwriting programs
Step 1: Write the program in a high-level
language (in your case, C)
Step 2: Compile the program using a C
compiler
Step 3: Run the program (as the computer
to execute it)
30.
30
A Computer (Level0 Version)
Central
Processing
Unit (CPU)
Storage
Peripherals
Output
Peripherals
Input
Peripherals
Main
Memory
31.
31
CPU registerand main memory are volatile
Data gets erased after power switched off
Secondary storage is non-volatile
Disk
Keep the program on the disk
During execution
Load the program from the disk to memory Disk
Memory
CPU
Program
How does program run in a
computer?
The fetch-decode-execute
cycle
Sequenceof machine instructions is copied to the instruction area of the memory.
A particular control register, called the program counter (PC), is loaded with the
address of the first instruction of the program.
The CPU fetches the instruction from that location in the memory that is currently
stored in the PC register.
The instruction (in IR) is decoded in the control unit of the CPU.
The instruction may require one or more operands.
An operand may be either a data or a memory address. A data may be either a constant (also
called an immediate operand) or a value stored in the data area of the memory or a value
stored in a register. Similarly, an address may be either immediate or a resident of the main
memory or available in a register.
Finally, data is fetched from the data part of the main memory.
36
PC MAR IR
MDR
Read
Instruction fetch
37.
If theinstruction is a data movement operation, the corresponding movement is
performed. For example, a "load" instruction copies the data fetched from memory
to a register, whereas a "store" instruction sends a value from a register to the
data area of the memory.
If the instruction is an arithmetic or logical instruction, it is executed in the ALU
after all the operands are available in the CPU (in its registers). The output from
the ALU is stored back in a register.
If the instruction is a jump instruction, the instruction must contain a memory
address to jump to. The program counter (PC) is loaded with this address. A jump
may be conditional, i.e., the PC is loaded with the new address if and only if some
condition(s) is/are true.
If the instruction is not a jump instruction, the address stored in the PC is
incremented by one.
If the end of the program is not reached, the CPU continues its fetch-decode-
execute cycle.
37
The fetch-decode-execute
cycle
38.
38
Binary Representation
Numbersare represented inside computers in
the base-2 system (Binary Numbers)
Only two symbols/digits 0 and 1
Positional weights of digits: 20
, 21
, 22
,…from right to
left for integers
Decimal number system we use is base-10
10 digits, from 0 to 9, Positional weights 100
, 101
,
102
,…from right to left for integers
Example: 723 = 3x100
+ 2x101
+ 7x102
Decimal to binaryconversion
(15)10=>(1111)2
Step 1: Divide the number by the “Base” until the quotient becomes 0
Step 2: Collect the remainder after each step
Finally: Trace the remainders in the reverse direction
41
42.
42
Bits and Bytes
Bit – a single 1 or 0
Byte – 8 consecutive bits
2 bytes = 16 bits
4 bytes = 32 bits
Max. integer that can represented
in 1 byte = 255 (=11111111)
In 4 bytes = 4294967295 (= 32 1’s)
No. of integers that can be represented in 1 byte
= 256 (the integers 0, 1, 2, 3,….255)
43.
Bits and Bytes
Addressable unit
Length of the word
Size of memory
Size of register
CPU
MAR
MDR
Control
Unit
Address Bus
Data Bus
Read
ALU
10
54
90
07
18
0
1
2
3
8 bits
16 bits
word
Size of the memory (16 × 8)
1.16 addressable units
2.Each unit can store 8 bits (word)
45
Structure of aC program
A collection of functions (we will see what they
are later)
Exactly one special function named main must
be present. Program always starts from there
Each function has statements (instructions) for
declaration, assignment, condition check,
looping etc.
Statements are executed one by one
46.
46
The C CharacterSet
The C language alphabet
Uppercase letters ‘A’ to ‘Z’
Lowercase letters ‘a’ to ‘z’
Digits ‘0’ to ‘9’
Certain special characters:
A C program should not contain anything else
! # % ^ & * ( )
- _ + = ~ [ ]
| ; : ‘ “ { } ,
. < > / ? blank
Keywords (reserved
words)
Identifies (user
defined words)
47.
47
First C program– print on screen
#include <stdio.h>
void main()
{
printf ("Hello, World! n") ;
}
functions
Library
(standard)
User defined
48.
48
Variables
Very importantconcept 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
49.
49
Contd.
Variables storedin 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
59
Data Types
Eachvariable 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)
60.
60
Contd.
Must declarea 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’;
61.
61
Variable Names
Sequenceof 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
62.
More Valid andInvalid Identifiers
Valid identifiers
X
abc
simple_interest
a123
LIST
stud_name
Empl_1
Empl_2
avg_empl_salary
Invalid identifiers
10abc
my-name
“hello”
simple interest
(area)
%rate
63.
C Keywords
Usedby the C language, cannot be used
as variable names
Examples:
int, float, char, double, main, if else, for, while.
do, struct, union, typedef, enum, void, return,
signed, unsigned, case, break, sizeof,….
There are others, see textbook…
64.
64
Output: printf function
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 %dn", 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
65.
65
Contd.
General syntax:
printf(format string, arg1, arg2, …, argn);
format string refers to a string containing formatting
information and data types of the arguments to be
output
the arguments arg1, arg2, … represent list of
variables/expressions whose values are to be printed
The conversion characters are the same as in
scanf
66.
66
Input: scanf function
Takes 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
int a, b;
float c;
scanf(“%d %d %f”, &a, &b, &c);
Format string
Variable list (note the &
before a variable name)
67.
67
Commonly usedconversion characters
c for char type variable
d for int type variable
f for float type variable
lf for double type variable
Examples
scanf ("%d", &size) ;
scanf ("%c", &nextchar) ;
scanf ("%f", &length) ;
scanf (“%d%d”, &a, &b);
69
Write a Cprogram that reads a temperature in
Celsius, for example t C, and outputs the
equivalent temperature in Fahrenheit, f F.
70.
70
Centigrade to Fahrenheit
#include<stdio.h>
int main()
{
float cent, fahr;
scanf(“%f”,¢);
fahr = cent*(9.0/5.0) + 32;
printf( “%f C equals %f Fn”, cent, fahr);
}
71.
71
Example 1
#include <stdio.h>
voidmain()
{
int x, y, sum;
scanf(“%d%d”,&x,&y);
sum = x + y;
printf( “%d plus %d is %dn”, x, y, sum );
}
Three int type variables declared
Values assigned
72.
72
Example - 2
#include<stdio.h>
void main()
{
float x, y;
int d1, d2 = 10;
scanf(“%f%f%d”,&x, &y, &d1);
printf( “%f plus %f is %fn”, x, y, x+y);
printf( “%d minus %d is %dn”, d1, d2, d1-d2);
}
Assigns an initial value to d2,
can be changed later
73.
73
Read-only variables
Variableswhose 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
Prevents accidental change of the value
74.
74
void main() {
constint LIMIT = 10;
int n;
scanf(“%d”, &n);
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);
}
Correct
Incorrect: Limit changed
75.
75
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
76.
76
Reading a singlecharacter
A single character can be read using scanf with
%c
It can also be read using the getchar() function
char c;
c = getchar();
Program waits at the getchar() line until a
character is typed, and then reads it and stores it
in c
77.
Program and Algorithm
Swap two elements
Search an element from the list
…
77
Problem or
Task
Design the
Algorithm (Logic)
Write the
program (say
in C)