C++ Level 5 Function Exercises With Solutions

by Alex Johnson 46 views

Welcome to the comprehensive guide for Level 5 C++ function exercises! This article provides detailed solutions and explanations for a set of programming problems designed to enhance your understanding and proficiency in C++ functions. Whether you're a student, a self-learner, or a seasoned programmer looking to brush up your skills, this guide will help you master essential C++ concepts through practical examples.

1. Calculating the Number of Digits in a Given Number

In this section, we'll explore a C++ function to calculate the number of digits in a given integer. This exercise is a classic example of using loops and basic arithmetic operations to solve a common programming problem. Understanding how to manipulate numbers and extract their components is crucial for various applications, from data validation to algorithm design. Let's dive into the problem and its solution.

#include <iostream>
using namespace std;

int reqemsayi (int n){
    int say=0;
    
    if (n == 0)
        return 1;

    while (n > 0) {
        n /= 10;
        say++;}
    
    return say;
}

int main(){
    int eded;
    cout << "Ededi daxil edin: ";
    cin >> eded;

    cout << "Reqemlerin sayi: " << reqemsayi(eded) << endl;

    return 0;
}

Explanation:

The reqemsayi function takes an integer n as input and returns the number of digits it contains. The function initializes a counter variable say to 0. If the input number n is 0, the function immediately returns 1 because 0 is considered to have one digit. Otherwise, the function enters a while loop that continues as long as n is greater than 0. Inside the loop, n is divided by 10 in each iteration, effectively removing the last digit. The counter say is incremented in each iteration, tracking the number of digits processed. Once n becomes 0, the loop terminates, and the function returns the final value of say, which represents the total number of digits in the original number.

In the main function, the program prompts the user to enter an integer, reads the input into the eded variable, calls the reqemsayi function with eded as the argument, and prints the result to the console. This demonstrates a simple yet effective way to count the digits of a number using a while loop and integer division.

2. Displaying 3-Digit Numbers with a Digit Sum of 10

This section focuses on identifying and displaying three-digit numbers whose digits sum up to 10. This problem involves iterating through a range of numbers and applying a condition to filter out the ones that meet our criteria. It’s a great exercise for understanding loops, conditional statements, and modular arithmetic in C++. Let's explore the code and break down how it works.

#include <iostream>
using namespace std;

int reqemcemi (int n){
    int cem = 0;
    while (n > 0) {
        cem += n % 10;
        n /= 10;}
    return cem;
}

int main() {
    cout << "Reqemlerinin cemi 10 olan 3 reqemli ededler:";

    for (int i = 100; i <= 999; i++) {
        if (reqemcemi(i) == 10) {
            cout << i << " ";}
    }

    return 0;
}

Explanation:

The reqemcemi function calculates the sum of the digits of a given integer n. It initializes a variable cem to 0. The function then enters a while loop that continues as long as n is greater than 0. Inside the loop, the last digit of n is obtained using the modulo operator (n % 10), and this digit is added to cem. The number n is then divided by 10, effectively removing the last digit. This process continues until n becomes 0, at which point the function returns the total sum of the digits.

The main function iterates through all three-digit numbers (from 100 to 999) using a for loop. For each number i, it calls the reqemcemi function to calculate the sum of its digits. If the sum is equal to 10, the number i is printed to the console. This exercise effectively demonstrates how to combine loops and conditional statements to filter numbers based on a specific criterion, providing a practical application of fundamental C++ concepts.

3. Checking if a Number is a Perfect Number

Here, we'll delve into the concept of perfect numbers and how to identify them using C++. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding the number itself). This exercise is a great way to practice your understanding of loops, conditional statements, and number theory in programming. Let's break down the code and see how it works.

#include <iostream>
using namespace std;

bool mukemmel (int n) {
    int cem = 0;

    for (int i =1; i < n; i++) {
        if (n % i == 0)
            cem += i;}

    return cem == n;
}

int main() {
    int eded;
    cout << "Ededi daxil edin: ";
    cin >> eded;

    if (mukemmel(eded))
        cout << eded << " mukemmel ededdir";
    else
        cout << eded << " mukemmel eded deyil";

    return 0;
}

Explanation:

The mukemmel function checks if a given integer n is a perfect number. It initializes a variable cem to 0, which will store the sum of the proper divisors. The function then iterates through numbers from 1 to n - 1 using a for loop. For each number i, it checks if i is a divisor of n using the modulo operator (n % i == 0). If i is a divisor, it is added to cem. After the loop finishes, the function returns true if cem is equal to n, indicating that n is a perfect number, and false otherwise.

The main function prompts the user to enter an integer, reads the input into the eded variable, and calls the mukemmel function with eded as the argument. It then prints a message to the console indicating whether the entered number is a perfect number or not. This exercise nicely combines the concept of perfect numbers with the practical implementation of loops and conditional statements in C++.

4. Calculating the Sum of Digits of a Number

In this section, we'll focus on writing a C++ function to calculate the sum of the digits of a given number. This is a fundamental problem that reinforces the use of loops and arithmetic operations. It’s a common task in many programming scenarios, such as data validation and numerical analysis. Let's explore the code and its functionality.

#include <iostream>
using namespace std;

int sum(int n) {
    int sum = 0;
    n = abs(n); 
    while (n > 0) {
        sum += n % 10;
        n /= 10; }
    return sum;
}

int main() {
    int number;
    cout << "Ededi daxil edin: ";
    cin >> number;

    int a = sum(number);
    cout << "Reqemlerin cemi: " << a << endl;

    return 0;
}

Explanation:

The sum function calculates the sum of the digits of an integer n. It starts by initializing a variable sum to 0. The function uses the abs function to ensure that the input number is positive, handling both positive and negative inputs. A while loop is then used to iterate through the digits of n. Inside the loop, the last digit of n is obtained using the modulo operator (n % 10), and this digit is added to sum. The number n is then divided by 10, effectively removing the last digit. This process continues until n becomes 0, at which point the function returns the total sum of the digits.

The main function prompts the user to enter an integer, reads the input into the number variable, and calls the sum function with number as the argument. The result is stored in the variable a, and the program prints the sum of the digits to the console. This example showcases a clear and concise way to calculate the sum of digits using basic arithmetic operations and a while loop.

5. Finding the Reverse of a Number

This section will guide you through the process of finding the reverse of a number using C++. Reversing a number is a common programming task that involves rearranging its digits in reverse order. This exercise is a valuable way to practice your skills in manipulating numbers and using loops effectively. Let's examine the code and understand its implementation.

#include <iostream>
using namespace std;

int ters(int n) {
    int t = 0;
    while (n > 0) {
        t = t * 10 + n % 10;
        n /= 10; }
    return t;
}

int main() {
    int a;
    cout << "Ededi daxil et: ";
    cin >> a;

    cout << "Tersi: " << ters(a);
    return 0;
}

Explanation:

The ters function takes an integer n as input and returns its reverse. The function initializes a variable t to 0, which will store the reversed number. The function then enters a while loop that continues as long as n is greater than 0. Inside the loop, the last digit of n is obtained using the modulo operator (n % 10). This digit is then added to the reversed number t after multiplying t by 10 (which shifts the existing digits to the left). The number n is then divided by 10, effectively removing the last digit. This process continues until n becomes 0, at which point the function returns the reversed number t.

The main function prompts the user to enter an integer, reads the input into the a variable, and calls the ters function with a as the argument. The reversed number is then printed to the console. This exercise is a great illustration of how to reverse a number by iteratively extracting its digits and constructing the reversed number.

6. Checking if a Number is Prime

In this section, we'll explore how to determine whether a given number is prime or not using C++. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. This exercise is fundamental in number theory and provides a practical application of loops and conditional statements in programming. Let's delve into the code and its explanation.

#include <iostream>
using namespace std;

bool sade(int n) {
    
    for (int i = 2; i < n; i++)
        if (n % i == 0) return false;
    return true;
}

int main() {
    int a;
    cout << "Ededi daxil et: ";
    cin >> a;

    if (sade(a))
       cout << "Sadedir";
    else 
       cout << "Sade deyil";

    return 0;
}

Explanation:

The sade function checks if a given integer n is a prime number. It iterates through numbers from 2 to n - 1 using a for loop. For each number i, it checks if n is divisible by i using the modulo operator (n % i == 0). If n is divisible by any i, the function immediately returns false, indicating that n is not prime. If the loop completes without finding any divisors, the function returns true, indicating that n is prime.

The main function prompts the user to enter an integer, reads the input into the a variable, and calls the sade function with a as the argument. It then prints a message to the console indicating whether the entered number is prime or not. This exercise effectively demonstrates how to check for primality using a loop and conditional statements, a crucial skill in computational number theory.

7. Displaying the Larger of Two Numbers

This section focuses on writing a C++ function to determine and display the larger of two given numbers. This is a basic yet essential programming task that involves conditional statements. It’s a fundamental building block for more complex algorithms and decision-making processes in programs. Let's break down the code and see how it works.

#include <iostream>
using namespace std;

int boyuk(int a, int b) {
    if (a > b) return a;
    return b;
}

int main() {
    int x, y;
    cout << "Iki eded daxil edin:";
    cin >> x >> y;

    cout << "Boyuk eded: " << boyuk(x, y);

    return 0;
}

Explanation:

The boyuk function takes two integers, a and b, as input and returns the larger of the two. The function uses an if statement to check if a is greater than b. If it is, the function returns a. Otherwise, it returns b. This simple conditional check is an efficient way to find the larger number.

The main function prompts the user to enter two integers, reads the inputs into the x and y variables, and calls the boyuk function with x and y as arguments. The result, which is the larger of the two numbers, is then printed to the console. This exercise provides a straightforward example of using conditional statements to make decisions in C++ code.

8. Determining if a Number is Positive, Negative, or Zero

Here, we'll explore a C++ function that checks whether a given number is positive, negative, or zero. This exercise is a classic example of using conditional statements to handle different cases based on the value of a variable. It’s a fundamental skill in programming, as it allows programs to respond differently to various inputs. Let's examine the code and its explanation.

#include <iostream>
using namespace std;

void yoxla(int n) {
    if (n > 0)
        cout << "Musbetdir";
    else if (n < 0)
        cout << "Menfidir";
    else
        cout << "Sifirdir";
}

int main() {
    int a;
    cout << "Ededi daxil et: ";
    cin >> a;

    yoxla(a);

    return 0;
}

Explanation:

The yoxla function takes an integer n as input and determines whether it is positive, negative, or zero. The function uses a series of if-else if-else statements to check the value of n. If n is greater than 0, it prints "Musbetdir" (which means "Positive" in Azerbaijani). If n is less than 0, it prints "Menfidir" (which means "Negative" in Azerbaijani). Otherwise, if n is neither greater nor less than 0, it must be 0, and the function prints "Sifirdir" (which means "Zero" in Azerbaijani).

The main function prompts the user to enter an integer, reads the input into the a variable, and calls the yoxla function with a as the argument. This exercise clearly demonstrates how to use conditional statements to handle different scenarios based on the input value, a crucial skill in any programming language.

9. Calculating the Square and Cube of a Number

In this section, we'll focus on writing a C++ program to calculate the square and cube of a number provided by the user. This is a basic yet important exercise that reinforces understanding of arithmetic operations and function usage. Calculating powers of numbers is a common task in various fields, including mathematics, physics, and computer graphics. Let's explore the code and its functionality.

#include <iostream>
using namespace std;

int kvadrat(int n) {
    return n * n;
}

int kub(int n) {
    return n * n * n;
}

int main() {
    int a;
    cout << "Ededi daxil et: ";
    cin >> a;

    cout << "Kvadrati: " << kvadrat(a) << endl;
    cout << "Kubu: " << kub(a) << endl;

    return 0;
}

Explanation:

The kvadrat function takes an integer n as input and returns its square (n * n). The kub function takes an integer n as input and returns its cube (n * n * n). These functions demonstrate a straightforward way to calculate powers of numbers using basic arithmetic operations.

The main function prompts the user to enter an integer, reads the input into the a variable, and calls both the kvadrat and kub functions with a as the argument. The results, which are the square and cube of the input number, are then printed to the console. This exercise provides a clear example of how to define and use functions to perform specific calculations, making the code modular and easier to understand.

10. Finding the Average of Three Numbers

This section guides you through writing a C++ program to calculate the average of three numbers. This is a fundamental programming task that involves basic arithmetic operations and function usage. Calculating the average is a common operation in data analysis, statistics, and various other applications. Let's examine the code and understand its implementation.

#include <iostream>
using namespace std;

int orta(int a, int b, int c) {
    return (a + b + c) / 3;  
}

int main() {
    int x, y, z;
    cout << "Uc ededi daxil et: ";
    cin >> x >> y >> z;

    cout << "Ededlerin ortasi: " << orta(x, y, z);

    return 0;
}

Explanation:

The orta function takes three integers, a, b, and c, as input and returns their average. The average is calculated by summing the three numbers and dividing the result by 3. This function provides a simple and efficient way to calculate the average of three numbers.

The main function prompts the user to enter three integers, reads the inputs into the x, y, and z variables, and calls the orta function with x, y, and z as arguments. The result, which is the average of the three numbers, is then printed to the console. This exercise is a clear illustration of how to define and use functions to perform specific calculations, making the code organized and easy to maintain.

Conclusion

Congratulations on completing this guide to Level 5 C++ function exercises! By working through these problems, you've strengthened your understanding of C++ functions, loops, conditional statements, and basic arithmetic operations. These skills are essential for any programmer, and mastering them will set you on the path to more advanced programming concepts and projects.

For further learning and practice, you can explore more C++ exercises and resources on websites like C++ Programming. Keep practicing and happy coding!