Sie sind auf Seite 1von 57

Design and Pedagogy

of the
Introductory Programming Course

Abhiram Ranade
IIT Bombay

Pedagogy
Where we are

We defined the topics to be covered in the syllabus.


I Detailed discussion of rationale, scope, and depth of each topic
The next big task
How do we teach all this?
I How do we motivate all these topics to students?
Should appeal to students’ taste/career goals/sense of fun
I Should we use any scaffolding?
Scaffolding: extra code given to students to get started quickly
and for enabling appealing programming applications.

Any specific teaching problems we should address?


I Slow start: several initial weeks typically spent without writing exciting
programs.
“Cannot write exciting programs unless students know many things.”
I Looping constructs are hard to learn for many students.

I Recursion is hard to understand.


Outline

I Overview of the main ideas in our pedagogy


I Scaffolding
I A graphics library
I A “repeat” statement
I A quick tour through the core topics in the syllabus
I Detailed remarks on how to teach
Some educational principles (1)

Motivations for learning:


I ”I cannot get a degree unless I learn this”

I ”My teacher tells me it will be useful later”

I ”I like it and I see it is useful”

“If you want to build a ship, don’t drum up people together to collect wood and
don’t assign them tasks and work, but rather teach them to long for the endless
immensity of the sea.”
– Antoine de Saint-Exupery

Teachers report that students respond better if they explain the motivation clearly.
Some educational principles (2)
How learning is assimilated:
I New learning must be reconciled with prior knowledge.

I Reconciliation can improve quality of both!

I By drawing on prior knowledge, learning can be speeded up.

Prior knowledge:
I Mathematics: Arithmetic, algebra, geometry, calculus, statistics.

I Physics: Mechanics, optics, circuit theory.

I General Knowledge: Networks of various kinds: family trees, web pages,


transportation networks..
Students already know many algorithms in these areas. Build up on these.
Students report that programming helps their understanding of math!
Students are excited by the synergy. (Also revise a bit.)
Some educational principles (3)

Any subject = Principles or Essence + Details

Details must be taught, but they must not overwhelm the principles/essensce.

What is the essence of computer programming?


Some educational principles (4)

How learning happens:

”I hear and I forget. I see and I remember. I do and I understand.”


– Confucious
I Pictures are important. Animations even more so. Even more interesting if the
student herself does the animation.
I Doing and experiencing is more important than dry theory.
A general principle: First impressions are important!

On the first day, students are most fresh, most energetic, and possessing their most
positive attitude.

Can we produce “love at first sight”?

We must rise to the occasion and provide them excitement and challenge!

Put forward your best foot – exhibit the best features of your subject and get them
to actively participate.

The Challenge: students havent learned anything; how will they understand
interesting ideas? And participate??
Textbook
Even the best teachers will not always connect to all students.
I Student does not follow teacher’s accent.

I Student is not able to take good notes.

I Student is absent.

A good textbook helps and serves as a safety net.


Select textbook carefully: read it yourself first!
I Does the textbook motivate each topic in a manner that the student can
understand?
“Why do we need dynamic memory allocation? inheritance?”
I Are difficult topics explained well?
“How exactly does a function call execute?”
I Is the explanation too verbose?

I Are alternate ways of writing the same logic discussed?


Selecting and using a textbook
Selecting a textbook (contd.):
I Are there good problems?
The book should give problems from diverse areas, e.g. physics
I Is there enough background material given with the problems?
The relevant scientific information, e.g. laws/formulae should also be provided.
I Designing medium sized programs is harder than just understanding the
language. Are their such case studies using interesting problems?
Students will understand issues such as “how to organize large programs etc.”
only through such case studies.

Assign reading from the book so that students learn to become independent learners.
Later in life they will only have to books to learn from!

The teacher does not have to do all the work – let the book help you.
Summary
I Motivation is needed and it should come from the students’ world.
Motivation = “We want to write a program to do ...”
I Use programming examples from math and science, and even fun and art, to
have synergy with the prior knowledge, and career goals of our students.
I In the era of cellphones, graphical input and output are very important if the
students are to take us seriously.
I Graphics is important also for science and math visualization.
I Keep the focus on understanding computations and their structure, rather than
language syntax.
I The language will be learned with minimal effort if there are exciting motivating
programs to be written.
I Get to interesting programming examples on day 1.
I Use a good textbook.
Scaffolding
Scaffolding

Scaffolding: “Additional material that we teach in order to help teach the main
material”
I Scaffolding should have minimal cognitive load.

I Scaffolding should appeal to all.


Scaffolding 1: A 2D graphics library
Implements “Turtle Graphics” and also coordinate based graphics:
I Can create objects on a separate window.

I Objects can be moved, scaled, rotated

I Object colours can be changed.

I Objects can draw lines as they move.

I Graphical input

I Animations, graph plotting is easy.

Cognitive load is minimal.


2D graphics is very intuitive
Graphics/visualization is very useful in science/engineering.
Most students will like it.
Games, animation can be designed.
Perhaps will be enough to attract students..
Scaffolding 2: The repeat statement
We used preprocessor macro facility of C++ to create a “repeat” statement.

Syntax: repeat (count) {code to be repeated}

Semantics: Will cause “code to be repeated” to execute count times.

The repeat macro gets loaded alongwith the graphics library.


We treat it as a real C++ statement until we teach standard looping statements.

Motivation:
I repeat + graphics allow us to write interesting programs from day 1.

I This allows us to excite students and improve learning.

I Standard looping statements are quite complicated; they become easier to


understand after the students have understood repeat.
Simplecpp and repeat available at [Sim14].
Lesson plan
Lesson plan (Only core topics)
1. Introduction: Turtle prog., How computers work and solve problems. 4 hrs
2. Basic data types, variables, assignment statements. 2 hrs
3. Basics of program design (computing e) 2 hrs
4. Coordinate based graphics, projectile motion 1 hr
5. Conditionals 2 hrs
6. Loops including computing math functions, Newton-Raphson. 5 hrs
7. Functions including recursion, correctness 6 hrs
8. Arrays including polynomial mult., insertion sort. 5 hrs
9. Structures 4 hrs
10. Basics of memory management 1 hr
11. String and vector classes 2 hrs
12. Pragmatic issues (Debugging, input output redirection, files) 1 hr
Total: 35 hrs
Typical course has 40 hours total. Additional 5 hours can be used to cover Tier 2
core (T2C) topics, or discuss more applications, revise.
A quick tour of the course
Begin with a bang: get to the essence of programming on day 1

Introduction using “Turtle Geometry”:


Invented in 1960s by Seymour Pappert, as part of the Logo programming language
for teaching programming to children.

Turtle: a symbolic animal that lives on the screen.

Moves as per commands issued by the program.

Has a pen, which draws on the screen as the turtle moves.

Goal of turtle graphics: Draw interesting pictures on the screen.


A simple program fragment
turtleSim(); // Start turtle graphics

forward(100); // Tells turtle to move forward 100 pixels.


right(90); // Tells turtle to turn right by 90 degrees

forward(100);
right(90);

forward(100);
right(90);

forward(100);

Ask students: What does this draw?


This gives us our first program.
The full day 1 program
#include <simplecpp>
main_program{
turtleSim();
forward(100); wait(0.5); right(90); wait(0.5);
forward(100); wait(0.5); right(90); wait(0.5);
forward(100); wait(0.5); right(90); wait(0.5);
forward(100);
wait(5);
}
I <simplecpp>: For graphics functionality. Also includes “using namespace
std;”, and <iostream>.
I main program: C++ preprocessor macro. Gets translated to int main()
I Students must understand namespaces, iostreams, int main, but not on day 1.
I wait : So that we have time to see..
The second program for day 1

main_program{
turtleSim();
repeat(4){
forward(100); right(90);
}
}

Show the program without explaining “repeat”.

Most students understand without explanation; explain after letting them guess.
Another day 1 program
main_program{
turtleSim();
repeat(10){
repeat(4){
forward(100); right(90);
}
right(10);
}
wait(10);
}

“What do you think it does?”


This is what I ask students. Most figure it out!
Why? Because it is an interesting challenge!
What have students learnt on day 1?

1. Control flow
2. Elementary iteration, including nested iteration
3. Basic ideas of syntax, spaces, indentation
4. Importance of observing patterns in what is to be accomplished, and expressing
them using repeat
Do not write 100 statements to draw a 100 sided polygon!
Very important activity while designing programs!

Essence of programming?

Last activity for day 1: Show movie of what is possible using graphics.
Homework for day 1:
I Draw a two dimensional grid.
I Draw a circle (as limit of n sided polygon).
I Draw 5 cornered star.
Requires some high school geometry.
Note: most programming needs domain knowledge.
Students know the required geometry, but we might as well remind them of the
important ideas, as a part of the homework statement.
I “If the turtle starts at a certain orientation and at the end has the same
orientation, it must have turned through a multiple of 360 degrees.”
Will help in drawing stars.
I “If you change the angle gradually the path traced by the turtle will look lie an
arc.” Will help in drawing circles.
Students will be happy to do the homeworks they will be eager to see how the turtle
will move. They want to feel the power.
Topic 1 b: How computers solve problems
I We would like students to believe that computers are very useful.
I Some interesting computations should be explained at popular science level.
Candidate examples: Image processing, Text processing, Weather prediction.

Key ideas to be explained: Chapter 2, [Ran14]


I “Everything must be represented as numbers”!
Numeric codes for text, discretization and intensity values
I “Next apply laws of physics, set up equations, solve...”

I (Manual) Algorithm = Precise description of what calculations are needed.


“You already know algorithms: primary school arithmetic
I Assurance that a computer can perform all the steps that are used in manual
algorithms. Arithmetic, conditional execution, looping
Topic 1 c: How a computer works

Some rough idea needs to be given to help in the discussion of programming.

You have to either give a realistic view or an abstract/notional view.

Engineering students may relish a realistic view.


Chapter 2 of [Ran14]

Realistic views may be misunderstood less. Next


Realistic and notional views of how computers work
Notional view: “A computer circuit understands C++ programs.”
Anthropomorphic view suggests computer will “have common sense”.
Realistic view: Chapter 2, [Ran14]
I C++ program is translated into a machine language program by a compiler.
I Machine language program is a sequence of numbers representing actions that
the computer must perform.
Example: 70 30 31 32 might mean “Add the contents of locations 30 and 31 and
place the result in location 32”.
Example: 80 30 31 32 might mean “Multiply the contents of locations 30 and 31
and place the result in location 32”.
Students like knowing this.
Also, it reinforces the idea that a computer will only do what it is told.
No harm in saying in addition that “your program must contain every action you
want performed, in exactly the order you want”
Realistic and notional view of a variable
Realistic view: When you write “int xyz;” you typically get 32 capacitors in your
computer memory for storing the value of xyz.
Notional view: “A variable is like a box into which you place the value.”
This can give rise to many misconceptions. [dB89, Koh17]
I A variable can contain several values simultaneously. Several slips of paper.
I When you execute x = y; the value moves from y to x. The paper moves..
I A variable can contain a formula or an unevaluated expression.

“The number of children is the number of girls plus the number of boys. How many
children are there if there are seven girls and five boys?” [Sim11]
int chlidren, boys, girls;
children = boys + girls; // children "box" gets formula
boys = 5; girls = 7;

Misconceptions less likely with capacitors..


Remarks
Homeworks:
I “Describe in words how you multiply n digit numbers”
Student must say “in ith iteration we do ...” etc.
I What happens if you execute instruction 70 30 30 30?
Square calculated
I What happens if you execute program 70 30 30 30 70 30 30 30?
Fourth power calculated
Don’t expect students to remember what 70, 80 means.
The homework should reinforce idea: computers work “mechanically”

But what do you do in programming labs?


Drawing programs can be asked!
Just using repeat, left, right it is possible to draw very interesting intricate pictures.
Topic 2: Data types and variables. Assignment statements

Operators, precedence, rounding/truncation, ...


Information overload! Can we make learning “active”?

The most interesting program possible using standard teaching style:


Convert from pounds to kilograms...
Students havent even learned the if statement!

Students will remember concepts better if they are used for doing interesting things.

With our approach:


Because students already know ”repeat”, many interesting programs can be written!
Exciting things you can do with repeat + assignment

Draw more interesting pictures: Spiral. Chapter 3, [Ran14]

int i=10;
repeat(10){forward(i); right(90); i = i + 10;}

Calculate averages. Chapter 3, [Ran14]

int n; cin >> n; double sum = 0;


repeat(n){
int x; cin >> x; sum = sum + x;
}
cout << sum/n << endl;
Remark on teaching assignment operation
Some trivial points need to be hammered into students..
“How computer computation is different from human”
= is assignment, not comparison: confuses every generation of students.
I In principle, this confusion is only syntactic, and so should be easy to avoid.

I But in practice, because the math interpretation of = so well established,


students who are slightly inattentive can get lost.
invites “Storing formula in variable” interpretation

Students use = to mean comparison: instead of ==


Use compiler option to warn about this.

Division truncates: Natural to write centigrade = 5/9 * (fahrenheit - 32);


Beginners spend countless hours on this “bug”
Topic 3: Program Design
Many students report that they can understand the language but not write complete
programs.
I “Don’t know how to start”

I Students find the interaction between different language statements for, if


etc. difficult to manage.
I Turtle programs involve very primitives and hence are easier to write.

I Useful to show some full programs and ask students to modify those.

Discussion about design needed when we discuss the first non-trivial program.
I Our choice: Calculate e by summing series Chapter 4, [Ran14]
I Needs only repeat and assignment statements. Language complexity will not
overwhelm design considerations.
I Should be taught in a leisurely manner. Next
I Students appreciate the slow development.
Program Design (continued)
Our recipe for program design (Discussed last week)
I Understand problem: create input output examples.
I Understand how you would solve the problem manually.
I State what values you calculate in each iteration.
In ith iteration ith term ti of series is calculated...
I Make your program mirror the manual computation.
Statement of what happens in iteration i : Plan
Stating plans is very important for debugging.
I Identify what variables you will need.
A variable to hold each value that needs to be remembered.
Emphasize the distinction between what to compute and how to compute it.
What: Plan. States what values will be calculated.
How: Code that does the computation. Comes later.

Homeworks: Programs to (approximately) evaluate other infinite sums and products.


Remarks

Program design issues should continue to get discussed throughout the course.
I Students should be frequently reminded to design manual algorithms before
writing programs.
I Writing down precise plans for all important loops should be expected.

I Plans should be like invariants, and they should contain all the information
required to see that the program is correct.
Should not demand formal proof of correctness.
I When you find students debugging code in labs, see if they have written a plan.
Remind them that this will help in debugging.
I Likewise for every function it is important to clearly state what it is supposed
to do, before writing the function – also useful in debugging.
Topic 4: Coordinate based graphics:
Creation, Manipulation, Graphical input
Circle c1(200,225,25);
// c1 = circle. center at (200,225), r = 25
Rectangle r1(200,200,50,70);
// center coordinates, width, height
r1.right(45); // rotate 45 degrees
c1.move(10,20); // move by 10,20 in x,y directions
int z = getClick();
// z = 65536 * x coordinate of cursor + y coordinate
Educational goals acheived: Implicit introduction to constructor and member access
syntax. Practice with repetition, which will be needed to do interesting animations.
Excitement value: Elementary animation can be done.
Will provide examples/programming problems for weeks to come
Topic 4 example 1: Projectile motion
initCanvas("Projectile motion", 500,500); // start 2d graphics

int start = getClick(); // launch point

Circle sp(start /65536, start % 65536, 5);


sp.penDown();

double vx=1,vy=-5; // initial velocity


repeat(100){
sp.move(vx,vy);
vy += .1;
wait(0.1);
}
getClick(); // just so that you can see
Topic 4 example 2: Least squares fit T2C

(x1 , y1 ), . . . , (xn , yn ) : points to fit line to

Best fit line is y = mx + c where

nr − qs ps − qr
m= c=
np − q 2 np − q 2

xi2 , q =
P P P P
where p = i i xi , r = i xi yi , and s = i yi .

All calculations can be done using a simple repeat loop! Next


Week 3 assignments 2: Least squares fit
initCanvas("Fitting a line to data",500,500);
double p=0, q=0, r=0, s=0;
int n; cin >> n;
repeat(n){
int cPos = getClick(); double x = cPos/65536, y = cPos % 65536;
Circle(x,y,5).imprint();

p += x*x;
q += x;
r += x*y;
s += y;
}
double m = (n*r - q*s)/(n*p - q*q);
double c = (p*s - q*r)/(n*p - q*q);
Line l(0,c, 500, 500*m+c);
The if statement
All lectures should begin by stating the motivation for what will be taught
“Here is a problem you cannot program with what you already know.”
Then teach whatever language feature that is needed for the program.

Motivation for the if statement:


“Suppose you want to calculate tax according to the following rules: (1) If your
annual income is less than Rs 180000 you pay no tax, (2) If your annual income is
between Rs 180001 and Rs 500000 you pay 10 % of your income above Rs. 180000,
(3) If your income is between ...”
You may have other favourite examples
This example can be used to develop many programs.
I One if statement per tax bracket.

I One large if-then-elseif-... statement with simpler consecutive


conditions. Use flowcharts to help students understand the difference.
Students should see different ways of writing the same logic.
Loops
Motivation for while loop: In repeat you need to know upfront how many times
the loop executes.
I Soloway’s rainfall problem: Given a sequence of numbers terminated by 99999
(sentinel), find the average of all numbers excepting 99999.
Infinite looping possible: Need to argue termination.
Example of difficult termination argument: Euclid’s GCD
Rainfall problem loop: (read, test, process)
Can be implemented using code copying or break statement.
Nicely explained using flowcharts.
for loop: Must use when there is a natural “control variable”
Students should be able to transform while to for and vice versa.
Example programs: Many from scientific computing, physical simulation.
Tell students that repeat is implemented using for Chapter 7,8 [Ran14]
Functions
Most obvious use of functions: Code needed in several places can be written just
once.
Less obvious to intro students: Functions enable program to be broken up into
manageable pieces.

How functions execute: Must state explicitly


I At the time of the call an area in memory is allocated for storing the
parameters and local variables while the call executes “Activation frame”
I Calling program suspends

I When return statement is executed the activation frame is deallocated.

Explains why local variables in calling and called functions can have the same name
Chapter 9 [Ran14]

If your explanation is good, students will automatically understand how recursive


functions execute.
Functions: references and pointers
References and pointers are useful in writing functions that
I Return more than one result.

I Modify their arguments.

References are natural to be taught with functions.

Teaching of pointers can be deferred to arrays or structures, but:


I When taught with arrays there is additional complexity of index calculation.

I When taught with structures, there is additional complexity of references to


elements of the same type.
I When taught with functions we need discuss only the operators address of, &
and dereference, *.
Recursion
Many facets
I Algorithm design strategy

I Mechanics of execution of recursive programs

I Structural recursion

Introduction could be through Euclidean GCD (preferred) or factorial.


GCD: Euclid probably discovered GCD by thinking recursively.
Euclidean GCD: contrast with proof of iterative version.
Mechanics of execution: do an example.
“Function call mechanism is not different for recursion.”

Chapter 10 [Ran14]
Structural recursion
Structural recursion is more known to student, e.g. family trees.

Canonical problem class that can be studied:


Persons are numbered 0 through n − 1. Array Father[0..n-1] contains values s.t.
I If Father[i] = −1, then the father of person i is not known.

I If Father[i] ≥ 0, then Father[i] is the father of person i.

“Write a program that reads a number j and finds the oldest ancestor of i.”
“Write a program that reads a number j and finds the number of descendants of i.”
I Many such relationship questions can be asked.
I Students will be able to solve them, while getting practice with index
manipulation and recursive thinking.

Classical structural recursion is discussed in Chapter 24, [Ran14]


Pictorial Recursion
Tree = trunk + two small trees

void tree(int levels){


if(levels > 0){
forward(levels*25); // trunk
left(15);
tree(levels-1); // first small tree
right(30);
tree(levels-1); // second small tree
left(15);
forward(-levels*25);
}
}

Helps in understanding recursion + source of good problems.


Arrays
Many uses of arrays:
I Unordered list/set Roll nos of students in a class
I Queue Passengers waiting for taxis
I Map from integers 0, . . . , n − 1 to array elements Histogram

Index calculation:
I A[i] calculated in constant time.

I Why A[i] might go out of bounds.

I Pointer interpretation, especially for passing to functions.

Brief discussion:
I Multidimensional arrays, representing matrices.

I Null terminated character arrays.


Structures: starting point of OOP
I Structures and classes are essentially same in C++.
Members are public in structures and private in classes by default.
I Motivation for structures: aggregation/composition
Gathering together the data/code associated with an entity.
Represent every interesting entity using a structure.
I Member functions are natural and can be motivated.
I Constructors can be motivated as a means to “not forget to initialize”.
struct queue{int elts[10],next; queue(){next = 0;}}
I Copy constructor, destructor, are harder to motivate.
T2C
I Operator overloading is not hard, but perhaps not worth the effort as core.
T2C
I Encapsulation, inheritance and polymorphism are slightly harder to motivate.
T2C
Basics of memory management: Heap memory

Motivating example: Using memory efficiently


I Storing names, each of which can be very short or very long

I Storing polygons of different number of sides

Basic operations: new, delete


Much safer than malloc..

There is much more to memory management, it should be discussed only if you


have time. T2C
The string and vector classes
string class should be considered core and discussed well.
I Manipulating null terminated strings is very error prone.

I If you do not introduce string class your students will continue to use null
terminated strings.

vector class should also be considered core.


I If you don’t teach this your students will somehow learn linked lists and use
those.
I Vectors are better than lists in most use cases.

I Convenient even otherwise: no need to pass length.

I Library function for sorting.

“These classes use memory allocation but that is an advanced topic.”


T2C: Chapter 21, [Ran14]
Working environment

Choices: shell + editor. Choose editor that indents.


Codeblocks IDE: modified to allow single file program.
Utility of graphics and repeat
I Graphics and repeat enable discussing interesting problems from day 1.
I Graphics is useful throughout the course for generating interesting problems.
I repeat is useful until standard looping statements are taught, which might
happen as much as a month into the course.
I Having good programming examples is very useful to make students remember
concepts.
I Graphics is useful for explaining concepts also, e.g. recursion.
I Repeat is halfway to looping constructs, so breaks down the difficulty of
understanding looping constructs.
I Graphics and repeat are very easy to learn: ideal scaffolding.
Like training wheels on children’s bikes.

Experience: Even the weakest student understands turtle movements and repeat.
Concluding remarks

I Basic ideas behind our pedagogy were presented.


I Pedagogy for the core syllabus was presented.

To come: Pedagogy for the advanced topics (T2C), Design of examinations.


B. du Boulay, Some difficulties of learning to program, Studying the novice
programmer (E. Soloway and J. Spohrer, eds.), Lawrence Erlbaum, Hillsdale,
NJ, 1989, pp. 283–299.
Tobias Kohn, Variable evaluation: An exploration of novice programmers’
understanding and common misconceptions, Proceedings of the 2017 ACM
SIGCSE Technical Symposium on Computer Science Education (New York, NY,
USA), SIGCSE ’17, ACM, 2017, pp. 345–350.
Abhiram Ranade, An Introduction to Programming through C++, McGraw Hill
Education (India) Private Limited, New Delhi, 2014,
http://www.cse.iitb.ac.in/~ranade/book.html.
Simon, Assignment and sequence: Why some students can’t recognise a simple
swap, Proceedings of the 11th Koli Calling International Conference on
Computing Education Research (New York, NY, USA), Koli Calling ’11, ACM,
2011, pp. 10–15.
Simplecpp Library, 2014,
http://www.cse.iitb.ac.in/~ranade/simplecpp.

Das könnte Ihnen auch gefallen