0% found this document useful (0 votes)
70 views19 pages

Basic Structure of A C Program

The document outlines the basic structure of a C program, which includes six essential sections: Documentation, Pre-processor Section, Definition, Global Declaration, Main() Function, and Sub Programs. It explains the purpose of each section and provides examples of C code, along with an overview of the compilation process and type conversion in C. Additionally, it discusses input and output operations, including various functions for reading and displaying data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views19 pages

Basic Structure of A C Program

The document outlines the basic structure of a C program, which includes six essential sections: Documentation, Pre-processor Section, Definition, Global Declaration, Main() Function, and Sub Programs. It explains the purpose of each section and provides examples of C code, along with an overview of the compilation process and type conversion in C. Additionally, it discusses input and output operations, including various functions for reading and displaying data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

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.

Sections of the C Program


There are 6 basic sections responsible for the proper execution of a program.
Sections are mentioned below:
1. Documentation
2. Pre-processor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs

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

The global declaration section contains global variables, function declaration,


and static variables. Variables and functions which are declared in this scope can
be used anywhere in the program.
Example:
int num = 18;

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.
*/

Header file which is used for standard input-output.


#include<stdio.h> This is the preprocessor section.

This is the definition section. It allows the use of


#define X 20 constant X in the code.

This is the Global declaration section includes the


function declaration that can be used anywhere in the
int sum(int y) program.

main() is the first function that is executed in the C


int main() program.

These curly braces mark the beginning and end of the


{…} main function.

printf(“Sum: %d”,
printf() function is used to print the sum on the screen.
sum(y));

return 0; We have used int as the return type so we have to return


0 which states that the given program is free from the

4
Sections Description

error and it can be exited successfully.

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

Linker generates the executable Loader loads the executable module to


module of a source program. the main memory for execution.

Linker takes the object code Loader takes executable module


generated by an assembler, as input. generated by a linker as input.

Linker combines all the object Loader allocates the addresses to an


modules of a source code to generate executable module in main memory
an executable module. for execution.

The types of Loader are Absolute


The types of Linker are Linkage
loading, Relocatable loading and
Editor, Dynamic linker.
Dynamic Run-time loading.
Type Conversion in C
Type conversion in C is the process of converting one data type to another. The
type conversion is only performed to those data types where conversion is
possible. Type conversion is performed by a compiler. In type conversion, the
7
destination data type can’t be smaller than the source data type. Type conversion
is done at compile time and it is also called widening conversion because the
destination data type can’t be smaller than the source data type. There are two
types of Conversion:

Implicit Type Conversion:

Also known as ‘automatic type conversion’.

 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;

// Explicit conversion from double to int


int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;
}
Output:
Sum=2
Example 2:
#include <stdio.h>

int main() {
float a = 1.5;
int b = (int)a;

printf("a = %f\n", a);


printf("b = %d\n", b);

return 0;
}
Output:
a = 1.500000
b=1

Advantages of Type Conversion

 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.

Disadvantages of type conversions in C programming:

 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.

Managing Input and Output Operations:


Managing Input and
Output Operations

Constructs for displaying output

Constructs for getting input 1)scanf( )


2)getchar
1)scanf( ) () 3)gets(
2)putchar )
()
3)puts()

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)

1. Single character input and output [getchar() andputchar()]

 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()

 Input--- gets (str)


 Output---puts (str)

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 );

printf( "\nYou entered: ");

puts( str );

return 0;
}

Output:

Enter a value: This is CPNM class

You entered: This is CPNM class


1. Formatted Input [ scanf ( ) ] and FormattedOutput [ printf( ) ]
Specifier Meaning
%c – Print a character
%d – Print a Integer
%i – Print a Integer
%u-- Unsigned int
%ld-- Long int
%e – Print float value in exponential form.
%f – Print float value
%g – Print using %e or %f whichever is smaller
%lf --Double
%lf-- Long double
%o – Print octal value
%s – Print a string
%x – Print a hexadecimal integer (Unsigned) using lower case a – f
%X – Print a hexadecimal integer (Unsigned) using upper case A – F
%a – Print a unsigned integer.
%p – Print a pointer value
%hx – hex short
scanf()

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

scanf("control string", &variable1, &variable2, ...);

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()

Printf() is a predefined function in "stdio.h" header file, by using this function,


we can print the data or user defined message on console or monitor. While
working with printf(), it can take any number of arguments but first argument
must be within the double cotes (" ") and every argument should separated with
comma ( , ) Within the double cotes, whatever we pass, it prints same, if any
format specifies are there, then value is copied in that place.

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

Program (integer and float)


#include <stdio.h>
#include <conio.h>
void main()
{
int a;
14
float b;
clrscr();
printf("Enter any two numbers: ");
scanf("%d %f",&a,&b);
printf("%d %f \n",a,b);
getch();
}
Output:
Enter any two numbers: 10 3.5
10
3.5
Program
#include <stdio.h>
int main()
{
int integer = 9876;
float decimal = 987.6543;
printf("4 digit integer right justified to 6 column: %6d\n", integer);
printf("4 digit integer right justified to 3 column: %3d\n", integer); printf("Floating
point number rounded to 2 digits: %.2f\n",decimal); printf("Floating point number
rounded to 0 digits: %.f\n",987.6543); printf("Floating point number in
exponential form: %e\n",987.6543);
return 0;
}
Output:
4 digit integer right justified to 6 column:9876
4 digit integer right justified to 3 column:9876
Floating point number rounded to 2 digits:987.65
Floating point number rounded to 0 digits:988
Floating point number in exponential form:9.876543e+02
FILE INPUT and OUTPUT

File string input and output using fgets( )and fputs( )


The fgets() function
The fgets() function is used to read string(array of characters) from the file.
Syntax fgets(char str[],int n,FILE *fp);

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.

Syntax: fscanf(FILE *fp,"format-string",var-list);

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:

Reading from file...

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:

#incl ude<s tdio. h>


void main()
{
FILE *fp;introll; char name[25];

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

You might also like