Using Macros Find Arithmetic Mean, Absolute Value, Biggest of 3 number and convert upper case alphabet to lower case: C Program

Problem Statement: Write down macro definitions for the following:

1. To find arithmetic mean of two numbers.
2. To find absolute value of a number.
3. To convert an upper case alphabet to lower case.
4. To obtain the biggest of three numbers.

Related Read:
Switch Case Default In C Programming Language
Macros With Arguments: C Program
do-while Loop In C Programming Language

Video Tutorial: Using Macros Find Arithmetic Mean, Absolute Value, Biggest of 3 number and convert upper case alphabet to lower case: C Program


[youtube https://www.youtube.com/watch?v=JvLQTBD7S3Q]

YouTube Link: https://www.youtube.com/watch?v=JvLQTBD7S3Q [Watch the Video In Full Screen.]

Source Code: Using Macros Find Arithmetic Mean, Absolute Value, Biggest of 3 number and convert upper case alphabet to lower case: C Program

#include<stdio.h>

#define MEAN(a, b)  ( (a + b) / 2.0 )
#define ABS(num)    ( (num > 0) ? num : (num * -1) )
#define LOWER(ch)   ( ch + 32 )
#define BIGGEST(a, b, c) ( (a > b && a > c) ? a : ( (b > c) ? b : c ) )

int main()
{
    int choice, num, repeat;
    float a, b, c;
    char ch;

    do
    {
        printf("1. Find Arithmetic Mean of 2 numbers\n");
        printf("2. Find Absolute Value of a number\n");
        printf("3. Convert a Uppercase letter to lowercase\n");
        printf("4. Find Biggest of 3 numbers\n");

        printf("\nEnter your choice\n");
        scanf("%d", &choice);

        switch(choice)
        {
            case 1: printf("Enter 2 numbers\n");
                    scanf("%f%f", &a, &b);
                    printf("Arithmetic Mean: %0.2f\n", MEAN(a, b));
                    break;
            case 2: printf("Enter a integer number\n");
                    scanf("%d", &num);
                    printf("Absolute value of |%d| is %d\n", num, ABS(num));
                    break;
            case 3: printf("Enter a uppercase alphabet\n");
                    fflush(stdin);
                    scanf("%c", &ch);

                    if( ch >= 65 && ch <= 90)
                        printf("To Lowercase: %c\n", LOWER(ch));
                    else
                        printf("Enter a valid uppercase alphabet\n");

                    break;
            case 4: printf("Enter 3 numbers\n");
                    scanf("%f%f%f", &a, &b,&c);
                    printf("Biggest no is %0.2f\n", BIGGEST(a, b, c));
                    break;
            default: printf("Please enter valid choice\n");
        }

        printf("\nDo you want to continue? Ans: 0 or 1\n");
        scanf("%d", &repeat);

        printf("\n");

    }while(repeat);

    return 0;
}

Output:
1. Find Arithmetic Mean of 2 numbers
2. Find Absolute Value of a number
3. Convert a Uppercase letter to lowercase
4. Find Biggest of 3 numbers

Enter your choice
1
Enter 2 numbers
41
14
Arithmetic Mean: 27.50

Do you want to continue? Ans: 0 or 1
1

1. Find Arithmetic Mean of 2 numbers
2. Find Absolute Value of a number
3. Convert a Uppercase letter to lowercase
4. Find Biggest of 3 numbers

Enter your choice
2
Enter a integer number
5
Absolute value of |5| is 5

Do you want to continue? Ans: 0 or 1
1

1. Find Arithmetic Mean of 2 numbers
2. Find Absolute Value of a number
3. Convert a Uppercase letter to lowercase
4. Find Biggest of 3 numbers

Enter your choice
2
Enter a integer number
-5
Absolute value of |-5| is 5

Do you want to continue? Ans: 0 or 1
1

1. Find Arithmetic Mean of 2 numbers
2. Find Absolute Value of a number
3. Convert a Uppercase letter to lowercase
4. Find Biggest of 3 numbers

Enter your choice
3
Enter a uppercase alphabet
S
To Lowercase: s

Do you want to continue? Ans: 0 or 1
1

1. Find Arithmetic Mean of 2 numbers
2. Find Absolute Value of a number
3. Convert a Uppercase letter to lowercase
4. Find Biggest of 3 numbers

Enter your choice
3
Enter a uppercase alphabet
$
Enter a valid uppercase alphabet

Do you want to continue? Ans: 0 or 1
1

1. Find Arithmetic Mean of 2 numbers
2. Find Absolute Value of a number
3. Convert a Uppercase letter to lowercase
4. Find Biggest of 3 numbers

Enter your choice
4
Enter 3 numbers
20
40
50
Biggest no is 50.00

Do you want to continue? Ans: 0 or 1
0

Formula and Logic

1. Arithmetic mean: If user enters two numbers, then we add those 2 numbers and divide it by 2 to get the result. If user inputs 3 numbers, we first add all these 3 numbers and divide it by 3 to get mean.

In this program, according to problem statement, we need to add 2 numbers and divide it by 2 to get the mean of those 2 user input numbers.

Since we’re taking 2 floating point numbers, we’re dividing the sum of two numbers by 2.0 and not by integer 2. If we divide float or double number with integer number 2, then there is possibility of getting wrong result.

Calculate Sum and Average of N Numbers without using Arrays: C Program

Average and Mean are same in mathematics.

2. Absolute Value: Absolute value is like distance. In whichever direction you move there can only be positive distance. You can’t walk negative 5 kilometre!

So for any integer input by the user, we return it’s positive value by multiplying it by -1, in case user input number is negative.

C Program To Find Absolute Value of a Number

Note: We could have used built-in method abs() from the library file stdlib.h to get absolute value of user input number. But to use a single built-in method abs() we must include all the things present in stdlib.h file, so we better write definition to calculate absolute value ourselves.

3. Convert a Uppercase alphabet to lowercase: We should know the ASCII value of A and Z, as well as ASCII value of a and z to get the result.

C Program To Print All ASCII Characters and Code

ASCII value range of upper case alphabets:
ASCII value of A is 65.
ASCII value of B is 66.
ASCII value of C is 67.

and so on till Z ..

ASCII value of Z is 90.

ASCII value range of lower case alphabets:
ASCII value of a is 97.
ASCII value of b is 98.
ASCII value of c is 99.

and so on till z ..

ASCII value of z is 122.

If you observe the ASCII values properly, you’ll know that there is a difference of 32 between a and A in it’s ASCII value. So, if user inputs a capital letter, then we simply add 32 to it and display the character – which will be its corresponding lowercase alphabet.

Note: Since we might start to input information from the keyboard repeatedly inside do-while block, scanf() method keeps checking the input buffer. And often times it gets confused with the input buffer and thinks that the user has pressed the enter key. To avoid that we flush out the previous buffer present in input device(ex: keyboard) using function fflush(). fflush takes stdin as argument, so that it can clear the buffer of standard input device. fflush(stdin);

4. Biggest of 3 Numbers: Here we make use of nested ternary or conditional operator. If a is greater than b and c, then we return value of a. ORELSE if b is greater than c, then we return the value of b, else we return the value of c.

Biggest of 3 Numbers Using Ternary Operator: C

Note: We can continue writing macro expansion in next line by making use of macro continuation operator(\). You can see that we’ve broken the line and written the code in next line inside macro expansion of BIGGEST(a, b, c).

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Determine Leap Year or Not using Macros

In this video tutorial lets learn how to determine user input year is a leap year or not, using Macros and nested ternary / conditional operator.

Related Read:
C Program To Check Leap Year
C Program To Check Leap Year Using Ternary Operator
Using Macro Template In Macro Expansion: C Program

Leap Year Logic

1. If a year is century year(year ending with 00) and is perfectly divisible by 400, then it’s a leap year.

2. If a year is not a century year, and is perfectly divisible by 4, then it’s a leap year.

Video Tutorial: Determine Leap Year or Not using Macros: C Program


[youtube https://www.youtube.com/watch?v=Du7YNk8GGDk]

YouTube Link: https://www.youtube.com/watch?v=Du7YNk8GGDk [Watch the Video In Full Screen.]

Source Code: C Program To Determine Leap Year or Not using Macros

#include<stdio.h>

#define NOT_LEAP(x) printf("%d is not leap year\n", x)
#define LEAP_YEAR(x) printf("%d is leap year\n", x)

#define LEAP(x) ( (x % 100 == 0 && x % 400 == 0) ? LEAP_YEAR(x) : \
                 ( (x % 4 ==0) ? LEAP_YEAR(x) : NOT_LEAP(x)) )

int main()
{
    int year;

    printf("Enter a year\n");
    scanf("%d", &year);

    LEAP(year);

    return 0;
}

Output 1:
Enter a year
2018
2018 is not leap year

Output 2:
Enter a year
2019
2019 is not leap year

Output 3:
Enter a year
2020
2020 is leap year

Output 4:
Enter a year
2023
2023 is not leap year

Output 5:
Enter a year
2024
2024 is leap year

In above program we’re writing NOT_LEAP(x) macro to display a message that the user input year is not a leap year. LEAP_YEAR(x) macro is used to display message that the user input year is a leap year.

We use both NOT_LEAP(x) and LEAP_YEAR(x) macro names or macro templates inside LEAP(x) macro expansion.

We’re also using macro continuation(\) to break the line and continue writing the logic in next line in macro expansion of LEAP(x).

List of some leap years

2000
2004
2008
2012
2016
2020
2024
2028
2032
2036
2040
2044
2048

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Macro With Argument v/s Function: C Program

In today’s video tutorial lets see the difference between a Macro with argument and a simple function.

Related Read:
Macros With Arguments: C Program
Function / Methods In C Programming Language

Video Tutorial: Macro With Argument v/s Function Call: C Program


[youtube https://www.youtube.com/watch?v=kVQsekPnbMU]

YouTube Link: https://www.youtube.com/watch?v=kVQsekPnbMU [Watch the Video In Full Screen.]

Source Code: Macro With Argument v/s Function Call: C Program

#include<stdio.h>

#define PI 3.14159265358979323846
#define AREA(r) ( PI * r * r )

double circle_area(float);

int main()
{
    float r;

    printf("Enter radius of Circle\n");
    scanf("%f", &r);

    printf("Area of Circle, using Macro is %f\n", AREA(r));
    printf("Area of Circle, using Function is %f\n", circle_area(r));

    return 0;
}

double circle_area(float r)
{
    return( 3.14159265358979323846 * r * r );
}

Output:
Enter radius of Circle
5
Area of Circle, using Macro is 78.539816
Area of Circle, using Function is 78.539816

As you can see in above output the result is same for Macro and function call. Now the question is, when to use macros and when to use functions?

When to use macros and when to use functions?

Macro: If a macro template is used 100 times inside a C program, all these macro template will be replaced with its macro expansion before its passed to the compiler. This process is called as preprocessing, and it’s done by preprocessor. Because of this, the size of the program increases.

Function: Function definition is written only once and even if its called 100 times inside a program it won’t increase the program size. Whenever there is a function call, the control is passed to the function definition where some logical operation is performed and then a meaningful result is returned back to the calling function. This takes some time.

So the trade off is between memory space and time.

If memory is not an issue, then you can simply use Macros – as it brings in speed of execution as an advantage. But if memory space is an issue – if you’re writing for a mobile device, then it’s better to go with functions. Though its slower, it uses less memory space.

While coding for bigger real-time projects you’ll surely need the knowledge of macros and macros with argument, so know the syntax and it’s advantages. In this fast moving world speed of execution really matters. And C programming specifically is famous and used often for its speed and its easy integration(and interaction) with the hardware devices.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Using Macro Template In Macro Expansion: C Program

In this video tutorial lets see how we can make use of a macro template in a macro expansion.

Objective

We define PI in a macro, and then we use PI in expansion of another macro.

We shall also modify the same program to make use of constant M_PI present in math.h library file instead of macro template PI.

Related Read:
Preprocessors In C Programming Language
C Program To Find Area of Circle Using Macro Expansion
Macros With Arguments: C Program

Video Tutorial: Using Macro Template In Macro Expansion: C Program


[youtube https://www.youtube.com/watch?v=s3bMxi6Isu8]

YouTube Link: https://www.youtube.com/watch?v=s3bMxi6Isu8 [Watch the Video In Full Screen.]

Source Code: Using Macro Template In Macro Expansion: C Program

#include<stdio.h>

#define PI 3.14159265358979323846

#define AREA(r) ( PI * r * r )

int main()
{
    float r;

    printf("Enter radius of Circle\n");
    scanf("%f", &r);

    printf("Area of Circle is %f\n", AREA(r));

    return 0;
}

Output:
Enter radius of Circle
5
Area of Circle is 78.539816

In above source code, preprocessor replaces every occurrence of PI with 3.14159265358979323846 and then checks for every occurrence of AREA(r) and replaces with ( 3.14159265358979323846 * r * r ).

With this simple example I’m trying to illustrate that we can make use of Macro template inside macro expansion of another macro definition.

Using M_PI constant present in Math.h header file

#include<stdio.h>
#include<math.h>

#define AREA(r) ( M_PI * r * r )

int main()
{
    float r;

    printf("Enter radius of Circle\n");
    scanf("%f", &r);

    printf("Area of Circle is %f\n", AREA(r));

    return 0;
}

Output:
Enter radius of Circle
5
Area of Circle is 78.539816

Note: M_PI is also a macro inside math.h library file.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Area of Circle Using Macro Expansion

In this video tutorial lets learn about Macro Expansion and also lets write a simple program to find area of Circle using Macros.

Related Read:
Preprocessors In C Programming Language

Rules To Construct/Write Macro Definition

1. Space between # and define is optional.
2. There must be a space or tab between Macro Template and Macro Expansion.
3. #define MACRO_TEMPLATE MACRO_EXPANSION is called Macro Definition.
4. Macro definition must not end with semi-colon.
5. Using all capital letters for Macro template is convention and not a syntax of C. You can use any name for Macro template, except the C reserve words.

Video Tutorial: C Program To Find Area of Circle Using Macro Expansion


[youtube https://www.youtube.com/watch?v=fMe5ieQY_Zk]

YouTube Link: https://www.youtube.com/watch?v=fMe5ieQY_Zk [Watch the Video In Full Screen.]

Source Code: C Program To Find Area of Circle Using Macro Expansion

#include<stdio.h>

#define PI 3.14

int main()
{
    float r, area;

    printf("Enter Radius of Circle\n");
    scanf("%f", &r);

    area = PI * r * r;

    printf("Area of Circle is %f\n", area);

    return 0;
}

Output 1:
Enter Radius of Circle
5
Area of Circle is 78.500000

Source Code: Writing printf statement in Macro expansion

#include<stdio.h>

#define DISPLAY printf("I'm in Love with iPhone UI Elements\n\n")

int main()
{
    DISPLAY;
    return 0;
}

Output 1:
I’m in Love with iPhone UI Elements

Note: Careful not to enter semicolon at the end of Macro definition. i.e., after the end of printf() statement.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert