Virtual Base class Inheritance


Came across this interesting case of multiple base class inheritance which can result in compilation errors.

Figure above demonstrates the ambiguity that can occur in diamond inheritance. The program defines class Base, which contains pure virtual function print. Classes DerivedOne and DerivedTwo each publicly inherit from class Base and override the print function. Class DerivedOne and class DerivedTwo each contain what the C++ standard refers to as a base-class subobject—i.e., the members of class Base in this example.

Class Multiple inherits from both classes DerivedOne and DerivedTwo. In class Multiple, function print is overridden to call DerivedTwo’s print.

Function main declares objects of classes Multiple, DerivedOne and DerivedTwo. main also declares an array of Base * pointers. Each array element is initialized with the address of an object. An error occurs when the address of both—an object of class Multiple—is assigned to array[ 0 ]. The object both actually contains two subobjects of type Base, so the compiler does not know which subobject the pointer array[ 0 ] should point to, and it generates a compilation error indicating an ambiguous conversion.

The problem of duplicate subobjects is resolved with virtual inheritance. When a base class is inherited as virtual, only one subobject will appear in the derived class—a process called virtual base-class inheritance.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example showing virtual base class inheritance
//http://www.deitel.com/articles/cplusplus_tutorials/20060225/virtualBaseClass/index.html

#include <iostream>
using std::cout;
using
std::endl;

// class Base definition
class Base
{

public
:
virtual
void print() const = 0; // pure virtual
}; // end class Base

// class DerivedOne definition
//class DerivedOne : public Base - REF1
class DerivedOne : virtual public Base
{

public
:
// override print function
void print() const
{

cout << "DerivedOne\n";
}
// end function print
}; // end class DerivedOne

// class DerivedTwo definition
//class DerivedTwo : public Base - REF2
class DerivedTwo : virtual public Base
{

public
:
// override print function
void print() const
{

cout << "DerivedTwo\n";
}
// end function print
}; // end class DerivedTwo

// class Multiple definition
class Multiple : public DerivedOne, DerivedTwo
{

public
:
// qualify which version of function print
void print() const
{

DerivedTwo::print();
}
// end function print
}; // end class Multiple

int
main()
{

Multiple both; // instantiate Multiple object
DerivedOne one; // instantiate DerivedOne object
DerivedTwo two; // instantiate DerivedTwo object
Base *array[ 3 ]; // create array of base-class pointers

array[ 0 ] = &both; // ERROR - ambiguous if REF1 and REF2 used
array[ 1 ] = &one;
array[ 2 ] = &two;

// polymorphically invoke print
for ( int i = 0; i < 3; i++ )
array[ i ] -> print();

return
0;
}
// end main

The output is as follows:


String literals in C++

Here's a short one on string literals in C++. Ask yourself: what is their type? It is 'array of n const char', correct! So, we might think:

char* literal = "Hello World!";

would be "invalid"/"illegal" in C++. But you'd be surprised it is not and even Comeau online compiles it successfully without even a warning.

The C++ standard, however, tries to protect you hinting that the above is wrong by stating that it is a deprecated feature in C++ that probably was allowed to keep backward compatibility with C.

Here is what the standard says as part of section [2.13.4/2]:

[quote]
A string literal that does not begin with u, U, or L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type “array of n const char”, where n is the size of the string as defined below; it has static storage duration (3.7) and is initialized with the given characters.
[/quote]

So, the following would have definitely been invalid in C++:

char* literal = "Hello World!";

"Hello World!" is an array of 13 [spooky :-)] constant characters. 'literal' is the pointer to the first element of the array and since that element is const, the pointer cannot be declared as a non-const char*. The pointer has to be of the type 'pointer to a const char'.

But as mentioned above, to have backward compatibility with C where the above works an implicit conversion is defined for array to pointer conversion where a string literal would be converted to an r-value of type "pointer to a char". The standard mentions this in section [4.2/2]:

[quote]
A string literal (2.13.4) with no prefix, with a u prefix, with a U prefix, or with an L prefix can be converted to an rvalue of type “pointer to char”, “pointer to char16_t”, “pointer to char32_t”, or “pointer to wchar_t”, respectively. In any case, the result is a pointer to the first element of the array. This conversion is considered only when there is an explicit appropriate pointer target type, and not when there is a general need to convert from an lvalue to an rvalue. [ Note: this conversion is deprecated. See Annex D. —end note ]
[/quote]

But, the thing to be happy about is the note above, that is re-iterated in Annexure D section [D.4/1] as:

[quote]
The implicit conversion from const to non-const qualification for string literals (4.2) is deprecated.
[/quote]

So, best is to keep the good habit of declaring the pointer to the literal as a pointer to a const. :-)

[The C++ standard's draft version used for quotes above, has document number : N2315=07-0175 dated 2007-06-25]

[Ant] Build .WAR files in Eclipse for Web Applications

Eclipse JEE versions support Java Web Application projects, but other Eclipse versions do not. Java developers need to build WAR (web archive) files for deployments (yes, Exploded deployments are also possible). However Eclipse does not provide a direct way to create war files; developers write ant build files for this. So we thought of sharing a generic ant build file for Web Applications.

Our general Web Application's folder structure is shown in the image. In most cases, this structure will exactly match t your project structure; however the folder named "WebRoot" may be different to yours. (If your folder structure is different, let us know in comments section).

Ant Build file (build.xml)

Following is the general ant build file (build.xml).

<project name="MyWebApplication" basedir="." default="archive">

<property name="WEB-INF" value="${basedir}/WebRoot/WEB-INF" />
<property name="OUT" value="${basedir}/out" />
<property name="WAR_FILE_NAME" value="mywebapplication.war" />
<property name="TEMP" value="${basedir}/temp" />

<target name="help">
<echo>
--------------------------------------------------
compile - Compile
archive - Generate WAR file
--------------------------------------------------
</echo>
</target>

<target name="init">
<delete dir="${WEB-INF}/classes" />
<mkdir dir="${WEB-INF}/classes" />
</target>

<target name="compile" depends="init">
<javac srcdir="${basedir}/src"
destdir="${WEB-INF}/classes"
classpathref="libs">
</javac>
</target>

<target name="archive" depends="compile">
<delete dir="${OUT}" />
<mkdir dir="${OUT}" />
<delete dir="${TEMP}" />
<mkdir dir="${TEMP}" />
<copy todir="${TEMP}" >
<fileset dir="${basedir}/WebRoot">
</fileset>
</copy>
<move file="${TEMP}/log4j.properties"
todir="${TEMP}/WEB-INF/classes" />
<war destfile="${OUT}/${WAR_FILE_NAME}"
basedir="${TEMP}"
compress="true"
webxml="${TEMP}/WEB-INF/web.xml" />
<delete dir="${TEMP}" />
</target>

<path id="libs">
<fileset includes="*.jar" dir="${WEB-INF}/lib" />
</path>

</project>

You can go through the above xml file and see the process; we have created an attribute for WAR file's name.

<property name="WAR_FILE_NAME" value="mywebapplication.war" />

You should change the value "mywebproject.war" to match your project name. Save the above build.xml file inside Web applications project folder as shown in the folder structure image.

Ant build file has separate tasks for compiling the project and to build the war file. In Eclipse you just have to right click on this build file and select "Ant Build" to execute it. The war file will be generated and stored inside <web-project>/out folder.

Related Articles

How to open a .war (web archive) or .jar (java archive) files
Open and read any file in a .war file of a web application with Java

Example of C++ STL 'pair' container

The pair container is a rather basic container. It can be used to store two elements, called first and second, and that's about it. To define a variable as a pair container, the header file must be included. 'pair' can do basic features like assignment and comparisons and has no further special features. It is, however, a basic ingredient of the abstract containers map, multimap and hash_map.

Lets look at the example now:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//A simple example of C++ STL container 'pair'
#include<iostream>
#include<string>
#include<utility>

using namespace
std;

int
main()
{

pair<string, string> name("Zahid","Ghadialy"); //firstname, lastname
string custName = name.first+" "+name.second;
pair<string, int> customerNum(custName, 23456); //firstname, cust. no.
pair<int, int> customerAge(customerNum.second, 30); //cust. no., age

cout<<"Customer Full Name = "<<custName<<endl;
cout<<"Customer Number of "<<customerNum.first<<" is "<<customerNum.second<<endl;
cout<<"Age of Customer Number = "<<customerAge.first<<" is "<<customerAge.second<<endl;

//If we now want to increment say, age by 1
customerAge.second++;
cout<<"New age of Customer Number = "<<customerAge.first<<" is "<<customerAge.second<<endl;

return
0;
}

The output is as follows:


Initialising References in a class

Unassigned references cannot exist for a class. There is no C++ concept of an "unassigned reference" and the behavior of any program that has one is undefined. If a class contains a reference then it must be initialised through an initialiser list. You can't declare a reference variable in the class and then assign it later on. Non-reference variables and pointers can be left uninitialised but references must have a value upon entry. The only way to do this is through an initialiser.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example showing initializing of refrences in a class
#include<iostream>

using namespace
std;

class
A
{

public
:
A(string &name);
void
print()
{

cout<<"a = "<<a<<" and s = "<<s.c_str()<<endl;
}

void
set_a(int x) {a = x;}
private
:
A(); //Shouldnt really be called because we need to have a reference
int a;
string &s;
};


A::A(string &name): s(name)
{

//s = name; - error. Should be in initialiser
a = 0;
}


int
main()
{

string z = "zahid";
A a(z);
a.print();
z = "christian";
a.print();
a.set_a(30);
a.print();
return
0;
}

The output is as follows:

Searching for BASIC

When people search for BASIC online using Google or Bing, or whatever, what keywords do they search with? Some of the obvious choices to me are:

  • basic
  • basic for windows
  • qbasic
  • visual basic
  • vb

How would you search for BASIC?

Between Elasticity and Scalability

Followup on an interesting question being asked in the Cloud Computing Forum.

Definition of Scalability

"Scalability" is the ability to meet an increasing workload requirement by incrementally adding a proportional amount of resources capacity. Therefore, Scalability is quantified by a measure of "linearity", which maintains a constant ratio between resource : workload. This linearity allows the enterprise to plan for its resource budget according to their foreseeable workload growth.

In reality, the range of linearity is not infinite. It is important to understand where the linearity reaches its limit and whether the workload will growth beyond such limit.

A "scalable" design can push the limit of such linearity very far. Far enough that you don't need to worry about the workload ever get beyond that. Scalability architecture is typically built on a repeatable basic infrastructure with minimal coupling such that growth can be achieved by simply repeatedly buying the same set of basic hardware.

Traditionally, people design for scalability to make sure that their operation cost can grow linearly with respect to the workload. They usually don't worry about "removing" resources, nor it worries about whether the resource is fully utilized, because the purchased resources is already a sunk cost. At least for now, "Scalability" is not about managing fluctuating workload and also doesn't have a time dimension. But I expect such mindset will change as people move to Cloud computing when operation cost depends on usage. There are financial motivations to decommission resource once they are no longer used.

Many of existing distributed applications have a very scalable architecture, but very few of them are design with extreme elasticity in mind. Usually they expect the underlying infrastructure are relatively stable with low churn rate (machine crashes are the only cause of infrastructure changes, which is relatively infrequent), therefore they are willing to pay a higher degradation when the churn happens.


Definition of Elasticity

On the other hand, "elasticity" is the ability to instantly commission and decommission large amount of resource capacity on the fly, and then charge purely based on the actual resource usage. "Elasticity" is quantitatively measured by
  • Speed of commissioning / decommissioning
  • Max amount of resource can be brought in
  • Granularity of usage accounting
It is important to understand that even you get "elasticity" automatically when your application is deployed in the cloud, you DO NOT get "scalability" (which is a characteristic of your application architecture). A non-scalable in-house application deployed into the cloud won't magically becomes scalable. Instead, you will just receive a huge bill from your cloud provider at the month end. "Elasticity" is a double edge sword, it lets bad things happen fast.

"Elasticity" is a pretty new feature to our industry and we are in the process of discovering how we can fully utilize it. Most of existing distributed applications are built with scalability but not extreme elasticity in mind. I think an ideal app should have both "scalability" and "elasticity" built in, but I haven't seen much yet. Therefore, although most of existing applications can run in the cloud without modification, I don't think they have fully exploit the benefits of the cloud yet.

"Statefulness" and "Elasticity" are fundamentally in conflict with each other. Data transfer rate has put a limit of the speed of commissioning/decommissioning, which is a measure of elasticity. In other words, I believe smart data distribution algorithm can reduce this friction by reducing the amount of data transfer during commissioning. This is an area of research that I'd love to see.

New Design Paradigm for Cloud Applications

In order to fully exploit the benefits of the cloud, it is necessary to have a new set of design considerations, with both scalability and elasticity in mind. There are many coverages in how to do a scalable design, which I am not trying to repeat here. Lets focus more on "design for elasticity".

  1. Make your application as stateless as possible (but don't just dump all state somewhere else)
  2. Use a smart data migration / balancing algorithm which minimize data movement when the infrastructure grow and shrink elastically. A typical way to do this is to use asynchronous data transfer so that your application can serve immediately (even before the completion of data transfer)
  3. Use a smart scheduler that control the growth/shrink of the environment. Such scheduling algorithm takes the usage charge and performance impact during the dust settlement period into consideration to decide whether a change of the environment should be initiated. Underlying, there is also a monitoring mechanism in place that collects the necessary metrics, perform the analytics and feedback the result to the scheduler to fine tune its earlier policy decision.

c++ cout (displays output to console)

Display output to console

In c++, cout is used to display the data to the console. The statement #include <iostream> is used add the file - iostream to the source code. The file - iostream (input-output-stream) is used by cout and its related function.

Syntax of cout ?

Type cout followed by insertion operator (<<) followed by your data and terminate it by semi-colon. The following program demonstrates the use of cout that displays integers, decimal equivalents string and so on.


A C++ Program example that demonstrate the various implementation of c++ cout


#include <iostream>

int main ()
{

    std::cout << "Lets have a look on cout !!" << endl;
    std::cout << "The number 99 : " << 99 << endl;
    std::cout << "The sum of of 9 + 8 : " << 9 + 8 << endl;
    std::cout << "The division of 7 / 18: "<< float (7 / 18) << endl;
    std::cout << "The multiplication of 6000 & 6000: "
                   << double (6000 * 6000) << endl;
    std::cout << "Replace Mohammed Homam with your name ..."
                   << std::endl;
    std::cout << "Mohammed Homam is a C++ programmer"
                   << std::endl;

    return 0;
}


C++ Notes :

The \n symbol is an special formatting character. It is used to write new line to the screen. The manipulator std::endl is also used to write new line to the screen. like cout, endl is also provided by standard library. Therefore, std:: is added in front of endl just as it was added for cout. But use of endl is preferred over \n because it is adapted to the operating system in use. The term float and double tells cout to display the number in floating-point value.

Simple example of BitSets in C++

From "The C++ Standard Library" By Nicolai M Josuttis: A bitset is a bitfield with an arbitrary but fixed number of bits. You can consider it a container for bits or Boolean values. Note that the C++ standard library also provides a special container with a variable size for Boolean values: vector.

Lets write a simple program using rainbow colours.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Simple example of BitSets
#include<iostream>
#include<bitset>

using namespace
std;

int
main()
{

enum
Colour {red, orange, yellow, green, blue, indigo, violet, numOfColours};

bitset<numOfColours> usedColours;

usedColours.set(red);
usedColours.set(blue);

//Lets see the output
cout << "bitfield of used colours: " << usedColours << endl;
cout << "number of used colors: " << usedColours.count() << endl;
cout << "bitfield of unused colors: " << ~usedColours << endl;

//If any colour is used
if (usedColours.any())
{

// loop over all colors
for (int c = 0; c < numOfColours; ++c)
if
(usedColours[(Colour)c])
cout << Colour(c)<< " used "<<endl; //No way to print enum names directly
}

return
0;
}

The output is as follows:


Reference:


C++ Tutorial For The First Program

C++ Tutorial

Quiz :

1) What differs compiler from interpreter ?
2) Give the steps involved in the normal development cycles

Exercises :

1) Create a c++ program that displays your name.
2) Find the bug in the following program :

#include <iostream>

int main ();
{

    std::cout << "I love C++";

    return 0;
}


Solution of the Quiz :

1) Interpreters turn program instruction directly into actions by reading through the source code. Compilers create an executable program by translating the source code that can be run later.
2) Editing source code, compiling, linking, running and when required repeat it.

Solution of the Exercises :

1) A c++ program that displays name :

#include <iostream>

int main ()
{

    std::cout << "Mohammed Homam";

    return 0;
}

2) The main function is terminated by the semicolon.

Write a program to store Name, Age and address of student

Name age and address of students are stored in a string..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. #include<stdio.h>
  4. void main()
  5. {
  6. clrscr();
  7. char name[100],age[100],address[100];
  8. cout<<"Please enter a name: ";
  9. gets(name);
  10. cout<<"Please enter age: ";
  11. //Coding by: Snehil Khanor
  12. //http://WapCPP.blogspot.com
  13. gets(age);
  14. cout<<"Please eneter address: ";
  15. gets(address);
  16. cout<<endl<<endl<<"Name is: "<<name<<endl<<"Age is: "<<age<<endl<<"Address is:
  17. "<<address;
  18. getch();
  19. }

Write a program to count number of words in a line

A line is taken from user and number of words is calculated..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. #include<stdio.h>
  4. void main()
  5. {
  6. clrscr();
  7. char str[100];
  8. int w=1;
  9. cout<<"Please enter a String: ";
  10. gets(str);
  11. //Coding by: Snehil Khanor
  12. //http://WapCPP.blogspot.com
  13. for (int i=0;str[i]!='\0';i++)
  14. {
  15. if(str[i]==' ')
  16. w++;
  17. }
  18. cout<<"There are "<<w<<" words.";
  19. getch();
  20. }

Write a program to count the number of vowels in a word

A word is taken from the user and number of vowels is determined..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. char str[10];
  7. int v=0;
  8. cout<<"Please enter a string: ";
  9. cin>>str;
  10. //Coding by: Snehil Khanor
  11. //http://WapCPP.blogspot.com
  12. for(int i=0;str[i]!='\0';i++)
  13. {
  14. if(str[i]=='a'||str[i]=='A'||str[i]=='e'||str[i]=='E'||str[i]=='i'||str[i]=='I'||str[i]=='o'||str[i]=='O'||str[i]=='u'||str[i]=='U')
  15. v++;
  16. }
  17. cout<<v<<" Number of Vowels are there.";
  18. getch();
  19. }

Write a program to check a character is in upper case or lower case

A character is taken from user and is checked if it is in UPPER CASE or lower case..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. char x;
  7. cout<<"Please enter a character: ";
  8. cin>>x;
  9. //Coding by: Snehil Khanor
  10. //http://WapCPP.blogspot.com
  11. if(x>='A'&&x<='Z')
  12. cout<<x<<" is in UPPER CASE:)";
  13. else
  14. cout<<x<<" is in lower case :)";
  15. getch();
  16. }

Write a program to store a character and check it is vowel or consonant

A character is taken from user.. and is checked if it is a vowel or a consonant..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. //Coding by: Snehil Khanor
  7. //http://WapCPP.blogspot.com
  8. char x;
  9. cout<<"Please enter a character: ";
  10. cin>>x;
  11. if(x=='a'||x=='A'||x=='e'||x=='E'||x=='i'||x=='I'||x=='o'||x=='O'||x=='u'||x=='U')
  12. cout<<x<<" is a Vowel :)";
  13. else
  14. cout<<x<<" is a consonant :)";
  15. getch();
  16. }

Write a program to find transpose of a matrix

A matrix is taken from user.. and its Transpose is displayed as output..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int a[10][10],m,n,i,j;
  7. cout<<"Enter number of rows: ";
  8. cin>>m;
  9. cout<<"Enter number of coloumns: ";
  10. cin>>n;
  11. //Coding by: Snehil Khanor
  12. //http://WapCPP.blogspot.com
  13. if(m!=n)
  14. {
  15. cout<<"Matrix not square so Transpose not possible :(";
  16. }
  17. else
  18. {
  19. cout<<endl<<"Enter elements of matrix: "<<endl;
  20. for(i=0;i<m;i++)
  21. {
  22. for(j=0;j<n;j++)
  23. {
  24. cout<<"Enter element a"<<i+1<<j+1<<": ";
  25. cin>>a[i][j];
  26. }
  27. }
  28. cout<<endl<<"Displaying Matrix: "<<endl<<endl;
  29. for(i=0;i<m;i++)
  30. {
  31. for(j=0;j<n;j++)
  32. {
  33. cout<<a[i][j]<<" ";
  34. }
  35. cout<<endl<<endl;
  36. }
  37. cout<<endl<<"Displaying Matrix Transpose: "<<endl<<endl;
  38. for(i=0;i<m;i++)
  39. {
  40. for(j=0;j<n;j++)
  41. {
  42. cout<<a[j][i]<<" ";
  43. }
  44. cout<<endl<<endl;
  45. }
  46. }
  47. getch();
  48. }

Write a program for multiplication of two matrices

Two matrices are taken from user..multiplication matrix is displayed as output.


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int a[10][10],b[10][10],c[10][10],m,n,o,p,i,j;
  7. cout<<"Enter number of rows of A: ";
  8. cin>>m;
  9. cout<<"Enter number of coloumns of A: ";
  10. cin>>n;
  11. cout<<endl<<"Enter elements of matrix A: "<<endl;
  12. //Coding by: Snehil Khanor
  13. //http://WapCPP.blogspot.com
  14. for(i=0;i<m;i++)
  15. {
  16. for(j=0;j<n;j++)
  17. {
  18. cout<<"Enter element a"<<i+1<<j+1<<": ";
  19. cin>>a[i][j];
  20. }
  21. }
  22. cout<<endl<<"Enter number of rows of B: ";
  23. cin>>o;
  24. cout<<"Enter number of coloumns of B: ";
  25. cin>>p;
  26. cout<<endl<<"Enter elements of matrix B: "<<endl;
  27. for(i=0;i<o;i++)
  28. {
  29. for(j=0;j<p;j++)
  30. {
  31. cout<<"Enter element b"<<i+1<<j+1<<": ";
  32. cin>>b[i][j];
  33. }
  34. }

  35. cout<<endl<<"Displaying Matrix A: "<<endl<<endl;
  36. for(i=0;i<m;i++)
  37. {
  38. for(j=0;j<n;j++)
  39. {
  40. cout<<a[i][j]<<" ";
  41. }
  42. cout<<endl<<endl;
  43. }
  44. cout<<endl<<"Displaying Matrix B: "<<endl<<endl;
  45. for(i=0;i<o;i++)
  46. {
  47. for(j=0;j<p;j++)
  48. {
  49. cout<<b[i][j]<<" ";
  50. }
  51. cout<<endl<<endl;
  52. }
  53. if(n==o)
  54. {
  55. for(i=0;i<m;i++)
  56. {
  57. for(j=0;j<p;j++)
  58. {
  59. c[i][j]=0;
  60. for(int k=0;k<n;k++)
  61. {
  62. c[i][j]=c[i][j]+a[i][k]*b[k][j];
  63. }
  64. }
  65. }
  66. cout<<endl<<"Matrix A * Matrix B = Matrix C: "<<endl<<endl;
  67. for(i=0;i<m;i++)
  68. {
  69. for(j=0;j<p;j++)
  70. {
  71. cout<<c[i][j]<<" ";
  72. }
  73. cout<<endl<<endl;
  74. }
  75. }
  76. else
  77. cout<<"Multiplication not possible :(";
  78. getch();
  79. }

Write a program to find Difference of two matrix

Two matrix are taken from user.. Substraction matrix is displayed as output..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int a[10][10],b[10][10],c[10][10],m,n,i,j;
  7. cout<<"Enter number of rows: ";
  8. cin>>m;
  9. cout<<"Enter number of coloumns: ";
  10. cin>>n;
  11. cout<<endl<<"Enter elements of matrix A: "<<endl;
  12. //Coding by: Snehil Khanor
  13. //http://WapCPP.blogspot.com
  14. for(i=0;i<m;i++)
  15. {
  16. for(j=0;j<n;j++)
  17. {
  18. cout<<"Enter element a"<<i+1<<j+1<<": ";
  19. cin>>a[i][j];
  20. }
  21. }
  22. cout<<endl<<"Enter elements of matrix B: "<<endl;
  23. for(i=0;i<m;i++)
  24. {
  25. for(j=0;j<n;j++)
  26. {
  27. cout<<"Enter element b"<<i+1<<j+1<<": ";
  28. cin>>b[i][j];
  29. }
  30. }
  31. //Coding by: Snehil Khanor
  32. //http://WapCPP.blogspot.com
  33. cout<<endl<<"Displaying Matrix A: "<<endl<<endl;
  34. for(i=0;i<m;i++)
  35. {
  36. for(j=0;j<n;j++)
  37. {
  38. cout<<a[i][j]<<" ";
  39. }
  40. cout<<endl<<endl;
  41. }
  42. cout<<endl<<"Displaying Matrix B: "<<endl<<endl;
  43. for(i=0;i<m;i++)
  44. {
  45. for(j=0;j<n;j++)
  46. {
  47. cout<<b[i][j]<<" ";
  48. }
  49. cout<<endl<<endl;
  50. }
  51. cout<<endl<<"Matrix A - Matrix B = Matrix C: "<<endl<<endl;
  52. for(i=0;i<m;i++)
  53. {
  54. for(j=0;j<n;j++)
  55. {
  56. cout<<a[i][j]-b[i][j]<<" ";
  57. }
  58. cout<<endl<<endl;
  59. }
  60. getch();
  61. }

Write a program to find sum matrix of two matrix

Two matrix are taken from user.. Sum matrix is displayed as output..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int a[10][10],b[10][10],c[10][10],m,n,i,j;
  7. cout<<"Enter number of rows: ";
  8. cin>>m;
  9. cout<<"Enter number of coloumns: ";
  10. cin>>n;
  11. cout<<endl<<"Enter elements of matrix A: "<<endl;
  12. for(i=0;i<m;i++)
  13. {
  14. for(j=0;j<n;j++)
  15. {
  16. cout<<"Enter element a"<<i+1<<j+1<<": ";
  17. cin>>a[i][j];
  18. }
  19. }
  20. cout<<endl<<"Enter elements of matrix B: "<<endl;
  21. //Coding by: Snehil Khanor
  22. //http://WapCPP.blogspot.com
  23. for(i=0;i<m;i++)
  24. {
  25. for(j=0;j<n;j++)
  26. {
  27. cout<<"Enter element b"<<i+1<<j+1<<": ";
  28. cin>>b[i][j];
  29. }
  30. }

  31. cout<<endl<<"Displaying Matrix A: "<<endl<<endl;
  32. for(i=0;i<m;i++)
  33. {
  34. for(j=0;j<n;j++)
  35. {
  36. cout<<a[i][j]<<" ";
  37. }
  38. cout<<endl<<endl;
  39. }
  40. cout<<endl<<"Displaying Matrix B: "<<endl<<endl;
  41. for(i=0;i<m;i++)
  42. {
  43. for(j=0;j<n;j++)
  44. {
  45. cout<<b[i][j]<<" ";
  46. }
  47. cout<<endl<<endl;
  48. }
  49. cout<<endl<<"Matrix A + Matrix B = Matrix C: "<<endl<<endl;
  50. for(i=0;i<m;i++)
  51. {
  52. for(j=0;j<n;j++)
  53. {
  54. cout<<a[i][j]+b[i][j]<<" ";
  55. }
  56. cout<<endl<<endl;
  57. }

  58. getch();
  59. }

Write a program to store elements in m x n 2D array (Matrix)

m(row) and n(coloumns) are taken from user.. Elements are taken from user.. matrix is displayed in tabular form..
This should be your first program for Matrix.


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int a[10][10],m,n,i,j;
  7. cout<<"Enter number of rows: ";
  8. cin>>m;
  9. cout<<"Enter number of coloumns: ";
  10. cin>>n;
  11. cout<<endl<<"Enter elements of matrix: "<<endl;
  12. //Coding by: Snehil Khanor
  13. //http://WapCPP.blogspot.com
  14. for(i=0;i<m;i++)
  15. {
  16. for(j=0;j<n;j++)
  17. {
  18. cout<<"Enter element a"<<i+1<<j+1<<": ";
  19. cin>>a[i][j];
  20. }
  21. }
  22. cout<<endl<<"Displaying Matrix: "<<endl<<endl;
  23. for(i=0;i<m;i++)
  24. {
  25. for(j=0;j<n;j++)
  26. {
  27. cout<<a[i][j]<<" ";
  28. }
  29. cout<<endl<<endl;
  30. }
  31. getch();
  32. }

Write a program to Insert and Delete elemnt of an array

Size of array is taken from user.. Elements are Entered.. Array is shown.. user is prompted for adding another element.. new element is added at desired position.. user is prompted to delete an element.. Element is deleted from entered position..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<conio.h>
  2. #include<iostream.h>
  3. void main()
  4. {
  5. clrscr();
  6. int a[100],i,pos,num,item,size;
  7. cout<<"How many element: ";
  8. cin>>size;
  9. cout<<"Enter the elements of array: "<<endl;
  10. for(i=0;i<size;i++)
  11. cin>>a[i];
  12. cout<<endl;
  13. cout<<"Now Array is: "<<endl;
  14. for(i=0;i<size;i++)
  15. cout<<"Element at position "<<i+1<<" is "<<a[i]<<endl;
  16. cout<<endl<<"Press any key to add another element"<<endl<<endl;
  17. getch();
  18. //Coding by: Snehil Khanor
  19. //http://WapCPP.blogspot.com
  20. cout<<"Enter another element: ";
  21. cin>>num;
  22. cout<<"Enter position number: ";
  23. cin>>pos;
  24. cout<<endl;
  25. --pos;
  26. for(i=size;i>=pos;i--)
  27. a[i+1]=a[i];
  28. a[pos]=num;
  29. size++;
  30. cout<<"New Array: "<<endl;
  31. for(i=0;i<size;i++)
  32. cout<<"Element at position "<<i+1<<" is "<<a[i]<<endl;
  33. cout<<endl<<"Press any key to delete any element"<<endl<<endl;
  34. getch();

  35. //Coding by: Snehil Khanor
  36. //http://WapCPP.blogspot.com
  37. cout<<"Enter position number to delete: ";
  38. cin>>pos;
  39. --pos;
  40. item=a[pos];
  41. for(i=pos;i<size;i++)
  42. a[i]=a[i+1];
  43. size--;
  44. cout<<"Deleted element: "<<item<<endl;
  45. cout<<endl<<"New array: "<<endl;
  46. for(i=0;i<size;i++)
  47. cout<<"Element at position "<<i+1<<" is "<<a[i]<<endl;
  48. getch();
  49. }

Write a program to sort elements of array (bubble Sorting)

Size of array is taken from user.. Elemnts are entered by user.. Elements are sorted in ascending order..

Select To use this code as it is.. select and copy paste this code into code.cpp file :)
  1. #include<conio.h>

  2. #include<iostream.h>

  3. void main()

  4. {

  5. clrscr();

  6. int a[100],i,n,j,temp;

  7. cout<<"How many element: ";

  8. cin>>n;

  9. cout<<"Enter the elements of array: "<<endl;

  10. for(i=0;i<n;i++)

  11. cin>>a[i];

  12. cout<<"The elements of array Before Sorting: "<<endl;

  13. //Coding by: Snehil Khanor

  14. //http://WapCPP.blogspot.com

  15. for(i=0;i<n;i++)

  16. cout<<a[i]<<" ";

  17. cout<<endl;

  18. for(i=0;i<n;i++)

  19. {

  20. for(j=0;j<n-1-i;j++)

  21. {

  22. if(a[j]>a[j+1])

  23. {

  24. temp=a[j];

  25. a[j]=a[j+1];

  26. a[j+1]=temp;

  27. }

  28. }

  29. }

  30. cout<<"Elements of array After Sorting: "<<endl;

  31. for(i=0;i<n;i++)

  32. cout<<a[i]<<" ";

  33. getch();

  34. }

Write a program to search an element in an array (Binary searching)

Size of array is taken from user.. Elements are entered by user in order (ascending or descending).. user is asked for the element to be searched... Search is performed..
Select To use this code as it is.. select and copy paste this code into code.cpp file :)
  1. #include<conio.h>

  2. #include<iostream.h>

  3. void main()

  4. {

  5. clrscr();

  6. int a[100],i,loc,mid,beg,end,n,flag=0,item;

  7. cout<<"How many element: ";

  8. cin>>n;

  9. cout<<"Enter (IN ORDER) the elements of array: "<<endl;

  10. //Coding by: Snehil Khanor

  11. //http://WapCPP.blogspot.com

  12. for(i=0;i<n;i++)

  13. cin>>a[i];

  14. cout<<"Enter the element to be searched: ";

  15. cin>>item;

  16. loc=0;

  17. beg=0;

  18. end=n-1;

  19. while((beg<=end)&&(item!=a[mid]))

  20. {

  21. mid=(beg+end)/2;

  22. if(item==a[mid])

  23. {

  24. cout<<"Search successful :)";

  25. loc=mid;

  26. cout<<"Position of the Item: "<<loc+1;

  27. flag=flag+1;

  28. }

  29. else if(item<a[mid])

  30. end=mid-1;

  31. else

  32. beg=mid+1;

  33. }

  34. if(flag==0)

  35. {

  36. cout<<"Search NOT sucessfull :( ";

  37. }

  38. getch();

  39. }

Write a program to search an element in an array (Linear searching)

Size of array is taken from user.. Elements are entered.. Then user is asked to enter element to be searched.. Search is performed..
Select To use this code as it is.. select and copy paste this code into code.cpp file :)
  1. #include<iostream.h>

  2. #include<conio.h>

  3. void main()

  4. {

  5. clrscr();

  6. int ar[10],n,num,no;

  7. cout<<"Enter size of the array: ";

  8. cin>>n;

  9. cout<<"Enter array element: "<<endl;

  10. for(int i=0;i<n;i++)

  11. {

  12. cout<<"Enter element "<<i<<": ";

  13. cin>>ar[i];

  14. }

  15. //Coding by: Snehil Khanor

  16. //http://WapCPP.blogspot.com

  17. cout<<"Elements of array: "<<endl;

  18. for(i=0;i<n;i++)

  19. cout<<"Element at index number "<<i<<" is: "<<ar[i]<<endl;

  20. //////To search////

  21. cout<<"Enter number to search: ";

  22. cin>>num;

  23. for(i=0;i<n;i++)

  24. {

  25. if(num==ar[i])

  26. {

  27. cout<<"Found at index number: "<<i;

  28. no=0;

  29. break;

  30. }

  31. else

  32. {

  33. no=1;

  34. continue;

  35. }

  36. }

  37. if(no==1)

  38. cout<<"Sorry your search returned NO results. :(";

  39. getch();

  40. }

Write a program to find minimum in array

Size of array is taken from user..Elements are entered by user..Minimum of the elements is displayed..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int ar[10],n,min;
  7. cout<<"Enter size of the array: ";
  8. cin>>n;
  9. cout<<"Enter array element: "<<endl;
  10. for(int i=0;i<n;i++)
  11. //Coding by: Snehil Khanor
  12. //http://WapCPP.blogspot.com
  13. {
  14. cout<<"Enter element "<<i<<": ";
  15. cin>>ar[i];
  16. }
  17. cout<<"Elements of array: "<<endl;
  18. for(i=0;i<n;i++)
  19. cout<<"Element at index number "<<i<<" is: "<<ar[i]<<endl;
  20. ////To find MIN////
  21. min=ar[0];
  22. for(i=0;i<n;i++)
  23. {
  24. if(min>ar[i])
  25. min=ar[i];
  26. }
  27. cout<<"Minimum in the array is "<<min;
  28. getch();
  29. }

Write a program to find maximum in array

Size of array is taken from user..elements are entered by user..biggest ellement is displayed.


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int ar[10],n,max;
  7. cout<<"Enter size of the array: ";
  8. cin>>n;
  9. cout<<"Enter array element: "<<endl;
  10. for(int i=0;i<n;i++)
  11. {
  12. cout<<"Enter element "<<i<<": ";
  13. cin>>ar[i];
  14. }
  15. //Coding by: Snehil Khanor
  16. //http://WapCPP.blogspot.com
  17. cout<<"Elements of array: "<<endl;
  18. for(i=0;i<n;i++)
  19. cout<<"Element at index number "<<i<<" is: "<<ar[i]<<endl;
  20. ////To find MAX////
  21. max=ar[0];
  22. for(i=0;i<n;i++)
  23. {
  24. if(max<ar[i])
  25. max=ar[i];
  26. }
  27. cout<<"Maximum in the array is "<<max;
  28. getch();
  29. }

Write a program to reverse elements of array

Size of array is taken from user..Elements are stored by user..Then reverse of array is displayed..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int ar[10],n,s=0;
  7. cout<<"Enter size of the array: ";
  8. cin>>n;
  9. cout<<"Enter array element: "<<endl;
  10. for(int i=0;i<n;i++)
  11. {
  12. cout<<"Enter element "<<i<<": ";
  13. cin>>ar[i];
  14. }
  15. //Coding by: Snehil Khanor
  16. //http://WapCPP.blogspot.com
  17. cout<<"Elements of array in original order: "<<endl;
  18. for(i=0;i<n;i++)
  19. cout<<"Element at index number "<<i<<" is: "<<ar[i]<<endl;
  20. cout<<"Elements of array in reverse order: "<<endl;
  21. for(i=n-1;i>=0;i--)
  22. cout<<"Element at index number "<<i<<" is: "<<ar[i]<<endl;
  23. getch();
  24. }

Write a program to find sum of array elements

Size of array is taken from user..Numbers are stored in the array.. and sum is determined of the elements of array..


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int ar[10],n,s=0;
  7. cout<<"Enter size of the array: ";
  8. cin>>n;
  9. cout<<"Enter array element: "<<endl;
  10. for(int i=0;i<n;i++)
  11. {
  12. cout<<"Enter element "<<i<<": ";
  13. cin>>ar[i];
  14. }
  15. //Coding by: Snehil Khanor
  16. //http://WapCPP.blogspot.com
  17. cout<<"Elements of array: "<<endl;
  18. for(i=0;i<n;i++)
  19. cout<<"Element at index number "<<i<<" is: "<<ar[i]<<endl;
  20. ///For adding all elements///
  21. for(i=0;i<n;i++)
  22. s=s+ar[i];
  23. cout<<"Sum of elements: "<<s;
  24. getch();
  25. }

write a program to store n numbers to an array and display them

Size of array is taken from user as n. then n numbers are stored in array..Array is displayed as output.


Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int ar[10],n;
  7. cout<<"Enter size of the array: ";
  8. cin>>n;
  9. cout<<"Enter array element: "<<endl;
  10. for(int i=0;i<n;i++)
  11. //Coding by: Snehil Khanor
  12. //http://WapCPP.blogspot.com
  13. {
  14. cout<<"Enter element "<<i<<": ";
  15. cin>>ar[i];
  16. }
  17. cout<<"Elements of array: "<<endl;
  18. for(i=0;i<n;i++)
  19. cout<<"Element at index number "<<i<<" is: "<<ar[i]<<endl;
  20. getch();
  21. }

write a program to store and display 10 numbers in an array

10 numbers are first stored in array and then the array is displayed.
This should be your first array program.

Select To use this code as it is.. select and copy paste this code into code.cpp file :)



  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int ar[10];
  7. cout<<"Enter array element: "<<endl;
  8. for(int i=0;i<10;i++)
  9. //Coding by: Snehil Khanor
  10. //http://WapCPP.blogspot.com
  11. {
  12. cout<<"Enter element "<<i<<": ";
  13. cin>>ar[i];
  14. }
  15. cout<<"Elements of array: "<<endl;
  16. for(i=0;i<10;i++)
  17. cout<<"Element at index number "<<i<<" is: "<<ar[i]<<endl;
  18. getch();
  19. }

Create Your First C++ Program

Create Your First C++ Program

Don't worry if you don't understand everything right now. Everything will be cleared as you proceed with further lessons. Just keep practicing every program until you are able do it with your own. If you get any error, check your source code with this one carefully. Fix your error then compile and run it again.

A Small C++ Program Example


#include <iostream>

int main ()
{

    std::cout << "Hi! Hello! Wassup!";

    return 0;
}


What are header files (Preprocessor Directive) ?

The statement that begins with #include are known as header files. It is also called as preprocessor directive. When you start the compiler the preprocessor runs first. The preprocessor will be discussed in detail in further chapters. The command #include is a preprocessor instruction that says, "What follows is a file-name. Find that file, read it, and replace it right here." The angle brackets around the file-name tell the preprocessor to look in all the usual places for this file. For example, the file iostream (input-output-stream) is used by cout which displays the output.

What is function ?

Every function starts from the opening brace ({ ) and ends with closing brace ( }). Opening and closing brace together are also called as a block. A block of code that performs one or more action is called function.

What is main function ?

In actual program starts from main function. Main function is also known as primary function or building block of the program. It is compulsory function.
Every C++ program has main function. Every function is called by other function except for main function. Main is a special function which is called directly when your program starts. The return type of main is int, which means it should return an interger value. The main function returns value to an operating system. In this case it return 0 to the operating system. It is used to determine success or failure of the program. It will be discussed in detail in later chapter of functions. Its okay if you don't understand it now but just understand that when you write "int main()" then it becomes compulsory to write "return 0;" before the closing brace of main.

What is cout ? What are syntax of cout ? How to use cout ?

The "cout" is used to display the output. But before cout there is std (standard liabrary) and two colons which tells the compiler to search for cout in standard liabrary. "cout" is a part of standard liabrary. So if we want to use cout we should write std and two colons before it. After cout there is redirection operator (<<) followed by string (whatever we write in double-inverted comma is called string. It is a series of characters.) which ends with the semi-colon. Every statement of C++ ends with semi-colon.

How to create program in C++ using Dev-C++

How to create program in C++ using Dev-C++

01. Create a new folder in "My Documents" to save your programs.



02. Name that folder. For example, "My C++ Programs" or whatever you like.



03. Start Dev-C++.


 
04. Click on file ->new->Source File.



05. Click on file -> Save As.


 
06. Select the destination to save your file.



07. Give the file name and save it on the folder that you created for it.



08. Type your source code.



09. To compile and run both with single key press F9.




10. If you type your source code properly, your program will execute, otherwise it will show error.

11. If your program shows error, then see your source code carefully, identify the errors and correct it.

12. After correcting your source code, you to have compile and run it again. Press F9 again to compile and run.

Example of C++ class invariant

According to Bjarne Stroustrup in 'The C++ Programming Language':

The values of the members and the objects referred to by members are collectively called the state of the object (or simply, its value). A major concern of a class design is to get an object into a well defined state (initialization/construction), to maintain a well defined state as operations are performed, and finally to destroy the object gracefully. The property that makes the state of an object well-defined is called its invariant.

Thus, the purpose of initialization is to put an object into a state for which the invariant holds. Typically, this is done by a constructor. Each operation on a class can assume it will find the invariant true on entry and must leave the invariant true on exit. The destructor finally invalidates the invariant by destroying the object.

Another way of writing the same thing:

A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.

The conditions that have to be met for a condition to be an invariant of the class are:
=> The condition should hold at the end of every constructor.
=> The condition should hold at the end of every mutator (non-const) operation.

Lets look at an example. Suppose we are designing a system where the user input some pressure to be applied. The pressure can be between 30 and 100 units. A user should not be allowed to put pressure outside these bounds:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example of class invariant
#include<iostream>

using namespace
std;

const
int PressureOverflow = 1;
const
int PressureUnderflow = 2;

const
int MIN_PRESSURE = 30;
const
int MAX_PRESSURE = 100;

class
Pressure
{

public
:
Pressure();
void
setPressure(int p);
void
displayPressure(void) const;
private
:
int
pressureMonitor; //invariant
};

Pressure::Pressure()
{

pressureMonitor = 30;
}


void
Pressure::setPressure(int p)
{

try

{

if
(p < MIN_PRESSURE)
throw
PressureUnderflow;
if
(p > MAX_PRESSURE)
throw
PressureOverflow;
pressureMonitor = p;
}

catch
(int pError)
{

switch
(pError)
{

case
PressureUnderflow:
pressureMonitor = MIN_PRESSURE;
cout<<"ERROR: Pressure should be between "<<MIN_PRESSURE<<" and "<<
MAX_PRESSURE<<" - Value set to "<<pressureMonitor<<endl;
break
;
case
PressureOverflow:
pressureMonitor = MAX_PRESSURE;
cout<<"ERROR: Pressure should be between "<<MIN_PRESSURE<<" and "<<
MAX_PRESSURE<<" - Value set to "<<pressureMonitor<<endl;
break
;
default
:
break
;
}
}
}


void
Pressure::displayPressure(void) const
{

cout<<"Current Pressure set to: "<<pressureMonitor<<endl;
}


int
main()
{

Pressure p;
int
x=0;
while
(1)
{

p.displayPressure();
cout<<"Enter new Pressure: ";
cin>>x;
p.setPressure(x);
}


return
0;
}


The output is as follows:

Check out this stream