Uploaded by cassandra.francesca

C PROGRAMMING LANGUAGE FULL

COURSE NAME: C PROGRAMMING
COURSE FACILITATOR: FOKAM NGUIFO Michel
CLASS: CSE, CEE
Chap 0: GENERAL REVISION ON ALGORITHM AND
PROBLEM SOLVING TECHNIQUE
Chap 1: Introduction to programming language
To communicate with the computers, we need some languages. These are computer languages.
In this chapter we are going to give an overview on programming language
I-
Definitions of some concepts
A-Programming: Is a process of writing programs
B- Computer Programming is an art of making a computer to do the required operations,
by means of issuing sequence of commands to it.
C-A programming language is a formal language that specifies a set of instructions
that can be used to produce various kinds of output.
It (programming language) can also be defined as a vocabulary and set of
grammatical rules for instructing the computer to perform specific tasks.
II-
Overview and example of programming language
Programming languages generally consist of instructions for a computer or command to
the computer.
Programming languages can be used to create programs that implement specific
algorithms.
Each programming language has a unique set of characters, key words and the syntax for
organizing programming instructions.
Some examples of programming languages are BASIC, C, C++, COBOL,
FORTRAN, Java, Assembly, Python, Ada, and Pascal...etc.
III-
Why Study Programming Languages?
The design of new programming languages and implementation methods have been evolved
and improved to meet the change in requirements. Thus, there are many new languages.
The study of more than one programming language helps us:
-
to master different programming paradigms
-
to enhance the skills to state different programming concepts
-
to understand the significance of a particular language implementation
- To compare different languages and to choose appropriate language
IV-
to improve the ability to learn new languages and to design new languages
Types of Programming Languages
There are two major types of programming languages:
- Low Level Languages
- High Level Languages
IV.1- Low Level Languages
The term low level refers closeness to the way in which the machine has been built. Low
level languages are machine oriented and require extensive knowledge of computer
hardware architecture and its configuration. Low Level languages are further divided in to
Machine language and Assembly language.
(a) Machine Language
Machine Language is the only language that is directly understood by the computer. It does
not need any translator program. The instructions are called machine instruction (machine
code) and it is written as strings of 1's (one) and 0’s (zero). When this sequence of codes is
fed in to the computer, it recognizes the code and converts it in to electrical signals.
For example, a program instruction may look like this: 1011000111101 Machine language is
considered to be the first generation language. Because of it design, machine language is not
an easy language to learn. It is also difficult to debug the program written in this language.
 Advantages
-
The program runs faster because no translation is needed. (It is already in
machine understandable form)
-
Machine language makes fast and efficient use of the computer.
 Disadvantages
-It is very difficult to write programs in machine language. The programmer has to know
details of hardware to write program
-It is difficult to find errors in a program written in the machine language
- All operation codes have to be remembered
- All memory addresses have to be remembered.
(b) Assembly Language
In assembly language, set of mnemonics (symbolic keywords) are used to represent machine
codes. Mnemonics are usually combination of words like ADD, SUB and LOAD etc.
Example of instruction in assembly language:
1- MOV AL, 61h
2- ADD Al, Num1
In order to execute the programs written in assembly language, a translator program is
required to translate it to the machine language. This translator program is called Assembler.
Assembly language is considered to be the second-generation language.
 Advantages:
-The symbolic keywords are easier to code and saves time and effort
-It is easier to correct errors and modify programming instructions
- Assembly Language has utmost the same efficiency of execution as the machine level
language, because there is one-to-one translation between assembly language program and
its corresponding machine language program
 Disadvantages:
-
Assembly languages are machine dependent. A program written for
one computer might not run in other computer
-
Since it is machine dependent, the programmer also needs to
understand the hardware.
IV.2- High Level Languages
It is any programming language that enables development of a program in a much more
user-friendly programming context and is generally independent of the computer hardware
architecture. In other word High level languages are the simple languages that use English
like instructions and mathematical symbols like +, -, %, /, for its program construction.
They are referred to as “closer to human”. In other words, their programming style and
context is easier to learn and implement than low level language and the entire code
generally focuses on the specific program to be created.
Every single program written in a high level language must be converts to a machine
language before being executed by the computer. This conversion is done by the
compiler.
Compiler is a special program that converts (transforms) a source code program written in high
level language into a low level object code in machine language. High level languages are easy
to learn and use
Advantages
-
High-level languages are user-friendly
-
They are similar to English and use English vocabulary and well-known
symbols
-
They are easier to learn
-
They are easier to maintain
-
They are problem-oriented rather than 'machine'-based
-
A program written in a high-level language can be translated into many machine
languages and can run on any computer for which there exists an appropriate translator
-
The language is independent of the machine on which it is used i.e. programs
developed in a high-level language can be run on any computer text
Disadvantages
-
The object code generated by a translator might be inefficient compared to an
equivalent assembly language program
-
A high-level language has to be translated into the machine language by a
translator, which takes up time
Some examples of high level language are BASIC (Beginners All-purpose Symbolic
Instruction Code), COBOL (Common Business Oriented Language), JAVA, C, C++,
FORTRAN (Formula Translation), ALGOL (Algorithmic Language), PROLOG (for
“Programming Logic”);
Chap 2: Introduction to C programming language
Lesson 1 : Overview of C Language
C is a structured programming language developed by Dennis Ritchie in 1972 at Bell
Laboratories. It is one of the most popular computer languages today because of its structure,
high-level abstraction, machine independent feature etc. C language was developed to write
the UNIX operating system, hence it is strongly associated with UNIX, which is one of the
most popular network operating system in use today and heart of internet data superhighway.
1- History of C language
C language has evolved from three different structured language ALGOL, BCPL and B
Language. It uses many concepts from these languages while introduced many new concepts
such as datatypes, struct, pointer etc. In 1988, the language was formalised by American
National Standard Institute (ANSI). Between 1989 and 1990, a version of C language was
approved by the International Standard Organisation (ISO) and that version of C is also
referred to as C89.
Let's see the programming languages that were developed before C language.
Language
Year
Developed By
Algol
1960
International Group
BCPL
1967
Martin Richard
B
1970
Ken Thompson
Traditional C
1972
Dennis Ritchie
K&RC
1978
Kernighan & Dennis Ritchie
ANSI C
1989
ANSI Committee
ANSI/ISO C
1990
ISO Committee
C99
1999
Standardization Committee
The current latest version of C language is C11, which was introduced in 2011. It is supported
by all the standard C language compilers.
Many new features have been introduced in this version and an overall attempt to improve
compatibility of the C language with C++ language has been made.
The idea behind creating C language was to create an easy language which requires a
simple compiler and enables programmers to efficiently interact with the machine/system, just
like machine instructions.
C language compiler converts the readable C language program into machine instruction.
2- Why C Language is so popular?
C language is a very good language to introduce yourself to the programming world, as it is a
simple procedural language which is capable of doing wonders.
Programs written in C language takes very less time to execute and almost executes at the
speed of assembly language instructions.
Initially C language was mainly used for writing system level programs, like designing
operating systems, but there are other applications as well which can be very well designed
and developed using C language, like Text Editors, Compilers, Network Drivers etc.
3- FEATURES OF C PROGRAMMING LANGUAGE:
C language is one of the powerful language. Below are some of the features of C
language.
 Reliability
 Portability: this means that programs once written can be run on another machines
with little or no modification
 Flexibility
 Interactivity
 Modularity
 Efficiency and Effectiveness
4- USES OF C PROGRAMMING LANGUAGE:
The C programming language is used for developing system applications that forms a major
portion of
operating systems such as Windows, UNIX and Linux. Below are some examples of C being
used.
 Database systems
 Graphics packages
 Word processors
 Spreadsheets
 Operating system development
 Compilers and Assemblers
 Network drivers
 Interpreters
Note: C is called middle-level language because it actually binds the gap between a
machine level language and high-level languages.
5- C LANGUAGE IS A STRUCTURED LANGUAGE:
Structure oriented language:
 In this type of language, large programs are divided into small programs called functions
 Prime focus is on functions and procedures that operate on the data
 Data moves freely around the systems from one function to another
 Program structure follows “Top Down Approach”
 Examples: C, Pascal, ALGOL and Modula-2
Object oriented language:
 In this type of language, programs are divided into objects
 Prime focus is in the data that is being operated and not on the functions or procedures
 Data is hidden and cannot be accessed by external functions
 Program structure follows “Bottom UP Approach”
 Examples: C++, JAVA and C# (C sharp)
Non structure oriented language:
 There is no specific structure for programming this language. Examples: BASIC, COBOL,
FORTRAN
KEY POINTS TO REMEMBER IN C LANGUAGE:
1. The C language is a structure oriented programming language developed by Dennis
Ritchie
2. The C language is belonging to middle level programming language.
3. Operating system programs such as Windows, Unix, Linux are written in C language.
4.
C89/C90 and C99 are two standardized editions of C language.
5. C has been written in assembly language.
Lesson 2 : C basic syntax
This C programming basics section explains a simple “Hello World” C program. Also, it
covers below basic
Topics as well, which are to be known by any C programmer before writing a C program.
1. C programming basic commands to write a C program
2. A simple C program with output and explanation
3. Steps to write C programs and get the output
4. Creation, Compilation and Execution of a C program
* How to install C compiler and IDE tool to run C programming codes
5. Basic structure of a C program
* Example C program to compare all the sections
* Description for each section of the C program
2.1- C PROGRAMMING BASICS COMMANDS:
Below are few commands and syntax used in C programming to write a simple C program.
Let’s see all the sections of a simple C program line by line.
C Basic commands
Explanation
This is a preprocessor command that includes
#include <stdio.h>
standard input output header file(stdio.h) from the
C
library before compiling a C program
This is the main function from where execution of
int main()
any
C program begins.
{
/*_some_comments_*
/
This indicates the beginning of the main function.
whatever is given inside the command “/* */” in
any
C program, won’t be considered for compilation
and
execution.
printf(“Hello_World!
“);
getch();
return 0;
}
printf command prints the output onto the screen.
This command waits for any character input from
keyboard.
This command terminates C program (main
function) and returns 0.
This indicates the end of the main function.
2.2-
A SIMPLE C PROGRAM:
Below C program is a very simple and basic program in C programming language. This C
program displays
“Hello World!” in the output window. And, all syntax and commands in C programming are
case sensitive.
Also, each statement should be ended with semicolon (;) which is a statement terminator.
#include <stdio.h>
int main(){
/* Our first simple C basic program */
printf("Hello World I doing c programming! ");
getch();
return 0;
}
OUTPUT:
Hello World I doing c programming!
2.3-
STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT:
Below are the steps to be followed for any C program to create and get the output. This is
common to all C
program and there is no exception whether its a very small C program or very large C
program.
1. Create
2. Compile
3. Execute or Run
4. Get the Output
2.4-
ENVIRONMENT SETUP:
Local Environment Setup
If you want to set up your environment for C programming language, you need the following
two software
tools available on your computer,
(a) Text Editor and
(b) The C Compiler.
Or you install an IDE(Integrated Development Environment) embedding both text editor and
compiler (codeblock, Turbo C, ….etc.
(a)Text Editor
This will be used to type your program. Examples of a few editors include Windows Notepad,
OS Edit command, Brief, Epsilon, EMACS, and vim or vi …..etc. The name and version of
text editors can vary on different operating systems. For example, Notepad will be used on
Windows, and vim or vi can be used on Windows as well as on Linux or UNIX. The files you
create with your editor are called the source files and they contain the program source codes.
The source files for C programs are typically named with the extension ".c".
Before starting your programming, make sure you have one text editor in place and you have
enough experience to write a computer program, save it in a file, compile it and finally
execute it.
(b)The C Compiler
The source code written in source file is the human readable source for your program. It needs
to be "compiled" into machine language so that your CPU can actually execute the program as
per the instructions given.
The compiler compiles the source codes into final executable programs. The most frequently
used and free available compiler is the GNU C/C++ compiler, otherwise you can have
compilers either from HP or Solaris if you have the respective operating systems.
The following section explains how to install GNU C/C++ compiler on WINDOWS
especially since it is the system that we are using. We keep mentioning C/C++ together
because GNU gcc(GNU Compiler Collection) works for both C and C++ programming
languages
2.5-
FULL STRUCTURE OF A C PROGRAM:
Structure of C program is defined by set of rules called protocol, to be followed by
programmer while writing C program. All C programs are having sections/parts which are
mentioned below.
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section
EXAMPLE C PROGRAM TO COMPARE ALL THE SECTIONS:
You can compare all the sections of a C program with the below C program.
DESCRIPTION FOR EACH SECTION OF THE C PROGRAM:
 Let us see about each section of a C basic program in detail below.
 Please note that a C program mayn’t have all below mentioned sections except main
function and link sections.
 Also, a C program structure mayn’t be in below mentioned order.
Sections
Description
We can give comments about the program, creation
or modified date, author name etc in this section. The
characters or words or anything which are given
Documentation
section
between “/*” and “*/”, won’t be considered by C
compiler for compilation process. These will be
ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment
3
*/
Link Section
Definition Section
Header files that are required to execute a C program
are included in this section
In this section, variables are defined and values are
set to these variables.
Global
Global variables are defined in this section. When a
declaration
variable is to be used throughout the program, can be
section
defined in this section.
Function
prototype
declaration
section
Function prototype gives many information about a
function like return type, parameter names used
inside the function.
Every C program is started from main function and
Main function
this function contains two major sections called
declaration section and executable section.
User defined
function section
User can define their own functions in this section
which perform particular task as per the user
requirement.
KEY POINTS TO REMEMBER IN C PROGRAMMING BASICS:
1. C programming is a case sensitive programming language.
2. Each C programming statement is ended with semicolon (;) which are referred as
statement terminator.
3. printf() command is used to print the output onto the screen.
4. C programs are compiled using C compilers and displays output when executed.
Lesson 3: C input and output, data types, TOKENS, KEYWORDS,
IDENTIFIER, VARIABLES AND CONSTANTS
3.1 –Input / Output in C
Input and output is terminology referring to the communication between a computer
program and its user. Input is the user giving something to the program and we use scanf()
function , and output is the program giving something to the user by displaying on the screen
and we use printf() function.
C programming language provides many built-in functions to read any given input and to
display data on screen when there is a need to output the result.
Format specifier: Format specifiers defines the type of data to be printed on standard output.
Whether to print formatted output or to take formatted input we need format specifiers.
Format specifiers are also called as format string. Each format specifier begins with the
percentage character (%) followed by a conversion character which indicates the type of the
corresponding data item.
Here is a list of all format specifiers used in C programming language:
Format specifiers
Uses
Example
%c
For ‘char’ type data
scanf(“%c”,&a); printf(“%c”,a);
%d
For ‘int’ type data
scanf(“%d”,&a); printf(“%d”,a);
%f
For ‘float’ type data
scanf(“%f”,&a); printf(“%f”,a);
%lf
For ‘double’ type data
scanf(“%lf”,&a); printf(“%lf”,a);
%ld
For ‘long int ‘ type data
scanf(“%ld”,&a); printf(“%ld”,a);
For ‘unsigned int ‘ type
%u
data
scanf(“%u”,&a); printf(“%u”,a);
%o
For ‘Octal’ type data
scanf(“%o”,&a); printf(“%o”,a);
For ‘Hexadecimal’ type
%x
data
scanf(“%x”,&a); printf(“%x”,a);
6- Uses of scanf() function:
Format of scanf() function for taking single input:
scanf(“format_specifier “, &variable_name);
Example:

scanf() function for taking ‘char’ type data in variable a: scanf(“%c”, &a);

scanf() function for taking ‘int’ type data in variable a: scanf(“%d”, &a);

scanf() function for taking ‘float’ type data in variable a: scanf(“%f”, &a);

scanf() function for taking ‘double’ type data in variable a: scanf(“%lf”, &a);
Format of scanf() function for taking multiple inputs:
scanf(” format_specifier1 format_specifier2….”, &variable_name1, &variable_name2…….);
Example:
Format of scanf() function for taking same type of multiple inputs:

If variable a,b and c are int type then the format of scanf():

scanf(“%d %d %d”, &a, &b, &c);
Format of scanf() function for taking different type of multiple inputs:

If variable a,b and c are int, float and double type respectively then the format of scanf():

scanf(“%d %f %lf”, &a, &b, &c);
Uses of printf() function:
printf() function can be used in two ways. First one is, to print a text that is not a value of a
variable. Second one is, to print the value of variables.
Format of printf() function to print a text: The text should be in double quotation of the
function.
printf(” Output text should be here “);
Format of printf() function to print the value of a single variable:
printf(“format_specifier”, variable_name);
Example:

printf() function for printing ‘char’ type data of variable a: printf(“%c”, a);

printf() function for printing ‘int’ type data of variable a: printf(“%d”, a);

printf() function for printing ‘float’ type data of variable a: printf(“%f”, a);

printf() function for printing ‘double’ type data of variable a: printf(“%lf”, a);
Format of printf() function to print the value of multiple variables:
printf(“format_specifier1, format_specifier2….”, variable_name1, variable_name2…);
Format of printf() function for printing same type of multiple variables:

If variable a,b and c are int type then the format of printf():

printf(“%d %d %d”, a, b, c);
Format of printf() function for printing different type of multiple variables:

If variable a,b and c are int, float and double type respectively then the format of printf():

printf(“%d %f %lf”, a, b, c);
Backslash Constant Characters: In C language a sequence of characters that doesn’t
represent itself when used inside string literal or character. It is composed of two or more
characters starting with backslash \. For example: \n represents new line.
Backslash
Characters
Uses
Examples
Output
Learning
\n
Printing Newline
printf(“Learning\n ICT”);
ICT
printf(“Learning\t ICT”);
Learning
Printing Horizontal
\t
tab
ICT
Learning
\v
Printing Vertical tab
printf(“Learning\v ICT”);
\a
Alarm or Beep
printf(“\aLearning ICT”);
Printing Double
printf(“Learning \”ICT\”
quotation mark
“);
Learning “ICT”
\”
ICT
Alerm!
Printing Single
\’
quotation mark
printf(“Learning \’ICT\’ “);
Learning ‘ICT’
\\
Printing Backslash
printf(“Learning \\ICT\\ “);
Learning \ICT\
Printing Question
printf(” Are you learning
mark
ICT\? “);
\?
Are you learning ICT?
3.2 Data types
'C' provides various data types to make it easy for a programmer to select a suitable data type
as per the requirements of an application. Following are the three data types:
1. Primitive data types
2. Derived data types
3. User-defined data types
There are five primary fundamental data types,
1. int for integer data
2. char for character data
3. float for floating point numbers
4. double for double precision floating point numbers
5. void
Array, functions, pointers, structures are derived data types. 'C' language provides more
extended versions of the above mentioned primary data types. Each data type differs from one
another in size and range. Following table displays the size and range of each data type.
Data type
Size in bytes
Range
Char or signed char
1
-128 to 127
Unsigned char
1
0 to 255
int or signed int
2
-32768 to 32767
Unsigned int
2
0 to 65535
Short int or Unsigned short int
2
0 to 255
Signed short int
2
-128 to 127
Long int or Signed long int
4
-2147483648 to 2147483647
Unsigned long int
4
0 to 4294967295
Float
4
3.4E-38 to 3.4E+38
Double
8
1.7E-308 to 1.7E+308
Long double
10
3.4E-4932 to 1.1E+4932
Note: In C, there is no Boolean data type.
Integer data type
Integer is nothing but a whole number. The range for an integer data type varies from machine
to machine. The standard range for an integer data type is -32768 to 32767.
An integer typically is of 2 bytes which means it consumes a total of 16 bits in memory. A
single integer value takes 2 bytes of memory. An integer data type is further divided into other
data types such as short int, int, and long int.
Each data type differs in range even though it belongs to the integer data type family. The size
may not change for each data type of integer family.
The short int is mostly used for storing small numbers, int is used for storing averagely sized
integer values, and long int is used for storing large integer values.
Whenever we want to use an integer data type, we have place int before the identifier such as,
int age;
Here, age is a variable of an integer data type which can be used to store integer values.
Floating point data type
Like integers, in 'C' program we can also make use of floating point data types. The 'float'
keyword is used to represent the floating point data type. It can hold a floating point value
which means a number is having a fraction and a decimal part. A floating point value is a real
number that contains a decimal point. Integer data type doesn't store the decimal part hence
we can use floats to store decimal part of a value.
Generally, a float can hold up to 6 precision values. If the float is not sufficient, then we can
make use of other data types that can hold large floating point values. The data type double
and long double are used to store real numbers with precision up to 14 and 80 bits
respectively.
While using a floating point number a keyword float/double/long double must be placed
before an identifier. The valid examples are,
float division;
double BankBalance;
7- Character data type
Character data types are used to store a single character value enclosed in single quotes.
A character data type takes up-to 1 byte of memory space.
Example,
Char letter;
8- Void data type
A void data type doesn't contain or return any value. It is mostly used for defining functions in
'C'.
Example,
void displayData()
Type declaration of a variable
int main() {
int x, y;
float salary = 13.48;
char letter = 'K';
x = 25;
y = 34;
int z = x+y;
printf("%d \n", z);
printf("%f \n", salary);
printf("%c \n", letter);
return 0;}
Output:
59
13.480000
K
We can declare multiple variables with the same data type on a single line by separating them
with a comma. Also, notice the use of format specifiers in printf output function float (%f)
and char (%c) and int (%d).
3.4- Tokens
A token is the smallest unit in a 'C' program. A token is divided into six different types as
follows,
Tokens in C
3.5- Keywords and identifiers
In 'C' every word can be either a keyword or an identifier.
Keywords have fixed meanings, and the meaning cannot be changed. They act as a building
block of a 'C' program. There are total 32 keywords in 'C'. Keywords are written in lowercase
letters.
Following table represents the keywords in 'C',
Auto
Double
Int
Struct
Break
Else
Long
Switch
Case
Enum
Register
typedef
Char
Extern
Return
Union
Const
Short
Float
unsigned
continue
For
Signed
Void
default
Goto
Sizeof
volatile
Do
If
Static
While
3.6- Identifier
An identifier is nothing but a name assigned to an element in a program. Example, name of a
variable, function, etc. Identifiers are the user-defined names consisting of 'C' standard
character set. As the name says, identifiers are used to identify a particular element in a
program. Each identifier must have a unique name. Following rules must be followed for
identifiers:
1. The first character must always be an alphabet or an underscore.
2. It should be formed using only letters, numbers, or underscore.
3. A keyword cannot be used as an identifier.
4. It should not contain any whitespace character.
5. The name must be meaningful.
3.7- Variable
A variable is an identifier which is used to store some value. Constants can never change at
the time of execution. Variables can change during the execution of a program and update the
value stored inside it.
A single variable can be used at multiple locations in a program. A variable name must be
meaningful. It should represent the purpose of the variable.
Example: Height, age, are the meaningful variables that represent the purpose it is being used
for. Height variable can be used to store a height value. Age variable can be used to store the a
ge of a person
A variable must be declared first before it is used somewhere inside the program. A variable
name is formed using characters, digits and an underscore.
Following are the rules that must be followed while creating a variable:
1. A variable name should consist of only characters, digits and an underscore.
2. A variable name should not begin with a number.
3. A variable name should not consist of whitespace.
4. A variable name should not consist of a keyword.
5. 'C' is a case sensitive language that means a variable named 'age' and 'AGE' are
different.
Following are the examples of valid variable names in a 'C' program:
height or HEIGHT
_height
_height1
My_name
Following are the examples of invalid variable names in a 'C' program:
1height
Hei$ght
My name
For example, we declare an integer variable my_variable and assign it the value 48:
int my_variable;
my_variable = 48;
By the way, we can both declare and initialize (assign an initial value) a variable in a single
statement:
int my_variable = 48;
Format for declaring a variable is given bellow:

Data_type variable_name;

For example: int number;
The Programming language C has two main variable types:

1. Local Variables

2. Global Variables
Local Variables: Local variables scope is confined within the block or function where it is
defined. Local variables must always be defined at the top of a block. When a local variable is
defined – it is not initialized by the system, you must initialize it yourself. When execution of
the block starts the variable is available, and when the block ends the variable ‘dies’.
Global Variables: Global variable is defined at the top of the program file and it can be
visible and modified by any function that may reference it. Global variables are initialized
automatically by the system when you define them!. If same variable name is being used for
global and local variable then local variable takes preference in its scope. But it is not a good
practice to use global variables and local variables with the same name.
3.8- Constants
Constants are the fixed values that never change during the execution of a program. Following
are the various types of constants:
Integer constants
An integer constant is nothing but a value consisting of digits or numbers. These values never
change during the execution of a program. Integer constants can be octal, decimal and
hexadecimal.
1. Decimal constant contains digits from 0-9 such as,
Example, 111, 1234
Above are the valid decimal constants.
2. Octal constant contains digits from 0-7, and these types of constants are always
preceded by 0.
Example, 012, 065
Above are the valid decimal constants.
3. Hexadecimal constant contains a digit from 0-9 as well as characters from A-F.
Hexadecimal constants are always preceded by 0X.
Example, 0X2, 0Xbcd
Above are the valid hexadecimal constants.
The octal and hexadecimal integer constants are very rarely used in programming with 'C'.
Character constants
A character constant contains only a single character enclosed within a single quote (''). We
can also represent character constant by providing ASCII value of it.
Example, 'A', '9'
Above are the examples of valid character constants.
String constants
A string constant contains a sequence of characters enclosed within double quotes ("").
Example, "Hello", "Programming"
These are the examples of valid string constants.
Real Constants
Like integer constants that always contains an integer value. 'C' also provides real constants
that contain a decimal point or a fraction value. The real constants are also called as floating
point constants. The real constant contains a decimal point and a fractional value.
Example, 202.15, 300.00
These are the valid real constants in 'C'.
A real constant can also be written as,
Mantissa e Exponent
For example, to declare a value that does not change like the classic circle constant PI, there
are two ways to declare this constant
1. By using the const keyword in a variable declaration which will reserve a storage
memory
#include <stdio.h>
int main() {
const double PI = 3.14;
printf("%f", PI);
//PI++; // This will generate an error as constants cannot be changed
return 0;}
2. By using the #define pre-processor directive which doesn't use memory for storage
and without putting a semicolon character at the end of that statement
#include <stdio.h>
#define PI 3.14
int main() {
printf("%f", PI);
return 0;}
Summary

A constant is a value that doesn't change throughout the execution of a program.

A token is the smallest unit in a program.

A keyword is reserved words by language.

There are total 32 keywords.

An identifier is used to identify elements of a program.

A variable is an identifier which is used to store a value.

There are four commonly used data types such as int, float, char and a void.

Each data type differs in size and range from one another.
EXERCISES:
Knowledge Based Questions:
1. What is input function?
2. What is output function?
3. What is format specifier?
4. What is backslash character?
Comprehension Based Questions:
5. What is meant by output function?
6. Explain the statement scanf(“%d”, &a);
7. Explain the statement scanf(“%d %x”, &a, &b);
8. Write input and output functions used in c programming language.
9. Explain printf() and scanf() function with examples.
10. ‘There are some rules for declaring a variable’-explain.
11. When long integer is used instead of integer? Explain.
12. In C language, is “int roll@no;” valid or invalid? Explain.
13. What do you understand by float type? Write down with example.
14. Write down the differences between variable and constant?
15. Write down the advantages of using constant in program.
Lesson 4: Operators and expressions of C language
4.1. Definition and description
Operator: An operator is a symbol that tells the compiler to perform specific mathematical or
logical operations. In other words we can say that an operator operates the operands.The data
items on which operators act upon are called operands. Operators are used in programs to
manipulate constant and operands.
Consider the expression A + B * 5. Where, +, * are operators, A, B are operands, 5 is
constant and A + B * 5 is an expression.
4.2. Classification of oparators
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:

1. Unary Operators

2. Binary Operators

3. Ternary Operators
1. Unary Operators:Those operators that require only single operand to act upon are
known as unary operators. For Example increment(++) and decrement(–) operators.
2. Binary Operators:Those operators that require two operands to act upon are called
binary operators.Binary operators are classified into :

1. Arithmetic operators (+, -, * etc.)

2. Relational Operators ( <, >, ==)

3. Logical Operators (&&, ||)

4. Assignment Operators (=, +=, -=)

5. Bitwise Operators (&, |)
3. Ternary Operators: These operators requires three operands to act upon. For
Example Conditional operator(?:).
4.3. Types of operator based on operations
C operators can be classified into following types based on operations:

1. Arithmetic operators

2. Relational operators

3. Logical operators

4. Assignment operators

5. Increment/decrement operators

6. Conditional operators

7. Bitwise operators

8. Special operators
Arithmetic operators:These operators are used to perform mathematical calculations on
operands like addition, subtraction, multiplication, division and modulus.
Operators
Description
+
Adds two operands.
−
Subtracts second operand from the first.
*
Multiplies both operands.
/
Divides numerator by de-numerator.
%
Modulus Operator and remainder of after an integer division.
Relational operators: These operators are used to compare the value of two operands. For
example: checking if one operand is equal to the other operand or not, an operand is greater
than the other operand or not etc.
Operators
Description
Example
Checks if the values of two operands are equal or not. If
==
yes, then the condition becomes true.
(A == B) is not true.
Checks if the values of two operands are equal or not. If
the values are not equal, then the condition becomes
!=
true.
(A != B) is true.
Checks if the value of left operand is greater than the
value of right operand. If yes, then the condition
>
becomes true.
(A > B) is not true.
Checks if the value of left operand is less than the value
<
of right operand. If yes, then the condition becomes true.
(A < B) is true.
Checks if the value of left operand is greater than or
equal to the value of right operand. If yes, then the
>=
condition becomes true.
(A >= B) is not true.
Checks if the value of left operand is less than or equal
to the value of right operand. If yes, then the condition
<=
becomes true.
(A <= B) is true.
Logical operators: Logical Operators are used to combine two or more conditions/constraints
or to complement the evaluation of the original condition in consideration. The result of the
operation of a logical operator is a boolean value either true or false.
Operator
Description
Example
Called Logical AND operator. If both the operands are
&&
non-zero, then the condition becomes true.
(A && B) is false.
Called Logical OR Operator. If any of the two operands
||
is non-zero, then the condition becomes true.
(A || B) is true.
Called Logical NOT Operator. It is used to reverse the
logical state of its operand. If a condition is true, then
!
Logical NOT operator will make it false.
!(A && B) is true.
Assignment operators: These operators are used to assign the values for the variables in C
programs. The left side operand of the assignment operator is a variable and right side
operand of the assignment operator is a value. The value on the right side must be of the same
data-type of variable on the left side otherwise the compiler will raise an error.
Operator
=
Description
Example
Simple assignment operator. Assigns values from right
C = A + B will assign the
side operands to left side operand
value of A + B to C
Add AND assignment operator. It adds the right
+=
operand to the left operand and assign the result to the
C += A is equivalent to C =
left operand.
C+A
Subtract AND assignment operator. It subtracts the
-=
right operand from the left operand and assigns the
C -= A is equivalent to C = C
result to the left operand.
–A
Multiply AND assignment operator. It multiplies the
*=
right operand with the left operand and assigns the
C *= A is equivalent to C =
result to the left operand.
C*A
Divide AND assignment operator. It divides the left
/=
operand with the right operand and assigns the result to
C /= A is equivalent to C = C
the left operand.
/A
Modulus AND assignment operator. It takes modulus
%=
using two operands and assigns the result to the left
C %= A is equivalent to C =
operand.
C%A
Increment/decrement operators: Increment Operators are used to increase the value of the
variable by one and Decrement Operators are used to decrease the value of the variable by
one in C programs. Both increment and decrement operator are used on a single operand and
variable, so it is called as a unary operator. Unary operators are having higher priority than the
other operators it means unary operators are executed before other operators.
9- Type of Increment Operator
o
pre-increment
o
post-increment
pre-increment (++ variable): In pre-increment first increment the value of variable and then
used inside the expression (initialize into another variable).
Example of pre-increment
1
2
3
4
5
6
<span style="font-family: 'times new roman', times, serif; font-size:
14pt;">#include<stdio.h>
#include<conio.h>
main()
{
int x,i;
7
i=10;
8
x=++i;
9
printf("x: %d",x);
10
printf("i: %d",i);
11
12
getch();
}</span>
post-increment (variable ++): In Post-increment first value of variable is used in the
expression (initialize into another variable) and then increment the value of variable.
Example of post-increment
1
2
3
4
5
6
7
8
9
10
11
12
<span style="font-family: 'times new roman', times, serif; font-size:
14pt;">#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i++;
printf("x: %d",x);
printf("i: %d",i);
getch();
}</span>
10- Type of Decrement Operator
o
pre-decrement
o
post-decrement
Pre-decrement (– variable): In pre-decrement first decrement the value of variable and then
used inside the expression (initialize into another variable).
Example of pre-decrement
<span style="font-family: 'times new roman', times, serif; font-size:
14pt;">#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=--i;
printf("x: %d",x);
printf("i: %d",i);
getch();
}
post-decrement (variable –): In Post-decrement first value of variable is used in the
expression (initialize into another variable) and then decrement the value of variable.
Example of post-decrement
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i--;
printf("x: %d",x);
printf("i: %d",i);
getch();
}
Conditional operators: Conditional operators return one value if condition is true and returns
another value is condition is false. This operator is also called as ternary operator.
Syntax
:
Example :
(Condition? true_value: false_value);
(A < 0 ? Negative : Positive);
In above example, if A is less than 0, Negative is returned else Positive is returned. This is
equal to if else conditional statements.
Bitwise operators: These operators are used to perform bit-level operations on the
operands. The operators are first converted to bit-level and then calculation is performed on
the operands. Bitwise operators can not be used on float and double type data.
Truth table of bitwise operators:
Special operators: Below are some of the special operators that the C programming
language offers.
Operators
Description
This is used to get the address of the variable.
&
Example : &a will give address of a.
This is used as pointer to a variable.
*
Example : * a where, * is pointer to the variable a.
This gives the size of the variable.
Sizeof ()
Example : size of (char) will give us 1.
4.3.Expression
Expression: 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.
Mathematical expressions are written in c program in the following way:
Operator precedence and associativity in expression:
Operator precedence determines which operator is performed first in an expression with more
than one operators with different precedence. For example 10 + 20 * 30 is calculated as 10 +
(20 * 30) and not as (10 + 20) * 30.
Associativity is used when two operators of same precedence appear in an expression.
Associativity can be either Left to Right or Right to Left. For example ‘*’ and ‘/’ have same
precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated
as “(100 / 10) * 10”.
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
Lesson EvaluationKnowledge Based Questions:

a. What is operator?

a. What is unary operator?

a. What is binary operator?

a. What is ternary operator?

a. What is relational operator?

a. What is logical operator?

a. What is conditional operator?

a. What is expression?

a. What is operand?

a. What is operator precedence?
Lesson 5: Conditional(If statement) and loop(do---while, while, for) Control
statements in C programming
At the end of this lesson1. You will be able to explain control statement.
2. You will be able to explain different control statements.
3. You will be able to explain conditional control statement details.
4. You will be able to write program using conditional control statement.
5. You will be able to explain loop.
6. You will be able to explain loop control statements.
7. You will be able to explain for, while and do-while loop control statements.
8. You will be able to differentiate between while and do-while loop control statements.
5.1- Control statement (if statement)
Control statements: A control statement is a statement that determines whether other
statements will be executed. Control statements control the flow of program. They make it
possible to make decisions, to perform tasks repeatedly or to jump from one section of code to
another.
Control Statements are:

1. Conditional Control Statements / Decision control statements

2. Loop Control Statements

3. Jumping Control Statements
Decision control statements: In decision control statements, group of statements are
executed when condition is true. If condition is false, then else part statements are
executed. Decision control statements are:

if statements

if-else statements

else if statements

nested if-else statements

switch statements
if statements: It is used to decide whether a certain statement or block of statements will be
executed or not. The ‘if’ statement evaluates the condition inside the parenthesis. If the
condition is true statement(s) inside the body of ‘if’ is executed. If the condition is false
statement(s) inside the body of ‘if’ is skipped from execution. Syntax of ‘If’ statement:
if(condition)
{
statement(s)
}
Program for determining a number is positive.
#include<stdio.h>
int main()
{
int a;
printf("Enter a number");
scanf("%d",&a);
if(a>0)
printf("The given number is Positive");
return 0;
}
if-else statements: In if-else control statement, group of statements are executed when
condition is true. If condition is false, then else part statements are executed. There is no
condition for else statement. Syntax of ‘if-else’ statement:
if(condition)
{
statement(s)
}
else
{
statement(s)
}
Program for determining a number is whether positive or negative.
#include<stdio.h>
int main()
{
int a;
printf("Enter a number");
scanf("%d",&a);
if(a>=0)
printf("The given number is Positive");
else
printf("The given number is Negative");
return 0;
}
else if statements: The else..if statement is useful when you need to check multiple
conditions within the program, nesting of if-else blocks can be avoided using else..if
statement. Syntax of else..if statement:
if(Condition1)
{
statement(s)
}
else if(Condition2)
{
statement(s)
}
……………
……………
else
{
statement(s)
}
Program for determining a number is whether zero, positive or negative.
#include<stdio.h>
int main()
{
int a;
printf("Enter a number");
scanf("%d",&a);
if(a==0)
printf("The given number is Zero");
else if(a>0)
printf("The given number is Positive");
else
printf("The given number is Negative");
return 0;
}
nested if-else statements: It is possible to include if-else statement(s) inside the body of
another if-else statement. Syntax of nested if-else:
if(Condition1)
{
if(Condition2)
{
statement(s)
}
}
Program for determining a year whether leap year or not.
#include<stdio.h>
int main()
{
int y;
printf("Enter a year");
scanf("%d",&y);
if(y%4==0)
{
if(y%100!=0)
printf("The given year is a leap year");
}
else if(y%400)
printf("The given year is a leap year");
else
printf("The given year is not a leap year");
return 0;
}
switch statements: The switch statement is a multiway branch statement. A switch statement
tests the value of a variable and compares it with multiple cases. Once the case match is
found, a block of statements associated with that particular case is executed. If a case match is
found, then the default statement is executed, and the control goes out of the switch block.
Syntax of switch statement:
switch(expression)
{
case constant_1:
statements_for_constant_1;
break;
case constant_2:
statements_for_constant_2;
break;
------------------
-----------------case constant_n:
statements_for_constant_n;
break;
default: // Default case is optional
default_statements;
break;
}
The following rules apply to a switch statement:
1. Case constants must be either char(‘A’, ‘B’../ ‘a’,’b’…/’+’,’-‘ , etc) or int(1,2,3 – -) type.

If it is char type it should be enclosed with single quotation(‘ ‘).

2. Case constants must be unique.

3. Case constants must end with a colon ( : ).

4. A break keyword must be present in each case.

5. It can be same code block for multiple cases.

6. There can be only one default label.
Example-1: Program using switch statement that can perform addition, subtraction,
multiplication, division.
#include<stdio.h>
int main()
{
char ope;
int a,b;
printf("Enter Operator Either + or - or * or /");
scanf("%c",&ope);
printf("Enter Two numbers");
scanf("%d %d",&a,&b);
switch(ope)
{
case '+':
printf("Sum=%d",a+b);
break;
case '-':
printf("Subtraction=%d",a-b);
break;
case '*':
printf("Multiplication=%d",a*b);
break;
case '/':
printf("Quotient=%d",a/b);
break;
default:
printf("Your Operation is not matched");
break;
}
return 0;
}
Exercise: Write a program using switch statement to determine a letter is whether vowel or
consonant.
4.2. Loop Control Statements
Loop: Loops are used in programming to repeat a block of code multiple times or until a
specific condition is false.
Types of loop:

1. Infinite loop: The loop that repeat continuously and never end. A loop becomes an
infinite loop if a condition never becomes false.

2. Finite loop : The loop that repeat for a particular times and it continues until a specific
condition is false.

3. Nested loop: When one loop is inside another loop is called nested loop.
Loop Control Statements: A loop statement allows us to execute a statement or group of
statements multiple times.
Types of loop control statement:

1. for loop statement

2. while loop statement

3. do…while loop statement
Each loop control statement is divided into two parts:
Loop Declaration: There are three main parts of this section. Such as –

o
Initialization Statement- In this expression we have to initialize the loop counter to
some value. for example: int i=1;
o
Test Expression- In this expression we have to test the condition. If the condition
evaluates to true then we will execute the body of loop and go to update expression
otherwise we will exit from the for loop. For example: i <= 10;
o
Update Statement- After executing loop body this expression increments/decrements
the loop variable by some value. for example: i++;

Loop Body: The sequence of statements to be executed is kept inside the curly braces {
} known as the Loop body. it is is executed with each loop cycle.
Loop control statements are two types based on the position of loop_body and
test_expression. They are1. Entry Controlled loops: In this type of loops the test condition is tested before entering
the loop body. For Loop and While Loop are entry controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the
end of loop body. Therefore, the loop body will execute at least once, irrespective of whether
the test condition is true or false. do – while loop is exit controlled loop.
for Loop Statement: for loop is used to execute a set of statements repeatedly until a
particular condition is false. It tests the condition before executing the loop body. The for loop
is commonly used when the number of iterations is known. Syntax of for loop-
for (initializationStatement; testExpression; updateStatement)
{
// codes
}
11- How for loop works1. The initialization statement is executed only once.
2. Then, the test expression is evaluated. If the test expression is true, codes inside the body
of for loop is executed and the update expression is updated. This step-2 repeats until the test
expression is false.
3. If the test expression is false, for loop is terminated.
Flowchart of for loop:
Let’s see a program using for loop to print Hello World five times.
#include<stdio.h>
int main()
{
int i;
for(i=1; i<=5; i++)
{
printf("Hello World\n");
}
return 0;
}
while loop statement: Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable. It tests the condition before executing the loop
body. while loops are used in situations where we do not know the exact number of iterations
of loop beforehand. The loop execution is terminated on the basis of test condition. Syntax of
while loop-
while (testExpression)
{
//codes
}
12- How while loop works1. The while loop evaluates the test expression. If the test expression is true, codes inside the
body of while loop is executed. The test expression is evaluated again. The process goes on
until the test expression is false.
2. When the test expression is false, the while loop is terminated.
Flowchart of while loop:
Syntax of while loop like for loop:
initializationStatement;
while(testExpression)
{
// codes;
updateStatement;
}
Let’s see a program using while loop to print Hello World five times.
#include<stdio.h>
int main()
{
int i;
i=1;
while(i<=5)
{
printf("Hello World\n");
i++;
}
return 0;
}
do-while loop statement: The do-while loop is similar to the while loop with one important
difference. The body of do-while loop is executed once, before checking the test expression.
Hence, the do-while loop is executed at least once. Syntax of while loop-
Do
{
// codes
}
while (testExpression);
13- How do-while loop works1. The code block of loop body is executed once.
2. Then, the test expression is evaluated. If the test expression is true, the loop body is
executed again. This process goes on until the test expression is false.
3. When the test expression is false, the do-while loop is terminated.
Flowchart of do-while loop:
Syntax of do-while loop like for loop:
Initialization Statement;
do
{
// codes;
updateStatement;
}while(testExpression);
Let’s see a program using do-while loop to print Hello World five times.
#include<stdio.h>
int main()
{
int i;
i=1;
do
{
printf("Hello World\n");
i++;
}while(i<=5);
return 0;
}
Lesson Evaluationa. What is control statement?
b. What is conditional control statement?
c. What is switch statement?
d. What is loop?
e. What is loop control statement?
f. What is entry control loop statement?
g. What is exit control loop statement?
h. Which one of for loop and while loop is more convenient to use?
i. Explain the difference between while loop and do-while loop.
Lesson 6: ‘continue’ statement, ‘break’ statement and ‘goto’ statement
At the end of this lesson
1. You will be able to write a program using ‘continue’ statement.

2. You will be able to write a program using ‘break’ statement.

3. You will be able to write a program using ‘goto’ statement.
6.1. Continue statement
‘continue’ statement: The continue statement is used inside loops to bring the program
control to the beginning of the loop. When a continue statement is encountered inside a
loop, statement skips some lines of code inside the loop body and continues with the next
iteration. It is mainly used for a condition so that we can skip some code for a particular
condition.
The syntax for a continue statement in C is as follows −
continue;
How ‘continue’ statement works-
A program using ‘continue’ statement in for loop to print all the odd numbers between 1
to 10.
/* Program using for loop */
#include<stdio.h>
int main()
{
int i;
for(i=1; i<=10; i=i+1)
{
if(i%2==0)
continue;
printf("%d\t ",i);
}
return 0;
}
In the above program, when test_expression of the loop body becomes true, then ‘continue’
statement works. ‘continue’ statement works that means skipping execution of printf()
function and continues with the next iteration.
6.2.break statement
‘break’ Statement: The ‘break’ is a keyword in C and break Statement is a loop control
statement which is used to terminate the loop. The break statement is used inside loops or
switch statement. As soon as the break statement is encountered from within a loop, the loop
iterations stops there and control returns from the loop immediately to the first statement after
the loop. In the case of nested loops, it breaks the inner loop first and then proceeds to outer
loops. Basically break statements are used in the situations when we are not sure about the
actual number of iterations for the loop or we want to terminate the loop based on some
condition.
The syntax for a break statement in C is as follows −
break;
How ‘break’ statement works-
Let’s see the following program-
/* Program using for loop */
#include<stdio.h>
int main()
{
int i;
for(i=1; i<=5; i=i+1)
{
printf("Bangladesh\n");
if(i==3)
break;
}
return 0;
}
In the above program, iteration of the loop will be three times instead of five times. Because,
when condition of the loop body will be true, break statement will work that means the
control directly comes out of loop and the loop gets terminated. As a result Bangladesh word
will be printed three times.
6.3. goto statement
‘goto’ statement: The ‘goto’ statement is known as jump statement in C. goto is used to
transfer the program control to a predefined label. The goto statment can be used to repeat
some part of the code for a particular condition. It can also be used to break the multiple loops
which can’t be done by using a single break statement. However, the goto statement is rarely
used because it makes program confusing, less readable and complex.
The syntax for a goto statement in C is as follows −
label:
------------------goto label;
OR
goto label;
--------------------label:
In the above syntax, here label is a user defined identifier which indicates where program
execution control will be shifted. To write this identifier it should be followed the rules of
writing identifier. Do remember, this identifier ends with colon(:) instead of semicolon(;).
Let’s see the the following program that determine LCM of two numbers.
#include<stdio.h>
int main()
{
int a,b,l;
printf("Enter the two numbers: ");
scanf("%d %d",&a,&b);
if(a>b)
l=a;
else
l=b;
again:
if(l%a==0 && l%b==0)
printf("LCM of %d and %d is %d",a,b,l);
else
{
l=l+1;
goto again;
}
return 0;
}
In the above program, using ‘goto’ statement program execution control has been shifted to
the above particular position.
Lesson 7: C ARRAY
At the end of this lesson
1. You will be able to explain array.

2. You will be able to explain types of array.

3. You will be able to declare an array and assign the value of that array.

4. You will be able to explain the advantages and disadvantages of using array.
7.1. Description
Array: Array is a kind of data structure which is a collection of variables of same data
type. Array is called derived data type. An array is used to store group of data of same data
type. Types of array
1. One-dimensional array

2. Multidimensional array (two-dimensional,…)
7.2. One dimension array
A one-dimensional array (or single dimension array) is a type of linear array. Accessing its
elements involves a single subscript which can either represent a row or column index.
Declaration of one dimensional Array in C:
Data_Type Array_Name [ array_size ];
array_size defines how many variables the array hold.The array_size must be an integer
constant greater than zero. Array_Name is just a name of array followed by how to name a
variable. Data_Type indicates the data type of the data that will be stored in the
array. Data_Type can be any valid C data type.
Examples
int id [5];

float marks[5];
Explain: When int id [5]; is declared as array, then five int type variables are declared as the
following.

int id [0];

int id [1];

int id [2];

int id [3];

int id [4];
Initialization of an Array: The values of an array can be initialized in three ways. They are
1. At the time of array declaration

2. After array declaration

3. At the time of program execution
At the time of array declaration: The following way how an array (int id [5];) can be
initialized.
int id [5]={101, 102, 103, 104, 105};
The vales will be assigned in array as follows –

int id [0]=101;

int id [1]=102;

int id [2]=103;

int id [3]=104;

int id [4]=105;
After array declaration: The following way how an array (int id [5];) can be initialized after
array declaration.
int id [5]; // array declaration
Than value assign to the array
id [0]=101;

id [1]=102;

id [2]=103;

id [3]=104;

id [4]=105;
At the time of program execution: Single variable of array can be initialized normally. All
the variables of array can also be initialized using loop statement. Using loop statement, int id
[5]; array initialization-
#include<stdio.h>
int main()
{
int i;
int id[5];
for(i=0; i<5; i++)
{
printf("Enter id");
scanf("%d",&id[i]);
}
return 0;
}
7.3. TWO DIMENSION ARRAY IN C
C language supports multidimensional arrays also. The simplest form of a multidimensional
array is the two-dimensional array. Two dimensional array is nothing but array of array. Both
the row’s and column’s index begins from 0.
Declaration of two dimensional Array in C:
Data_Type Array_Name [ row_size ][ column_size ];
row_size and column_size indicate number of row and column of array respectively. The
row_size and column_size must be an integer constant greater than zero. Array_Name is just
a name of array followed by how to name a variable. Data_Type indicates the data type of the
data that will be stored in the array. Data_Type can be any valid C data type.
Example: To store the elements of a 3×4 matrice in an array, It should be declared as
followsint mat [3][4];
Advantages of using array:

1. It can be used to represent multiple data items of same type by using only single name.

2. It can be used to implement other data structures like linked lists, stacks, queues, trees,
graphs etc.

3. Iterating the arrays using their index is faster compared to any other methods like linked
list etc.

4. It does not allocate any extra space/ memory for its elements. Hence there is no memory
overflow or shortage of memory in arrays.

5. 2D arrays are used to represent matrices.
Disadvantages of using array:

1. We must know in advance that how many elements are to be stored in array.

2. Array is static structure. It means that array is of fixed size. The memory which is
allocated to array can not be increased or reduced.

3. Since array is of fixed size, if we allocate more memory than requirement then the
memory space will be wasted. And if we allocate less memory than requirement, then it
will create problem.

4. The elements of array are stored in consecutive memory locations. So insertions and
deletions are very difficult and time consuming.
Lesson Evaluation-
a. What is array?
b. ‘Array and variable are not same’-explain.
c. ‘Array reduces the complexity of program’-explain.
d. ‘Same type of multiple data can be stored in a single name’-explain.
Lesson 8: Function and String
At the end of this lesson
1. You will be able to explain function.

2. You will be able to explain library function and user defined function.

3. You will be able to explain the importance of using function.

4. You will be able to explain recursive function and it’s advantages and disadvantages.
8.1. Description
Function: A function is a group of statements that together perform a specific task. A
function that take inputs, do some process and produces a output.
8.2. Syntax of a function:
Function declaration: A function declaration tells the compiler about a function’s name, return type,
and parameters. Function declaration is also called as “function prototype”.
Return_type: A function may return a value. Return type can be of any data type such as int,
double, char, void, short etc. Some functions perform the desired operations without returning
a value. In this case, the return_type is the keyword void.
Function_name: It is an identifier and it can be anything, however it is advised to have a
meaningful name for the functions so that it would be easy to understand the purpose of
function just by seeing it’s name.To write function’s name rules of identifier should be
followed.
Parameters: Parameters contains variables names along with their data types that defines
what type and how many inputs for the function. Parameters are optional; that is, a function
may contain no parameters.
Function definition:The function body contains a collection of statements that define what
the function does.
There are two types of function in C programming:

1. Standard library functions

2. User defined functions
Standard library functions: The standard library functions are built-in functions in the
compiler which already have a definition in header files, so we just call them from main()
function whenever there is a need to use them. For example- scanf(), printf(), gets(), puts(),
getchar(), putchar(), abs(), pow(b,p), sqrt(), sin(), cos(), tan(), rand() etc. To use each of the
library function in the program, programmer should add the respective header file at the top of
the program. Library functions are two types. They areNumerical function: Perform mathematical operations. eg. pow(b,p), sqrt(), sin(), rand() etc.
String Function: Perform string related operation. eg. strcpy(), strcat(), strcmp() etc.
Some library functions and their respective header file:
Library function
Header file
scanf(),printf(), gets(), puts(), getchar(),
putchar()
<stdio.h>
sqrt(), pow(), abs(), sin(), cos(), tan(),
rand()
<math.h>
clrscr(), getch()
<conio.h>
strcpy(), strcat(), strcmp()
<string.h>
User defined functions: The functions that a programmer create in a program are known as
user defined functions. main() function is called user-defined function. Each C program must
have at least one function, which is main(). You can create as many user-defined functions as
you want.
Functions are used because of following reasons –
1. To improve the readability of code.
2. Improves the reusability of the code, same function can be used in any program rather than
writing the same code from scratch.
3. Debugging of the code would be easier if you use functions, as errors are easy to be traced.
4. Reduces the size of the code, duplicate set of statements are replaced by function calls.
Elements of function: The following four things are considered when a user-defined
function is used in a ‘C’ program.

1. Function definition

2. Function Call

3. Prototype of function

4. Return type and return statement of function
8.3.Function arguments or parameters
The variables that accept the arguments values can only be used in functions. These variables are also
called as formal parameters of the function.
Inside of the function formal parameters behaves like other local variables and are created when entered
into the function and destroys when exits the function.
Any Functions in C normally accepts the argument and it gives back a return value to the calling
Program.So, there establishes two-way Communication between calling function and called function.
There are two ways to pass the arguments while calling a function from a program. They are :

Call by value.

Call by reference.
By default, all functions are passed by “call by value”. The value of the variable is passed as a parameter.
Actual value cannot be modified by using the derived parameter i.e formal parameter. Both are given
different memories.
#include<stdio.h>
#include<conio.h>
int swap(int , int); // Declaration of function
main( )
{
int a = 10, b = 20 ; // call by value
swap(a,b); // a and b are actual parameters
printf ( "\n Before Swapping \n a = %d b = %d \n", a, b ) ;
getch();
}
int swap( int x, int y ) // x and y are formal parameters
{
int t ;
t = x ;
x = y ;
y = t ;
printf ("\n\nAfter swapping \n x = %d y = %d", x, y ) ;
}
Output:
After swapping
x = 20 y = 10
Before Swapping
a = 10 b = 20
By using call by reference,address of the variable is passed as a parameter. Actual parameter can be
modified by using the derived parameter i.e formal parameter.Both are given same memories.
#include<stdio.h>
#include<conio.h>
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping: num1 value is %d and num2 value is %d", num1, num2);
/*calling swap function*/
swapnum ( &num1, &num2 );
printf("\nAfter swapping: num1 value is %d and num2 value is %d", num1, num2);
}
swapnum ( int *var1, int *var2 )
{
int tempnum ;
tempnum = *var1 ;
*var1 = *var2 ;
*var2 = tempnum ;
}
Output:
Before swapping: num1 value is 35 and num2 value is 45
After swapping: num1 value is 45 and num2 value is 35
Example of non return type function
#include<stdio.h>
void area();
// Prototype Declaration
void main()
{
area();
}
void area()
{
float area_circle;
float rad;
printf("\nEnter the radius : ");
scanf("%f",&rad);
area_circle = 3.14 * rad * rad ;
printf("Area of Circle = %f",area_circle);
}
Output:
Enter the radius : 5
Area of Circle = 78.500000
Example of return type function
#include<stdio.h>
int sum();
int main()
{
int addition;
addition = sum();
printf("\nSum of two given values = %d", addition);
return 0;
}
int sum()
{
int a = 50, b = 80, sum;
sum = a + b;
return sum;
}
Output:
Sum of two given values = 130
8.4.Recursion
Recursive function: A function can call any other function as well as can call itself. When a
function calls itself then the function is called recursive function and the process of calling
itself is called recursion. While using recursion, programmers need to be careful to define an
exit condition from the function, otherwise it will go into an infinite loop. Recursive functions
are very useful to solve many mathematical problems, such as calculating the factorial of a
number, generating Fibonacci series, etc.
a. Syntax
void recursive_function()
{
//statements;
recursive_function();
}
int main()
{
//statements;
recursive_function();
}
b. Conceptual figure
c. Reason
Basic function of Recursion in C is to repeat many times and it may happen forever. But, in real
time what happens is, after some recursions, the program gets crashed. This is because,

For every recursion occurring, the memory creates a stack.

As the recursion occurs multiple times, multiple stacks are added into the memory.

After reaching a point, creation of stacks stops since there occurs a stack overflow. So
the program crashes finally.
Example 1:
Control flow for factorial example will be as follows.
//program for finding factorial of a number
#include<stdio.h>
#include<conio.h>
#include<math.h>
int fact(int);
int main()
{
int number,f;
printf("\nEnter a number: ");
scanf("%d",&number);
f=fact(number);
printf("\nFactorial of %d is: %d",number,f);
return 0;
}
int fact(int n)
{
if(n==1)
{
return 1;
}
else
return(n*fact(n-1));
}
Output:
Enter a number: 5
Factorial of 5 is: 120
Example 2:
//program for finding sum of n numbers
#include<stdio.h>
#include<math.h>
int main()
{
int a,sum;
printf("Enter the value of n: ");
scanf("%d",&a);
sum = getSum(a);
printf("Sum of n numbers: %d",sum);
return 0;
}
int getSum(a)
{
static int sum=0;
if(a>0)
{
sum = sum + a;
getSum(a-1);
}
return sum;
}
Output:
Enter the value of n: 8
Sum of n numbers: 36
Advantages of recursive function:

1. Reduce unnecessary calling of function.

2. Through recursion one can solve problems in easy way while its iterative solution is
very big and complex.


3. Extremely useful when applying the same solution.
Recursion is more powerful in C-language because, it requires only few variables to
perform the action on the variables.

Recursion reduces the code.
Disadvantages of recursive function:

Recursive solution is always logical and it is very difficult to debug and understand.

Fairly slower than its iterative solution.

Due to repetition, stack overflow occurs.

Writing logic for recursion requires a lot of effort.
8.5.C STRING
Description
As discussed in previous chapters, there is no string data type in C-language. Hence, the group
of characters without data type forming a word, can be given individually as an array of
characters using String in C .
A string can be defined as an array of characters which are ended using null character(\0).To
read strings given by user, %s is used in scanf function.
Note:
One character is compulsory needed to store ‘0‘.If not specified ‘\0‘ at the end of array, compiler
assigns unknown size and leads to wastage of memory.
String declaration will be similar to array declaration. But here, strings are of char type.
Eg: char i[5];
C strings can be initialized in various ways.
Eg:
char i[]="xyz";
OR
char i[5]="xyz";
OR
char i[]={'x','y','z','\0'};
OR
char i[4]={'x','y','z','\0'};
Example
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}
Few Strings
String Functions Description
strrev()
Reverses teh given string
strset()
Sets all character in a string to given character
strnset()
Sets the portion of characters in a string to given character
strtok()
Tokenizing given string using delimiter
strncpy()
Copies given number of characters of one string to another
strlen()
Gives the length of string
strdup()
Duplicates the string
strlwr()
Converts the string to lower case
strupr()
Converts the string to upper case
strcat()
Concatenates the two string values
strcmp()
Compares the two strings
strcmpi()
Compares the two strings but it is not case sensitive
strchr()
Pointer points to first character in string
strrchr()
Pointer points to last character in string
strstr()
Pointer points to first character of second string in first
strrstr()
Pointer points to first character of second string in first string
Example
Reading text of line manually is tedious and hence gets() and puts() functions are used in C
language to read and display string respectively.
#include<stdio.h>
#include<conio.h>
int main(){
char name[30];
printf("Enter name: ");
gets(name);
//Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Enter name: SPLessons Tutorial
Name: SPLessons Tutorial
Functions
Functions in C can be defined as a partitioned blocks of code in a program, which can be called
any number of times during single execution of a program.
String can be passed to a function similar to arrays as, string is also an array.
#include <stdio.h>
void Display(char p[]);
int main(){
char s[50];
printf("Enter any string: ");
gets(s);
Display(s);
// Passing string c to function.
return 0;
}
void Display(char p[]){
printf("String Output: ");
puts(p);
}
Output:
Enter any string: SPLessons Tutorial
String Output: SPLessons Tutorial
Key Points
A re-usability block function may or may-not possess arguments but can be called

whenever required.

Function can be called by value or by reference.

Recursive function calls itself for multiple times.

Stacks are created during recursion.

String is group of characters.

In Initialization of the string, if the specific number of character are not initialized then
rest of characters will be initialized with NULL(/0).
Programming Tips

Strings are always enclosed in double quotes(” “).

String variable str accepts only one word because if white space is found, the scanf()
function terminates the program. So, to prevent use gets() function.
Lesson Evaluation
a. What is function?

a. What is library function?

a. What is user-defined function?

a. What is recursive function?

a. What is recursion?

b. ‘Library function and user-defined function in program are not same’- explain.

b. What type of function is main()? explain.

b. Header file has to be written for what type of function using?

b. Why header file has to be written for using library function in program?
Lesson 9: C Pointer
9.1. Description
In the current lesson of Pointers in C, the introduction to address is given initially and then
about the pointers and pointer variables. Any compiler need to store the variables in a memory.
The memory address given to a particular variable is called as a Pointer.
Computer’s memory consists of 8 bit bytes in a continuous sequence. Portions of this memory
are reserved when a program starts to store a program code, variables, functions, arguments,
local variables and so on. The storage for each variable must reside in memory, and where it
resides is defined by an address.
Every variable has an address even if it is not used which is just the offset from the base address
to the location where the variable storage resides. Now, C provides a special category of
variables specifically for handling these addresses. So these are address variables and they are
called Pointers.
Pointers in C or pointer variables also has a type that indicates the variable type being pointed
to provide a degree of safety as the compiler can check that the variable being pointed to,
according to the rules governing that particular type. Sometimes type of a pointer might not be
considered. There are many reasons to do this, but it should be done with some caution.In that
situations, C provides a special type called void which means some storage whose type is
unknown to the compiler.
Simply, pointer is memory locator of a variable.
Note:
Whenever declaring a pointer specify the location where it has to be pointed. Pointer cannot
point wherever it likes.
The simplest way to start using pointers is to get the address of some variable. This variable is
stored on the memory stack, and there is no need to think about where or how its storage was
provided. But its address can be obtained using the address of operator.
When using Pointers in C the compiler usually unable to detect whether pointers are, in fact,
pointing to some valid location. C also does not offer any run time facility for making these
sorts of checks.
9.2. Conceptual figure

In the above figure, a is the variable having value 10 located at an address 1000. This
address is stored in another variable “ptr” called as pointer variable located at an
address 2000.So, the datatype should be same for normal variable and pointer variable.

In C-language, the address of a variable can obtained by giving & in front of the variable
like i=&a.
9.3. Syntax
pointer_type *(pointer_name)
Eg: char *ptr;
9.4. Example
#include <stdio.h>
int main()
{
int var =10;
int *p;
p= &var;
printf ( "\n Address of var is: %u", &var);
printf ( "\n Address of var is: %u", p);
printf ( "\n Address of pointer p is: %u", &p);
/* Note I have used %u for p's value as it should be an address*/
printf( "\n Value of pointer p is: %u", p);
printf ( "\n Value of var is: %d", var);
printf ( "\n Value of var is: %d", *p);
printf ( "\n Value of var is: %d", *( &var));
}
Output:
Address of var is: 2358860
Address of var is: 2358860
Address of pointer p is: 2358848
Value of pointer p is: 2358860
Value of var is: 10
Value of var is: 10
Value of var is: 10
a- Advantages

Pointers helps in dynamic memory management.

Complexity of the program is reduced by pointers.

Pointers increases the efficiency while handling arrays and structures.
Note :
1- A pointer variable will always be given a garbage value. It is better to make a pointer
variable “null” in order to identify the variable easily.If a pointer is declared as null, it
is called as null pointer .
2- Pointers in C and arrays are very closely related in C. In fact, the language construct for
pointers and arrays are largely interchangeable.
3- Pointers are handy when dealing with arrays i.e pointer arithmetic is used to change the
element being pointed to very efficiently. Pointer can be incremented and it will point
to the next element in the array.
Example
#include<stdio.h>
#include<conio.h>
const int x=3;
int main()
{
int a[]={10,20,30};
int i,*ptr[x];
for(i=0;i<x;i++)
{
ptr[i]=&a[i];
}
for(i=0;i<x;i++)
{
printf("value of a[%d]=%d\n",i, *ptr[i]);
}
}
Output:
value of a[0]=10
value of a[1]=20
value of a[2]=30
Key Points

Pointers in C are variables that points to address of a another variable.

Specification of pointing address is must.
Note:
It is better to free and insert 0 in the pointer variable to avoid confusion when any new variable
is allocated the address.
Lesson 10: C Structure and union
Introduction
In C-programming, a variable consists of single data and single data type. An array consists of
multiple data of the same data type. Continuing in advance, Structure and Union in C consists
of multiple data and multiple data types, sometimes called records in other languages.
10.1. Structure
Structure in C can be defined as group of variables with same name and different data types
which can be created, pointed to, copied, and refer to conveniently and easily. Unlike in C++,
the names of structures are declared in a separate name space in C. .
a- Description
Defining a structure can be done two ways.
1. Using “struct” as the datatype
2. Using header file
b- Syntax
struct structure_name
{
//statements;
};
Example
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int age;
float percentage;
}file;
int main()
{
strcpy(file.name, "John");
file.age=25;
file.percentage=78-9;
printf("Name is %s\n",file.name);
printf("age is %d\n",file.age);
printf("percentage is %f\n", file.percentage);
}
Output:
Name is John
age is 25
percentage is 69.000000
More Info
Every member of structure is called as Structure Member or an Element.In the above
example, John, age,percentage are called as tags which are of different data types.
The structures can be accessed using the dot . operator. Structure can also be accessed
by using ->. As using arrow is bit complex, dot operator is used.
Any structure is initialized in order to access it and allocate a memory to it.
Declaring will be same as defining. Coming to defining a structure, assign values to variables
at the end of structure block ( after the braces) by giving a semicolon.
Example
struct student
{
char name[20];
int age;
float percentage;
}
student1={"John",15,77.5};
student2{"Mike",16,78};
When there are no values to declare, structure should be declared as null. Otherwise,
there will be no memory allocation for the variable.
There is also another way for defining a structure by using “header files“.

Create the file with .h extension and write the structure code as follows.Now write the
structure code in it and save.

Open other file with extension .c and include the header section created before and use
it in the program.
Eg: #include “structure.h”.
Example
#include<stdio.h>
#include<conio.h>
#include"structure.h"
int main()
{
strcpy(file.name, "splessons");
file.age=25;
file.percentage=78-9;
printf("Name is %s\n",file.name);
printf("age is %d\n",file.age);
printf("percentage is %f\n", file.percentage);
}
Note:
Just declaring the structure will never allocate memory to it. Structure must be initialized.
An Array is the collection of similar type of elements stored in continuous memory address
whose range is defined before the declaration. The elements in array can be selectively updated.
Example
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "John");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Mike");
record[1].percentage = 90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name, "Anderson");
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf("Records of STUDENT : %d \n", i+1);
printf("Id is: %d \n", record[i].id);
printf("Name is: %s \n", record[i].name);
printf("Percentage is: %f\n\n",record[i].percentage);
}
return 0;
}
Output:
Records of STUDENT : 1
Id is: 1
Name is: John
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Mike
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Anderson
Percentage is: 81.500000
Description
The information is passed to the functions by using arguments.Basically, a function consists of
fixed number of parameters and for every parameter passing of an argument is needed.
The memory address given to a particular variable is called as a Pointer.
Example
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "William", 90.5};
struct student *ptr;
ptr = &record1;
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}
Output:
Records of STUDENT1:
Id is: 1
Name is: William
Percentage is: 90.500000
9.2. Union in C
Unions in C are very similar to structures. The keyword used is “union“. Union is used mainly
to save the memory space and to store the values dynamically. The differences between Unions
in C and structure is,

Structure allocates memory for every member of it separately. Whereas union allocates
a single shared storage space for all of its members which will be the size of its biggest
data member.

Manipulations made on one member will not effect the other in structures. As only
single member is allocated at a time in unions, manipulations done on one member will
reflect on other.
Conceptual figure
Syntax
union union_name
{
//declarations and initializations of members;
};
Description
The union variable can be retrieved in the same manner as in the structure. To access the union
variable . dot operator is used and to get the address of union variable * is used.
Unions in C are not much used when compared to structures as they does not store all the
variables at a time.
union example
{
char c;
int a;
float b;
} ex;
union example
{
char c;
int a;
float b;
} ex;
ex.c;
ex.a;
ex.b;
Example
#include<stdio.h>
#include<conio.h>
union car
{
int model;
float cost;
char car_name;
};
int main( )
{
union car c;
c.model = 2011;
c.cost = 100000;
c.car_name='i20';
clrscr();
printf("%d\n",c.model);
printf("%f\n",c.cost);
printf("%c\n",c.car_name);
getch();
return 0;
}
Key Points

Variables of different data type and same name in structures can be accessed with dot
operator.

Every structure member are given different memory space and can be accessed
individually.

Structure “struct” keyword is replaced with “union” and is used in shareable mode.

Unions are used to focus on memory as each member within union structure is assigned
its own unique storage space.
Programming Tips

The structure declaration type must end with a semicolon( ; ).

Basically, structure in C is written in global declaration section. That can also be done
in main section.

Initialization of all the members of the structure is not necessary.

Do not initialize multiple members using union. The compiler gives an error.
Lesson 11: C Dynamic Memory management
The process of allocating memory during program execution is called dynamic memory
allocation.
C language offers 4 dynamic memory allocation functions. They are,
1. malloc()
2. calloc()
3. realloc()
4. free()
Function
Syntax
malloc ()
malloc (number *sizeof(int));
calloc ()
calloc (number, sizeof(int));
realloc ()
realloc (pointer_name, number * sizeof(int));
free ()
free (pointer_name);
1. MALLOC() FUNCTION IN C:

malloc () function is used to allocate space in memory during the execution of the program.

malloc () does not initialize the memory allocated during execution. It carries garbage
value.

malloc () function returns null pointer if it couldn’t able to allocate requested amount of
memory.
EXAMPLE PROGRAM FOR MALLOC() FUNCTION IN C:
2. CALLOC() FUNCTION IN C:

calloc () function is also like malloc () function. But calloc () initializes the allocated
memory to zero. But, malloc() doesn’t.
3. REALLOC() FUNCTION IN C:

realloc () function modifies the allocated memory size by malloc () and calloc () functions
to new size.

If enough space doesn’t exist in memory of current block to extend, new block is allocated
for the full size of reallocation, then copies the existing data to new block and then frees
the old block.
4. FREE() FUNCTION IN C:

free () function frees the allocated memory by malloc (), calloc (), realloc () functions and
returns the memory to the system.
OUTPUT:
Dynamically allocated memory content : fresh2refresh.com
Resized memory : space is extended upto 100 characters
DIFFERENCE BETWEEN STATIC MEMORY ALLOCATION AND DYNAMIC MEMORY
ALLOCATION IN C:
Static memory allocation
Dynamic memory allocation
In static memory allocation, memory is
In dynamic memory allocation,
allocated while writing the C program.
memory is allocated while
Actually, user requested memory will be
executing the program. That
allocated at compile time.
means at run time.
Memory size can’t be modified while
Memory size can be modified
execution.
while execution.
Example: array
Example: Linked list
DIFFERENCE BETWEEN MALLOC() AND CALLOC() FUNCTIONS IN C:
malloc()
calloc()
It allocates only single block of requested
It allocates multiple blocks of
memory
requested memory
int *ptr;Ptr = calloc( 20, 20 *
sizeof(int) );For the above, 20
int *ptr;ptr = malloc( 20 * sizeof(int)
blocks of memory will be created
);For the above, 20*4 bytes of memory
and each contains 20*4 bytes of
only allocated in one block.
memory.
Total = 80 bytes
Total = 1600 bytes
malloc () doesn’t initializes the allocated
calloc () initializes the allocated
memory. It contains garbage values
memory to zero
type cast must be done since this function
Same as malloc () function int
returns void pointer int *ptr;ptr =
*ptr;ptr = (int*)calloc( 20, 20 *
(int*)malloc(sizeof(int)*20 );
sizeof(int) );
Lesson 12: C File I/O management
Description
Termination or sudden problem in C-program may lead to loss of data. So, to overcome this
problem in C-language, C-files are used and can be accessed by using C File I/O functions.
File can be defined as the collection of similar data stored permanently in a disk. The data
stored in this can be changed if needed and can be used at any time by using C File I/O functions.
File is declared in <stdio.h> header file and can be accessed with a pointer.
To declare a file in C language, structure pointer of file type is used.
FILE *fp;
High level C File IO functions can be categorized as:
1. Text file
2. Binary file
Some of the basic C File IO operations are as shown below.
Function
description
fopen()
Used to create a new file or open a existing file.
fclose()
Used to close a file.
fscanf()
Used to read a dataset from a file.
fprintf()
Used to write data to a file.
getc()
Used to read characters from files.
putc()
Used to write a character to a file.
getw()
Used to read an integer from a file.
putw()
Used to write an integer to a file.
rewind()
Used to set the position to the beginning point.
ftell()
Used to give current position in the file.
fseek()
Used to set the position to required point.
Conceptual figure
Below are C File IO Functions
Description
The first step in opening a file goes with creating a file by declaring a file pointer and then open
the created file. Opening a file is done with fopen() function.
Syntax
*fp = FILE *fopen(const char *filename, const char *mode);
(or)
fp=fopen(“filename”,”mode”);
In the above syntax,
filename is the name of the file to be opened.
mode in the syntax which denotes the purpose of creating a file.
*fp refers to the opened(or created) file.
Mode Types
Mode
Description
R
Represents open a file for read
W
Represents open empty file for writing
A
Represents open a file to append
r+
Represents open a binary file for read and write
w+
Represents open a binary file for write and read
r+
Represents open a binary file for append and read
Example
#include<stdio.h>
int main()
{
FILE *fp;
char a;
fp= fopen ("splessons.C");
if(fp==NULL)
{
printf("can't open");
exit(1);
}
}
exit() function in above program is similar to the return function the C main section.
Description
Various file I/O functions are discussed in the above table which performs reading and writing
operations on file. getc() and putc() are two simple functions to read and write individual
characters to a file.
When the user inputs the data, data is written and stored in the file. This can be done by using
C File I/O function, fprintf() function. f in the starting represents the file argument pointed to
file structure.
#include<stdio.h>
int main()
{
int a;
FILE *fp;
fp=fopen("C:\\splessons.txt");
if(fp==NULL)
{
printf("no file exists");
exit(1);
}
printf"Enter a:");
scanf("%d",&a);
fprintf(fp,"%d",a);
fclose(fp);
return 0;
}
To read the data from a file fscanf() function is used.
#include<stdio.h>
int main()
{
int a;
FILE *fp;
if ((fp=fopen("C:\\aplessons.txt")==NULL)
{
printf("Cannot open the file");
exit(1);
}
fscanf(fp,"%d",&a);
printf("Value of n=%d",a);
fclose(fp);
return 0;
}
Description
When there is no action to be performed with a file, it can be closed. This can be done by using
C File I/O function, fclose(ptr). Compiler returns zero if the action is complete (or)
returns eof if there is any error in closing the file.
/* fclose example */
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ("myfile.txt","wt");
fprintf (pFile, "fclose example");
fclose (pFile);
return 0;
}
Description
A file can be renamed as per the requirement. Renaming actually means that the user can give
their own names to the file according to their convenience.This can be done
with rename()function.
int rename(const char *old_filename, const char *new_filename)
If the file is renamed zero is returned.Otherwise, -1 is returned, and errno is set appropriately.
#include <stdio.h>
int main ()
{
int r;
char oldname[] = "file.txt";
char newname[] = "newfile.txt";
r = rename(oldname, newname);
if(r == 0)
{
printf("File renamed successfully");
}
else
{
printf("Error: unable to rename the file");
}
return(0);
}
Output:
Error: unable to rename the file
Description
A file can be deleted if there is no use with it in future. Once the file is deleted, it cannot be
restored.This can be done with remove() function.
int remove(const char *filename)
#include <stdio.h>
#include <string.h>
int main ()
{
int r;
FILE *fp;
char filename[] = "file.txt";
fp = fopen(filename, "w");
fprintf(fp, "%s", "This is splessons.com");
fclose(fp);
r = remove(filename);
if(r == 0)
{
printf("File deleted successfully");
}
else
{
printf("Error: unable to delete the file");
}
return(0);
}
Output:
File deleted successfully
Key Points

File is collection of data.

Opening, closing, writing, reading,deleting and renaming are C File I/O functions.
Programming Tips

It is better practice to delete the files if not necessary to save the memory.

When using string literal as the argument,do not forget to use double backslashes rather
than a single backslash as double backslashes \\ escapes the \ key, so the string works
as it is expected