Can anyone tell me how can i write a program where i have to read a c program from a text file and then count the number of if-else statements, excluding the nested if-else. Her
If you aren't stuck to Java I would suggest Python pycparser https://github.com/eliben/pycparser . If you have to use Java then check Parsing / reading C-Header files using Java
In general counting if-else statements the way you've specified is wrong 'cause in a programming language if-else statement is not only line containing if
or else
(consider 'if' or 'else' words in comments and so on). It's exactly a statement in a language defined by a specific set of rules - grammar. Moreover your code will return successfully from not even a C program, which might not be correct...
So the ultimate way to solve the problem is to build an AST tree for the input program and traverse it counting only top-level if-else statements.
There are several tools that can help you with this.
Both of them can generate language parsers from the specified grammar. You can use these parsers to figure out what you input program consist of.
The main problem of such approach is finding (creating?) the correct grammar. For example there are lots of grammars for both ANTLR (https://github.com/antlr/grammars-v4) and JavaCC (https://java.net/projects/javacc/downloads/directory/contrib/grammars); but none of them can be used to generate AST - only plain parsing will be produced. On the other hand since you need to count only if-else statements you might be good with parsing only (without AST tree)...
So at this point there are 2 possible solutions:
ps: for more info on updating grammars to support AST trees see How to implement JJTree on grammar (JavaCC) and How to output the AST built using ANTLR? (ANTLR).
Without seeing the original file to read, I would use regex to count the total number of if/else and then count the number of nested if/else. The math for the result should be pretty simple... :)