Basic Structure of A C Program
Basic Structure of A C Program
The basic structure of a C program is divided into 6 parts which makes it easy to
read, modify, document, and understand in a particular format. C program must
follow the below-mentioned outline in order to successfully compile and execute.
Debugging is easier in a well-structured C program.
1. Documentation
This section consists of the description of the program, the name of the program,
and the creation date and time of the program. It is specified at the start of the
program in the form of comments. Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
Or
/*
description, name of the program, programmer name, date, time etc.
*/
2. Pre-processor Section
All the header files of the program will be declared in the preprocessor section of
the program. Header files help us to access other’s improved code into our code.
A copy of these multiple files is inserted into our program before the process of
compilation.
Example:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
#include<file.h>
1
3. Definition
Pre-processors are the programs that process our source code before the process
of compilation. There are multiple steps which are involved in the writing and
execution of the program. Pre-processor directives start with the ‘#’ symbol. The
#define pre-processor is used to create a constant throughout the program.
Whenever this name is encountered by the compiler, it is replaced by the actual
piece of defined code.
Example:
#define PI 3.14
#define CONST 100
4. Global Declaration
5. Main() Function
Every C program must have a main function. The main() function of the program
is written in this section. Operations like declaration and execution are performed
inside the curly braces of the main program. The return type of the main()
function can be int as well as void too. void() main tells the compiler that the
program will not return any value. The int main() tells the compiler that the
program will return an integer value.
Example:
void main()
or
int main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of
the program is shifted to the called function whenever they are called from the
main or outside the main() function. These are specified as per the requirements
of the programmer.
Example:
int sum(int x, int y)
2
{
return x+y;
}
Structure of C Program with example:
Write a c program to find the sum of 2 numbers:
// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
// Subprogram
int sum(int y)
{
return y + X;
}
Output
3
Sum: 75
Explanation of the above Program
Below is the explanation of the above program. With a description explaining the
program’s meaning and use.
Sections Description
/**
* file: sum.c
* author: you It is the comment section and is part of the description
* description: program section of the code.
to find sum.
*/
printf(“Sum: %d”,
printf() function is used to print the sum on the screen.
sum(y));
4
Sections Description
int sum(int y)
{ This is the subprogram section. It includes the user-
return y + X; defined functions that are called in the main() function.
}
Execution of a c program:
5
6
In the above diagram there are different steps −
C Code − This is the code that you have written. This code is sent to the Pre-
processor section.
Pre-processor − In this section the pre-processor files are attached with our code.
We have use different header files like stdio.h, math.h etc. These files are attached
with the C Source code and the final C Source generates. (‘#include’, ‘#define’
These are Pre-processor Directives.)
Compiler − After generating the pre-processed source code, it moves to the
compiler and the compiler generates the assembly level code after compiling the
whole program.
Assembler − This part takes the assembly level language from compiler and
generates the Object code, this code is quite similar to the machine code (set of
binary digits).
Linker − Linker is another important part of the compilation process. It takes the
object code and link it with other library files, these library files are not the part of
our code, but it helps to execute the total program. After linking the Linker
generates the final Machine code which is ready to execute.
Loader − A program, will not be executed until it is not loaded in to Primary
memory. Loader helps to load the machine code to RAM and helps to execute it.
While executing the program is named as Process. So process is (Program in
execution).
Difference between Linker and Loader
Linker Loader
Done by the compiler on its own, without any external trigger from the
user.
Generally takes place when in an expression more than one data type is
present. In such conditions type conversion (type promotion) takes place to
avoid loss of data.
All the data types of the variables are upgraded to the data type of the
variable with the largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost
(when signed is implicitly converted to unsigned), and overflow can occur
(when long is implicitly converted to float).
Example of Type Implicit Conversion
#include <stdio.h>
int main()
8
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
}
Output:
x = 107, z = 108.000000
Explicit Type Conversion:
This process is also called type casting and it is user-defined. Here the user can
typecast the result to make it of a particular data type. The syntax in C
Programming:
(type) expression
Type indicated the data type to which the final result is converted.
Example 1:
// C program to demonstrate explicit type casting
#include<stdio.h>
int main()
9
{
double x = 1.2;
return 0;
}
Output:
Sum=2
Example 2:
#include <stdio.h>
int main() {
float a = 1.5;
int b = (int)a;
return 0;
}
Output:
a = 1.500000
b=1
Type safety: Type conversions can be used to ensure that data is being stored
and processed in the correct data type, avoiding potential type mismatches and
type errors.
Improved code readability: By explicitly converting data between different
types, you can make the intent of your code clearer and easier to understand.
10
Improved performance: In some cases, type conversions can be used to
optimize the performance of your code by converting data to a more efficient
data type for processing.
Improved compatibility: Type conversions can be used to convert data
between different types that are not compatible, allowing you to write code
that is compatible with a wider range of APIs and libraries.
Improved data manipulation: Type conversions can be used to manipulate
data in various ways, such as converting an integer to a string, converting a
string to an integer, or converting a floating-point number to an integer.
Improved data storage: Type conversions can be used to store data in a more
compact form, such as converting a large integer value to a smaller integer
type, or converting a large floating-point value to a smaller floating-point
type.
Loss of precision: Converting data from a larger data type to a smaller data
type can result in loss of precision, as some of the data may be truncated.
Overflow or underflow: Converting data from a smaller data type to a larger
data type can result in overflow or underflow if the value being converted is
too large or too small for the new data type.
Unexpected behavior: Type conversions can lead to unexpected behavior,
such as when converting between signed and unsigned integer types, or when
converting between floating-point and integer types.
Confusing syntax: Type conversions can have confusing syntax, particularly
when using typecast operators or type conversion functions, making the code
more difficult to read and understand.
Increased complexity: Type conversions can increase the complexity of your
code, making it harder to debug and maintain.
Slower performance: Type conversions can sometimes result in slower
performance, particularly when converting data between complex data types,
such as between structures and arrays.
11
Input and Output
Input means to provide the program with some data to be used in the program(Stdin)
Output means to display data on screen or write the data to a printer or a file.(Stdout)
input- getchar()
output- putchar()
The int getchar(void) function reads the next available character from the screen
and returns it as an integer. This function reads only single character at a time.
The int putchar(int c) function puts the passed character on the screen and returns
the same character. This function puts only single character at a time.
program
#include <stdio.h>
int main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
return 0;
}
Output:
Enter a value: This is CPNM class
You entered: T
1. String input and output [gets() and puts()
The gets( ) function reads a line from stdin into the buffer pointed to by s
until either a terminating newline or EOF (End of File).
The puts( ) function writes the string 's' and 'a' trailing newline to stdout.
Program
#include <stdio.h>
int main( )
{
char str[100];
12
printf( "Enter a value :");
gets( str );
puts( str );
return 0;
}
Output:
scanf() is a predefined function in "stdio.h" header file. It can be used to read the
input value from the keyword.
Syntax of scanf() function
& ampersand symbol is the address operator specifying the address of the
13
variable
control string holds the format of the data
variable1, variable2, ... are the names of the variables that will hold the input
value
int a;
float b;
scanf("%d%f",&a,&b);
Example
double d;
char c;
long int l;
scanf("%c%lf%ld",&c&d&l);
Printf()
Program
#include <stdio.h> //This is needed to run printf() function.
int main()
{
printf("C Programming"); //displays the content inside quotation
return 0;
}
Output: C Programming
The fgets() function takes three arguments, first is the string read from the file,
second is size of string(character array) and third is the file pointer from where the
string will be read.
15
Example:
File*fp; Str[80];
fgets(str,80,fp)
Program:
#include<stdio.h>
void main()
{
FILE *fp; char str[80];
fp = fopen("file.txt","r"); // opens file in read mode (“r”)
while((fgets(str,80,fp))!=NULL)
printf("%s",str); //reads content from file
fclose(fp);
}
Data in file...
C is a general-purpose programming language.
It is developed by Dennis Ritchie.
The fputs() function
The fputs() function is used to write string(array of characters) to the file.
The fputs() function takes two arguments, first is the string to be written to the file
and second is the file pointer where the string will be written.
Syntax: fputs(char str[],FILE*fp;
Program:
#include<stdio.h>
int main()
{
FILE*fp;
fp=fopen(“proverb.txt”,”w+”); //opening file in write mode
fputs(“cleanliness is next to godliness.”,fp);
fputs(“Better late than never.”,fp);
fputs(“The pen is than the sword.”,fp);
fclose(fp);
return 0;
}
Output:
cleanliness is next to godliness
Better late than never
The pen is than the sword
16
File string input and output using fgets( )and fputs( ):
The fscanf() function is used to read mixed type(characters, strings and integers)
form the file.
The fscanf() function is similar to scanf() function except the first argument which
is a file pointer that specifies the file to be read.
Program:
#include<stdio.h>
void main()
{
FILE *fp; char ch;
int roll;
char name[25];
fp = fopen("file.txt","r"); printf("\n Reading from file...\n");
while((fscanf(fp,"%d%s",&rollno,&name))!=NULL)
printf("\n %d\t%s",rollno,name);//reading data
fclose(fp);
}
Output:
6666 keith
7777 rose
The fprintf() function:
The fprintf() function is used to write mixed type(characters, strings and
integers) in thefile.
The fprintf() function is similar to printf() function except the first argument
which is a filepointer specifies the filename to be written.
Syntax:
fprintf(FILE *fp,"format-string",var-list);
Program:
17
fp = fopen("file.txt","w");
scanf("%d",&roll);
scanf("%s",name);
fprintf(fp,"%d%s%",roll,name);
close(fp);
}
Output: 6666
lucky
18
19