Lecture Preview: Functions

(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;
    }
}
This document and its content are copyright © Marty Stepp and Julie Zelenski, 2019. 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.