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

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

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