Review Function

Estimated reading: 15 minutes 932 Views

The Structure of C++ program

#include <iostream>
using namespace std;

int main()
{
    cout << "Welcome to OOP in C++" << endl;

    return 0;
}

Let’s break down the structure and purpose of each command line in the provided C++ code:

#include <iostream>

Structure: This line begins with the #include preprocessor directive, followed by the <iostream> header file enclosed in angle brackets.

Purpose: This line includes the Input/Output Stream Library (iostream), which is essential for performing input and output operations in C++. It provides functionalities like cin for input and cout for output.

using namespace std;

Structure: The using namespace std; line declares that the code will be using the std namespace.

Purpose: The std namespace contains the standard C++ library components, including the cout and endl used in the code. By including this line, you can use these components without explicitly specifying the namespace each time you use them.

int main()
{

Structure: This line marks the beginning of the main function, which is the entry point of every C++ program.

Purpose: The main function is where the program execution starts. It is required in every C++ program, and the code within the curly braces {} defines the body of the main function.

cout << "Welcome to OOP in C++" << endl;

Structure: This line uses the cout object to output the text “Welcome to OOP in C++” to the console. The << operator is used for streaming the text to the output.

Purpose: This line is responsible for displaying a welcome message on the console, indicating that the program is focused on Object-Oriented Programming (OOP) in C++.

    return 0;
}

Structure: The return 0; line signifies the end of the main function. The 0 is returned to the operating system, indicating that the program executed successfully.

Purpose: The return 0; line is a common way to indicate a successful termination of the program. The value 0 is typically returned to the operating system to signify that the program executed without errors.

Libraries in C++

In C++, a library is a collection of pre-compiled functions, classes, and procedures that can be used by a program. These libraries provide a set of functionalities that can be utilized to perform common tasks, ranging from basic input/output operations to complex mathematical computations. Libraries offer a way to modularize code, promote code reuse, and streamline development by providing ready-made solutions for various tasks.

Here are some key aspects of libraries in C++:

  1. Standard Template Library (STL):
    The C++ Standard Library, often referred to as the Standard Template Library (STL), is a core part of C++. It includes a wide range of generic algorithms (e.g., sorting, searching) and data structures (e.g., vectors, lists, maps) that are implemented using templates. The STL simplifies programming by providing efficient and generic solutions to common problems.
  2. Header Files:
    C++ libraries are typically distributed as header files (with the extension .h or .hpp) and implementation files (with the extension .cpp). Header files contain declarations of functions, classes, and other entities that can be used in your program, while the implementation files contain the actual code.
  3. IOStream Library:
    The iostream library is a fundamental part of the C++ Standard Library and provides functionality for input and output operations. It includes cin (for input) and cout (for output), among other stream classes. Here’s an example of using the iostream library:

    #include <iostream>
    
    int main() {
        std::cout << "Hello, C++!" << std::endl;
        return 0;
    }
    
  4. Math Library:
    The cmath library provides a set of mathematical functions, such as trigonometric, logarithmic, and exponential functions.
  5. User-Defined Libraries:
    Apart from the standard libraries, you can create your own libraries to encapsulate and organize your code. This involves creating header files that declare the functions and classes, and implementation files that define their behavior. You can then include your custom library in other C++ programs.

Function in C++

In the realm of programming, functions play a pivotal role in organizing code, enhancing reusability, and promoting a structured approach to problem-solving. In C++, a function is a self-contained unit of code designed to perform a specific task or achieve a particular objective. It encapsulates a set of instructions, allowing you to break down a complex program into smaller, more manageable pieces.

Key Concepts
1. Modularity:
Functions enable the decomposition of a program into smaller, more manageable modules. Each function handles a specific aspect of the overall functionality, promoting a modular and organized code structure.

2. Reusability:
Once a function is defined, it can be reused in different parts of the program or even in other programs. This promotes the “Don’t Repeat Yourself” (DRY) principle, saving both time and effort.

3. Abstraction:
Functions provide a level of abstraction, allowing you to focus on high-level functionality without getting bogged down by the implementation details. This abstraction enhances code readability and simplifies the debugging process.

4. Parameters and Return Values:
Functions can accept input parameters and return values, allowing for dynamic and interactive code. Parameters provide a way to pass information into a function, while return values allow functions to communicate results back to the calling code.

Basic Syntax
A typical C++ function follows this basic syntax:

returnType functionName(parameterType1 parameterName1, parameterType2 parameterName2, ...) {
    // Function body: Code to perform the desired task
    // Optionally, a return statement to provide a result back to the caller
}

Let’s break down the components:

returnType: Specifies the type of data the function will return (if any).
functionName: The unique identifier for the function.
parameters: Input values that the function receives.
functionBody: The set of instructions defining the function’s behavior.

Example 1:

#include <iostream>
using namespace std;
int sum(int x, int y)
{
    return x + y;
}

int main()
{
    cout << sum(10,20) << endl;
    return 0;
}

This C++ code is a simple program that calculates and displays the sum of two numbers.

  • Define a Sum Function:
int sum(int x, int y)
{
    return x + y;
}

This block of code creates a function called sum. It takes in two numbers (x and y) and gives back their sum.

  • Use the Sum Function in the Main Part:
int main()
{
    cout << sum(10, 20) << endl;
    return 0;
}

Here, the main part is like the director of the program. It says, “Hey, calculate the sum of 10 and 20 using the sum function, and show me the result on the screen.” The endl is like pressing Enter on the keyboard; it moves to the next line.

  • Run the Program:

When you run this program, it does the calculation (10 + 20) inside the sum function, then displays the result (30) on the screen. The return 0; part tells the computer that everything went well.

 

Of course, the user can enter the data to be calculated using cin, using this command:

cin >> x >> y;

This command can be located inside the main function, but it’s better to use it inside the function itself to have a cleaner code.
See the following example:

#include <iostream>

using namespace std;
int sum(int x, int y)
{
    cout << "Enter two numbers:\n";
    cin >> x >> y;
    return x + y;
}
int main()
{
    int x = 0, y = 0;
    int z = sum(x, y);
    cout << "The sum is = " << z << endl;

    return 0;
}

This code asks the user to input two numbers, adds them together, and then displays the result.

  • Define a Sum Function:
int sum(int x, int y)
{
    cout << "Enter two numbers:\n";
    cin >> x >> y;
    return x + y;
}

This block of code defines a function called sum. It asks the user to enter two numbers, reads those numbers from the keyboard (cin), and then returns the sum of those numbers.

  • Use the Sum Function in the Main Part:
int main()
{
    int x = 0, y = 0;
    int z = sum(x, y);
    cout << "The sum is = " << z << endl;
    return 0;
}

In the main part, it starts with x and y set to 0. It then calls the sum function, passing x and y as arguments. The sum function gets user input, adds the numbers, and returns the result. The result is stored in z. Finally, it displays the sum with a message using cout.

So, in a nutshell, this program is like a simple interactive calculator. It asks you for two numbers, adds them together, and then shows you the result on the screen.

Providing initial values to variables is crucial to avoid errors.

Example 2:

#include <iostream>
using namespace std;

double avg(double m1, double m2, double m3)
{
    return (m1 + m2 + m3) / 3;
}

int main()
{
    cout << avg(100, 60, 50);
    return 0;
}

This code calculates and displays the average of three numbers.

The avg function takes in three numbers (m1, m2, and m3), adds them together, divides by 3, and returns the result. This is how you calculate the average of three numbers.
In the main part, it directly calls the avg function with three numbers (100, 60, and 50) as arguments. It then uses cout to display the result, which is the average of these three numbers.

Example 3:

#include <iostream>
using namespace std;

int max(int n1, int n2, int n3)
{
    int m = n1;
    if (m < n2)
        m = n2;
    if (m < n3)
        m = n3;
    return m;
}

int main()
{
    cout << max(100, 20, 800);
    return 0;
}

This code finds and displays the maximum of three numbers.

The max function takes in three numbers (n1, n2, and n3) and uses conditional statements (if) to determine the maximum among them. It begins by considering n1 as the initial maximum value and then employs conditional statements (if) to compare it with the other values. Whenever the condition is met, the maximum value is updated. The maximum value is then returned.

In the main part, it directly calls the max function with three numbers (100, 20, and 800) as arguments. It then uses cout to display the result, which is the maximum of these three numbers.

We can find a minimum value among other values using the same logic but changing the conditions.

Example 4:

#include <iostream>
using namespace std;

void p()
{
    cout << "myName\n";
}

int main()
{
    p();
    return 0;
}

This code defines a function and then calls that function in the main part of the program.

The function called p used void keyword before the function name which means that this function doesn’t return any value. Inside the function, it uses cout to display the text “myName” on the screen.

In the main part, it calls the p function. When a function is called, the program jumps to that function, performs the tasks inside it, and then returns to where it was called. In this case, it jumps to the p function, prints “myName” to the screen, and then returns to the main function.

  • Now, let’s talk about the concept of a void function:

A void function is a function that doesn’t return a value. In this example, the p function is a void function because it has the void keyword before its name.

Void functions are useful when you want a function to perform a task or set of tasks without needing to provide a result back to the part of the program that called it.

Example 5:

#include <iostream>
using namespace std;

int mul(int x = 10, int y = 50)
{
    return x*y;
}

int main()
{
    cout << mul(10) << endl;
    cout << mul(10, 2) << endl;
    cout << mul() << endl;

    return 0;
}

This code demonstrates the use of default arguments in a function.

The function called mul multiplies two numbers (x and y). The interesting part is that both x and y have default values assigned (10 and 50, respectively). If these values are not provided when the function is called, these defaults will be used.

In the main part, it calls the mul function multiple times with different combinations of arguments:

mul(10): It uses the default value 50 for y, so it multiplies 10 by 50.
mul(10, 2): It uses both 10 and 2 provided as arguments, so it multiplies 10 by 2.
mul(): Since no arguments are provided, it uses both default values (10 and 50), so it multiplies 10 by 50.

  • Now, let’s talk about the concept of default arguments:

Default arguments allow you to provide values to parameters in a function declaration, so if the caller doesn’t provide values, the default values are used.

In this example, the mul function has default values for both x and y, making it flexible when calling the function with different numbers of arguments.

Example 6:

#include <iostream>
using namespace std;

void ref(int &x, int &y)
{
    x += 1;
    y += 1;
}

int main()
{
    int p = 0, t = 0;
    ref(p, t);
    cout << "p = " << p << endl;
    cout << "t = " << t << endl;
    return 0;
}

This code demonstrates the concept of “call by reference.”

The function called ref has an interesting part which is that it takes references (&x and &y) as parameters, indicating that it will directly modify the values of the variables passed to it.

In the main part, it declares two variables (p and t) and initializes them to 0. Then, it calls the ref function with p and t as arguments. Inside the ref function, both p and t are increased by 1. Finally, it prints the values of p and t after the function call using cout.

  • Now, let’s talk about the concept of call by reference:

In C++, when you pass parameters to a function by reference (using &), the function receives the memory addresses of the actual variables, not just copies of their values.

This means any changes made to the parameters inside the function directly affect the original variables outside the function.

In this example, the ref function modifies the values of p and t directly because they are passed by reference.

Built-in functions

Built-in functions in C++ are pre-defined functions provided by the C++ programming language. These functions are part of the standard C++ library and offer ready-made solutions for common tasks. They are designed to perform specific operations and can be used by programmers without the need to write the entire code for those operations.

Here’s a simple breakdown:

  • Ready-made Tools:
    Built-in functions are like tools that are already available for you to use. Instead of creating these tools from scratch, you can simply use the built-in functions to perform various tasks.
  • Part of the Standard C++ Library:
    These functions are part of the standard C++ library, which is a collection of tools and functionalities that come with every C++ compiler. You don’t need to create or install anything extra to use them.
  • Common Operations:
    Built-in functions are designed to perform common operations such as input/output, mathematical calculations, string manipulations, and more. Examples include cout and cin for printing and reading from the console, sqrt for square root, and strlen for getting the length of a string.
  • Saves Coding Time:
    By using built-in functions, you can save a lot of time and effort. You don’t need to write complex code for tasks that are already handled by these functions.
  • Consistency Across Platforms:
    Since these functions are part of the standard library, they provide a consistent way to perform operations across different platforms and compilers. This makes your code more portable and ensures it works similarly on various systems.

In essence, built-in functions in C++ are like a toolbox that comes with the language. They provide a set of tools you can use to make your programming tasks easier, faster, and more standardized. As you become more familiar with C++, you’ll discover and leverage these functions to streamline your code.

Here are some common built-in functions in C++:

  1. Input/Output Functions:
    cout: Used to display output to the console.
    cin: Used to take input from the user through the console.
  2. Mathematical Functions:
    sqrt(): Calculates the square root of a number.
    abs(): Returns the absolute value of a number.
    pow(): Raises a number to a specified power.
  3. String Functions:
    strlen(): Returns the length of a string.
    strcpy(): Copies one string to another.
    strcat(): Concatenates (joins) two strings.
  4. Character Functions:
    isalpha(): Checks if a character is an alphabet letter.
    isdigit(): Checks if a character is a digit.
    toupper(): Converts a character to uppercase.
  5. Array Functions:
    sizeof(): Returns the size of a data type or an array.
    sort(): Sorts elements in an array in ascending order.
  6. Memory Functions:
    malloc(): Allocates a specified amount of memory dynamically.
    free(): Releases memory that was previously allocated with malloc.
  7. Time and Date Functions:
    time(): Returns the current time in seconds.
    ctime(): Converts a time value into a string representation.

Example 7:

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;

int main()
{
    cout << abs(-10) << endl;
    cout << max(10, 20) << endl;
    cout << max(max(10, 20), 30) << endl;
    int x = 10, y = 20;
    swap(x,y);
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    
    return 0;
}

This code demonstrates the usage of several built-in functions from the <cmath> and <algorithm> libraries.

  • abs(-10): Calculates the absolute value of -10 and prints the result (10) to the console.
  • max(10, 20): Finds the maximum of two numbers (10 and 20) and prints the result (20) to the console.
  • max(max(10, 20), 30): Compares three numbers (10, 20, and 30) and finds the maximum among them. It prints the result (30) to the console.
  • swap(x, y): Swaps the values of x and y. After this line, x will be 20, and y will be 10.

Output:

10
20
30
x = 20
y = 10

 

 

Share this

Review Function

Or copy link

CONTENTS
English