c macros


Macros
MACRO is a String Replacer.
We DEFINE a SYMBOL as a DEFINITION
Whenever the SYMBOL is encountered in the Program the DEFINITION
attached to the SYMBOL is REPLACED.
Difference between Function and macro
The Parameter Mechanism Performed by a MACRO is Illegal Operation.
The Parameter Mechanism Performed by a FUNCTION is a Logical One.
In case of MACRO there will not be any TRANSFER of CONTROL.
The Definition of MACRO is already Stored in a TABLE and will be REPLACED
whenever the MACRO is CALLED at Compile Time.
Whenever a FUNCTION is called the CONTROL will JUMP from the MAIN
FUNCTION to the DEFINITION of the CALLED FUNCTION.
Program
#include<stdio.h>
#define UPPER 20
void main()
{
int x;
for(x = 1; x <= UPPER; x++)
printf("\nThe Value is : %d", x);
}
Program
#include<stdio.h>
#define PI 3.1415
void main()
{
float r, area;
printf("\nEneter Value of Radius : "); scanf("%f", &r);
area = PI * r * r;
printf("\nArea of The Circle is : %0.2f", area);
}
Program
#include <stdio.h>
#define SQR(x) x * x
void main()
{
int result, a;
printf("\nEneter Any Value : ");
scanf("%d", &a);
result = SQR (a + 2);
printf("\nThe Result is : %d", result);
}
Recursion
The ability of a FUNCTION to CALL ITSELF UNTIL BASE CONDITION is
reached is called RECURSION.
Properties of Recursive Procedure:
BASE CONDITION.
RECURSIVE STATEMENT.
Base condition
The BASE CONDITION of a recursive procedure indicates when the recursive
calls are going to be TERMINATED.
Recursive statement:
The RECURSIVE STATEMENT is used to reduce Nth order problem to (n-1)th
order.
Illustrative Examples
Factorial Using Recursion
Program
#include<stdio.h>
void main()
{
int factorial(int);
int m;
printf("\nEnter Any Number : "); scanf("%d", &m);
printf("\nFactorial of %d is %d.", m, factorial(m));
}
int factorial(int n)
{
int x, y;
if(n == 0)
return 1;
else
x = n - 1; y = factorial(x); return(n * y);
}

Finding ‘A’ to the power of ‘B’ using Recursion
Program
#include<stdio.h>
void main()
{
int power(int, int);
int a, b;
printf("\nEnter Values of a and b : ");
scanf("%d%d", &a, &b);
printf("\n%d To The Power of %d is %d.", a, b, power(a, b));
}
int power(a, b)
{
if(b == 0)
return 1;
else
return (a * power(a, b - 1));
}

No comments: