Showing posts with label Commented code. Show all posts
Showing posts with label Commented code. Show all posts

List of C++ Function Exercises (Resolved and Commented)

We have reached the end of another section of our C++ course, about functions.
In the exercises below, you should use all your knowledge learned so far, such as the basics, loops, loopings, conditional tests and, of course, function.

Use and use again the functions. Create many functions.
Each function must do a single thing, in the simplest and most direct way possible.

Make them easily coupled, that is, you should receive and return information whenever possible. This allows you to use your function codes later.

Remember: a large program is nothing more than a series of small programs.
Your functions should be these little programs, making specific functionalities, ok?

Function Exercises in C++

01. Create a program that receives two smaller sides of a right triangle and a function returns the value of the hypotenuse.

02. Create a program that receives the three sides of a triangle, passes these values ​​to a function that says whether that triangle exists or not (due to the condition of the triangle's existence, each side must be greater than the subtraction module of the other two sides and must be less than the sum of the other two sides)

03. Make a program that asks the user for a positive integer 'n' and print a square of side 'n' filled with hashtags. For example, for n = 4, it should appear on the screen:

####
####
####
####

04. Program a software that receives three numbers, stops for a function and it returns the largest one. Make another function that receives the same numbers and returns the smallest one.


05. A number is said to be perfect when it is equal to the sum of its divisors.
For example, six is ​​perfect, because: 6 = 1 + 2 + 3
Programs a software that asks the user for a number and tells them if it is perfect or not.

06. Create software that receives a number from the user, passes that value to a function and it returns that number written in reverse. For example, you gave the value 1234, so it will return 4321. Tip: first, create a function that counts how many digits a number has.

07. Make a program to toss a coin. When we call a function, it must return heads or tails. In another function, make 'n' coin tosses, 'n' is the amount the user wants, and show the percentage of times he has heads and tails. If you flip the coin 10, 100, 1000, a million times ... what tends to happen?

08. Create data in C++. Roll the dice: that is, a function must draw a random number from 1 to 6. Now, make the previous die roll 100 times, a thousand times and 1 million times. Each time it runs, you must store the value it provided, at the end, you show how many times each number was drawn. Does it match the results of the statistic?

09. Create an odds and even game. You must choose 0 for even or 1 for odd, then provide a number. The computer generates a number from 0 to 10, adds the values ​​and says who won, besides showing the score and asking if you want to play another round.
How to program odds or even in C++

10. Like the odd or even game, create the Rock, Paper or Scissors game, in C ++.

11. Create a game where the computer draws a number from 1 to 10, and you try to guess what it is.

12.  Are we really going to make a cool and interesting game? Make the computer draw a number from 1 to 100. Each time you kick, it should tell you if you kicked below the real value, above or if you got it right. At the end, it tells you the number of attempts you had and whether or not you hit the record. Oh, at the end of each round, the program asks if you want to play again or not, displaying the current record.
Guess the number

Equilateral Triangle, Isosceles or Scalene? C++ Exercise

In this C++ tutorial, we will solve the following question from our list of exercises:

  • 10. Make a program that takes all three sides of a triangle and tells you if it is equilateral, isosceles, or scalene.

C++ Triangle Types

There are three types of triangle:

  1. Equilateral: all sides are equal
  2. Isosceles: Only Two Sides Are Equal
  3. Scalene: All Sides Are Different


So all we have to do is ask for three sides of a triangle, and test whether the sides are all the same, or have two equal or if it's all different.

One way to do this is by testing if it's all the same in an IF, to know if it's equilateral:

  • if ((a == b) && (b == c))

Then if they are all different, to know if it is scalene:

  • if ((a! = b) && (a! = c) && (b! = c))


If it is none of the above, it is because it is isosceles.

Our code looks like this:
#include <iostream>
using namespace std;

int main()
{
    int a, b, c;

    cout << "Side a: ";
    cin >> a;

    cout << "Side b: ";
    cin >> b;

    cout << "Side c: ";
    cin >> c;

    if( (a==b) && (b==c) )
        cout<<"Equilateral\n";
    else if( (a!=b) && (a!=c) && (b!=c))
        cout<<"Scalene\n";
    else
        cout<<"Isosceles\n";

}

Equilateral, Isosceles or Scalene?

An interesting thing about programming is that code is a kind of fingerprint.
Each one does their own thing, each one has their own methods, lines of thought and creativity.

Sometimes it is common to make big code, ugly and confusing.
Then we see someone using half the lines we use, doing something far more beautiful and comprehensive.

That's why it's important to study through other people's books, websites, tutorials, and codes to 'pick up' on others' reasoning. Never miss this custom, okay?

Let's go for one more solution.
First, let's test if there are two equal sides:

  • (a == b) || (a == c) || (b == c)


If you have, either one: either equilateral or just isosceles.
So we test if the three sides are equal:

  • (a == b) && (b == c)

If so, we say it is equilateral. Otherwise it falls into the nested ELSE and we say it is isosceles.
If it does not have at least two equal sides, it is scalene.

Look:

#include <iostream>
using namespace std;

int main()
{
    int a, b, c;

    cout << "Side a: ";
    cin >> a;

    cout << "Side b: ";
    cin >> b;

    cout << "Side c: ";
    cin >> c;

    if( (a==b) || (a==c) || (b==c))
        if( (a==b)&&(b==c) )
            cout<<"Equilateral\n";
        else
            cout<<"Isosceles\n";
    else
        cout<<"Scalene\n";

}

C++ hacker test


A hacker is the one who finds loopholes, errors, code problems.
There is a problem with the code above: the conditions of existence of a triangle.

It's not just entering three values and we have a triangle, no.

Research the conditions of existence of a triangle, and before deciding whether it is equilateral, isosceles or scalene, see if the triangle can even exist.

Post your code in the comments.

How many days does the month have - C++ Exercise

In this tutorial, we will solve the following exercise from our list:
  • 08. Using switch case concepts, make a program that asks the user the month (number 1 through 12), and tells you how many days that month has. February has 28 days (not leap year).

How many days are there in the month

Come on.
Months with 28 days: 2Months with 30 days: 4, 6, 9 and 11Months with 31 days: 1, 3, 5, 7, 8, 10 and 12

Let's do accumulating cases so you can better fix this important switch technique.
The days variable starts with 0.

The logic is as follows ... every month has 28 days or more. So we want case 2 to always run so it will be down there.

There we will add the value 28 to the days variable.
Okay, any month you enter will be at 28 days, because we will not use break in cases, to accumulate.
  • days = days + 28;

The middle cases are the months 4, 6, 9 and 11 have 30 days.
As we will added 28 days, we only have to add 2 more days to stay 30, in these cases:
  • days = days + 2;

You see: if you type 2, it falls only in case 2, which puts 28 in the days variable. If you type 4, 6, 9 or 11, it falls into those cases that add up to 2 and then falls into the case that adds up to 28 days, totaling 30 days.

So if you type 1, 3, 5, 7, 8, 10, or 12, we should just add +1:
  • days = days + 1;
See how our code looked:

#include <iostream>
using namespace std;

int main()
{
    int days=0, month;

    cout << "Month number: ";
    cin >> month;

    switch(month)
    {
        case 1: case 3: case 5: case 7:
        case 8: case 10: case 12:
            days = days + 1;

        case 4: case 6:
        case 9: case 11:
            days = days + 2;

        case 2:
            days=days+28;
            break;
        default:
            cout <<"Invalid month"<<endl;
    }

    cout <<"Month "<<month<<" has "<<days<<" days.\n";
}

Can you understand? It is a very charming solution.

Leap Year solution



  • 09. Using switch case concepts, make a program that asks the user the month (number 1 through 12), and tells you how many days that month has, including whether it is a leap year or not.



Here, in addition to what is in the previous code, we have to ask the year to the user. If it is leap year, we should add 29 in case 2 to the days variable, if not, we keep adding only 28.


We do this with an IF ELSE statement internal to the switch case.
Here's how the code looks:
#include <iostream>
using namespace std;

int main()
{
    int days=0, month, year;

    cout << "Month number: ";
    cin >> month;

    cout << "Year: ";
    cin >> year;

    switch(month)
    {
        case 1: case 3: case 5: case 7:
        case 8: case 10: case 12:
            days = days + 1;

        case 4: case 6:
        case 9: case 11:
            days = days + 2;

        case 2:
            if( (year % 400 == 0) || ( (year % 4 == 0) && (year % 100 != 0) ) )
                days = days+29;
            else
                days = days+28;
            break;
        default:
            cout <<"Invalid month"<<endl;
    }

    cout <<"The month "<<month<<" has "<<days<<" days.\n";
}

Comparing Two Numbers in C++: Larger, Smaller, or Equal

Resolved, coded-out question from the C++ Conditional statements Exercises tutorial:

01. Make a program that asks for two numbers, and say which one is greater, witch is smaller or if they are equal.

How to compare two numbers in C++

Let's store the numbers in variables num1 and num2.
First, let's test if the first one is larger than the second, if it go in the first IF and says it in cout.

If not, fall into the ELSE.
In this ELSE, the second number is greater than the first, or can be equal.

We tested this with a new nested IF, to see if num2 is greater than num1, if so, we warn you.
If num1 is not greater than num2, or num2 is not greater than num1, then it falls into the nested ELSE and we necessarily have the numbers to be equal.

See how our code looked:




#include <iostream>
using namespace std;

int main()
{
    int num1, num2;

    cout << "Number 1: ";
    cin >> num1;
    cout << "Number 2: ";
    cin >> num2;

    if(num1>num2)
        cout <<num1<<" is greater than "<<num2<<endl;
    else
        if(num2>num1)
            cout <<num2<<" is greater than "<<num1<<endl;
        else
            cout << "Equals"<<endl;
    return 0;
}

C++ Conditional Statements Exercises

Guys, let's wrap up a section of our C ++ course once again.
Congratulations if you arrived here. Now let's practice our knowledge by doing some exercises.

And remember, try hard, but really, really hard.
Not of? Think some more. Then more, take a walk, cool your head, and try again.

Problem solving is synonymous with being a programmer, so try to solve the exercises below using your basic knowledge of C ++ and conditional testing.

C++ conditional testing problems

01. Make a program that asks for two numbers, and say which one is larger or if they are equal.
How to compare two numbers in C++

02. Write a program that tells you whether a received number is positive or negative.

03. Make a program that asks for two integers and store in two variables. Then change the value of the variables and display on screen
Swapping two numbers

04. Make a program that asks for 3 numbers and places them in ascending order.

05. Make a program that asks for 3 numbers and puts them in descending order.
3 numbers in ascending and descending order

06. Program software that receives the user's X and Y coordinates, and tell which quadrant the point is in.

07. Make a simple calculator program that asks the user for two numbers, then displays a menu where he will choose which operation to perform. The operation and output must be in a switch case.

08. Using switch case concepts, make a program that asks the user the month (number 1 through 12), and tells you how many days that month has. February is 28 days old (not leap).

09. Using switch case concepts, make a program that asks the user the month (number 1 through 12), and tells you how many days that month has, including whether it is a leap year or not.
How many days a month has

10. Make a program that takes all three sides of a triangle and tells you if it is equilateral, isosceles, or scalene.
Types of triangle

11. Make a program that calculates the roots of a quadratic equation in the form ax² + bx + c. The program should request the values ​​of a, b and c and make the calculations, informing the user in the following situations:

    If the user enters the value of A equal to zero, the equation is not of the second degree and the program should not ask the other values, being closed;
    If the calculated delta is negative, the equation has no real roots. Inform the user and quit the program;
    If the calculated delta equals zero the equation has only one real root; inform it to the user;
    If delta is positive, the equation has two real roots; inform them to the user;

PS: Use cmath library (#include <cmath>) and sqrt(x) function to calculate the square root of x.

How to solve quadratic equation in C++

Odd or Even in C++ - How to Find Out (and Other Multiples)

C++ tutorialIn this tutorial from our C++ e-book, we will learn how to find out if a given number is odd or even (as well as how to use other multiples than 2).

Odd or Even in C ++

Now that we've learned about the IF/ELSE conditional statement test as well as the mathematical operators, let's learn how to use the remainder division operator (%) to check and find out if a given number is odd or even.

Even numbers are actually numbers that are multiples of 2.
That is, they are formed by the number 2 multiplied by any other integer.

See some examples:
2x1 = 2
2 x 2 = 4
2x3 = 6
2 x 4 = 8
...

That is, to know if a number stores a pair value, just test if its remainder of division by 2 is equal to 0. The conditional test that represents this is:
  • (num % 2 == 0)

If such an operation returns true, it is even.
Otherwise (ELSE), it is because the number is odd (it is always odd or even).

Here's what our C ++ code looks like from a program that asks the user for an integer and says whether it's even or odd:
#include <iostream>
using namespace std;

int main()
{
    int num;

    cout << "Type a number: ";
    cin >> num;

    if (num%2==0)
        cout <<"It's even"<<endl;
    else
        cout <<"It's odd"<<endl;
    return 0;
}

Multiple of 3

As we said, the even number is nothing more than a multiple of 2.
There are also multiples of 3, 4, 5, ...

For example, multiple numbers of 3 are:
3x1 = 3
3x2 = 6
3x3 = 9
3x4 = 12

To find out if a given number is a multiple of 3, just check the rest of the division of any number by 3, here's how our code looks:
#include <iostream>
using namespace std;

int main()
{
    int num;

    cout << "Type a number: ";
    cin >> num;

    if (num%3==0)
        cout <<"Multiple of 3"<<endl;
    else
        cout <<"Not a 3 multiple"<<endl;
    return 0;
}

Multiple numbers

Make a program that receives two integers: num1 and num2.
Then verify that num1 is a multiple of num2.

#include <iostream>
using namespace std;

int main()
{
    int num1, num2;

    cout << "First number : ";
    cin >> num1;

    cout << "Second number: ";
    cin >> num2;

    if (num1%num2==0)
        cout <<num1<<" is multiple of "<<num2<<endl;
    else
        cout <<num1<<" is not a multiple of "<<num2<<endl;
    return 0;
}