CS 70

A First Look at C++

  • Duck speaking

    I'd like to see some actual C++ code!

  • LHS Cow speaking

    Okay! We'll begin with a program in a (hopefully) more familiar language, and then move to C++.

Let's begin with a simple “Hello” program that

  • Asks someone their name and greets them
  • Asks their favorite number and tells them something about that number.

Python Code

Here's the program in Python:

# A function to test if a number is prime, takes an integer and returns a
# boolean.
def isPrime(n):
    if n < 2:
        return False
    # Try dividing by all numbers from 2 to sqrt(n).
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    # If we get here, we didn't find a factor, so n is prime.
    return True

# Main program starts here.

name = input("What is your name? ")
print("Hello, {}!".format(name))
number = int(input("What is your favorite number? "))
print("Your favorite number is {}".format(number), end='')
if isPrime(number):
    print(", and that's a prime number!")
else:
    print(". It's not a prime number, but that's okay!")

Run This Code

Click the button below to open this code in the website “Online GDB” (in a new tab).

You can click the green “Run” button in the ribbon at the top of the page. The window at the bottom of the page will show the program running, and you can interact with it there.

If you want to make changes to the code, you can click the “Fork this” button in the bar at the top.

C++ Code

Here is the same program in C++:

#include <iostream>
#include <string>

// This is an example of a function definition, this function takes an integer
// as input and returns a boolean.
bool isPrime(int n) {
    if (n < 2) {
        return false;
    }
    // Try dividing by all numbers from 2 to sqrt(n).
    for (int i = 2; i*i < n; ++i) {
        if (n % i == 0) {
            return false;
        }
    }
    // If we get here, we didn't find a factor, so n is prime.
    return true;
}

int main() {
    std::cout << "What is your name? (one word only please) ";
    std::string name;
    std::cin >> name;
    std::cout << "Hello, " << name << "!" << std::endl;

    std::cout << "What is your favorite number? ";
    int number;
    std::cin >> number;
    std::cout << "Your favorite number is " << number;

    if (isPrime(number)) {
        std::cout << ", and that's a prime number!" << std::endl;
    } else {
        std::cout << ". It's not a prime number, but that's okay!" << std::endl;
    }

    return 0;
}
  • Hedgehog speaking

    I can sort-of see the connection but there are a bunch of weird things here.

  • LHS Cow speaking

    The Online GDB version adds extra comments explaining various things.

Run This Code

Run the code, but also read it over. There are various comments explaining some of the unfamiliar things.

Differences Between Python and C++

What are some differences you notice between the Python and C++ versions of the code?

  • Duck speaking

    One thing I noticed is that is someone had a name like “Jean Marie” it won't accept it, it thinks “Marie” is the number and reads zero.

  • LHS Cow speaking

    That's right. The >> operator reads the next “word”. But you can comment out the line that says

    std::cin >> name;
    

    and uncomment the line that says:

    std::getline(std::cin, name);
    

    Give it a try!

  • RHS Cow speaking

    Remember that you need to click the “Fork this” button at the top to make changes.

Make some change to the C++ code (e.g., the one suggested above) and rerun it.

Question

What small change did you make?

  • LHS Cow speaking

    In the next section, we'll look at the differences between variables in Python and C++.

  • Cat speaking

    Hmm… I wonder what this code would look like in other languages…

  • LHS Cow speaking

    Just for fun (if you're curious), here's the same program in Swift, Go, Rust, C (actually C89), Haskell and even Pascal.

  • Goat speaking

    Meh, if it won't be on the test, I'm not clicking.

(When logged in, completion status appears here.)