Javatpoint Logo
Javatpoint Logo

First and Follow Program in C

First and Follow sets are used in the process of syntax analysis. In this article, we will learn the First and Follow sets in the context of C programming and also write a program to calculate the First and Follow sets in C language.

As First and Follow Sets are used in compiler design and parsing techniques, it is recommended to go through the basics of syntax analysis, LL(1) parsing, and the rules for finding the First and Follow sets of a given grammar.

Let us understand the First Set and Follow Set:

First Set:

The First set of non-terminal symbols in grammar is the set of terminal symbols that can be derived as the first symbol of a string generated by the non-terminal. In other words, it is the set of all possible tokens that can be encountered at the beginning of a string derived from that non-terminal.

Follow Set:

The Follow set of non-terminal symbols in grammar is the set of terminal symbols that can come immediately after a string derived from that non-terminal in any valid sentence of the grammar. In other words, it is the set of all possible tokens that can appear immediately after the non-terminal in a valid sentence.

Example:

Let us consider the following context-free grammar as input:

Input:

C program to calculate the First and Follow sets for a given grammar:

Code:

Output:

First and Follow Program in C

Explanation:

The above C program will print the calculated First and Follow sets of a given grammar. Let us understand how the First and Follow Sets are calculated.

Step 1: Calculation of First Sets

First(E): It includes the first terminal of the production E -> AB, which is 'i' from A's First set.

First(A): It includes the first terminal of the production A ->"ilove", which is 'i'.

First(B): It includes the first terminal of the production B ->"jtptutorials", which is 'j'.

Step 2: Calculation of Follow Sets

Follow(E): Since 'E' is the start symbol, Follow(E) will include the '$' symbol, which represents the end of the input because the start symbol can be followed by the end of the input.

Follow(A): It includes the terminals that can follow 'A' in any production. In this grammar, 'A' is followed by 'B', so we include the First(B) in Follow(A).

Follow(B): It includes the terminals that can follow 'B' in any production. As there is no other production that follows 'B', we will look at Follow(E) as 'E' can produce 'B'.

Conclusion:

We have understood how to write a C program to compute the First and Follow Sets of a given context-free grammar.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA