Imperative programming

Fundamentals on Computing for Robotics, Graphics and Computer Vision

Darío Suárez - Adolfo Muñoz

Sequential composition

Instructions are executed in order from the beginning { to the end }

Sequential composition


		{
			instruction1();
			instruction2();
			instruction3();
		}
		

hello-world.cpp

presentation.cpp

addition.cpp

Thinking sequential

  • Identify actions of the sequence
  • Identify variables that carry information
  • Identify order of the actions (total or partial)

Problem

Implement a program that asks the user for a 2-digit natural number and shows the user the addition of both digits.

Conditional composition

Only one of two instructions is executed, depending on a condition.

Conditional composition


			if (condition)
				instructiontrue();
			else
				instructionfalse();
			

Conditional composition


			if (condition) {
				instructiontrue_01();
				instructiontrue_02();
			} else {
				instructionfalse_01();
				instructionfalse_02();
			}
			

absolute.cpp

absolute2.cpp

order2.cpp

Thinking conditional

  • Identify two (or more) alternative actions/sequences (including "do nothing")
  • Identify condition(s) to select actions

Problem

Implement a program that asks the user for three real numbers and outputs the maximum of the three.

Iterative composition

An instruction (set) is continuosly executed several times until a condition is not met. Solves unbounded problems.

Iterative composition


			while (condition)
				instruction();
			instruction_next();
			

Iterative composition


			while (condition) {
				instruction_01();
				instruction_02();
			}	
			instruction_next();
			

count-digits.cpp

power.cpp

Thinking iterative

  • Identify initial state / trivial solution
  • Identify recurrence rule / instructions / induction process
  • Identify condition / last step

Problem

Implement a program that calculates the factorial of a natural number.

for loops


				[initialization] 
				while([condition]) 
				{
					[instructions]
					[iteration]		
				} 
				

					for ([initialization];[condition];[iteration]) 
					{
						[instructions]	
					} 
				

Problem

Implement a program that calculates the factorial of a natural number, using for loops