Showing posts with label Conditional statement. Show all posts
Showing posts with label Conditional statement. Show all posts

3 Numbers in ascending and descending order in C++

In this tutorial, we will solve two exercises from our list of conditional statements tests.

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

3 numbers in ascending order

We will store the numbers in the num1, num2 and num3 variables, and we will also use a temporary variable, an auxiliary, temp.

The idea is this: we want to put the largest value entered in the num1 variable. The second largest value in variable num2 and the smallest in num3.

For this, let's make three comparisons:

  1. Compare num1 with num2, if num2 is greater, we invert the values. After this first test, we guarantee that the value contained in num1 is greater than num2.
  2. Compare num1 with num3, if num3 is greater, we invert the values. After this second test, we guarantee that the value contained in num1 is greater than num2 and now greater than num3.
  3. Now we have num2 and num3, if num3 is greater, we must invert the values, so we have the value contained in num2 greater than num3.

To do the value inversions, we will use the tutorial:
How to change the value of two variables

Our code is:
#include <iostream>
using namespace std;

int main()
{
    int num1, num2, num3, temp;

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

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

    cout << "Number 3: ";
    cin >> num3;

    if(num2 > num1){
        temp = num1;
        num1 = num2;
        num2 = temp;
    }

    if(num3 > num1){
        temp = num1;
        num1 = num3;
        num3 = temp;
    }

    if(num3 > num2){
        temp = num2;
        num2 = num3;
        num3 = temp;
    }

    cout <<num1<<" >= "<<num2<<" >= "<<num3<<endl;
}

3 numbers in descending order

The logic is the same as above, we just want num1 to have the smallest value, num2 the second smallest value and num3 the greater value.

Our code is:




#include <iostream>
using namespace std;

int main()
{
    int num1, num2, num3, temp;

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

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

    cout << "Number 3: ";
    cin >> num3;

    if(num2 < num1){
        temp = num1;
        num1 = num2;
        num2 = temp;
    }

    if(num3 < num1){
        temp = num1;
        num1 = num3;
        num3 = temp;
    }

    if(num3 < num2){
        temp = num2;
        num2 = num3;
        num3 = temp;
    }

    cout <<num1<<" <= "<<num2<<" <= "<<num3<<endl;
}

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++

C++ Logical Operators: AND (&&), OR (||) and NOT (!)

In this tutorial of our C++ course, we will learn three more operators, called logical operators, that will allow us to do more complex and interesting conditional tests. They are:

  • && - AND 
  • || - OR
  • ! - NOT

Logical Operator AND: &&

The && operator serves to merge two logical expressions into one, like this:

  • expression1 && expression2

The result of this expression is true only if expression1 and expression2 are true.
If either one of them is false, the general expression becomes false as well.

The truth table of the && operator is:

Logical operators in C++

For example, for you to donate blood, there must be two conditions:
  • Be in legal age
  • Not have diseases

That is, for pain you need to be adult AND ALSO not have diseases:
  • adulthood && have no diseases

If any of these conditions are not true, you cannot donate blood.
Let's redo the program that says whether you must vote or not.

To be mandatory, it must satisfy two conditions:
  1. 21 years or older
  2. Under 65

That is, you must be 21 years old AND (AND) must be under 65 years old.
Our C++ code looks like this:

#include <iostream>
using namespace std;

int main()
{
    int age;

    cout <<"Your age: ";
    cin >> age;


    if( age>=21 && age<65 )
        cout << "Required to vote.";
    else
        cout << "Optional vote";


    return 0;
}

See that it was much more cleaner code, because we made two conditional tests at once within the IF.
If the person is under 21, the first expression will be false and the entire test will be false, going to ELSE.
If it is 65 or older, the second expression is already false, leaving the IF result false as well, going to ELSE.
In both cases, voting is optional.


Logical Operator OR: ||

The logical operator || (OR) joins two expressions like this:

  • expression1 || expression2

It returns true if any of the expressions are true.
That is, it only returns false if both are false. Check out this operator's truth table:

Truth table in C++

For example, if on a highway the maximum speed is 80 km/h, walking above and below half (40 km/h ) will give you a traffic ticket. Lets test:

  • speed> 80 || speed <40


That is: if the speed is greater than 80 km/h OR is below 40 km/h, the driver will be fined. If any of the expressions are true, the entire test is true.

Here's a program that takes the speed of a car and tells you whether it will generate a ticket or not:
#include <iostream>
using namespace std;

int main()
{
    int speed;

    cout <<"Speed: ";
    cin >> speed;


    if( speed>80 || speed<40 )
        cout << "You'll be fined.";
    else
        cout << "That's ok.";


    return 0;
}
The IF detects if you are going to get a fine, that is, not to get it needs to fall into ELSE, and only falls into ELSE if both expressions are false, so you are neither above 80 nor below 40, so you are between 40 and 80, which is the correct one. Did you get it? OR one thing OR another.

Logical Operator NOT: !

Finally, we have the negation operator.
It turns what is false into true, and what is true into false.

See his truth table:
Truth Tablet NOT Operator
That is:

  • !true is the same as false
  • !false is the same as true


Redoing the first code:
#include <iostream>
using namespace std;

int main()
{
    int age;

    cout <<"Your age: ";
    cin >> age;


    if( !(age>=21 && age<65) )
        cout << "Optional vote.";
    else
        cout << "Required to vote";


    return 0;
}
Redoing the second code:
#include <iostream>
using namespace std;

int main()
{
    int speed;

    cout <<"Speed: ";
    cin >> speed;


    if( !(speed>80 || speed<40) )
        cout << "Thats ok.";
    else
        cout << "You'll be fined.";


    return 0;
}
It may seem more complicated or the same thing, in fact it is the same thing, but often it will be more logical and it will make more sense to use the NOT operator in some conditional statements in C++. We will see this a few times over the our C ++ course.

The precedence of operators between them is from top to bottom:
!
&&
||

Logical Operators Exercise

In the last tutorial on nested IF and ELSEs, we posed a question about converting a numeric note to A, B, C ... but there is a bug there.

What if the user types less than 0 or more than 10?

It is a mistake. Arrange the program using the logical operator || if you type notes below 0 or above 10.

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;
}

The IF and ELSE Statement in C++

In this tutorial of our C ++ Online Course, we will teach you how to use the IF ELSE statement, without doubt one of the most important programming commands.

IF and ELSE Statement from C++

In the last tutorial, we learned how to use the IF conditional statement test, and saw that it does a test (huh, swear?), And if the result is TRUE, it executes a specific block of code. And if it is FALSE, it does not execute, it simply skips the IF.

Well, there's a problem there ... if it's TRUE, do something ... would be interesting if you did something else if it was FALSE, would you agree? This is where the ELSE command comes in.

The IF ELSE duo has the following syntax:
if (test){
   // Code in case
   // the test be TRUE
}
else {
   // Code in case
   // the test be FALSE
}
See I said duo. ELSE only exists if it has an IF.
IF may come alone, as we saw in the previous tutorial, but ELSE only comes with IF and always after it, as shown in the scope of this command.

Let's practice?

IF and ELSE Example

You were hired to make a program for a concert hall. In a certain piece of code, you will ask the age of the customer. If you are of legal age (21 years or older), please let him know that he can buy the ticket. If the customer have less, your program should state that he cannot enter the house.

First, we ask and store the age of the user in the integer variable age.
Now let's test if it is greater than or equal to 21.

If so, it falls in IF and it is larger.
If not, he drops to ELSE and we warn him that he cannot enter the place.

See how our code looked:
#include <iostream>
using namespace std;

int main()
{
    int age;

    cout << "Your age: ";
    cin >> age;

    if (age>=21){
        cout << "Ok, you can buy tickets!" << endl;
    } 
    else {
        cout << "You're underage, can't come in!" << endl;
    }

    return 0;
}
Can you rewrite the above program using the relational operator > instead of >=?

How to use IF and ELSE

Your teacher hired you to create a program that gets the student's grade. If it is 7.0 or higher, it has been approved. Otherwise, it is failed.

Here, no mystery, isn't it?
Only make conditional test greater than or equal to 7:
#include <iostream>
using namespace std;

int main()
{
    float grade;

    cout << "Your grade: ";
    cin >> grade;

    if (grade>=7)
        cout << "You are approved." << endl;
    else
        cout << "Damn, you failed." << endl;

    return 0;
}
See that we do not use the braces. In this case it is ok, because after the IF command and after the ELSE, there is only a single code statement.

If inside your IF or ELSE you have more than one line of code to run, enclose everything in braces, ok?

Using IF and ELSE in C ++

Write a program that asks a person's salary. If it is greater than $ 3,000, you have to pay 20% tax. If it is smaller, it has to pay 15%. Display the amount of tax the person has to pay.

We will store the salary in the sal variable and the tax the value of the tax.
Our code looks like this:
#include <iostream>
using namespace std;

int main()
{
    float sal, tax;

    cout << "Your paycheck ";
    cin >> sal;

    if (sal > 3000){
        tax = 0.20;
        cout << "Tax to pay: $ " << tax*sal <<endl;
    }
    else{
        tax = 0.15;
        cout << "Tax to pay: $ " << tax*sal <<endl;
    }
    return 0;
}
First, we test if the salary is greater than 3,000.
If so, the rate will be 20%. Otherwise it will be 15%.

Then we just calculate the amount of tax due.
Very simple, no?

Can you shorten the previous code? Show in the comments.

The IF conditional statement in C++

In this C ++ tutorial, we will learn how to use the IF conditional statement.
This will make our programs more flexible and dynamic.

Making decisions in C++

So far, all our codes have been purely sequential.
That is, they ran from top to bottom in the main function, executing line by line, command by command, and always like this.

If we run our programs 1 million times, they do the same 1 million times.
But is this what happens in everyday programs?

When you click one thing, you open one thing, if you click another, something else opens.
If you type a command, something happens. If you type another, something else happens.

That is, what your computer will do depends on what you do, it needs to do some testing before making what decision it should make.

Let's learn how to make these decisions now using the if conditional statement.

The IF command in C++

The structure of the IF command is very simple and easy to understand, see:
if ( conditional_statement ){
  // code
  // code
  // code
}
We start with the if statement, then open parentheses, and inside it must have some boolean value (1 or 0, true or false), in which case we usually do some relational operation (comparison test), then some code in braces .

The operation is quite simple: the if statement will analyze what's inside the parentheses.

If what is there is true, it executes the code in braces.
If what's inside is false, it does nothing, if is skipped, as if it didn't exist.

So read: if true, then do it.

How to use IF in C++

The program below has a conditional statement:
2 > 1

If this test is true, cout inside the IF is performed:
#include <iostream>
using namespace std;

int main()
{
    if( 2 > 1){
        cout << "Well, 2 is greather than 1";
    }
    return 0;
}
Obviously true, so the message always appears on the screen.
Now test with 2 <1

What happened?

Usage example of IF

Make a program that asks the user for their age and let them know if they are older.

A person is older if they are 18 or older, so our code looks like this:
#include <iostream>
using namespace std;

int main()
{
    int age;

    cout << "What's your age: ";
    cin >> age;

    if( age >= 21){
        cout << "You're adulthood";
    }

    return 0;
}
Can you solve this exercise using the > operator instead of >=?

IF Usage Example

Ask the user for a grade, and if it is less than 6, say that he failed the test.

See how the code looks:
#include <iostream>
using namespace std;

int main()
{
    float grade;

    cout << "Your grade: ";
    cin >> grade;

    if( grade < 6)
        cout << "Failed";

    return 0;
}
Note that we do not use braces, this is because the IF code is composed of only one instruction line. In such cases, you do not need to enclose it in braces.

But if the statement within the IF is larger, use braces.

See how C ++ is a strict teacher, I put the grade 5.99999 and yet he disapproved:
IF and ELSE in C++ tutorial


Using IF in C++

Make a program that asks the user for two numbers, and tell them if they are the same.
#include <iostream>
using namespace std;

int main()
{
    float num1, num2;

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

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

    if( num1 == num2)
        cout << "Equal!";

    return 0;
}
Pretty simple, isn't it?

Note that if you enter different numbers, IF receives the false result on the conditional statement and does not execute your code.

That is, nothing happens, the program simply skips the IF.

Exercise

Write a program that prompts the user for a numeric password and displays an error message if he ERRORS the password. The password is 2112.

Post your solution in the comments.