Copyright © Programs ++
Design by Dzignine
Monday, 30 January 2012

Multiple increment operators in a sinlge expression

I came across this problem while reading a program in my sophomore year. When multiple increment operators are used in a single statement, the results can be quite unpredictable. For e.g, consider this piece of code :
int C,a = 10;
C = a++ + ++a + ++a + a;
std::cout<<C<<" "<<a;

Now, usually the compiler evaluates the expression from right to left, and hence the result should come out to be 10 + 11 + 12 + 12 = 45(if my math is correct :p), but when the program is executed, the result comes out to be 12 + 12 + 12 + 12 = 48( :O ). Does this mean that the computer made a mistake ?? No, the compiler did not. What happened actually is that when multiple increment operators are used in a single statement, the compiler 
1 - first evaluates all the prefix expressions i.e. ++a leading the value of 'a' to be 11 then again ++a, thus 'a' becomes 12.
2 - then the expression is evaluated, so the expression becomes 12 + 12 + 12 + 12 = 48;
3 - finally it evaluates the postfix expressions i.e a++ hence the the final value of 'a' becomes 13.
The following program demonstrates the above concept :

// Multiple incremnet operators in a single expression

#include <iostream>

int main()
{
    int a = 10,result;
    result = a++ + ++a + ++a + a;
    std::cout<<" Result : "<<result; // displays the result
    std::cout<<" \n Value of a : "<<a; // displays the value of a
    std::cin.get();  
    return 0;
} // end of main
Output in turbo compiler












NOTE : The above output is obtained when the program is executed using a turbo C++ compiler or a borland c++ compiler. 
The way in which the expression is evaluated varies from compiler to compiler. For e.g, when the same program is executed in Dev-C++, the result comes out to be 46. Hence different compilers evaluate an expression containing multiple increment operators differently.
Output in dev-c++









  




------Related Posts ------

http://programsplusplus.blogspot.com/2012/01/4-pre-and-post-increment-operators.html

Sunday, 29 January 2012

Swapping two variables(with and without using a third variable)

Swapping of variables is one of the most common type of operation in c++. It involves interchanging the values of two variables. It can be achieved by one of three ways.
1 - Using a third variable.
2 - Without using a third variable

1- Swapping using a third variable : In this method a third variable is used to hold the value of one of the variables.Suppose we want to swap the values of two integers, say x and y. To do that , we would first declare a third variable, say temp. Next, assign the value of x to temp so we have to copies of x , one in x and another in temp. 
Then, assign the value of y to x. This will overwrite the value of x with y.
Now, assign the value of x to y, using temp, which contains the original value of x, and there we have it. Swap successful !!!! The following program shows the above procedure :
// Program to swap two numbers
#include <iostream>

int main()
{
    int x,y,temp;
    std::cout<<" Enter the value of x : ";
    std::cin>>x;
    std::cout<<"\n Enter the value of y : ";
    std::cin>>y;
    std::cin.ignore();                  // to clear the buffer
    std::cout<<"\n Value of x and y before swapping : "<<x<<" "<<y;
    // swaps the two variables x and y using the third variable temp
    temp = x;           
    x = y;
    y = temp;
    std::cout<<"\n Value of x and y after swapping : "<<x<<" "<<y;
    std::cin.get();      // to prevent the console from closing immediately
    return 0;
} // end of main 
Swapping using a third variable











 2 - Swapping using WITHOUT using a third variable : This is a very simple concept to understand. First add both the variables, then subtract two times. For e.g. , let us swap two variables x and y each having values 10 and 5 respectively. 
Then, according to swap the values , firstly
x = x + y; // adding x and y and assigning the result to x ie x = 10 + 5 i.e x = 15;
y = x - y; // subtracting  x and y and assigning it to y i.e y = 10 - 5 which is 5, which is also the original value of x, hence y now has the original value of x.
finally x = x - y; // i.e 15 - 5 = 10, hence x = 10, which is the original value of y.
Who la, we have swapped the two value.
NOTE : This method is only useful when x > y and will not work the other way round.
A program is given below to demonstrate the above method :
 // Program to swap two numbers(without using a third variable)
#include <iostream>

int main()
{
    int x,y;
    std::cout<<" Enter the value of x : ";
    std::cin>>x;
    std::cout<<"\n Enter the value of y : ";
    std::cin>>y;
    std::cin.ignore(); // to clear the buffer
    std::cout<<"\n Value of x and y before swapping : "<<x<<" "<<y;
    x = x + y;        
    y = x - y;
    x = x - y;
    std::cout<<"\n Value of x and y after swapping : "<<x<<" "<<y;
    std::cin.get();      // to prevent the console from closing immediately
    return 0;
} // end of main

Swapping without using a third variable









 
 
Thursday, 26 January 2012

Uppercase to Lowercase

The program converts a string form UPPERCASE to LOWERCASE using a function strlwr() found in the C string library(<cstring>).
It has the following syntax :  strlwr(char *);
This means that it takes the address of the first character of the target string and converts it into lowercase. 
For example, if the input string was : HELLO, MY NAME IS DEEPAK.
The output would be : hello, my name is deepak. 
A sample program is written to demonstrate the use of strlwr().

// Program to convert a string from uppercase to lowercase 

#include <iostream>
#include <cstring> // header file that cotains the function strlwr

int main()
{
    char string1[20],*ptr;
    std::cout<<" Enter a string of your choice(max 20 characters : ";
    std::cin.getline(string1,sizeof(string1));
    ptr = &string1[0]; // assigns the address of the first character of the sting to ptr
    strlwr(ptr); // convers the string to lowercase
    std::cout<<" \n The string is as follows : "<<string1;
    std::cin.get(); // displays the output
    return 0;
} // end of main 

 

sizeof() --  the sizeof() calculate the total size of a variable,string or an object. 
The above program prompts the user to enter a string in uppercase and stores it in string1 variable.
Then it assigns the address of the first element of the sting to the ptr pointer which is of char type, because in the strlwr() function the whole string is not passed, instead the address of the first element of the string is passed. 
However, one should keep in mind that using strlwr() function causes changes in the original string, hence it should not be used if the original string is to be preserved.

Note : strupr() and strlwr() are not standard C++ functions, standard c++ functions for converting uppercase to lowercase and vice-verse, use tolower() and toupper() functions located in <cctype> or for those who use turbo c++ , it is located in the ctype.h header file. Click the link below to gain for a demo program:
http://programsplusplus.blogspot.com/2012/01/lowercase-to-uppercase.html


Lowercase to Uppercase

The program converts a string form LOWERCASE to UPPERCASE using a function strupr() found in the C string library(<cstring>).
It has the following syntax :  strupr(char *);
This means that it takes the address of the first character of the target string and converts it into uppercase. 
For example, if the input string was : hello, my name is deepak.
The output would be : HELLO, MY NAME IS DEEPAK. 
A sample program is written to demonstrate the use of strupr().

*Note : strlwr() and strupr() are not standard C++ functions. Functions such as tolower() and toupper() found in ctype.h are standard c++ functions.

// Program to convert a string from lowercase to uppercase

#include <iostream>
#include <cstring> // header file that contains the strupr() function

int main()
{
    char string1[20],*ptr;
    std::cout<<" Enter a string of your choice(max 20 characters : ";
    std::cin.getline(string1,sizeof(string1)); // stores the string in the string1 variable
    ptr = &string1[0]; // assigns the address of the first element to the pointer variable of char type
    strupr(ptr); // converts the string to uppercase
    std::cout<<" \n The string is as follows : "<<string1;
    std::cin.get(); // displays the output
    return 0;
} // end of main 
 





sizeof() --  the sizeof() calculate the total size of a variable,string or an object. 
The above program prompts the user to enter a string in lowercase and stores it in string1 variable
Then it assigns the address of the first element of the sting to the ptr pointer which is of char type, because in the strupr() function the whole string is not passed, instead the address of the first element of the string is passed. 
However, one should keep in mind that using strupr() function causes changes in the original string, hence it should not be used if the original string is to be preserved.

*Note : strlwr() and strupr() are not standard C++ functions. Functions such as tolower() and toupper() found in ctype.h are standard c++ functions. The following program demonstrates the use of toupper() function to convert strings from lowercase to uppercase.
// Program to convert lowercase and uppercase (using standard C++ functions)
#include <iostream>

#include <cctype>

int main()
{
    char string1[20],string2[20];
    std::cout<<" Enter a string in lowercase (max 20) : ";
    std::cin.getline(string1,sizeof(string1)); // gets the input string
    int i;
    // keep running the loop until \0 is not occuered i.e end of string
    for (i=0; string1[i] != '\0'; i++)
    {
        string2[i] = (char)toupper(string1[i]);
        }
    string2[i] = '\0'; // append \0 at after the last character
    std::cout<<" String in UPPERCASE is : "<<string2; // displays the output string
    std::cin.get();
    return 0;
} // end of main
lowercase to uppercase (alternate version)











Use of '&' operator in C++


// Program to demonstrate the use of &(ampersand) operator
#include <iostream>

int main()
{
    int x,y;
    std::cout<<" Enter the value of x : ";
    std::cin>>x;
    std::cout<<" The VALUE of x is : "<<x;
    std::cout<<" \n The ADDRESS of x is : "<<&x; // displays the address of x
    std::cin.get(); // displays the output
    return 0;
} // end of main










Wednesday, 25 January 2012

Descending Triangle Pattern - alternate version

// Program to print a descending triangle pattern - alternate version

#include <iostream>

int main()
{
    char ch;
    int n,j,k;
    std::cout<<" Enter a character : ";
    std::cin>>ch;
    std::cout<<" Ener the no of lines to print : ";
    std::cin>>n;
      for (int i=1; i<=n; i++)
    {
        for (j=0; j<i; j++)
            std::cout<<" "; // prints white spaces
        for (k=n; k>=i; k--)
            std::cout<<ch; // prints the specified character 
    
        std::cout<<std::endl; // to leave a line space
    }
    std::cin.get();
    return 0; // to display the output
} // end of main
Descending star pattern -alter nate

Descending Triangle Pattern

// Program to print a descending triangle pattern

#include <iostream>

int main()
{
    char ch;
    int n,j,k;
    std::cout<<" Enter a character : ";
    std::cin>>ch;
    std::cout<<" Ener the no of lines to print : ";
    std::cin>>n;
    for (int i=1; i<=n; i++)
    {
        for (j=n; j>=i; j--)
            std::cout<<ch; // prints the specified character
       
        std::cout<<std::endl; // to leave a line space
    }
    std::cin.get(); // to display the output
    return 0;
} // end of main
Descending star pattern

Ascending Triangle Pattern - alternate version

// Program to print an ascending triangle pattern - alternate version

#include <iostream>

int main()
{
    char ch;
    int n,j,k;
    std::cout<<" Enter a character : ";
    std::cin>>ch;
    std::cout<<" Ener the no of lines to print : ";
    std::cin>>n;
    for (int i=1; i<=n; i++)
    {
        for (j=n; j>=i; j--)
            std::cout<<" "; // for blank spaces
        for (k=1; k<=i; k++)
            std::cout<<ch;
           
        std::cout<<std::endl; // to leave a line space
    }
    std::cin.get(); // to see the output
    return 0;
} // end of main
Star patten in alternate triangle

Ascending Triangle Pattern

// Program to print an ascending triangle pattern

#include <iostream>

int main()
{
    char ch;
    int n,j;
    std::cout<<" Enter a character : ";
    std::cin>>ch;
    std::cout<<" Enter the no of lines to print : ";
    std::cin>>n;
    for (int i=1; i<=n; i++)
    {
        for (j=1; j<=i; j++)
            std::cout<<ch;    // prints the specified character
        std::cout<<std::endl; // to leave a line space
    }
    std::cin.get();
    return 0;
} // end of main

Exception Handling (try n catch)

Exception handling in C++ is implemented by using try,catch and throw. An example of how these are used is given in the following program : 

try { ....  } // tries a set of statement to test the presence of an exception
throw(VALUE); // to throw a value in case an exception has occured 
catch( ... ) { ... } // to catch the exception and take appropriate steps to handle it. Can have parameters to receive a particular type of value.

// Program for exeception handling in C++

#include <iostream>

int main()
{
    int x;
    std::cout<<" Enter the value of x : ";
    std::cin>>x; // prompts the user to enter some value of x
    try // try block to test the value of x
    {
       if ( x > 0 )
          throw (0); // throws an integer
       else
          throw ('a'); // throws a character
    }
   
    catch(int n)
    {
              std::cout<<" \n Caught Integer !!! ";
    }
    catch(char ch)
    {
               std::cout<<"\n Caught Character !!!";
    }
    std::cin.get();
    return 0;
} // end of main

Exception handled when x < 0

Exception handled when x > 0



Tuesday, 24 January 2012

ASCII values from a-z

ASCII value of a-z range from 97 to 122


// Program to print the ASCII value for a-z characters
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    int x; // to store the ascii codes
    char ch; // to store the characters
    for (int i=97; i<=122; i++)
    {
        ch = i; // puts integer value into char
        cout<<" Character "<<ch<<" ASCII Code "<<i;
        cout<<endl;
    }
    cin.get();
    return 0;
} // end of main  
a-z ASCII values
 

ASCII values from A-Z

ASCII value of A-Z range from 65 to 90

// Program to print the ASCII value for A-Z characters
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    int x; // to store the ascii codes
    char ch; // to store the characters
    for (int i=65; i<=90; i++)
    {
        ch = i; // puts integer value into char
        cout<<" Character "<<ch<<" ASCII Code "<<i;
        cout<<endl;
    }
    cin.get();
    return 0;
} // end of main   
ASII values of A-Z

           

Using scope resolution operator

The scope resolution operator ( :: ) is used when we have to direct the compiler to use a variable with a particular scope. It comes handy when we have a global and a local variable of the same name as shown in the following example : 

// Program to show the use of scope resolution operator
#include <iostream>
using namespace std;
int x = 25; // global variable

int main()
{
    int x; // local variable
    cout<<" Entre the value of x : ";
    cin>>x;
    cout<<" \n Value of x stored as variable with LOCAl scope : "<<x;
    cout<<" \n Value of x stored as variable wih GLOBAL scope : "<<::x; // scope resolution operator
    cin.get(); // to show the output
    return 0;
} // end of main
 




























































Scope resolution operator demo program 













Get IP address your own computer

The IP (internet protocol) address is a command that displays the ip address of the host computer. The code given below displays the ipv4 adress,ipv6(if available), subnet mask and default gateway along with some additional information. The same can also be achieved by using the command prompt by typing 'ipconfig' in the command prompt.
Just follow the steps :
Step 1 : Open 'Run' in the START menu.
Step 2 : Type 'cmd' in the run tab.The command prompt will appear.
Step 3 : Type 'ipconfig' and press ENTER.
The ip address along with some other information will appear. 
The following program does the same : 

#include <iostream>

using namespace std;
int main()
{
    system("C:\\Windows\\system32\\ipconfig");
    cin.get();
    return 0; // halts the program until enter is pressed
} // end of main
Ip address of the host computer on windows 7