TYPES OF USER DEFINED FUNCTIONS

 

 


For better understanding of arguments and return in functions, user-defined functions can be categorised as:

    Function with no argument and no return value
    Function with no argument but return value
    Function with argument but no return value
    Function with argument and return value

Consider a situation in which you have to check prime number. This problem is solved below by making user-defined function in 4 different ways as mentioned above.


Example 1: No arguments passed and no return value


void prime(){
// Return type of function is void because value is not returned.
void prime()

    int num, i, flag = 0;

    cout << "Enter a positive integer enter to check: ";
    cin >> num;

    for(i = 2; i <= num/2; ++i)
    {
        if(num % i == 0)
        {
            flag = 1;
            break;
        }    }   if (flag == 1)
    {
        cout << num << " is not a prime number.";
    }
    else
    {
        cout << num << " is a prime number.";
    }
}

int main()
{
    // No argument is passed to prime()
    prime();
    return 0;
}


In the above program, prime() is called from the main() with no arguments.

prime() takes the positive number from the user and checks whether the number is a prime number or not.

Since, return type of prime() is void, no value is returned from the function.

 
Example 2: No arguments passed but a return value


#include <iostream>
using namespace std;
int prime();
int main()
{
    int num, i, flag = 0;
    // No argument is passed to prime()
    num = prime();
    for (i = 2; i <= num/2; ++i)
    {
        if (num%i == 0)
        {
            flag = 1;
            break;
        }
    }
    if (flag == 1)
    {
        cout<<num<<" is not a prime number.";
    }
    else
    {
        cout<<num<<" is a prime number.";
    }
    return 0;
}

// Return type of function is int
int prime()
{
    int n;

    printf("Enter a positive integer to check: ");
    cin >> n;

    return n;
}


In the above program, prime() function is called from the main() with no arguments.
prime() takes a positive integer from the user. Since, return type of the function is an int, it returns the inputted number from the user back to the calling main() function.
Then, whether the number is prime or not is checked in the main() itself and printed onto the screen.

 
Example 3: Arguments passed but no return value

#include <iostream>
using namespace std;
void prime(int n);

int main()
{
    int num;
    cout << "Enter a positive integer to check: ";
    cin >> num;
    
    // Argument num is passed to the function prime()
    prime(num);
    return 0;
}

// There is no return value to calling function. Hence, return type of function is void. */
void prime(int n)
{
    int i, flag = 0;
    for (i = 2; i <= n/2; ++i)
    {
        if (n%i == 0)
        {
            flag = 1;
            break;
        }
    }
    if (flag == 1)
    {
        cout << n << " is not a prime number.";
    }
    else {
        cout << n << " is a prime number.";
    }
}

 
In the above program, positive number is first asked from the user which is stored in the variable num.
Then, num is passed to the prime() function where, whether the number is prime or not is checked and printed.
Since, the return type of prime() is a void, no value is returned from the function.

 
Example 4: Arguments passed and a return value.

#include <iostream>
using namespace std;
int prime(int n);

int main()
{
    int num, flag = 0;
    cout << "Enter positive integer to check: ";
    cin >> num;

    // Argument num is passed to check() function
    flag = prime(num);

    if(flag == 1)
        cout << num << " is not a prime number.";
    else
        cout<< num << " is a prime number.";
    return 0;
}

/* This function returns integer value.  */
int prime(int n)
{
    int i;
    for(i = 2; i <= n/2; ++i)
    {
        if(n % i == 0)
            return 1;
    }

    return 0;
}


In the above program, a positive integer is asked from the user and stored in the variable num.

Then, num is passed to the function prime() where, whether the number is prime or not is checked.

Since, the return type of prime() is an int, 1 or 0 is returned to the main() calling function. If the number is a prime number, 1 is returned. If not, 0 is returned.

Back in the main() function, the returned 1 or 0 is stored in the variable flag, and the corresponding text is printed onto the screen.

 
Which method is better?

All four programs above gives the same output and all are technically correct program.

There is no hard and fast rule on which method should be chosen.

The particular method is chosen depending upon the situation and how you want to solve a problem.

 

Functions

 

A function is a block of code that performs a specific task.

Suppose we need to create a program to create a circle and color it. We can create two functions to solve this problem:

  • a function to draw the circle
  • a function to color the circle

Dividing a complex problem into smaller chunks makes our program easy to understand and reusable.

There are two types of function:

  1. Standard Library Functions: Predefined in C++
  2. User-defined Function: Created by users

 

C++ User-defined Function

C++ allows the programmer to define their own function.

A user-defined function groups code to perform a specific task and that group of code is given a name (identifier).

When the function is invoked from any part of the program, it all executes the codes defined in the body of the function.

 

C++ Function Declaration

The syntax to declare a function is:

returnType functionName (parameter1, parameter2,...) {
    // function body   
}

Here's an example of a function declaration.
 

// function declaration
void greet() {
    cout << "Hello World";
}

Here,

  • the name of the function is greet()
  • the return type of the function is void
  • the empty parentheses mean it doesn't have any parameters
  • the function body is written inside {}
  •  
  • Calling a Function

    In the above program, we have declared a function named greet(). To use the greet() function, we need to call it.

    Here's how we can call the above greet() function.

    int main() {
         
        // calling a function   
        greet(); 
    
    }
     Hello World

    Function Parameters

    As mentioned above, a function can be declared with parameters (arguments). A parameter is a value that is passed when declaring a function.


    For example, let us consider the function below:

    void printNum(int num) {
        cout << num;
    }
     

     

    Benefits of Using User-Defined Functions

  • Functions make the code reusable. We can declare them once and use them multiple times.
  • Functions make the program easier as each small task is divided into a function.
  • Functions increase readability.

C++ Library Functions

Library functions are the built-in functions in C++ programming.

Programmers can use library functions by invoking the functions directly; they don't need to write the functions themselves.

Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.

In order to use library functions, we usually need to include the header file in which these library functions are defined.

For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include the header file cmath.

 

Example 5: C++ Program to Find the Square Root of a Number

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

int main() {
    double number, squareRoot;
    
    number = 25.0;

    // sqrt() is a library function to calculate the square root
    squareRoot = sqrt(number);

    cout << "Square root of " << number << " = " << squareRoot;

    return 0;
}

Output

Square root of 25 = 5

In this program, the sqrt() library function is used to calculate the square root of a number.

The function declaration of sqrt() is defined in the cmath header file. That's why we need to use the code #include <cmath> to use the sqrt() function.

 

 

 

While and Do...While Loop

 

 
 

C++ while Loop

The syntax of the while loop is:

while (condition) {
    // body of the loop
}

Here,

  • A while loop evaluates the condition
  • If the condition evaluates to true, the code inside the while loop is executed.
  • The condition is evaluated again.
  • This process continues until the condition is false.
  • When the condition evaluates to false, the loop terminates.
 

Example: Sum of Positive Numbers Only

// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
    int number;
    int sum = 0;

    // take input from the user
    cout << "Enter a number: ";
    cin >> number;

    while (number >= 0) {
        // add all positive numbers
        sum += number;

        // take input again if the number is positive
        cout << "Enter a number: ";
        cin >> number;
    }

    // display the sum
    cout << "\nThe sum is " << sum << endl;
    
    return 0;
}

Output

Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25

In this program, the user is prompted to enter a number, which is stored in the variable number.

In order to store the sum of the numbers, we declare a variable sum and initialize it to the value of 0.

The while loop continues until the user enters a negative number. During each iteration, the number entered by the user is added to the sum variable.

When the user enters a negative number, the loop terminates. Finally, the total sum is displayed.

 

C++ do...while Loop

The do...while loop is a variant of the while loop with one important difference: the body of do...while loop is executed once before the condition is checked.

Its syntax is:

do {
   // body of loop;
}
while (condition);

Here,

  • The body of the loop is executed at first. Then the condition is evaluated.
  • If the condition evaluates to true, the body of the loop inside the do statement is executed again.
  • The condition is evaluated once again.
  • If the condition evaluates to true, the body of the loop inside the do statement is executed again.
  • This process continues until the condition evaluates to false. Then the loop stops.

Example 3: Display Numbers from 1 to 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
    int i = 1; 

    // do...while loop from 1 to 5
    do {
        cout << i << " ";
        ++i;
    }
    while (i <= 5);
    
    return 0;
}

Output

1 2 3 4 5

Here is how the program works.

Iteration       Variable i <= 5 Action
                      
i = 1 not checked 1 is printed and i is increased to 2
1st i = 2 true 2 is printed and i is increased to 3
2nd i = 3 true 3 is printed and i is increased to 4
3rd i = 4 true 4 is printed and i is increased to 5
4th i = 5 true 5 is printed and i is increased to 6
5thi = 6falseThe loop is terminated

 

 

Infinite while loop

If the condition of a loop is always true, the loop runs for infinite times (until the memory is full). For example,

// infinite while loop
while(true) {
    // body of the loop
}

Here is an example of an infinite do...while loop.

// infinite do...while loop

int count = 1;

do {
   // body of loop
} 
while(count == 1);

In the above programs, the condition is always true. Hence, the loop body will run for infinite times.


for vs while loops

A for loop is usually used when the number of iterations is known. For example,

// This loop is iterated 5 times
for (int i = 1; i <=5; ++i) {
   // body of the loop
}

Here, we know that the for-loop will be executed 5 times.

However, while and do...while loops are usually used when the number of iterations is unknown. For example,

while (condition) {
    // body of the loop
}

 

 


For Loop

 


 

 

In computer programming, loops are used to repeat a block of code.

For example, let's say we want to show a message 100 times. Then instead of writing the print statement 100 times, we can use a loop.

That was just a simple example; we can achieve much more efficiency and sophistication in our programs by making effective use of loops.

There are 3 types of loops in C++.

  • for loop
  • while loop
  • do...while loop

C++ for loop

The syntax of for-loop is:

for (initialization; condition; update) {
    // body of-loop 
}

Here,

  • initialization - initializes variables and is executed only once
  • condition - if true, the body of for loop is executed
    if false, the for loop is terminated
  • update - updates the value of initialized variables and again checks the condition


Example: Printing Numbers From 1 to 5

#include <iostream>

using namespace std;

int main() {
        for (int i = 1; i <= 5; ++i) {
        cout << i << " ";
    }
    return 0;
}

Output

1 2 3 4 5

Here is how this program works

Iteration  Variable i <= 5 Action
1st              
i = 1 true      
1 is printed. i is increased to 2.
2nd i = 2 true 2 is printed. i is increased to 3.
3rd i = 3 true 3 is printed. i is increased to 4.
4th i = 4 true 4 is printed. i is increased to 5.
5th i = 5 true 5 is printed. i is increased to 6.
6thi = 6false  The loop is terminated             

 

Ranged Based for Loop

In C++11, a new range-based for loop was introduced to work with collections such as arrays and vectors. Its syntax is:

for (variable : collection) {
    // body of loop
}

Here, for every value in the collection, the for loop is executed and the value is assigned to the variable.


Example: Range Based for Loop

#include <iostream>

using namespace std;

int main() {
  
    int num_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  
    for (int n : num_array) {
        cout << n << " ";
    }
  
    return 0;
}

Output

1 2 3 4 5 6 7 8 9 10

In the above program, we have declared and initialized an int array named num_array. It has 10 items.

Here, we have used a range-based for loop to access all the items in the array.


C++ Infinite for loop

If the condition in a for loop is always true, it runs forever (until memory is full). For example,

// infinite for loop
for(int i = 1; i > 0; i++) {
    // block of code
}

In the above program, the condition is always true which will then run the code for infinite times.

 

Switch Statement

 

Switch Statement

The switch statement allows us to execute a block of code among many alternatives.

The syntax of the switch statement in C++ is:

switch (expression)  {
    case constant1:
        // code to be executed if 
        // expression is equal to constant1;
        break;

    case constant2:
        // code to be executed if
        // expression is equal to constant2;
        break;
        .
        .
        .
    default:
        // code to be executed if
        // expression doesn't match any constant
}

How does the switch statement work?

The expression is evaluated once and compared with the values of each case label.

  • If there is a match, the corresponding code after the matching label is executed. For example, if the value of the variable is equal to constant2, the code after case constant2: is executed until the break is encountered.
  • If there is no match, the code after default: is executed.

Note: We can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is cleaner and much easier to read and write.

 

C++ switch...case flowchart 

 

Example: Create a Calculator using the switch Statement

// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    cout << "Enter an operator (+, -, *, /): ";
    cin >> oper;
    cout << "Enter two numbers: " << endl;
    cin >> num1 >> num2;

    switch (oper) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2;
            break;
        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2;
            break;
        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2;
            break;
        case '/':
            cout << num1 << " / " << num2 << " = " << num1 / num2;
            break;
        default:
            // operator is doesn't match any case constant (+, -, *, /)
            cout << "Error! The operator is not correct";
            break;
    }

    return 0;
}

Output 1

Enter an operator (+, -, *, /): +
Enter two numbers: 
2.3
4.5
2.3 + 4.5 = 6.8

Output 2

Enter an operator (+, -, *, /): -
Enter two numbers: 
2.3
4.5
2.3 - 4.5 = -2.2

Output 3

Enter an operator (+, -, *, /): *
Enter two numbers: 
2.3
4.5
2.3 * 4.5 = 10.35

Output 4

Enter an operator (+, -, *, /): /
Enter two numbers: 
2.3
4.5
2.3 / 4.5 = 0.511111

Output 5

Enter an operator (+, -, *, /): ?
Enter two numbers: 
2.3
4.5
Error! The operator is not correct.

In the above program, we are using the switch...case statement to perform addition, subtraction, multiplication, and division.

How This Program Works

  1. We first prompt the user to enter the desired operator. This input is then stored in the char variable named oper.
  2. We then prompt the user to enter two numbers, which are stored in the float variables num1 and num2.
  3. The switch statement is then used to check the operator entered by the user:
    • If the user enters +, addition is performed on the numbers.
    • If the user enters -, subtraction is performed on the numbers.
    • If the user enters *, multiplication is performed on the numbers.
    • If the user enters /, division is performed on the numbers.
    • If the user enters any other character, the default code is printed.

Notice that the break statement is used inside each case block. This terminates the switch statement.

If the break statement is not used, all cases after the correct case are executed.

 

C++ Ternary Operator

 

 

 

Ternary Operator in C++

A ternary operator evaluates the test condition and executes a block of code based on the result of the condition.

Its syntax is

condition ? expression1 : expression2;

Here, condition is evaluated and

  • if condition is true, expression1 is executed.
  • And, if condition is false, expression2 is executed.

The ternary operator takes 3 operands (condition, expression1 and expression2). Hence, the name ternary operator.


Example : C++ Ternary Operator

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

int main() {
  double marks;

  // take input from users
  cout << "Enter your marks: ";
  cin >> marks;

  // ternary operator checks if
  // marks is greater than 40
  string result = (marks >= 40) ? "passed" : "failed";

  cout << "You " << result << " the exam.";

  return 0;
}

Output 1

Enter your marks: 80
You passed the exam.

Suppose the user enters 80. Then, the condition marks >= 40 evaluates to true. Hence, the first expression "passed" is assigned to result.

Output 2

Enter your marks: 39.5
You failed the exam.

Now, suppose the user enters 39.5. Then, the condition marks >= 40 evaluates to false. Hence, the second expression "failed" is assigned to result.

 

When to use a Ternary Operator?

In C++, the ternary operator can be used to replace certain types of if...else statements.

 

Nested Ternary Operators

It is also possible to use one ternary operator inside another ternary operator. It is called the nested ternary operator in C++.

Here's a program to find whether a number is positive, negative, or zero using the nested ternary operator.

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

int main() {
  int number = 0;
  string result;

  // nested ternary operator to find whether
  // number is positive, negative, or zero
  result = (number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

  cout << "Number is " << result;

  return 0;
}

Output

Number is Zero

In the above example, notice the use of ternary operators,

(number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

Here,

  • (number == 0) is the first test condition that checks if number is 0 or not. If it is, then it assigns the string value "Zero" to result.
  • Else, the second test condition (number > 0) is evaluated if the first condition is false.