Helper library (aka Stanford library)

Getting Console Input

Use the helper library simpio:
#include "simpio.h"
Function name Description
getInteger("prompt") repeatedly prompts until an integer is typed; returns it
getReal("prompt") repeatedly prompts until a double is typed; returns it
getLine("prompt") repeatedly prompts and reads/returns an entire line of text
getYesOrNo("prompt") repeatedly prompts for a Yes/No answer; return it as a bool

Note: cin is the standard C++ method to get input and these helper library functions use it inside them. cin has some issues for easy use in our course:

If/Else in Karel and C++

if (condition)
{
  statement;
  statement;
  ..
}
else
{
  statement;
  statement;
  ..
}
statement;
statement;
  ..
Condition must be of type bool.

Example:

string fullName = getLine("Student name? ");
int age = getInteger("How old are you? ");
double gpa = getReal("What's your GPA so far? ");
if (getYesOrNo("Destroy the universe?"))
{
  ...
}
Condition must be of type bool. Repeats the statments in the body until condition is no longer true. Each time, all statements in the body are executed, and then the condition is checked.

Exercise: Opposition vs. Government

Write a program to compute who won the no-confidence motion in the Lok Sabha

Code:

/* This program prints the outcome of a no-confidence motion in the parliament. */
#include <iostream>
#include "simpio.h"
using namespace std;
int main() {
  int government = getInteger("Government (votes against the motion)? ");
  int opposition = getInteger("Opposition (votes for the motion)? ");
  if (government > opposition) {
    cout << "Government won!" << endl;
  } else {
    if (opposition > government) {
      cout << "Opposition won!" << endl;
    } else {
      cout << "A tie." << endl;
    }
  }
  return 0;
}

If/Else can be nested

if (condition1)
{
  if (condition2)
  {
  }
} else
{
  if (condition3)
  {
  }
}




For a single statement in the body, do not necessarily need braces

if (condition)
  statement;
else
{
  statement;
  statement;
  ...
}
or
if (condition)
{
  statement;
  statement;
  ...
}
else
  statement;

If/Else can be stringed together

if (condition1)
{
  ...
} else if (condition2)
{
  ...
} else if (condition3)
{
  ...
} else
{
  ...
}

Precedence rules for arithmetic operators: division (/), multiplication (*), add and subtract.

Logical operators

Precedence rules for logical operators: not (!), and (&&), or (||)

Precedence overall: arithmetic > relational > logical

Example

5 * 7 >= 3 + 5 * (7 - 1) && 7 <= 11
  1. (7-1)=6
  2. 5*7=35, 5*6 = 30
  3. 3+30=33
  4. 35>=33 is true
  5. 7<=11 is true
  6. true && true is true