Variables

  • Remember that a variable is a placeholder that stores a value.

Types

  • Below are some of the common variable types in C++:

    Type Description Sample values

    bool

    Yes or no, true or false, etc.

    true, false

    char

    A single character

    'a', 'b', '1', '!', ' ', '\n', …​

    int

    An integers

    -1, 0, 1, 2, …​

    double

    A real number

    -1.5, 1.0, 3.14, …​

    string

    A combination of 0 or more characters

    "hello", "EECS 183", "a", "", …​

  • On most systems, ints range from –2,147,483,648 to 2,147,483,647.

    A bit is a 0 or a 1. A byte is 8 such bits (0s and 1s) grouped together. On most systems, ints are represented using 4 bytes (32 bits). Therefore, ints can represent a total of 232 = 4,294,967,296 possible values. Since ints represent both positive and negative numbers (as well as zero), they range from –2,147,483,648 to 2,147,483,647.
  • string is not a native C++ type, so you must #include <string> atop your program whenever you use strings.

  • strings are combinations of 0 or more characters, so a variable of type string can have 0 characters (i.e., an empty string): "". However, a char is a single character, so it must always represent one character.

Casting

  • Casting is the process of converting a value of one type to another (e.g., a double to an int).

  • There are three ways to cast in C++. All of the three lines below print 3.

    1 2 3
    cout << static_cast<int>(3.14) << endl; cout << int(3.14) << endl; cout << (int) 3.14 << endl;

I/O

  • To make programs at least somewhat interesting, they should be able to take input from the user and then output their result (e.g., to the console).

Input

  • There are several ways to read input from the keyboard

    • Use this method to read in numbers, single characters separated by whitespace, or single words:

      type someVariable;
      cin >> someVariable;
      • This method will skips any leading whitespace.

      • This method will read into someVariable until whitespace or type mismatch.

    • Use this method to read a single line into a string:

      string someString;
      getline(cin, someString);
      • This method does not skip leading whitespace.

      • This method reads into someString until end of line.

      • Next reading starts on the following line.

  • Consider this other program:

    #include <iostream>
    using namespace std;
    
    int main()
    {
        cout << "Please give me an int " << endl;
        int number;
        cin >> number;
        cout << "Thanks for the " << number << "!" << endl;
    }

    What prints if user types 183? What prints if user types 1,000,000?

    Answer: 183, 1.

  • Consider this program:

    #include <iostream>
    using namespace std;
    
    int main()
    {
        cout << "Please give me a name " << endl;
        string name;
        cin >> name;
        cout << "Hello " << name << "!" << endl;
    }

    What prints if user types Maxim? What prints if user types Lord Voldemort?

    Answer: Hello Maxim!, Hello Lord.

Output

  • Output to the console with cout.

    string name = "Maxim";
    cout << "Hello " << name << "!\n";
  • To print a new line (i.e., a line break), either insert endl into cout, as in

    cout << "Hello Grace!" << endl;

    or print a string containing \n (or just the character '\n');

    cout << "Hello Grace!\n";
    cout << 183 << '\n';

Percentages

  • Let’s write a program that asks the user for a numerator,
 asks the user for a denominator and then prints the fraction as a percent.

  • Solution (also in Week 3 source code):

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    /** * percentages.cpp * * Maxim Aleksa * maximal@umich.edu * * Asks the user for a numerator and a denominator. * Then prints the fraction as a percentage. * * Demonstrates operators and casting. */ #include <iostream> using namespace std; int main() { // get the numerator cout << "Numerator: "; int numerator; cin >> numerator; // get the denominator cout << "Denominator (non-zero): "; int denominator; cin >> denominator; // calculate percentage double percentage = (double) numerator / (double) denominator * 100; cout << percentage << "%" << endl; }
  • A problem with the above program is that its behavior is indeterminate if the user enters 0 for the denominator. Try to use an if-else statement to fix!

Showers

  • Check out Nebia!

  • Write a program that asks how many minutes the user spent in the shower and then prints how many gallons of water were used (in a “normal” shower and in a Nebia shower). Assume that 8 minutes is equivalent to using 20 gallons of water in a “normal” shower and to using 6 gallons of water in a Nebia shower.

  • Look at Week 3 source code (showers-0.cpp) for the implementation.

  • Now also print how many water bottles were used. Recall that 1 gallon = 128 ounces
. A typical bottle of (drinking) water might be 16 ounces.

  • Look at Week 3 source code (showers-1.cpp) for the implementation.

  • Let’s modify the program to use the pluralize function from Project 1 to correctly print gallon, gallons, bottle and bottles.

  • Look at Week 3 source code (showers-2.cpp) for the implementation.

Functions

  • You can think of a function as a black box that accepts 0 or more inputs and give you back 0 or 1 output. Functions might also have a side effect (i.e. printing something to the screen, reading something from the keyboard, or even ).

    black box
  • For example, sqrt function that comes in the cmath library takes one input (of type double) and returns the square root of that number. We don’t exactly know how it’s able to that, but we can rely on it and use it in our programs.

  • Another useful function is ceil (also from the cmath library). It also takes a single input of type double and returns the smallest integer not less than its input.

  • In general, inputs to functions are called arguments or parameters and outputs of functions are called return values.

Using Functions

  • Using functions is referred to as calling functions.

  • Call functions by specifying the function’s name, immediately followed by a set of parentheses. Inside parentheses, list the arguments separated by commas.

  • Functions that return a value are not very useful unless you assign their return value to a variable, print the return value or use the return value in another way.

    For example, this is not very useful, since nothing is done with the return value of max:

    int bestScore = max(100, 80);

    But this is more useful, since we use the return value of max by printing it.

    cout << "The larger value is " << max(100, 80) << endl;

    The line below is also useful, since we store the return value of max in the variable bestScore.

    int bestScore = max(100, 80);

    Here’s another example of functions that return a value:

    int score0 = getInt(); (1)
    int score1 = getInt(); (1)
    int bestScore = max(score0, score1); (2)
    cout << "The best score is "
         << bestScore << endl;
    1 getInt takes no arguments (inputs) and returns an int. The function is called twice and the return values get assigned to score0 and to score1.
    2 max function takes two arguments and returns the largest of the two. The return value is assigned to bestScore and is then printed to the console.
  • Functions can also have side effects. For example, they might print something to the console or read user’s input. Here’s an example:

    cout << "What is your name? ";
    string name;
    getline(cin, name); (1)
    sayHello(name); (2)
    1 getline reads users input from cin (standard input) until the end of the line and stores the result in name. We are not using its return value, but getline has a side effect of reading input and storing it in name.
    2 sayHello function doesn’t return a value, but instead supposedly greets the user by name.
  • When writing your own programs (after Project 1!), use functions to achieve

    • Organization

    • Simplification

    • Reusability

  • Be sure to use the pluralize function in Project 1. Look at showers-2.cpp from Week 3 source code for an example of how to use it.

  • You might also find the ceil function from the cmath library useful.

  • When calling functions, do not specify the types of inputs! In other words, don’t do

    int bestScore = max(int score0, int score1);

    Instead, do

    int bestScore = max(score0, score1);

Nested Expressions

  • We can nest function calls and use return values of functions as arguments to other functions.

  • Below is a somewhat meaningless example that demonstrates how nesting works.

    double result = pow(sqrt(4), ceil(2 + 0.75)); (1)
    double result = pow(2.0, ceil(2 + 0.75)); (2)
    double result = pow(2.0, ceil(2.75)); (3)
    double result = pow(2.0, 3.0); (4)
    double result = 8.0; (5)
    1 The assignment operator (=) is right-associative. This means that we first evaluate what is on the right of = and then assign the value of the right side to the left side (variable result).
    2 Before we can call pow, we evaluate all of its arguments. The first argument of pow, sqrt(4), returns 2.0.
    3 The second argument of pow is also a function call, but a bit more complicated. We first add 2 to 0.75 and get 2.75.
    4 After we call ceil by passing it 2.75, we get 3.0 back.
    5 pow takes two arguments and returns the value of the first argument raised to the power of the second argument. 2.0 raised to the power of 3.0 is 8.0, so 8.0 is what is ultimately assigned to result.

Style

  • For each project, 10 points will come from style. It’s easy to get (and to lose) these points!

  • Be sure to read EECS 183 Style Guide. For Project 1, review sections on Comments, Whitespace and Indentation and Variables and Constants.

  • Style rubric for Project 1 is also available.

  • Don’t use global variables (declared outside of any function, such as main).

  • Use descriptive variable names, such as numberOfCookies instead of x, y, a, b, etc.

  • Be sure to declare constants for each conversion factor, so as to avoid using magic numbers. (Magic numbers refer to hardcoding numbers with a meaning in source code instead of using constants.) Declare constants as follows:

    const int OUNCES_IN_GALLON = 128;
  • When calling functions such as pluralize and ceil, be sure to not have any spaces around ( and ), but do include a space after , when separating functions’ arguments:

    cout << pluralize("cookie", "cookies", numberOfCookies) << endl;
  • Comment every few lines (“blocks”) of code, but over-comment. For example, this is a good comment:

    // convert gallons to bottles
    int numberOfBottles = gallonsOfWater * OUNCES_IN_GALLON;

    And this is an example of a bad example of a comment:

    // declaring a variable to store the number of cookies and setting its value to 5
    int numberOfCookies = 5;

Project 1

  • Due by 6pm on Friday 1/22, but accepted until 11:59pm. Project 1 is graded on correctness (50 points) and style (10 points). Submit no later than Wednesday 9/23 (or earlier) for 5% extra credit. Submit no later than Thursday 9/24 for 2.5% extra credit.

  • pluralize function that is declared and implemented in distribution code will help you correctly print singular and plural versions of a word.

  • cmath library that we’ve #included in the distribution code comes with useful functions such as ceil (short for ceiling). For example, ceil(183) will return 183, but ceil(183.4) and ceil(183.9) will return 184.

  • Common reasons for failing test cases on the autograder:

    • Incorrect calculations.

    • Dividing ints instead of doubles.

    • Mispellings Misspellings.

    • Incorrect number of dashes below Shopping List for "Best Ever" Vanilla Cupcakes.

  • Work on the project in office hours!