Previous Lecture lect03 Slides Next Lecture

Code from lecture

https://github.com/ucsb-cs16-f18-mirza/cs16-f18-lectures/tree/master/lec-03

Topics

Boolean Expressions

==  // true if two values are equivalent
!=  // true if two values are not equivalent
< // true if left value is less than the right value
<=  // true if left value is less than OR EQUAL to the right value
> // true if left value is greater than the right value
>=  // true if left value is greater than OR EQUAL to the right value
bool x = 5 == 1;  // x = 0
bool x = 3 != 2;  // x = 1
!   // inverts true to false or false to true
&&  // boolean AND
||  // boolean OR
bool x = true;
bool y = true;
x = !x;     // x = false
x = x && y    // x = false
x = x || y    // x = true

Control Structures

If-else statements

if (BOOLEAN_EXPRESSION) {
  // code1
} else {
  // code2
}
int x = 4;
if ((x > 3) && (x < 6)) {
  cout << “x is either 4 or 5” << endl;
} else {
  cout << “x is not 4 or 5” << endl;
}
int x = 4;
if ((x > 3) && (x < 6))
  cout << “x is either 4 or 5” << endl;
else
  cout << “x is not 4 or 5” << endl;
// Will have the same output as the last statement.

int x = 6;
if ((x > 3) && (x < 6))
  cout << “1” << endl;
  cout << “2” << endl; // outside if block
  cout << “3” << endl; // outside if block

Multi-way If-else Statements

int x = 3;
if (x == 1)
  cout << “x equals 1” << endl;
else if (x == 2)
  cout << “x equals 2” << endl;
else if (x == 3)
  cout << “x equals 3” << endl;
else
  cout << “x does not equal 1, 2, or 3” << endl;

User Input

Example of interacting with the console using the cin function

#include <iostream>
#include <string>

using namespace std;

int main() {  
// Example receiving a string from the user
  string name;
  cout << "What is your name? ";
  cin >> name;
  cout << "Hello " << name << endl;

  // Example receiving a number from the user
  int i;
  cout << "Enter a number: ";
  cin >> i;
  cout << "The number entered is " << i << endl;

  cout << i / 2 << endl; // what value / type is this if i == 11? 
}

Example of using command line arguments

int main(int argc, char *argv[]) {
#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[]) {

  cout << "Number of arguments: " << argc << endl;

  cout << argv[0] << endl;
  cout << argv[1] << endl;
  cout << argv[2] << endl;

  // how to use these arguments as numbers?
  // We can convert them using the atoi function
  // in the cstdlib standard library

  int x = atoi(argv[1]) + atoi(argv[2]);
  cout << x << endl;
  return 0;
}

In class demo: Fizzbuzz!