SlideShare ist ein Scribd-Unternehmen logo
1 von 233
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
1
© NIELIT Gorakhpur Centre.
2© NIELIT Gorakhpur Centre.
Chapter No. Topic
1 Language
2 Flow Charts
3 C Language
4 Data Types and Operator
5 Decision Making & Control Statement
6 Loops
7 Functions
8 Pointers
9 Storage Class
10 C Preprocessor
11 Structure
12 File Handling
13 Command Line Argument
14 Dynamic Memory Allocation
15 Linked List
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
3
© NIELIT Gorakhpur Centre.
• What is Language?
• Programming Language
4© NIELIT Gorakhpur Centre.
Language is a collection of words and symbols which can be used to perform certain task or
activities and to establish a communication between person to person.
In the same manner computer languages are the collection of predefine key words which can
be used to perform certain task and to communicate between to entities like between two
machines or between human and computers or computers and others peripherals. There are
three different level of programming languages. They are:
 Machine languages (low level)
 Assembly languages
 Procedure Oriented languages (high level)
5© NIELIT Gorakhpur Centre.
 Machine Languages:
Computers are made of No. of electronic components and they all are two – state
electronic components means they understand only the 0 – (pulse) and 1 (non – pulse).
Therefore the instruction given to the computer must be written using binary numbers.
1and 0. Computers do not understand English or any other language but they only
understand or respond to binary numbers (0 and 1). So each computer has its own
Machine languages.
6© NIELIT Gorakhpur Centre.
 Assembly Languages:
As it was very tedious to understand and remember 0’s representing numerous data and
instruction. So to resolve this problem mnemonics codes were developed. For example
add is used as symbolic code to represent addition. SUB is used for subtraction. They are
the symbolic representation of certain combination of binary numbers .
for example S U B
Which represents certain actions as computer understand only Machine language
instructions a program written in Assembly Language must be translated into Machine
languages. Before it can be executed this translation if done by another program called
assembler. This assembler will translate mnemonic codes into Machine languages.
7© NIELIT Gorakhpur Centre.
 Procedure Oriented Languages:
In earlier assembly languages assembler programs produced only one Machine languages
instruction for every assembly languages instruction. So to resolve this problem now
assembler were introduced. Which can produce several machine level instructions for one
assembly language instruction. Thus programmer was relieve from the task of writing and
instruction for every machine operation performed. These languages contains set of words
and symbols and one can write program with the combination of these keywords. These
languages are also called high level languages. Basic, Fortran, Pascal and COBOL. The
most important characteristic of high level languages is that it is machine independent and
a program written in high level languages can be run on any computers with different
architecture with no modification or very little modification.
8© NIELIT Gorakhpur Centre.
All programming languages can be divided into two categories:
Problem Oriented Language
Or
High Level Language
Problem Oriented Language
Or
Low Level Language
Programming
Language
9© NIELIT Gorakhpur Centre.
Problem oriented languages or high languages :
Examples of languages falling in this category are FORTRAN, BASIC, Pascal, etc. These
languages have been designed to give a better programming efficiency, faster program
development. Generally these languages have better programming capability but they are less
capable to deal with hardware or Hardware related programming.
Machine oriented languages of Low Level Languages :
Examples of languages falling in this category are Assembly language and Machine
Language. This languages have been designed to give a better machine efficiency i.e. faster
program execution. Generally these languages have better hardware programming capability
but it is very difficult and tedious to do create complex application like and business
application or some commercial application
C as Middle Level Language :
C stands in between these two categories. That’s why it is called a Middle Level Language,
since it was designed to have both; a relatively good programming efficiency (as compared to
Machine Oriented Language) and a relatively good machine efficiency (as compared to
Problem Oriented Language).
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
10
© NIELIT Gorakhpur Centre.
• Introduction
• Flow Chart Symbol
• Examples
• Advantages
• Limitation
START
Statement
Condition
Statement
Statement
STOP
11© NIELIT Gorakhpur Centre.
A flowchart is a graphical representation of decisions and their results mapped out in
individual shapes that were first developed by Herman Goldstine and John von Neumann
in the 1940’s. Flowcharts can provide a step-by-step diagram for mapping out complex
situations, such as programming code or troubleshooting problems with a Computer.
 A diagrammatic representation that illustrates the sequence of operations to be
performed to get the solution of a problem.
 Generally drawn in the early stages of formulating computer solutions.
 Facilitate communication between programmers and business people/end users.
 Once the flowchart is drawn, it becomes easy to write the program in any high level
language.
 Must for the better documentation of a complex program.
12© NIELIT Gorakhpur Centre.
Symbol Description
Used to indicates the start and end of a flowchart. Single
flow line. Only one “Start” and “Stop” terminal for each
program.
Process: Used whenever data is being manipulated. One flow
line enters and one flow line exits.
Input / Output: Used whenever data is entered (input) or
displayed (output). One flow line enters and one flow line
exits.
Decision: Used to represent operations in which there are two
possible selections. One flow line enters and two flow lines
exit.
Flow line: Used to indicate the direction of flow of control.
13© NIELIT Gorakhpur Centre.
 Example 1: Draw a flow chart to show the addition of two no.
START
STOP
Accept no1 & no1
Sum=no1+no2
Display the sum
14© NIELIT Gorakhpur Centre.
Example 2: Draw a flowchart to find the sum of first 50 natural numbers.
15© NIELIT Gorakhpur Centre.
Example 3: Draw a flowchart to find the largest of three numbers A,B and C.
16© NIELIT Gorakhpur Centre.
Example 4: Draw a flowchart for computing factorial of a given number.
17© NIELIT Gorakhpur Centre.
 Communication: Flowcharts are better way of communicating the logic of a system to
all concerned.
 Effective analysis: With the help of flowchart, problem can be analyzed in more
effective way.
 Proper documentation: Program flowcharts serve as a good program documentation,
which is needed for various purposes.
 Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis
and program development phase.
 Proper Debugging: The flowchart helps in debugging process.
 Efficient Program Maintenance: The maintenance of operating program becomes easy
with the help of flowchart. It helps the programmer to put efforts more efficiently on that
part.
18© NIELIT Gorakhpur Centre.
 Complex logic: Sometimes, the program logic is quite complicated.
 Alterations and Modifications: Alterations may require re-drawing completely.
 Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart
becomes a problem.
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
19
© NIELIT Gorakhpur Centre.
• Introduction
• History of C
• Importance of C
• Basic Structure of C program
• Execution of C program
• Variable
• Keywords
• Constant in C
20© NIELIT Gorakhpur Centre.
C language is a general purpose and structured programming language developed
by 'Dennis Ritchie' at AT &T's Bell Laboratories in the 1972 in USA.
It is also called as 'Procedure oriented programming language.'
C is not specially designed for specific applications areas like COBOL (Common
Business-Oriented Language) or FORTRAN (Formula Translation).
It is well suited for business and scientific applications.
It has some various features like control structures, looping statements, arrays, macros
required for these applications.
 The C language has following numerous features as:
 Flexibility
 Portability
 Compactness
 Reusability
21© NIELIT Gorakhpur Centre.
FLEXIBLILITY: C is a powerful and flexible language. C is used for projects as diverse as
operating system, word processor, graphics, spreadsheets and even compilers for other
language. C is a popular language preferred by professional programmers. As a result, a wide
variety of C compilers and helpful accessories are available.
PORTABILITY: C is a portable language. Portable means that a C program written for one
computer system can be run on another system with little or no modification. Portability is
enhanced by the ANSI standard by C, the set of rules for C compilers.
COMPACTNESS: C is a language of few words, containing only a handful terms, called
keywords, which serve as the base on which the language’s functionality is built. You might
think that a language with more keyword would be more powerful. This isn’t true. As you
will find that it can be programmed to do any task.
REUSABILITY: C is modular, C code can and should be written in routine called
functions. These functions can be reused in other applications or programs. By passing
pieces of information to the function, you can create useful, reusable code.
22© NIELIT Gorakhpur Centre.
23© NIELIT Gorakhpur Centre.
 C was evolved from ALGOL, BCPL and B.
 C was developed by Dennis Ritchie at the Bell Laboratories in 1972.
 Added new features and concepts like “data types”.
 It was developed along with the UNIX operating system.
 It was strongly integrated with the UNIX operating system.
 In 1983 American National Standards Institute (ANSI) appointed a technical committee
to define a standard for C. The committee approved a version of C in December 1989
which is now known as ANSI C.
 In 1990 International Standards Organization (ISO) has approved C and this version of C
is referred to as C89.
24© NIELIT Gorakhpur Centre.
 Rich set of built-in functions
 Operators can be used to write any complex program.
 The C compiler combines the capabilities of an assembly language with the features of a
high-level language.
 It is well sited for writing both system software and business packages.
 Due to variety of data types and powerful operators programs written in C are efficient
and fast.
 There are only 32 keywords in C and its strength lies in its built in functions.
 C is highly portable.
 Ability to extend itself.
 C is a Structured Programming Language (requiring the user to think of a problems in
terms of function modules or blocks).
25© NIELIT Gorakhpur Centre.
C program can be viewed a s group of building blocks called functions. A function is a
subroutine that may include one or more statement designed to perform a specific task. A C
program may contain one or more section as shown below :
Documentation Section
• Link Section
• Definition Section
• Global declaration Section
• main( ) function section
{
Declaration Part
Executable Part
}
Subprogram Section
Function1 ( )
{
}
Function2 ( )
{
}
26© NIELIT Gorakhpur Centre.
 Documentation Section:
This section contains set of comments lines consist of details like program name, author
name and purpose or functionality of the program.
 Link Section:
This section consist of instructions to be given to the compiler to link functions from the
system library. For example if you want to use some mathematical function then you have
to define link for math.h file in link section.
For Example:
# include<stdio.h>
# include<math.h>
 Definition Section:
This section defines all the symbolic constants. For example PI=3.14. By defining
symbolic constant one can use these symbolic constant instead of constant value.
# define PI 3.14
# define Temp 35
27© NIELIT Gorakhpur Centre.
 Global Declaration Section :
This section contains the declaration of variables which are used by more then more then
one function of the program.
 Main Function Section :
A main() function is a heart of any ‘C’ language program. Any C program is made up of
1 or more then 1 function. If there is only 1 function in the program then it must be the
main program. An execution of any C program starts with main() function.
 Subprogram Or Sub Function Section :
They are the code section which are define outside the boundary of main function. This
function can be called from any point or anywhere from the program. Generally they are
define to solve some frequent tasks.
28© NIELIT Gorakhpur Centre.
C program executes in following 4 (four steps).
29© NIELIT Gorakhpur Centre.
1. Creating a program :
An editor like notepad or WordPad is used to create a C program. This file contains a source
code which consists of executable code. The file should be saved as '*.c' extension only.
2. Compiling the program :
The next step is to compile the program. The code is compiled by using compiler. Compiler
converts executable code to binary code i.e. object code.
3. Linking a program to library :
The object code of a program is linked with libraries that are needed for execution of a
program. The linker is used to link the program with libraries. It creates a file with '*.exe'
extension.
4. Execution of program :
The final executable file is then run by dos command prompt or by any other software.
30© NIELIT Gorakhpur Centre.
Character Set
A character refers to the digit, alphabet or special symbol used to data representation.
 Alphabets : A-Z, a-z
 Digits : 0-9
 Special Characters : ~ ! @ # $ % ^ & * ( ) _ + { } [ ] - < > , . / ?  | : ; " '
 White Spaces : Horizontal tab, Carriage return, New line
 Identifier
identifier is the name of a variable that is made up from combination of alphabets, digits
and underscore.
Variable
It is a data name which is used to store data and may change during program execution. It is
opposite to constant. Variable name is a name given to memory cells location of a computer
where data is stored.
31© NIELIT Gorakhpur Centre.
Rules for variables:
• First character should be letter or alphabet.
• Keywords are not allowed to use as a variable name.
• White space is not allowed.
• C is case sensitive i.e. UPPER and lower case are significant.
• Only underscore, special symbol is allowed between two characters.
32© NIELIT Gorakhpur Centre.
There are totally 32 (Thirty Two) keywords used in a C programming.
int float double long
short signed unsigned const
if else switch break
default do while for
register extern static struct
typedef enum return sizeof
goto union auto case
void char continue volatile
33© NIELIT Gorakhpur Centre.
 Keywords are the system defined identifiers.
 All keywords have fixed meanings that do not change.
 White spaces are not allowed in keywords.
 Keyword may not be used as an identifier.
 It is strongly recommended that keywords should be in lower case letters.
34© NIELIT Gorakhpur Centre.
A constant is an entity that doesn't change during the execution of a program.
Syntax: const data type var_name=expression;
Example: const float pi=3.147
Followings are the different types of constants :
1. Real Constant :
It must have a decimal point which may be positive or negative. Example: +194.143, -416.41
2. Integer Constant :
It should not contain a decimal place.
It can be positive or negative. Example: 1990, 194, -394
3. Character Constant :
It is a single alphabet or a digit or a special symbol enclosed in a single quote.
Maximum length of a character constant is 1. Example: 'T', '9', '$'
4. String Constant :
It may contain letters, digits, special characters and blank space. Example: “Hello friends"
35© NIELIT Gorakhpur Centre.
C supports some special escape sequence characters that are used to do special tasks.
Character Constant Meaning
n New line (Line break)
b Backspace
t Horizontal Tab
f Form feed
a Alert (alerts a bell)
r Carriage Return
v Vertical Tab
? Question Mark
' Single Quote
'' Double Quote
 Backslash
0 Null
36© NIELIT Gorakhpur Centre.
Comments in C are of the general of
/* . . . . . * /
Comments can be inserted anywhere you can put a space (blank). Comments are ignored
by the C compiler and not included in the executable file.
The */ can be on the next line but then every character between the /* and the */ is
ignored by the C compiler.
37© NIELIT Gorakhpur Centre.
 Syntax Errors
The C compiler will catch these errors and give you Error messages.
Example: x + 1 = x; (should be x = x+1; for a valid assignment statement)
 Run-time Errors
The C compiler will not catch these errors.
Example: User enters the value 0 and your code reads this value into variable x, and
then computes 1/x .
 Logical Errors
The C compiler will not catch these errors. Program will run and not generate any error
messages but results outputted by the program are incorrect.
Example: User programs solution using the wrong formula.
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
38
© NIELIT Gorakhpur Centre.
• Data Types
• Operators
• Increment / Decrement Operator
• Input / Output Statement
39© NIELIT Gorakhpur Centre.
PRIMARY
DATATYPE
DERIVED
DATATYPE
INTEGER
CHAR
FLOAT
VOID
ARRAY
POINTER
STRUCTURE
UNION
USER DEFINED
TYPE
TYPEDEF
ENUM
40© NIELIT Gorakhpur Centre.
 Integer :
To access and to store any integer value int data type is use. C’s int data type occupies
2 bytes in the memory.
To declare any integer variable : int variable_name;
 Float :
To access and to store any real value float data type is use. C’s float data type occupies
4 bytes in the memory.
To declare any float variable : float variable_name;
 Character :
To access and to store single character it use char data type in C. Char data type
occupies 1 bytes. It means that char data type use 1 byte of memory to store some
character value.
Declaration of character variable : char variable_name;
41© NIELIT Gorakhpur Centre.
Keyword Format Specifier Size Data Range
char %c 1 Byte -128 to +127
unsigned char %c 1 Byte 0 to 255
int %d 2 Bytes -32768 to +32767
long int %ld 4 Bytes -231 to +231
unsigned int %u 2 Bytes 0 to 65535
float %f 4 Bytes -3.4e38 to +3.4e38
double %lf 8 Bytes -1.7e38 to +1.7e38
long double %Lf 10Bytes -3.4e38 to +3.4e38
“Data type can be defined as the type of data of variable or constant store.”
 Followings are the most commonly used data types in C.
42© NIELIT Gorakhpur Centre.
“Operator is a symbol that is used to perform operations.”
 Followings are the most commonly used data types in C.
Operator Name Operators
Assignment =
Arithmetic + , - , *, /, %
Logical &&, ||, !
Relational <, >, <=, >=, ==, !=
Shorthand +=, -=, *=, /=, %=
Unary ++, --
Conditional Y=(x>9)? 100 :200 ;
Bitwise &, |, ^, <<, >>, ~
43© NIELIT Gorakhpur Centre.
 Arithmetic operators are used to perform numerical calculations among the values.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
44© NIELIT Gorakhpur Centre.
Example:
#include<stdio.h>
int main()
{
int a, b, add, sub, mul, div, rem;
printf("Enter a, b values : ");
scanf("%d%d",&a,&b); // Reading two values
add=a+b; // Addition Operator
sub=a-b; // Subtraction Operator
mul=a*b; // Multiplication Operator
div=a/b; // Division Operator
rem=a%b; // Remainder (Modulo) Operator
printf("Result of addition is=%dn", add);
printf("Result of subtraction=%dn", sub);
printf("Result of multiplication is=%dn", mul);
printf("Result of division is=%dn", div);
printf("Result of remainder=%dn",rem);
return 0;
}
45© NIELIT Gorakhpur Centre.
 These operators are used for testing more than one condition and making decisions.
 C has three logical operators they are:
Operator Meaning
&& Logical AND
| | Logical OR
! Logical NOT
46© NIELIT Gorakhpur Centre.
Example:
#include<stdio.h>
void main()
{
int a, b;
printf(“Enter values for a and b : ");
scanf(“%d %d", &a, &b);
printf("n %d",(a<b)&&(a!=b));
printf("n %d",(a<b)||(b<a));
printf("n %d",!(a==b));
}
47© NIELIT Gorakhpur Centre.
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
=> Is greater than or equal to
== Is equal to
!= Is not equal to
 Relational Operators are used to compare two quantities and take certain decision
depending on their relation.
If the specified relation is true it returns one.
If the specified relation is false it returns zero.
48© NIELIT Gorakhpur Centre.
Example:
#include<stdio.h>
void main()
{
int a, b;
printf(“Enter values for a and b : ");
scanf("%d %d", &a, &b);
printf("n The < value of a is %d", a<b);
printf("n The <= value of a is %d", a<=b);
printf("n The > value of a is %d", a>b);
printf("n The >= value of a is %d", a>=b);
printf("n The == value of a is %d", a==b);
printf("n The != value of a is %d", a!=b);
}
49© NIELIT Gorakhpur Centre.
C includes a unary increment operator (++) and decrement operator (--).
Increment and decrement operators increase and decrease a value stored in a number variable by 1.
For example, the expression,
count = count + 1; //increment the value of count by 1 is equivalent to count++;
Operator Use Description
++ i++ Increments i by 1; evaluates to
the value of i before it was incremented
++ ++i Increments i by 1; evaluates to
the value of i after it was incremented
-- i-- Decrements i by 1; evaluates to
the value of i before it was decremented
-- --i Decrements i by 1; evaluates to
the value of i after it was decremented
For example:
int i = 10,
int j = 3;
int k = 0;
k = ++j + i; //will result to k = 4+10 = 14
k = j++ + i; //will result to k = 3+10 = 13
50© NIELIT Gorakhpur Centre.
Example:
#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter the values for a and b :");
scanf("%d %d", &a, &b);
printf("n The value of c is %d", c=++a);
printf("n The value of c is %d", c=a++);
printf("n The value of c is %d", c=--b);
printf("n The value of c is %d", c=b--);
}
51© NIELIT Gorakhpur Centre.
The conditional operator ? : is a ternary operator. This means that it takes in three
arguments that together form a conditional expression.
Syntax:
exp1 ? exp2 : exp3;
Where in exp1 is a Boolean expression whose result must either be true or false. If exp1 is
true, exp2 is the value returned. If it is false, then exp3 is returned.
52© NIELIT Gorakhpur Centre.
Example:
void main()
{
int x;
printf("enter any number");
scanf("%d",&x);
x>0? printf("Positive"):printf("Negative");
}
53© NIELIT Gorakhpur Centre.
 These operators works on bit level
 Applied to Integers only
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift Left
>> Shift Right
~ One’s Complement
54© NIELIT Gorakhpur Centre.
Let A=0x56 and B=0x32
A & B ( Bitwise AND )
0 1 0 1 0 1 1 0
0 0 1 1 0 0 1 0
---------------------
0 0 0 1 0 0 1 0
---------------------
A ^ B ( Bitwise XOR )
0 1 0 1 0 1 1 0
0 0 1 1 0 0 1 0
---------------------
0 1 1 0 0 10 0
---------------------
A | B ( Bitwise OR )
0 1 0 1 0 1 1 0
0 0 1 1 0 0 1 0
---------------------
0 1 1 1 0 1 1 0
---------------------
~ A ( Complement )
0 1 0 1 0 1 1 0
---------------------
1 0 1 0 1 0 0 1
---------------------
55© NIELIT Gorakhpur Centre.
Let A=0x56
A << 2 ( Left Shift )
0 1 0 1 0 1 1 0 << 2  0 1 0 1 0 1 1 0 0 0 ( 0x158 )
A >> 2 ( Right Shift )
0 1 0 1 0 1 1 0 >> 1  0 1 0 1 0 1 1 ( 0x2B)
NOTE:
 For multiply given number by two, left shifted by one time, i.e., a<<1
 For divide given number by two, right shifted by one time, i.e., a>>1
56© NIELIT Gorakhpur Centre.
Example:
void main()
{
int x,y;
clrscr();
printf(“Enter value of x:”);
scanf(“%d”,&x);
y=x<<3;
printf(“Left shifted data=%d”,y);
printf(“Right shifted data=%d”,x>>3);
}
Output: Enter value of x:16
Left shifted data=128
Right shifted data=2
57© NIELIT Gorakhpur Centre.
 Printf() Function :
Printf() function is use to display something on the console or to display the value of
some variable on the console.
The general syntax for printf() function is as follows
printf(<”format specifier”>,<list of variables>);
 Scanf() Function :
Scanf() function is use to read data from keyboard and to store that data in the variables.
The general syntax for scanf() function is as follows.
Scanf(“format specifier”,&variable);
58© NIELIT Gorakhpur Centre.
#include <stdio.h>
#include <conio.h>
void main()
{
printf(“Welcome to NIELIT");
getch();
}
Description of the above C Program:
 #include <stdio.h> includes the standard input output library functions. The printf()
function is defined in stdio.h .
 #include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.
 void main() The main() function is the entry point of every program in c language.
The void keyword specifies that it returns no value.
 printf() The printf() function is used to print data on the console.
 getch() The getch() function asks for a single character. Until you press any key, it
blocks the screen.
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
59
© NIELIT Gorakhpur Centre.
• If Statement
• If-else Statement
• Nested If-else Statement
• Switch Case
60© NIELIT Gorakhpur Centre.
Decision Making / Conditional Statements:
C program executes program sequentially. Sometimes, a program requires checking of
certain conditions in program execution.
 Followings are the different conditional statements used in C.
 If Statement
 If-else Statement
 Nested If-else Statement
 Switch Case
61© NIELIT Gorakhpur Centre.
 If Statement:
This is a conditional statement used in C to check condition or to control the flow of
execution of statements.
Syntax: if (condition)
{
statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and executes the block of statements associated with it. If it returns
false, then program skips the braces.
62© NIELIT Gorakhpur Centre.
 Example of If Statement:
#include<stdio.h>
main( )
{
int qty, dis = 0 ;
float rate, tot ;
printf ( "Enter quantity and rate " ) ;
scanf ( "%d %f", &qty, &rate) ;
if ( qty > 1000 )
dis = 10 ;
tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ;
printf ( "Total expenses = Rs. %f", tot ) ;
}
63© NIELIT Gorakhpur Centre.
 If-Else Statement:
This is also one of the most useful conditional statement used in C to check conditions.
Syntax:
if(condition)
{
true statements;
}
else
{
false statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and executes the block of statements associated with it. If it returns
false, then it executes the else part of a program.
64© NIELIT Gorakhpur Centre.
Example:
main( )
{
float bs, gs, da, hra ;
printf ( "Enter basic salary " ) ;
scanf ( "%f", &bs ) ;
if ( bs < 1500 )
{
hra = bs * 10 / 100 ;
da = bs * 90 / 100 ;
}
else
{
hra = 500 ;
da = bs * 98 / 100 ;
}
gs = bs + hra + da ;
printf ( "gross salary = Rs. %f", gs ) ;
}
65© NIELIT Gorakhpur Centre.
 Nested If-Else Statement:
It is a conditional statement which is used when we want to check more than 1 conditions at
a time in a same program. The conditions are executed from top to bottom checking each
condition whether it meets the conditional criteria or not.
Syntax: if(condition)
{
if(condition)
{
statements;
}
else
{
statements;
} }
else
{
statements;
}
In this syntax, the condition is checked first. If it is true,
then the program control flow goes inside the braces
and again checks the next condition. If it is true then it
executes the block of statements associated with it else
executes else part.
66© NIELIT Gorakhpur Centre.
Example:
#include<stdio.h>
main( )
{
int i ;
printf ( "Enter either 1 or 2 " ) ;
scanf ( "%d", &i ) ;
if ( i == 1 )
printf ( "You are Welcome !" ) ;
else
{
if ( i == 2 )
printf ( “I m great" ) ;
else
printf ( “I m the best !" ) ;
}
}
67© NIELIT Gorakhpur Centre.
Switch case Statement :
This is a multiple or multi-way branching decision making statement. When we use nested
if-else statement to check more than 1 conditions then the complexity of a program
increases in case of a lot of conditions. So to overcome this problem, C provides 'switch
case‘. Switch case checks the value of a expression against a case values, if condition
matches the case values then the control is transferred to that point.
68© NIELIT Gorakhpur Centre.
Example :
In this syntax, switch, case, break are keywords.
expr1, expr2 are known as 'case labels.'
Break statement causes an exit from switch statement.
Default case is optional case. When neither any match
found, it executes
Syntax: switch (expression)
{
case expr1:
statements;
break;
case expr2:
statements;
break;
.
.
case expr N:
statements;
break;
default:
statements;
break;
}
Note: The break statement is needed so that once a case has
been executed, it will skip all the other cases and go outside the
switch statement.
If the break statement is omitted, the execution will be carried
out to the next alternatives until the next break statement is
found.
69© NIELIT Gorakhpur Centre.
#include<stdio.h>
#include<conio.h>
main()
{
int x,i;
clrscr();
printf("enter any digit no.");
scanf("%d",&x);
for(i=0;x!=0;x/=10)
i++;
switch(i)
{
case 1:
printf("One Digit No.");
break;
case 2:
printf("Two Digit No.");
break;
case 3:
printf("Three Digit No.");
break;
case 4:
printf("Four Digit No.");
break;
case 5:
printf("Five Digit No.");
break;
default:
printf("Wrong Input");
}
getch();
}
Example of Switch Case
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
70
© NIELIT Gorakhpur Centre.
• While Loop
• For Loop
• Do while Loop
• Break and Continue Statement
• Goto Statement
71© NIELIT Gorakhpur Centre.
'A Loop' is a part of code of a program which is executed repeatedly.
A Loop is used using condition. The repetition is done until condition becomes condition
true.
A loop declaration and execution can be done in following ways.
 Check condition to start a loop
 Initialize loop with declaring a variable.
 Executing statements inside loop.
 Increment or decrement of value of a variable.
 Types of looping statements :
Basically, the types of looping statements depends on the condition checking mode.
Condition checking can be made in two ways as :
Before loop and after loop.
So, there are 2(two) types of looping statements.
 Entry Controlled Loop
 Exit Controlled Loop
72© NIELIT Gorakhpur Centre.
 Entry controlled loop :
In such type of loop, the test condition is checked first before the loop is executed.
Some common examples of this looping statements are :
 while loop
 for loop
 Exit controlled loop :
In such type of loop, the loop is executed first. Then condition is checked after block of
statements are executed.
The loop executed atleast one time compulsorily. Some common example of this looping
statement is :
 do-while loop
73© NIELIT Gorakhpur Centre.
 While loop :
This is an entry controlled looping statement. It is used to repeat a block of statements until
condition becomes true.
Syntax:
while(condition)
{
statements;
increment/decrement;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the loop and executes the block of statements associated with it. At the end of
loop increment or decrement is done to change in variable value. This process continues
until test condition satisfies.
74© NIELIT Gorakhpur Centre.
 Example of While loop :
#include<stdio.h>
#include<conio.h>
main()
{
int i=1;
clrscr();
while(i<=10)
{
printf("n%d",i);
i++;
}
getch();
}
False
True
75© NIELIT Gorakhpur Centre.
 For loop :
This is an entry controlled looping statement. In this loop structure, more than one variable
can be initialized. One of the most important feature of this loop is that the three actions
can be taken at a time like variable initialization, condition checking and
increment/decrement.
Syntax:
for(initialization; test-condition; incre/decre)
{
statements;
}
Features :
 More concise
 Easy to use
 Highly flexible
 More than one variable can be initialized.
 More than one increments can be applied.
 More than two conditions can be used.
76© NIELIT Gorakhpur Centre.
 Example of For loop :
#include<stdio.h>
#include<conio.h>
main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
printf("n%d",i);
getch();
}
False
True
77© NIELIT Gorakhpur Centre.
 Do-While loop:
This is an exit controlled looping statement. Sometimes, there is need to execute a block of
statements first then to check condition. At that time such type of a loop is used. In this,
block of statements are executed first and then condition is checked.
Syntax:
do
{
statements;
(increment/decrement);
}
while(condition);
In above syntax, the first the block of statements are executed. At the end of loop, while
statement is executed. If the resultant condition is true then program control goes to
evaluate the body of a loop once again. This process continues till condition becomes true.
When it becomes false, then the loop terminates.
78© NIELIT Gorakhpur Centre.
 Example of do while loop :
#include <stdio.h>
main()
{
int digit = 0;
do
{
printf(“%d”, digit++);
}while(digit<=9);
}False
True
79© NIELIT Gorakhpur Centre.
Nested loop
A loop inside another loop is known as nested loop. We can write any loop inside any
loop in c i.e. we can write for loop inside the loop or while loop or do while loop etc.
Syntax:
do
{
statements;
statements;
|
|
do
{
statements;
}while(expression);
}
} while(expression)
for(initialization; test; increment)
{
statements;
for(initialization; test; increment)
{
statements;
|
|
|
for(initialization; test; increment)
{
statements;
}
}}
while(expression)
{
statements;
|
|
|
while(expression)
{
statements;
}
}
80© NIELIT Gorakhpur Centre.
Example : Print the table from 1 to 10.
#include<stdio.h>
#include<conio.h>
main()
{
int i,j;
clrscr();
for(i=1;i<=10;i++)
{
for(j=1;j<=10;j++)
printf("%2dt",i*j);
printf("n");
}
getch();
}
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 10
0
Output
81© NIELIT Gorakhpur Centre.
Example : Print the following pattern. (with the help of while loop)
#include<stdio.h>
#include<conio.h>
main()
{
int r=1,c;
while (r<=5)
{
c=1;
while(c<=r)
{
printf(“*”);
c++;
}
r++;
printf("n");
}
getch();
}
*
**
***
****
*****
Output
82© NIELIT Gorakhpur Centre.
Example : Print the following pattern. (with the help of for loop)
#include<stdio.h>
#include<conio.h>
main()
{
int r,c;
clrscr();
for(r=1;r<=5;r++)
{
for(c=5;c>=r;c--)
printf(“*”);
printf("n");
}
getch();
}
*****
****
***
**
*
Output
83© NIELIT Gorakhpur Centre.
Example : Print the Pascal Triangle. (with the help of for loop)
#include<stdio.h>
void main()
{
int x,y,r,c,s,l=1;
for(r=1;r<=5;r++)
{
for(s=5;s>r;s--)
printf("%c",32);
x=l;
for(c=1;c<=r;c++)
{
y=(x%10);
printf(" %d",y);
x/=10;
}
printf("n");
l=l*11;
}}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Output
84© NIELIT Gorakhpur Centre.
Example : Print the following pattern. (with the help of for loop)
#include<stdio.h>
main()
{
int i,j,k=71,l=-1,s;
for(i=1;i<=7;i++)
{
for(j=65;j<=k;j++)
printf("%c",j);
if(i==1)
j--;
else
for(s=l;s>=1;s--)
printf(" ");
for(j--;j>=65;j--)
printf("%c",j);
printf("n");
l=l+2;
k--;
}
}
Output
A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
A B C D D C B A
A B C C B A
A B B A
A A
85© NIELIT Gorakhpur Centre.
 Break Statement :
Sometimes, it is necessary to exit immediately from a loop as soon as the condition is satisfied.
When break statement is used inside a loop, then it can cause to terminate from a loop. The
statements after break statement are skipped.
 Continue Statement :
Sometimes, it is required to skip a part of a body of loop under specific conditions. So, C supports
'continue' statement to overcome this problem. The working structure of 'continue' is similar as that
of that break statement but difference is that it cannot terminate the loop. Continue statement
simply skips statements and continues next iteration.
Syntax: break;
while(condition)
{
- - - - -
- - - - - -
break;
- - -
- - -
}
Syntax: continue;
while(condition)
{
- - - - -
- - - - - -
Continue;
- - - -
- - - -
}
86© NIELIT Gorakhpur Centre.
Example of Break Statement Example of Continue Statement
#include <stdio.h>
main ()
{
int a = 10;
while( a < 20 )
{
printf("value of a: %dn", a);
a++;
if( a > 15)
break;
}
}
#include <stdio.h>
main ()
{
int a = 10;
do
{
if( a == 15)
{
a = a + 1;
continue;
}
printf("value of a: %dn", a);
a++;
} while( a < 20 );
}
87© NIELIT Gorakhpur Centre.
It is a well known as ‘jumping statement’. It is primarily used to transfer the
control of execution to any place in a program. It is useful to provide branching within a loop.
When the loops are deeply nested at that if an error occurs then it is difficult to get
exited from such loops. Simple break statement cannot work here properly. In this situations,
goto statement is used.
Syntax : goto [expr];
while(condition)
{
- - - - -
- - - - - -
goto label;
- - -
- - -
label:
}
while(condition)
{
- - - - -
label:
- - - -
- - - -
goto label;
- - -
}
88© NIELIT Gorakhpur Centre.
Example:
#include <stdio.h>
#include<conio.h>
main()
{
int x,i=0;
clrscr();
printf("enter any digit no.");
scanf("%d",&x);
abc:
if(x!=0)
{
i++;
x/=10;
goto abc;
}
else
printf("number=%d Digit No.",i);
getch();
}
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
89
© NIELIT Gorakhpur Centre.
• What is Function
• Built in Function
• User Defined Function
• Types of Function
• Calling of Function
• Recursion
90© NIELIT Gorakhpur Centre.
A function is a group of statements that together perform a task. Every C program has at
least one function, which is main(), and all the most trivial programs can define additional
functions. You can divide up your code into separate functions.
The function is a self contained block of statements which performs a coherent task of a
same kind.
 Types of functions :
 Build in Functions
 User Defined Functions
91© NIELIT Gorakhpur Centre.
 Built in Functions :
These functions are also called as ‘Library Functions'. These functions are provided by
system. These functions are stored in library files.
Example:
scanf( )
printf( )
strcpy( )
strlwr( )
strcmp( )
strlen( )
strcat( )
92© NIELIT Gorakhpur Centre.
 User Defined Functions :
The functions which are created by user for program are known as 'User defined
functions'.
Advantages :
 It is easy to use, It reduces the size of a program.
 Debugging is more suitable for programs.
 It is easy to understand the actual logic of a program.
 Highly suited in case of large programs.
 By using functions in a program, it is possible to construct modular and
structured programs.
93© NIELIT Gorakhpur Centre.
Syntax:
// Function definition
<return_type> <function_name>(argu_list);
void main()
{
// Function Call
<function_name>(<arguments>);
}
// Function declaration
<return_type><function_name>(<argu_list>)
{
<function_body>;
}
94© NIELIT Gorakhpur Centre.
 FUNCTION TYPES:
Function with No arguments and No return value
Function with arguments but No return value
Function with No arguments but Returns a value
Function with arguments and return values
Function with multiple return values
95© NIELIT Gorakhpur Centre.
An argument is an entity used to pass the data from calling function to the called function.
There are two types of arguments:
1. Formal
2. Actual
Formal Arguments are the arguments available in the function definition.
They are preceded by their own data types.
Actual Arguments are available in the function call.
96© NIELIT Gorakhpur Centre.
There are two ways to call a function (used when invoking functions)
 Call by Value:
 Copy of argument pass to a function
 Changes in function do not effect original
 Call by reference:
 Passes original arguments to a function
 Changes in function effect original
97© NIELIT Gorakhpur Centre.
98© NIELIT Gorakhpur Centre.
#include <stdio.h>
#include<conio.h>
int prime (int);
main()
{
int x,y;
clrscr();
printf("enter any number");
scanf("%d",&x);
y=prime(x);
if(y==1)
printf("Prime No.");
else
printf("Not Prime Number");
getch();
}
int prime (int z)
{
int i=2;
if(z==1 | | z==2)
return(1);
else
while(i<z)
{
if(z%i==0)
return(0);
else
i++;
}
if(i==z)
return(1);
}
Example: To check any number is prime or not.
99© NIELIT Gorakhpur Centre.
Example: To find the factorial value of any no.
#include<stdio.h>
#include<conio.h>
int fact (int);
main()
{
int x,n;
clrscr();
printf("enter any number");
scanf("%d",&x);
n=fact(x);
printf(n);
getch();
}
int fact (int y)
{
int i;
for(i=1;y>=1;y--)
i=i*y;
return(i);
}
100© NIELIT Gorakhpur Centre.
 A function cannot be defined within another function.
 All function definitions must be disjoint.
 Nested function calls are allowed.
 A calls B, B calls C, C calls D, etc.
 The function called last will be the first to return.
 A function can also call itself, either directly or in a cycle.
 A calls B, B calls C, C calls back A.
 Called recursive call or recursion.
101© NIELIT Gorakhpur Centre.
Recursion is a programming technique that allows the programmer to express operations in
terms of themselves. In C, this takes the form of a function that calls itself. A useful way to
think of recursive functions is to imagine them as a process being performed where one of
the instructions is to "repeat the process".
102© NIELIT Gorakhpur Centre.
 Either directly.
 X calls X.
 Cyclically in a chain.
 X calls Y, and Y calls X.
Used for repetitive computations in which each action is stated in terms of a previous result.
For a problem to be written in recursive form, two conditions are to be satisfied:
 It should be possible to express the problem in recursive form.
 The problem statement must include a stopping condition
103© NIELIT Gorakhpur Centre.
 Mechanism of Execution:
 When a recursive program is executed, the recursive function calls are not executed
immediately.
 They are kept aside (on a stack) until the stopping condition is encountered.
 The function calls are then executed in reverse order.
void main( )
{
- - - - -
- - - - -
main( );
- - - - -
- - - - -
- - - - -
}
104© NIELIT Gorakhpur Centre.
/* PRIME NUMBER USING RECURSION */
#include <stdio.h>
#include<conio.h>
int prime (int);
main()
{
int no,i;
printf("enter any number");
scanf("%d",&no);
i=prime(no);
if(i==1)
printf("Prime Number");
else
printf("Not Prime Number");
getch();
}
prime (int n)
{
static int x=2;
if(x==n)
return(1);
if(n%x==0)
return(0);
else
{
x++;
prime(n);
}
}
105© NIELIT Gorakhpur Centre.
/* Convert any decimal number to its binary equivalent using
Recursion */
#include <stdio.h>
#include<conio.h>
void change (int, int);
main()
{
int n,base;
clrscr();
printf("enter the number and base");
scanf("%d%d",&n,&base);
change(n,base);
getch();
}
void change(int n1, int b)
{
int x;
if(n1==0)
return;
x=n1%b;
change(n1/b,b);
printf("%d",x);
}
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
106
© NIELIT Gorakhpur Centre.
107© NIELIT Gorakhpur Centre.
Pointer is a variable which holds the memory address of another variable. Pointers are
represented by '*'. It is a derive data type in C. Pointer returns the value of stored address.
Syntax: <data_type> *pointer_name;
int *j;
int i = 5;
In above syntax,
* = variable pointer_name is a pointer variable.
pointer_name requires memory location
pointer_name points to a variable of type data type.
108© NIELIT Gorakhpur Centre.
There are two C operators that are necessary when using pointer variables.
the address operator returns the address of a variable
Example:
int x;
int *ptr = &x;
The declaration of ptr initializes the variable ptr = &x;
Suppose the address of the variable x is 65524.
ptr holds the address of x.
We say ptr “points” to x.
We will apply the & operator only to variables.
e.g. &77 or &(x+1) are not valid.
&
65524
x
ptr
109© NIELIT Gorakhpur Centre.
*
5
65524
x
ptr
Example:
int x;
int *ptr;
ptr=&x ;
To assign the value “5” to the variable x in C:
x = 5;
We can use the “ * ” operator to indirectly reference x.
We can assign “5” to x by:
*ptr=5;
Here we use the fact that “ptr” points to integer values.
means "a pointer to" and is called an indirection operator or dereferencing operator,
since a pointer "indirectly" references a value in a storage location.
110© NIELIT Gorakhpur Centre.
/*Swap the values of two variable using pointer. */
#include <stdio.h>
void swap(int * , int *);
void main(void)
{
int x = 1;
int y = 2;
swap(&x,&y); /* pass the addresses of x and y */
printf(“x = %d , y = %d n”,x,y); /* prints x = 2 , y = 1 */
}
void swap(int *ptrX , int *ptrY) /* pointer variables */
{
int temp = *ptrX;
*ptrX = *ptrY ;
*ptrY = temp;
return;
}
111© NIELIT Gorakhpur Centre.
 Features of Pointer :
Pointer variable should have prefix '*‘.
Combination of data types is not allowed.
Pointers are more effective and useful in handling arrays.
It can also be used to return multiple values from a function using function arguments.
It supports dynamic memory management.
It reduces complexity and length of a program.
It helps to improve execution speed that results in reducing program execution time.
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
112
© NIELIT Gorakhpur Centre.
• Automatic storage class
• Register storage class
• Static storage class
• External storage class
113© NIELIT Gorakhpur Centre.
'Storage' refers to the scope of a variable and memory allocated by compiler to store that
variable. Scope of a variable is the boundary within which a variable can be used. Storage
class defines the the scope and lifetime of a variable.
 Functions of storage class:
 To determine the location of a variable where it is stored ?
 Set initial value of a variable or if not specified then setting it to default value.
 Defining scope of a variable.
 To determine the life of a variable.
114© NIELIT Gorakhpur Centre.
 Types of Storage Classes :
Storage classes are categorized in 4 (four) types as,
 Automatic storage class
 Register storage class
 Static storage class
 External storage class
115© NIELIT Gorakhpur Centre.
 Automatic Storage Class:
Automatic variables are declared inside a function in which they are to be utilized. They
are created when the function is called and destroyed automatically when the function is
exited, hence the name automatic. Automatic variables are therefore private to the
function in which they are declared. Because of this property, automatic variables are
also referred to as local or internal variable.
Keyword : auto
Storage Location : Main memory
Initial Value : Garbage Value
Life : Control remains in a block where it is defined.
Scope : Local to the block in which variable is declared.
Syntax : auto [data_type] [variable_name];
Example : auto int a;
116© NIELIT Gorakhpur Centre.
 Register Storage Class :
We can tell the compiler that a variable should be kept in one of the machine’s register
instead of keeping in the memory where normal variables are stored. Since a register
access is much faster than a memory access. Keeping frequently accessed variables in
the register will lead to faster execution of program.
Keyword : register
Storage Location : CPU Register
Initial Value : Garbage
Life : Local to the block in which variable is declared.
Scope : Local to the block.
Syntax : register [data_type] [variable_name];
Example : register int a;
117© NIELIT Gorakhpur Centre.
 Static Storage Class :
As the name suggest, the value of static exist until the end of the program. A static variable
may be either an internal type or an external type depending on the piece of declaration.
Internal static variables are those which are declared inside a function. A static variable is
initialized only once, when the program is compiled. It is never initialized again. An
external static variable is declared outside that program. The difference between a static
external variable and simple external variable is that the static external variable is available
only within the file where it is defined while the simple external variables can be accessed
by other files.
Keyword : static
Storage Location : Main memory
Initial Value : Zero and can be initialize once only.
Life : depends on function calls and the whole
application or program.
Scope : Local to the block.
Syntax : static [data_type] [variable_name];
Example : static a;
118© NIELIT Gorakhpur Centre.
 External Storage Class :
Variables that are both alive and active throughout the entire program are known as
external variables. They are also known as global variables. Unlike function in the
program external variables are declared outside a function.
Keyword : extern
Storage Location : Main memory
Initial Value : Zero
Life : Until the program ends.
Scope : Global to the program.
Syntax : extern [data_type] [variable_name];
Example : extern int a;
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
119
© NIELIT Gorakhpur Centre.
120© NIELIT Gorakhpur Centre.
Preprocessor processes source program before it is passed to compiler.
Produce a source code file with the preprocessing commands properly sorted out.
Preprocessor commands are known as directives.
Preprocessor provides certain features.
These features are also known as preprocessor directives.
Preprocessor directives start with #sign.
Preprocessor directives can be placed any where in the source program.
Note: Place it at start of the program.
Each preprocessor directive must be on it’s own line.
121© NIELIT Gorakhpur Centre.
 Preprocessor Directives
 Macro Expansion
 File Inclusion
 Conditional compilation
 Miscellaneous directives
122© NIELIT Gorakhpur Centre.
 Macro Expansion
 #define directive is known as macro expansion.
Definition:
#define PI 3.1415
General Form:
#define macro_template macro_expansion
#define macro_name char_sequence
 Preprocessor search for macro definition.
 After finding #define directive it search entire program for macro_template.
 Replace each macro_template with macro_expansion.
 Best Practice: Use capital letters for macro template.
 Do not use semicolon ‘;’
123© NIELIT Gorakhpur Centre.
 Benefits of Macro
 To write efficient programs.
 To increase readability of programs.
 Variable Vs Macro_template
 Compiler can generate faster and compact code for constant than it can for variables.
 When you are dealing with a constant, why use variable.
 A variable may change in the program.
124© NIELIT Gorakhpur Centre.
Replace operator:
#define AND &&
#define OR | |
Replace condition:
#define EXCELLENT (a>=75)
Replace statement:
#define ALERT printf(“Security Alert”);
 Defined macro name can be used as a part of definition of other macro name.
#define MIN 1
#define MAX 9
#define MIDDLE (MAX-MIN)/2
 No text substitution occur if the identifier is within a quoted string.
125© NIELIT Gorakhpur Centre.
 Macro With Arguments
Macros can have arguments, same as functions
#define ISEXCELLENT(x) (x >= 75)
#define ISLOWER(x) (x>=97 && x<=122)
Macros expansions should be enclosed within parenthesis.
#define ISLOWER(x) (x>=97 && x<=122)
if(!ISLOWER(‘a’));
Use ‘’ to split macro in multiple line.
#define HLINE for(i=0; i < 40; i++)
printf(“_”);
126© NIELIT Gorakhpur Centre.
Macro Function
Macro is Preprocessed Function is Compiled
No Type Checking Type Checking is Done
Code Length Increases Code Length remains Same
Use of macro can lead to side effect No side Effect
Just the replacement of the code.
Passing arguments, doing calculation,
returning results. (More serious work).
Macros make the program run faster. Function calls and return make the program
slow.
Before Compilation macro name is
replaced by macro value
During function call , Transfer of Control
takes place
Useful where small code appears many
time
Useful where large code appears many time
Generally Macros do not extend beyond
one line
Function can be of any number of lines
Macro does not Check Compile Errors Function Checks Compile Errors
127© NIELIT Gorakhpur Centre.
 Causes one file to be included in another.
#include <filename> //OR
#include “filename”
 <filename>: search the directory on current directory only.
 “filename”: search the directory on current directory and specified directories as
specified in the include search path.
 Divide a program in multiple files.
o Each file contains related functions.
 Some functions or macros are required in each program.
o Put them in a file (Library).
o Include them in program that need them.
 Nested includes: Included file may have more included files in it.
128© NIELIT Gorakhpur Centre.
 Write single program to run on different environments.
 #ifdef – if defined
 #endif – end if
 #else – else
 #ifndef – in not defined
 #if – if
 #elif – else if
129© NIELIT Gorakhpur Centre.
#ifdef & #endif
General form:
#ifdef macroname
statement sequence
#endif
 if macroname has been defined using #define the code between #ifdef & #endif will
execute.
#else
 Use #else with #ifdef same as else with if.
General-form:
#ifdef macroname
statement sequence
#else
statement sequence
#endif
130© NIELIT Gorakhpur Centre.
#ifndef
 #ifndef is just opposite to #ifdef
#ifndef __file_h
#define __file_h
 #if directive test whether an expression evaluates to nonzero value or not.
 #elif used same as else if.
131© NIELIT Gorakhpur Centre.
Where conditional compilation?
 Instead of comments.
o Nested comments not allowed in C.
 Run the same code on different environment.
 To avoid multiple declaration error.
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
132
© NIELIT Gorakhpur Centre.
• Single/One dimensional
• Multidimensional
• Advantages and Disadvantages
• String and Character Array
133© NIELIT Gorakhpur Centre.
Array is a collection or group of similar data type elements stored in contiguous memory
location. The individual data items can be characters, integers, floating points numbers and
so on . Here contiguous memory allocation means array occupies contiguous bytes as
needed in the memory.
 Types of an Array :
 Single / One Dimensional Array
 Multidimensional Array
134© NIELIT Gorakhpur Centre.
 Single / One Dimensional Array :
The array which is used to represent and store data in a linear form is called as 'single or
one dimensional array’. Has a unique identifier for each element, called as a subscript or
an index.
Syntax: <data-type> <array_name> [size];
Example: int a[5];
Memory allocation for Single / One dimensional array
A[0] A[1] A[2] A[n]
5 7 2 12
1000 1002 1004 n
A[index no.]
element
Memory address
135© NIELIT Gorakhpur Centre.
The array size could also be specified using a symbolic constant:
#define ARRAY_SIZE 25
int a[ARRAY_SIZE];
We can initialize array elements in declaration statements; e.g.,
int x[5] = {1, 2, 3, 4, 5};
int x[ ] = {2, 4, 6, 8}; /*This array has 4 elements*/
We cannot specify more initial values than there are array elements, but we can specify
fewer initial values, and the remaining elements will be initialized to 0. e.g.,
int y[10] = { 2 };
double x[250 ] = { 0 };
136© NIELIT Gorakhpur Centre.
Given that the array x is declared as:
int x[250];
To initialize a large array to a nonzero value - say 5, we can use a loop. e.g.,
for (k=0; k<=249; k++)
x[k] = 5;
k is a subscript
Note: when referencing a particular element of an array use square brackets, not parenthesis
or curly braces.
A subscript value for an array element can be specified as any integer expression.
137© NIELIT Gorakhpur Centre.
There are number of operations that can be performed on arrays. These operations
include :
 Transversal
 Insertion
 Search
 Deletion
 Merging
 Sorting
 Selection Sort
 Bubble Sort
 Insertion Sort
138© NIELIT Gorakhpur Centre.
 Example of traversal an array.
#include<stdio.h>
#include<conio.h>
main()
{
int x[10], i;
for(i=0;i<10;i++)
{
printf(“Enter the elements in array: t”);
scanf(“%d”, &x[i]);
}
printf(“The Traverse of array is:n”);
for(i=0;i<10;i++)
printf(“%dn”, x[i]);
getch();
}
139© NIELIT Gorakhpur Centre.
 Example of insert any new element of another existing of an array.
#include<stdio.h>
#include<conio.h>
main()
{
int a[10],s,n,i,j,n1;
clrscr();
printf("enter the size of array");
scanf("%d",&s);
for(i=0;i<s;i++)
{
printf("enter the element");
scanf("%d",&a[i]);
}
printf("enter value which afterbe inserted");
scanf("%d",&n);
for(i=0;i<s;i++)
{
if(a[i]==n)
break;
}
if(i==s)
printf("Element not found");
for(j=s-1;j>i;j--)
a[j+1]=a[j];
printf("enter the no. to be inserted");
scanf("%d",&n1);
a[i+1]=n1;
for(i=0;i<=s;i++)
printf("n%d",a[i]);
getch();
}
140© NIELIT Gorakhpur Centre.
 Example of search any element in an array.
#include<stdio.h>
main()
{
int x[5], ele, i;
printf("nEnter the values :");
for (i = 0; i < 5; i++)
scanf("%d", &x[i]);
printf("nEnter the elements to be searched :");
scanf("%d", &ele);
for (i=0;i < num && ele != x[i];i++)
i++;
if (i < 5)
printf("Number found at the location = %d", i + 1);
else
printf("Number not found");
}
141© NIELIT Gorakhpur Centre.
 Example of deletion in an array.
#include <stdio.h>
main()
{
int x[5], p, c, n;
printf("Enter the elementsn”);
for ( c=0 ; c<5 ; c++ )
scanf("%d", &x[c]);
printf("Enter the location where you wish to delete elementn");
scanf("%d", &position);
if ( p>=5 )
printf("Deletion not possible.n");
else
{
for (c=p -1 ; c < 5-1 ; c++ )
x[c] = x[c+1];
printf("Resultant array isn");
for( c=0 ; c <5-1 ; c++ )
printf("%dn", x[c]);
}}
142© NIELIT Gorakhpur Centre.
#include<stdio.h>
main()
{
int x[5],y[5],z[10],i,j,k;
printf("nEnter no of elements in 1st array :");
for(i=0; i<5; i++)
scanf("%d", &x[i]);
printf("nEnter no of elements in 2nd array :");
for(i=0; i<n2;i++)
scanf("%d", &arr2[i]);
i=0;
j=0;
k=0;
while (i<5 && j<5)
{ if(x[i]<=y[j])
{ z[k]=x[i];
i++;
k++; }
 Example of merging in an array. else
{ z[k]=y[j];
k++;
j++; } }
while (i<n1)
{
z[k]=x[i];
i++;
k++; }
while (j < n2)
{
z[k]=y[j];
k++;
j++;
}
printf("nMerged array is :");
for (i=0; i<10;i++)
printf("%d ",z[i]);
}
143© NIELIT Gorakhpur Centre.
 Example sorting in an array. (Selection Sort)
#include<stdio.h>
#include<conio.h>
main()
{ int x[5],i,j,t;
clrscr();
printf("nenter the array element");
for(i=0;i<5;i++)
scanf("%d",&x[i]);
for(i=0;i<4;i++)
for(j=i+1;j<5;j++)
if(x[i]>x[j])
{ t=x[i];
x[i]=x[j];
x[j]=t; }
for(i=0;i<5;i++)
printf("n%d",x[i]);
getch();
}
0 1 2 3 4
5 7 2 12 6
i [index no.]
x [element]
Output
0 1 2 3 4
2 5 6 7 12
i [index no.]
x [element]
Input
144© NIELIT Gorakhpur Centre.
 Example sorting in an array. (Bubble Sort)
#include<stdio.h>
#include<conio.h>
void main()
{int i,j,temp,a[5];
clrscr();
printf("Enter the array of a");
for(j=0;j<5;j++)
scanf("%d",&a[j]);
for(i=0;i<4;i++)
for(j=0;j<5-i;j++)
if (a[j]>a[j+1])
{temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;}
for(j=0;j<5;j++)
printf("n%d",a[j]);
getch();
}
0 1 2 3 4
4 3 1 5 2
i [index no.]
a [element]
Output
0 1 2 3 4
1 2 3 4 5
i [index no.]
a [element]
Input
145© NIELIT Gorakhpur Centre.
 Example sorting in an array. (Insertion Sort)
#include<stdio.h>
#include<conio.h>
main()
{ int arr[5],i,j,k,temp;
clrscr();
for(i=0;i<5;i++)
{ printf("nenter the array element");
scanf("%d",&arr[i]); }
for(i=1;i<5;i++)
for(j=0;j<=i-1;j++)
if(arr[i]<arr[j])
{ temp=arr[i];
for(k=i-1;k>=j;k--)
arr[k+1]=arr[k];
arr[j]=temp;
break; }
for(i=0;i<=4;i++)
printf("n%d",arr[i]);
getch();}
0 1 2 3 4
4 3 1 5 2
i [index no.]
arr [element]
Output
0 1 2 3 4
1 2 3 4 5
i [index no.]
arr [element]
Input
146© NIELIT Gorakhpur Centre.
 Multidimensional Array :
The array which is used to represent and store data in a tabular form is called as
‘multidimensional array.' Such type of array specially used to represent data in a matrix
form. The following syntax is used to represent multidimensional array.
Syntax: <data-type> <array_name> [row_size][column_size];
Example: int a[3][3];
j column
i row
a[i][j]
a[0][0] a[0][1] a[0][2]
a[1][0] a[1][1] a[1][2]
a[2][0] a[2][1] a[2][2]
Memory allocation for Multidimensional array
147© NIELIT Gorakhpur Centre.
Notation of Multidimensional Array
B =
51, 52, 53
54, 55, 56
Algebraic notation
Col 1 Col 2 Col 3
Row 1
Row 2
int b[2][3] = {(51, 52, 53),(54, 55, 56)};
Array type Array name
Two rows
Three columns
First row second row
C notation
148© NIELIT Gorakhpur Centre.
 Example to add two matrix entered by the user and print it.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;
clrscr();
printf(“enter the elements in both the array:”);
for(i=0 ; i<3 ; i++)
for(j=0 ; j<3 ; j++)
scanf(“%d”,&a[i][j]);
for(i=0 ; i<3 ; i++)
for(j=0 ; j<3 ; j++)
scanf(“%d”,&b[i][j]);
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++)
{
c[i][j]=a[i][j]+b[i][j];
printf(“%d”,c[i][j]);
}
printf(“n”);
}
getch();
}
149© NIELIT Gorakhpur Centre.
 Example to transpose any matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3], i,j;
clrscr();
printf(“enter the elements in the array”);
for(i=0 ; i<3 ; i++)
for(j=0 ; j<3 ; j++)
scanf(“%d”,&a[i][j]);
for(j=0 ; i<3 ; i++)
{
for(i=0 ; j<3 ; j++)
printf(“%2d”,a[j][i]);
printf(“n”);
}
getch();
}
1 2 3
4 5 6
7 8 9
Input
1 4 7
2 5 8
3 6 9
Output
150© NIELIT Gorakhpur Centre.
 Example to print diagonal of any matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int x[3][3], i,j;
clrscr();
printf(“enter the elements in the array”);
for(i=0 ; i<3 ; i++)
for(j=0 ; j<3 ; j++)
scanf(“%d”,&x[i][j]);
for(j=0 ; i<3 ; i++)
for(i=0 ; j<3 ; j++)
if(i==j)
printf(“%d”,x[i][j]);
getch();
}
1 2 3
4 5 6
7 8 9
Input
1 5 9
Output
151© NIELIT Gorakhpur Centre.
 Example to multiplication of two matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],k,i,j,s,c[3][3];
clrscr();
printf("enter element in array a");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("enter element in array b");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
s=0;
for(k=0;k<3;k++)
{
s=s+a[i][k]*b[k][j];
c[i][j]=s;
}
}
printf("nMultiplication of Array A * B");
for(i=0;i<3;i++)
{
printf("n");
for(j=0;j<3;j++)
printf("t%d",c[i][j]);
}
getch();
}
152© NIELIT Gorakhpur Centre.
 Limitations of Multidimensional array:
 We cannot delete any element from an array.
 If we don't know that how many elements have to be stored in a memory in
advance, then there will be memory wastage if large array size is specified.
153© NIELIT Gorakhpur Centre.
 Advantages:
 It is used to represent multiple data items of same type by using only single name.
 It can be used to implement other data structures like linked lists, stacks, queues,
trees, graphs etc.
 Multidimensional arrays are used to represent matrices.
 Disadvantages:
 We must know in advance that how many elements are to be stored in array.
 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.
 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.
 The elements of array are stored in consecutive memory locations. So insertions and
deletions are very difficult and time consuming.
154© NIELIT Gorakhpur Centre.
String is a sequence of characters that is treated as a single data item and terminated by
null character '0'. Remember that C language does not support strings as a data type. A
string is actually one-dimensional array of characters in C language. These are often used
to create meaningful and readable programs.
 Strings are used in string handling operations such as,
 Counting the length of a string.
 Comparing two strings.
 Copying one string to another.
 Converting lower case string to upper case.
 Converting upper case string to lower case.
 Joining two strings.
 Reversing string.
Declaration
Syntax : char string_nm[size];
Example : char name [15];
155© NIELIT Gorakhpur Centre.
Declaring character arrays with a string constant
char astring[5]= “Zip!”;
char atomic[ ]= “hydrogen”;
Declaring a string array with character constants
char astring[ ]= {‘Z’, ’i’, ‘p’, ‘!’, ‘0’};
Important
In C, you must always terminate a character array with the NULL character, ‘0’ . Therefore,
the array size of your character array should be one plus the maximum length of the string
you want to store. Example: In the declaration
char atomic[ ]= “hydrogen”;
“atomic” is an array of nine elements, the last being ‘0’.
156© NIELIT Gorakhpur Centre.
String memory representation
0 1 2 3 4 5 6 7 8
h y d r o g e n 0
Index
Variable
The memory presentation of the string in C is:
char atomic[10]= “hydrogen”;
Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the '0' at the end of the string when it initializes the
array.
157© NIELIT Gorakhpur Centre.
 Read Strings:
To read a string, we can use scanf() function with format specifier %s.
char name[50];
scanf("%s",name);
 Write Strings :
To write a string, we can use printf() function with format specifier %s.
char name[50];
scanf("%s",name);
printf("%s",name);
158© NIELIT Gorakhpur Centre.
C supports a large number of string handling functions. There are numerous functions
defined in "string.h" header file. Few commonly used string handling functions are:
Function Name Description
strlen( ) Returns the length of a string.
strlwr () Returns upper case letter to lower case.
strupr () Returns lower case letter to upper case.
strcat () Concatenates two string.
strcmp () Compares two strings.
strrev () Reverse a string.
strcpy () Copies a string from source to destination.
159© NIELIT Gorakhpur Centre.
The gets and puts functions facilitate the transfer of strings between the computer and the
standard input/output devices. Each of these functions accepts a single argument. The
argument must be a data item that represents a string(e.g. character array). The string may
include white space characters. In the case of gets, the string will enter from the keyboard
and will terminate with a new line character(i.e. the string will end when the user presses
the RETURN key).
The gets and puts functions offer simple alternatives to the use of scanf() and printf() for
reading and displaying strings:
#include<stdio.h>
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;
}
Note: gets() & puts( ) handle string, both these functions are defined in “stdio.h” header file.
160© NIELIT Gorakhpur Centre.
 Example: Find the length of the string.
#include <stdio.h>
int main()
{
char s[1000], i;
printf("Enter a string: ");
gets(s);
for(i=0; s[i]!='0'; ++i);
printf("Length of string: %d",i);
}
161© NIELIT Gorakhpur Centre.
 Example: Find the frequency of character in a string.
#include <stdio.h>
main()
{
char c[50],ch;
int i,count=0;
printf("Enter a string: ");
gets(c);
printf("Enter a character to find frequency: ");
scanf("%c",&ch);
for(i=0;c[i]!='0';++i)
{
if(ch==c[i])
++count;
}
printf("Frequency of %c = %d", ch, count);
}
162© NIELIT Gorakhpur Centre.
 Example: Insert any character in given string at any specified position.
#include<stdio.h>
#include<conio.h>
main()
{
char x[25],c;
int i,j,l;
clrscr();
printf("enter any string");
gets(x);
printf("nenter the position where you want to
insert");
scanf("%d",&j);
fflush(stdin);
printf("nEnter the character");
scanf("%c",&c);
l=strlen(x);
for(i=l;i>=j-1;i--)
x[i+1]=x[i];
x[j-1]=c;
puts(x);
getch();
}
163© NIELIT Gorakhpur Centre.
 Example: Concatenate two string.
#include <stdio.h>
main()
{
char s1[100], s2[100], i, j;
printf("Enter first string: ");
gets(s1);
printf("Enter second string: ");
gets(s2);
for(i=0; s1[i]!='0'; ++i); /* i contains length of string s1. */
for(j=0; s2[j]!='0'; ++j, ++i)
{
s1[i]=s2[j];
}
s1[i]='0';
printf("After concatenation: %s",s1);
}
164© NIELIT Gorakhpur Centre.
Example: Sort Words in Dictionary Order
#include<stdio.h>
#include <string.h>
main()
{ int i,j;
char str[10][50],temp[50];
printf("Enter 10 words:n");
for(i=0;i<10;++i)
gets(str[i]);
for(i=0;i<9;++i)
for(j=i+1;j<10 ;++j)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("In Dictionary order: n");
for(i=0;i<10;++i)
puts(str[i]);
}
165© NIELIT Gorakhpur Centre.
Example: Check any input string is palindrome or not.
else
f=1;
}
if(f==0)
printf("n String is palindrome");
else
printf("n String is not palindrome");
getch();
}
#include<stdio.h>
#include<conio.h>
main()
{
int i,j=0,n,f=0;
char x[100];
clrscr();
printf("nenter any string");
gets(x);
for(i=0;x[i]!='0';i++);
n=i/2;
i--;
while ((j!=n) && (f==0))
{
if(x[j]==x[i])
{
j++;
i--;
}
166© NIELIT Gorakhpur Centre.
Example: User define function to reverse any string.
void xstrrev(char *p)
{
char *t=p,c;
for(;*p!='0';p++);
for(p--;p>t;p--)
{
c=*p;
*p=*t;
*t=c;
t++;
}
}
#include<stdio.h>
#include<conio.h>
void xstrrev(char *);
main()
{
char ch[25];
clrscr();
printf("enter any string");
gets(ch);
xstrrev(&ch);
puts(ch);
getch();
}
167© NIELIT Gorakhpur Centre.
Example: User define function to copy any string.
#include<stdio.h>
#include<conio.h>
void xstrcpy(char *, char*);
main()
{char ch[25],ch1[25];
clrscr();
printf("enter any string");
gets(ch);
xstrcpy(&ch, &ch1);
puts(ch);
puts(ch1);
getch();
}
void xstrcpy(char *p, char *p1)
{ for(;*p!='0';p++)
*p1++=*p;
*p1='0';
}
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
168
© NIELIT Gorakhpur Centre.
• Structure
• Nesting of Structure
• Union
169© NIELIT Gorakhpur Centre.
Structure is user defined data type which is used to store heterogeneous data under unique
name. Keyword 'struct' is used to declare structure. The variables which are declared inside
the structure are called as 'members of structure'.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - - -
- - - - - - - - -
<data-type> element n;
}struct_var;
 Accessing Structure Members :
Structure members can be accessed using member operator '.' .
It is also called as 'dot operator' or 'period operator'.
structure_var.member;
170© NIELIT Gorakhpur Centre.
Structures can be used as structures within structures. It is also called as 'nesting of
structures'.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - - - -
- - - - - - - -
<data-type> element n;
struct structure_nm {
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - - -
- - - - - - - - - -
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
171© NIELIT Gorakhpur Centre.
#include<stdio.h>
main()
{
struct student{
char name[25];
int m1,m2,m3;
};
struct student b,b1,b2;
printf("enter the name, and marks of three subject's");
scanf("%s%d%d%d",&b.name,&b.m1,&b.m2,&b.m3);
printf("enter the name, and marks of three subject's");
scanf("%s%d%d%d",&b1.name,&b1.m1,&b1.m2,&b1.m3);
printf("enter the name, and marks of three subject's");
scanf("%s%d%d%d",&b2.name,&b2.m1,&b2.m2,&b2.m3);
printf("nNAMEtMark1tMark2tMark3");
printf("n%st%dt%dt%d",b.name,b.m1,b.m2,b.m3);
printf("n%st%dt%dt%d",b1.name,b1.m1,b1.m2,b1.m3);
printf("n%st%dt%dt%d",b2.name,b2.m1,b2.m2,b2.m3);
}
172© NIELIT Gorakhpur Centre.
main()
{
struct emp{
char name[25];
float bs;
}s[3];
float hra,da,pf,gs[3];
int i;
clrscr();
for (i=0;i<3;i++)
{
printf("enter the emp_name and salary");
scanf("%s%f",&s[i].name,&s[i].bs);
hra=s[i].bs*30/100;
da=s[i].bs*15/100;
/* Define a structure named employee, the member of the structure are employee name
and his/her basic salary. Write a program to calculate the gross salary of such three
employee, where hra=30%, da=15% and pf=10%.* /
pf=s[i].bs*10/100;
gs[i]=(s[i].bs+hra+da)-pf;
}
printf("nNAMEtGross salary”);
for(i=0;i<3;i++)
printf("n%st%f",s[i].name,gs[i]);
getch();
}
173© NIELIT Gorakhpur Centre.
Union is user defined data type used to stored data under unique variable name at single
memory location. Syntax of union is similar to structure. But the major difference between
structure and union is 'storage.' In structures, each member has its own storage location,
whereas all the members of union use the same location. Union contains many members of
different types, it can handle only one member at a time.
Syntax: union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;
Example:
union techno
{
int comp_id;
char nm;
float sal;
}tch;
Memory Allocation
To access union members, we can use the following syntax.
tch.comp_id
tch.nm
tch.sal
174© NIELIT Gorakhpur Centre.
#include <stdio.h>
#include <conio.h>
union item {
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch='z';
clrscr();
printf(“a=%dn",it.a);
printf(“b=%fn",it.b);
printf(“ch=%cn",it.ch);
getch();
return 0;
}
a= -26426
b= 20.1999
c=z
Output
As you can see here, the values of a and b get
corrupted and only variable c prints the expected
result. Because in union, the only member whose
value is currently stored will have the memory.
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
175
© NIELIT Gorakhpur Centre.
Open File
Process
Data
Close
File
176© NIELIT Gorakhpur Centre.
 A collection of data or information that are stored on a computer known as file
 A file is a collection of bytes stored on a secondary storage device.
 There are four different types of file
 Data Files
 Text Files
 Program Files
 Directory Files
 Different types of file store different types of information
 A file has a beginning and an end.
 We need a marker to mark the current position of the file from the beginning (in terms
of bytes) while reading and write operation, takes place on a file.
 Initially the marker is at the beginning of the file. We can move the marker to any other
position in the file.
 The new current position can be specified as an offset from the beginning the file.
177© NIELIT Gorakhpur Centre.
 A stream refers to the flow of data (in bytes) from one place to another (from program
to file or vice-versa).
 There are two types of streams
 Text Stream
It consists of sequence of characters
Each line of characters in the stream may be terminated by a newline character.
Text streams are used for textual data, which has a consistent appearance from
one environment to another or from one machine to another
 Binary Stream
It is a series of bytes.
Binary streams are primarily used for non-textual data, which is required to keep
exact contents of the file.
178© NIELIT Gorakhpur Centre.
 ASCII Text files
 A text file can be a stream of characters that a computer can process sequentially.
 It is processed only in forward direction.
 It is opened for one kind of operation (reading, writing, or appending) at any give
time.
 We can read only one character at a time from a text file.
 Binary File
 A binary file is a file consisting of collection of bytes.
 A binary file is also referred to as a character stream.
179© NIELIT Gorakhpur Centre.
Disk I/O Functions
High-level Low-level
Text Binary
Formatted Unformatted UnformattedFormatted
180© NIELIT Gorakhpur Centre.
Function Name Operation
fopen()
Create a new file for use
Opens an existing file for use
fclose() Closes file which was opened for us
fgetc() Read a character from a file
fputc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
fseek() Sets the position to a desired point in the file
ftell()
Gives the current position in the file (in terms of bytes from
the start)
rewind() Sets the position to the beginning of the file
181© NIELIT Gorakhpur Centre.
Mode Meaning
r  Open a text file for reading only. If the file doesn’t exist, it returns null.
w  Opens a file for writing only.
 If file exists, than all the contents of that file are destroyed and new fresh blank file
is copied on the disk and memory with same name
 If file doesn’t exists, a new blank file is created and opened for writing.
 Returns NULL if it is unable to open the file
a  Appends to the existing text file
 Adds data at the end of the file.
 If file doesn’t exists then a new file is created.
 Returns NULL if it is unable to open the file.
rb  Open a binary file for reading
wb  Open a binary file for reading
ab  Append to a binary file
r+  Open a text file for read/write
w+  Opens the existing text file or Creates a text file for read/write
a+  Append or create a text file for read/write
182© NIELIT Gorakhpur Centre.
183© NIELIT Gorakhpur Centre.
 The general format for declaring and opening a file is:
FILE *fp;
fp=fopen(“filename”,mode”);
 Here, the first statement declares the variable fp as a “pointer to the data type FILE”.
 The second statement opens the file named filename with the purpose mode and the
beginning address of the buffer area allocated for the file is stored by file pointer fp.
Note: Any no. of files can be opened and used at a time.
184© NIELIT Gorakhpur Centre.
 The closing a file ensures that all outstanding information associated with the file is
flushed out from the buffers and all links to the file are broken.
 In cases where there is a limit to the no. of files that can be kept open simultaneously,
closing of unwanted files help in opening the required ones.
 Another instance where we have to close a file is when we want to reopen the same file
in different mode.
 fclose() returns 0 if the file is closed successfully.
 The fcloseall() closes all the files opened previously.
 The file is closed using library function fclose() as:
fclose(fp);
185© NIELIT Gorakhpur Centre.
 To read contents from an existing file, we need to open that file in read mode that
means “r” mode
 Algorithm to read data from a file:
 Open the file in read mode
 Read data from the file
 Write the data into an output device
 Repeat steps 3 and 4 until the end of file occurs
 Stop procedure.
186© NIELIT Gorakhpur Centre.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen(“clear.c”,”r”);
if(fp==NULL)
print(“Unable to open clear.c”);
else
{
do
{
ch = getc(fp);
putchar(ch);
}while(ch!=EOF);
fclose(fp);
}
}
187© NIELIT Gorakhpur Centre.
 char *fgets(char *str, int n, FILE *fptr);
This function reads a character from the file stream pointed by fptr and stores it in
the character array ‘str’ until a new line character (n) is read or end of file (EOF) is
reached or n-1 characters have been read.
 fputs(const char *str, FILE *fptr);
This function writes data to the stream pointed to by fptr, the content of the string
stored in ‘str’
188© NIELIT Gorakhpur Centre.
#include <stdio.h>
main( )
{
FILE *fp ;
char s[80] ;
fp=fopen( “fun.txt", "w" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit( ) ;
}
printf ( "nEnter a few lines of text:n" ) ;
while ( strlen ( gets ( s ) ) > 0 )
{
fputs ( s, fp ) ;
fputs ( "n", fp ) ;
}
fclose ( fp ) ;
}
/* Receives strings from keyboard and writes them to file */
189© NIELIT Gorakhpur Centre.
#include<stdio.h>
main( )
{
FILE *fp ;
char s[80] ;
fp = fopen ( “fun.txt", "r" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit( ) ;
}
while ( fgets ( s, 79, fp ) != NULL )
printf ( "%s" , s ) ;
fclose ( fp ) ;
}
/* Reads strings from the file and displays them on screen */
190© NIELIT Gorakhpur Centre.
 A file can be accessed in two ways:
 Serial access
 Random access
 Generally all the text files are considered to be sequential files because lines of text
(also called records) are stored in a file
 The beginning of each record in a sequential file is unpredictable
 Whereas, in random access files, all the records are in same length.
 To modify the content of a file, open the file with read and write mode (“r+” or “w+” or
“a+”)
 Generally “r+” mode is used for both reading and writing operation. The procedure is as
follows:
 Initialize a pointer variable
 Open the file in read and write mode
 Read data from file and Print it
 Move the file pointer to the place where we have the data to be modified and
re-write the new data in that place.
 Repeat steps 3 and 4 till the end of file reaches.
 Stop the Process
191© NIELIT Gorakhpur Centre.
#include<stdio.h>
struct stock
{
int itid, qty;
char n[100];
float rate;
}it;
void main()
{
FILE *fp; int ch; int r = 0;
fp = fopen(“item.c”, “r+”);
if(fp==NULL)
{
printf(“Unable to open item.c”);
}
else{
do{
fread(&it, sizeof(it),1,fp);
printf(“n%d %s %d %f”, it.itid, it.n, it.qty, it.rate);
printf(“n Press 1 to change it?”);
scanf(“%d”,&ch);
if(ch==1)
{
printf(“n Enter Itemid ItemName Quantity & Price”);
scanf(“%d%s%d%f”, &it.itid, it.n, &it.qty, &it.rate);
fseek(fp, r*sizeof(it), 0);
fwrite(&it, sizeof(it),1,fp);
}r++;
}while(!feof(fp));
fclose(fp);
}
}
192© NIELIT Gorakhpur Centre.
Using formatted I/O functions, fprintf() and fscanf(), numbers, characters or string can be
read from file or written onto file according to our requirement format.
 fprintf(): is formatted output function which is used to write integer, float, char or string
value to a file.
Syntax:
fprintf(fp,”control_string”, list_of variables);
 fscanf(): is formatted input function which is used to read integer, float, char or string
value from a file.
Syntax:
fscanf(fp,”control_string”, &list_of variables);
193© NIELIT Gorakhpur Centre.
void main()
{
FILE *fp;
char name[20];
int roll;
char address[20];
float marks;
clrscr();
fp=fopen("C:student.txt", "w");
if(fp==NULL)
{
printf("n File cannot be created or opened.");
exit();
}
printf("n Enter name of student:t");
gets(name);
printf("n Enter roll number of %s:t", name);
scanf("%d", &roll);
fflush(stdin);
/* Program to create a file named student.txt and write name, roll, address and marks of
a student to this file*/
printf("n Enter address of %s:t", name);
gets(address);
printf("n Enter marks of %s:t", name);
scanf("%f", &marks);
printf("n Now writing data to file...");
fprintf(fp, "Name=%sn Roll=%dn
Address=%sn Marks=%.2f", name, roll,
address, marks);
printf("n Completed");
fclose(fp);
getch();
}
194© NIELIT Gorakhpur Centre.
 Trying to read beyond the end-of-file mark.
 Trying to use a file that has not been opened.
 Trying to perform an operation on a file, when the file is opened for another type of
operation.
 Opening a file with an invalid filename.
195© NIELIT Gorakhpur Centre.
 I/O errors can be detected using two status-inquiry library functions: feof() and ferror().
 feof(): It is used to test for an end-of-file condition. It takes a FILE pointer as its only
argument and returns a nonzero integer value if all of the data from the specified file has
been read, and returns zero otherwise. If fp is a pointer to a file that has just been
opened for reading, then the statement
if(feof(fp))
printf(“End of data”);
would display the message “End of data” on reaching the end-of-file condition.
 ferror(): This function reports the status of the file indicated. It takes a FILE pointer as
its argument and returns a nonzero integer if an error has been detected up to that point,
during processing. It returns zero otherwise. So the statement
if(ferrorfp)!=0)
printf(“An error has occured”);
would print the error message, if the reading is not successful.
196© NIELIT Gorakhpur Centre.
 ftell()
This function takes a file pointer as argument and returns a number of type long, that indicates
the current position of the file pointer within the file. This function is useful in saving the
current position of a file, which can be used later in the program.
Syntax:
n=ftell(fp);
Here, n would give the relative offset (in bytes) of the current position. This means that n bytes
have already been read (or written).
197© NIELIT Gorakhpur Centre.
 rewind():
This function takes a file pointer as argument and resets the current position of the file
pointer to the start of the file.
Syntax:
rewind(fp);
What these statements do?: rewind(fp);
n=ftell(fp);
Here, n would be assigned 0, because file position has been set to the start of the file by
rewind().
Note: The first byte in the file is numbered as 0, second as 1, and so on.
198© NIELIT Gorakhpur Centre.
 fseek():
This function is used to move the file pointer to a desired position within a file.
Syntax:
fseek(fp,offset,position);
where fp is a file pointer, offset is a number or variable data type long, and position is an
integer number
The offset specifies the number of positions (bytes) to be moved from the location
specified by position.
The position can have one of the following 3 values:
Value Meaning
0 Beginning of file
1 Current Position
2 End of file
199© NIELIT Gorakhpur Centre.
The offset may be positive, meaning move forwards, or negative, meaning move backwards.
Examples:
Statement Meaning
fseek(fp, 0L, 0); Move file pointer to beginning of file. (Same as rewind.)
fseek(fp, 0L, 1); Stay at the current position. (File pointer is not moved.)
fseek(fp, 0L, 2); Move file pointer past the last character of the file. (Go to the end
of file.)
fseek(fp, m, 0); Move file pointer to (m+1)th byte in the file.
fseek(fp, m, 1); Move file pointer forwards by m bytes.
fseek(fp, -m, 1); Move file pointer backwards by m bytes from the current position.
fseek(fp, -m, 2); Move file pointer backwards by m bytes from the end. (Positions
the file pointer to the mth character from the end.)
200© NIELIT Gorakhpur Centre.
 fseek()
 When the operation is successful, fseek() returns a 0 (zero).
 If we attempt to move the file pointer beyond the file boundaries, an error occurs
and fseek() returns -1 (minus one).
 It is good practice to check whether an error has occurred or not, before proceeding
further.
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
201
© NIELIT Gorakhpur Centre.
202© NIELIT Gorakhpur Centre.
It is a parameter supplied to a program when the program is invoked. This parameter may
represent a filename the program should process.
For example, if we want to execute a program to copy the contents of a file named X_FILE
to another one named Y_FILE, then we may use a command line like
C:TC>PROGRAM X_FILE Y_FILE
PROGRAM is the filename where the executable code of the program is stored. This
eliminates the need for the program to request the user to enter the filenames during
execution.
203© NIELIT Gorakhpur Centre.
How do these parameters get into the program?
We know that every C program should have one main function and that it marks the
beginning of the program.
But what we have not mentioned so far is that it can also take arguments like other
functions. In fact main can take two arguments called argc and argv and the information
contained in the command line is passed on to the program through these arguments, when
main is called up by the system.
The variable argc is an argument counter that counts the number of arguments on the
command line. The argv is an argument vector and represents an array of character pointers
that point to the command line arguments
204© NIELIT Gorakhpur Centre.
The size of this array will be equal to the value of argc. For instance, for the command line
given above, argc is three and argv is array of three pointers to strings as shown below:
argv[0] PROGRAM
argv[1] X_FILE
argv[2] Y_FILE
In order to access the command line arguments, we must declare the main function and its
parameters as follows:
main(argc,argv);
int argc;
char *argv[];
The first parameter in the command line is always the program name and therefore argv[0]
always represents the program name.
205© NIELIT Gorakhpur Centre.
Example: Command Line Argument
#include<stdio.h>
#include<conio.h>
void main(argc,argv)
int argc;
char *argv[];
{
FILE *fp;
int i;
char word[15];
clrscr();
fp = fopen(argv[1],"w");
printf("nNo.of arguments in Command line=%dnn",argc);
for(i=2;i<argc;i++)
fprintf(fp,"%s",argv[i]);
fclose(fp);
printf("Contents of %s filenn",argv[1]);
fp=fopen(argv[1],"r");
for(i=2;i<argc;i++)
{
fscanf(fp,"%s",word);
printf("%s",word);
}
fclose(fp);
printf("nn");
for(i=0;i<argc;i++)
printf("%*sn",i*5,argv[i]);
getch();
}
NIELIT Gorakhpur Centre
MMMUT Campus, Gorakhpur (UP), PIN-273010
206
© NIELIT Gorakhpur Centre.
• Malloc Function
• Calloc Function
• Free Function
• Realloc Function
207© NIELIT Gorakhpur Centre.
The process of allocating memory at runtime is known as dynamic memory allocation.
Library routines known as "memory management functions" are used for allocating and
freeing memory during execution of a program. These functions are defined in stdlib.h.
Function Description
malloc()
Allocates requested size of bytes and returns a void pointer
to the first byte of the allocated space
calloc()
Allocates space for an array of elements, initialize them to
zero and then return a void pointer to the memory
free() Release previously allocated memory
realloc() Modifies the size of previously allocated space
208© NIELIT Gorakhpur Centre.
 malloc( )
The name malloc stands for "memory allocation". The function malloc() used for
allocating block of memory at runtime. This function reserves a block of memory of
given size and returns a pointer of type void. This means that we can assign it to any type
of pointer using typecasting. If it fails to locate enough space it returns a NULL pointer.
Syntax:
ptr=(datatype*)malloc(byte_size);
ptr is pointer of type datatype. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
Example:
x=(int*)malloc(sizeof(int));
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material
C Course material

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Computer Engineering. Motherboard.
Introduction to Computer Engineering. Motherboard.Introduction to Computer Engineering. Motherboard.
Introduction to Computer Engineering. Motherboard.marada0033
 
MIPI DevCon 2016: Implementing MIPI C-PHY
MIPI DevCon 2016: Implementing MIPI C-PHYMIPI DevCon 2016: Implementing MIPI C-PHY
MIPI DevCon 2016: Implementing MIPI C-PHYMIPI Alliance
 
Programacion RPG: Conceptos ILE
Programacion RPG: Conceptos ILEProgramacion RPG: Conceptos ILE
Programacion RPG: Conceptos ILEGiovanny Guillen
 
Launch the First Process in Linux System
Launch the First Process in Linux SystemLaunch the First Process in Linux System
Launch the First Process in Linux SystemJian-Hong Pan
 
Diseño de pantallas en as400
Diseño de pantallas en as400Diseño de pantallas en as400
Diseño de pantallas en as400Carlos
 
[Advantech] PAC SW Multiprog Tutorial step by step
[Advantech] PAC SW Multiprog Tutorial step by step [Advantech] PAC SW Multiprog Tutorial step by step
[Advantech] PAC SW Multiprog Tutorial step by step Ming-Hung Hseih
 
Algorithm and c language
Algorithm and c languageAlgorithm and c language
Algorithm and c languagekamalbeydoun
 
C programming language Reference Note
C programming language Reference NoteC programming language Reference Note
C programming language Reference NoteChetan Thapa Magar
 
Microcontroladores PIC - Manipulação de pinos de I/O com a Linguagem C
Microcontroladores PIC - Manipulação de pinos de I/O com a Linguagem CMicrocontroladores PIC - Manipulação de pinos de I/O com a Linguagem C
Microcontroladores PIC - Manipulação de pinos de I/O com a Linguagem CFabio Souza
 
Creo packaging and solution capabilities presentation (1) za sajta creo desig...
Creo packaging and solution capabilities presentation (1) za sajta creo desig...Creo packaging and solution capabilities presentation (1) za sajta creo desig...
Creo packaging and solution capabilities presentation (1) za sajta creo desig...Victor Mitov
 
Digital design with Systemc
Digital design with SystemcDigital design with Systemc
Digital design with SystemcMarc Engels
 
Andes building a secure platform with the enhanced iopmp
Andes building a secure platform with the enhanced iopmpAndes building a secure platform with the enhanced iopmp
Andes building a secure platform with the enhanced iopmpRISC-V International
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal BootloaderSatpal Parmar
 

Was ist angesagt? (20)

Introduction to Computer Engineering. Motherboard.
Introduction to Computer Engineering. Motherboard.Introduction to Computer Engineering. Motherboard.
Introduction to Computer Engineering. Motherboard.
 
Embedded C - Day 1
Embedded C - Day 1Embedded C - Day 1
Embedded C - Day 1
 
MIPI DevCon 2016: Implementing MIPI C-PHY
MIPI DevCon 2016: Implementing MIPI C-PHYMIPI DevCon 2016: Implementing MIPI C-PHY
MIPI DevCon 2016: Implementing MIPI C-PHY
 
Programacion RPG: Conceptos ILE
Programacion RPG: Conceptos ILEProgramacion RPG: Conceptos ILE
Programacion RPG: Conceptos ILE
 
Pcie drivers basics
Pcie drivers basicsPcie drivers basics
Pcie drivers basics
 
Launch the First Process in Linux System
Launch the First Process in Linux SystemLaunch the First Process in Linux System
Launch the First Process in Linux System
 
Resume
ResumeResume
Resume
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
 
Diseño de pantallas en as400
Diseño de pantallas en as400Diseño de pantallas en as400
Diseño de pantallas en as400
 
[Advantech] PAC SW Multiprog Tutorial step by step
[Advantech] PAC SW Multiprog Tutorial step by step [Advantech] PAC SW Multiprog Tutorial step by step
[Advantech] PAC SW Multiprog Tutorial step by step
 
Algorithm and c language
Algorithm and c languageAlgorithm and c language
Algorithm and c language
 
C programming language Reference Note
C programming language Reference NoteC programming language Reference Note
C programming language Reference Note
 
Computer basics
Computer basicsComputer basics
Computer basics
 
Microcontroladores PIC - Manipulação de pinos de I/O com a Linguagem C
Microcontroladores PIC - Manipulação de pinos de I/O com a Linguagem CMicrocontroladores PIC - Manipulação de pinos de I/O com a Linguagem C
Microcontroladores PIC - Manipulação de pinos de I/O com a Linguagem C
 
C Programming - Refresher - Part I
C Programming - Refresher - Part I C Programming - Refresher - Part I
C Programming - Refresher - Part I
 
Creo packaging and solution capabilities presentation (1) za sajta creo desig...
Creo packaging and solution capabilities presentation (1) za sajta creo desig...Creo packaging and solution capabilities presentation (1) za sajta creo desig...
Creo packaging and solution capabilities presentation (1) za sajta creo desig...
 
Digital design with Systemc
Digital design with SystemcDigital design with Systemc
Digital design with Systemc
 
Lec13
Lec13Lec13
Lec13
 
Andes building a secure platform with the enhanced iopmp
Andes building a secure platform with the enhanced iopmpAndes building a secure platform with the enhanced iopmp
Andes building a secure platform with the enhanced iopmp
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
 

Andere mochten auch

IT and web designing
IT and web designingIT and web designing
IT and web designingSarwan Singh
 
Aspire Systems Introduction
Aspire Systems IntroductionAspire Systems Introduction
Aspire Systems IntroductionRam Kasi
 
Seo: www o non www - Come Impostare versione preferita del dominio
Seo: www o non www - Come Impostare versione preferita del dominioSeo: www o non www - Come Impostare versione preferita del dominio
Seo: www o non www - Come Impostare versione preferita del dominioAntonio Mecca
 
Test of Written English
Test of Written EnglishTest of Written English
Test of Written EnglishAnnasta Tastha
 
Linear equations in two variables
Linear equations in two variablesLinear equations in two variables
Linear equations in two variablesVinisha Pathak
 
Repsol: Informe Anual 2013
Repsol: Informe Anual 2013Repsol: Informe Anual 2013
Repsol: Informe Anual 2013Repsol
 
M1-R4 - IT Tools And Business Systems - Jan 2014 Solved Paper Part-1
M1-R4 - IT Tools And Business Systems - Jan 2014 Solved Paper Part-1M1-R4 - IT Tools And Business Systems - Jan 2014 Solved Paper Part-1
M1-R4 - IT Tools And Business Systems - Jan 2014 Solved Paper Part-1saisyam
 
Repsol: Informe anual 2014
Repsol: Informe anual 2014Repsol: Informe anual 2014
Repsol: Informe anual 2014Repsol
 
48266497 101-shortcut-maths
48266497 101-shortcut-maths48266497 101-shortcut-maths
48266497 101-shortcut-mathssrhaider
 
Marc Records and Bibliographic Control
Marc Records and Bibliographic ControlMarc Records and Bibliographic Control
Marc Records and Bibliographic ControlDenise Garofalo
 
Classified catalogue (Tony Vimal)
Classified  catalogue (Tony Vimal)Classified  catalogue (Tony Vimal)
Classified catalogue (Tony Vimal)tonyviamll89
 
MAPPING OF KNOWLEDGE IN COLON CLASSIFICATION
MAPPING OF KNOWLEDGE IN COLON CLASSIFICATION MAPPING OF KNOWLEDGE IN COLON CLASSIFICATION
MAPPING OF KNOWLEDGE IN COLON CLASSIFICATION ARUNVR2467
 
Basic Access Notes
Basic Access NotesBasic Access Notes
Basic Access NotesPyi Soe
 
Colon Classification: An Overview
Colon Classification: An OverviewColon Classification: An Overview
Colon Classification: An Overviewsarika meher
 

Andere mochten auch (20)

IT and web designing
IT and web designingIT and web designing
IT and web designing
 
Teoria critica
Teoria criticaTeoria critica
Teoria critica
 
Aspire Systems Introduction
Aspire Systems IntroductionAspire Systems Introduction
Aspire Systems Introduction
 
elaf1028shirai
elaf1028shiraielaf1028shirai
elaf1028shirai
 
Seo: www o non www - Come Impostare versione preferita del dominio
Seo: www o non www - Come Impostare versione preferita del dominioSeo: www o non www - Come Impostare versione preferita del dominio
Seo: www o non www - Come Impostare versione preferita del dominio
 
Executive Assistant job profile - MEF
Executive Assistant job profile - MEFExecutive Assistant job profile - MEF
Executive Assistant job profile - MEF
 
Test of Written English
Test of Written EnglishTest of Written English
Test of Written English
 
ramamrita
ramamrita ramamrita
ramamrita
 
Linear equations in two variables
Linear equations in two variablesLinear equations in two variables
Linear equations in two variables
 
Repsol: Informe Anual 2013
Repsol: Informe Anual 2013Repsol: Informe Anual 2013
Repsol: Informe Anual 2013
 
M1-R4 - IT Tools And Business Systems - Jan 2014 Solved Paper Part-1
M1-R4 - IT Tools And Business Systems - Jan 2014 Solved Paper Part-1M1-R4 - IT Tools And Business Systems - Jan 2014 Solved Paper Part-1
M1-R4 - IT Tools And Business Systems - Jan 2014 Solved Paper Part-1
 
Repsol: Informe anual 2014
Repsol: Informe anual 2014Repsol: Informe anual 2014
Repsol: Informe anual 2014
 
48266497 101-shortcut-maths
48266497 101-shortcut-maths48266497 101-shortcut-maths
48266497 101-shortcut-maths
 
Marc Records and Bibliographic Control
Marc Records and Bibliographic ControlMarc Records and Bibliographic Control
Marc Records and Bibliographic Control
 
Dewey Classification
Dewey ClassificationDewey Classification
Dewey Classification
 
Classified catalogue (Tony Vimal)
Classified  catalogue (Tony Vimal)Classified  catalogue (Tony Vimal)
Classified catalogue (Tony Vimal)
 
MAPPING OF KNOWLEDGE IN COLON CLASSIFICATION
MAPPING OF KNOWLEDGE IN COLON CLASSIFICATION MAPPING OF KNOWLEDGE IN COLON CLASSIFICATION
MAPPING OF KNOWLEDGE IN COLON CLASSIFICATION
 
Basic Access Notes
Basic Access NotesBasic Access Notes
Basic Access Notes
 
Colon Classification: An Overview
Colon Classification: An OverviewColon Classification: An Overview
Colon Classification: An Overview
 
S R Ranganathan Powerpoint
S R  Ranganathan PowerpointS R  Ranganathan Powerpoint
S R Ranganathan Powerpoint
 

Ähnlich wie C Course material

Lecture_1_Introduction_to_Programming.pptx
Lecture_1_Introduction_to_Programming.pptxLecture_1_Introduction_to_Programming.pptx
Lecture_1_Introduction_to_Programming.pptxChewe Lulembo
 
English de lenguaje de programacion
English de lenguaje de programacionEnglish de lenguaje de programacion
English de lenguaje de programacionVillalba Griselda
 
Computer programming programming_langugages
Computer programming programming_langugagesComputer programming programming_langugages
Computer programming programming_langugageseShikshak
 
A Research Study of Data Collection and Analysis of Semantics of Programming ...
A Research Study of Data Collection and Analysis of Semantics of Programming ...A Research Study of Data Collection and Analysis of Semantics of Programming ...
A Research Study of Data Collection and Analysis of Semantics of Programming ...IRJET Journal
 
Introduction to programming language (basic)
Introduction to programming language (basic)Introduction to programming language (basic)
Introduction to programming language (basic)nharsh2308
 
Introduction Programming Languages
Introduction Programming LanguagesIntroduction Programming Languages
Introduction Programming LanguagesManish Kharotia
 
Computer Software and It's Development
Computer Software and It's DevelopmentComputer Software and It's Development
Computer Software and It's DevelopmentRabin BK
 
High Level Language (HLL)
High Level Language (HLL)High Level Language (HLL)
High Level Language (HLL)Maliha Jahan
 
introduction to programming languages
introduction to programming languagesintroduction to programming languages
introduction to programming languagesNaqashAhmad14
 
PPL_Unit01 for the insem study first year.pptx
PPL_Unit01 for the insem study first year.pptxPPL_Unit01 for the insem study first year.pptx
PPL_Unit01 for the insem study first year.pptxrockstarr066gj
 
introduction to programming
introduction to programmingintroduction to programming
introduction to programmingGaea Bonita
 

Ähnlich wie C Course material (20)

C.pdf
C.pdfC.pdf
C.pdf
 
Lecture_1_Introduction_to_Programming.pptx
Lecture_1_Introduction_to_Programming.pptxLecture_1_Introduction_to_Programming.pptx
Lecture_1_Introduction_to_Programming.pptx
 
Ppt 1
Ppt 1Ppt 1
Ppt 1
 
English de lenguaje de programacion
English de lenguaje de programacionEnglish de lenguaje de programacion
English de lenguaje de programacion
 
Computer programming programming_langugages
Computer programming programming_langugagesComputer programming programming_langugages
Computer programming programming_langugages
 
A Research Study of Data Collection and Analysis of Semantics of Programming ...
A Research Study of Data Collection and Analysis of Semantics of Programming ...A Research Study of Data Collection and Analysis of Semantics of Programming ...
A Research Study of Data Collection and Analysis of Semantics of Programming ...
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Introduction to programming language (basic)
Introduction to programming language (basic)Introduction to programming language (basic)
Introduction to programming language (basic)
 
Fundamentals of Programming Chapter 2
Fundamentals of Programming Chapter 2Fundamentals of Programming Chapter 2
Fundamentals of Programming Chapter 2
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Introduction Programming Languages
Introduction Programming LanguagesIntroduction Programming Languages
Introduction Programming Languages
 
Computer Software and It's Development
Computer Software and It's DevelopmentComputer Software and It's Development
Computer Software and It's Development
 
Computer Programming
Computer Programming Computer Programming
Computer Programming
 
Computer
ComputerComputer
Computer
 
CS3251-_PIC
CS3251-_PICCS3251-_PIC
CS3251-_PIC
 
High Level Language (HLL)
High Level Language (HLL)High Level Language (HLL)
High Level Language (HLL)
 
introduction to programming languages
introduction to programming languagesintroduction to programming languages
introduction to programming languages
 
PPL_Unit01 for the insem study first year.pptx
PPL_Unit01 for the insem study first year.pptxPPL_Unit01 for the insem study first year.pptx
PPL_Unit01 for the insem study first year.pptx
 
introduction to programming
introduction to programmingintroduction to programming
introduction to programming
 
Programming in c
Programming in cProgramming in c
Programming in c
 

C Course material

  • 1. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 1 © NIELIT Gorakhpur Centre.
  • 2. 2© NIELIT Gorakhpur Centre. Chapter No. Topic 1 Language 2 Flow Charts 3 C Language 4 Data Types and Operator 5 Decision Making & Control Statement 6 Loops 7 Functions 8 Pointers 9 Storage Class 10 C Preprocessor 11 Structure 12 File Handling 13 Command Line Argument 14 Dynamic Memory Allocation 15 Linked List
  • 3. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 3 © NIELIT Gorakhpur Centre. • What is Language? • Programming Language
  • 4. 4© NIELIT Gorakhpur Centre. Language is a collection of words and symbols which can be used to perform certain task or activities and to establish a communication between person to person. In the same manner computer languages are the collection of predefine key words which can be used to perform certain task and to communicate between to entities like between two machines or between human and computers or computers and others peripherals. There are three different level of programming languages. They are:  Machine languages (low level)  Assembly languages  Procedure Oriented languages (high level)
  • 5. 5© NIELIT Gorakhpur Centre.  Machine Languages: Computers are made of No. of electronic components and they all are two – state electronic components means they understand only the 0 – (pulse) and 1 (non – pulse). Therefore the instruction given to the computer must be written using binary numbers. 1and 0. Computers do not understand English or any other language but they only understand or respond to binary numbers (0 and 1). So each computer has its own Machine languages.
  • 6. 6© NIELIT Gorakhpur Centre.  Assembly Languages: As it was very tedious to understand and remember 0’s representing numerous data and instruction. So to resolve this problem mnemonics codes were developed. For example add is used as symbolic code to represent addition. SUB is used for subtraction. They are the symbolic representation of certain combination of binary numbers . for example S U B Which represents certain actions as computer understand only Machine language instructions a program written in Assembly Language must be translated into Machine languages. Before it can be executed this translation if done by another program called assembler. This assembler will translate mnemonic codes into Machine languages.
  • 7. 7© NIELIT Gorakhpur Centre.  Procedure Oriented Languages: In earlier assembly languages assembler programs produced only one Machine languages instruction for every assembly languages instruction. So to resolve this problem now assembler were introduced. Which can produce several machine level instructions for one assembly language instruction. Thus programmer was relieve from the task of writing and instruction for every machine operation performed. These languages contains set of words and symbols and one can write program with the combination of these keywords. These languages are also called high level languages. Basic, Fortran, Pascal and COBOL. The most important characteristic of high level languages is that it is machine independent and a program written in high level languages can be run on any computers with different architecture with no modification or very little modification.
  • 8. 8© NIELIT Gorakhpur Centre. All programming languages can be divided into two categories: Problem Oriented Language Or High Level Language Problem Oriented Language Or Low Level Language Programming Language
  • 9. 9© NIELIT Gorakhpur Centre. Problem oriented languages or high languages : Examples of languages falling in this category are FORTRAN, BASIC, Pascal, etc. These languages have been designed to give a better programming efficiency, faster program development. Generally these languages have better programming capability but they are less capable to deal with hardware or Hardware related programming. Machine oriented languages of Low Level Languages : Examples of languages falling in this category are Assembly language and Machine Language. This languages have been designed to give a better machine efficiency i.e. faster program execution. Generally these languages have better hardware programming capability but it is very difficult and tedious to do create complex application like and business application or some commercial application C as Middle Level Language : C stands in between these two categories. That’s why it is called a Middle Level Language, since it was designed to have both; a relatively good programming efficiency (as compared to Machine Oriented Language) and a relatively good machine efficiency (as compared to Problem Oriented Language).
  • 10. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 10 © NIELIT Gorakhpur Centre. • Introduction • Flow Chart Symbol • Examples • Advantages • Limitation START Statement Condition Statement Statement STOP
  • 11. 11© NIELIT Gorakhpur Centre. A flowchart is a graphical representation of decisions and their results mapped out in individual shapes that were first developed by Herman Goldstine and John von Neumann in the 1940’s. Flowcharts can provide a step-by-step diagram for mapping out complex situations, such as programming code or troubleshooting problems with a Computer.  A diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem.  Generally drawn in the early stages of formulating computer solutions.  Facilitate communication between programmers and business people/end users.  Once the flowchart is drawn, it becomes easy to write the program in any high level language.  Must for the better documentation of a complex program.
  • 12. 12© NIELIT Gorakhpur Centre. Symbol Description Used to indicates the start and end of a flowchart. Single flow line. Only one “Start” and “Stop” terminal for each program. Process: Used whenever data is being manipulated. One flow line enters and one flow line exits. Input / Output: Used whenever data is entered (input) or displayed (output). One flow line enters and one flow line exits. Decision: Used to represent operations in which there are two possible selections. One flow line enters and two flow lines exit. Flow line: Used to indicate the direction of flow of control.
  • 13. 13© NIELIT Gorakhpur Centre.  Example 1: Draw a flow chart to show the addition of two no. START STOP Accept no1 & no1 Sum=no1+no2 Display the sum
  • 14. 14© NIELIT Gorakhpur Centre. Example 2: Draw a flowchart to find the sum of first 50 natural numbers.
  • 15. 15© NIELIT Gorakhpur Centre. Example 3: Draw a flowchart to find the largest of three numbers A,B and C.
  • 16. 16© NIELIT Gorakhpur Centre. Example 4: Draw a flowchart for computing factorial of a given number.
  • 17. 17© NIELIT Gorakhpur Centre.  Communication: Flowcharts are better way of communicating the logic of a system to all concerned.  Effective analysis: With the help of flowchart, problem can be analyzed in more effective way.  Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes.  Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase.  Proper Debugging: The flowchart helps in debugging process.  Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part.
  • 18. 18© NIELIT Gorakhpur Centre.  Complex logic: Sometimes, the program logic is quite complicated.  Alterations and Modifications: Alterations may require re-drawing completely.  Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
  • 19. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 19 © NIELIT Gorakhpur Centre. • Introduction • History of C • Importance of C • Basic Structure of C program • Execution of C program • Variable • Keywords • Constant in C
  • 20. 20© NIELIT Gorakhpur Centre. C language is a general purpose and structured programming language developed by 'Dennis Ritchie' at AT &T's Bell Laboratories in the 1972 in USA. It is also called as 'Procedure oriented programming language.' C is not specially designed for specific applications areas like COBOL (Common Business-Oriented Language) or FORTRAN (Formula Translation). It is well suited for business and scientific applications. It has some various features like control structures, looping statements, arrays, macros required for these applications.  The C language has following numerous features as:  Flexibility  Portability  Compactness  Reusability
  • 21. 21© NIELIT Gorakhpur Centre. FLEXIBLILITY: C is a powerful and flexible language. C is used for projects as diverse as operating system, word processor, graphics, spreadsheets and even compilers for other language. C is a popular language preferred by professional programmers. As a result, a wide variety of C compilers and helpful accessories are available. PORTABILITY: C is a portable language. Portable means that a C program written for one computer system can be run on another system with little or no modification. Portability is enhanced by the ANSI standard by C, the set of rules for C compilers. COMPACTNESS: C is a language of few words, containing only a handful terms, called keywords, which serve as the base on which the language’s functionality is built. You might think that a language with more keyword would be more powerful. This isn’t true. As you will find that it can be programmed to do any task. REUSABILITY: C is modular, C code can and should be written in routine called functions. These functions can be reused in other applications or programs. By passing pieces of information to the function, you can create useful, reusable code.
  • 23. 23© NIELIT Gorakhpur Centre.  C was evolved from ALGOL, BCPL and B.  C was developed by Dennis Ritchie at the Bell Laboratories in 1972.  Added new features and concepts like “data types”.  It was developed along with the UNIX operating system.  It was strongly integrated with the UNIX operating system.  In 1983 American National Standards Institute (ANSI) appointed a technical committee to define a standard for C. The committee approved a version of C in December 1989 which is now known as ANSI C.  In 1990 International Standards Organization (ISO) has approved C and this version of C is referred to as C89.
  • 24. 24© NIELIT Gorakhpur Centre.  Rich set of built-in functions  Operators can be used to write any complex program.  The C compiler combines the capabilities of an assembly language with the features of a high-level language.  It is well sited for writing both system software and business packages.  Due to variety of data types and powerful operators programs written in C are efficient and fast.  There are only 32 keywords in C and its strength lies in its built in functions.  C is highly portable.  Ability to extend itself.  C is a Structured Programming Language (requiring the user to think of a problems in terms of function modules or blocks).
  • 25. 25© NIELIT Gorakhpur Centre. C program can be viewed a s group of building blocks called functions. A function is a subroutine that may include one or more statement designed to perform a specific task. A C program may contain one or more section as shown below : Documentation Section • Link Section • Definition Section • Global declaration Section • main( ) function section { Declaration Part Executable Part } Subprogram Section Function1 ( ) { } Function2 ( ) { }
  • 26. 26© NIELIT Gorakhpur Centre.  Documentation Section: This section contains set of comments lines consist of details like program name, author name and purpose or functionality of the program.  Link Section: This section consist of instructions to be given to the compiler to link functions from the system library. For example if you want to use some mathematical function then you have to define link for math.h file in link section. For Example: # include<stdio.h> # include<math.h>  Definition Section: This section defines all the symbolic constants. For example PI=3.14. By defining symbolic constant one can use these symbolic constant instead of constant value. # define PI 3.14 # define Temp 35
  • 27. 27© NIELIT Gorakhpur Centre.  Global Declaration Section : This section contains the declaration of variables which are used by more then more then one function of the program.  Main Function Section : A main() function is a heart of any ‘C’ language program. Any C program is made up of 1 or more then 1 function. If there is only 1 function in the program then it must be the main program. An execution of any C program starts with main() function.  Subprogram Or Sub Function Section : They are the code section which are define outside the boundary of main function. This function can be called from any point or anywhere from the program. Generally they are define to solve some frequent tasks.
  • 28. 28© NIELIT Gorakhpur Centre. C program executes in following 4 (four steps).
  • 29. 29© NIELIT Gorakhpur Centre. 1. Creating a program : An editor like notepad or WordPad is used to create a C program. This file contains a source code which consists of executable code. The file should be saved as '*.c' extension only. 2. Compiling the program : The next step is to compile the program. The code is compiled by using compiler. Compiler converts executable code to binary code i.e. object code. 3. Linking a program to library : The object code of a program is linked with libraries that are needed for execution of a program. The linker is used to link the program with libraries. It creates a file with '*.exe' extension. 4. Execution of program : The final executable file is then run by dos command prompt or by any other software.
  • 30. 30© NIELIT Gorakhpur Centre. Character Set A character refers to the digit, alphabet or special symbol used to data representation.  Alphabets : A-Z, a-z  Digits : 0-9  Special Characters : ~ ! @ # $ % ^ & * ( ) _ + { } [ ] - < > , . / ? | : ; " '  White Spaces : Horizontal tab, Carriage return, New line  Identifier identifier is the name of a variable that is made up from combination of alphabets, digits and underscore. Variable It is a data name which is used to store data and may change during program execution. It is opposite to constant. Variable name is a name given to memory cells location of a computer where data is stored.
  • 31. 31© NIELIT Gorakhpur Centre. Rules for variables: • First character should be letter or alphabet. • Keywords are not allowed to use as a variable name. • White space is not allowed. • C is case sensitive i.e. UPPER and lower case are significant. • Only underscore, special symbol is allowed between two characters.
  • 32. 32© NIELIT Gorakhpur Centre. There are totally 32 (Thirty Two) keywords used in a C programming. int float double long short signed unsigned const if else switch break default do while for register extern static struct typedef enum return sizeof goto union auto case void char continue volatile
  • 33. 33© NIELIT Gorakhpur Centre.  Keywords are the system defined identifiers.  All keywords have fixed meanings that do not change.  White spaces are not allowed in keywords.  Keyword may not be used as an identifier.  It is strongly recommended that keywords should be in lower case letters.
  • 34. 34© NIELIT Gorakhpur Centre. A constant is an entity that doesn't change during the execution of a program. Syntax: const data type var_name=expression; Example: const float pi=3.147 Followings are the different types of constants : 1. Real Constant : It must have a decimal point which may be positive or negative. Example: +194.143, -416.41 2. Integer Constant : It should not contain a decimal place. It can be positive or negative. Example: 1990, 194, -394 3. Character Constant : It is a single alphabet or a digit or a special symbol enclosed in a single quote. Maximum length of a character constant is 1. Example: 'T', '9', '$' 4. String Constant : It may contain letters, digits, special characters and blank space. Example: “Hello friends"
  • 35. 35© NIELIT Gorakhpur Centre. C supports some special escape sequence characters that are used to do special tasks. Character Constant Meaning n New line (Line break) b Backspace t Horizontal Tab f Form feed a Alert (alerts a bell) r Carriage Return v Vertical Tab ? Question Mark ' Single Quote '' Double Quote Backslash 0 Null
  • 36. 36© NIELIT Gorakhpur Centre. Comments in C are of the general of /* . . . . . * / Comments can be inserted anywhere you can put a space (blank). Comments are ignored by the C compiler and not included in the executable file. The */ can be on the next line but then every character between the /* and the */ is ignored by the C compiler.
  • 37. 37© NIELIT Gorakhpur Centre.  Syntax Errors The C compiler will catch these errors and give you Error messages. Example: x + 1 = x; (should be x = x+1; for a valid assignment statement)  Run-time Errors The C compiler will not catch these errors. Example: User enters the value 0 and your code reads this value into variable x, and then computes 1/x .  Logical Errors The C compiler will not catch these errors. Program will run and not generate any error messages but results outputted by the program are incorrect. Example: User programs solution using the wrong formula.
  • 38. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 38 © NIELIT Gorakhpur Centre. • Data Types • Operators • Increment / Decrement Operator • Input / Output Statement
  • 39. 39© NIELIT Gorakhpur Centre. PRIMARY DATATYPE DERIVED DATATYPE INTEGER CHAR FLOAT VOID ARRAY POINTER STRUCTURE UNION USER DEFINED TYPE TYPEDEF ENUM
  • 40. 40© NIELIT Gorakhpur Centre.  Integer : To access and to store any integer value int data type is use. C’s int data type occupies 2 bytes in the memory. To declare any integer variable : int variable_name;  Float : To access and to store any real value float data type is use. C’s float data type occupies 4 bytes in the memory. To declare any float variable : float variable_name;  Character : To access and to store single character it use char data type in C. Char data type occupies 1 bytes. It means that char data type use 1 byte of memory to store some character value. Declaration of character variable : char variable_name;
  • 41. 41© NIELIT Gorakhpur Centre. Keyword Format Specifier Size Data Range char %c 1 Byte -128 to +127 unsigned char %c 1 Byte 0 to 255 int %d 2 Bytes -32768 to +32767 long int %ld 4 Bytes -231 to +231 unsigned int %u 2 Bytes 0 to 65535 float %f 4 Bytes -3.4e38 to +3.4e38 double %lf 8 Bytes -1.7e38 to +1.7e38 long double %Lf 10Bytes -3.4e38 to +3.4e38 “Data type can be defined as the type of data of variable or constant store.”  Followings are the most commonly used data types in C.
  • 42. 42© NIELIT Gorakhpur Centre. “Operator is a symbol that is used to perform operations.”  Followings are the most commonly used data types in C. Operator Name Operators Assignment = Arithmetic + , - , *, /, % Logical &&, ||, ! Relational <, >, <=, >=, ==, != Shorthand +=, -=, *=, /=, %= Unary ++, -- Conditional Y=(x>9)? 100 :200 ; Bitwise &, |, ^, <<, >>, ~
  • 43. 43© NIELIT Gorakhpur Centre.  Arithmetic operators are used to perform numerical calculations among the values. Operator Meaning + Addition - Subtraction * Multiplication / Division % Modulo Division
  • 44. 44© NIELIT Gorakhpur Centre. Example: #include<stdio.h> int main() { int a, b, add, sub, mul, div, rem; printf("Enter a, b values : "); scanf("%d%d",&a,&b); // Reading two values add=a+b; // Addition Operator sub=a-b; // Subtraction Operator mul=a*b; // Multiplication Operator div=a/b; // Division Operator rem=a%b; // Remainder (Modulo) Operator printf("Result of addition is=%dn", add); printf("Result of subtraction=%dn", sub); printf("Result of multiplication is=%dn", mul); printf("Result of division is=%dn", div); printf("Result of remainder=%dn",rem); return 0; }
  • 45. 45© NIELIT Gorakhpur Centre.  These operators are used for testing more than one condition and making decisions.  C has three logical operators they are: Operator Meaning && Logical AND | | Logical OR ! Logical NOT
  • 46. 46© NIELIT Gorakhpur Centre. Example: #include<stdio.h> void main() { int a, b; printf(“Enter values for a and b : "); scanf(“%d %d", &a, &b); printf("n %d",(a<b)&&(a!=b)); printf("n %d",(a<b)||(b<a)); printf("n %d",!(a==b)); }
  • 47. 47© NIELIT Gorakhpur Centre. Operator Meaning < Is less than <= Is less than or equal to > Is greater than => Is greater than or equal to == Is equal to != Is not equal to  Relational Operators are used to compare two quantities and take certain decision depending on their relation. If the specified relation is true it returns one. If the specified relation is false it returns zero.
  • 48. 48© NIELIT Gorakhpur Centre. Example: #include<stdio.h> void main() { int a, b; printf(“Enter values for a and b : "); scanf("%d %d", &a, &b); printf("n The < value of a is %d", a<b); printf("n The <= value of a is %d", a<=b); printf("n The > value of a is %d", a>b); printf("n The >= value of a is %d", a>=b); printf("n The == value of a is %d", a==b); printf("n The != value of a is %d", a!=b); }
  • 49. 49© NIELIT Gorakhpur Centre. C includes a unary increment operator (++) and decrement operator (--). Increment and decrement operators increase and decrease a value stored in a number variable by 1. For example, the expression, count = count + 1; //increment the value of count by 1 is equivalent to count++; Operator Use Description ++ i++ Increments i by 1; evaluates to the value of i before it was incremented ++ ++i Increments i by 1; evaluates to the value of i after it was incremented -- i-- Decrements i by 1; evaluates to the value of i before it was decremented -- --i Decrements i by 1; evaluates to the value of i after it was decremented For example: int i = 10, int j = 3; int k = 0; k = ++j + i; //will result to k = 4+10 = 14 k = j++ + i; //will result to k = 3+10 = 13
  • 50. 50© NIELIT Gorakhpur Centre. Example: #include<stdio.h> void main() { int a,b,c; printf("Enter the values for a and b :"); scanf("%d %d", &a, &b); printf("n The value of c is %d", c=++a); printf("n The value of c is %d", c=a++); printf("n The value of c is %d", c=--b); printf("n The value of c is %d", c=b--); }
  • 51. 51© NIELIT Gorakhpur Centre. The conditional operator ? : is a ternary operator. This means that it takes in three arguments that together form a conditional expression. Syntax: exp1 ? exp2 : exp3; Where in exp1 is a Boolean expression whose result must either be true or false. If exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned.
  • 52. 52© NIELIT Gorakhpur Centre. Example: void main() { int x; printf("enter any number"); scanf("%d",&x); x>0? printf("Positive"):printf("Negative"); }
  • 53. 53© NIELIT Gorakhpur Centre.  These operators works on bit level  Applied to Integers only Operator Meaning & Bitwise AND | Bitwise OR ^ Bitwise Exclusive OR << Shift Left >> Shift Right ~ One’s Complement
  • 54. 54© NIELIT Gorakhpur Centre. Let A=0x56 and B=0x32 A & B ( Bitwise AND ) 0 1 0 1 0 1 1 0 0 0 1 1 0 0 1 0 --------------------- 0 0 0 1 0 0 1 0 --------------------- A ^ B ( Bitwise XOR ) 0 1 0 1 0 1 1 0 0 0 1 1 0 0 1 0 --------------------- 0 1 1 0 0 10 0 --------------------- A | B ( Bitwise OR ) 0 1 0 1 0 1 1 0 0 0 1 1 0 0 1 0 --------------------- 0 1 1 1 0 1 1 0 --------------------- ~ A ( Complement ) 0 1 0 1 0 1 1 0 --------------------- 1 0 1 0 1 0 0 1 ---------------------
  • 55. 55© NIELIT Gorakhpur Centre. Let A=0x56 A << 2 ( Left Shift ) 0 1 0 1 0 1 1 0 << 2  0 1 0 1 0 1 1 0 0 0 ( 0x158 ) A >> 2 ( Right Shift ) 0 1 0 1 0 1 1 0 >> 1  0 1 0 1 0 1 1 ( 0x2B) NOTE:  For multiply given number by two, left shifted by one time, i.e., a<<1  For divide given number by two, right shifted by one time, i.e., a>>1
  • 56. 56© NIELIT Gorakhpur Centre. Example: void main() { int x,y; clrscr(); printf(“Enter value of x:”); scanf(“%d”,&x); y=x<<3; printf(“Left shifted data=%d”,y); printf(“Right shifted data=%d”,x>>3); } Output: Enter value of x:16 Left shifted data=128 Right shifted data=2
  • 57. 57© NIELIT Gorakhpur Centre.  Printf() Function : Printf() function is use to display something on the console or to display the value of some variable on the console. The general syntax for printf() function is as follows printf(<”format specifier”>,<list of variables>);  Scanf() Function : Scanf() function is use to read data from keyboard and to store that data in the variables. The general syntax for scanf() function is as follows. Scanf(“format specifier”,&variable);
  • 58. 58© NIELIT Gorakhpur Centre. #include <stdio.h> #include <conio.h> void main() { printf(“Welcome to NIELIT"); getch(); } Description of the above C Program:  #include <stdio.h> includes the standard input output library functions. The printf() function is defined in stdio.h .  #include <conio.h> includes the console input output library functions. The getch() function is defined in conio.h file.  void main() The main() function is the entry point of every program in c language. The void keyword specifies that it returns no value.  printf() The printf() function is used to print data on the console.  getch() The getch() function asks for a single character. Until you press any key, it blocks the screen.
  • 59. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 59 © NIELIT Gorakhpur Centre. • If Statement • If-else Statement • Nested If-else Statement • Switch Case
  • 60. 60© NIELIT Gorakhpur Centre. Decision Making / Conditional Statements: C program executes program sequentially. Sometimes, a program requires checking of certain conditions in program execution.  Followings are the different conditional statements used in C.  If Statement  If-else Statement  Nested If-else Statement  Switch Case
  • 61. 61© NIELIT Gorakhpur Centre.  If Statement: This is a conditional statement used in C to check condition or to control the flow of execution of statements. Syntax: if (condition) { statements; } In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then program skips the braces.
  • 62. 62© NIELIT Gorakhpur Centre.  Example of If Statement: #include<stdio.h> main( ) { int qty, dis = 0 ; float rate, tot ; printf ( "Enter quantity and rate " ) ; scanf ( "%d %f", &qty, &rate) ; if ( qty > 1000 ) dis = 10 ; tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ; printf ( "Total expenses = Rs. %f", tot ) ; }
  • 63. 63© NIELIT Gorakhpur Centre.  If-Else Statement: This is also one of the most useful conditional statement used in C to check conditions. Syntax: if(condition) { true statements; } else { false statements; } In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then it executes the else part of a program.
  • 64. 64© NIELIT Gorakhpur Centre. Example: main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) { hra = bs * 10 / 100 ; da = bs * 90 / 100 ; } else { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; }
  • 65. 65© NIELIT Gorakhpur Centre.  Nested If-Else Statement: It is a conditional statement which is used when we want to check more than 1 conditions at a time in a same program. The conditions are executed from top to bottom checking each condition whether it meets the conditional criteria or not. Syntax: if(condition) { if(condition) { statements; } else { statements; } } else { statements; } In this syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and again checks the next condition. If it is true then it executes the block of statements associated with it else executes else part.
  • 66. 66© NIELIT Gorakhpur Centre. Example: #include<stdio.h> main( ) { int i ; printf ( "Enter either 1 or 2 " ) ; scanf ( "%d", &i ) ; if ( i == 1 ) printf ( "You are Welcome !" ) ; else { if ( i == 2 ) printf ( “I m great" ) ; else printf ( “I m the best !" ) ; } }
  • 67. 67© NIELIT Gorakhpur Centre. Switch case Statement : This is a multiple or multi-way branching decision making statement. When we use nested if-else statement to check more than 1 conditions then the complexity of a program increases in case of a lot of conditions. So to overcome this problem, C provides 'switch case‘. Switch case checks the value of a expression against a case values, if condition matches the case values then the control is transferred to that point.
  • 68. 68© NIELIT Gorakhpur Centre. Example : In this syntax, switch, case, break are keywords. expr1, expr2 are known as 'case labels.' Break statement causes an exit from switch statement. Default case is optional case. When neither any match found, it executes Syntax: switch (expression) { case expr1: statements; break; case expr2: statements; break; . . case expr N: statements; break; default: statements; break; } Note: The break statement is needed so that once a case has been executed, it will skip all the other cases and go outside the switch statement. If the break statement is omitted, the execution will be carried out to the next alternatives until the next break statement is found.
  • 69. 69© NIELIT Gorakhpur Centre. #include<stdio.h> #include<conio.h> main() { int x,i; clrscr(); printf("enter any digit no."); scanf("%d",&x); for(i=0;x!=0;x/=10) i++; switch(i) { case 1: printf("One Digit No."); break; case 2: printf("Two Digit No."); break; case 3: printf("Three Digit No."); break; case 4: printf("Four Digit No."); break; case 5: printf("Five Digit No."); break; default: printf("Wrong Input"); } getch(); } Example of Switch Case
  • 70. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 70 © NIELIT Gorakhpur Centre. • While Loop • For Loop • Do while Loop • Break and Continue Statement • Goto Statement
  • 71. 71© NIELIT Gorakhpur Centre. 'A Loop' is a part of code of a program which is executed repeatedly. A Loop is used using condition. The repetition is done until condition becomes condition true. A loop declaration and execution can be done in following ways.  Check condition to start a loop  Initialize loop with declaring a variable.  Executing statements inside loop.  Increment or decrement of value of a variable.  Types of looping statements : Basically, the types of looping statements depends on the condition checking mode. Condition checking can be made in two ways as : Before loop and after loop. So, there are 2(two) types of looping statements.  Entry Controlled Loop  Exit Controlled Loop
  • 72. 72© NIELIT Gorakhpur Centre.  Entry controlled loop : In such type of loop, the test condition is checked first before the loop is executed. Some common examples of this looping statements are :  while loop  for loop  Exit controlled loop : In such type of loop, the loop is executed first. Then condition is checked after block of statements are executed. The loop executed atleast one time compulsorily. Some common example of this looping statement is :  do-while loop
  • 73. 73© NIELIT Gorakhpur Centre.  While loop : This is an entry controlled looping statement. It is used to repeat a block of statements until condition becomes true. Syntax: while(condition) { statements; increment/decrement; } In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the loop and executes the block of statements associated with it. At the end of loop increment or decrement is done to change in variable value. This process continues until test condition satisfies.
  • 74. 74© NIELIT Gorakhpur Centre.  Example of While loop : #include<stdio.h> #include<conio.h> main() { int i=1; clrscr(); while(i<=10) { printf("n%d",i); i++; } getch(); } False True
  • 75. 75© NIELIT Gorakhpur Centre.  For loop : This is an entry controlled looping statement. In this loop structure, more than one variable can be initialized. One of the most important feature of this loop is that the three actions can be taken at a time like variable initialization, condition checking and increment/decrement. Syntax: for(initialization; test-condition; incre/decre) { statements; } Features :  More concise  Easy to use  Highly flexible  More than one variable can be initialized.  More than one increments can be applied.  More than two conditions can be used.
  • 76. 76© NIELIT Gorakhpur Centre.  Example of For loop : #include<stdio.h> #include<conio.h> main() { int i; clrscr(); for(i=1;i<=10;i++) printf("n%d",i); getch(); } False True
  • 77. 77© NIELIT Gorakhpur Centre.  Do-While loop: This is an exit controlled looping statement. Sometimes, there is need to execute a block of statements first then to check condition. At that time such type of a loop is used. In this, block of statements are executed first and then condition is checked. Syntax: do { statements; (increment/decrement); } while(condition); In above syntax, the first the block of statements are executed. At the end of loop, while statement is executed. If the resultant condition is true then program control goes to evaluate the body of a loop once again. This process continues till condition becomes true. When it becomes false, then the loop terminates.
  • 78. 78© NIELIT Gorakhpur Centre.  Example of do while loop : #include <stdio.h> main() { int digit = 0; do { printf(“%d”, digit++); }while(digit<=9); }False True
  • 79. 79© NIELIT Gorakhpur Centre. Nested loop A loop inside another loop is known as nested loop. We can write any loop inside any loop in c i.e. we can write for loop inside the loop or while loop or do while loop etc. Syntax: do { statements; statements; | | do { statements; }while(expression); } } while(expression) for(initialization; test; increment) { statements; for(initialization; test; increment) { statements; | | | for(initialization; test; increment) { statements; } }} while(expression) { statements; | | | while(expression) { statements; } }
  • 80. 80© NIELIT Gorakhpur Centre. Example : Print the table from 1 to 10. #include<stdio.h> #include<conio.h> main() { int i,j; clrscr(); for(i=1;i<=10;i++) { for(j=1;j<=10;j++) printf("%2dt",i*j); printf("n"); } getch(); } 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 10 0 Output
  • 81. 81© NIELIT Gorakhpur Centre. Example : Print the following pattern. (with the help of while loop) #include<stdio.h> #include<conio.h> main() { int r=1,c; while (r<=5) { c=1; while(c<=r) { printf(“*”); c++; } r++; printf("n"); } getch(); } * ** *** **** ***** Output
  • 82. 82© NIELIT Gorakhpur Centre. Example : Print the following pattern. (with the help of for loop) #include<stdio.h> #include<conio.h> main() { int r,c; clrscr(); for(r=1;r<=5;r++) { for(c=5;c>=r;c--) printf(“*”); printf("n"); } getch(); } ***** **** *** ** * Output
  • 83. 83© NIELIT Gorakhpur Centre. Example : Print the Pascal Triangle. (with the help of for loop) #include<stdio.h> void main() { int x,y,r,c,s,l=1; for(r=1;r<=5;r++) { for(s=5;s>r;s--) printf("%c",32); x=l; for(c=1;c<=r;c++) { y=(x%10); printf(" %d",y); x/=10; } printf("n"); l=l*11; }} 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Output
  • 84. 84© NIELIT Gorakhpur Centre. Example : Print the following pattern. (with the help of for loop) #include<stdio.h> main() { int i,j,k=71,l=-1,s; for(i=1;i<=7;i++) { for(j=65;j<=k;j++) printf("%c",j); if(i==1) j--; else for(s=l;s>=1;s--) printf(" "); for(j--;j>=65;j--) printf("%c",j); printf("n"); l=l+2; k--; } } Output A B C D E F G F E D C B A A B C D E F F E D C B A A B C D E E D C B A A B C D D C B A A B C C B A A B B A A A
  • 85. 85© NIELIT Gorakhpur Centre.  Break Statement : Sometimes, it is necessary to exit immediately from a loop as soon as the condition is satisfied. When break statement is used inside a loop, then it can cause to terminate from a loop. The statements after break statement are skipped.  Continue Statement : Sometimes, it is required to skip a part of a body of loop under specific conditions. So, C supports 'continue' statement to overcome this problem. The working structure of 'continue' is similar as that of that break statement but difference is that it cannot terminate the loop. Continue statement simply skips statements and continues next iteration. Syntax: break; while(condition) { - - - - - - - - - - - break; - - - - - - } Syntax: continue; while(condition) { - - - - - - - - - - - Continue; - - - - - - - - }
  • 86. 86© NIELIT Gorakhpur Centre. Example of Break Statement Example of Continue Statement #include <stdio.h> main () { int a = 10; while( a < 20 ) { printf("value of a: %dn", a); a++; if( a > 15) break; } } #include <stdio.h> main () { int a = 10; do { if( a == 15) { a = a + 1; continue; } printf("value of a: %dn", a); a++; } while( a < 20 ); }
  • 87. 87© NIELIT Gorakhpur Centre. It is a well known as ‘jumping statement’. It is primarily used to transfer the control of execution to any place in a program. It is useful to provide branching within a loop. When the loops are deeply nested at that if an error occurs then it is difficult to get exited from such loops. Simple break statement cannot work here properly. In this situations, goto statement is used. Syntax : goto [expr]; while(condition) { - - - - - - - - - - - goto label; - - - - - - label: } while(condition) { - - - - - label: - - - - - - - - goto label; - - - }
  • 88. 88© NIELIT Gorakhpur Centre. Example: #include <stdio.h> #include<conio.h> main() { int x,i=0; clrscr(); printf("enter any digit no."); scanf("%d",&x); abc: if(x!=0) { i++; x/=10; goto abc; } else printf("number=%d Digit No.",i); getch(); }
  • 89. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 89 © NIELIT Gorakhpur Centre. • What is Function • Built in Function • User Defined Function • Types of Function • Calling of Function • Recursion
  • 90. 90© NIELIT Gorakhpur Centre. A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. The function is a self contained block of statements which performs a coherent task of a same kind.  Types of functions :  Build in Functions  User Defined Functions
  • 91. 91© NIELIT Gorakhpur Centre.  Built in Functions : These functions are also called as ‘Library Functions'. These functions are provided by system. These functions are stored in library files. Example: scanf( ) printf( ) strcpy( ) strlwr( ) strcmp( ) strlen( ) strcat( )
  • 92. 92© NIELIT Gorakhpur Centre.  User Defined Functions : The functions which are created by user for program are known as 'User defined functions'. Advantages :  It is easy to use, It reduces the size of a program.  Debugging is more suitable for programs.  It is easy to understand the actual logic of a program.  Highly suited in case of large programs.  By using functions in a program, it is possible to construct modular and structured programs.
  • 93. 93© NIELIT Gorakhpur Centre. Syntax: // Function definition <return_type> <function_name>(argu_list); void main() { // Function Call <function_name>(<arguments>); } // Function declaration <return_type><function_name>(<argu_list>) { <function_body>; }
  • 94. 94© NIELIT Gorakhpur Centre.  FUNCTION TYPES: Function with No arguments and No return value Function with arguments but No return value Function with No arguments but Returns a value Function with arguments and return values Function with multiple return values
  • 95. 95© NIELIT Gorakhpur Centre. An argument is an entity used to pass the data from calling function to the called function. There are two types of arguments: 1. Formal 2. Actual Formal Arguments are the arguments available in the function definition. They are preceded by their own data types. Actual Arguments are available in the function call.
  • 96. 96© NIELIT Gorakhpur Centre. There are two ways to call a function (used when invoking functions)  Call by Value:  Copy of argument pass to a function  Changes in function do not effect original  Call by reference:  Passes original arguments to a function  Changes in function effect original
  • 98. 98© NIELIT Gorakhpur Centre. #include <stdio.h> #include<conio.h> int prime (int); main() { int x,y; clrscr(); printf("enter any number"); scanf("%d",&x); y=prime(x); if(y==1) printf("Prime No."); else printf("Not Prime Number"); getch(); } int prime (int z) { int i=2; if(z==1 | | z==2) return(1); else while(i<z) { if(z%i==0) return(0); else i++; } if(i==z) return(1); } Example: To check any number is prime or not.
  • 99. 99© NIELIT Gorakhpur Centre. Example: To find the factorial value of any no. #include<stdio.h> #include<conio.h> int fact (int); main() { int x,n; clrscr(); printf("enter any number"); scanf("%d",&x); n=fact(x); printf(n); getch(); } int fact (int y) { int i; for(i=1;y>=1;y--) i=i*y; return(i); }
  • 100. 100© NIELIT Gorakhpur Centre.  A function cannot be defined within another function.  All function definitions must be disjoint.  Nested function calls are allowed.  A calls B, B calls C, C calls D, etc.  The function called last will be the first to return.  A function can also call itself, either directly or in a cycle.  A calls B, B calls C, C calls back A.  Called recursive call or recursion.
  • 101. 101© NIELIT Gorakhpur Centre. Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to "repeat the process".
  • 102. 102© NIELIT Gorakhpur Centre.  Either directly.  X calls X.  Cyclically in a chain.  X calls Y, and Y calls X. Used for repetitive computations in which each action is stated in terms of a previous result. For a problem to be written in recursive form, two conditions are to be satisfied:  It should be possible to express the problem in recursive form.  The problem statement must include a stopping condition
  • 103. 103© NIELIT Gorakhpur Centre.  Mechanism of Execution:  When a recursive program is executed, the recursive function calls are not executed immediately.  They are kept aside (on a stack) until the stopping condition is encountered.  The function calls are then executed in reverse order. void main( ) { - - - - - - - - - - main( ); - - - - - - - - - - - - - - - }
  • 104. 104© NIELIT Gorakhpur Centre. /* PRIME NUMBER USING RECURSION */ #include <stdio.h> #include<conio.h> int prime (int); main() { int no,i; printf("enter any number"); scanf("%d",&no); i=prime(no); if(i==1) printf("Prime Number"); else printf("Not Prime Number"); getch(); } prime (int n) { static int x=2; if(x==n) return(1); if(n%x==0) return(0); else { x++; prime(n); } }
  • 105. 105© NIELIT Gorakhpur Centre. /* Convert any decimal number to its binary equivalent using Recursion */ #include <stdio.h> #include<conio.h> void change (int, int); main() { int n,base; clrscr(); printf("enter the number and base"); scanf("%d%d",&n,&base); change(n,base); getch(); } void change(int n1, int b) { int x; if(n1==0) return; x=n1%b; change(n1/b,b); printf("%d",x); }
  • 106. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 106 © NIELIT Gorakhpur Centre.
  • 107. 107© NIELIT Gorakhpur Centre. Pointer is a variable which holds the memory address of another variable. Pointers are represented by '*'. It is a derive data type in C. Pointer returns the value of stored address. Syntax: <data_type> *pointer_name; int *j; int i = 5; In above syntax, * = variable pointer_name is a pointer variable. pointer_name requires memory location pointer_name points to a variable of type data type.
  • 108. 108© NIELIT Gorakhpur Centre. There are two C operators that are necessary when using pointer variables. the address operator returns the address of a variable Example: int x; int *ptr = &x; The declaration of ptr initializes the variable ptr = &x; Suppose the address of the variable x is 65524. ptr holds the address of x. We say ptr “points” to x. We will apply the & operator only to variables. e.g. &77 or &(x+1) are not valid. & 65524 x ptr
  • 109. 109© NIELIT Gorakhpur Centre. * 5 65524 x ptr Example: int x; int *ptr; ptr=&x ; To assign the value “5” to the variable x in C: x = 5; We can use the “ * ” operator to indirectly reference x. We can assign “5” to x by: *ptr=5; Here we use the fact that “ptr” points to integer values. means "a pointer to" and is called an indirection operator or dereferencing operator, since a pointer "indirectly" references a value in a storage location.
  • 110. 110© NIELIT Gorakhpur Centre. /*Swap the values of two variable using pointer. */ #include <stdio.h> void swap(int * , int *); void main(void) { int x = 1; int y = 2; swap(&x,&y); /* pass the addresses of x and y */ printf(“x = %d , y = %d n”,x,y); /* prints x = 2 , y = 1 */ } void swap(int *ptrX , int *ptrY) /* pointer variables */ { int temp = *ptrX; *ptrX = *ptrY ; *ptrY = temp; return; }
  • 111. 111© NIELIT Gorakhpur Centre.  Features of Pointer : Pointer variable should have prefix '*‘. Combination of data types is not allowed. Pointers are more effective and useful in handling arrays. It can also be used to return multiple values from a function using function arguments. It supports dynamic memory management. It reduces complexity and length of a program. It helps to improve execution speed that results in reducing program execution time.
  • 112. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 112 © NIELIT Gorakhpur Centre. • Automatic storage class • Register storage class • Static storage class • External storage class
  • 113. 113© NIELIT Gorakhpur Centre. 'Storage' refers to the scope of a variable and memory allocated by compiler to store that variable. Scope of a variable is the boundary within which a variable can be used. Storage class defines the the scope and lifetime of a variable.  Functions of storage class:  To determine the location of a variable where it is stored ?  Set initial value of a variable or if not specified then setting it to default value.  Defining scope of a variable.  To determine the life of a variable.
  • 114. 114© NIELIT Gorakhpur Centre.  Types of Storage Classes : Storage classes are categorized in 4 (four) types as,  Automatic storage class  Register storage class  Static storage class  External storage class
  • 115. 115© NIELIT Gorakhpur Centre.  Automatic Storage Class: Automatic variables are declared inside a function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited, hence the name automatic. Automatic variables are therefore private to the function in which they are declared. Because of this property, automatic variables are also referred to as local or internal variable. Keyword : auto Storage Location : Main memory Initial Value : Garbage Value Life : Control remains in a block where it is defined. Scope : Local to the block in which variable is declared. Syntax : auto [data_type] [variable_name]; Example : auto int a;
  • 116. 116© NIELIT Gorakhpur Centre.  Register Storage Class : We can tell the compiler that a variable should be kept in one of the machine’s register instead of keeping in the memory where normal variables are stored. Since a register access is much faster than a memory access. Keeping frequently accessed variables in the register will lead to faster execution of program. Keyword : register Storage Location : CPU Register Initial Value : Garbage Life : Local to the block in which variable is declared. Scope : Local to the block. Syntax : register [data_type] [variable_name]; Example : register int a;
  • 117. 117© NIELIT Gorakhpur Centre.  Static Storage Class : As the name suggest, the value of static exist until the end of the program. A static variable may be either an internal type or an external type depending on the piece of declaration. Internal static variables are those which are declared inside a function. A static variable is initialized only once, when the program is compiled. It is never initialized again. An external static variable is declared outside that program. The difference between a static external variable and simple external variable is that the static external variable is available only within the file where it is defined while the simple external variables can be accessed by other files. Keyword : static Storage Location : Main memory Initial Value : Zero and can be initialize once only. Life : depends on function calls and the whole application or program. Scope : Local to the block. Syntax : static [data_type] [variable_name]; Example : static a;
  • 118. 118© NIELIT Gorakhpur Centre.  External Storage Class : Variables that are both alive and active throughout the entire program are known as external variables. They are also known as global variables. Unlike function in the program external variables are declared outside a function. Keyword : extern Storage Location : Main memory Initial Value : Zero Life : Until the program ends. Scope : Global to the program. Syntax : extern [data_type] [variable_name]; Example : extern int a;
  • 119. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 119 © NIELIT Gorakhpur Centre.
  • 120. 120© NIELIT Gorakhpur Centre. Preprocessor processes source program before it is passed to compiler. Produce a source code file with the preprocessing commands properly sorted out. Preprocessor commands are known as directives. Preprocessor provides certain features. These features are also known as preprocessor directives. Preprocessor directives start with #sign. Preprocessor directives can be placed any where in the source program. Note: Place it at start of the program. Each preprocessor directive must be on it’s own line.
  • 121. 121© NIELIT Gorakhpur Centre.  Preprocessor Directives  Macro Expansion  File Inclusion  Conditional compilation  Miscellaneous directives
  • 122. 122© NIELIT Gorakhpur Centre.  Macro Expansion  #define directive is known as macro expansion. Definition: #define PI 3.1415 General Form: #define macro_template macro_expansion #define macro_name char_sequence  Preprocessor search for macro definition.  After finding #define directive it search entire program for macro_template.  Replace each macro_template with macro_expansion.  Best Practice: Use capital letters for macro template.  Do not use semicolon ‘;’
  • 123. 123© NIELIT Gorakhpur Centre.  Benefits of Macro  To write efficient programs.  To increase readability of programs.  Variable Vs Macro_template  Compiler can generate faster and compact code for constant than it can for variables.  When you are dealing with a constant, why use variable.  A variable may change in the program.
  • 124. 124© NIELIT Gorakhpur Centre. Replace operator: #define AND && #define OR | | Replace condition: #define EXCELLENT (a>=75) Replace statement: #define ALERT printf(“Security Alert”);  Defined macro name can be used as a part of definition of other macro name. #define MIN 1 #define MAX 9 #define MIDDLE (MAX-MIN)/2  No text substitution occur if the identifier is within a quoted string.
  • 125. 125© NIELIT Gorakhpur Centre.  Macro With Arguments Macros can have arguments, same as functions #define ISEXCELLENT(x) (x >= 75) #define ISLOWER(x) (x>=97 && x<=122) Macros expansions should be enclosed within parenthesis. #define ISLOWER(x) (x>=97 && x<=122) if(!ISLOWER(‘a’)); Use ‘’ to split macro in multiple line. #define HLINE for(i=0; i < 40; i++) printf(“_”);
  • 126. 126© NIELIT Gorakhpur Centre. Macro Function Macro is Preprocessed Function is Compiled No Type Checking Type Checking is Done Code Length Increases Code Length remains Same Use of macro can lead to side effect No side Effect Just the replacement of the code. Passing arguments, doing calculation, returning results. (More serious work). Macros make the program run faster. Function calls and return make the program slow. Before Compilation macro name is replaced by macro value During function call , Transfer of Control takes place Useful where small code appears many time Useful where large code appears many time Generally Macros do not extend beyond one line Function can be of any number of lines Macro does not Check Compile Errors Function Checks Compile Errors
  • 127. 127© NIELIT Gorakhpur Centre.  Causes one file to be included in another. #include <filename> //OR #include “filename”  <filename>: search the directory on current directory only.  “filename”: search the directory on current directory and specified directories as specified in the include search path.  Divide a program in multiple files. o Each file contains related functions.  Some functions or macros are required in each program. o Put them in a file (Library). o Include them in program that need them.  Nested includes: Included file may have more included files in it.
  • 128. 128© NIELIT Gorakhpur Centre.  Write single program to run on different environments.  #ifdef – if defined  #endif – end if  #else – else  #ifndef – in not defined  #if – if  #elif – else if
  • 129. 129© NIELIT Gorakhpur Centre. #ifdef & #endif General form: #ifdef macroname statement sequence #endif  if macroname has been defined using #define the code between #ifdef & #endif will execute. #else  Use #else with #ifdef same as else with if. General-form: #ifdef macroname statement sequence #else statement sequence #endif
  • 130. 130© NIELIT Gorakhpur Centre. #ifndef  #ifndef is just opposite to #ifdef #ifndef __file_h #define __file_h  #if directive test whether an expression evaluates to nonzero value or not.  #elif used same as else if.
  • 131. 131© NIELIT Gorakhpur Centre. Where conditional compilation?  Instead of comments. o Nested comments not allowed in C.  Run the same code on different environment.  To avoid multiple declaration error.
  • 132. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 132 © NIELIT Gorakhpur Centre. • Single/One dimensional • Multidimensional • Advantages and Disadvantages • String and Character Array
  • 133. 133© NIELIT Gorakhpur Centre. Array is a collection or group of similar data type elements stored in contiguous memory location. The individual data items can be characters, integers, floating points numbers and so on . Here contiguous memory allocation means array occupies contiguous bytes as needed in the memory.  Types of an Array :  Single / One Dimensional Array  Multidimensional Array
  • 134. 134© NIELIT Gorakhpur Centre.  Single / One Dimensional Array : The array which is used to represent and store data in a linear form is called as 'single or one dimensional array’. Has a unique identifier for each element, called as a subscript or an index. Syntax: <data-type> <array_name> [size]; Example: int a[5]; Memory allocation for Single / One dimensional array A[0] A[1] A[2] A[n] 5 7 2 12 1000 1002 1004 n A[index no.] element Memory address
  • 135. 135© NIELIT Gorakhpur Centre. The array size could also be specified using a symbolic constant: #define ARRAY_SIZE 25 int a[ARRAY_SIZE]; We can initialize array elements in declaration statements; e.g., int x[5] = {1, 2, 3, 4, 5}; int x[ ] = {2, 4, 6, 8}; /*This array has 4 elements*/ We cannot specify more initial values than there are array elements, but we can specify fewer initial values, and the remaining elements will be initialized to 0. e.g., int y[10] = { 2 }; double x[250 ] = { 0 };
  • 136. 136© NIELIT Gorakhpur Centre. Given that the array x is declared as: int x[250]; To initialize a large array to a nonzero value - say 5, we can use a loop. e.g., for (k=0; k<=249; k++) x[k] = 5; k is a subscript Note: when referencing a particular element of an array use square brackets, not parenthesis or curly braces. A subscript value for an array element can be specified as any integer expression.
  • 137. 137© NIELIT Gorakhpur Centre. There are number of operations that can be performed on arrays. These operations include :  Transversal  Insertion  Search  Deletion  Merging  Sorting  Selection Sort  Bubble Sort  Insertion Sort
  • 138. 138© NIELIT Gorakhpur Centre.  Example of traversal an array. #include<stdio.h> #include<conio.h> main() { int x[10], i; for(i=0;i<10;i++) { printf(“Enter the elements in array: t”); scanf(“%d”, &x[i]); } printf(“The Traverse of array is:n”); for(i=0;i<10;i++) printf(“%dn”, x[i]); getch(); }
  • 139. 139© NIELIT Gorakhpur Centre.  Example of insert any new element of another existing of an array. #include<stdio.h> #include<conio.h> main() { int a[10],s,n,i,j,n1; clrscr(); printf("enter the size of array"); scanf("%d",&s); for(i=0;i<s;i++) { printf("enter the element"); scanf("%d",&a[i]); } printf("enter value which afterbe inserted"); scanf("%d",&n); for(i=0;i<s;i++) { if(a[i]==n) break; } if(i==s) printf("Element not found"); for(j=s-1;j>i;j--) a[j+1]=a[j]; printf("enter the no. to be inserted"); scanf("%d",&n1); a[i+1]=n1; for(i=0;i<=s;i++) printf("n%d",a[i]); getch(); }
  • 140. 140© NIELIT Gorakhpur Centre.  Example of search any element in an array. #include<stdio.h> main() { int x[5], ele, i; printf("nEnter the values :"); for (i = 0; i < 5; i++) scanf("%d", &x[i]); printf("nEnter the elements to be searched :"); scanf("%d", &ele); for (i=0;i < num && ele != x[i];i++) i++; if (i < 5) printf("Number found at the location = %d", i + 1); else printf("Number not found"); }
  • 141. 141© NIELIT Gorakhpur Centre.  Example of deletion in an array. #include <stdio.h> main() { int x[5], p, c, n; printf("Enter the elementsn”); for ( c=0 ; c<5 ; c++ ) scanf("%d", &x[c]); printf("Enter the location where you wish to delete elementn"); scanf("%d", &position); if ( p>=5 ) printf("Deletion not possible.n"); else { for (c=p -1 ; c < 5-1 ; c++ ) x[c] = x[c+1]; printf("Resultant array isn"); for( c=0 ; c <5-1 ; c++ ) printf("%dn", x[c]); }}
  • 142. 142© NIELIT Gorakhpur Centre. #include<stdio.h> main() { int x[5],y[5],z[10],i,j,k; printf("nEnter no of elements in 1st array :"); for(i=0; i<5; i++) scanf("%d", &x[i]); printf("nEnter no of elements in 2nd array :"); for(i=0; i<n2;i++) scanf("%d", &arr2[i]); i=0; j=0; k=0; while (i<5 && j<5) { if(x[i]<=y[j]) { z[k]=x[i]; i++; k++; }  Example of merging in an array. else { z[k]=y[j]; k++; j++; } } while (i<n1) { z[k]=x[i]; i++; k++; } while (j < n2) { z[k]=y[j]; k++; j++; } printf("nMerged array is :"); for (i=0; i<10;i++) printf("%d ",z[i]); }
  • 143. 143© NIELIT Gorakhpur Centre.  Example sorting in an array. (Selection Sort) #include<stdio.h> #include<conio.h> main() { int x[5],i,j,t; clrscr(); printf("nenter the array element"); for(i=0;i<5;i++) scanf("%d",&x[i]); for(i=0;i<4;i++) for(j=i+1;j<5;j++) if(x[i]>x[j]) { t=x[i]; x[i]=x[j]; x[j]=t; } for(i=0;i<5;i++) printf("n%d",x[i]); getch(); } 0 1 2 3 4 5 7 2 12 6 i [index no.] x [element] Output 0 1 2 3 4 2 5 6 7 12 i [index no.] x [element] Input
  • 144. 144© NIELIT Gorakhpur Centre.  Example sorting in an array. (Bubble Sort) #include<stdio.h> #include<conio.h> void main() {int i,j,temp,a[5]; clrscr(); printf("Enter the array of a"); for(j=0;j<5;j++) scanf("%d",&a[j]); for(i=0;i<4;i++) for(j=0;j<5-i;j++) if (a[j]>a[j+1]) {temp=a[j]; a[j]=a[j+1]; a[j+1]=temp;} for(j=0;j<5;j++) printf("n%d",a[j]); getch(); } 0 1 2 3 4 4 3 1 5 2 i [index no.] a [element] Output 0 1 2 3 4 1 2 3 4 5 i [index no.] a [element] Input
  • 145. 145© NIELIT Gorakhpur Centre.  Example sorting in an array. (Insertion Sort) #include<stdio.h> #include<conio.h> main() { int arr[5],i,j,k,temp; clrscr(); for(i=0;i<5;i++) { printf("nenter the array element"); scanf("%d",&arr[i]); } for(i=1;i<5;i++) for(j=0;j<=i-1;j++) if(arr[i]<arr[j]) { temp=arr[i]; for(k=i-1;k>=j;k--) arr[k+1]=arr[k]; arr[j]=temp; break; } for(i=0;i<=4;i++) printf("n%d",arr[i]); getch();} 0 1 2 3 4 4 3 1 5 2 i [index no.] arr [element] Output 0 1 2 3 4 1 2 3 4 5 i [index no.] arr [element] Input
  • 146. 146© NIELIT Gorakhpur Centre.  Multidimensional Array : The array which is used to represent and store data in a tabular form is called as ‘multidimensional array.' Such type of array specially used to represent data in a matrix form. The following syntax is used to represent multidimensional array. Syntax: <data-type> <array_name> [row_size][column_size]; Example: int a[3][3]; j column i row a[i][j] a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] Memory allocation for Multidimensional array
  • 147. 147© NIELIT Gorakhpur Centre. Notation of Multidimensional Array B = 51, 52, 53 54, 55, 56 Algebraic notation Col 1 Col 2 Col 3 Row 1 Row 2 int b[2][3] = {(51, 52, 53),(54, 55, 56)}; Array type Array name Two rows Three columns First row second row C notation
  • 148. 148© NIELIT Gorakhpur Centre.  Example to add two matrix entered by the user and print it. #include<stdio.h> #include<conio.h> void main() { int a[3][3],b[3][3],c[3][3]; int i,j; clrscr(); printf(“enter the elements in both the array:”); for(i=0 ; i<3 ; i++) for(j=0 ; j<3 ; j++) scanf(“%d”,&a[i][j]); for(i=0 ; i<3 ; i++) for(j=0 ; j<3 ; j++) scanf(“%d”,&b[i][j]); for(i=0 ; i<3 ; i++) { for(j=0 ; j<3 ; j++) { c[i][j]=a[i][j]+b[i][j]; printf(“%d”,c[i][j]); } printf(“n”); } getch(); }
  • 149. 149© NIELIT Gorakhpur Centre.  Example to transpose any matrix. #include<stdio.h> #include<conio.h> void main() { int a[3][3], i,j; clrscr(); printf(“enter the elements in the array”); for(i=0 ; i<3 ; i++) for(j=0 ; j<3 ; j++) scanf(“%d”,&a[i][j]); for(j=0 ; i<3 ; i++) { for(i=0 ; j<3 ; j++) printf(“%2d”,a[j][i]); printf(“n”); } getch(); } 1 2 3 4 5 6 7 8 9 Input 1 4 7 2 5 8 3 6 9 Output
  • 150. 150© NIELIT Gorakhpur Centre.  Example to print diagonal of any matrix. #include<stdio.h> #include<conio.h> void main() { int x[3][3], i,j; clrscr(); printf(“enter the elements in the array”); for(i=0 ; i<3 ; i++) for(j=0 ; j<3 ; j++) scanf(“%d”,&x[i][j]); for(j=0 ; i<3 ; i++) for(i=0 ; j<3 ; j++) if(i==j) printf(“%d”,x[i][j]); getch(); } 1 2 3 4 5 6 7 8 9 Input 1 5 9 Output
  • 151. 151© NIELIT Gorakhpur Centre.  Example to multiplication of two matrix. #include<stdio.h> #include<conio.h> void main() { int a[3][3],b[3][3],k,i,j,s,c[3][3]; clrscr(); printf("enter element in array a"); for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%d",&a[i][j]); printf("enter element in array b"); for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%d",&b[i][j]); for(i=0;i<3;i++) for(j=0;j<3;j++) { s=0; for(k=0;k<3;k++) { s=s+a[i][k]*b[k][j]; c[i][j]=s; } } printf("nMultiplication of Array A * B"); for(i=0;i<3;i++) { printf("n"); for(j=0;j<3;j++) printf("t%d",c[i][j]); } getch(); }
  • 152. 152© NIELIT Gorakhpur Centre.  Limitations of Multidimensional array:  We cannot delete any element from an array.  If we don't know that how many elements have to be stored in a memory in advance, then there will be memory wastage if large array size is specified.
  • 153. 153© NIELIT Gorakhpur Centre.  Advantages:  It is used to represent multiple data items of same type by using only single name.  It can be used to implement other data structures like linked lists, stacks, queues, trees, graphs etc.  Multidimensional arrays are used to represent matrices.  Disadvantages:  We must know in advance that how many elements are to be stored in array.  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.  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.  The elements of array are stored in consecutive memory locations. So insertions and deletions are very difficult and time consuming.
  • 154. 154© NIELIT Gorakhpur Centre. String is a sequence of characters that is treated as a single data item and terminated by null character '0'. Remember that C language does not support strings as a data type. A string is actually one-dimensional array of characters in C language. These are often used to create meaningful and readable programs.  Strings are used in string handling operations such as,  Counting the length of a string.  Comparing two strings.  Copying one string to another.  Converting lower case string to upper case.  Converting upper case string to lower case.  Joining two strings.  Reversing string. Declaration Syntax : char string_nm[size]; Example : char name [15];
  • 155. 155© NIELIT Gorakhpur Centre. Declaring character arrays with a string constant char astring[5]= “Zip!”; char atomic[ ]= “hydrogen”; Declaring a string array with character constants char astring[ ]= {‘Z’, ’i’, ‘p’, ‘!’, ‘0’}; Important In C, you must always terminate a character array with the NULL character, ‘0’ . Therefore, the array size of your character array should be one plus the maximum length of the string you want to store. Example: In the declaration char atomic[ ]= “hydrogen”; “atomic” is an array of nine elements, the last being ‘0’.
  • 156. 156© NIELIT Gorakhpur Centre. String memory representation 0 1 2 3 4 5 6 7 8 h y d r o g e n 0 Index Variable The memory presentation of the string in C is: char atomic[10]= “hydrogen”; Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '0' at the end of the string when it initializes the array.
  • 157. 157© NIELIT Gorakhpur Centre.  Read Strings: To read a string, we can use scanf() function with format specifier %s. char name[50]; scanf("%s",name);  Write Strings : To write a string, we can use printf() function with format specifier %s. char name[50]; scanf("%s",name); printf("%s",name);
  • 158. 158© NIELIT Gorakhpur Centre. C supports a large number of string handling functions. There are numerous functions defined in "string.h" header file. Few commonly used string handling functions are: Function Name Description strlen( ) Returns the length of a string. strlwr () Returns upper case letter to lower case. strupr () Returns lower case letter to upper case. strcat () Concatenates two string. strcmp () Compares two strings. strrev () Reverse a string. strcpy () Copies a string from source to destination.
  • 159. 159© NIELIT Gorakhpur Centre. The gets and puts functions facilitate the transfer of strings between the computer and the standard input/output devices. Each of these functions accepts a single argument. The argument must be a data item that represents a string(e.g. character array). The string may include white space characters. In the case of gets, the string will enter from the keyboard and will terminate with a new line character(i.e. the string will end when the user presses the RETURN key). The gets and puts functions offer simple alternatives to the use of scanf() and printf() for reading and displaying strings: #include<stdio.h> 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; } Note: gets() & puts( ) handle string, both these functions are defined in “stdio.h” header file.
  • 160. 160© NIELIT Gorakhpur Centre.  Example: Find the length of the string. #include <stdio.h> int main() { char s[1000], i; printf("Enter a string: "); gets(s); for(i=0; s[i]!='0'; ++i); printf("Length of string: %d",i); }
  • 161. 161© NIELIT Gorakhpur Centre.  Example: Find the frequency of character in a string. #include <stdio.h> main() { char c[50],ch; int i,count=0; printf("Enter a string: "); gets(c); printf("Enter a character to find frequency: "); scanf("%c",&ch); for(i=0;c[i]!='0';++i) { if(ch==c[i]) ++count; } printf("Frequency of %c = %d", ch, count); }
  • 162. 162© NIELIT Gorakhpur Centre.  Example: Insert any character in given string at any specified position. #include<stdio.h> #include<conio.h> main() { char x[25],c; int i,j,l; clrscr(); printf("enter any string"); gets(x); printf("nenter the position where you want to insert"); scanf("%d",&j); fflush(stdin); printf("nEnter the character"); scanf("%c",&c); l=strlen(x); for(i=l;i>=j-1;i--) x[i+1]=x[i]; x[j-1]=c; puts(x); getch(); }
  • 163. 163© NIELIT Gorakhpur Centre.  Example: Concatenate two string. #include <stdio.h> main() { char s1[100], s2[100], i, j; printf("Enter first string: "); gets(s1); printf("Enter second string: "); gets(s2); for(i=0; s1[i]!='0'; ++i); /* i contains length of string s1. */ for(j=0; s2[j]!='0'; ++j, ++i) { s1[i]=s2[j]; } s1[i]='0'; printf("After concatenation: %s",s1); }
  • 164. 164© NIELIT Gorakhpur Centre. Example: Sort Words in Dictionary Order #include<stdio.h> #include <string.h> main() { int i,j; char str[10][50],temp[50]; printf("Enter 10 words:n"); for(i=0;i<10;++i) gets(str[i]); for(i=0;i<9;++i) for(j=i+1;j<10 ;++j) { if(strcmp(str[i],str[j])>0) { strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } } printf("In Dictionary order: n"); for(i=0;i<10;++i) puts(str[i]); }
  • 165. 165© NIELIT Gorakhpur Centre. Example: Check any input string is palindrome or not. else f=1; } if(f==0) printf("n String is palindrome"); else printf("n String is not palindrome"); getch(); } #include<stdio.h> #include<conio.h> main() { int i,j=0,n,f=0; char x[100]; clrscr(); printf("nenter any string"); gets(x); for(i=0;x[i]!='0';i++); n=i/2; i--; while ((j!=n) && (f==0)) { if(x[j]==x[i]) { j++; i--; }
  • 166. 166© NIELIT Gorakhpur Centre. Example: User define function to reverse any string. void xstrrev(char *p) { char *t=p,c; for(;*p!='0';p++); for(p--;p>t;p--) { c=*p; *p=*t; *t=c; t++; } } #include<stdio.h> #include<conio.h> void xstrrev(char *); main() { char ch[25]; clrscr(); printf("enter any string"); gets(ch); xstrrev(&ch); puts(ch); getch(); }
  • 167. 167© NIELIT Gorakhpur Centre. Example: User define function to copy any string. #include<stdio.h> #include<conio.h> void xstrcpy(char *, char*); main() {char ch[25],ch1[25]; clrscr(); printf("enter any string"); gets(ch); xstrcpy(&ch, &ch1); puts(ch); puts(ch1); getch(); } void xstrcpy(char *p, char *p1) { for(;*p!='0';p++) *p1++=*p; *p1='0'; }
  • 168. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 168 © NIELIT Gorakhpur Centre. • Structure • Nesting of Structure • Union
  • 169. 169© NIELIT Gorakhpur Centre. Structure is user defined data type which is used to store heterogeneous data under unique name. Keyword 'struct' is used to declare structure. The variables which are declared inside the structure are called as 'members of structure'. Syntax: struct structure_nm { <data-type> element 1; <data-type> element 2; - - - - - - - - - - - - - - - - - - - - - <data-type> element n; }struct_var;  Accessing Structure Members : Structure members can be accessed using member operator '.' . It is also called as 'dot operator' or 'period operator'. structure_var.member;
  • 170. 170© NIELIT Gorakhpur Centre. Structures can be used as structures within structures. It is also called as 'nesting of structures'. Syntax: struct structure_nm { <data-type> element 1; <data-type> element 2; - - - - - - - - - - - - - - - - - - - - - <data-type> element n; struct structure_nm { <data-type> element 1; <data-type> element 2; - - - - - - - - - - - - - - - - - - - - - - <data-type> element n; }inner_struct_var; }outer_struct_var;
  • 171. 171© NIELIT Gorakhpur Centre. #include<stdio.h> main() { struct student{ char name[25]; int m1,m2,m3; }; struct student b,b1,b2; printf("enter the name, and marks of three subject's"); scanf("%s%d%d%d",&b.name,&b.m1,&b.m2,&b.m3); printf("enter the name, and marks of three subject's"); scanf("%s%d%d%d",&b1.name,&b1.m1,&b1.m2,&b1.m3); printf("enter the name, and marks of three subject's"); scanf("%s%d%d%d",&b2.name,&b2.m1,&b2.m2,&b2.m3); printf("nNAMEtMark1tMark2tMark3"); printf("n%st%dt%dt%d",b.name,b.m1,b.m2,b.m3); printf("n%st%dt%dt%d",b1.name,b1.m1,b1.m2,b1.m3); printf("n%st%dt%dt%d",b2.name,b2.m1,b2.m2,b2.m3); }
  • 172. 172© NIELIT Gorakhpur Centre. main() { struct emp{ char name[25]; float bs; }s[3]; float hra,da,pf,gs[3]; int i; clrscr(); for (i=0;i<3;i++) { printf("enter the emp_name and salary"); scanf("%s%f",&s[i].name,&s[i].bs); hra=s[i].bs*30/100; da=s[i].bs*15/100; /* Define a structure named employee, the member of the structure are employee name and his/her basic salary. Write a program to calculate the gross salary of such three employee, where hra=30%, da=15% and pf=10%.* / pf=s[i].bs*10/100; gs[i]=(s[i].bs+hra+da)-pf; } printf("nNAMEtGross salary”); for(i=0;i<3;i++) printf("n%st%f",s[i].name,gs[i]); getch(); }
  • 173. 173© NIELIT Gorakhpur Centre. Union is user defined data type used to stored data under unique variable name at single memory location. Syntax of union is similar to structure. But the major difference between structure and union is 'storage.' In structures, each member has its own storage location, whereas all the members of union use the same location. Union contains many members of different types, it can handle only one member at a time. Syntax: union union_name { <data-type> element 1; <data-type> element 2; <data-type> element 3; }union_variable; Example: union techno { int comp_id; char nm; float sal; }tch; Memory Allocation To access union members, we can use the following syntax. tch.comp_id tch.nm tch.sal
  • 174. 174© NIELIT Gorakhpur Centre. #include <stdio.h> #include <conio.h> union item { int a; float b; char ch; }; int main( ) { union item it; it.a = 12; it.b = 20.2; it.ch='z'; clrscr(); printf(“a=%dn",it.a); printf(“b=%fn",it.b); printf(“ch=%cn",it.ch); getch(); return 0; } a= -26426 b= 20.1999 c=z Output As you can see here, the values of a and b get corrupted and only variable c prints the expected result. Because in union, the only member whose value is currently stored will have the memory.
  • 175. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 175 © NIELIT Gorakhpur Centre. Open File Process Data Close File
  • 176. 176© NIELIT Gorakhpur Centre.  A collection of data or information that are stored on a computer known as file  A file is a collection of bytes stored on a secondary storage device.  There are four different types of file  Data Files  Text Files  Program Files  Directory Files  Different types of file store different types of information  A file has a beginning and an end.  We need a marker to mark the current position of the file from the beginning (in terms of bytes) while reading and write operation, takes place on a file.  Initially the marker is at the beginning of the file. We can move the marker to any other position in the file.  The new current position can be specified as an offset from the beginning the file.
  • 177. 177© NIELIT Gorakhpur Centre.  A stream refers to the flow of data (in bytes) from one place to another (from program to file or vice-versa).  There are two types of streams  Text Stream It consists of sequence of characters Each line of characters in the stream may be terminated by a newline character. Text streams are used for textual data, which has a consistent appearance from one environment to another or from one machine to another  Binary Stream It is a series of bytes. Binary streams are primarily used for non-textual data, which is required to keep exact contents of the file.
  • 178. 178© NIELIT Gorakhpur Centre.  ASCII Text files  A text file can be a stream of characters that a computer can process sequentially.  It is processed only in forward direction.  It is opened for one kind of operation (reading, writing, or appending) at any give time.  We can read only one character at a time from a text file.  Binary File  A binary file is a file consisting of collection of bytes.  A binary file is also referred to as a character stream.
  • 179. 179© NIELIT Gorakhpur Centre. Disk I/O Functions High-level Low-level Text Binary Formatted Unformatted UnformattedFormatted
  • 180. 180© NIELIT Gorakhpur Centre. Function Name Operation fopen() Create a new file for use Opens an existing file for use fclose() Closes file which was opened for us fgetc() Read a character from a file fputc() Writes a character to a file fprintf() Writes a set of data values to a file fscanf() Reads a set of data values from a file fseek() Sets the position to a desired point in the file ftell() Gives the current position in the file (in terms of bytes from the start) rewind() Sets the position to the beginning of the file
  • 181. 181© NIELIT Gorakhpur Centre. Mode Meaning r  Open a text file for reading only. If the file doesn’t exist, it returns null. w  Opens a file for writing only.  If file exists, than all the contents of that file are destroyed and new fresh blank file is copied on the disk and memory with same name  If file doesn’t exists, a new blank file is created and opened for writing.  Returns NULL if it is unable to open the file a  Appends to the existing text file  Adds data at the end of the file.  If file doesn’t exists then a new file is created.  Returns NULL if it is unable to open the file. rb  Open a binary file for reading wb  Open a binary file for reading ab  Append to a binary file r+  Open a text file for read/write w+  Opens the existing text file or Creates a text file for read/write a+  Append or create a text file for read/write
  • 183. 183© NIELIT Gorakhpur Centre.  The general format for declaring and opening a file is: FILE *fp; fp=fopen(“filename”,mode”);  Here, the first statement declares the variable fp as a “pointer to the data type FILE”.  The second statement opens the file named filename with the purpose mode and the beginning address of the buffer area allocated for the file is stored by file pointer fp. Note: Any no. of files can be opened and used at a time.
  • 184. 184© NIELIT Gorakhpur Centre.  The closing a file ensures that all outstanding information associated with the file is flushed out from the buffers and all links to the file are broken.  In cases where there is a limit to the no. of files that can be kept open simultaneously, closing of unwanted files help in opening the required ones.  Another instance where we have to close a file is when we want to reopen the same file in different mode.  fclose() returns 0 if the file is closed successfully.  The fcloseall() closes all the files opened previously.  The file is closed using library function fclose() as: fclose(fp);
  • 185. 185© NIELIT Gorakhpur Centre.  To read contents from an existing file, we need to open that file in read mode that means “r” mode  Algorithm to read data from a file:  Open the file in read mode  Read data from the file  Write the data into an output device  Repeat steps 3 and 4 until the end of file occurs  Stop procedure.
  • 186. 186© NIELIT Gorakhpur Centre. #include<stdio.h> void main() { FILE *fp; char ch; fp=fopen(“clear.c”,”r”); if(fp==NULL) print(“Unable to open clear.c”); else { do { ch = getc(fp); putchar(ch); }while(ch!=EOF); fclose(fp); } }
  • 187. 187© NIELIT Gorakhpur Centre.  char *fgets(char *str, int n, FILE *fptr); This function reads a character from the file stream pointed by fptr and stores it in the character array ‘str’ until a new line character (n) is read or end of file (EOF) is reached or n-1 characters have been read.  fputs(const char *str, FILE *fptr); This function writes data to the stream pointed to by fptr, the content of the string stored in ‘str’
  • 188. 188© NIELIT Gorakhpur Centre. #include <stdio.h> main( ) { FILE *fp ; char s[80] ; fp=fopen( “fun.txt", "w" ) ; if ( fp == NULL ) { puts ( "Cannot open file" ) ; exit( ) ; } printf ( "nEnter a few lines of text:n" ) ; while ( strlen ( gets ( s ) ) > 0 ) { fputs ( s, fp ) ; fputs ( "n", fp ) ; } fclose ( fp ) ; } /* Receives strings from keyboard and writes them to file */
  • 189. 189© NIELIT Gorakhpur Centre. #include<stdio.h> main( ) { FILE *fp ; char s[80] ; fp = fopen ( “fun.txt", "r" ) ; if ( fp == NULL ) { puts ( "Cannot open file" ) ; exit( ) ; } while ( fgets ( s, 79, fp ) != NULL ) printf ( "%s" , s ) ; fclose ( fp ) ; } /* Reads strings from the file and displays them on screen */
  • 190. 190© NIELIT Gorakhpur Centre.  A file can be accessed in two ways:  Serial access  Random access  Generally all the text files are considered to be sequential files because lines of text (also called records) are stored in a file  The beginning of each record in a sequential file is unpredictable  Whereas, in random access files, all the records are in same length.  To modify the content of a file, open the file with read and write mode (“r+” or “w+” or “a+”)  Generally “r+” mode is used for both reading and writing operation. The procedure is as follows:  Initialize a pointer variable  Open the file in read and write mode  Read data from file and Print it  Move the file pointer to the place where we have the data to be modified and re-write the new data in that place.  Repeat steps 3 and 4 till the end of file reaches.  Stop the Process
  • 191. 191© NIELIT Gorakhpur Centre. #include<stdio.h> struct stock { int itid, qty; char n[100]; float rate; }it; void main() { FILE *fp; int ch; int r = 0; fp = fopen(“item.c”, “r+”); if(fp==NULL) { printf(“Unable to open item.c”); } else{ do{ fread(&it, sizeof(it),1,fp); printf(“n%d %s %d %f”, it.itid, it.n, it.qty, it.rate); printf(“n Press 1 to change it?”); scanf(“%d”,&ch); if(ch==1) { printf(“n Enter Itemid ItemName Quantity & Price”); scanf(“%d%s%d%f”, &it.itid, it.n, &it.qty, &it.rate); fseek(fp, r*sizeof(it), 0); fwrite(&it, sizeof(it),1,fp); }r++; }while(!feof(fp)); fclose(fp); } }
  • 192. 192© NIELIT Gorakhpur Centre. Using formatted I/O functions, fprintf() and fscanf(), numbers, characters or string can be read from file or written onto file according to our requirement format.  fprintf(): is formatted output function which is used to write integer, float, char or string value to a file. Syntax: fprintf(fp,”control_string”, list_of variables);  fscanf(): is formatted input function which is used to read integer, float, char or string value from a file. Syntax: fscanf(fp,”control_string”, &list_of variables);
  • 193. 193© NIELIT Gorakhpur Centre. void main() { FILE *fp; char name[20]; int roll; char address[20]; float marks; clrscr(); fp=fopen("C:student.txt", "w"); if(fp==NULL) { printf("n File cannot be created or opened."); exit(); } printf("n Enter name of student:t"); gets(name); printf("n Enter roll number of %s:t", name); scanf("%d", &roll); fflush(stdin); /* Program to create a file named student.txt and write name, roll, address and marks of a student to this file*/ printf("n Enter address of %s:t", name); gets(address); printf("n Enter marks of %s:t", name); scanf("%f", &marks); printf("n Now writing data to file..."); fprintf(fp, "Name=%sn Roll=%dn Address=%sn Marks=%.2f", name, roll, address, marks); printf("n Completed"); fclose(fp); getch(); }
  • 194. 194© NIELIT Gorakhpur Centre.  Trying to read beyond the end-of-file mark.  Trying to use a file that has not been opened.  Trying to perform an operation on a file, when the file is opened for another type of operation.  Opening a file with an invalid filename.
  • 195. 195© NIELIT Gorakhpur Centre.  I/O errors can be detected using two status-inquiry library functions: feof() and ferror().  feof(): It is used to test for an end-of-file condition. It takes a FILE pointer as its only argument and returns a nonzero integer value if all of the data from the specified file has been read, and returns zero otherwise. If fp is a pointer to a file that has just been opened for reading, then the statement if(feof(fp)) printf(“End of data”); would display the message “End of data” on reaching the end-of-file condition.  ferror(): This function reports the status of the file indicated. It takes a FILE pointer as its argument and returns a nonzero integer if an error has been detected up to that point, during processing. It returns zero otherwise. So the statement if(ferrorfp)!=0) printf(“An error has occured”); would print the error message, if the reading is not successful.
  • 196. 196© NIELIT Gorakhpur Centre.  ftell() This function takes a file pointer as argument and returns a number of type long, that indicates the current position of the file pointer within the file. This function is useful in saving the current position of a file, which can be used later in the program. Syntax: n=ftell(fp); Here, n would give the relative offset (in bytes) of the current position. This means that n bytes have already been read (or written).
  • 197. 197© NIELIT Gorakhpur Centre.  rewind(): This function takes a file pointer as argument and resets the current position of the file pointer to the start of the file. Syntax: rewind(fp); What these statements do?: rewind(fp); n=ftell(fp); Here, n would be assigned 0, because file position has been set to the start of the file by rewind(). Note: The first byte in the file is numbered as 0, second as 1, and so on.
  • 198. 198© NIELIT Gorakhpur Centre.  fseek(): This function is used to move the file pointer to a desired position within a file. Syntax: fseek(fp,offset,position); where fp is a file pointer, offset is a number or variable data type long, and position is an integer number The offset specifies the number of positions (bytes) to be moved from the location specified by position. The position can have one of the following 3 values: Value Meaning 0 Beginning of file 1 Current Position 2 End of file
  • 199. 199© NIELIT Gorakhpur Centre. The offset may be positive, meaning move forwards, or negative, meaning move backwards. Examples: Statement Meaning fseek(fp, 0L, 0); Move file pointer to beginning of file. (Same as rewind.) fseek(fp, 0L, 1); Stay at the current position. (File pointer is not moved.) fseek(fp, 0L, 2); Move file pointer past the last character of the file. (Go to the end of file.) fseek(fp, m, 0); Move file pointer to (m+1)th byte in the file. fseek(fp, m, 1); Move file pointer forwards by m bytes. fseek(fp, -m, 1); Move file pointer backwards by m bytes from the current position. fseek(fp, -m, 2); Move file pointer backwards by m bytes from the end. (Positions the file pointer to the mth character from the end.)
  • 200. 200© NIELIT Gorakhpur Centre.  fseek()  When the operation is successful, fseek() returns a 0 (zero).  If we attempt to move the file pointer beyond the file boundaries, an error occurs and fseek() returns -1 (minus one).  It is good practice to check whether an error has occurred or not, before proceeding further.
  • 201. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 201 © NIELIT Gorakhpur Centre.
  • 202. 202© NIELIT Gorakhpur Centre. It is a parameter supplied to a program when the program is invoked. This parameter may represent a filename the program should process. For example, if we want to execute a program to copy the contents of a file named X_FILE to another one named Y_FILE, then we may use a command line like C:TC>PROGRAM X_FILE Y_FILE PROGRAM is the filename where the executable code of the program is stored. This eliminates the need for the program to request the user to enter the filenames during execution.
  • 203. 203© NIELIT Gorakhpur Centre. How do these parameters get into the program? We know that every C program should have one main function and that it marks the beginning of the program. But what we have not mentioned so far is that it can also take arguments like other functions. In fact main can take two arguments called argc and argv and the information contained in the command line is passed on to the program through these arguments, when main is called up by the system. The variable argc is an argument counter that counts the number of arguments on the command line. The argv is an argument vector and represents an array of character pointers that point to the command line arguments
  • 204. 204© NIELIT Gorakhpur Centre. The size of this array will be equal to the value of argc. For instance, for the command line given above, argc is three and argv is array of three pointers to strings as shown below: argv[0] PROGRAM argv[1] X_FILE argv[2] Y_FILE In order to access the command line arguments, we must declare the main function and its parameters as follows: main(argc,argv); int argc; char *argv[]; The first parameter in the command line is always the program name and therefore argv[0] always represents the program name.
  • 205. 205© NIELIT Gorakhpur Centre. Example: Command Line Argument #include<stdio.h> #include<conio.h> void main(argc,argv) int argc; char *argv[]; { FILE *fp; int i; char word[15]; clrscr(); fp = fopen(argv[1],"w"); printf("nNo.of arguments in Command line=%dnn",argc); for(i=2;i<argc;i++) fprintf(fp,"%s",argv[i]); fclose(fp); printf("Contents of %s filenn",argv[1]); fp=fopen(argv[1],"r"); for(i=2;i<argc;i++) { fscanf(fp,"%s",word); printf("%s",word); } fclose(fp); printf("nn"); for(i=0;i<argc;i++) printf("%*sn",i*5,argv[i]); getch(); }
  • 206. NIELIT Gorakhpur Centre MMMUT Campus, Gorakhpur (UP), PIN-273010 206 © NIELIT Gorakhpur Centre. • Malloc Function • Calloc Function • Free Function • Realloc Function
  • 207. 207© NIELIT Gorakhpur Centre. The process of allocating memory at runtime is known as dynamic memory allocation. Library routines known as "memory management functions" are used for allocating and freeing memory during execution of a program. These functions are defined in stdlib.h. Function Description malloc() Allocates requested size of bytes and returns a void pointer to the first byte of the allocated space calloc() Allocates space for an array of elements, initialize them to zero and then return a void pointer to the memory free() Release previously allocated memory realloc() Modifies the size of previously allocated space
  • 208. 208© NIELIT Gorakhpur Centre.  malloc( ) The name malloc stands for "memory allocation". The function malloc() used for allocating block of memory at runtime. This function reserves a block of memory of given size and returns a pointer of type void. This means that we can assign it to any type of pointer using typecasting. If it fails to locate enough space it returns a NULL pointer. Syntax: ptr=(datatype*)malloc(byte_size); ptr is pointer of type datatype. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer. Example: x=(int*)malloc(sizeof(int));

Hinweis der Redaktion

  1. Slide is Self Explanatory
  2. Slide is Self Explanatory
  3. Slide is Self Explanatory
  4. Slide is Self Explanatory
  5. Slide is Self Explanatory
  6. Slide is Self Explanatory
  7. Slide is Self Explanatory
  8. Slide is Self Explanatory
  9. Slide is Self Explanatory
  10. Slide is Self Explanatory
  11. Slide is Self Explanatory
  12. Slide is Self Explanatory
  13. Slide is Self Explanatory
  14. Slide is Self Explanatory
  15. Slide is Self Explanatory
  16. Slide is Self Explanatory
  17. Slide is Self Explanatory
  18. Slide is Self Explanatory
  19. Slide is Self Explanatory
  20. Slide is Self Explanatory
  21. Slide is Self Explanatory
  22. Slide is Self Explanatory
  23. Slide is Self Explanatory
  24. Slide is Self Explanatory
  25. Slide is Self Explanatory
  26. Slide is Self Explanatory
  27. Slide is Self Explanatory
  28. Slide is Self Explanatory
  29. Slide is Self Explanatory
  30. Slide is Self Explanatory
  31. Slide is Self Explanatory
  32. Slide is Self Explanatory
  33. Slide is Self Explanatory
  34. Slide is Self Explanatory
  35. Slide is Self Explanatory
  36. Slide is Self Explanatory
  37. Slide is Self Explanatory
  38. Slide is Self Explanatory
  39. Slide is Self Explanatory
  40. Slide is Self Explanatory
  41. Slide is Self Explanatory
  42. Slide is Self Explanatory
  43. Slide is Self Explanatory
  44. Slide is Self Explanatory
  45. Slide is Self Explanatory
  46. Slide is Self Explanatory
  47. Slide is Self Explanatory
  48. Slide is Self Explanatory
  49. Slide is Self Explanatory
  50. Slide is Self Explanatory
  51. Slide is Self Explanatory
  52. Slide is Self Explanatory
  53. Slide is Self Explanatory
  54. Slide is Self Explanatory
  55. Slide is Self Explanatory
  56. Slide is Self Explanatory
  57. Slide is Self Explanatory
  58. Slide is Self Explanatory
  59. Slide is Self Explanatory
  60. Slide is Self Explanatory
  61. Slide is Self Explanatory
  62. Slide is Self Explanatory
  63. Slide is Self Explanatory
  64. Slide is Self Explanatory
  65. Slide is Self Explanatory
  66. Slide is Self Explanatory
  67. Slide is Self Explanatory
  68. Slide is Self Explanatory
  69. Slide is Self Explanatory
  70. Slide is Self Explanatory
  71. Slide is Self Explanatory
  72. Slide is Self Explanatory
  73. Slide is Self Explanatory
  74. Slide is Self Explanatory
  75. Slide is Self Explanatory
  76. Slide is Self Explanatory
  77. Slide is Self Explanatory
  78. Slide is Self Explanatory
  79. Slide is Self Explanatory
  80. Slide is Self Explanatory
  81. Slide is Self Explanatory
  82. Slide is Self Explanatory
  83. Slide is Self Explanatory
  84. Slide is Self Explanatory
  85. Slide is Self Explanatory
  86. Slide is Self Explanatory
  87. Slide is Self Explanatory
  88. Slide is Self Explanatory
  89. Slide is Self Explanatory
  90. Slide is Self Explanatory
  91. Slide is Self Explanatory
  92. Slide is Self Explanatory
  93. Slide is Self Explanatory
  94. Slide is Self Explanatory
  95. Slide is Self Explanatory
  96. Slide is Self Explanatory
  97. Slide is Self Explanatory
  98. Slide is Self Explanatory
  99. Slide is Self Explanatory
  100. Slide is Self Explanatory
  101. Slide is Self Explanatory
  102. Slide is Self Explanatory
  103. Slide is Self Explanatory
  104. Slide is Self Explanatory
  105. Slide is Self Explanatory
  106. Slide is Self Explanatory
  107. Slide is Self Explanatory
  108. Slide is Self Explanatory
  109. Slide is Self Explanatory
  110. Slide is Self Explanatory
  111. Slide is Self Explanatory
  112. Slide is Self Explanatory
  113. Slide is Self Explanatory
  114. Slide is Self Explanatory
  115. Slide is Self Explanatory
  116. Slide is Self Explanatory
  117. Slide is Self Explanatory
  118. Slide is Self Explanatory
  119. Slide is Self Explanatory
  120. Slide is Self Explanatory
  121. Slide is Self Explanatory
  122. Slide is Self Explanatory
  123. Slide is Self Explanatory
  124. Slide is Self Explanatory
  125. Slide is Self Explanatory
  126. Slide is Self Explanatory
  127. Slide is Self Explanatory
  128. Slide is Self Explanatory
  129. Slide is Self Explanatory
  130. Slide is Self Explanatory
  131. Slide is Self Explanatory
  132. Slide is Self Explanatory
  133. Slide is Self Explanatory
  134. Slide is Self Explanatory
  135. Slide is Self Explanatory
  136. Slide is Self Explanatory
  137. Slide is Self Explanatory
  138. Slide is Self Explanatory
  139. Slide is Self Explanatory
  140. Slide is Self Explanatory
  141. Slide is Self Explanatory
  142. Slide is Self Explanatory
  143. Slide is Self Explanatory
  144. Slide is Self Explanatory
  145. Slide is Self Explanatory
  146. Slide is Self Explanatory
  147. Slide is Self Explanatory
  148. Slide is Self Explanatory
  149. Slide is Self Explanatory
  150. Slide is Self Explanatory
  151. Slide is Self Explanatory
  152. Slide is Self Explanatory
  153. Slide is Self Explanatory
  154. Slide is Self Explanatory
  155. Slide is Self Explanatory
  156. Slide is Self Explanatory
  157. Slide is Self Explanatory
  158. Slide is Self Explanatory
  159. Slide is Self Explanatory
  160. Slide is Self Explanatory
  161. Slide is Self Explanatory
  162. Slide is Self Explanatory
  163. Slide is Self Explanatory
  164. Slide is Self Explanatory
  165. Slide is Self Explanatory
  166. Slide is Self Explanatory
  167. Slide is Self Explanatory
  168. Slide is Self Explanatory
  169. Slide is Self Explanatory
  170. Slide is Self Explanatory
  171. Slide is Self Explanatory
  172. Slide is Self Explanatory
  173. Slide is Self Explanatory
  174. Slide is Self Explanatory
  175. Slide is Self Explanatory
  176. Slide is Self Explanatory
  177. Slide is Self Explanatory
  178. Slide is Self Explanatory
  179. Slide is Self Explanatory
  180. Slide is Self Explanatory
  181. Slide is Self Explanatory
  182. Slide is Self Explanatory
  183. Slide is Self Explanatory
  184. Slide is Self Explanatory