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 adouble.Example:
sqrt(16.0)returns .pow(x, y): Calculates x raised to the power of y. Bothxandyaredouble.Example:
pow(2.0, 3.0)returns .floor(x): Calculates the largest integer less than or equal to x. Returns adouble.Example:
floor(4.7)returns .
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
iostreamheader, which provides input and output functionalities likecinandcout.Math functions are located in the
cmathheader, which includes mathematical functions likesqrt,pow,sin, andcos.
To use predefined functions, the corresponding header file must be included using an
#includestatement 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:coniois not standard C++ and is mostly used in older compilers).ctype: Contains information used by character classification and conversion macros (e.g.,isalphaandtoascii). These functions are used to test and modify characters.Example:
isalpha('A')returnstruebecause '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 usingcinandcout.
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 .
cos(radians): Returns the trigonometric cosine of an angle in radians.Example:
cos(0.0)returns .
tan(radians): Returns the trigonometric tangent of an angle in radians.Example:
tan(0.0)returns .
asin(a): Returns the angle in radians for the inverse of sine. The input should be between -1 and 1.Example:
asin(1.0)returns .
acos(a): Returns the angle in radians for the inverse of cosine. The input should be between -1 and 1.Example:
acos(1.0)returns .
atan(a): Returns the angle in radians for the inverse of tangent.Example:
atan(0.0)returns .
Exponential Functions
exp(x): Returns raised to the power of x ().Example:
exp(1.0)returns .
log(x): Returns the natural logarithm of x (). The input must be greater than 0.Example:
log(2.71828)returns approximately .
log10(x): Returns the base 10 logarithm of x (). The input must be greater than 0.Example:
log10(100)returns .
pow(a, b): Returns a raised to the power of b ().Example:
pow(2.0, 3.0)returns .
sqrt(x): Returns the square root of x () for x >= 0. ReturnsNAN(Not a Number) if is negative.Example:
sqrt(9.0)returns .
Rounding Functions
ceil(x): Rounds up to its nearest integer and returns it as a double.Example:
ceil(4.3)returns .
floor(x): Rounds down to its nearest integer and returns it as a double.Example:
floor(4.7)returns .
Min, Max, and Absolute Value Functions
min(a, b): Returns the minimum of two numbers, and . Both and should be of the same data type.Example:
min(5, 3)returns .
max(a, b): Returns the maximum of two numbers, and . Both and should be of the same data type.Example:
max(5, 3)returns .
abs(x): Returns the absolute value of (int, long, float, or double). The return type is the same as the input type.Example:
abs(-5)returns .
Examples of min, max, and abs functions
max(2, 3)returns 3max(2.5, 4.0)returns 4.0min(2.5, 4.6)returns 2.5abs(-2)returns 2abs(-2.1)returns 2.1
Character Functions (require cctype header file)
isalpha(arg): Returnstrueifargis a letter (A-Z, a-z),falseotherwise.Example:
isalpha('A')returnstrue,isalpha('2')returnsfalse.
isalnum(arg): Returnstrueifargis a letter or digit,falseotherwise.Example:
isalnum('A')returnstrue,isalnum('2')returnstrue,isalnum('@')returnsfalse.
isdigit(arg): Returnstrueifargis a digit (0-9),falseotherwise.Example:
isdigit('2')returnstrue,isdigit('A')returnsfalse.
islower(arg): Returnstrueifargis a lowercase letter,falseotherwise.Example:
islower('a')returnstrue,islower('A')returnsfalse.
isprint(arg): Returnstrueifargis a printable character (includes spaces),falseotherwise.Example:
isprint('A')returnstrue,isprint('\n')returnsfalse.
ispunct(arg): Returnstrueifargis a punctuation character,falseotherwise.Example:
ispunct(',')returnstrue,ispunct('A')returnsfalse.
isupper(arg): Returnstrueifargis an uppercase letter,falseotherwise.Example:
isupper('A')returnstrue,isupper('a')returnsfalse.
isspace(arg): Returnstrueifargis a whitespace character (space, tab, newline, etc.),falseotherwise.Example:
isspace(' ')returnstrue,isspace('A')returnsfalse.
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 . Both and are of typedouble.For example,
pow(2, 3)= = 8.0, andpow(2.5, 3)= = 15.625.The
powfunction is of typedoubleand returns a value of typedouble.and are the parameters (or arguments) of the
powfunction.The
powfunction 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 for >= 0.0. For example,sqrt(2.25)is 1.5.The
sqrtfunction is of typedoubleand has only one parameter.It's important to ensure that the input to
sqrtis non-negative, as attempting to find the square root of a negative number will result inNAN(Not a Number).
Example: Finding the Hypotenuse of a Right Triangle
Formula:
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 . The data type of is double.For example,
floor(48.79)is .The
floorfunction is of typedoubleand 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 and lexicographically. Returns 0 if the strings are equal, a negative value if is less than , and a positive value if is greater than .strncmp(s1, s2, n): Compares at most the first bytes of strings and . Useful when you only need to compare a portion of the strings.
String Concatenation and Length Functions
strcat(s1, s2): Appends string to string . It's crucial to ensure that 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 tostrcatby limiting the number of characters appended.strlen(s): Returns the length of string , not including the null terminator. Useful for determining the size of a string.
String Copy Functions
strcpy(s1, s2): Copies string to string . Similar tostrcat, it's essential to ensure that has enough allocated memory to prevent buffer overflows.strncpy(s1, s2, n): Copies at most bytes of string to string . A safer alternative tostrcpy, especially when handling strings of unknown lengths. It's important to manually add a null terminator to if is longer than to ensure it's properly terminated.
Examples: String Functions
Demonstrates
strcmp,strncmp,strcat,strlen,strcpy, andstrncpy.
#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;
}