FoodForFutureGeeks

Sunday, 15 April 2012

Introduction to pointers

What is a pointer?

A pointer is a special type of variable that is used to hold the address of another variable or a pointer,pointer can be used to manipulate the value stored at that address.
Often it may be required to manipulate the value stored at a particular address, this is not possible by using normal variables, so we need pointers.(Read article on Pass by value&Pass by reference in general programming.)

Declaring a Pointer: 

Pointer variables are declared by prefixing variable name with * symbol.
ex: int *ipointer;
float *fpointer; etc


Assigning Value to a pointer/pointing it to a variable:

a pointer can be assigned the address of a variable as follows:
int *ipointer;
int k=15;
ipointer=&k;
the & operator is used to obtain the address of variable k.

Dereferencing a pointer/obtaining the value pointed by pointer:

this can be done by prefixing the pointer with *.
ex:
float *fpointer;
float  f=10.00;
fpointer=&f;
//use * to obtain the value pointed by pointer
printf("value pointed by fpointer:%f",*fpointer);

Important Note:

 * is used in two places when dealing with pointers
1. int* ip ; // here it means u are declaring a pointer to an integer.
2. int k=*ip; or printf(“%d”,*ip);  here it means dereferencing or fetching the value stored at the address pointed by pointer.

Sample Program:

#include<stdio.h>
void main()
{
//declaring a pointer
int *pointer;
int k=10;
//storing the address of variable k in a pointer
pointer=&k;
//the symbol & gives the address of variable k
printf("Getting the value From pointer\n");
//here * is used to dereference or obtain the value pointed by pointer
printf("K:%d",*pointer);
}

Two dimensional pointers:

two dimensional pointers are pointers to pointers or they can be considered as an array of pointers

ex1:pointer to a pointer 

char* str="hi im learning pointers";
char** strp=&str;
printf("%s",*strp);

here strp acts as a pointer to str which is pointing to the starting address of string "hi im learning pointers"

ex2 (complicated only for C++ ):

This concept is very useful when an array has to be populated using pass by reference
#include<iostream>
#include<conio.h>
void populatearray(int** mainarray,int* count)
{
    int a[]={1,2,3,4,5};
    //create a single dimension array for storing the values
    int* myarray=new int[5];
    //assign the values to be stored to the array
    for(int i=0;i<5;i++)
    {
        myarray[i]=a[i];
    }
    //store the count in the adress pointed by formal parameter
    *count=5;
    //store the array in the adress pointed by formal parameter
    *mainarray=myarray;
}
void main()
{   //the main array where values have to be stored
    int* arraymain=0;
    //count of elements
    int maincount=0;
    //pass the adess of pointer to array, adress of counter
    populatearray(&arraymain,&maincount);
    //check whether pass by reference has worked
    printf("The array Elements:\n");
    for(int i=0;i<maincount;i++)
    {
        printf("\n%d",arraymain[i]);
    }
    getch();
}

Saturday, 14 April 2012

Need for C++/Features of C++

Object Oriented:

C++ is object oriented, unlike C which focuses mainly on Function/procedure based approach to solve problems.The object oriented approach allows us to model the real world objects/scenarios by creating objects/instances which combine both the properties and behavior of real life objects.

ex:

Consider an electric bulb:
it has two states on,off, the behavior is it can be turned on to glow, turned off.

class bulb
{
int state=0;
//state 0 indicates bulb is off, 1 indicates it is on
void turnon()
{
  //if it is off turn it on
 if(state==0)
  state=1;
}
void turnoff()
{
  //if it is on turn it off
 if(state==1)
    state=0;
}
};//end of class bulb

Encapsulation:

encapsulation literally means to hold something, through the concept of classes, C++ provides for encapsulation of the Data members and functions , that is  the data members and the functions are bound together by the class.

In the Bulb class, only the functions turnon() and turnoff() can change the state of the bulb, it is not possible to change the state directly.


void main()
{
//declare an object
bulb b=new bulb();
//refer article on declaration of objects,constructors for more details
//change the state of bulb to on
b.turnon();//valid
state=1;//invalidgives an error state can be changed only through the member functions.
}

Abstraction:

abstraction is hiding the data, abstraction hides the finer implementation details and allows the user to focus on the functionality required.
ex:
an end user wants the bulb to be turned on, he can just call the turnon() function, the data related to state of bulb which causes it to turn on is hidden from the user.

refer the source code given for Encapsulation, same holds good for abstraction.

Note:

Abstraction and encapsulation go hand in hand, they are two closely related terms, often they are confused.

Polymorphism:

polymorph means a single entity existing in many forms, C++ supports for the entities to exist in many forms ie each form has a different behavior.
ex:
Imagine an electric bulb capable of giving different colours of light depending on input voltage.

function overloading and overriding are two standard examples of polymorphism in C++.

Dynamic Memory Management:

C++ supports for dynamic memory allocation and deallocation, this can be done by using new and delete keywords.The requires blocks of memory are assigned during run time, a combination of dynamic memory allocation and deallocation after its not needed can make the program more efficient in terms of memory usage.

Inheritance:

Inheritance is a concept which enables a child class to inherit the features from a parent class ie it provides for code reusability, the child class inherits the functions and data members from the parent class.
ex:
consider the shape class as parent of all geometric shapes.


here circle,square,triangle, inherit the draw and erase functions from the parent class shape.







Thursday, 5 April 2012

Functions Pass By Value & Pass By Reference

We can pass arguments to a function in two ways:

Pass by Value:

Only the value of the variable is passed on to a function, this value is stored in a formal parameter of function, any manipulations done by the function will not be reflected back to the actual variable.

Pass by Reference:

Here the address of the variable is passed, this will be received by the formal argument which is a pointer, the formal argument acts as a reference to the original variable, so any changes made using the function will be reflected back to the actual parameter.

Example program:
Pass by Value


#include<stdio.h>
//function declaration
void add(int var1,int var2,int result);

//main function
void main()
{
 int result=0,var1=10,var2=20;
 printf("before passing by value:\nresult:%d",result);
 //pass the variable result by value
 add(var1,var2,result);
 printf("\nafter passing by value:\nresult:%d",result);

}
//function definition for add function
void add(int var1,int var2,int result)
{
result=var1+var2;
}

output:

before passing by value:
result:0
after passing by value:
result:0


we see that even though in the add function we are storing the sum of var1,var2 in result its not reflected in main function as the variables are passed by value.

Pass by Reference:


#include<stdio.h>
//function declaration
void add(int var1,int var2,int* result);

//main function
void main()
{
 int result=0,var1=10,var2=20;
 printf("before passing by Reference:\nresult:%d",result);

 //pass the variable result by Reference
 add(var1,var2,&result);
 printf("\nafter passing by Reference:\nresult:%d",result);

}
//function definition for add function
void add(int var1,int var2,int* result)
{
 *result=var1+var2;
}



before passing by Reference:
result:0
after passing by Reference:
result:30

we see that since the result was passed by reference, the changes done in the add function are reflected back to main function.

Figure showing pass by value&pass by reference



Wednesday, 4 April 2012

Structures, Structure pointers

A structure  is a user defined datatype, it is a collection of heterogeneous data types that are supported by default. It is defined by using the keyword struct, the definition has to be terminated by a semi colon.
ex:

struct student
{
char name[15];
int age;
};
structure variables/members cannot be initialized or assigned values during structure definition.

Declaring and accessing structure variables:

structure variables can be declared just like normal integer or float variables,by mentioning the structure name followed by variable name.


#include<stdio.h>
#include<conio.h>
#include<string.h>
//structure definition

struct student
{

char name[15];
int age;
};

void main()
{
//declaring a structure variable
student s;
//accessing the structure members using . operator
strcpy(s.name,"harish");
s.age=15;
printf("student name:%s",s.name);
printf("\n student age is:%d",s.age);
_getch();

}
Structure members can be accessed by using the dot operator as shown in the sample program.

Pointer to a structure:

whenever we are working with structure variables it may be required to pass the structure variables by reference to other functions for performing operations, in such cases we need pointers to structures.Structure pointers can be declared just like ordinary pointers by using * symbol after the structure name or before variable name.
ex: student* s;

Accessing structure members from pointer:

The arrow operator(->) is used to access the structure memebers from a structure pointer, in case of ordinary structure variables we have to use the dot(.) operator to access the structure members but for structure pointer arrow operator has to be used.
ex: s->name;

Sample program to illustrate structure pointers:


#include<stdio.h>
#include<conio.h>

//structure declaration
struct student
{
char name[15];
float marks_sub1;
float marks_sub2;
float marks_sub3;
float average;
float percentile;
};

//user defined function declaration

void setData(student* temp);
void calcAvg(student* temp);
void printData(student* temp);

//main function

void main()
{

int i;

//declare an array of student type variables
student s[5];

for( i=0;i<5;i++ )
{
printf("\nenter the student %d details",i);
//set data collects the student information
setData(&s[i]);

//calculates the average
calcAvg(&s[i]);

}

for( i=0;i<5;i++ )
{

printf("\nstudent %d details",i);
//call print data to print the student details
printData(&s[i]);
}

getch();

}

//function to print data
void printData(student* temp)
{
printf("\n\n***************************************");
printf("\nname:%s",temp->name);
printf("\nsubject1 marks:%f",temp->marks_sub1);
printf("\nsubject2 marks:%f",temp->marks_sub2);
printf("\nsubject3 marks:%f",temp->marks_sub3);
printf("\nAverage marks:%f",temp->average);
printf("\n**************************************");
}

//this function calculates the average
void calcAvg(student* temp)
{
temp->average=(temp->marks_sub1+temp->marks_sub2+temp->marks_sub3)/3;
}

//this function collects the input data
void setData(student* temp)
{

printf("\nenter the name:");
scanf("%s",temp->name);
printf("\n enter the subject1 marks:");
scanf("%f",&temp->marks_sub1);
printf("\n enter the subject2 marks:");
scanf("%f",&temp->marks_sub2);
printf("\n enter the subject3 marks:");
scanf("%f",&temp->marks_sub3);
}


C program using Structures to read and display Student details


#include<stdio.h>
#include<conio.h>

//structure declaration
struct student
{
char name[15];
float marks_sub1;
float marks_sub2;
float marks_sub3;
float average;
};

//user defined function declaration

void setData(student* temp);
void calcAvg(student* temp);
void printData(student* temp);

//main function

void main()
{

int i;

//declare an array of student type variables
student s[5];

for( i=0;i<5;i++ )
{
printf("\nenter the student %d details",i);
//set data collects the student information
setData(&s[i]);

//calculates the average
calcAvg(&s[i]);

}

for( i=0;i<5;i++ )
{

printf("\nstudent %d details",i);
//call print data to print the student details
printData(&s[i]);
}

getch();

}

//function to print data
void printData(student* temp)
{
printf("\n\n***************************************");
printf("\nname:%s",temp->name);
printf("\nsubject1 marks:%f",temp->marks_sub1);
printf("\nsubject2 marks:%f",temp->marks_sub2);
printf("\nsubject3 marks:%f",temp->marks_sub3);
printf("\nAverage marks:%f",temp->average);
printf("\n**************************************");
}

//this function calculates the average
void calcAvg(student* temp)
{
temp->average=(temp->marks_sub1+temp->marks_sub2+temp->marks_sub3)/3;
}

//this function collects the input data
void setData(student* temp)
{

printf("\nenter the name:");
scanf("%s",temp->name);
printf("\n enter the subject1 marks:");
scanf("%f",&temp->marks_sub1);
printf("\n enter the subject2 marks:");
scanf("%f",&temp->marks_sub2);
printf("\n enter the subject3 marks:");
scanf("%f",&temp->marks_sub3);
}

Monday, 2 April 2012

Programming approaches in C,C++

Basically there are two programming approaches in C, C++:
  1. Top Down Approach.
  2. Bottom Up Approach.

Top Down Approach:

This approach is known as top down as the main function is defined at the top, other user defined functions are defined below it.
ex:
//top down approach
#include
//function declaration
int add(int,int);
int sub(int,int);
//main function definition
void main()
{
int sum=0,difference=0,var1=0,var2=0;
printf("enter two variables to calculate the sum:\n");
scanf("%d%d",&var1,&var2);
//call to add function, main function is the calling function
sum=add(var1,var2);
//call to sub function
difference=sub(var1,var2);
printf("sum is:%d",sum);
printf("difference is:%d",difference);
}
//user defined functions are defined below main
int add(int value1,int value2)
{
return value1+value2;
}
int sub(int value1,int value2)
{
return value1-value2;
}

so when a function is called, control goes from top to bottom and returns to top again, ie from main function to the user defined function and back to main function again.


Bottom up approach:

This approach is known as bottom up as the main function is at the bottom and user defined function definitions are at the top.
ex:
//bottom up approach
#include
//user defined functions are defined above main
int add(int value1,int value2)
{
return value1+value2;
}
int sub(int value1,int value2)
{
return value1-value2;
}
//main function definition
void main()
{
int sum=0,difference=0,var1=0,var2=0;
printf("enter two variables to calculate the sum:\n");
scanf("%d%d",&var1,&var2);
//call to add function, main function is the calling function
sum=add(var1,var2);
//call to sub function
difference=sub(var1,var2);
printf("sum is:%d",sum);
printf("difference is:%d",difference);
}

so when a function is called, the control goes from bottom to top and returns to bottom again ie from main function to the user defined function and back to main function again.

Functions

function is an independent block of code, that is designed to carry out a specific task, it can accept certain values as input or it can have no input, it may return the results after completion or it may not.

General format of a  C function:

Returntype function name(formal arguments list)
ex: void add(int var1,int var2), void print(void);
sample program:
#include 
int add(int,int);
void main()
{
int sum=0,var1=0,var2=0;
printf("enter two variables to calculate the sum:\n");
scanf("%d%d",&var1,&var2);
//call to add function, main function is the calling function
sum=add(var1,var2);//var1 var2 are the actual parameters
printf("sum is:%d",sum);
}
int add(int value1,int value2)//value1,value2 are called as formal parameters
{
return value1+value2;
}//returns the sum

Return Type:

The return type indicates datatype of the value returned by the function on completion of its execution, if a function doesn't return any value then its return type will be void.
ex:
void add(int var1,int var2) ; this function does not return anything.
int add(int var1,int vbar2);  this function returns an integer value.
similarly a function can have return types as float,char etc.

Formal arguments/parameters:

formal arguments are the variables in called function,that accepts the value passed from the calling function.
ex: void add(int var1,int var2 ) here var1,var2 are the formal parameters.

Actual arguments/parameters:

actual arguments are the variables passed from the calling function like main in the sample program.

Function declaration/prototyping a function:

function declaration  is used to inform the compiler about the existence of a function body after the main, this is done by just defining the function signature ie the return type, function name, formal argument types/formal arguments.Since C is a top down programming language(read article on programming approaches c,c++), this should be the ideal approach ie all functions should be declared before main(), definition should be after the main().
ex:
//top down approach
#include 
//function declaration or prototype
int add(int,int);
void main()
{
int sum=0,var1=0,var2=0;
printf("enter two variables to calculate the sum:\n");
scanf("%d%d",&var1,&var2);
//call to add function, main function is the calling function
sum=add(var1,var2);//var1 var2 are the actual parameters
printf("sum is:%d",sum);
}
//function definition
int add(int value1,int value2)//value1,value2 are called as formal parameters
{
return value1+value2;
}//returns the sum

Calling a function:

A function can be called by using its name and by passing the arguments required in parenthesis.
ex:
    sum=add(10,20);
    sub(5,10); etc
the values passed should be of same datatype as mentioned in the declaration or definition.
if the function returns some value then we can accept the returned value by using a variable of same type.

Function definition:

a function definition has the actual code/instructions that enables the function to perform a specific task.ex: performing addition ,subtraction,calculate the simple interest etc.

Bottom up programming:

ex :read article programming approaches c,c++ in general programming
//bottom up approach
#include 
//function definition
int add(int value1,int value2)//value1,value2 are called as formal parameters
{
return value1+value2;
}//returns the sum
void main()
{
int sum=0,var1=0,var2=0;
printf("enter two variables to calculate the sum:\n");
scanf("%d%d",&var1,&var2);
//call to add function, main function is the calling function
sum=add(var1,var2);//var1 var2 are the actual parameters
printf("sum is:%d",sum);
}