Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

CS10003:

Programming & Data Structures

Spring 2021

Dept. of Computer Science & Engineering

1
Course Materials
 Slides available at http://cse.iitkgp.ac.in/pds/current
 More materials available at http://cse.iitkgp.ac.in/pds

Books:
1. Programming with C
Byron Gottfried
2. The C Programming Language
Brian W Kernighan, Dennis M Ritchie
3. Programming in ANSI C
E. Balaguruswamy
4. Data Structures
S. Lipschutz, Schaum’s Outline Series
2
Teachers and Class Timings
 Section 1, 2
 Monday (3-4:55 pm), Tuesday (3-3:55 pm)
 Teacher: Prof. Abhijit Das (AD)
 Section 3, 4
 Monday (3-4:55 pm), Tuesday (3-3:55 pm)
 Teacher: Prof. Dipanwita Roy Chowdhury (DRC)
 Section 5, 6
 Monday (3-4:55 pm), Tuesday (3-3:55 pm)
 Teacher: Prof. Sujoy Ghose (SG)
 Section 7, 8
 Wednesday (10-10:55 am), Thursday (9-9:55 am), Friday (11-11:55 am)
 Teacher: Prof. Arobinda Gupta (AG)
 Section 9, 10
 Wednesday (10-10:55 am), Thursday (9-9:55 am), Friday (11-11:55 am)
 Teacher: Prof. Debasis Samanta (DS)
3
Evaluation (Tentative)

 2 short tests (around 30 minutes each)


 Around 30-40% of the marks
 2 long tests
 Around 70-60% of the marks
Introduction

5
Basic Components in a Computer

Input Central Output


Devices: Processing Devices:
Keyboard, Unit (CPU) Monitor,
mouse,… printer,…

Main
Memory (RAM)

Disk
6
Programming and Software
A computer needs to be programmed to do 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

7
Three steps in writing 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)

8
Binary Representation
 Numbers are 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

9
Binary Numbers
Dec Binary
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000 10
Binary Numbers
Dec Binary
Binary to Decimal Conversion
0 0
1 1 101011  1x25 + 0x24 + 1x23 + 0x22 + 1x21 + 1x20
= 43
2 10 (101011)2 = (43)10
3 11
111001  1x25 + 1x24 + 1x23 + 0x22 + 0x21 + 1x20
4 100 = 57
5 (111001)2 = (57)10
101
6 110 10100  1x24 + 0x23 + 1x22 + 0x21 + 0x20 = 20
(10100)2 = (20)10
7 111
8 1000 11
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)

12
Fundamentals of C

13
First C program – print on screen
#include <stdio.h> Output
int main() Hello, World!
{
printf ("Hello, World! \n") ;
return 0;
}

14
A Simple C program
When you run the program
#include <stdio.h>
int main()
{
int x, y, sum, max; Output after you type 15 and 20

scanf(“%d%d”, &x, &y); 15 20


Sum = 35
sum = x + y;
Larger = 20
if (x > y) max = x;
else max = y;
printf (“Sum = %d\n”, sum);
printf (“Larger = %d\n”, max);
return 0;
}
15
Structure of a C 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.
 Until we study functions in detail, this is the only
function your programs will have for now
 Each function has statements for variable
declarations, assignment, condition check, looping
etc.
 Statements are executed one by one in order

16
#include <stdio.h> main function
int main()
{ Declaration statement
int x, y, sum, max;
scanf(“%d%d”, &x, &y); Input statement
sum = x + y; Assignment statements
if (x > y)
max = x; Control statement
else
max = y;
printf (“Sum = %d\n”, sum); Output statement
printf (“Larger = %d\n”, max);
return 0; Return statement
17
}
Writing a C program
 You will have to understand what different statements
do to decide which you should use in what order to
solve your problem
 There is a fixed format (“syntax) for writing each
statement and other things. Need to remember the
syntax
 Do not question why you have to type exactly like this,
you just have to or it is not a C program!!
 Compiler will give error if your typed program does not
match required C syntax
 There are other rules to follow
18
Things you will see in a C program (we
will look at all these one by one)
 Variables
 Constants
 Expressions (Arithmetic, Logical, Assignment)
 Statements (Declaration, Assignment, Control
(Conditional/Branching, Looping)
 Arrays
 Functions
 Structures
 Pointers
19
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:

! # % ^ & * ( )
- _ + = ~ [ ] \
| ; : ‘ “ { } ,
. < > / ?
whitespace characters (space, tab, …)

A C program should not contain anything else 20


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

21
Contd.
 Variables stored in memory
 Memory is a list of consecutive 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

22
Example
#include <stdio.h>
int main( )
{
int x;
int y;
x=1;
y=3;
printf("x = %d, y= %d\n", x, y);
return 0;
}
23
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

24
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

25
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

26
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

27
Variables (contd.)

X = 20
X
Y=15 20

X = Y+3 ? Y

Y=X/6

28
Variables (contd.)

X = 20
X
Y=15 20

X = Y+3 15 Y

Y=X/6

29
Variables (contd.)

X = 20
X
Y=15 18

X = Y+3 15 Y

Y=X/6

30
Variables (contd.)

X = 20
X
Y=15 18

X = Y+3 3 Y

Y=X/6

31
Data Types
 Each variable has a type, indicates what type of
values the variable can hold
 Four common data types in C (there are others)
 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)

32
Contd.
 First rule of variable use: Must declare a variable
(specify its type and name) before using it
anywhere in your program
 All variable declarations should ideally be at the
beginning of the main() or other functions
 There are exceptions, we will see later
 A value can also be assigned to a variable at the
time the variable is declared.
int speed = 30;
char flag = ‘y’;
33
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
34
More Valid and Invalid Identifiers

 Valid identifiers  Invalid identifiers


X 10abc
abc my-name
simple_interest “hello”
a123 simple interest
LIST (area)
stud_name %rate
Empl_1
Empl_2
avg_empl_salary
C Keywords
 Used by 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…
Example 1
#include <stdio.h>
int main()
Three int type variables declared
{
int x, y, sum;
scanf(“%d%d”,&x,&y); Values assigned
sum = x + y;
printf( “%d plus %d is %d\n”, x, y, sum );
return 0;
}

37
Example 2
#include <stdio.h>
int 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);
return 0;
} 38
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
 Prevents accidental change of the value

39
Correct
int main() {
const int LIMIT = 10;
int n;
scanf(“%d”, &n);
if (n > LIMIT) Incorrect: Limit changed
printf(“Out of limit”);
return 0; int main() {
} const int Limit = 10;
int n;
scanf(“%d”, &n);
Limit = Limit + n;
printf(“New limit is %d”, Limit);
return 0;
} 40
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”
41
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

42
Typical Size of Data Types
 char – 1 byte
 int – 4 bytes
 float – 4 bytes
 double – 8 bytes

 “Typical”, because some of them vary depending on


machine/OS type
 Never use the values (1, 4, 8) directly, use the sizeof()
operator given
 sizeof(char) will give 1, sizeof(int) will give 4 and so on your
PC/Laptop

43
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

int a, b; Variable list (note the &


before a variable name)
float c;
scanf(“%d%d%f”, &a, &b, &c);
Format string 44
 Commonly used conversion characters
c for char type variable
d for int type variable
f for float type variable
lf for double type variable

45
Examples
 scanf ("%d", &size) ;
 Reads one integer from keyboard into an int type variable
named size
 scanf ("%c", &nextchar) ;
 Reads one character from keyboard into a char type
variable named nextchar
 scanf ("%f", &length) ;
 Reads one floating point (real) number from keyboard into
a float type variable named length
 scanf (“%d%d”, &a, &b);
 Reads two integers from keyboard, the first one in an int
type variable named a and the second one in an int type
variable named b
46
 Important:
 scanf will wait for you to type the input from the
keyboard
 You must type the same number of inputs as the
number of %’s in the format string
 Example: if you have scanf(“%d%d”,…), then you
must type two integers (in same line or different
lines), or scanf will just wait and the next statement
will not be executed

47
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();

 Program waits at the getchar() line until a


character is typed, and then reads it and stores it
in c
48
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 %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

49
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

50
 Examples:
printf (“Average of %d and %d is %f”, a, b, avg);
printf (“Hello \nGood \nMorning \n”);
printf(“%3d %3d %5d”, a, b, a*b+2);
printf(“%7.2f %5.1f”, x, y);
 Many more options are available for both printf and
scanf
 Read from the book

51
More Examples
(Explain the outputs to test if you understood format strings etc.)

52
More print
Output
#include <stdio.h>
Hello, World! Hello
int main() World!
{
printf ("Hello, World! ") ;
printf ("Hello \n World! \n") ;
return 0;
}

53
Some more print
Output
Hello, World!
#include <stdio.h> Hello
int main() World!
{ Hell
o World!
printf ("Hello, World! \n") ;
printf ("Hello \n World! \n") ;
printf ("Hell\no \t World! \n") ;
return 0;
}

54
Some more print Output
Enter values for f1 and f2:
#include <stdio.h> 23.5 14.326
int main() Enter values for x1 and x2:
{ 54 7
f1 = 23.500000, f2 = 14.33
float f1, f2;
x1 = 54, x2 = 7
int x1, x2;
Can you explain why 14.326
printf(“Enter values for f1 and f2: \n”); got printed as 14.33?
scanf(“%f%f”, &f1, &f2);
printf(“Enter values for x1 and x2: \n”);
scanf(“%d%d”, &x1, &x2);
printf(“f1 = %f, f2 = %5.2f\n”, f1, f2);
printf(“x1 = %d, x2 = %10d\n”, x1, x2);
return 0;
} 55
Some more print
Output
ab
#include <stdio.h> ab
int main()
{
char c1, c2;
scanf(“%c%c”, &c1, &c2);
printf(“%c%c”, c1, c2);
return 0;
}

56
What about this?
Output
ab
#include <stdio.h> a
int main() Can you explain why only ‘a’
{ was printed this time, even
though it is the same program
char c1, c2; as in the last slide? Note the
difference from the last slide
scanf(“%c%c”, &c1, &c2); carefully. Also note that two
characters were read this time
printf(“%c%c”, c1, c2); also, or scanf would have
waited
return 0;
}

57
Practice Problems
 Write C programs to
1. Read two integers and two floating point numbers, each in a separate
scanf() statement (so 4 scanf’s) and print them with separate printf
statements (4 printf’s) with some nice message
2. Repeat 1, but now read all of them in a single scanf statement and
print them in a single printf statement
3. Repeat 1 and 2 with other data types like double and char
4. Repeat 1 and 2, but now print all real numbers with only 3 digits after
the decimal point
5. Read 4 integers in a single scanf statement, and print them (using a
single printf statement) in separate lines such that the last digit of
each integer is exactly 10 spaces away from the beginning of the line
it is printed in (the 9 spaces before will be occupied by blanks or other
digits of the integer). Remember that different integers can have
different number of digits
6. Repeat 5, but now the first integer of each integer should be exactly 8
spaces away from the beginning of the line it is printed in. 58

You might also like