0% found this document useful (0 votes)
43 views

C Full Note

C was originally developed by Dennis Ritchie at Bell Labs in the early 1970s to write the UNIX operating system. It became widely popular due to being easy to learn yet capable of producing efficient, low-level programs. The structure of a typical C program includes preprocessor directives, function definitions, and a main function that acts as the program entry point.

Uploaded by

sreeja sethu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

C Full Note

C was originally developed by Dennis Ritchie at Bell Labs in the early 1970s to write the UNIX operating system. It became widely popular due to being easy to learn yet capable of producing efficient, low-level programs. The structure of a typical C program includes preprocessor directives, function definitions, and a main function that acts as the program entry point.

Uploaded by

sreeja sethu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

1

4
5
6
8
About C Language

C is a general-purpose, high-level language that was originally developed by Dennis M.


Ritchie to develop the UNIX operating system at Bell Labs. C was originally first
implemented on the DEC PDP-11 computer in 1972.
The UNIX operating system, the C compiler, and essentially all UNIX application programs
have been written in C. C has now become a widely used professional language for various
reasons −

• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
Facts about C
• C was invented to write an operating system called UNIX.
• C is a successor of B language which was introduced around the early 1970s.
• The language was formalized in 1988 by the American National Standard
Institute (ANSI).
• The UNIX OS was totally written in C.
• Today C is the most widely used and popular System Programming Language.
• Most of the state-of-the-art software have been implemented using C.
• Today's most popular Linux OS and RDBMS MySQL have been written in C.
Why use C?
C was initially used for system development work, particularly the programs that make-up the
operating system. C was adopted as a system development language because it produces code
that runs nearly as fast as the code written in assembly language. Some examples of the use
of C might be −

• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
Structure of a C program

The structure of a C program are listed below:

1. Documentation section
2. Preprocessor section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions

1. Documentation section

It includes the statement specified at the beginning of a program, such as a program's name,
date, description, and title. It is represented as:

//name of a program

Or

/*
Overview of the code
*/

Both methods work as the document section in a program. It provides an overview of the
program. Anything written inside will be considered a part of the documentation section and
will not interfere with the specified code.

2. Preprocessor section

The preprocessor section contains all the header files used in a program. It informs the system
to link the header files to the system libraries. It is given by:

1. #include<stdio.h>
2. #include<conio.h>

The #include statement includes the specific file as a part of a function at the time of the
compilation. Thus, the contents of the included file are compiled along with the function being
compiled. The #include<stdio.h> consists of the contents of the standard input output files,
which contains the definition of stdin, stdout, and stderr. Whenever the definitions stdin, stdout,
and stderr are used in a function, the statement #include<stdio.h> need to be used.

There are various header files available for different purposes. For example, # include
<math.h>. It is used for mathematic functions in a program.

3. Define section

The define section comprises of different constants declared using the define keyword. It is
given by:

#define a = 2
4. Global declaration

The global section comprises of all the global declarations in the program. It is given by:

float num = 2.54;


int a = 5;
char ch ='z';

The size of the above global variables is listed as follows:

char = 1 byte

float = 4 bytes

int = 4 bytes

5. Main function

main() is the first function to be executed by the computer. It is necessary for a code to include
the main(). Parenthesis () are used for passing parameters (if any) to a function.

The main function is declared as:

main()

We can also use int or void with the main (). The void main() specifies that the program will
not return any value. The int main() specifies that the program can return integer type data.

int main()

Or

void main()

Main function is further categorized into local declarations, statements, and expressions.
Local declarations

The variable that is declared inside a given function or block refers to as local declarations.

void main()
{
int i = 2;
i++;
}

Statements

The statements refers to if, else, while, do, for, etc. used in a program within the main function.

Expressions

An expression is a type of formula where operands are linked with each other by the use of
operators. It is given by:

1. a - b;
2. a +b;

6. User defined functions

The user defined functions specified the functions specified as per the requirements of the user.
For example, color(), sum(), division(), etc.

Example 1: To find the sum of two numbers given by the user

/* Sum of two numbers */


#include<stdio.h>
void main()
{
int a, b, sum;
printf("Enter two numbers to be added ");
scanf("%d %d", &a, &b);
// calculating sum
sum = a + b;
printf("%d + %d = %d", a, b, sum);
getch(); // return the integer value in the sum
}
Output
Introduction to Programming Languages & Translators

Language is way of communication between two persons.


Computer Languages are communication between computer and person.
Computers can understand only machine instructions. Instructions are to be given
in machine understandable language.
A programming language is defined by a set of rules. It is a formal constructed
language, designed to communication instructions to a computer. Programming
languages can be used to create programs to control the behaviour of the machine.
A program is a list of instructions or statements for directing the computer to
perform a required data-processing task.

TYPES

Machine language:

At the lowest level computer understands only 0 and 1.


Programs expressed in terms of binary language are called machine language and
is the only one language computer can understand.
A computer’s programming language consists of strings of binary numbers (0’s
and 1’s).
A machine language programmer
o has to know the binary code for each operation to be carried out,
o must also be familiar with the internal organization of the computer, must also
keep track of all the addresses of main memory locations that are referred to in the
program.
Assembly language and Assembler:

A low level first generation computer language, popular during early 1960s, which
uses abbreviations or mnemonic codes for operation. This symbolic instruction
language is called Assembly language.
The mnemonics are converted into binaries with the help of a translator known as
Assembler.
The program written using mnemonics is called Source Program or assembly
language program, the binary form of the source program equivalent is called
Object Program.
Assembler is used to convert assembly language into the machine language.
Assembly language programs are commonly used to write programs for electronic
controls using microprocessors e.g., compilers, operating systems, animation in
computer graphics and so on.

High level languages and compiler:

Instructions which are written using English language with symbols and digits are
called high level languages and is closer to our natural language.
The commonly used high level languages are FORTRAN, BASIC, COBOL,
PASCAL, PROLOG, C, C++, JAVA etc.

The complete instruction set written in one of these languages is called a high
level language program or computer program or source program.
In order to execute the instructions, the source program is translated into binary
form by a compiler or interpreter.

Compiler:

Compiler is a translator that converts the program instructions from human


understandable form (high level language) to machine understandable form (machine
language) and the translated program instruction is called object code. Every
programming language requires its own compiler to translate the program. A compiler
is also used to translate source program into an object program.

Interpreter:

An interpreter is a program which takes the source program line by line and converts
into machine code but execute each line by line as it is entered. Programming
languages BASIC, LISP, JAVA use interpreters.
A simple code that would print the words "Hello World"

#include <stdio.h>
#include <conio.h>
void main()
{
/* my first program in C */
printf("Hello, World! \n");

getch();
}

➢ #include <stdio.h> : It includes the standard input output library functions.


The printf() and scanf() function is defined in stdio.h . Both functions are inbuilt
library functions.
➢ main() : The main() function is the entry point of every program in c
language.
➢ printf(): The printf() function is used to print data on the console.

The syntax of printf() function is given below:

1. printf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

➢ scanf() function

The scanf() function is used for input. It reads the input data from the console.

1. scanf("format string",argument_list);

➢ How to compile and run the c program

There are 2 ways to compile and run the c program, by menu and by shortcut.

By menu
Now click on the compile menu then compile sub menu to compile the c program.

Then click on the run menu then run sub menu to run the c program.
By shortcut
Press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.

You can view the user screen any time by pressing the alt+f5 keys.

Compilation process in c
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 compilation process can be divided into four steps, i.e., Pre-processing, Compiling,
Assembling, and Linking.

The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor 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:

o Preprocessor
o Compiler
o Assembler
o Linker
Preprocessor
The source code is the code which is written in a text editor and the source code file is given
an extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.

Compiler

The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the pre-
processed code into assembly code.

Assembler

The assembly code is converted into object code by using an assembler. The name of
the object file generated by the assembler is the same as the source file. The extension
of the object file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the
source file is 'hello.c', then the name of the object file would be 'hello.obj'.

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. 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.
In the above flow diagram, the following steps are taken to execute a program:

o Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the
preprocessor converts the source code into expanded source code. The
extension of the expanded source code would be hello.i.
o The expanded source code is passed to the compiler, and the compiler converts
this expanded source code into assembly code. The extension of the assembly
code would be hello.s.
o This assembly code is then sent to the assembler, which converts the assembly
code into object code.
o After the creation of an object code, the linker creates the executable file. The
loader will then load the executable file for the execution.
1
3
4
Executable File

An executable file is a type of computer file that runs a program when it is opened. This means
it executes code or a series of instructions contained in the file. The two primary types of
executable files are 1) compiled programs and 2) scripts.

On Windows systems, compiled programs have an .EXE file extension and are often referred
to as "EXE files." On Macintosh computers, compiled programs have an .APP extension,
which is short for application.

Uncompiled executable files are often referred to as scripts. These files are saved in a plain
text format, rather than a binary format. In other words, you can open a script file and view the
code in a text editor. Since scripts do not contain executable machine code, they require
an interpreter to run. For example, a PHP file can execute code only when run through a PHP
interpreter. If a PHP interpreter is not available, the PHP script can only be opened as a text
file.

Since executable files run code when opened, you should not open unknown executable files,
especially ones received as email attachments. While compiled executable files are the most
dangerous, script files can run malicious code as well.

Windows file extensions: .EXE, .COM, .BAT, .VB, .VBS, .WSF, .PIF
Macintosh file extensions: .APP, .SCPT, .APPLESCRIPT

File extensions

A file extension is a three- or four-letter identifier found at the end of a file name and following
a period. These extensions tell you about the characteristics of a file and its use.

• Audio file extension

There are several audio file extensions used today.

.aif - AIF audio file

.mp3 - MP3 audio file

.ogg - Ogg Vorbis audio file

.wav - WAV file

• Executable file extensions

The most common executable file are files ending with the .exe file extension.

.apk - Android package file


.com - MS-DOS command file

.exe - Executable file

• Image file extension


There are many different image types and image file extensions that can be used when creating
and saving images on the computer.
.bmp - Bitmap image
.gif - GIF image
.jpeg or .jpg - JPEG image
.png - PNG image
• Programming file extensions
Many file extensions are used for programs before they are compiled or used as scripts.
.c - C source code file
.class - Java class file
.cpp - C++ source code file
.java - Java Source code file
.php - PHP script file.

What is a header file?


In C language, header files contain the set of predefined standard library functions. Your
request to use a header file in your program by including it with the C preprocessing
directive “#include”. All the header files have a ‘.h’ an extension. By including a header file,
we can use its contents in our program.

A header file contains:

1. Function definitions
2. Data type definitions
3. Macros

Whenever we require the definition of a function, then we simply include that header file in which
function is declared. Header file is used to avoid writing large and complex code.

There are two types of header files defined in a program:

o System defined header file: The header file which is predefined is known as a system
defined header file.
o User-defined header file: The header file which is defined by the user is known as a
user-defined header file.

Both the user-defined and system-defined header file can be included in a program with the
help of using preprocessing directive (#). These preprocessor directives are used to instruct the
compiler to process these files before compilation. There are two forms of including header
file:

o #include<file>
o #include "file"

There is a difference between the header files given above. If the header file is defined within
the predefined source path, we can specify the header within the angular brackets. If the header
file is not defined within the predefined source path then we can specify the full path of the
header file within the double-quotes.

Some of the header files are given below:

o #include<stdio.h>: It is used for performing input and output operations with the help
of using printf() and scanf() function.
o #include<string.h>: It is used for performing string related functionalities like strlen(),
strcmp(), etc.
o #include<iostream>: It is used to perform input and output operations with the help of
using cin and cout objects.
o #include<math.h>: This header file contains some predefined math functions that
perform mathematical operations, such as sqrt(), log2(), pow(), etc.
o #include<errno.h>: It performs the error handling related operations like errno(),
strerror(), perror(), etc.
o #include<time.h>: It is used to perform functions related to date()
and time() like setdate() and getdate().

➢ Preprocessor Directives
The preprocessor directives give instruction to the compiler to preprocess the information
before actual compilation starts.

All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates
that, whatever statement starts with #, is going to the preprocessor program, and preprocessor
program will execute this statement. Examples of some preprocessor directives
are: #include, #define, #ifndef etc.

There are 4 main types of preprocessor directives:


1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives

➢ C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros:

1. Object-like Macros
2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:

1. #define PI 3.14

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Example:

// C program to illustrate macros


#include <stdio.h>

// Macro definition
#define LIMIT 5

int main()
{
// Print the value of macro defined
printf("The value of LIMIT is %d", LIMIT);

return 0;
}

Output:
The value of LIMIT is 5
 Variables
A variable is a name of the memory location. It is used to store data. Its value can be changed,
and it can be reused many times.

The primary purpose of variables is to store data in memory for later use. If you declare a variable
in C, that means you are asking the operating system to reserve a piece of memory with that
variable name.
Variable Declaration
data type variable_name;

or
data type variable_name, variable_name, variable_name;

Variable Declaration and Initialization


Example:
int width, height=5;

char letter='A';

float age, area;

double d;

/* actual initialization */

width = 10;

age = 26.5;

Variable Assignment

A variable assignment is a process of assigning a value to a variable.

Example:
int width = 60;

int age = 31;


 Rules for naming the variables

 A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and the
underscore character.
 The first character must be a letter or underscore.
 Blank spaces cannot be used in variable names.
 Special characters like #, $ are not allowed.
 C keywords cannot be used as variable names.
 Variable names are case sensitive.
 Values of the variables can be numeric or alphabetic.
 Variable type can be char, int, float, double, or void.

C Program to Print Value of a Variable


Example:
#include<stdio.h>

#include<conio.h>

void main()

int age = 33; // c program to print value of a variable

printf("I am %d years old.\n", age);

Program Output:
I am 33 years old.

 Types of Variables
There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

void function1()
{
int x=10;//local variable
}

You must have to initialize the local variable before it is used.

Global Variable

A variable that is declared outside the function or block is called a global variable. Any function
can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

int value=20;//global variable

void function1()
{
int x=10;//local variable
}
Static Variable

A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.


void function1()
{
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}

If you call this function many times, the local variable will print the same value for each function
call, e.g, 11,11,11 and so on. But the static variable will print the incremented value in each
function call, e.g. 11, 12, 13 and so on.

 Identifiers
An identifier is a collection of alphanumeric characters that begins either with an alphabetical

character or an underscore, which are used to represent various programming elements such as variables,

functions, arrays, structures, unions, labels, etc. An identifier can be composed of letters such as

uppercase, lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an

underscore.

Example of valid identifiers

total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers

2sum (starts with a numerical digit)

1. int (reserved word)


2. char (reserved word)
3. m+n (special character, i.e., '+')
 Rules for constructing C identifiers
o The first character of an identifier should be either an alphabet or an underscore, and then

it can be followed by any of the character, digit, or underscore.

o It should not begin with any numerical digit.


o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that

identifiers are case sensitive.

o Commas or blank spaces cannot be specified within an identifier.


o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Constants
Constants are the fixed values that are used in a program, and its value remains the same during
the entire execution of the program.

2 ways to define constant in C

There are two ways to define constant.

1. const keyword
2. #define preprocessor

1) const keyword

The const keyword is used to define constant in C programming.

const float PI=3.14;

Now, the value of PI variable can't be changed.


#include<stdio.h>
#include<conio.h>
void main()
{
const float PI=3.14;
printf("The value of PI is: %f",PI);
geth();
}

Output:

The value of PI is: 3.140000

2) #define preprocessor

The #define preprocessor is also used to define constant.

#include<stdio.h>

#include<conio.h>

#define LIMIT 5

void main()

printf("The value of LIMIT is %d", LIMIT);

getch();

Output: The value of LIMIT is 5


List of Constants in C

Primary Constants

1. Numeric Constants
o Integer Constants
o Real Constants

2. Character Constants
o Single Character Constants
o String Constants
o Backslash Character Constants

Integer Constant

It's referring to a sequence of digits. Integers are of three types :

1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6

Real constant

The numbers containing fractional parts like 99.25 are called real or floating points constant.

Single Character Constants

It simply contains a single character enclosed within ' ' (a pair of single quote). It is to be noted
that the character '8' is not the same as 8.

Example:

'X', '5', ';'


String Constants

These are a sequence of characters enclosed in double quotes, and they may include letters,
digits, special characters, and blank spaces. It is again to be noted that "G" and 'G' are different -
because "G" represents a string as it is enclosed within a pair of double quotes whereas 'G'
represents a single character.

Example:

"Hello!", "2015", "2+1"

Backslash character constant

C supports some character constants having a backslash in front of it. The lists of backslash
characters have a specific meaning which is known to the compiler. They are also termed as
"Escape Sequence".

For Example:

\t is used to give a tab


\n is used to give a new line
Constants Meaning

\a beep sound

\b backspace

\f form feed

\n new line

\r carriage return

\t horizontal tab

\v vertical tab

\' single quote

\" double quote


\\ backslash

\0 null

Secondary Constant

 Array
 Pointer
 Structure
 Union
 Enum

What are literals?


Literals are the constant values assigned to the constant variables. We can say that the literals
represent the fixed values that cannot be modified. It also contains memory but does not have
references as variables. For example, const int =10; is a constant integer expression in which 10 is
an integer literal.

 Data Types
A data type specifies the type of data that a variable can store such as integer, floating, character,
etc.
There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating system.

int Used to denote an integer type.

char Used to denote a character type.

float, double Used to denote a floating point type.

Declaration
After taking suitable variable names, they need to be assigned with a data type. This is how the
data types are used along with variables:

Example:
int age;

char letter;

float height, width;

The following table provides the details of standard integer types with their storage sizes and
value ranges −
Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

-32,768 to 32,767 or -2,147,483,648 to


int 2 or 4 bytes
2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 8 bytes or (4bytes for 32 bit OS) -9223372036854775808 to


9223372036854775807

unsigned long 8 bytes 0 to 18446744073709551615

To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or
type in bytes.
The following table provide the details of standard floating-point types with storage sizes
and value ranges and their precision.
Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Derived Data Type


Structure It is a package of variables of different types under a single name. This is done to handle
data efficiently. "struct" keyword is used to define a structure.

Union These allow storing various data types in the same memory location. Programmers can
define a union with different members, but only a single member can contain a value at a
given time.

Pointers Which are used to access the memory and deal with their addresses.

Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements
of the same type.

Void Data Type


void As the name suggests, it holds no value and is generally used for specifying the type of
function or what it returns. If the function has a void type, it means that the function
will not return any value.

Enumeration Data Type

Enum Enumeration is a special data type that consists of integral constants, and each of them is
assigned with a specific name. "enum" keyword is used to define the enumerated data type.
Module 2
OPERATORS AND EXPRESSIONS

 The symbols which are used to perform logical and mathematical operations in a C program
are called C operators.
 These C operators join individual constants and variables to form expressions.
 Operators, functions, constants and variables are combined together to form expressions.
 Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant
and A + B * 5 is an expression.

TYPES OF C OPERATORS:

 An operator is a symbol that operates on a value or a variable. C language offers many types
of operators. They are,

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

1. Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction,
multiplication, division etc on numerical values.

Operator Meaning of Operator


+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division (modulo division)
Example 1: Arithmetic Operators
// Working of arithmetic operators
#include <stdio.h>
void main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
getch();
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
2. Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b

Example 3: Assignment Operators

// Working of assignment operators


#include <stdio.h>
void main()
{
int a = 5, c;

c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);

getch();
}

Output

c=5
c = 10
c=5
c = 25
c=5
c=0

3. Relational Operators

A relational operator checks the relationship between two operands. If the relation is true,
it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators

// Working of relational operators


#include <stdio.h>
void main()
{
int a = 5, b = 5, c = 10;

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


printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

getch();
}

Output

5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1

4. Logical Operators

An expression containing logical operator returns either 0 or 1 depending upon whether


expression results true or false. Logical operators are commonly used in decision making
in C programming.
Operator Meaning Example

Logical AND. True only if all If c = 5 and d = 2 then, expression


&&
operands are true ((c==5) && (d>5)) equals to 0.

Logical OR. True only if either If c = 5 and d = 2 then, expression


||
one operand is true ((c==5) || (d>5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression !(c==5) equals


!
operand is 0 to 0.

Example 5: Logical Operators

// Working of logical operators

#include <stdio.h>
void main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) is %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) is %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);


printf("!(a != b) is %d \n", result);

result = !(a == b);


printf("!(a == b) is %d \n", result);

getch();
}
Output

(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0

5. Bitwise Operators

During computation, mathematical operations like: addition, subtraction, multiplication,


division, etc are converted to bit-level which makes processing faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

6. Increment and Decrement Operators

C programming has two operators increment ++ and decrement -- to change the value of
an operand (constant or variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1.


These two operators are unary operators, meaning they only operate on a single operand.

Example 2: Increment and Decrement Operators

// Working of increment and decrement operators


#include <stdio.h>
void main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

getch();
}

Output

++a = 11
--b = 99
++c = 11.500000
--d = 99.500000

Here, the operators ++ and -- are used as prefixes. These two operators can also be used
as postfixes like a++ and a--.

7. Other Operators

 Comma Operator

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;
 The sizeof operator
The sizeof is a unary operator that returns the size of data (constants, variables, array,
structure, etc).

Example 6: sizeof Operator

#include <stdio.h>
void main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));

getch();
}

Output

Size of int = 4 bytes


Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

8. Conditional Operator

The conditional operator is also known as a ternary operator. The conditional statements are the
decision-making statements which depends upon the output of the expression. It is represented by
two symbols, i.e., '?' and ':'.

As conditional operator works on three operands, so it is also known as the ternary operator.

The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is
also a decision-making statement.

Syntax of a conditional operator


1. Expression1? expression2: expression3;

o In the above syntax, the expression1 is a Boolean condition that can be either true or false
value.
o If the expression1 results into a true value, then the expression2 will execute.
o The expression2 is said to be true only when it returns a non-zero value.
o If the expression1 returns false value then the expression3 will execute.
o The expression3 is said to be false only when it returns zero value.

#include <stdio.h>
void main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditi
onal operator
getch();
}

Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


Format Specifier

The Format specifier is a string used in the formatted input and output functions. The format
string determines the format of the input and output. The format string always starts with a '%'
character.

The commonly used format specifiers in printf() function are:

Format Description
specifier

%d or %i It is used to print the signed integer value where signed integer means
that the variable can hold both positive and negative values.

%u It is used to print the unsigned integer value where the unsigned integer
means that the variable can hold only positive value.

%f It is used for printing the decimal floating-point values. By default, it


prints the 6 values after '.'

%c It is used to print the unsigned character.

%s It is used to print the strings.

Decision Making

Decision making structures require that the programmer specifies one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed if
the condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Show below is the general form of a typical decision-making structure found in most of the
programming languages −
C programming language provides the following types of decision-making statements.

Sl.No. Statement & Description

1 if statement

An if statement consists of a boolean expression followed by one or more


statements.

2 if...else statement
An if statement can be followed by an optional else statement, which executes
when the Boolean expression is false.

3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).

4 switch statement
A switch statement allows a variable to be tested for equality against a list of
values.

5 nested switch statements


You can use one switch statement inside another switch statement(s).

1. if Statement

The if statement is used to check some given condition and perform some operations depending
upon the correctness of that condition. It is mostly used in the scenario where we need to
perform the different operations for the different conditions. The syntax of the if statement is
given below.

Syntax:
if(expression)
{

//code to be executed
}
Flowchart:

Example:
#include <stdio.h>
#include <conio.h>
void main () {
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
getch();
}
Output:
a is less than 20;
value of a is : 10

2. if-else Statement

The if-else statement is used to perform two operations for a single condition. The if-else
statement is an extension to the if statement using which, we can perform two different
operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness
of the condition. Here, we must notice that if and else block cannot be executed simultaneously.
The syntax of the if-else statement is given below.

Syntax:

if(expression)
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
}
Flowchart:
Example to check whether a number is even or odd using if-else statement.

#include<stdio.h>
#include<stdio.h>
void main()
{
int number;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0)
{
printf("%d is even number",number);
}
else
{
printf("%d is odd number",number);
}
getch();
}

3. if else-if ladder Statement

The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario
where there are multiple cases to be performed for different conditions. In if-else-if ladder
statement, if a condition is true then the statements defined in the if block will be executed,
otherwise if some other condition is true then the statements defined in the else-if block will
be executed, at the last if none of the condition is true then the statements defined in the else
block will be executed. There are multiple else-if blocks possible.

Syntax:

if(condition1){

//code to be executed if condition1 is true


}
else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Flowchart:

Example Program to calculate the grade of the student according to the specified
marks.

#include <stdio.h>
#include<conio.h>
void main()
{
int marks;
printf("Enter your marks?");
scanf("%d",&marks);
if(marks > 85 && marks <= 100)
{
printf("Congrats ! you scored grade A ...");
}
else if (marks > 60 && marks <= 85)
{
printf("You scored grade B + ...");
}
else if (marks > 40 && marks <= 60)
{
printf("You scored grade B ...");
}
else if (marks > 30 && marks <= 40)
{
printf("You scored grade C ...");
}
else
{
printf("Sorry you are fail ...");
}
}

Output:

Enter your marks?10


Sorry you are fail ...
Enter your marks?40
You scored grade C ...
Enter your marks?90
Congrats ! you scored grade A ...

4. nested-if

Nested if statements mean an if statement inside another if statement.

Syntax:

if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Flowchart :

Example:

#include <stdio.h>
#include <conio.h>
void main()
{
int dig1, dig2, dig3;
printf("Enter three numbers: ");
scanf("%d%d%d", &dig1, &dig2, &dig3);
if(dig1 > dig2)
{
if(dig1 > dig3)
{
printf("dig1 is the maximum");
}
else
{
printf("dig3 is the maximum");
}
}
else
{
if(dig2 > dig3)
{
printf("dig2 is the maximum");
}
else
{
printf("dig3 is the maximum");
}
}
getch();
}

5.Switch Statement

The switch statement in C is an alternate to if-else-if ladder statement which allows us to


execute multiple operations for the different possible values of a single variable called switch
variable. Here, we can define various statements in the multiple cases for the different values
of a single variable.

Syntax :

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}

Rules for switch statement

1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement
found in the case, all the cases will be executed present after the matched case. It is known
as fall through the state of C switch statement.

Flowchart:
Functioning of switch case statement:

First, the integer expression specified in the switch statement is evaluated. This value is then
matched one by one with the constant values given in the different cases. If a match is found,
then all the statements specified in that case are executed along with the all the cases present
after that case including the default statement. No two cases can have similar values. If the
matched case contains a break statement, then all the cases present after that will be skipped,
and the control comes out of the switch. Otherwise, all the cases following the matched case
will be executed.

Example:

include <stdio.h>

include <conio.h>
void main()
{
char operator;
int num1,num2;
printf(“\n Enter the operator (+, -, *, /):”);
scanf(“%c”,&operator);
printf(“\n Enter the Two numbers:”);
scanf(“%d%d”,&num1,&num2);
switch (operator)
{
case ‘+’:
printf(“%d+%d=%d”,num1,num2,num1+num2);
break;
case ‘-‘:
printf(“%d-%d=%d”,num1,num2,num1-num2);
break;
case ‘*’:
printf(“%d*%d=%d”,num1,num2,num1*num2);
break;
case ‘/’:
printf(“%d / %d = %d”,num1,num2,num1/num2);
break;
default:
printf(“\n Enter a valid operator only”);
break;

getch();

}
CONTROL STATEMENTS

“C” supports mainly three types of control statements.

1. Decision making statements


a) if Statement
b) if – else Statement
c) Nested if-else statement
d) else – if Ladder
e) switch statement

2. Loop control statements


a) for Loop
b) while Loop
c) do-while Loop

3. Unconditional control statements


a) goto Statement
b) break Statement
c) continue Statement
d) return statement

Loop control statements

The looping can be defined as repeating the same process multiple times until a specific
condition satisfies. There are three types of loops used in the C language.

Why use loops in C language?

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow
of the program so that instead of writing the same code again and again, we can repeat the same
code for a finite number of times. For example, if we need to print the first 10 natural numbers
then, instead of using the printf statement 10 times, we can print inside a loop which runs up
to 10 iterations.

Advantage of loops in C

1) It provides code reusability.

2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures (array or linked lists).

Types of C Loops

There are three types of loops in C language.


1. do while
2. while
3. for

1. do-while loop

The do-while loop continues until a given condition satisfies. It is also called post tested loop.
It is used when it is necessary to execute the loop at least once.

The syntax of do-while loop.

do{
//code to be executed
}while(condition);

Flowchart of do while loop

Example
#include<stdio.h>
void main(){
int i=1;
do{
printf("%d \n",i);
i++;
}while(i<=10);
getch();
}

Infinitive do while loop

The do-while loop will run infinite times if we pass any non-zero value as the conditional
expression.

do{
//statement
}while(1);

2. while loop

The while loop in c is to be used in the scenario where we don't know the number of iterations
in advance. The block of statements is executed in the while loop until the condition specified
in the while loop is satisfied. It is also called a pre-tested loop.

The syntax of while loop in c language is given below:

while(condition){
//code to be executed
}
Flowchart of while loop in C
Example

#include<stdio.h>
void main(){

int i=1;
while(i<=10){
printf("%d \n",i);
i++;
}
getch();
}

Properties of while loop

o A conditional expression is used to check the condition. The statements defined inside
the while loop will repeatedly execute until the given condition fails.
o The condition will be true if it returns 0. The condition will be false if it returns any
non-zero number.
o In while loop, the condition expression is compulsory.
o Running a while loop without a body is possible.
o We can have more than one conditional expression in while loop.
o If the loop body contains only one statement, then the braces are optional.

Infinitive while loop

If the expression passed in while loop results in any non-zero value then the loop will run the
infinite number of times.

while(1){
//statement
}

3. for loop

The for loop is used in the case where we need to execute some part of the code until the given
condition is satisfied. It is better to use for loop if the number of iteration is known in advance.
The syntax of for loop:

for(initialization;condition;incr/decr){
//code to be executed
}

Flowchart of for loop

Example
#include<stdio.h>
void main(){
int i;
for(i=1;i<=10;i++){
printf("%d \n",i);
}
getch();
}

Loop body
The braces {} are used to define the scope of the loop. However, if the loop contains only one
statement, then we don't need to use braces. A loop without a body is possible. The braces work
as a block separator, i.e., the value variable declared inside for loop is valid only for that block
and not outside.

Infinitive for loop


To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we
need to provide two semicolons to validate the syntax of the for loop. This will work as an
infinite for loop.

#include<stdio.h>
void main ()
{
for(;;)
{
printf("welcome");
}
getch();
}

break statement
The break is a keyword in C which is used to bring the program control out of the loop. The
break statement is used inside loops or switch statement. The break statement breaks the loop
one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. The break statement in C can be used in the following two scenarios:

1. With switch case


2. With loop

Syntax:

//loop or switch case


break;
Flowchart of break

Example

#include<stdio.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
getch();
}

Output

0 1 2 3 4 5 came outside of loop i = 5

continue statement

The continue statement in C language is used to bring the program control to the beginning
of the loop. The continue statement skips some lines of code inside the loop and continues with
the next iteration. It is mainly used for a condition so that we can skip some code for a particular
condition.
Syntax:

//loop statements
continue;
//some lines of the code which is to be skipped

Example

#include<stdio.h>
int main(){
int i=1;//initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++){
if(i==5){//if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}//end of for loop
return 0;
}

Output

1
2
3
4
6
7
8
9
10

As you can see, 5 is not printed on the console because loop is continued at i==5.
Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc. It also has the capability to
store the collection of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly accessed by using its index
number.

C array is beneficial if you have to store similar elements. For example, if we want to store
the marks of a student in 6 subjects, then we don't need to define different variables for the
marks in the different subject. Instead of that, we can define an array which can store the
marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are required
to access the elements of the array.

Properties of Array
The array contains the following properties.

• Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.

• Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.

• Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.

Advantages

1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList.

Declaration of Array

We can declare an array in the following way.

data_type array_name[array_size];

Example

int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of Array
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index.

Example

marks[0]=80;//initialization of array

marks[1]=60;

marks[2]=70;

marks[3]=85;

marks[4]=75;

Array: Declaration with Initialization


We can initialize the array at the time of declaration.
int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define the size. So it may also be written as the
following code.

int marks[]={20,30,40,50,60};

Array example:

#include<stdio.h>

void main(){

int i=0;

int marks[5];//declaration of array

marks[0]=80;//initialization of array

marks[1]=60;

marks[2]=70;

marks[3]=85;

marks[4]=75;

//traversal of array

for(i=0;i<5;i++){

printf("%d \n",marks[i]);

}//end of for loop

getch();

Two Dimensional Array


The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D
arrays are created to implement a relational database look alike data structure. It provides
ease of holding the bulk of data at once which can be passed to any number of functions
wherever required.

Declaration of two dimensional Array


The syntax to declare the 2D array is:

data_type array_name[rows][columns];

Example:

int twodimen[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.

Initialization of 2D Array

In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D arrays. We
will have to define at least the second dimension of the array. The two-dimensional array can
be declared and defined in the following way.

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Two-dimensional array example:

#include<stdio.h>

void main(){

int i=0,j=0;

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

//traversing 2D array

for(i=0;i<4;i++){

for(j=0;j<3;j++){

printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);

}//end of j

}//end of i

getch();

}
Module 3
Concept of modular programming

The concept of modular programming originated in the 1960s to help users. Programmers
began to divide the more extensive programs into smaller parts. It is the most convenient
programming method.

Modular programming is the process of subdividing a computer program into separate sub-
programs. A module is a separate software component. It can often be used in a variety of
applications and functions with other components of the system.

• Some programs might have thousands or millions of lines and to manage such
programs it becomes quite difficult as there might be too many of syntax errors or
logical errors present in the program, so to manage such type of programs concept of
modular programming approached.

• Each sub-module contains something necessary to execute only one aspect of the
desired functionality.

• Modular programming emphasis on breaking of large programs into small problems


to increase the maintainability, readability of the code and to make the program handy
to make any changes in future or to correct the errors.

Examples of modular programming languages

All the object-oriented programming languages like C++, Java, etc., are modular
programming languages.

Advantages of Modular Programming Approach :

• Ease of Use :This approach allows simplicity, as rather than focusing on the entire
thousands and millions of lines code in one go we can access it in the form of
modules. This allows ease in debugging in the code.

• Reusability :It allows the user to reuse the functionality with a different interface
without typing the whole program again.

• Ease of Maintenance : It helps in less collision at the time of working on modules,


helping a team to work with proper collaboration while working on a large
application.

Disadvantages of modular programming :

• There is a need for extra time and budget for a product in modular programming.
• It is a challenging task to combine all the modules.

• Careful documentation is required so that other program modules are not affected.

• Some modules may partly repeat the task performed by other modules. Hence,
Modular programs need more memory space and extra time for execution.
Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program.

Advantages of functions

• By using functions, we can avoid rewriting same logic/code again and again in a
program.

• We can call C functions any number of times in a program and from any place in a
program.

• We can track a large C program easily when it is divided into multiple functions.

• Reusability is the main achievement of C functions.

• However, Function calling is always a overhead in a C program.

Function Aspects

There are three aspects of a function.

• Function declaration

A function must be declared globally in a c program to tell the compiler about the function
name, function parameters, and return type.

• Function call

Function can be called from anywhere in the program. The parameter list must not differ in
function calling and function declaration. We must pass the same number of parameters as it
is declared in the function declaration.

• Function definition

It contains the actual statements which are to be executed. It is the most important aspect to
which the control comes when the function is called. Here, we must notice that only one
value can be returned from the function.
The syntax of creating function is given below:

return_type function_name(data_type parameter...)

//code to be executed

Types of Functions

There are two types of functions in C programming:


• Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.

• User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.

Return Value

A function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.

Example without return value:

void hello(){

printf("hello c");

If you want to return any value from the function, you need to use any data type such as int,
long, char, etc. The return type depends on the value to be returned from the function.

Example with return value:

int get(){

return 10;

}
In the above example, we have to return 10 as a value, so the return type is int. If you want to
return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type
of the method.

Different aspects of function calling:

A function may or may not accept any argument. It may or may not return any value. Based
on these facts, There are four different aspects of function calls.

• function without arguments and without return value

• function without arguments and with return value

• function with arguments and without return value

• function with arguments and with return value

1. Example for Function without argument and without return value

#include<stdio.h>

#include<conio.h>

void sum();

void main()

printf("\nGoing to calculate the sum of two numbers:");

sum();

void sum()

int a,b;

printf("\nEnter two numbers");

scanf("%d %d",&a,&b);

printf("The sum is %d",a+b);

2. Example for Function with argument and without return value

#include<stdio.h>
void sum(int, int);

void main()

int a,b,result;

printf("\nGoing to calculate the sum of two numbers:");

printf("\nEnter two numbers:");

scanf("%d %d",&a,&b);

sum(a,b);

void sum(int a, int b)

printf("\nThe sum is %d",a+b);

Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place
called the library. Such functions are used to perform some specific operations. For example,
printf is a library function used to print on the console. The library functions are created by
the designers of compilers. All C standard library functions are defined inside the different
header files saved with the extension .h. We need to include these header files in our program
to make use of the library functions defined in such header files. For example, To use the
library functions such as printf/scanf we need to include stdio.h in our program which is a
header file that contains all the library functions regarding standard input/output.

The list of mostly used header files are:


Pointers
The pointer in C language is a variable which stores the address of another variable. This variable
can be of type int, char, array, function, or any other pointer. The size of the pointer depends on
the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.

 Pointers : Key Points

 Normal variables stores value, and pointer variable stores address.


 The pointer in c is used to allocate memory dynamically (at run time).
 C language has two symbols ( & and *) to work with pointers.
 & – returns the address of a variable in C.
 * – returns the value of a variable, pointed by a pointer variable.
 %p – Format in c to print pointer reference.

 Example

int n = 10;
int *p=&n; // Variable p of type pointer is pointing to the address of the variable n of type integer.

Normal variable
Whenever we declare a variable in c, it takes some space in memory and each memory has a unique
address.

Print address of a variable in C language.


#include<stdio.h>
int main()
{
int n=10;
printf("\n %d",n); // print value of n.
printf("\n %p",&n); //print address of n
return 0;
}
Sample Output:
10
0x7ffe676efd6c
 Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection
pointer used to dereference a pointer.

int *a;//pointer to int


char *c;//pointer to char

#include<stdio.h>
int main()
{
int n, *p;
n=10;
p=&n;
printf("\nValue : %d", n); // print value of n.
printf("\nAddress %p", p); //print address of n
printf("\nValue : %d", *p); // print value of n.
return 0;
}
Sample Output:

Value : 10
Address 0x7ffd90c6b3b4
Value: 10

Advantages of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees,
etc. and used with arrays, structures, and functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.
Usage of pointer

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where
the pointer is used.

2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and
improves the performance.

 The Address of (&) and dereference (*) operators with the pointers

1) The Address of Operator (&)

It is an "address of" operator which returns the address of any variable. The
statement &var1 represents the address of var1 variable. Since it can be used anywhere but with
the pointers, it is required to use for initializing the pointer with the address of another variable.

2 ) The Dereference Operator (*)

It is used for two purposes with the pointers 1) to declare a pointer, and 2) get the value of a
variable using a pointer.

Example:

#include <stdio.h>
int main(void)
{
//normal variable
int num = 100;
//pointer variable
int *ptr;
//pointer initialization
ptr = &num;
//printing the value
printf("value of num = %d\n", *ptr);
//printing the addresses
printf("Address of num: %x\n", &num);
printf("Address of ptr: %x\n", &ptr);

return 0;
}
Output:
value of num = 100
Address of num: 9505c134
Address of ptr: 9505c138

Double Pointer (Pointer to Pointer)


A pointer is used to store the address of a variable in C. Pointer reduces the access time of a
variable. However, In C, we can also define a pointer to store the address of another pointer. Such
pointer is known as a double pointer (pointer to pointer). The first pointer is used to store the
address of a variable whereas the second pointer is used to store the address of the first pointer.

The syntax of declaring a double pointer is given below.

int **p; // pointer to a pointer which is pointing to an integer.

Example:

#include<stdio.h>

void main ()

int a = 10;
int *p;

int **pp;

p = &a; // pointer p is pointing to the address of a

pp = &p; // pointer pp is a double pointer pointing to the address of pointer p

printf("address of a: %x\n",p); // Address of a will be printed

printf("address of p: %x\n",pp); // Address of p will be printed

printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 10 will be
printed

printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the pointer
stored at pp

Output:
address of a: d26a8734
address of p: d26a8738
value stored at p: 10
value stored at pp: 10

Call by value and Call by reference


There are two methods to pass the data into the function in C language, i.e., call by value and call
by reference.
Call by value
o In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the function
call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
o In call by value, different memory is allocated for actual and formal parameters since the
value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.
Example: Swapping the values of the two variables

#include <stdio.h>

void swap(int , int); //prototype of the function

int main()

int a = 10;

int b = 20;

printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a
and b in main

swap(a,b);

printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters
do not change by changing the formal parameters in call by value, a = 10, b = 20

void swap (int a, int b)

int temp;

temp = a;

a=b;

b=temp;

printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20,


b = 10

}
Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference
o In call by reference, the address of the variable is passed into the function call as the actual
parameter.
o The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the
address of the actual parameters, and the modified value gets stored at the same address.

Example: Swapping the values of the two variables

#include <stdio.h>

void swap(int *, int *); //prototype of the function

int main()

int a = 10;

int b = 20;

printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in
main

swap(&a,&b);

printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do
change in call by reference, a = 10, b = 20

void swap (int *a, int *b)

int temp;
temp = *a;

*a=*b;

*b=temp;

printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b =


10

Output:
Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 20, b = 10

Difference between call by value and call by reference

No. Call by value Call by reference

1 A copy of the value is passed into the function An address of value is passed into the function

2 Changes made inside the function is limited to Changes made inside the function validate
the function only. The values of the actual outside of the function also. The values of the
parameters do not change by changing the actual parameters do change by changing the
formal parameters. formal parameters.

3 Actual and formal arguments are created at the Actual and formal arguments are created at the
different memory location same memory location
Recursion
Recursion is the process which comes into existence when a function calls itself to work on a
smaller problem. Any function which calls itself is called recursive function, and such function
calls are called recursive calls. Recursion involves several numbers of recursive calls. However, it
is important to impose a termination condition of recursion.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching,
and traversal problems.

Generally, iterative solutions are more efficient than recursion since function call is always
overhead. Any problem that can be solved recursively, can also be solved iteratively. However,
some problems are best suited to be solved by the recursion, for example, tower of Hanoi,
Fibonacci series, factorial finding, etc.

In the following example, recursion is used to calculate the factorial of a number.

#include <stdio.h>

int fact (int);

void main()

int n,f;

printf("Enter the number whose factorial you want to calculate?");

scanf("%d",&n);

f = fact(n);

printf("factorial = %d",f);

int fact(int n)

if (n==0)
{

return 0;

else if ( n == 1)

return 1;

else

return n*fact(n-1);

Output

Enter the number whose factorial you want to calculate?5

factorial = 120
Dynamic memory allocation
The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h
header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

tDifference between static memory allocation and dynamic memory allocation.he number whose
factori you want to calculate?5
fact

Static memory allocation Dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while executing memory can be increased while executing
program. program.

used in array. used in linked list.

The methods used for dynamic memory allocation.

malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc() functions.

free() frees the dynamically allocated memory.

1. malloc() function

 The malloc() function allocates single block of requested memory.


 It doesn't initialize memory at execution time, so it has garbage value initially.
 It returns NULL if memory is not sufficient.
The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)

2. calloc() function

 The calloc() function allocates multiple block of requested memory.


 It initially initialize all bytes to zero.
 It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

ptr=(cast-type*)calloc(number, byte-size)

3. realloc() function
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.

Syntax of realloc() function.

ptr=realloc(ptr, new-size)

4. free() function
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.

Syntax of free() function.

free(ptr)

orial = 120 nter the number whose factorial you want to calcula
Module 4
Strings
The string can be defined as the one-dimensional array of characters terminated by a null ('\0').
The character array or the string is used to manipulate text such as word or sentences. The
termination character ('\0') is important in a string since it is the only way to identify where the
string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with
the null in the memory.

There are two ways to declare a string in c language.

1. By char array
2. By string literal

Example of declaring string by char array in C language.


char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

While declaring string, size is not mandatory. So we can write the above code as given below:

char ch[]={'H', 'E', 'L', 'L', 'O', '\0'};

We can also define the string by the string literal in C language. For example

char ch[]="hello";

In such case, '\0' will be appended at the end of the string by the compiler.

Following is the memory presentation of the above defined string in C/C++ −


Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array.
Example program:
#include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}

When the above code is compiled and executed, it produces the following result −
Greeting message: Hello

C supports a wide range of functions that manipulate null-terminated strings :

Sr.No. Function & Purpose

1 strcpy(s1, s2);
Copies string s2 into string s1.

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

#include <stdio.h>
#include <string.h>
void main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );
getch();
}
When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
Structure
Structure is a user-defined data type that enables us to store the collection of different data types
at different memory locations. Each element of a structure is called a member. The struct keyword
is used to define the structure.

The syntax to define the structure is:

struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type member N;
};

The example to define a structure for an entity employee is:

struct employee
{ int id;
char name[20];
float salary;
};

The following image shows the memory allocation of the structure employee that is defined in the
above example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the
members or fields of the structure.

Declaring structure variable


We can declare a variable for the structure so that we can access the member of the structure easily.
There are two ways to declare structure variable:

1. By struct keyword within main() function


2. By declaring a variable at the time of defining the structure.
1st way:

To declare the structure variable by struct keyword. It should be declared within the main function.

struct employee
{ int id;
char name[50];
float salary;
};
Now write given code inside the main() function.
struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure.
.
2nd way:
Another way to declare variable at the time of defining the structure.

struct employee
{ int id;
char name[50];
float salary;
}e1,e2;

Accessing members of the structure


There are two ways to access structure members:

1. By . (member or dot operator)


2. By -> (structure pointer operator)
Structure example

#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
void main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Ram");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
getch();
}
Output:
employee 1 id : 101
employee 1 name : Ram
Union
Union can be defined as a user-defined data type which is a collection of different variables of
different data types in the same memory location. The union can also be defined as many members,
but only one member can contain a value at a particular point in time.

Union is a user-defined data type, but unlike structures, they share the same memory location.

Defining a Union

To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program.

The format of the union statement is as follows −

union {

member definition;

member definition;

...

member definition;

} [one or more union variables];

At the end of the union's definition, before the final semicolon, you can specify one or more union
variables but it is optional. Here is the way you would define a union type named Data having
three members i, f, and str −

union Data {

int i;

float f;

char str[20];

} data;
Accessing Union Members
To access any member of a union, we use the member access operator (.). The
member access operator is coded as a period between the union variable name and the
union member that we wish to access. You would use the keyword union to define
variables of union type. The following example shows how to use unions in a program −

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};

void main( ) {
union Data data;

data.i = 10;
printf( "data.i : %d\n", data.i);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);
getch();
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.

Difference between Structure and Union

Struct Union

The struct keyword is used to define a structure. The union keyword is used to define union.

When the variables are declared in a structure, the compiler When the variable is declared in the union, the compiler
allocates memory to each variable member. The size of a allocates memory to the largest size variable member. The
structure is equal or greater to the sum of the sizes of each data size of a union is equal to the size of its largest data member
member. size.

Each variable member occupied a unique memory space. Variables members share the memory space of the largest
size variable.

Changing the value of a member will not affect other variables Changing the value of one member will also affect other
members. variables members.

Each variable member will be assessed at a time. Only one variable member will be assessed at a time.

We can initialize multiple variables of a In union, only the first data member can be initialized.
structure at a time.

All variable members store some value at any point in the Exactly onlyonedatamember stores avalue at any particular
program. instance in the program.

The structure allows initializing multiple Union allows initializing only one variable member at
variable members atonce. once.
It is used to store different data type values. It is used for storing one at a time from different data
typevalues.

It allows accessing and retrieving any data member at a time. It allows accessing and retrieving any one data member
at a time.

File Handling in C
File Handling is the storing of data in a file using a program. In C programming language, the programs
store results, and other data of the program to a file using file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program.

The following operations can be performed on a file.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling

There are many functions in the C library to open, read, write, search and close the file.

A list of file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position


8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Opening File: fopen()

We must open a file before it can be read, write, or update. The fopen() function is used to

open a file. The syntax of the fopen() is given below:

FILE *fopen( const char * filename, const char * mode );

The fopen() function accepts two parameters:

The file name (string). If the file is stored at some specific location, then we must mention the path

at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext".

The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode


The fopen function works in the following way.

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and place it into the buffer. The buffer is

used to provide efficiency for the read operations.

o It sets up a character pointer which points to the first character of the file.

Consider the following example which opens a file in write mode.

#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Closing File: fclose()

The fclose() function is used to close a file. The file must be closed after performing all the

operations on it. The syntax of fclose() function is given below:

int fclose( FILE *fp );

Writing File : fprintf() function


The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}

Reading File : fscanf() function

The fscanf() function is used to read set of characters from file. It reads a word from the

file and returns EOF at the end of file.

Syntax:

int fscanf(FILE *stream, const char *format [, argument, ...])

Example:

#include <stdio.h>
void main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}

You might also like