Monday, 13 November 2017

C++ Constructors/Deconstructors

Constructors

Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors iitialize values to object members after storage is allocated to the object.
class A
{
 int x;
 public:
 A();  //Constructor
};
While defining a contructor you must remeber that the name of constructor will be same as the name of the class, and contructors never have return type.
Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator.
class A
{
 int i;
 public:
 A(); //Constructor declared
};

A::A()   // Constructor definition
{
 i=1;
}

Types of Constructors

Constructors are of three types :
  1. Default Constructor
  2. Parametrized Constructor
  3. Copy COnstructor

Default Constructor

Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax :
class_name () 
{ Constructor Definition }
Example :
class Cube
{
int side;
public:
Cube()
 {  
  side=10;
 }
};

int main()
{
Cube c;
cout << c.side;
}
Output : 10
In this case, as soon as the object is created the constructor is called which initializes its data members.
A default constructor is so important for initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly.
class Cube
{
 public:
 int side;
};

int main()
{
 Cube c;
 cout << c.side;
}
Output : 0
In this case, default constructor provided by the compiler will be called which will initialize the object data members to default value, that will be 0 in this case.

Parameterized Constructor

These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument.
Example :
class Cube
{
 public:
 int side;
 Cube(int x)
  {  
   side=x;
  }
};

int main()
{
 Cube c1(10);
 Cube c2(20);
 Cube c3(30);
 cout << c1.side;
 cout << c2.side;
 cout << c3.side;
}
OUTPUT : 10 20 30
By using parameterized construcor in above case, we have initialized 3 objects with user defined values. We can have any number of parameters in a constructor.

Copy Constructor

These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object. We will study copy constructors in detail later.

Constructor Overloading

Just like other member functions, constructors can also be overloaded. Infact when you have both default and parameterized constructors defined in your class you are having Overloaded Constructors, one with no parameter and other with parameter.
You can have any number of Constructors in a class that differ in parameter list.
class Student
{
 int rollno;
 string name;
 public:
 Student(int x)
 {
  rollno=x;
  name="None";
 }
 Student(int x, string str)
 {
  rollno=x ;
  name=str ;
 }
};

int main()
{
 Student A(10);
 Student B(11,"Ram");
}
In above case we have defined two constructors with different parameters, hence overloading the constructors.
One more important thing, if you define any constructor explicitly, then the compiler will not provide default constructor and you will have to define it yourself.
In the above case if we write Student S; in main(), it will lead to a compile time error, because we haven't defined default constructor, and compiler will not provide its default constructor because we have defined other parameterized constructors.

Destructors

Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope.
The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ~ sign as prefix to it.
class A
{
 public:
 ~A();
};
Destructors will never have any arguments.

Example to see how Constructor and Destructor is called

class A
{
A()
 {
  cout << "Constructor called";
 }

~A()
 {
  cout << "Destructor called";
 }
};

int main()
{
 A obj1;   // Constructor Called
 int x=1
 if(x)
  {
   A obj2;  // Constructor Called
  }   // Destructor Called for obj2
} //  Destructor called for obj1


Single Definition for both Default and Parameterized Constructor

In this example we will use default argument to have a single definition for both defualt and parameterized constructor.
class Dual
{
 int a;
 public:
 Dual(int x=0)
  {
   a=x;
  }
};

int main()
{
 Dual obj1;
 Dual obj2(10);
}
Here, in this program, a single Constructor definition will take care for both these object initializations. We don't need separate default and parameterized constructors.

Saturday, 29 April 2017

Social community for computer programmer

Learn C Programming

Learn C Programming

C is a powerful general-purpose programming language. It is fast, portable and available in all platforms.
If you are new to programming, C is a good choice to start your programming journey.
This is a comprehensive guide on how to get started in C programming language, why you should learn it and how you can learn it.

TABLE OF CONTENTS

  • C Tutorials
  • What is C Programming?
  • Reasons to Learn C
  • Your First C Program
  • Recommended Books
  • Things to Remember





What is C (Programming Language)? - The Basics

Before getting started with C programming, lets get familiarized with the language first.
C is a general-purpose programming language used for wide range of applications from Operating systems like Windows and iOS to software that is used for creating 3D movies.
C programming is highly efficient. That’s the main reason why it’s very popular despite being more than 40 years old.
Standard C programs are portable. The source code written in one system works in another operating system without any change.
As mentioned, it’s a good language to start learning programming. If you know C programming, you will not just understand how your program works, but will also be able to create a mental picture on how a computer works.
More information on C Language.


History of C programming

Features of C Programming Language

Should you learn C programming?

If only it were possible to answer this question with a simple “yes” or “no”. Unfortunately, it’s not an easy question to answer and varies from person to person.
Personally speaking, I love C programming. It is a good language to start your programming journey if you are a newbie. Even if you are an experienced programmer, I recommend you to learn it at some point; it will certainly help.

What will you gain if you learn C?

If you don’t know C, you don’t know what you are doing as a programmer. Sure, your application works fine and all. But, if you can’t say why while (*s++ = *p++); copies a string, you’re programming on a superstition. ( Joel Spolsky’s words, not mine ).
  1. You will understand how a computer works.

    If you know C, you will not only know how your program works but, you will be able to create a mental model on how a computer works (including memory management and allocation). You will learn to appreciate the freedom that C provides unlike Python and Java.

    Understanding C allows you to write programs that you never thought were possible before (or at the very least, you will have a broader understanding of computer architecture and programming as a whole).
  2. C is the lingua franca of programming.

    Almost all high-level programming languages like Java, Python, JavaScript etc. can interface with C programming. Also, it’s a good language to express common ideas in programming. Doesn’t matter if the person you are talking with doesn’t know C, you can still convey your idea in a way they can understand.
  3. Opportunity to work on open source projects that impact millions of people.

    At first, you may overlook the fact that C is an important language. If you need to develop a mobile app, you need Java (for Android), Swift and Objective C (for iOS). And there are dozens of languages like C#, PHP, ASP.net, Ruby, Python for building web application. Then, where is C programming?

    Python is used for making wide range for applications. And, C is used for making Python. If you want to contribute to Python, you need to know C programming to work on Python interpreter that impacts millions of Python programmers. This is just one example. A large number of softwares that you use today is powered by C.

    Some of the larger open source projects where C programming is used are Linux Kernel, Python Interpreter, SQLite Database.

    Another language that’s commonly used for large open source project is C++. If you know C and C++, you can contribute to large open source projects that impacts hundreds of millions of people.
  4. You will write better programs.

    To be honest, this statement may not be true all the time. However, knowing how computer works and manage memory gives you insight on how to write efficient code in other programming languages.
  5. You will find it much easier to learn other programming languages.

    A lot of popular programming languages are based on C (and C++, considered superset of C programming with OOP features). If you know C, you will get a head start learning C++.

    Languages like C# and Java are related to C and C++. Also, the syntax of JavaScript and PHP is similar to C.

    If you know C and C++ programming, you will not have any problem switching to another language.

Reasons not to learn C programming

You can create awesome softwares without knowing C programming at all. Jeff Atwood, one of the creators of Stackoverflow.com, apparently doesn’t know C and Stack Overflow is a really good web application.
If you are busy and don’t want to invest time on something that doesn’t have direct effect on your day-to-day work, C programming is not for you.
Also, if you are a newbie and want to start learning programming with an easier language (C is not the easiest of language to learn), you can start with Python.

Verdict on whether to learn C programming or not

For newbie:
For many, C programming is the best language to start learning programming. However, if you want to start with an easier language which is clean and easier to grasp, go for Python.
For experienced programmers:
It’s not absolutely essential but there are perks of learning C programming.
Don’t leave your current project immediately (I know you won’t) to learn C. You can learn it when you have free time and want to expand your programming skills.
I believe, it’s not necessary to learn C immediately. However, you should learn C eventually.

Compile and run C programming on your OS

There are numerous compilers and text editors you can use to run C programming. These compilers and text editors may differ from system to system.
You will find the easiest way to run C programming on your computer (Windows, Mac OS X or Linux) in this section.


Run C program Online

Run C Programming in Mac OS X

Run C programming on Linux

Run C Programming in Windows (XP, 7, 8 and 10)

To run C Programming in Windows, download a software called Code::Blocks. Then, write C code, save the file with .c extension and execute the code.
To make this procedure even easier, follow this step by step guide.
  1. Go to the binary release download page of Code:Blocks official site.
  2. Under Windows XP / Vista / 7 / 8.x / 10 section, click the link with mingw-setup (highlighted row) either from Sourceforge.net or FossHub.
    Download Code::Blocks in Windows
  3. Open the Code::Blocks Setup file and follow the instructions (Next > I agree > Next > Install); you don’t need to change anything. This installs the Code::Blocks with gnu gcc compiler, which is the best compiler to start with for beginners.
  4. Now, open Code::Blocks and go to File > New > Empty file (Shortcut: Ctrl + Shift + N)
    Create empty file in Codeblocks
  5. Write the C code and save the file with .c extension. To save the file, go to File > Save (Shortcut: Ctrl + S).
    Important: The filename should end with a .c extension, like: hello.c, your-program-name.c
    Create file with .c extension in Codeblocks to run C programming
  6. To run the program, go to Build > Build and Run (Shortcut: F9). This will build the executable file and run it.
If your program doesn’t run and if you see error message "can't find compiler executable in your search path(GNU GCC compiler)", go to Settings > Compiler > Toolchain executables and click Auto-detect. This should solve the issue in most cases.

The fun begins: Your first C program

You will learn to write a “Hello, World!” program in this section.

Why “Hello, World!” program?

“Hello, World!” is a simple program that displays “Hello, World!” on the screen. Since, it’s a very simple program, it is used to illustrate the basic syntax of any programming language.
This program is often used to introduce programming language to a beginner. So, let’s get started.
#include <stdio.h>
int main()
{
    printf("Hello, World!\n");
    return 0;
}

How “Hello, World!” program works?

Include stdio.h header file in your program.
C programming is small and cannot do much by itself. You need to use libraries that are necessary to run the program. The stdio.h is a header file and C compiler knows the location of that file. To use the file, you need to include it in your program using #include preprocessor.
Why do you need stdio.h file in this program?
In this program, we have used printf()function which displays the text inside the quotation mark. Since printf() is defined in stdio.h, you need to include stdio.h.
The main() function
In C programming, the code execution begins from the start of main() function (doesn’t matter if main() isn’t located at the beginning).
The code inside the curly braces { } is the body of main() function. The main() function is mandatory in every C program.
int main() {
}
This program doesn’t do anything but, it’s a valid C program.
The printf() function
The printf() is a library function that sends formatted output to the screen (displays the string inside the quotation mark). Notice the semicolon at the end of the statement.
In our program, it displays Hello, World! on the screen.
Remember, you need to include stdio.h file in your program for this to work.
The return statement
The return statement return 0; inside the main() function ends the program. This statement isn’t mandatory. However, it’s considered good programming practice to use it.

Key notes to take away

  • All C program starts from the main() function and it’s mandatory.
  • You can use the required header file that’s necessary in the program. For example: To use sqrt() function to calculate square root and pow() function to find power of a number, you need to include math.h header file in your program.
  • C is case-sensitive; the use of uppercase letter and lowercase letter have different meanings.
  • The C program ends when the program encounters the return statement inside the main()function. However, return statement inside the main function is not mandatory.
  • The statement in a C program ends with a semicolon.

Teach Yourself to Code in C

Learn C from Programiz

Programiz offers dozens of tutorials and examples to help you learn C programming from scratch.
The tutorials are designed for beginners who do not have any prior knowledge of C programming (or, any other programming languages). Each tutorial is written in depth with examples and detailed explanation.
If you are serious about learning programming (any programming language including C), you should get yourself a good book. 
Granted, reading a 600 page long programming book takes a lot of time and patience. But, you will get the big picture of programming concepts in the book which you may not find elsewhere.
Here are 3 books we personally recommend.

Learn C programming, the right way

Fact: You cannot learn C programming in a day. You might have difficulty grasping the important concepts if you try to learn C programming faster.  
If you just learn the syntax and dive in, your C code may work but you’ll not end up learning C programming the right way.,  

Don’t just look at the example code, run it in your system

Programiz has dozens of examples that will help you understand C programming. However, if you are reading it like a novel without running it in your system, you are doing it wrong.
If you want to learn a new feature of C programming, try to write code related to that feature. If you can’t, copy code from Programiz and run it in your system. Then, try to understand it. Once you understand it, modify the code, make it different and run it again.

Learn to use a Debugging tool

A debugging tool or debugger is a software (that’s already available in IDE) which allows programmers to stop a program at any point and helps to detect and correct errors.
When you have bugs in your program, rather than scratching your head to find the bug, you can use debugger to stop program at any point and find the value of variables to detect the bug. 
Knowing how to use a debugger is an important skill that every programmer should learn. 

Learn the feature the way it is intended 

Imagine a situation: It’s possible to solve a problem with an array. Also, you can solve the same problem with a structure. Technically both are correct, which method will you use?
To answer this question, you should have a good knowledge of when to use an array and when to use a structure.
Suppose, you are switching to C from a different language, let’s say C#. You do not want to write C# style code with C syntax in your C program.

Join C communities

Once you get the hang of writing simple C programs, join online communities and forums. You can help other programmers where you can and ask for help when you are stuck. 

Always follow good programming practice     

Good programming practice are the informal rules which can improve quality and decrease development time of the software.
Some of the programming practices mentioned here are valid in all programming languages whereas some are valid only for C programming. 
Be consistent with the formatting. 
The number of spaces you use in the program doesn’t matter in C. However, that doesn’t mean you should use different number of spaces at different places. Also, use proper indentation so that the code is easier to understand. 
Use one statement per line.
What’s wrong with the following code?
int count; float squareRoot = 10.0; printf(“Square root = %f”, squareRoot);
Actually, the code is perfectly valid. But, wouldn’t this be better:
int count;
float squareRoot = 10.0;
printf(“Square root = %f”, squareRoot);
The goal here is to write code that your fellow programmers can understand.
Naming convention and Consistency!
Give a proper name to variables and functions and be consistent with it. 
int a, b;
Here, a and b are two variables and I have no idea what they do. Instead you can choose name like:
int counter, power; 
Also, follow a convention while naming. For example:
int base_number, powerNumber;
Both conventions: using _ to separate words and using capital letter after first word is popular. However, don’t use both in one program; choose one and be consistent with it.
Start Habit of Using Comments
Comments are part of code that compiler ignores.
You can use comments in your program to explain what you are trying to achieve in your program. This helps your fellow programmer to understand the code.
You can use comments in C programming by using //. For example:
// My first C program

#include <stdio.h>
int main()
{
    printf("Hello, World!\n");   // displays Hello, World! on the screen
    return 0;
}
“Commenting your code is like cleaning your bathroom - you never want to do it, but it really does create a more pleasant experience for you and your guests.”

— Ryan Campbell
We at Programiz think C is a terrific language to learn.
If you are a beginner, it’s a good language to start learning programming. And, if you are a professional programmer with a tight schedule, learn it at your leisure; it will certainly help your brush up on programming basics.

C Program to Find the Sum of Natural Numbers using Recursion

C Program to Find the Sum of Natural Numbers using Recursion

Example to find the sum of natural numbers by using a recursive function.


Sum of natural numbers using recursion





The positive numbers 1, 2, 3... are known as natural numbers. The program below takes a positive integer from the user and calculates the sum up to the given number.
You can find the sum of natural numbers using loop as well. However, you will learn to solve this problem using recursion here.

Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int addNumbers(int n);

int main()
{
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);
    printf("Sum = %d",addNumbers(num));
    return 0;
}

int addNumbers(int n)
{
    if(n != 0)
        return n + addNumbers(n-1);
    else
        return n;
}

Output
Enter a positive integer: 20
Sum = 210
Suppose the user entered 20.
Initially, the addNumbers() is called from the main() function with 20 passed as an argument.
The number (20) is added to the result of addNumbers(19).
In the next function call from addNumbers() to addNumbers(), 19 is passed which is added to the result of addNumbers(18). This process continues until n is equal to 0.
When n is equal to 0, there is no recursive call and this returns the sum of integers to the main() function.

C Program to Convert Binary Number to Decimal (example)

C Program to Convert Binary Number to Decimal and vice-versa

In this example, you will learn to convert binary number to decimal and decimal number to binary manually by creating a user-defined function.

Example 1: Program to convert binary number to decimal

#include <stdio.h>
#include <math.h>
int convertBinaryToDecimal(long long n);

int main()
{
    long long n;
    printf("Enter a binary number: ");
    scanf("%lld", &n);
    printf("%lld in binary = %d in decimal", n, convertBinaryToDecimal(n));
    return 0;
}

int convertBinaryToDecimal(long long n)
{
    int decimalNumber = 0, i = 0, remainder;
    while (n!=0)
    {
        remainder = n%10;
        n /= 10;
        decimalNumber += remainder*pow(2,i);
        ++i;
    }
    return decimalNumber;
}

Output
Enter a binary number: 110110111
110110111 in binary = 439
Visit this page to learn, how to convert decimal number to binary.

Example 2: Program to convert decimal number to binary

#include <stdio.h>
#include <math.h>
long long convertDecimalToBinary(int n);

int main()
{
    int n;
    printf("Enter a decimal number: ");
    scanf("%d", &n);
    printf("%d in decimal = %lld in binary", n, convertDecimalToBinary(n));
    return 0;
}

long long convertDecimalToBinary(int n)
{
    long long binaryNumber = 0;
    int remainder, i = 1, step = 1;

    while (n!=0)
    {
        remainder = n%2;
        printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, remainder, n/2);
        n /= 2;
        binaryNumber += remainder*i;
        i *= 10;
    }
    return binaryNumber;
}
Output
Enter a decimal number: 19
Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary