Using Macros Check For Uppercase / Lowercase and Alphabet or Not and Biggest of 2 Numbers: C Program

Problem State: Write down macro definitions for the following:
1. To test whether a character is a small case letter or not.
2. To test whether a character is an upper case letter or not.
3. To test whether a character is an alphabet or not. Make use of the macros you defined in 1 and 2 above.
4. To obtain the bigger of two numbers.

Related Read:
Switch Case Default In C Programming Language
Macros With Arguments: C Program
Biggest of Two Numbers Using Ternary Operator: C
C Program To Print Uppercase Alphabet(A-Z) using While loop
C Program To Print Lowercase Alphabet(a-z) using While loop
C Program To Check Whether a Character is an Alphabet or Not

Problem Statement Analysis

1. We need to write 4 Macro definitions.
2. We must write macros to find upper and lower case, and then make use of these two macros to find if user entered character is alphabet or not.
3. We can find biggest of 2 numbers by using Ternary / conditional operator in macro expansion.

Video Tutorial: Using Macros Check For Uppercase / Lowercase and Alphabet or Not and Biggest of 2 Numbers: C Program


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

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

Source Code: Using Macros Check For Uppercase / Lowercase and Alphabet or Not and Biggest of 2 Numbers: C Program

#include<stdio.h>

#define isUPPER(ch) ( ch >= 'A' && ch <= 'Z' )
#define isLOWER(ch) ( ch >= 'a' && ch <= 'z' )
#define isALPHABET(ch) ( isUPPER(ch) || isLOWER(ch) )
#define BIGGEST(a, b) ( ( a > b ) ? \
                       printf("%d is the biggest\n", a) : \
                       printf("%d is the biggest\n", b) )

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

    do
    {
        printf("1. Check if entered character is upper or lower case\n");
        printf("2. Check if entered character is alphabet or not\n");
        printf("3. Find biggest of 2 numbers\n");

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

        switch(choice)
        {
            case '1': printf("\nEnter a character\n");
                      scanf(" %c", &ch);

                      if( isUPPER(ch) )
                      {
                          printf("Entered character is upper case letter\n");
                      }
                      else if( isLOWER(ch) )
                      {
                          printf("Entered character is lower case letter\n");
                      }
                      else
                      {
                          printf("Please enter a valid alphabet\n");
                      }

                      break;
            case '2': printf("\nEnter a character\n");
                      scanf(" %c", &ch);

                      if( isALPHABET(ch) )
                      {
                          printf("Entered character is an alphabet\n");
                      }
                      else
                      {
                          printf("Entered character is not an alphabet\n");
                      }
                      break;
            case '3': printf("\nEnter 2 numbers\n");
                      scanf("%d%d", &a, &b);

                      BIGGEST(a, b);

                      break;
            default:  printf("\nPlease enter valid choice\n");
        }

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

        printf("\n");
        fflush(stdin);

    }while(repeat);

    return 0;
}

Output:
1. Check if entered character is upper or lower case
2. Check if entered character is alphabet or not
3. Find biggest of 2 numbers

Enter your choice
1

Enter a character
S
Entered character is upper case letter

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

1. Check if entered character is upper or lower case
2. Check if entered character is alphabet or not
3. Find biggest of 2 numbers

Enter your choice
1

Enter a character
s
Entered character is lower case letter

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

1. Check if entered character is upper or lower case
2. Check if entered character is alphabet or not
3. Find biggest of 2 numbers

Enter your choice
1

Enter a character
$
Please enter a valid alphabet

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

1. Check if entered character is upper or lower case
2. Check if entered character is alphabet or not
3. Find biggest of 2 numbers

Enter your choice
2

Enter a character
A
Entered character is an alphabet

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

1. Check if entered character is upper or lower case
2. Check if entered character is alphabet or not
3. Find biggest of 2 numbers

Enter your choice
2

Enter a character
&
Entered character is not an alphabet

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

1. Check if entered character is upper or lower case
2. Check if entered character is alphabet or not
3. Find biggest of 2 numbers

Enter your choice
3

Enter 2 numbers
14
50
50 is the biggest

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

Here we are using do-while loop to repeatedly show the user choices: If user enters 1, the choices are shown once again. If the user enters 0, then control exits the do-while loop.

Choice 1: Upper or Lower Case Alphabet

All the characters have ASCII value associated with it in C programming. So internally it checks the ASCII value of user entered character against the ASCII values of “A” to “Z”.

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.

So all the ASCII values between 65 and 90 (including 65 and 90) are Capital letter alphabets.

Similarly, below we’ve listed the ASCII values of lower case alphabets.

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.

So all the ASCII values between 97 and 122 (including 97 and 122) are Lower case letter alphabets.

Related Read:
C Program To Print Uppercase Alphabet(A-Z) using While loop
C Program To Print Lowercase Alphabet(a-z) using While loop

Choice 2: Alphabet or Not

According to our problem statement we need to use the macros we defined for “Choice 1” to evaluate if the user entered character is alphabet or not. So if the user entered character is upper or lower case latter than its alphabet or else its not an alphabet.

Related Read:
C Program To Check Whether a Character is an Alphabet or Not

Choice 3: Biggest of Two Numbers

Inside macro expansion we make use of ternary / conditional operator to find biggest of 2 numbers.

Related Read:
Biggest of Two Numbers Using Ternary Operator: C

Bug in accepting character as input

When you input some data via console window and hit enter key, the enter key or the new line character gets stored inside input buffer. If you’re accepting a single character from keyboard via scanf() function, often times it gets confused with the input buffer and thinks that the user has pressed the enter key as the input character. We can avoid it in 3 ways:

1. Use double scanf() function, as illustrated in above video tutorial.
2. Use a space before %c inside scanf() method.
3. Use fflush(stdin) before every scanf() method which accepts a single character value.

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);

#include<stdio.h>

#define isUPPER(ch) ( ch >= 'A' && ch <= 'Z' )
#define isLOWER(ch) ( ch >= 'a' && ch <= 'z' )
#define isALPHABET(ch) ( isUPPER(ch) || isLOWER(ch) )
#define BIGGEST(a, b) ( ( a > b ) ? \
                       printf("%d is the biggest\n", a) : \
                       printf("%d is the biggest\n", b) )

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

    do
    {
        printf("1. Check if entered character is upper or lower case\n");
        printf("2. Check if entered character is alphabet or not\n");
        printf("3. Find biggest of 2 numbers\n");

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

        switch(choice)
        {
            case '1': printf("\nEnter a character\n");
                      fflush(stdin);
                      scanf("%c", &ch);

                      if( isUPPER(ch) )
                      {
                          printf("Entered character is upper case letter\n");
                      }
                      else if( isLOWER(ch) )
                      {
                          printf("Entered character is lower case letter\n");
                      }
                      else
                      {
                          printf("Please enter a valid alphabet\n");
                      }

                      break;
            case '2': printf("\nEnter a character\n");
                      fflush(stdin);
                      scanf("%c", &ch);

                      if( isALPHABET(ch) )
                      {
                          printf("Entered character is an alphabet\n");
                      }
                      else
                      {
                          printf("Entered character is not an alphabet\n");
                      }
                      break;
            case '3': printf("\nEnter 2 numbers\n");
                      scanf("%d%d", &a, &b);

                      BIGGEST(a, b);

                      break;
            default:  printf("\nPlease enter valid choice\n");
        }

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

        printf("\n");
        fflush(stdin);

    }while(repeat);

    return 0;
}

In above source code we’re making use of fflush(stdin) before every scanf() method which accepts single character. fflush(stdin) flushes out the previous buffer present in input device(ex: Keyboard).

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 to find biggest of 2 numbers.

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 Print Multiplication Table Using Macros

In this video lets see how we can print multiplication table(from 1 to 10) for any positive user input value, using Macros.

Related Read:
C Program To Print Multiplication Table Using While Loop

Video Tutorial: C Program To Print Multiplication Table Using Macros


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

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

Source Code: C Program To Print Multiplication Table Using Macros

#include<stdio.h>

#define MULTI(num, count) printf("%d x %d = %d\n", num, count, (num*count))

int main()
{
    int num, count = 1;

    printf("Enter a positive number\n");
    scanf("%d", &num);

    printf("\nMultiplication Table for %d is: \n\n", num);

    while(count <= 10)
    {
        MULTI(num, count);
        count++;
    }

    return 0;
}

Output 1:
Enter a positive number
5

Multiplication Table for 5 is:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Output 2:
Enter a positive number
4

Multiplication Table for 4 is:

4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

Here we are initializing variable count to 1 and iterating the while loop until count is less than or equal to 10. For each iteration we’re executing macro MULTI(num, count). But before compilation itself preprocessor will have replaced MULTI(num, count) by its macro expansion, which is printf(“%d x %d = %d\n”, num, count, (num*count)).

Note: If you see \ inside macro expansion – it is called as Macro continuation(\) operator. It is used to continue the code in next line, in macro expansion.

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