Home CPSC 340

C++ Basics

Similarities with Java


Differences from Java


Hello World


#include <iostream>
using namespace std;

int main() {
    cout << "Hello World!" << endl;
    return 0;
}

There are differences between this and hello world in Java:


Name spaces

The last difference is the using namespace std; line. In C++, classes and functions can be organized into name spaces which are similar to packages in Java. The "std" name space includes all of the C++ standard library. By including this line, we do not have to explicitly say what comes from the standard library. The hello world function can also be written as:


#include <iostream>

int main() {
    std::cout << "Hello World!" << std::endl;
    return 0;
}

Notice that cout and endl are now prefixed with std::. Some prefer to explicitly indicate which parts of a program are from which name spaces, while others prefer to save typing with the "using namespace" line.


Data Types

C++ provides largely the same basic types as Java, with some differences:


Input and Output

We have seen doing output with cout. We can use cout on variables as well as:


#include <iostream>
using namespace std;

int main() {
    int month = 1;
    int day = 18;
    int year = 2016;

    cout << "The date is " << month << "/" << day << "/" << year << endl;
    return 0;
}

cout outputs the items that are passed one by one, from left to right.

Input is done with cin. cin is passed one or more variables to read from the user:



#include <iostream>
using namespace std;

int main() {
    int month;
    int day;
    int year;

    cout << "Enter month: ";
    cin >> month;

    cout << "Enter day: ";
    cin >> day;

    cout << "Enter year: ";
    cin >> year;

    cout << "The date is " << month << "/" << day << "/" << year << endl;
    return 0;
}

Note that the angle brackets go opposite ways for cin & cout!

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.