C Programming language-Program Structure of C

Program Structure of C

The C program consists of following parts namely:

  • Preprocessor commands
  • Variables
  • Functions
  • Comments
  • Statements & Expressions

Hello Program

Look at the below simple C program to print “Hello World”

#include 
int main() {
   /* Hello World program in C */
   printf("Hello, World! \n");
   
   return 0;
}

From the above simple C program, let us look at the various parts present in the C program snippet,

  • The first line in the program is nothing but the Preprocessor command, which tells to C compiler to include stdio.h file before starting the actual compilation.
  • The next line of code is main() function, where the actual program execution begins.
  • The {..}  curly braces are used to group all the statements.
  • The next line is /*…*/ is called comments which will be ignored by the compiler. Commands are only for user references.
  • The next line printf() function used to print the message “Hello World!” to be displayed on the output screen.
  • The next line return 0; will be terminating the main() function and returns the value 0.
Basic Structure of C Program

From the above example program, we have discussed various parts of the C program. Here, we  discuss about the basic structure of the C program. All C programs must contain main() function which in turn contains two main parts such as

  • Declaration part 
  • Execution part
In Declaration part, we declare all the variables which will be used within the program. There needs to be atleast one line of code in the Execution part.  The execution of the program starts with open ‘{‘ curly braces and ends with closed ‘}’ curly braces. All the statements of these two parts should be ended with the semicolon(;).

Other than main function, we have sub-program section which deals with the user-define functions that are called within the main() function. These user-defined functions are usually declared and declared after the main() function.

Compile and Execute the C program

If you are using the GCC compiler, follow the below steps to compile and execute the C program.
  • Open the text editor, add your C code and save the file with any name (Example: hello.c) with ‘.c’ extension.
  • Open the command prompt and go to the directory where you have saved the file  and type gcc hello.c  and press enter to compile your code.
  • If do not have any errors in the code you have executed, then the command prompt will immediately take you to the next line. If not, you will get the list of errors displayed in the command prompt.
  • If your code is compiled successfully without errors, then type a.out in your command line and press enter.
  • You will see “Hello World!” output printed on your screen.