logo codesdope
Level 1
1.
What is a pre-processor?
2.
What is the difference between a macro and a function?
Level 2
1.
Write a macro to calculate area and perimeter of a rectangle.
Answer
#include <stdio.h>
#define area(l,b) (l*b)
#define perimeter(l,b) (2*(l+b))
int main()
{
  printf("Area is %d and perimeter is %d.\n",area(5,2),perimeter(5,2));
  return 0;
}
									

2.
Write a macro to compare two numbers.
Answer
#include <stdio.h>
#define equal(a,b) (a==b)
int main()
{
  printf("%d\n",equal(5,2));
  printf("%d\n",equal(5,5));
  return 0;
}
									

3.
Write a macro to find average of two numbers.
Answer
#include <stdio.h>
#define avg(a,b) ((a+b)/2.0)
int main()
{
  printf("%f\n",avg(5,2));
  return 0;
}
									

4.
Write a macro to find absolute value of number.
Answer
#include <stdio.h>
#define abs(a) ((a<1)?(-1*a):a)
int main()
{
  printf("%d\n",abs(-5));
  printf("%d\n",abs(5));
  return 0;
}
									

5.
Write a macro to calculate simple interest from principal, rate of interest and time.
Simple interest = (principal*rate of interest*time)/100.
Answer
#include <stdio.h>
#define si(p,r,t) ((p*r*t)/100.0)
int main()
{
  printf("%f\n",si(1000,12,3));
  return 0;
}
									
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.