Unit 3
Unit 3
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. Preprocessor 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.
*/
Anything written as comments will be treated as documentation of the program and this will
not interfere with the given code. Basically, it gives an overview to the reader of the program.
2. Preprocessor 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<math.h>
3. Definition
Preprocessors 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. Preprocessor directives start with the ‘#’ symbol. The #define preprocessor 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 long long ll
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()
Compilation process in c
What is a compilation?
The compilation is a process of converting the source code into object code. It is done with
the help of the compiler. The compiler checks the source code for the syntactical or structural
errors, and if the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.
The pre-processor takes the source code as an input, and it removes all the comments from
the source code. The pre-processor takes the pre-processor directive and interprets it. For
example, if <stdio.h>, the directive is available in the program, then the pre-processor
interprets the directive and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed
into an executable form:
Linker
Mainly, all the programs written in C use library functions. These library functions are
pre-compiled, and the object code of these library files is stored with '.lib' (or '.a') extension.
The main working of the linker is to combine the object code of library files with the object
code of our program. Sometimes the situation arises when our program refers to the functions
defined in other files; then linker plays a very important role in this. It links the object code of
these files to our program. Therefore, we conclude that the job of the linker is to link the
object code of our program with the object code of the library files and other files. The output
of the linker is the executable file. The name of the executable file is the same as the source
file but differs only in their extensions. In DOS, the extension of the executable file is '.exe',
and in UNIX, the executable file can be named as 'a.out'. For example, if we are using printf()
function in a program, then the linker adds its associated code in an output file.
Constants C
The constants in C are the read-only variables whose values cannot be modified once they are
declared in the C program. The type of constant can be an integer constant, a floating pointer
constant, a string constant, or a character constant. In C language, the const keyword is used
to define the constants.
Syntax to Define Constant
const data_type var_name = value;
Variables
Variables are containers for storing data values, like numbers and characters.
In C, there are different types of variables (defined with different keywords), for example:
● int - stores integers (whole numbers), without decimals, such as 123 or -123
● float - stores floating point numbers, with decimals, such as 19.99 or -19.99
● char - stores single characters, such as 'a' or 'B'. Characters are surrounded by single
quotes
Syntax
type variableName = value;
Where type is one of C types (such as int), and variableName is the name of the variable
(such as x or myName). The equal sign is used to assign a value to the variable.
So, to create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign the value 15 to it:
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable
can store like integer, character, floating, double, etc. Each data type requires different
amounts of memory and has some specific operations which can be performed over it.
The data types in C can be classified as follows:
User Defined The user-defined data types are defined by the user structure,
Data Types himself. union, enum
Size Format
Data Type (bytes) Range Specifier
-2,147,483,648 to
int 4 %d
2,147,483,647
-2,147,483,648 to
long int 4 %ld
2,147,483,647
unsigned long 0 to
8 %llu
long int 18,446,744,073,709,551,615
What is a C Operator?
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and
variables. The values and variables used with operators are called operands. So we can say
that the operators are the symbols that perform operations on operands.
he conditional statements (also known as decision control structures) such as if, if else,
switch, etc. are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not. These
decision-making statements in programming languages decide the direction of the flow of
program execution.
Need of Conditional Statements
There come situations in real life when we need to make some decisions and based on these
decisions, we decide what should we do next. Similar situations arise in programming also
where we need to make some decisions and based on these decisions we will execute the next
block of code. For example, in C if x occurs then execute y else execute z. There can also be
multiple conditions like in C if x occurs then execute p, else if condition y occurs execute q,
else execute r. This condition of C else-if is one of the many ways of importing multiple
conditions. To learn how to use these control structures alongside data structures in C, the C
Programming Course Online with Data Structures provides detailed lessons on program
control and logic.
Types of Conditional Statements in C
● break
● continue
● goto
● return
Let’s discuss each of them one by one.
1. if in C
The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is
true then a block of statements is executed otherwise not.
Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not. If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by
default if statement will consider the first immediately below statement to be inside its block.
Flowchart of if Statement
2. if-else in C
The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do something else when the
condition is false? Here comes the C else statement. We can use the else statement with
the if statement to execute a block of code when the condition is false. The if-else
statement consists of two blocks, one for false expression and one for true expression.
Syntax of if else in C
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart of if-else Statement
Flow Diagram of if else
3. Nested if-else in C
A nested if in C is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. Yes, C allow us to nested if
statements within if statements, i.e, we can place an if statement inside another if statement.
Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{
// statement 1
}
else
{
// Statement 2
}
}
else {
if (condition_3)
{
// statement 3
}
else
{
// Statement 4
}
}
The below flowchart helps in visualize the above syntax.
Flowchart of Nested if-else
4. if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple options. The C
if statements are executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the rest of the C else-if
ladder is bypassed. If none of the conditions is true, then the final else statement will be
executed. if-else-if ladder is similar to the switch statement.
Syntax of if-else-if Ladder
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Flowchart of if-else-if Ladder
switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to execute
the conditional code based on the value of the variable specified in the switch statement. The
switch block consists of cases to be executed based on the value of the switch variable.
Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
Note: The switch expression should evaluate to either integer or character. It cannot evaluate
any other data type.
Flowchart of switch
6. Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar to the
if-else statement. It is also known as the ternary operator as it works on three operands.
Syntax of Conditional Operator
(condition) ? [true_statements] : [false_statements];
Flowchart of Conditional Operator
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
To create an array, define the data type (like int) and specify the name of the array followed
by square brackets [].
To insert values to it, use a comma-separated list inside curly braces, and make sure all values
are of the same data type:
This statement accesses the value of the first element [0] in myNumbers:
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
// Outputs 25
first Initializes, then condition check, then executes the body and at last, the
for loop
update is done.
first Initializes, then condition checks, and then executes the body, and
while loop
updating can be inside the body.
do-while
do-while first executes the body and then the condition check is done.
loop
To master loops and control structures in C, our C programming course offers hands-on
practice and exercises that will help you write optimized, loop-based algorithms.
for Loop
for loop in C programming is a repetition control structure that allows programmers to write
a loop that will be executed a specific number of times. for loop enables programmers to
perform n number of steps together in a single line.
Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}
Example:
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
}
In for loop, a loop variable is used to control the loop. Firstly we initialize the loop variable
with some value, then check its test condition. If the statement is true then control will move
to the body and the body of for loop will be executed. Steps will be repeated till the exit
condition becomes true. If the test condition will be false then it will stop.
● Initialization Expression: In this expression, we assign a loop variable or loop counter to
some value. for example: int i=1;
● Test Expression: In this expression, test conditions are performed. If the condition
evaluates to true then the loop body will be executed and then an update of the loop
variable is done. If the test expression becomes false then the control will exit from the
loop. for example, i<=9;
● Update Expression: After execution of the loop body loop variable is updated by some
value it could be incremented, decremented, multiplied, or divided by any value.
for loop Equivalent Flow Diagram:
While Loop
While loop does not depend upon the number of iterations. In for loop the number of
iterations was previously known to us but in the While loop, the execution is terminated on
the basis of the test condition. If the test condition will become false then it will break from
the while loop else body will be executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
}
Flow Diagram for while loop:
do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop
test condition which is tested at the end of the body. In the do-while loop, the loop body
will execute at least once irrespective of the test condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);