Monday, September 20, 2010

Logical Operators: AND(&&) OR(||) NOT(!) in c++


Logical Operators: AND(&&) OR(||) NOT(!) in c++



To understand this chapter better, first go through relational operators. In a program, we often need to test more than one condition. To simplify this logical operators were introduced. In your school you might have learnt Boolean Algebra (Logic).


The three logical operators ( AND, OR and NOT ) are as follows:


1) AND (&&) : Returns true only if both operand are true.
2) OR (||) : Returns true if one of the operand is true.
3) NOT (!) : Converts false to true and true to false.

OperatorOperator's NameExampleResult
&&AND3>2 && 3>11(true)
&&AND3>2 && 3<10(false)
&&AND3<2 && 3<10(false)
||OR3>2 || 3>11(true)
||OR3>2 || 3<11(true)
||OR3<2 || 3<10(false)
!NOT!(3==2)1(true)
!NOT!(3==3)0(false)


/* A c++ program example that demonstrate the working of logical operators. */


// Program 1

#include <iostream>

using namespace std;

int main ()
{
    cout << "3 > 2 && 3 > 1: " << (3 > 2 && 3 > 1) << endl;
    cout << "3 > 2 && 3 < 1: " << (3 > 2 && 3 < 1) << endl;
    cout << "3 < 2 && 3 < 1: " << (3 < 2 && 3 < 1) << endl;
    cout << endl;
    cout << "3 > 2 || 3 > 1: " << (3 > 2 || 3 > 1) << endl;
    cout << "3 > 2 || 3 < 1: " << (3 > 2 || 3 < 1) << endl;
    cout << "3 < 2 || 3 < 1: " << (3 < 2 || 3 < 1) << endl;
    cout << endl;
    cout << "! (3 == 2): " << ( ! (3 == 2) ) << endl;
    cout << "! (3 == 3): " << ( ! (3 == 3) ) << endl;

    return 0;
}


In earlier chapter Selection Statement (if-else if-else), we were required to check two conditons: for username and password. If both username and password are correct then only "You are logged in!" message appears. We checked these two condition using nested if-else statement. However i told you at the end of that chapter that in the "Program 1" nesting can be avoided by using logical operator. Here we will rewrite the "Program 1" of Selection Statement (if-else if-else) using logical operator.

/* A c++ program example that uses a logical operator in selection statement if-else.*/


// Program 2

#include <iostream>
#include <string>

using namespace std;

const string userName = "computergeek";
const string passWord = "break_codes";

int main ()
{
    string name, pass;

    cout << "Username: ";
    cin >> name;

    cout << "Password: ";
    cin >> pass;

    if (name == userName && pass == passWord)
    {
        cout << "You are logged in!" << endl;
    }

    else
        cout << "Incorrect username or password." << endl;

    return 0;
}


/* A simple c++ program example that uses AND logical operator */


// Program 3

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second, third;

    cout << "Enter three integers." << endl;

    cout << "First "<< setw (3) << ": ";
    cin >> first;

    cout << "Second "<< setw (2) << ": ";
    cin >> second;

    cout << "Third "<< setw (3) << ": ";
    cin >> third;

    if (first > second && first > third)
        cout << "first is greater than second and third." << endl;

    else if (second > first && second > third)
        cout << "second is greater than first and third." << endl;

    else if (third > first && third > second)
        cout << "third is greater than first and second." << endl;

    else
        cout << "first, second and third are equal." << endl;

    return 0;
}

/* A simple c++ program example that uses OR logical operator*/


// Program 4

#include <iostream>

using namespace std;

int main ()
{
    char agree;

    cout << "Would you like to meet me (y/n): ";
    cin >> agree;

    if (agree == 'y' || agree == 'Y')
    {
        cout << "Your name: ";
        string name;
        cin >> name;
        cout << "Glad to see you, "+name << endl;
    }

    else if (agree == 'n' || agree == 'N')
        cout << "See you later!" << endl;

    else
        cout << "Please enter 'y' or 'n' for yes or no." << endl;

    return 0;
}


/* A simple c++ program example that uses NOT logical operator*/


// Program 5

#include <iostream>

using namespace std;

int main ()
{
    char agree;

    cout << "Would you like to meet me?" << endl;
    cout << "Press 'y' for yes and any other character for no: ";
    cin >> agree;

    if ( ! (agree == 'y' || agree == 'Y') )
    {
        cout << "See you later!" << endl;
    }

    else
    {
        cout << "Your name: ";
        string name;
        cin >> name;
        cout << "Glad to see you, "+name << "!" << endl;
    }

    return 0;
}

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.
Want to learn more? View List Of All Chapters

Tuesday, August 31, 2010

Nested if-else statements in c++

Nested if-else statements in c++



/*A c++ program example that takes input from user for username and password and then makes decision.*/


// Program 1

#include <iostream>
#include <string>

using namespace std;

const string userName = "computergeek";
const string passWord = "break_codes";


int main ()
{
    string name, pass;

    cout << "Username: ";
    cin >> name;

    cout << "Password: ";
    cin >> pass;

    if (name == userName)
    {
        if (pass == passWord)
            cout << "You are logged in!" << endl;
        else
            cout << "Incorrect username or password." << endl;
    }
    else
        cout << "Incorrect username or password." << endl;

    return 0;
}


/*A c++ program example that takes input from user for username and if username is correct then only asks for password and makes decision.*/


// Program 2

#include <iostream>
#include <string>

using namespace std;

const string userName = "computergeek";
const string passWord = "break_codes";

int main ()
{
    string name, pass;

    cout << "Username: ";
    cin >> name;

    if (name == userName)
    {
        cout << "Password: ";
        cin >> pass;

        if (pass == passWord)
            cout << "You are logged in!" << endl;
        else
            cout << "Incorrect password." << endl;
    }
    else
        cout << "Incorrect username." << endl;

    return 0;
}


Programming Advice & Explanation:


Whenever possible avoid nesting or deep nesting as it makes program difficult to read. We should program in a manner that it can be read and understood easily by us and other programmers. For example, in the "Program 1" the nesting can be avoided by using logical operator. However in "Program 2" the nesting is required as we want to take input for password only if username is correct.

In the next chapter we will learn about logical operators and will rewrite the "Program 1" using it.

Wednesday, August 11, 2010

Selection Statement (if-else if-else) in c++

Selection Statement (if-else if-else) in c++


To understand this chapter you should know about Comparison Operators which is explained in previous chapter. Selection statements are very important in programming because we make decisions using it.

/* A simple c++ program example to demonstrate the if statement. */


// Program 1

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "Enter two integers." << endl;

    cout << "First " << setw (3) << ": ";
    cin >> first;

    cout << "Second "<< setw (2) << ": ";
    cin >> second;

    if (first > second)
        cout << "first is greater than second." << endl;

    return 0;
}


/* A c++ program example to demonstrate if-else statements */


// Program 2

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "Enter two integers." << endl;

    cout << "First " << setw (3) << ": ";
    cin >> first;

    cout << "Second "<< setw (2) << ": ";
    cin >> second;

    if (first > second)
        cout << "first is greater than second." << endl;

    else
        cout << "first is less than or equal to second." << endl;

    return 0;
}


/* A c++ program example to demonstrate if-else if-else statements. */


// Program 3

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "Enter two integers." << endl;

    cout << "First " << setw (3) << ": ";
    cin >> first;

    cout << "Second "<< setw (2) << ": ";
    cin >> second;

    if (first > second)
        cout << "first is greater than second." << endl;

    else if (first < second)
        cout << "first is less than second" << endl;

    else
        cout << "first and second are equal." << endl;

    return 0;
}


Note: All the above three programs satisfies the condition that if first value
is greater then display the message "first is greater than second".

Question: When to use if, if-else and if-else if-else ?
Answer: It depends upon your program. The number of possibilities your program has. For example, in the above program there are three possibilities. The value could either be greater, smaller or equal. All these possibilities are covered using if-else if-else statements. Depending upon the possibilities you can add more "else if" statement before the final else statement. It is good programming to cover all the possibilities to make your program perfect.

In the next chapter we will learn about nested if statements.

Wednesday, July 28, 2010

Relational Operators (Comparison Operators) in c++

Relational Operators (also known as Comparison Operators)in C++

There is often need to compare two values in program. Such as whether the value in one a variable is greater than the value in the other variable. Depending upon the situation we can perform different operation for different cases.
Relational Operators (also known as Comparison Operators) are used to compare two values. The result of comparison is a boolean value.
The boolean value can either be true or false. In c and c++, 1 represents true and 0 represent false. However in c++ the data type bool has been introduced, which holds only two values either true or false. The value true in bool corresponds to 1 and 0 corresponds to false.

List of Relational Operators (aka Comparison Operators)


OperatorOperator's NameExampleResult
<less than5<101(true)
<=less than or equal to5<=101(true)
>greater than5>100(false)
>=greater than or equal to5>=100(false)
==equal to5==100(false)
!=not equal to5!=21(true)

/* A c++ program example to demonstrate that the result of comparison is always a boolean value, either 1 or 0. The value 1 represents true and 0 represents false. */



#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    cout << "5 <10" << setw (4) << ": " << (5 < 10) << endl;
    cout << "5 <=10" << setw(3) << ": " << (5 <= 10) << endl;
    cout << "5 >10" << setw (4) << ": " << (5 > 10) << endl;
    cout << "5 >= 10" << setw (2) << ": " << (5 >= 10) << endl;
    cout << "5 == 10" << setw (2) << ": " << (5 == 10) << endl;
    cout << "5 != 10" << setw (2) << ": " << (5 != 10) << endl;

    return 0;
}


This chapter is important to understand selection and looping statement. In coming chapters we will learn about selection and looping statement.

Tuesday, March 16, 2010

Maximum and minimum limit for numeric data type


Maximum and minimum value of numeric data type

In c++, the numeric data types are short, int, long, float, double and long double. Every data type has certain limits. There is minimum and maximum value that it can hold. If a variable of a given data type is assigned a value that is greater than the maximum limit or smaller than the minimum limit, it results into wrong output. This mistake does not produce compiler error or runtime error. Hence we should be careful while choosing data type for a variable. The below is a c++ program which is used to determine the maximum and minimum values that data type can hold.

A c++ program to determine the maximum and minimum values of numeric data types.


#include <iostream>
#include <limits>

using std::cout;
using std::endl;
using std::numeric_limits;

int main ()
{
    cout << "The values for data type short ranges from: "
            << numeric_limits<short>::min () << " to "
            << numeric_limits<short>::max () << endl;

    cout << "The values for the data type int ranges from: "
            << numeric_limits<int>::min () << " to "
            << numeric_limits<int>::max () << endl;

    cout << "The values for the data type long ranges from: "
            << numeric_limits<long>::min () << " to "
            << numeric_limits<long>::max () << endl;

    cout << "The values for the data type float ranges from: "
            << numeric_limits<float>::min () << " to "
            << numeric_limits<float>::max () << endl;

    cout << "The values for the data type double ranges from: "
            << numeric_limits<double>::min () << " to "
            << numeric_limits<double>::max () << endl;

    cout << "The values for the data type long double ranges from: "
            << numeric_limits<long double>::min () << " to "
            << numeric_limits<long double>::max () << endl;

    return 0;
}

Thursday, March 11, 2010

Using the sizeof keyword in c++

Determine the size of data type using sizeof keyword

When we compile the c++ program, the compiler translates that program into language of that machine in which you compile. For example, the size of the data type may vary on 16-bit and on 32-bit processor. In this case you might have to modify your source code to run your program properly. This is not the case in java. As java does not translates the program to machine language when it is compiled, rather it translates the program to bytecode. The java interpreter i.e. the java virtual machine (JVM) or the java run-time environment interprets the bytecode. Hence no modification is required. However in c++ we can find the amount memory allocated by each data type using the sizeof keyword.

The below is the program by which you can know how much memory, a particular data type will require on the machine in which it is executed. For example with windows xp operating system which runs on pentium 4 processor the size of int and long is same, it is 4 bytes.

A C++ Program example to find the size of the data type using sizeof keyword..


#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{

    cout << "The size of bool is" << setw (9) << ": "
            << sizeof (bool) << " byte" << endl;

    cout << "The size of char is" << setw (9) << ": "
            << sizeof (char) << " byte" << endl;

    cout << "The size of short is" << setw (8) << ": "
            << sizeof (short) << " byte" << endl;

    cout << "The size of int is" << setw (10) << ": "
            << sizeof (int) << " byte" << endl;

    cout << "The size of long is" << setw (9) << ": "
            << sizeof (long) << " byte" << endl;

    cout << "The size of float is" << setw (8) << ": "
            << sizeof (float) << " byte" << endl;

    cout << "The size of double is" << setw (7) << ": "
            << sizeof (double) << " byte" << endl;

    cout << "The size of long double is" << setw (2) << ": "
            << sizeof (long double) << " byte" << endl;

    return 0;
}

Sunday, November 22, 2009

Increment And Decrement Operator : prefix and postfix

Increment And Decrement Operator in C++

In C++ Programming Language, increasing a value by 1 is called incrementing and decreasing value by 1 is called decrementing. As 1 is the most common value used to add, subtract and to reassign into variable. Although we have short-hand assingnment operator but special operator are provided in c++ programming to increase or decrease value by 1. The increment operator(++) increases the variable's value by 1 and the decrement operator(--) decreases the value by 1.

A C++ Program example that demonstrate the use increment and decrement operator by comparing it with short hand assignment operator.


#include <iostream>

int main ()
{

    using std::cout;
    using std::endl;

    int b = 4, c = 7;

    cout << "The value of b is : " << b << endl;
    b = b + 1;
    cout << "The value of b is : " << b << endl;
    b += 1;
    cout << "The value of b is : " << b << endl;
    b++;
    cout << "The value of b is : " << b << endl;

    cout << endl;

    cout << "The value of c is : " << c << endl;
    c = c - 1;
    cout << "The value of c is : " << c << endl;
    c -= 1;
    cout << "The value of c is : " << c << endl;
    c--;
    cout << "The value of c is : " << c << endl;

    return 0;
}


Prefixing And Postfixing In Increment And Decrement Operator.

Both increment (++) and decrement (--) operator come in two varieties : prefix and postfix. In prefix the increment or decrement operator is written before the variable's name (++a or --a) and in postfix the increment or decrement operator is written after the variable's name (a++ or a--).

In simple statement it doesn't matter what you choose. But it differs in complex statement in which you increment or decrement value and also assign it to a variable in single statement. The prefix operator is evaluated before the assignment. The postfix opertor is evaluated after the assignment. Follwing example makes it clear.

A C++ Program example that demonstrate the similarities and difference between prefix and postfix operator.


#include <iostream>

int main ()
{

    using std::cout;
    using std::endl;

    int a = 10;

    a++;
    cout << "The value of a is : " << a << endl;
    ++a;
    cout << "The value of a is : " << a << endl;
    cout << "The value of a is : " << a++ << endl;
    cout << "The value of a is : " << ++a << endl;

    cout << endl;

    int b = 3;
    a = b++;
    cout << "The value of a is : " << a << endl;
    cout << "The value of b is : " << b << endl;
    a = ++b;
    cout << "The value of a is : " << a << endl;
    cout << "The value of b is : " << b << endl;

    return 0;
}


Another C++ Program example that demonstrate the use of postfix and prefix operator.


#include <iostream>

int main ()
{

    using namespace std;

    int age = 18;

    cout << "I was " << age++ << " years old." << endl;
    cout << "Now I am " << age << " years old." << endl;
    cout << "One year passes...." << endl;
    cout << "I am " << ++age << " years old." << endl;

    return 0;
}