4 - Specifying Algorithms: Flow of Control: COL 100 - Introduction To Computer Science and Programming
4 - Specifying Algorithms: Flow of Control: COL 100 - Introduction To Computer Science and Programming
4 - Specifying Algorithms: Flow of Control: COL 100 - Introduction To Computer Science and Programming
Flow of Control
COL 100 - Introduction to Computer Science and
Programming
II Semester 2015-2016
Department of Computer Science and Engineering
Indian Institute of Technology Delhi
Programming Tasks
Specification
data
algorithms
Analysis
Design and Implementation
Verification/Testing
Jan 2016
Specifying an Algorithm
Algorithm
Unambiguous specification of a method/
procedure
Jan 2016
main ( )
{
int a, b, c;
b=5
a = 4;
b = 5;
c = a + b;
cout << c;
c=a+b
Print value of c
}
END
Jan 2016
Conditionals
START
a divisible
by 2?
Print even
main ( )
{
int a;
F
cin >> a; // Input from user
if (a % 2 == 0)
cout << even << endl;
else
cout << odd << endl;
Print odd
}
END
Jan 2016
Nested Conditionals
Program to detect Leap year
START
T
T
100
|Y?
F
400
|Y?
Leap
4|
Y?
F
Leap
No
Jan 2016
END
main()
{
if (year % 4 == 0) {
F
if (year % 100 == 0) {
if (year % 400 == 0) {
cout << Leap;
} else {
cout << No;
No
}
} else {
cout << Leap;
}
} else {
cout << No << endl;
}
}
P. R. Panda, I.I.T Delhi
OR
main()
{
if (year % 100 == 0)
cout << No;
else
if (year % 4 == 0)
cout << Yes;
else
cout << No;
}
Which
is
better?
Multi-way Branch:
SWITCH/CASE Statement
START
month
apr,jun,...
30
feb
28
END
Jan 2016
others
31
main()
{
int month, days, year; ...
switch (month) {
case 4:
case 5:
case 9:
case 11: days = 30; break;
case 2: days = (year % 4) ? 28 : 29; break;
default: days = 31;
}
cout << Days in month << month << =
<< days;
}
P. R. Panda, I.I.T Delhi
Conditionals in C++
main()
{
int month, days, year; ...
switch (month) {
case 4:
case 5:
case 9:
case 11: days = 30; break;
case 2: days = (year % 4)?28:29; break;
default: days = 31;
}
cout << Days in month << month << =
<< days;
}
10
main()
{
int month, days, year; ...
switch (month) {
case 4:
case 5:
case 9:
case 11: days = 30; break;
case 2: days = (year % 4) ? 28 : 29; break;
default: days = 31;
}
cout << Days in month << month << =
<< days;
}
11