Sunday, July 22, 2012

Lecture 2:- Our First C++ Program

So lets start our programming journey from this lesson. I'll not go into the history of languages, but if you are interested, you can use google.

Today we'll see our first C++ program to get familiar of basics of compiler and C++ syntax. We'll use an open source C++ compiler "Dev C++". You can download it from , Its completely free. Now first have a look at the following program, then I'll explain it for you.


The first line of our code consists off "#include". This is a preprocessor directive. #include isn't the C++ statement, but its an instruction for the compiler. It asks compiler to include the content of the file mentioned in "<>". So when compiler compiles the code, it also includes the contents of the "iostream.h" file. IOStream.h is a header file saved in installation directory of compiler. It a library file having definition of Input and Output streams. It means that if we write or output something on the computer screen, or take or read input from the keyboard, we'll use this file. Because the functions that write on the screen or read from the keyboard are defined in this file.

The second line is main(). main is special function in C++. C++ program start executing from this point. Its the first step or first stair of our program. {} are called body of the main function. (We'll discuss functions later in detail).

Saturday, July 21, 2012

Lecture 1:- What is Programming

Welcome to Introduction to programming series. In this program I am going to teach you computer programming. We'll talk about the concepts (Basic to advance). We'll use C++ to explain programming concepts and to give examples. But these concepts are generic and can be implemented or used with any language. So should we start now????????

So guys what is the programming. First of all this is very basic question that we will answer. Programming is telling the computer what to do. We perform some task using computer and through programming we ask computer that perform this task for us. We tell computer by using a specific language (Programming Language), which computer understands. We write statements of that language and collection of that statements is called program. But this isn't precise definition of the program.

"Program is a precise sequence of steps to perform a particular task".

So here we will look at few things in little detail. "Precise sequence" means we have to do one task first and then do second task. Their order cannot be interchanged. So all steps must be performed in a sequence. By changing this sequence we cannot achieve the desired output.

Why we learn programming :- Now some people might ask this question. We learn programming to solve real world problems. You can see huge amount of application today that are helping us in almost every field of life. In scientific research, education, office work, medical and many many more field there are computer being used to solve problems and to facilitate us, and inside those computers programs are running. Of course there are pretty nice code generators are available today but they are very generic and cannot provide exactly what e want.

Keep in mind that programming is a creative activity. Its an art, so you must develop your analytic and critical thinking and creativity. When you are writing program, keep following points in mind.

Pay attention to details:- What does this means, you can't be vague. You should be very clear about what you are doing. Keep every aspect in your mind. Don't miss any minute detail or point. You must sure what you are doing. If you are not 100% sure, you can't create.

Computers are stupid:- They do not do anything on their own. They do what we ask them to do. So don't ever suppose "Oh computer will do the rest of things". Computers require exact input every time. They are not like humans where you ask you r friend "give me your pen" or "pen please" or just "pen" and his/her response is always same. This isn't the case with computers.

Re usability:- Its another important aspect in programming. When you program always think about to reduce your effort, time and money. So when write program, write in a way that it can be re used easily (make functions and classes).

Comment the code:- Always comment the code and take notes. Because you will forget your logic after few days or months. In that time you r comments will help you. Otherwise you have understand you code again and this will be time consuming.

ArrayList in Java

Last time we discussed array in java and i told you that its a fixed size data structure. You have to tell the compiler the size of array. But what if you don't know how many data item you will have in future. The arralist is the answer. It is a dynamic data structure. You don't need to tell the size, just declare it and keep adding the item in arraylist. It grows or shrinks as you add or remove item from arraylist.
In java to use arraylist you must import the java.util package. Here is how you declare the arralist.

ArrayList al = new ArrayList();

Arraylist has many methods, Here I am telling few useful ones.

add():- This adds an item to arraylist. In () or as arguments we provide the element to be added. Yon can add as many item as you want.

get():- This method is used to retrieve back items from the arraylist. In () we mention the index of the arraylist (as you studied in array). We tell the locationof element and it sends the item back to us.

remove():- This item is used to delete an arraylist item. In () again we supply the index or location. After removal the arraylist gets shrink.

int size():- This method tells the size or number of arraylist items.

You can add the object of any class in arraylist too. Here i am using Student class which we are using through out our course.

Student S1 = new Student("mike", 20);
Student S2 = new Student("rachel", 22);

al.add(S1);
a2.add(S2);

Its very simple and fair to use arraylist and its methods. Another useful method is to check whether arraylist is empty or not. Ths "isEmpty()" method can be used. This method returns true or false according to arraylist condition.
So with this our lecture ends. Bye

Friday, July 20, 2012

Arrays in Java

Array is a collection of variables or its a bunch of memory locations, you can say in simple word. Array is a very basic data structure, can have multiple locations or memory slots where we can keep our data. For example if create an integer variable, you can keep one number in it. But what if want to store 5 or 20 or 100 different numbers. Answers is the array. Array has a fixed size, it means if you have declared an array of size 100, you can change it to any other size after creation. We use a number called "index of array" to access different elements or members of the array. This index starts from 0, so in we want to use 3rd element of the array, we will use index value 2. The each location is one element of the array. So lets see how to declare an array.
There are few ways to declare an array.

int[] myArray;
int myArray[];
int myArray[] = new int[4];

you can give the size of array in brackets as I did in third example, or leave it open and define the size later like this.

int myArray[];
myArray[] = 12,33,544,71;

This array will now confirmed as 4 location array.

Now if you want to use array elements in your program, you can use following method.

System.out.println(myArray[2]);

This will print the third element of the array on screen. But what if want to print 1000 elements of the array. Would you write 1000 lines of System.out.println. No we will use for loop as follows.

for(int i = 0; i < 1000; i++)
{
System.out.println(myArray[i]);
}

Same technique can be used to put data in array. You must do the exercise yourself for better learning.
Array has a drawback of having fixed size. In next lectures we will discuss some other data structures that can be re sized. So stay with us.

Thursday, July 19, 2012

Garbage Collection in Java

In C++ when we create an object using "new" operator, the memory is allocated for this object and we use it in our program. When we think that we do not need this object anymore, we return this memory to the heap and hence this memory is available for other applications (programs). This operation is done by using "delete" operator in C++. But if we don't delete this object and make it unreferenced, then we will never get this memory back until we restart our computer. Because it is allocated for our program and no other program can use it until we free it. And if this process of allocation and not returning back is in loop, then after sometime our memory will get finished and computer will stop responding. The unavailability of this unreferenced memory is called memory leak. It is programmer's responsibility to free unused memory for other applications.
Java frees the programmer from this responsibility. The JVM (Java Virtual Machine) takes this responsibility. It look after some time for unreferenced memory and if find any memory locations, it sent back them to heap. Now lot of problems are solved with this technique. This process is called garbage collection. The Garbage collector of java runs and checks, if there is any unreferenced memory is there left by any java program and makes it free for other programs.
Garbage collector runs when it feels that most of CPU resources are free. If there are many heavy applications are running there, then garbage collector will not run. Anyway programmer is free now. GC (garbage collector) runs automatically but you can request to run GC to JVM. Your request will not instantly invoke the GC, again it depends on CPU resources and some other factors.
To request for invoking the gc Systemgc() method is used.

Wednesday, July 18, 2012

Constructors in Java

Constructor is also a method of class like other methods. But it is only invoked or called when an instance or object of the class is created. When memory is allocated successfully for that object, a constructor is called. It is used to initialize the attributes or member variables for that object. For example if we have a student class and want to assign 25 marks initially, when user didn't entered the marks. We will use constructor to assign this default value.
1. Constructor must have the same name as the class have.
2. Constructor must NOT have any return type. It even can't be void. So just write public or private before the name and then class name and the (). In Brackets you can have parameter.
3. If you don't write any constructor, a default constructor is called. That default constructor is always be parameter less and it will do nothing.
4. You can more than one constructor also. For example one constructor takes no arguments, second takes one and third takes two arguments. This is called constructor overloading.
Here are examples of constructor.

public class Student{

public Student()
{

}

public Student(int age)
{

}

public Student(int age, int marks)
{

}
}

I have not shown the rest of the code of class. It same as the previous one. Now when you create the object of the class, one of these constructor is called depending upon the number of arguments. See below examples.

Student S1 = new Student(); // first parameter less constructor will be called.

Student S2 = new Student(20); // second constructor will be called.

Student S1 = new Student(20, 78); // third constructor will be called.

That's the end of today's class. Next we will discuss garbage collection INSHALLAH.

Tuesday, July 17, 2012

Access modifiers in Java

In last lesson we were talking about classes and we have created four variables or properties of the class (did you remember that). We have used the word "private" before them. What was that. This was the access modifier. What we are asking to our program is that no one can use this variable or properties except Student class. So only Student class methods have access to use them. The benefit of this privacy is security and this technique is less prone to error. Changes and up gradation is easy. Because you don't need to worry about the other class and their methods.
Java has two other access modifier too. Which are "public" and "protected". All three keyword can be used with classes, methods and class members (class variables). By using these you can restrict the user of the class to use only provided methods to access them.
If you don't use any modifier then default access rule will be used. That is you can use that member in same package anywhere.

Public: If you use public keyword, it will be available for all other class that are included in your project. The use of public in class members is not appreciated so you must avoid this practice.
Private: As the name indicates, private member are only available to the same class member functions or methods.
Protected: Protected members of the super class are available to the sub class of the same package.

So guys these were the access modifiers. If you have questions or suggestions please do write us.

Classes in Java

In object oriented programming class is struct. It is used to make object or instances of some kind. For example if you have a class having the name "Car", then it will create cars as its objects or instances. In simple word class in factory which makes objects. Class itself can't be used in programming without creating its objects. We create objects and use them in our programs. For example if we have a program that calculates the grades of the student. It takes marks achieved by them and give some grade as its output. We have written a class named "Student". Then we will create the objects of this class and every object is assigned unique attributes or properties. So lets see an example of class to understand it.

public class Student {


}

This is very simple way of using classes in your programs. Now we have a class it will create object having no properties and operations. So now we will define the properties of this class. Think about the properties a student can have....There are lot of things a students can have like name, roll No or ID, father name, address, class or year,grades, fee, number of sisters and brother and many more things. But we will use only marks and grades so we will not touch other things. See the code below.


public class Student {
private int totalMarks;
private int totalSubjects;
private int average;
private String grade;
}

Now we have defined the required properties of the student. Now we define methods or functions of the class to use these properties.

public class Student {
private int totalMarks;
private int totalSubjects;
private int percentage;
private String grade;

public void calculateAverage()
{
percentage = totalMarks/totalSubjects;
}

public void display()
{
System.out,println(totalMarks);
System.out,println(totalSubjects);
System.out,println(average);
System.out,println(grade);
}
}

Now we have two methods of the class and can use them to perform our task. Of course there can be many other methods of the class but to keep it simple i have just defined two. Now we will use this class in our main program.

public class StudentTest{

public static void main(Stirng[] Args)
{
Student s1 = new Student();
Student s2 = new Student();
s1.display();
s2.display();
}
}

s1 and s2 is the object or variable of this class. They are separate students and can have different properties or values of its variables.
So that was the today's lesson. Hopefully you have enjoyed it. Please do lot of practice of this lesson because class is the most important or key element in object oriented programming. So its time say good bye. Stay with us..........

Monday, July 16, 2012

Do-While Loop in Java

Welcome to my next tutorial. Today i am gonna teach you the Do-While loop in java. This is another variation of loops in java. But unlike while loop this do-while loop will execute at least once, no matter the condition is false before reaching to the loop. Because it do the work before and check the condition after doing work. But in while loop the condition is checked first and then decision is taken to execute the loop or not. Lets see a code example.

public class WhileLoopTest {

public static void main(String[] Args)
{
int counter = 0;
do
{
System.out.println("Value of the counter is " + counter);
counter++;
}while(counter < 5);
}
}

So you can see the above code. Its almost similar to previous two loops examples. But here we have do-while loop. As you can see first we are asking the program to do first and then we are checking the condition. So if the condition is false the code have been run once. And don't forget to put a semicolon after the condition(). Most of the guys do this syntax mistake.
Here is the output of the code.

Value of the counter is 0
Value of the counter is 1
Value of the counter is 2
Value of the counter is 3
Value of the counter is 4

And this is the end of our class. Be ready for the next class. Bye

While Loop in Java

Hi guys. Today we are gonna look at while loop in java. In while loop again we have a counter and a stop condition like for loop. The code shown below explains this.

public class WhileLoopTest {

public static void main(String[] Args)
{
int counter = 0;
while(counter < 5)
{
System.out.println("Value of the counter is " + counter);
counter++;
}
}
}

in this code we have a counter variable again. But the counter is incremented in {} or body of the while loop. every time while loop check the condition inside the (). If the condition is true, it stops the loop and execute the next statement after "}" of the loop. An if condition is false it keeps executing the code inside the {}. Here is the output of the our program.

Value of the counter is 0
Value of the counter is 1
Value of the counter is 2
Value of the counter is 3
Value of the counter is 4

Hope you have enjoyed today's lesson. Please feel free to ask questions and problems. I'll be happy to answer. So see in next class.

Sunday, July 15, 2012

For Loop in Java

Loops are the iterations. That means we can repeat the code for several number of times using loop. But we can write the same code ten times and it will run ten times. Yeah we can do this but this make our code more lengthy, so isn't that good that we write the code once and run it hundred or thousands of times. It saves out time and effort and makes our code smart. So lets see an example

public class ForLoopTest {

public static void main(String[] Args)
{
int counter = 0;
for(counter = 0; counter < 5; counter++)
{
System.out.println("Value of the counter is " + counter);
}
}
}

so friends here we have a variable counter. As its name indicates that it will count our iterations. Initially this counter is set to zero. In for loop we have again initialized the counter to zero. next we have a check statement or check point. That will ensure that the loop runs exactly number of times that we want. So we have set this limit to 5. In the next step we have incremented the counter variable by one using ++. Now every time when loop will run counter will be incremented by one and on reaching a certain limit(in our case 5), the loop will stop.
Here is an important point to remember that this loop will run 5 times. We have set the limit less than 5 but initially was 0. So it run from 0,1,2,3,4 (five times). Here is the output of the code

Value of the counter is 0
Value of the counter is 1
Value of the counter is 2
Value of the counter is 3
Value of the counter is 4

So guys this was out new lesson. Stay tuned to our blog and get new tutorials daily.

Switch statement in Java

Switch is another flavor decision in Java. It depends on your problem whether you use IF else of switch. So lets quickly see an example and try to under stand what the switch actually is.

public class SwitchTest {

public static void main(String[] Args)
{
int marks = 80;

switch(marks)
{
case 80:
System.out.println("You have got good grades.");
break;
case 60:
System.out.println("You grades are average.");
break;
case 40:
System.out.println("Poor.");
break;
default:
System.out.println("you didn't told ur marks");
break;
}
}
}

So as you can see in above example we have again the same old variable "mark". And in the next line we have "switch" statement. In the () we have our variable. Next {} have the cases of switch statement. Cases are the conditions. We ask our code that if our variable has this value then do this. For example in above code we have asked if marks have the value of "80" then print "You have got good grades.". And the there is a break statement which will take us out of the {} of the switch. If none of the statement is true then a default code or statement will be executed.
One thing should be remembered that after the case we have ":" NOT ";". So be careful or compiler will give syntax error.
So how was this lesson. Hopefully you have enjoyed it. But if you have any problem please write us. We'll be happy to help you. Bye

IF ELSE or Condition in Java

Like other programming languages Java also provide conditional structures like IF, IF ELSE, IF ELSE IF or SWITCH. They all are similar to C++ in syntax. Here is a simple example on IF ELSE structure.

public class IfElse
{
public static void main(String[] Args)
{
int marks = 82;
if(marks > 80)
{
System.out.println("A+ Grade");
}

if(marks < 80)
{
System.out.println("Grade is not A+");
}
}
}

Here I have declared a variable "marks" which will have the value of marks achieved by some student. Now see the structure of the IF-ELSE statement. First we have "if" and then in () we have a condition. If this condition is true the next block of code in {} will get execute. And if that condition is false the block of code in {} next to else will get executed. Here we have marks = 82 so the first block of the code will execute and "A+ Grade" will be displayed on the console.
So this was our today's lesson. If else is very basic but very useful structure. So understand it and have lot of practice. We will use it a lot in our next codes. So stay with us for next lesson.

Saturday, July 14, 2012

Variables in Java

Here we will learn how to declare variables and use them in our programs. Variable is a memory location where we store the numbers, floats, string and our objects etc. We give some name to those memory location for better understanding and to easily remember them. For example if you want to store the marks of the students in memory, you can declare or make a variable having the name "marks". Now when you use the name marks in your program, this will mean the memory location where you have stored marks. Now lets see and example.

public class Variables
{
public static void main(String[] Args)
{
int studentID;
studentID = 2001;

String name = "Ahmad Faraz";

float cgpa = 3.20;

System.out.println("My name is " + name);
System.out.println("My ID is " + studentID);
System.out.println("My CGPA " + cgpa);
}
}

Here we are using the class Variables. So don't forget to save this file with the name "Variables.java". We have the same old "main" method. But this time in main method we are using three different variables. The first variable is the integer type. As we have written "int" before it. The variable "studentID" will store only integers in it. Here we have declared "studentID" in first line and then initialized it in second line. But in next variable "name" I have declared it and initialized in the same line. You can use the both method. It depends on your preference. The thirs variable is float type "cgpa". Now see it depends on the situation that which type we will use. Floating point numbers can be stored in integer type variables and compiler will NOT generate any error. It your responsibility to check such issues. Because integer variable will skip the numbers after the decimal point and you will get wrong calculations and results. So be careful in selecting the type of the variable.
In next three line the same old stuff, we are gonna print three variables on the screen. as you can see the we have just written the variables names to print them. But wait....whats "+" doing here. Did you noticed....good..... it is doing concatenation. It means joining to variables values or two data elements. Here first we have written text in "" and the used + and then variable name. So println will join the both thing and print them on the screen.
So this was our variables lesson. Hope you have enjoyed. See you next time with some new stuff, stay with us..........Bye

Hello World Program in JAVA

So here is our first program in Java. This will just print "Hello World" on the console. Save this code in text file and name the file "HelloWorld.java". Because in Java a file must have the same name as the public class. Lets review the code

public class HelloWorld
{
public static void main(String[] Args)
{
System.out.println("Hello World");
}
}

This is very simple code. I have use indentation in code so that it can be easily understood. In first line of code, We have defined the public class having name "HelloWorld". Inside this class we have only one method "main". Every java program must have at least one function the "main" function. When we execute the program, it starts from "main" function. In "main" function declaration we have written "public", which means it is a public method NOT private or protected. Next we have written "static". This means that it's a static method and doesn't needs to be belonged with any object. void means it will NOT return any thing. This method takes "String[] Args" in arguments. You can give your program arguments and use then from this array. In this method we are just printing a string. "System.out.println" will print the "Hello World" on the screen for us. "println" will print a line and cursor goes to next line. Here we can use "System.out.print" too. In "print" only the cursor stays on the same line.
So this was our first code and I hope you have enjoyed it. Thanks for being with us

Wednesday, February 8, 2012

Classes inside Classes

In C language, structures can be defined inside structures, Similarly in C++, we can
have structures or classes defined inside classes. Classes defined within other classes are called nested classes.
A nested class is written exactly in the same way as a normal class. We write its data members, member functions, constructors and destructors but no memory is allocated for a nested class unless an instance of it is created. C++ allows multiple levels of nesting. Importantly, we should be clear about the visibility of the nested class. If a class is nested inside the public section of a class, it is visible outside the outer (enclosed) class. If it is nested in the private section, it is only visible to the members of the outer class. The outer class has no special privileges with respect to the inner class. So, the inner class still has full control over the accessibility of its members by the outer class. Interestingly, the friend operator can be used to declare enclosed class as a friend of inner class to provide access to inner class’s private members. This operator is used in the same way as we use it for other classes that are not nested. We can also make the inner class to access the private members of enclosed class by declaring the inner class as a friend of outer class. The reason of nesting classes within other classes is simply to keep associated classes together for easier manipulation of the objects.

Templates

There are two different types of templates in C++ language i.e.’ function templates
and class templates. Before going ahead, it will be sagacious to know what a template
is? You have used a lot of templates in the childhood. There are small scales being
marketed at the stationary shops having some figures on them like circle, a square,
rectangle or a triangle. We have been using these articles to draw these shapes on the paper. We put the scale on the paper and draw the lines with the pencil over that figure to get that shape. These engraved shapes are generally called stencils. But in a way, these are also templates. We may also take these ‘cut-outs’ as sketches. So a template is a sketch to draw some shape or figure. While drawing a special design, say of furniture, we develop a template for this, which is not an actual piece of furniture. We try that its shape should be like the outline. Later,the cut out prepared out of wood in line with the template, is actual piece of furniture. We can think of making a triangular template and then drawing it on a piece of wood and shaping it into a triangle. We can use the same template and put it on a piece of metal and can cut it into a triangle and so on. In a way, that template is allowing us the reuse of a certain shape. This is the concept we are going to try and build on here.

Hi everyone

Hellow everyone........welcome to my blog. I am going to share some programming tutorials here with you. They are totally free and you can learn and share with your friends too. If you have any suggestions, please mail me and if you need any tutorial that I haven't shared here yet, feel free to ask and I'll try to provide that here. So Lets start learning how to program.