Lets understand the basic structure of a C program. A C program is divided into different sections. There are six main sections to a basic c program.
The six sections are,
Documentation
Include/Link/Preprocessor section
Definition
Global Declarations ( Functions and variables)
Main function
Subprogram functions
Figure: Basic Structure Of C Program
Sample Program
The C program here will find the area of a circle using a user-defined function and a global variable PI holding the value of pi
/* File Name: areaofcircle.c
Author: Abhijith
date: 06/05/2021
description: a program to calculate area of circle
user enters the radius
*/
#include<stdio.h> //link section
#define PI 3.14;//definition section
float area(float r);//global declaration
/****************************/
int main()//main function
{
float r;
printf(" Enter the radius:\n");
scanf("%f",&r);
printf("the area is: %f",area(r));
return 0;
}
/**************************/
float area(float r)
{
return pi * r * r;//sub program
}
The documentation section is the part of the program where the programmer gives the details associated with the program. He usually gives the name of the program, the details of the author and other details like the time of coding and description. It gives anyone reading the code the overview of the code.
/* File Name: areaofcircle.c
Author: Abhijith
date: 06/05/2021
description: a program to calculate area of circle
user enters the radius
*/
This part of the code is used to declare all the header files that will be used in the program. This leads to the compiler being told to include the header files to the source program and link the system libraries.
#include<stdio.h>
In this section, we define different constants. The keyword define is used in this part.
#define PI 3.14
This part of the code is the part where the global variables are declared. All the global variable used are declared in this part. The user-defined functions are also declared in this part of the code.
float area(float r);
int a=7;
Every C-programs needs to have the main function. Each main function contains 2 parts. A declaration part and an Execution part. The declaration part is the part where all the variables are declared. The execution part begins with the curly brackets and ends with the curly close bracket. Both the declaration and execution part are inside the curly braces.
{
float r;
printf(" Enter the radius:\n");
scanf("%f",&r);
printf("the area is: %f",area(r));
return 0;
}
Sub Program Section
All the user-defined functions are defined in this section of the program.
float area(float r)
{
return pi * r * r;//sub program
}
Comments
Post a Comment