Review

Why do we have char type and values when we also have string type and values? Efficiency (out of scope for this course).

While loops in Karel and C++

while (condition)
{
  statement;
  statement;
  ..
}
statement;
statement;
  ..
Draw flowchart on what happens in what order for the while statement. Show that if and while are very similar, except that while has a back-edge in the flow chart. Highlight that if the condition is false, then the loop body does not execute even once.

Exercise: Sentinel loops

Example: prompt the user for numbers until the user types -1, then output the sum of numbers: Enter a number: 10 Enter a number: 20 Enter a number: 30 Enter a number: -1 Sum is: 60

Program:

#include <iostream>
#include "simpio.h"
using namespace std;
int main() {
  int sum = 0;
  int num = getInteger("Enter a number: ");
  while (num != -1)
  {
    sum += num;
    num = getInteger("Enter a number: ");
  }
  cout << "Sum is " << sum << endl;
  return 0;
}

How is the condition formed? It can be any boolean value which can be formed by a constant (show a while(false) and a while(true) loop) or a variable or an expression. Expressions must be bool-valued and can involve arithmetic, relational and logical operators.

Exercise: write a program that allows you to sum at most 10 numbers at a time.

For loops in Karel and C++

for (int i = 0; i < count; i++)
{
  statement;
  statement;
  ...
}
Repeats the statements in the body count times.

i = 0 is the initializer and is run once before the loop starts

i > count is the condition that is checked before entering the loop at every repitition/iteration (including the first entry).

i++ is run each time the code gets to the end of the 'body'

for (int i = 0; i < 3; i++)
{
  cout << "I love COL100" << endl;
}