0% found this document useful (0 votes)
21 views20 pages

Unit 3

Uploaded by

Vijay Vivian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views20 pages

Unit 3

Uploaded by

Vijay Vivian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Unit 3 INTRODUCTION TO C

Overview of C – structure of a C program – compilation and linking processes, Constants,


Variables and Data Types – Operators and Expressions – Managing Input and Output
operators – Decision Making – Arrays, Branching and Looping, Handling of Character
Strings.

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

Declaring (Creating) Variables

To create a variable, specify the type and assign it a value:

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:

int myNum = 15;

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:

Types Description Data Types

Primitive data types are the most basic data types


Primitive Data int, char, float,
that are used for representing simple values such as
Types double, void
integers, float, characters, etc.

The data types that are derived from the primitive or


array, pointers,
Derived Types built-in datatypes are referred to as Derived Data
function
Types.

User Defined The user-defined data types are defined by the user structure,
Data Types himself. union, enum

Integer Data Type


The integer datatype in C is used to store the integer numbers (any number including positive,
negative and zero without decimal part). Octal values, hexadecimal values, and decimal
values can be stored in int data type in C.
● Range: -2,147,483,648 to 2,147,483,647
● Size: 4 bytes
● Format Specifier: %d

The integer data type can also be used as


1. unsigned int: Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768
to 32,767.
3. long int: Larger version of the int datatype so can store values greater than int.
4. unsigned short int: Similar in relationship with short int as unsigned int with int.
Character Data Type
Character data type allows its variable to store only a single character. The size of the
character is 1 byte. It is the most basic data type in C. It stores a single character and requires
a single byte of memory in almost all compilers.
● Range: (-128 to 127) or (0 to 255)
● Size: 1 byte
● Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of character type:
char var_name;

Float Data Type


In C programming float data type is used to store floating-point values. Float in C is used to
store decimal and exponential values. It is used to store decimal numbers (numbers with
floating point values) with single precision.
● Range: 1.2E-38 to 3.4E+38
● Size: 4 bytes
● Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;

Double Data Type


A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers with
decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding 64
bits of decimal numbers or floating points. Since double has more precision as compared to
that float then it is much more obvious that it occupies twice the memory occupied by the
floating-point type. It can easily accommodate about 16 to 17 digits after or before a decimal
point.
● Range: 1.7E-308 to 1.7E+308
● Size: 8 bytes
● Format Specifier: %lf
Syntax of Double
The variable can be declared as double precision floating point using the double keyword:
double var_name;

Size Format
Data Type (bytes) Range Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

-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 int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long 0 to
8 %llu
long int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f


Size Format
Data Type (bytes) Range Specifier

double 8 1.7E-308 to 1.7E+308 %lf

long double 16 3.4E-4932 to 1.1E+4932 %Lf

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.

Decision Making statements:

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

Following are the decision-making statements available in C:


1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement
6. Conditional Operator
7. Jump Statements:

● 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:

int myNumbers[] = {25, 50, 75, 100};

We have now created a variable that holds an array of four integers.

Access the Elements of an Array

To access an array element, refer to its index number.


Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

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

There are mainly two types of loops in C Programming:


1. Entry Controlled loops: In Entry controlled loops the test condition is checked before
entering the main body of the loop. For Loop and While Loop is Entry-controlled loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end
of the loop body. The loop body will execute at least once, irrespective of whether the
condition is true or false. do-while Loop is Exit Controlled loop.
Loop Type Description

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

A String in C programming is a sequence of characters terminated with a null character ‘\0’.


The C String is stored as an array of characters. The difference between a character array and
a C string is that the string in C is terminated with a unique character ‘\0’.

C String Declaration Syntax


Declaring a string in C is as simple as declaring a one-dimensional array. Below is the basic
syntax for declaring a string.
char string_name[size];
In the above syntax string_name is any name given to the string variable and size is used to
define the length of the string, i.e the number of characters strings will store.
There is an extra terminating character which is the Null character (‘\0’) used to indicate the
termination of a string that differs strings from normal character arrays. To get a deeper
understanding of how strings are used alongside various data structures, the C Programming
Course Online with Data Structures provides a complete guide to managing and
manipulating strings efficiently in C.
C String Initialization
A string in C can be initialized in different ways. We will explain this with the help of an
example. Below are the examples to declare a string with the name str and initialize it with
“GeeksforGeeks”.
We can initialize a C string in 4 different ways which are as follows:
1. Assigning a String Literal without Size
String literals can be assigned without size. Here, the name of the string str acts as a pointer
because it is an array.
char str[] = "GeeksforGeeks";
2. Assigning a String Literal with a Predefined Size
String literals can be assigned with a predefined size. But we should always account for one
extra space which will be assigned to the null character. If we want to store a string of size n
then we should always declare a string with a size equal to or greater than n+1.
char str[50] = "GeeksforGeeks";
3. Assigning Character by Character with Size
We can also assign a string character by character. But we should remember to set the end
character as ‘\0’ which is a null character.
char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. Assigning Character by Character without Size
We can assign character by character without size with the NULL character at the end. The
size of the string is determined by the compiler automatically.
char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
Note: When a Sequence of characters enclosed in the double quotation marks is encountered
by the compiler, a null character ‘\0’ is appended at the end of the string by default.
Let us now look at a sample program to get a clear understanding of declaring, and
initializing a string in C, and also how to print a string with its size.

You might also like