Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
C++ Fundamentals

You're reading from   C++ Fundamentals Hit the ground running with C++, the language that supports tech giants globally

Arrow left icon
Product type Paperback
Published in Mar 2019
Publisher
ISBN-13 9781789801491
Length 350 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
 Mallia Mallia
Author Profile Icon Mallia
Mallia
 Zoffoli Zoffoli
Author Profile Icon Zoffoli
Zoffoli
Arrow right icon
View More author details
Toc

Table of Contents (8) Chapters Close

About the Book 1. Getting Started FREE CHAPTER 2. Functions 3. Classes 4. Generic Programming and Templates 5. Standard Library Containers and Algorithms 6. Object-Oriented Programming 1. Appendix

Lesson 2: Functions

Activity 3: Calculating if a Person is Eligible to Vote or Not

  1. Include the header file in the program to print the output as shown here:

    #include <iostream>

  2. Now, create a function named byreference_age_in_5_years and the if loop with the following condition to print the message:

    void byreference_age_in_5_years(int& age) {

      if (age >= 18) {

        std::cout << “Congratulations! You are eligible to vote for your nation.” << std::endl;

        return;

  3. Add the else block to provide another condition if the age of the user is less than 18 years:

      } else{

        int reqAge = 18;

        int yearsToGo = reqAge-age;

        std::cout << “No worries, just “<< yearsToGo << “ more years to go.” << std::endl;

      }

    }

  4. In the main function, create a variable of type integer and pass it as a reference in the byreference_age_in_5_years function as shown:

    int main() {

        int age;

        std::cout << “Please enter your age:”;

        std::cin >> age;

        byreference_age_in_5_years(age);

    }

Activity 4: Apply the Understanding of Passing by Reference or Value in Functions

  1. After adding all the required header files, create the first function of type integer as shown here:

    int sum(int a, int b)

    {

      return a + b

    }

    Take by value, return by value, since the types are small in memory and there is no reason to use references.

  2. The second function should be written as follows:

    int& getMaxOf(std::array<int, 10>& array1, std::array<int, 10>& array2, int index) {

      if (array1[index] >= array2[index]) {

        return array1[index];

      } else {

        return array2[index];

      }

    }

Activity 5: Organizing Functions in Namespaces

  1. Include the required header file and namespace to print the required output:

    #include <iostream>

    using namespace std;

  2. Now, create a namespace named LamborghiniCar with the following output function:

    namespace LamborghiniCar

    {

      int output(){

        std::cout << “Congratulations! You deserve the Lamborghini.” << std::endl;

        return NULL;

      }

    }

  3. Create another namespace named PorscheCar and add an output function as shown:

    namespace PorscheCar

    {

      int output(){

        std::cout << “Congratulations! You deserve the Porsche.” << std::endl;

        return NULL;

      }

    }

In the main function, create a variable named magicNumber of type integer to accept the input from the user:

int main()

{

  int magicNumber;

  std::cout << “Select a magic number (1 or 2) to win your dream car: “;

  std::cin >> magicNumber;

  1. Add the following conditional ifelse-ifelse statement to complete the program:

      if (magicNumber == 1){

        std::cout << LamborghiniCar::output() << std::endl;

      } else if(magicNumber == 2){

        std::cout << PorscheCar::output() << std::endl;

      }else{

        std::cout << “Please type the correct magic number.” << std::endl;

      }

    }

Activity 6: Writing a Math Library for use in a 3D Game

  1. Add the required header files at the start of the program (mathlib.h file is provided):

    #include <mathlib.h>

    #include <array>

    #include <iostream>

  2. Create a global const variable of type float as shown here:

    const float ENEMY_VIEW_RADIUS_METERS = 5;

  3. In the main function, create two arrays of type float and assign the following values:

    int main() {

        std::array<float, 3> enemy1_location = {2, 2 ,0};

        std::array<float, 3> enemy2_location = {2, 4 ,0};

  4. Now, create a variable named enemy_distance of type float and use the distance function to assign the value after calculating it:

        float enemy_distance = johnny::mathlib::distance(enemy1_location, enemy2_location);

        float distance_from_center = johnny::mathlib::distance(enemy1_location);

  5. Using the circumference function of mathlib.h, calculate and assign the enemy visual radius to view_circumference_for_enemy of type float:

        using johnny::mathlib::circumference;

        float view_circumference_for_enemy = circumference(ENEMY_VIEW_RADIUS_METERS);

  6. Create a variable named total_distance of type float and assign the distance difference between the two enemies as shown in the following code:

        float total_distance = johnny::mathlib::total_walking_distance({

            enemy1_location,

            {2, 3, 0}, // y += 1

            {2, 3, 3}, // z += 3

            {5, 3, 3}, // x += 3

            {8, 3, 3}, // x += 3

            {8, 3, 2}, // z -= 1

            {2, 3, 2}, // x -= 6

            {2, 3, 1}, // z -= 1

            {2, 3, 0}, // z -= 1

            enemy2_location

        });

  7. Print the output using the following print statement:

        std::cout << “The two enemies are “ << enemy_distance << “m apart and can see for a circumference of “

                  << view_circumference_for_enemy << “m. To go to from one to the other they need to walk “

                  << total_distance << “m.”;

    }

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime
Visually different images