FoodForFutureGeeks

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.

No comments:

Post a Comment