Friday 27 May 2016

Guess the output of this recursion problem.

#include"iostream"
using namespace std;
void func(int bool)
{
if(!bool)
return 0;
cout<<bool;
func(!bool);
cout<<bool;
}

int main()
{
func(123);
}

What is the output?
1. 123123
2, 123
3. Stack Overflow
4. 0

#cprogramming #cpluplus #cprogramming #recursion

Thursday 12 May 2016

Operator overloading in c++

A small example of how to overload operators in c++. In this program we have binary operator, relation operator, stream operator used on String class. Constructor are also use to directly assign string to class.

#include <iostream.h>
#include<string.h>

class String
{
 char s[50];
public:
 String()
 {
   strcpy(s,NULL);
 }

 String(char *v)
 {
  strcpy(s,v);
 }

 String(String& v)
 {
  strcpy(s,v.s);
 }

 String operator +=(String a){
   return String(strcat(s,a.s));
 }

 int operator ==(String a)
 {
     return !strcmp(s,a.s);
 }

 int operator !=(String a)
 {
     return strcmp(s,a.s);
 }

 int operator >(String a)
 {
     return strcmp(s,a.s);
 }

  int operator <(String a)
 {
     return strcmp(s,a.s);
 }

  String operator =(String b){
   return String(strcpy(s,b.s));
 }

  String operator +(String b){
    String s1(s);
   return String(strcat(s1.s,b.s));
 }

  friend ostream &operator<<(ostream &, String );
  friend istream &operator>>(istream &, String &);
};

ostream &operator<<(ostream &os, String ob)
{
 os << ob.s;
 return os;
}

istream &operator>>(istream &is, String &ob)
{
 is>>ob.s;
 return is;
}

void main()
{

 String obj("Hello C ");
 String obj1("Hello C++ ");
 if(obj1>obj)
 cout<<obj1<<" is greater than "<<obj;
else if(obj1<obj)
     cout<<obj1<<" is less than "<<obj;
 else
     cout<<"Both "<<obj1<<" and "<<obj<<" are equal";
 return;
}
#cprogramming #clanguage #c++