CSC404 Programming II - Functions Part 1 Notes

Functions in C++

Introduction to Functions
  • Functions, also known as modules or subroutines, are self-contained blocks of code that perform a specific task. They are the building blocks of larger programs.

  • They facilitate the division of complex programs into manageable, smaller, and reusable pieces, which enhances code organization and readability.

  • Using functions promotes modular programming, making it easier to debug, test, and maintain code. Each function can be tested independently.

Function Calls
  • A function is called (or invoked) by writing its name followed by parentheses (). If the function requires arguments, these are placed inside the parentheses.

  • Arguments provide the necessary information for the function to operate. These can be constants, variables, or even expressions.

  • Syntax to call a value-returning function involves using the function's name with appropriate arguments, and the returned value can be stored in a variable or used directly in an expression.

    • Example: result = sqrt(25.0);

Predefined Functions
  • Predefined functions, also known as library or built-in functions, are functions that are already defined in standard C++ libraries.

  • In C++, a function is similar to a function in algebra: it has a name and performs a computation, but unlike algebraic functions, C++ functions can perform a wide variety of tasks, including I/O operations, string manipulation, and more.

  • Examples of predefined mathematical functions:

    • sqrt(x): Calculates the square root of x. Returns a double.

    • Example: sqrt(16.0) returns 4.04.0.

    • pow(x, y): Calculates x raised to the power of y. Both x and y are double.

    • Example: pow(2.0, 3.0) returns 8.08.0.

    • floor(x): Calculates the largest integer less than or equal to x. Returns a double.

    • Example: floor(4.7) returns 4.04.0.

Predefined Function Libraries
  • Predefined functions are organized into separate libraries, each with a specific header file that must be included in your program to use the functions within that library.

    • I/O functions are located in the iostream header, which provides input and output functionalities like cin and cout.

    • Math functions are located in the cmath header, which includes mathematical functions like sqrt, pow, sin, and cos.

  • To use predefined functions, the corresponding header file must be included using an #include statement at the beginning of your program.

    • Example: #include <cmath> to use math functions.

Header Files and Their Functions
  • conio: Declares variable functions used in calling the operating system console I/O routine. (Note: conio is not standard C++ and is mostly used in older compilers).

  • ctype: Contains information used by character classification and conversion macros (e.g., isalpha and toascii). These functions are used to test and modify characters.

    • Example: isalpha('A') returns true because 'A' is an alphabetic character.

  • math: Declares prototypes for mathematical functions and math error handlers. Essential for performing mathematical operations.

  • stdlib: Declares commonly used routines such as conversion, search, and sort functions. Also includes memory allocation functions and random number generation.

    • Example: atoi() to convert a string to an integer, rand() to generate a random number.

  • string: Declares functions for string and memory manipulation. Provides functionalities to work with strings efficiently.

  • time: Defines structures filled by time-conversion functions and types used by these routines. Used for measuring and manipulating time in programs.

  • iomanip: Declares C++ streams I/O manipulators and contains templates for creating parameterized manipulators. Used to format input and output.

    • Example: setprecision() to set the precision of floating-point numbers.

  • iostream: Declares the basic C++ streams I/O routines. Essential for basic input and output operations using cin and cout.

Trigonometric Functions
  • sin(radians): Returns the trigonometric sine of an angle in radians. The input should be in radians, not degrees.

    • Example: sin(0.0) returns 0.00.0.

  • cos(radians): Returns the trigonometric cosine of an angle in radians.

    • Example: cos(0.0) returns 1.01.0.

  • tan(radians): Returns the trigonometric tangent of an angle in radians.

    • Example: tan(0.0) returns 0.00.0.

  • asin(a): Returns the angle in radians for the inverse of sine. The input aa should be between -1 and 1.

    • Example: asin(1.0) returns π2\frac{\pi}{2}.

  • acos(a): Returns the angle in radians for the inverse of cosine. The input aa should be between -1 and 1.

    • Example: acos(1.0) returns 0.00.0.

  • atan(a): Returns the angle in radians for the inverse of tangent.

    • Example: atan(0.0) returns 0.00.0.

Exponential Functions
  • exp(x): Returns ee raised to the power of x (exe^x).

    • Example: exp(1.0) returns e≈2.71828e \approx 2.71828.

  • log(x): Returns the natural logarithm of x (ln(x)=loge(x)ln(x) = log_e(x)). The input xx must be greater than 0.

    • Example: log(2.71828) returns approximately 1.01.0.

  • log10(x): Returns the base 10 logarithm of x (log10(x)log_{10}(x)). The input xx must be greater than 0.

    • Example: log10(100) returns 2.02.0.

  • pow(a, b): Returns a raised to the power of b (aba^b).

    • Example: pow(2.0, 3.0) returns 8.08.0.

  • sqrt(x): Returns the square root of x (x\sqrt{x}) for x >= 0. Returns NAN (Not a Number) if xx is negative.

    • Example: sqrt(9.0) returns 3.03.0.

Rounding Functions
  • ceil(x): Rounds xx up to its nearest integer and returns it as a double.

    • Example: ceil(4.3) returns 5.05.0.

  • floor(x): Rounds xx down to its nearest integer and returns it as a double.

    • Example: floor(4.7) returns 4.04.0.

Min, Max, and Absolute Value Functions
  • min(a, b): Returns the minimum of two numbers, aa and bb. Both aa and bb should be of the same data type.

    • Example: min(5, 3) returns 33.

  • max(a, b): Returns the maximum of two numbers, aa and bb. Both aa and bb should be of the same data type.

    • Example: max(5, 3) returns 55.

  • abs(x): Returns the absolute value of xx (int, long, float, or double). The return type is the same as the input type.

    • Example: abs(-5) returns 55.

Examples of min, max, and abs functions
  • max(2, 3) returns 3

  • max(2.5, 4.0) returns 4.0

  • min(2.5, 4.6) returns 2.5

  • abs(-2) returns 2

  • abs(-2.1) returns 2.1

Character Functions (require cctype header file)
  • isalpha(arg): Returns true if arg is a letter (A-Z, a-z), false otherwise.

    • Example: isalpha('A') returns true, isalpha('2') returns false.

  • isalnum(arg): Returns true if arg is a letter or digit, false otherwise.

    • Example: isalnum('A') returns true, isalnum('2') returns true, isalnum('@') returns false.

  • isdigit(arg): Returns true if arg is a digit (0-9), false otherwise.

    • Example: isdigit('2') returns true, isdigit('A') returns false.

  • islower(arg): Returns true if arg is a lowercase letter, false otherwise.

    • Example: islower('a') returns true, islower('A') returns false.

  • isprint(arg): Returns true if arg is a printable character (includes spaces), false otherwise.

    • Example: isprint('A') returns true, isprint('\n') returns false.

  • ispunct(arg): Returns true if arg is a punctuation character, false otherwise.

    • Example: ispunct(',') returns true, ispunct('A') returns false.

  • isupper(arg): Returns true if arg is an uppercase letter, false otherwise.

    • Example: isupper('A') returns true, isupper('a') returns false.

  • isspace(arg): Returns true if arg is a whitespace character (space, tab, newline, etc.), false otherwise.

    • Example: isspace(' ') returns true, isspace('A') returns false.

Example: isalpha function
#include <iostream>
#include <cctype>
using namespace std;

int main() {
    char input;
    cout << "Enter any character: ";
    cin >> input;
    cout << "\nThe character you entered is: " << input << endl;
    if (isalpha(input))
        cout << "\nThat's an alphabetic character.\n" << endl;
    return 0;
}
Power Function
  • pow(x, y): Calculates xyx^y. Both xx and yy are of type double.

  • For example, pow(2, 3) = 232^3 = 8.0, and pow(2.5, 3) = 2.532.5^3 = 15.625.

  • The pow function is of type double and returns a value of type double.

  • xx and yy are the parameters (or arguments) of the pow function.

  • The pow function has two parameters. Proper error handling should be implemented when using this function, as raising certain numbers to particular powers can result in overflow or undefined behavior.

Square Root Function
  • sqrt(x): Calculates the non-negative square root of xx for xx >= 0.0. For example, sqrt(2.25) is 1.5.

  • The sqrt function is of type double and has only one parameter.

  • It's important to ensure that the input to sqrt is non-negative, as attempting to find the square root of a negative number will result in NAN (Not a Number).

Example: Finding the Hypotenuse of a Right Triangle
  • Formula: c=a2+b2c = \sqrt{a^2 + b^2}

Example: Square Root Function
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double a, b, c;
    cout << "Enter the length of side a:  ";
    cin >> a;
    cout << "Enter the length of side b:  ";
    cin >> b;
    c = sqrt(pow(a, 2.0) + pow(b, 2.0));
    cout << "The length of the hypotenuse is ";
    cout << c << endl;
    return 0;
}
Floor Function
  • floor(x): Calculates the largest whole number that is less than or equal to xx. The data type of xx is double.

  • For example, floor(48.79) is 48.048.0.

  • The floor function is of type double and has only one parameter. It is commonly used in scenarios where you need to round down to the nearest integer value.

String Comparison Functions
  • strcmp(s1, s2): Compares the strings s1s1 and s2s2 lexicographically. Returns 0 if the strings are equal, a negative value if s1s1 is less than s2s2, and a positive value if s1s1 is greater than s2s2.

  • strncmp(s1, s2, n): Compares at most the first nn bytes of strings s1s1 and s2s2. Useful when you only need to compare a portion of the strings.

String Concatenation and Length Functions
  • strcat(s1, s2): Appends string s2s2 to string s1s1. It's crucial to ensure that s1s1 has enough allocated memory to hold the concatenated string to prevent buffer overflows.

  • strncat(s1, s2, n): Appends the first n characters of string s2 to string s1. Provides a safer alternative to strcat by limiting the number of characters appended.

  • strlen(s): Returns the length of string ss, not including the null terminator. Useful for determining the size of a string.

String Copy Functions
  • strcpy(s1, s2): Copies string s2s2 to string s1s1. Similar to strcat, it's essential to ensure that s1s1 has enough allocated memory to prevent buffer overflows.

  • strncpy(s1, s2, n): Copies at most nn bytes of string s2s2 to string s1s1. A safer alternative to strcpy, especially when handling strings of unknown lengths. It's important to manually add a null terminator to s1s1 if s2s2 is longer than nn to ensure it's properly terminated.

Examples: String Functions
  • Demonstrates strcmp, strncmp, strcat, strlen, strcpy, and strncpy.

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    // strcmp & strncmp
    char *s1 = "abcdefg";
    char *s2 = "abcdg";
    char *s3 = "abcdg";
    cout << "strcmp(s1, s2) is " << strcmp(s1, s2) << endl;
    cout << "strcmp(s2, s1) is " << strcmp(s2, s1) << endl;
    cout << "strcmp(s2, s3) is " << strcmp(s2, s3) << endl;
    cout << "strncmp(s1, s2, 3) is " << strncmp(s1, s2, 3) << endl;

    // strcat & strlen
    char s4[20] = "Dallas";
    char s5[20] = "Texas, USA";
    char s6[20] = "Dallas";
    strcat(strcat(s4, ", "), s5);
    strncat(strcat(s6, ", "), s5, 5);
    cout << "The string in s4 is " << s4 << endl;
    cout << "The string in s5 is " << s5 << endl;
    cout << "The string in s6 is " << s6 << endl;
    cout << "The length of string s4 is " << strlen(s4) << endl;
    cout << "The length of string s6 is " << strlen(s6) << endl;

    // strcpy & strncpy
    char s7[20];
    char s8[20] = "Dallas, Texas";
    char s9[20] = "AAAAAAAAAA";
    strcpy(s7, s8);
    strncpy(s9, s8, 6);
    s9[6] = '\0'; // Insert null terminator
    cout << "The string in s7 is " << s7 << endl;
    cout << "The string in s8 is " << s8 << endl;
    cout << "The string in s9 is " << s9 << endl;

    return 0;
}