Lecture Preview: Functions, Strings

(Suggested book reading: Programming Abstractions in C++, Chapters 2-3)

C++ programs can have functions, which are essentially the same as methods in Java. Below is an example of a C++ program with a function to compute the absolute value of an integer. We will talk about the details of the syntax in lecture.

#include <iostream>
#include "console.h"
using namespace std;

// function prototype declaration
int absoluteValue(int n);

int main() {
    cout << "|-5| = " << absoluteValue(-5) << endl;   // function call
    return 0;

// function definition
int absoluteValue(int n) {
    if (n < 0) {
        return -n;
    } else {
        return n;

C++ also has a string type for storing characters of text. Here is a short example that prompts the user to type a string and then prints the string back:

string name;
cout << "Type your name: ";   // Type your name: John Doe
getline(cin, name);           // Hello, John Doe
cout << "Hello, " << name << endl;
This document and its content are copyright © Marty Stepp, 2017. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the authors' expressed written permission.