/*This code snippet is an example of operator overloading, constructor, destructor,mutator, faclitator methods Also it is divided in two parts, one a defintion part and another a declaration part */ #includeusing namespace std; #include "complex1.h" //Constructor Complex1 :: Complex1() { this->m_real = 0; this->m_imaginary = 0; } Complex1 :: Complex1(int m_real, int m_imaginary) { this->m_real = m_real; this->m_imaginary = m_imaginary; } //inspector Methods int Complex1 :: get_real() const { return this->m_real; } int Complex1 :: get_imaginary() const { return this->m_imaginary; } //Mutator Methods void Complex1 :: set_real(int m_real) { this->m_real = m_real; } void Complex1 :: set_imaginary(int m_imaginary) { this->m_imaginary = m_imaginary; } //Facilitator Methods void Complex1 :: accept() { cout << "Enter m_real and m_imaginary parts of a complex number ::"; cin >> this->m_real >> this->m_imaginary; } void Complex1 :: display() const { if(this->m_imaginary >= 0) cout << this->m_real << "+" << this->m_imaginary << "i" << endl; else if(this->m_imaginary < 0) cout << this->m_real << this->m_imaginary << "i" << endl; } Complex1 Complex1 :: complex_add(const Complex1& c1) const { Complex1 temp; temp.m_real = this->m_real + c1.m_real; temp.m_imaginary = this->m_imaginary + c1.m_imaginary; return temp; } Complex1 Complex1 :: complex_subtract(const Complex1& c1) const { Complex1 temp; temp.m_real = this->m_real - c1.m_real; temp.m_imaginary = this->m_imaginary - c1.m_imaginary; return temp; } Complex1 Complex1 :: operator+(const Complex1& c) const { return complex_add(c); } Complex1 Complex1 :: operator-(const Complex1& c) const { return complex_subtract(c); } Complex1 Complex1 :: operator++() { this->m_real++; return *this; } Complex1 Complex1 :: operator++(int) { Complex1 temp = *this; this->m_real++; return temp; } Complex1 Complex1 :: operator--() { this->m_real--; return *this; } Complex1 Complex1 :: operator--(int) { Complex1 temp = *this; this->m_real--; return temp; } bool Complex1 :: operator==(const Complex1& c)const { if(this->m_real == c.m_real && this->m_imaginary == c.m_imaginary) return true; else return false; } bool Complex1 :: operator!=(const Complex1& c) const { if(this->m_real != c.m_real || this->m_imaginary != c.m_imaginary) return true; else return false; } Complex1 :: ~Complex1() { cout << "Destroying... " << endl; } ostream& operator<<(ostream& out,const Complex1& c) { if(c.m_imaginary >= 0) out << c.m_real << "+" << c.m_imaginary << "i" << endl; else if(c.m_imaginary < 0) out << c.m_real << c.m_imaginary << "i" << endl; return out; } istream& operator>>(istream& in,Complex1& c) { in >> c.m_real >> c.m_imaginary; return in; } // Class Declaration class Complex1 { private: int m_real,m_imaginary; public: //constructors Complex1(); Complex1(int, int); //inspector Methods int get_real() const; int get_imaginary() const; //Mutator Methods void set_real(int ); void set_imaginary(int ); //Facilitator Methods void accept(); void display() const; Complex1 complex_add(const Complex1& c) const; Complex1 complex_subtract(const Complex1& c) const; Complex1 operator+(const Complex1& c) const; Complex1 operator-(const Complex1& c) const; Complex1 operator++(); Complex1 operator++(int); Complex1 operator--(); Complex1 operator--(int); bool operator==(const Complex1&) const; bool operator!=(const Complex1&) const; friend ostream& operator<<(ostream& ,const Complex1&); friend istream& operator>>(istream& ,Complex1&); //destructor ~Complex1(); };
Tuesday, October 20, 2009
Operator Overloading, Constructor, Destructor, Mutator, Facilitator methods in C++
Monday, October 19, 2009
Code Snippet to implement stack in Java
class MyStack
{
private:
int arr[5];
int top;
public:
MyStack()
{
int i;
for(i=0;i<5;i++)
{
arr[i]=0;
}
top=0;
}
void push(int val)
{
if(full())
System.out.println("Stack is Full.........\n");
this.arr[top]=val;
this.top=this.top+1;
}
int pop()
{
if(empty())
System.out.println("Stack is Empty.........\n");
this.top=this.top-1;
return arr.[top];
}
boolean empty()
{
if(this.top==0)
return true;
else
return false;
}
boolean full()
{
if(this.top==5)
return true;
else
return false;
}
}
class DemoStack
{
public static void main(String[] args)
{
}
}
A program to print all possible combination of three digits(Java)
/*For example if three digits are 1,2 and 3 then all the possible combinations are 123,132,231,213,321 and 312)*/
class Combination
{
public static int reverseNumber(int no)
{
int ono=0,rev=0,rem;
ono=no;
while(ono!=0)
{
rem=ono%10;
ono/=10;
rev= (rev*10)+rem;
}
return rev;
}
public static void main(String[] args)
{
int no,rem;
String num=javax.swing.JOptionPane.showInputDialog("Enter Three Digit Number");
no=Integer.parseInt(num);
for(int j=0;j<2;j++)
{
for(int i=0;i<3;i++)
{
rem=no%10;
no=no/10;
no=(rem*100)+no;
System.out.println("numbers are:"+no);
}
no=reverseNumber(no);
}
}
A class to validate, increment, decrement and compare dates(Java)
class ValidateDate
{
int day,month,year;
ValidateDate()
{
this.day=1;
this.month=1;
this.year=1;
}
ValidateDate(int d,int m,int y)
{
this.day=d;
this.month=m;
this.year=y;
}
void incrementByOneDay()
{
this.day=this.day+1;
if(this.day > 30 )
{
this.day=this.day-30;
this.month=this.month+1;
if(this.month > 12)
{
this.month=this.month-12;
this.year=this.year+1;
}
}
}
void decrementByOneDay()
{
this.day=this.day-1;
if(this.day == 0 )
{
this.day=30;
this.month=this.month-1;
if(this.month == 0)
{
this.month=12;
this.year=this.year-1;
}
}
}
boolean compareDates(ValidateDate d)
{
if(this.day==d.day && this.month==d.month && this.year==d.year)
return true;
else
return false;
}
void displayDate()
{
System.out.print("Date=>"+this.day);
System.out.print(":"+this.month);
System.out.print(":"+this.year);
}
public static void main(String[] args)
{
ValidateDate d1=new ValidateDate(30,12,2001);
d1.displayDate();
d1.incrementByOneDay();
System.out.println("After incrementing:");
d1.displayDate();
d1.decrementByOneDay();
System.out.println("After decrementing:");
d1.displayDate();
ValidateDate d2=new ValidateDate(30,12,2001);
if(d1.compareDates(d2))
System.out.println("EQUAL");
else
System.out.println("NOT EQUAL");
}
}
A program find the factorial of a number using recursive functions (Java)
class Factorial
{
public static int factorialRec(int no)
{
int ans;
if(no==1)
return 1;
ans=no*(factorialRec(no-1));
return ans;
}
public static void main(String[] args)
{
int fact,num;
String number=javax.swing.JOptionPane.showInputDialog("Enter Number");
num=Integer.parseInt(number);
fact=factorialRec(num);
System.out.println("Factorial of number::"+fact);
}
}
Friday, October 16, 2009
Code snippet to reverse the contents of a file (Java)
package reverse;
/* If contents of the file abc.txt are "Cricket is a religion in India", the below code will create a temp.txt file containing the output "aidnI ni noigiler a si tekcirC" */
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
public class Reverse {
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader("D:\\java\\workspace\\Reversefile\\src\\reverse\\abc.txt");//Enter full path of the file whose contents are to be reversed.
BufferedReader br =new BufferedReader(fr);
FileWriter fw=new FileWriter("temp.txt");
String str="";
while((str=br.readLine())!=null)
{
System.out.println(str);
fw.write(new StringBuffer(str+"\n").reverse().toString());
}
fw.close();
fr.close();
br.close();
}
}
Code snippet to read and display a file from a folder (Java)
package files;
import java.io.BufferedReader;
import java.io.IOException;
public class FileReader
{
public static void main(String[] args) throws IOException
{
BufferedReader fr = new BufferedReader(new java.io.FileReader
("D:\\Amit\\JavaAssignments\\Lab3\\MyBook.java"));//Give the complete path of the file you want to read. Above is an example.
String str;
while((str = fr.readLine())!= null)
{
System.out.println(str);
}
}
}
Code snippet to demonstrate synchronization in Java
package threadpack;
class PrintPoem
{
//synchronized
public void print(String poem) throws InterruptedException
{
String words[] = poem.split(",");
for(String word : words)
{
System.out.println(word);
Thread.sleep(1000);
}
}
}
class ReadPoem extends Thread
{
String poem;
PrintPoem printPoem;
public ReadPoem(String poem, PrintPoem printPoem)
{
this.poem = poem;
this.printPoem = printPoem;
this.start();
}
public void run()
{
synchronized (printPoem) {
try
{
printPoem.print(poem);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public class SynchronizationDemo
{
public static void main(String[] args)
{
PrintPoem pObject = new PrintPoem();
new ReadPoem("Twinkle,Twinkle,Little,Star",pObject);
new ReadPoem("Johny,Johny,Yes,Papa",pObject);
}
}
Code snippet to create an applet (Java)
package applet;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FirstApplet extends Applet implements ActionListener
{
Button buttonDefault,ButtonRed,ButtonBlue;
public void init()
{
this.setBackground(Color.yellow);
buttonDefault = new Button("Default");
ButtonRed = new Button("Red");
ButtonBlue = new Button("Blue");
this.add(buttonDefault);
this.add(ButtonRed);
this.add(ButtonBlue);
buttonDefault.addActionListener(this);
ButtonRed.addActionListener(this);
ButtonBlue.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==buttonDefault)
this.setBackground(Color.yellow);
else if(e.getSource()==ButtonRed)
this.setBackground(Color.red);
else
this.setBackground(Color.blue);
}
}
Thursday, October 15, 2009
Code to implement a tree (excercise done in cdac)
#includeusing namespace std; class tree; class node { private: int data; node *left; node *right; public: node(); node(int val); friend class tree; }; node::node() : data(0), left(NULL), right(NULL) { } node::node(int val) : data(val), left(NULL), right(NULL) { } class tree { private: node *root; public: // construct & destruct tree(); ~tree(); // creation void add_node(int val); // deletion void del_node(int val); void clear(node *trav); void clear() { clear(root); root = NULL; } // display void inorder(node *trav); void inorder() { inorder(root); } void preorder(node *trav); void preorder() { preorder(root); } void postorder(node *trav); void postorder() { postorder(root); } // others int height(node *trav); int height() { int ht = height(root); return ht; } node* search(int val); }; // construct & destruct tree::tree() { root = NULL; } tree::~tree() { clear(); } // creation void tree::add_node(int val) { node *newnode = new node(val); if(root == NULL) // tree is empty root = newnode; else // tree is not empty { node *trav = root; while(1) { if(val < trav->data) { // add node to the left if(trav->left == NULL) { trav->left = newnode; break; } else trav = trav->left; } else { // add node to the right if(trav->right == NULL) { trav->right = newnode; break; } else trav = trav->right; } } } } // deletion void tree::del_node(int val) { } void tree::clear(node *trav) { if(trav==NULL) return; clear(trav->left); clear(trav->right); delete trav; } // display void tree::inorder(node *trav) { if(trav==NULL) return; inorder(trav->left); cout << trav->data << " "; inorder(trav->right); } void tree::preorder(node *trav) { if(trav==NULL) return; cout << trav->data << " "; preorder(trav->left); preorder(trav->right); } void tree::postorder(node *trav) { if(trav==NULL) return; postorder(trav->left); postorder(trav->right); cout << trav->data << " "; } // others int tree::height(node *trav) { if(trav==NULL) return 0; int ht_left = height(trav->left); int ht_right = height(trav->right); int max = ht_left > ht_right ? ht_left : ht_right; return max+1; } node* search(int val) { return NULL; } int main() { tree t; t.add_node(10); t.add_node(5); t.add_node(3); t.add_node(15); t.add_node(18); t.add_node(8); t.add_node(12); cout << "pre order : "; t.preorder(); cout << endl; cout << "in order : "; t.inorder(); cout << endl; cout << "post order : "; t.postorder(); cout << endl; int h = t.height(); cout << "height : " << h << endl; return 0; }
C Program to read and write into a file...
// Write to file and read from file #include#include #include #include #include #include #define PATH "/* Give the path where u want to read or write the file*/ " void writefile(char *path) { char pathname[256], name[32], ch; int handle; strcpy(pathname,path); printf("\nEnter file name : "); scanf("%s",name); strcat(pathname,name); handle = open(pathname, O_WRONLY|O_CREAT|O_TRUNC, 0666); if(handle == -1) { perror("file open"); } else { printf("\nInsert data in file : "); while((ch=getchar()) != '^') { write(handle, &ch, sizeof(char)); } } close(handle); } void readfile(char *path) { char pathname[256], name[32], ch; int handle; strcpy(pathname, path); printf("\nEnter file name : "); scanf("%s",name); strcat(pathname,name); handle = open(pathname, O_RDONLY); if(handle == -1) { perror("file open"); } else { while(read(handle, &ch, sizeof(char))!= 0) putchar(ch); } close(handle); } int main() { int ch; do { printf("1.WRITE TO FILE\n2.READ FROM FILE\n3.EXIT\n"); printf("\nEnter choice : "); scanf("%d",&ch); switch(ch) { case 1: writefile(PATH); break; case 2: readfile(PATH); break; } }while(ch != 3); return 0; }
Code snippet to find out length of an array dynamically in C
#include#include int main() { int arr[] = {3,4,65,78,1,2,4}; int arr_length = sizeof(arr)/sizeof(arr[0]); printf("\nLength of the array is :[%d]\n\n", arr_length); getch(); return(0); }
Are these two statements same?
int *ptr = "NULL"; // Here is a statement int *ptr; // Here is a set of two statements *ptr = "NULL"; /* when you print the first it gives 0 and second if you print it gives linking error why so */
How to "CrAcK" technical interviews?
Below are some of very interesting Videos on the internet, which may be watched, as you prepare yourself for interviews. Some of the tips would be less technical oriented and more behavioural. But hey! the "Soft Skills" for instance your presentation, your manners and your attitude does definitely matter worldwide. So click on the below Links to watch the listed video's:-
Why should we hire you?
One more on Why should I hire you?
How to Answer Job Interview Questions
Job Interview Bootcamp- Answering Questions
and one of the rare kind, but very meaningful :-
Technical Interview & You
Also, find more literature or Gyaan on interview tips and tricks:-
Experts Guide on Interviewsand How to prepare for an interview and
Getting that Job!
One last tip,there is a great "Book" in the industry, and is highly recommended by
the Great Programmers and IT fellowmen world wide. If you are an Ace Programmer or a versatile analyst or an entry level IT graduate, dont forget to check out this book:-
Book Title - Programming Interviews Exposed
(And the ice on the cake is, you may grab a free pdf version somewhere on the internet. :) So Google and know)
Also try and search for great technical blogs which write about programming practices, programming interviews, programming languages and tools.
Places like Blogged.com offers you to search blogs on your favorite topics:-
Blogged.com - Show me Great blogs on Programmers
So have Fun! & all the Best to you..
Why should we hire you?
One more on Why should I hire you?
How to Answer Job Interview Questions
Job Interview Bootcamp- Answering Questions
and one of the rare kind, but very meaningful :-
Technical Interview & You
Also, find more literature or Gyaan on interview tips and tricks:-
Experts Guide on Interviewsand How to prepare for an interview and
Getting that Job!
One last tip,there is a great "Book" in the industry, and is highly recommended by
the Great Programmers and IT fellowmen world wide. If you are an Ace Programmer or a versatile analyst or an entry level IT graduate, dont forget to check out this book:-
Book Title - Programming Interviews Exposed
(And the ice on the cake is, you may grab a free pdf version somewhere on the internet. :) So Google and know)
Also try and search for great technical blogs which write about programming practices, programming interviews, programming languages and tools.
Places like Blogged.com offers you to search blogs on your favorite topics:-
Blogged.com - Show me Great blogs on Programmers
So have Fun! & all the Best to you..
Friday, October 2, 2009
Reversing a List in C
#includeint main( ) /* Pre: The user supplies an integer n and n decimal numbers. Post: The numbers are printed in reverse order. Uses: The STL class stack and its methods */ { int n; double item; stack numbers; // declares and initializes a stack of numbers cout << " Type in an integer n followed by n decimal numbers." << endl << " The numbers will be printed in reverse order." << endl; cin >> n; for (int i = 0; i < n; i‚‚) { cin >> item; numbers.push(item); } cout << endl << endl; while (!numbers.empty( )) { cout << numbers.top( ) << " "; numbers.pop( ); } cout << endl; }
Wednesday, September 30, 2009
Sample Code to find distance between a point & a line segment that connects two points in C++
/*This code snippet finds the distance between a P( x,y)
and a line segement that connects 2 points P1(x1,y1) and P2(x2,y2) */
int main()
{
float x1,y1,x2,y2;
float x,y;
char ch;
do
{
clrscr();
cout<<"\n\nEnter x position of the Point:";
cin>>x;
cout<<"\nEnter y position of the Point:";
cin>>y;
cout<<"\n\nEnter x position of the frist Point:";
cin>>x1;
cout<<"\nEnter y position of the frist Point:";
cin>>y1;
cout<<"\n\nEnter x position of the second Point:";
cin>>x2;
cout<<"\nEnter y position of the second Point:";
cin>>y2;
float linedist,dist1,dist2;
linedist = sqrt( (( x1-x2 )*( x1-x2 ))+(( y1-y2 )*( y1-y2 )) );
dist1 = sqrt( (( x1-x )*( x1-x ))+(( y1-y )*( y1-y )) );
dist2 = sqrt( (( x-x2 )*( x-x2 ))+(( y-y2 )*( y-y2 )) );
float height = linedist*(dist1)/(dist1+dist2);
float distance = sqrt( (dist1*dist1) - (height*height) );
cout<<"\n\nDistance minimum of point from line is::" << distance << "\n
\ncontinue[Y/N] ??";
cin>>ch;
}
while(ch!='n' && ch!='N');
return 0;
}
Program that will return the nth node from the end of a linked list
struct node
{
int data;
struct node *next;
}mynode;
mynode * nthNode(mynode *head, int n /*pass 0 for last node*/)
{
mynode *ptr1,*ptr2;
int count;
if(!head)
{
return(NULL);
}
ptr1 = head;
ptr2 = head;
count = 0;
while(count < ptr1="ptr1-">next)==NULL)
{
//Length of the linked list less than n. Error.
return(NULL);
}
}
while((ptr1=ptr1->next)!=NULL)
{
ptr2=ptr2->next;
}
return(ptr2);
}
Given a point with co-ordinates x, y write a function to check if it lies in a box whose center co-ordinates, width and height are known.
class BOX
{
int center_x;
int center_y;
int width;
int height;
public BOX()
{
//initialize center width,height
}
boolean IsOnBox(int x,int y);
{
return ( (x >= center_x - width/2) && (x <= center_x + width/2) && (y>=center_y- height/2) && (y <= center_x-height/2) )
}
}
Reverse an unsigned integer(C)(Kindly check if the code is working properly)
uint Reverse(uint x)
{
uint y = 0;
int i=0;
for (i=0;i<32;i++) y =" (x">>= 1;
}
return y;
}
Game Program
#include
#include
#include
class Nasa
{
int x;
int y;
char dir;
void moveNorth()
{
this->y++;
}
void moveSouth()
{
this->y--;
}
void moveEast()
{
this->x++;
}
void moveWest()
{
this->x--;
}
public:
int run()
{
char ch='n';
do
{
clrscr();
char *mov;
cout<<"\n\nEnter coordinates :\n"; cout<<"X:"; cin>>this->x;
cout<<"Y:"; cin>>this->y;
cout<<"direction[N/S/E/W]:"; cin>>this->dir;
if(dir<='z' && dir>='a')
dir-=32;
cout<<"\n\nEnter movement string:\n"; cin>>mov;
strupr(mov);
for(int i=0;mov[i]!=NULL;i++)
{
switch(mov[i])
{
case 'L':
switch(dir)
{
case 'N':
dir='W';
break;
case 'S':
dir='E';
break;
case 'E':
dir='N';
break;
case 'W':
dir='S';
break;
}
break;
case 'R':
switch(dir)
{
case 'N':
dir='E';
break;
case 'S':
dir='W';
break;
case 'E':
dir='S';
break;
case 'W':
dir='N';
break;
}
break;
case 'M':
switch(this->dir)
{
case 'N':
moveNorth();
break;
case 'S':
moveSouth();
break;
case 'E':
moveEast();
break;
case 'W':
moveWest();
break;
}
}
}
cout<<"\n\n"<<<" "< <<" "< <<"\n\n continue [Y/N] :"; cin>>ch;
}
while(ch!='n' && ch!='N');
return 0;
}
};
int main()
{
Nasa n;
n.run();
}
Sunday, September 27, 2009
Purpose...
The purpose of this website to get feedback from industry experienced developers on Amit's code, if you want to provide constructive feedback, post back your comments, so he can learn from his mistakes.
On how to post on the blog, read this post http://mlawire.blogspot.com/2009/07/blogger-syntax-highlighting.html
On how to post on the blog, read this post http://mlawire.blogspot.com/2009/07/blogger-syntax-highlighting.html
Subscribe to:
Comments (Atom)