Showing posts with label ELSE. Show all posts
Showing posts with label ELSE. Show all posts

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

Nested IF and ELSE in C ++

In this tutorial from our C++ course, we will learn how to use a very important programming technique, which is nested IF ELSE within IF ELSE.

IF and ELSE within IF and ELSE

Let's explain the technique of nesting IF and ELSE through examples.

Create a C++ program that asks for two numbers, and says if they are the same or one is bigger than the other (showing who's who).

Come on, let's store the numbers in the variables: num1 and num2
The first test is if (num1 == num2) to see if they are the same.

If so, it warns and the program is over.
If not, we have two options:

  1. num1 is greater than num2
  2. num2 is greater than num1

That is, we have to do one more test within ELSE.

Let's insert the test inside:
if (num1> num2)

If true, it says that num1 is greater than num2.

What if it's fake?
Then it must fall into another ELSE, this second nested IF, understand?

Let's see how our code looks:
#include <iostream>
using namespace std;

int main()
{
    float num1, num2;

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

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

    if(num1==num2)
        cout <<"Equal" << endl;
    else
        if(num1 > num2)
            cout << num1 <<" greater than "<<num2 << endl;
        else
            cout << num2 <<" greater than"<<num1 << endl;

    return 0;
}
Note that we made an indentation, that is, we gave a spacing so that each else is in the same vertical as its respective if.

Nested IF and ELSE Example

You have been hired by a hospital to check if people can donate blood or not.
They can only donate if they are 18 or older and have no disease.
Make a C++ program that asks how old a person is and if he or she has a disease, then tells whether they can donate blood or not.

Let's go first to the code:
#include <iostream>
using namespace std;

int main()
{
    int age, dis;

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

    cout <<"Do you have any disease ?"<<endl;
    cout <<"1. Not" << endl;
    cout <<"2. Yes" << endl;
    cin >> dis;

    if( age>=18 ){
        if(dis==1)
            cout << "You can donate blood!";
        else
            cout << "You can't donate because is sick";
    }else{
        cout << "You must be 18 or older to donate blood";
    }

    return 0;
}
Well, let's go.
First we store the age in the age variable.
Then, the user must type 1 if he has no disease and 2 if he has, this answer will be stored in the dis variable.

Now the tests.
First, we check if you are 18 or older. If you do not have it, you will get ELSE and let them know you need to be 18 or older to donate.

If so, if you are 18 or older, we will check if it has no disease, ie if you entered 1.
If not, we advise that you can donate.
If he entered 2, he warns that sick people cannot donate blood.

Cool not?
Now a hacker test: run the program above and find some error.

IF and ELSE nested in C++

If you are under 16, you cannot vote. From 16 to 18 is optional. From 65 too.
From 18 to 65, voting is required. Make a C++ program that asks for the age of the user and tells them if they are required to vote, optional or not.

Well, let's go.
In the first IF we will soon put the 'guys' who are under 16, they can't vote.

If you are 16 or older, go to ELSE.
Within that ELSE, let's check if it's under 18 with an IF, if it says it is optional.

If it's not smaller, it's because it's 18 or older.
Let's test if you are under 65, if you are have to vote.

If you are no less, you fall in the last ELSE and the person is over 65, voting optionally.
See how our code looked:
#include <iostream>
using namespace std;

int main()
{
    int age;

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

    if(age < 16)
        cout << "Can't vote, too young." << endl;
    else
        if(age < 18)
            cout << "Optional vote." << endl;
        else
            if(age < 65)
                cout << "Is required to vote." << endl;
            else
                cout << "Optional vote" << endl;

    return 0;
}

The IF/ELSE IF Command

Create a program that asks for a student's grade on a test, ranging from 0.0 to 10.
If the grade is greater than or equal to 9, say that he took A.
If it is 8.0 through 8.9, say that this person took B.
If it goes from 7.0 to 7.9, say she took C.
If it goes from 6.0 to 6.9, say she took D.
If it is below 6.0, she took F.

The first test to make is to see if the grade is greater than or equal to 9.0, if it is, the first IF ends the execution of the program.
If not, go to ELSE.

Inside ELSE we need to test with a new IF if the value is greater than or equal to 8.0.
You see, it only falls in this internal IF if it is from 8.0 to 8.9, above that it would have fallen in the first IF.

If it is not, it will fall into another internal ELSE.
Within this ELSE, let's test (IF) if it's from 7.0 to 7.9

If not, we create another ELSE and an IF within it to know if it's from 6.0 to 6.9

Finally, if none of the above, is grade F.

Let's see how our code looked:
#include <iostream>
using namespace std;

int main()
{
    float grade;

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

    if(grade >= 9)
        cout << "A"<<endl;
    else
        if(grade >=8 )
            cout << "B"<<endl;
        else
            if(grade >=7 )
                cout << "C"<<endl;
            else
                if(grade >=6 )
                    cout << "D"<<endl;
                else
                    cout << "F"<<endl;

    return 0;
}
Note that C ++ code is 'going' to the right.
Imagine if you had 10 more conditions to test, what would our code look like?
A mess, isn't it?

Now if I take the same code and do this:
#include <iostream>
using namespace std;

int main()
{
    float grade;

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

    if(grade >= 9)
        cout << "A"<<endl;
    else if(grade >=8 )
        cout << "B"<<endl;
    else if(grade >=7 )
        cout << "C"<<endl;
    else if(grade >=6 )
        cout << "D"<<endl;
    else
        cout << "F"<<endl;

    return 0;
}
More readable, do you agree?
This is a good programming technique because it makes reading and understanding the code easier.

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.

Relational (comparison) operators in C ++:>, <,> =, <=, == and !=

In this tutorial of our C++ Course, we will learn what they are and how to use relational operators, also known as comparison operators, which are:
  • >    greater than
  • <    less than
  • >=  greater than or equal
  • <=  less than or equal
  • ==  equal
  • !=  different

How to compare things in C++

Although this tutorial is a bit boring and theoretical, it is necessary to better understand the use of the IF and ELSE conditional tests, which we will use in the next tutorials.

What we are going to do now is teach you how to perform the comparison operation, it is done like this:
  • operand1 operator operand1

That is, we will use two operands (data, such as numbers or characters) and one operator (in this case, a relational).

And this operation always returns one of the values:
  • TRUE (true or 1)
  • FALSE (false or 0)

Ever.
Relation operation is always a question that the answer is 1 or 0, true or false.
OK?

Equality operator in C++: ==

Well, let's go.
If we want to know if an x value is equal to a y, we do:
x == y

You see, it's: x == y
And no: x = y

Let's test if 1 equals 1 and then if 2, run the code below:
#include <iostream>
using namespace std;

int main()
{
    cout << (1 == 1) << endl;
    cout << (1 == 2) << endl;

    return 0;
}
The result was:
C++ free online course and tutorials
Actually, 1 equals 1 (1, TRUE, the result of the comparison).
And 1 is not equal to 2 (0, FALSE, the result of the comparison).

Not equal operator in C++: !=

Just as you have one operator that checks for equality, so has another that checks for non-equality.
If two values are different, the comparison operation with != will result in TRUE.

If they are equal, it results in FALSE.

Let's see in practice, compile and run:
#include <iostream>
using namespace std;

int main()
{
    cout << ('a' != 'b') << endl;

    return 0;
}
That is, the character 'a' is different from 'b'.
Now test if 'a' is different from 'A'.
IT'S ?

Greater than operator C++: >

If we want to test if an X value is greater than a Y value, we use the operator: >
X> Y

If X is larger, it returns TRUE (1).
If equal or less, it returns FALSE (0).

Greater than or equal operator in C++: >=

If we want to test if a value is greater than or equal, we use: >=
X >= Y

It returns 1 (true) if X is greater than or equal to Y, and 0 if X is smaller.

For example, to test if a person can already drive, drink, enter the motel ... we should do:
age >= 21

Lessa than and less than or egual to operators C++: < and <=

Similarly, there are the smaller and smaller operators equal.

To test if a person can donate blood, we must test:
age < 65

To find out who is exempt from tax returns, we should test:
value <= 28559.70

Beware of comparisons

A very serious mistake is to confuse:
x = y;

With:
x == y;


In the first case, it is an assignment.
Variable x is receiving the value of variable y.

In the second case is a comparison.
Always read comparison as a question: x is equal to y?

And when you ask C ++ things, it only gives you two answers: 1 or 0
So if you want to store the value of a comparison, declare a boolean, ok?

  • C++ exercise

Make a program that prompts the user for two values (can be a number or a character), then display all comparison operations, as in the example below:

C++ tutorial

Did you try?
Worked?

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

int main()
{
    int op1, op2;

    cout << "First value  : ";
    cin >> op1;

    cout << "Second value : ";
    cin >> op2;

    cout << op1 << " >  " << op2 <<" : "<<(op1>op2)<<endl;
    cout << op1 << " <  " << op2 <<" : "<<(op1<op2)<<endl;
    cout << op1 << " >= " << op2 <<" : "<<(op1>=op2)<<endl;
    cout << op1 << " <= " << op2 <<" : "<<(op1<=op2)<<endl;
    cout << op1 << " == " << op2 <<" : "<<(op1==op2)<<endl;
    cout << op1 << " != " << op2 <<" : "<<(op1!=op2)<<endl;
    return 0;
}
And yours?