C Language

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 82

PROGRAMMING IN C

UNIT-I
CHAPTER-1: Introduction to Algorithms and Programming Languages

 Algorithm:
A set of sequential steps usually written in ordinary English language to solve a given
problem is called Algorithm. (Or)
A complete, unambiguous finite number of logical steps for solving a specified problem are
called Algorithm.
o It is one of the Basic Tools that are used to develop the Problem Solving Logic.
o An Algorithm provides a Blueprint for writing a program to solve a particular
problem.
o An Algorithm can be implemented in more than one Programming Language.
o An Algorithm is represented by Flowcharts, Pseudo-Codes.
o An algorithm has a finite number of steps and some steps may involve decision-making and
repetition.
 Features (Characteristics) of Algorithms:
 Finiteness: An algorithm should have Finite number of steps.
 Definiteness: Every Statement/instruction in an Algorithm must be clear and
unambiguous.
 Input: Every Algorithm must take Zero or one or more number of input values.
The input of an Algorithm can either be given interactively by user or generated
internally.
 Output: Every Algorithm must produce an output as result.
 Effectiveness: It should be easily convertible into program.
 Generality: The Algorithm applies to a set of Inputs.
 Examples of Algorithm:
1. Write an Algorithm for Sum of Two Numbers (Addition of Two Numbers):
Step 1: Start
Step 2: Read Two Numbers m, n.
Step 3: Add m and n, and Store the Result in „Sum‟ (Sum=m + n)
Step 4: Display „Sum‟ value
Step 5: Stop
2. Write an Algorithm For Largest of Two Numbers (Biggest of Two Numbers):
Step 1: Start
Step 2: Read Two numbers p, q.
Step 3: if p>q then Display p is Big
Step 4: else Display q is Big
Step 5: Stop
3. Write an Algorithm to Find Whether a Given Number is even or odd:
Step 1: Start

Page 1
PROGRAMMING IN C

Step 2: Take Input a Number as k


Step 3: if k%2==0, then Print Even Number
Step 4: else Print Odd Number
Step 5: Stop
4. Write an Algorithm to find the simple interest:

Step 1: Start
Step-2: Input principle as P
Step-3: Input time as T
Step-4: Input rate of interest as R
Step-5: Set SI= (P*T*R)/100
Step-6: Print SI value
Step-7: Stop

5. Write an Algorithm to find Area of a Circle:


(Sum of sides of a triangle is called perimeter of a Triangle.)
Step 1: Start
Step 2: Read the side1 of the triangle.
Step 3: Read the side2 of the triangle.
Step 4: Read the side3 of the triangle.
Step 5: Calculate perimeter of the triangle using the formula perimeter =
side1+side2+side3 Step 6: Print perimeter.
Step 7: Stop.
 Flow Charts:
Flowchart is Diagrammatic or Graphical representation of An Algorithm. It is constructed by
using different types of Symbols and boxes. (Or)
A Flowchart is a Diagrammatic representation that illustrates the sequence of steps that must
be performed to solve a problem.
The operation to be performed is written inside the box. All symbols are connected by
Arrows among themselves to indicate the flow of information and processing.
Advantages of Flow Charts:
 Once a flow chart is drawn programmers can understand the solution easily and
clearly.
 Once a flow chart is drawn, it becomes easy for the programmer to write the program
in any high-level language.
 Flowcharts are even more helpful in the case of complex programs.
 A flow chart follows top-down approach in solving problems.
 Flowcharts help in Proper Testing and debugging.
Disadvantages of Flow Charts:
 Drawing flowcharts is a time-consuming activity.
 The flowchart of complex (large) programs becomes complex and clumsy.
 A little change in the solution may require complete re-drawing of the flowchart.
Page 2
PROGRAMMING IN C

Flow Chart Symbols:

Usage of symbol in flow


S.No Symbol Name Purpose
chart
Rounded
1 start/stop(Terminal) It is used to start and stop
Rectangle(Oval)

It is used for input or


2 Parallelogram Data
output data

It is used to process the


3 Rectangle Process
data

4 Rhombus Decision It is used to give condition

Flow of control It is used to give flow of


5 Arrows
(Connections) given data.

It is used for loops like


6 Hexagon Preparation
“for, while, do-while”

It is used for connecting


7 Circle Connector
lines

 Pseudo code:
The pseudo code is neither an Algorithm nor a program. It is an Abstract form of program. It
is defined for an Algorithm. It does not use any Graphical representation.
 By using pseudo coeds user can easily understand the logic.
 To fill the Gap between Algorithm and Program, we need pseudo codes. [An
Algorithm is Independent of Any language or machine, where a program is dependent
on a language and machine.]
 Pseudo codes are an outline of a program that can easily be converted into
programming statements.
Example: IF age>=18 THEN
Display “Eligible to Vote”
ELSE
Display “Not Eligible”
ENDIF

Page 3
PROGRAMMING IN C

Flow chart Examples: /*Biggest of Two numbers*/

/*Sum of Two Numbers*/


START
START

Read x and y
Read A and B

False True
Sum=A + B If x>y

Display Sum Display y is big Display x is big

STOP

STOP

 Programming Languages:
A programming language is a computer language used to write instructions for the
computer in a well-defined format. The set of instructions is technically termed as Program
and the process of creating program is called Programming.
o Usually programming languages have a vocabulary of syntax and semantics for
instructing a computer to perform specific tasks.
o The term programming languages refers to high–level languages such as BASIC
(Beginners All-purpose Symbolic Instruction Code), C, C++, COBOL (COmmon
Business Oriented Language), FORTRAN (FORmula TRANslator), Pascal etc...
o Each of these languages has a unique set of keywords.
o A program written using any programming language has to be converted into
machine language so that the computer can understand it. There are two ways to do
this, Compile the program or interpret the program.

Page 4
PROGRAMMING IN C

 Generation of Programming Languages:


Programming languages are the primary tools for creating software. Generation of
programming languages (levels) is closely connected to advanced technology.
There are 5 Generations of Programming languages.
1. First Generation (1GL) (Machine Language)
2. Second Generation (2GL) (Assembly Language)
3. Third Generation (3GL) (High Level Language) (procedural)
4. Fourth Generation (4GL) (Very High Level Language) (Non-procedural)
5. Fifth Generation (5GL) (Artificial Intelligence)
1. First Generation (1GL) (Machine Language):-
 First generation computers relied on machine language, the lowest level
programming language understood by computers, to perform various input output
operations.
 All the commands and data values are expressed using 0‟s and 1‟s, corresponding
to the off and on electrical states in a computer.
Advantages:
1. Translation Free: The code written by a user executed very fast and efficient,
since there is no need for translation.
2. Computer understands the language directly.
3. Directly executed by the CPU.
Disadvantages:
1. Machine Dependent: Every computer type differs from other, based on its
architecture. Hence, an application developed for a particular type of computer
may not run on the other type of computer.
2. Complex Language: It is very difficult to modify the Machine language programs.
It is more difficult to edit, if errors occur.
3. Machine language is very difficult to read and write. Machine language is
more difficult to learn.
2. Second Generation (2GL) (Assembly Language):-
 Assembly language was the next higher level of computer programming languages, which can
be categorized as Second Generation languages (2GL).
 This language assigns a mnemonic code to each machine language instruction to make it easier
to remember or write.
 For example, ADD is used to perform an addition operation; SUB is used for subtraction and MULT
for multiplication and so on.
 A translator program called assembler is used to translate the instructions written in assembly
language to the machine language.
Advantages:
1. Easy to Understand and Use.
2. Less Error Prone.
3. Time saving.
Disadvantages:
1. This is Machine dependent language, i.e. it is specific to particular processor
family and environment.
Page 5
Page 6
PROGRAMMING IN C

2. Knowledge of hardware and operation codes is essential for the programmers.


3. Need of translator Program.
3. High-level language/procedural language (3GL):
 Languages such as COBOL, FORTRAN, BASIC and C are examples of 3GLs and
are considered as high-level languages.
 High-level languages are similar to English language. Programs written using these
languages are machine independent.
 Translators like Compilers and interpreters are used to translate the programs written
in high-level languages into machine language.
Advantages:
1. It is Machine Independent and more user-friendly.
2. The programmers do not require having a detailed knowledge of hardware.
3. Easy Debugging.
Disadvantages:
1. Programs are lengthy.
2. To run programs, computer needs translators.
4. Very High-level language/Non procedural language (4GL):
 Very High-level languages (VHLL) are the easiest programming languages
available today. They are very easy to learn, because their syntax and grammar is
very easy to learn. 4GLs are commonly used to access databases.
 Very High-level languages are also known as non-procedural languages. In non-
procedural languages, the computer is instructed what it must do rather than how a
computer must perform task. (instead of specifying each step one after another)
 SQL (Structured Query Language) is the best example of non-procedural language. It is
used to create and modify information in database management systems.
5. Fifth generation (Natural Programming language) (5GL):
 Fifth generation programming languages are designed to make the computer solve
a given problem without the programmer.
 The Fifth generation programming language is also known as Natural programming
language. It incorporates the concepts of expert systems, artificial intelligence and
natural language processing.
 5GL languages are widely used in artificial intelligence research.
 Prolog and Mercury are the best known natural programming languages.
 Structured Programming Language:

Page 7
PROGRAMMING IN C

Programming languages use different approaches of programming based on nature of


problem. T he major styles of programming or paradigm are classified as
 Procedural Programming
 Structural Programming
 Object Oriented Programming
Procedure Oriented Programming (POP):
It emphasizes on sequence of steps (Algorithm approach). It uses function programming and
modular approach. Here large programs are divided into smaller programs (Functions). It
uses top-down approach in program design. Functions communicate with each other by
passing the parameters. Examples are C, Basic, and Pascal etc. This approach is used for
designing medium size problems.
Structural Programming:
 The concept of structured programming also referred to as modular programming.
 The program makes it efficient and easy to understand and modify.
 Structured programming employs a top-down approach in which the overall program
structure is broken down into separate modules. It is based on modularization.
 Modularization makes it easy to write, debug, and understand a program.
 Structured programming also supports selection and repetition, i.e., if-else, switch, for,
while, do-while loops.
ADVANTAGES:
 The structured programs take less time than unstructured programming.
 To write correct program that is easy to understand and modify.
 With modules, many programmers can work on a single large program, with each
working on a different module.
 A structured program is easy to debug because it is easy to identify the errors in modules.

Page 8
PROGRAMMING IN C

CHAPTER-2: Introduction to ‘C’


Introduction: C is a general purpose programming language developed by Dennis Ritchie
in 1972 at AT&T (American Telephone and Telegraph) Bell Labs, New Jersey, U.S.A. It
was developed from B (Bell), BCPL (Basic Combined Programming Language), and
ALGOL (Algorithmic Language). Father of BCPL is “Ken Thompson”; Father of B
language is “Martin Richards”.
 Features of „C‟:
1. C language was standardized in 1988 by ANSI (American National
Standards Institute).
2. C language program is nothing but a collection of functions, each function has a
unique name and Each Function contains Block of code which performs a
particular Task. Hence C language is called as Procedural Programming Language.
3. C is very small language with only 32 keywords.
4. Using C we can learn the Basics of Programming very easily. Learning C helps
in learning C++, Java.
5. Programs written in C are efficient and fast. This is due to its variety of Data types and
powerful Operators.
6. C is often termed as Middle level programming language, because it combines
the power of a High level language with the flexibility of Low level Languages.
7. C language rich in Built-in Functions (Library Functions).
8. Users can create their own functions and add them to C library to perform a variety
of tasks.
9. C is portable language and free form Language. C is case sensitive language(use
lower case letters).
10.C language is a structured Programming Language. (if block, for block, do block etc).
 C – CHARACTER SET:
C language supports rich set of characters to define statements which are
a. Alphabets – (A to Z , a to z)
b. Numbers – (0 to 9)
c. Special Symbols – (~! @ # $ % ^ & ( ) _ -+ = | \, - * + : ; “ „ < > , . ? / …)
d. White Spaces – (space, horizontal tab, vertical tab, new line …)

 Writing First „C‟ Program:


main( )
{
printf(“ Welcome to C Programming”);
}
[To write a program we need Editor Software. TurboC Editor or IDE (Integrated
Development Environment) is an Integration of several Tools]
Page 9
PROGRAMMING IN C

 Basic Structure of C Program:


The general Structure of C language program is subdivided into different Sections.
1. Documentation Section
2. Preprocessor Directive Section
a. Link Section
b. Definition Section
3. Global Variable Declaration Section
4. main() function Section
5. Pair of Braces{ }
6. Local Variable Declaration Section
7. Executable statements
8. User Defined Functions
1. Documentation Section:
In Documentation section we give a comment. Comment statement is a non executable
statement. Comment Start by using “/*” and end with “*/” Symbols. The general Syntax is
/*Message line */.There are two types of comments. Single line comments and multi line
comments.
Examples: /* My First Program */
// My First Program
2. Preprocessor Directive Section:
These statements begin with # symbol. These statements direct the C preprocessor to include
header files and also Symbolic Constants into C program. There are two types of
Preprocessor Directives:
i. LINK SECTION: Link section is used to include the header files, which contains
definition for the standard library functions (printf,scanf,clrscr,sqrt) provided by C
developers.
Example: #include<Stdio.h>
ii. DEFINITION SECTION: By using this we can define constant variables with its
values. Example: #define PI 3.14
3. Global Variable Declaration Section:
If you want to use a variable throughout the program, you need to declare variable as Global variable. If we
declare variables before main( ), then it is called Global declaration. Global variables are automatically
initialized with zero.
4. main ( ) function Section:
As the name itself indicates, it is the main function of every C program. We cannot write programs without
main() function. Execution of program starts from main ( ). It should be written in lower case letters and
should not be terminated by Semicolon. It calls other library functions.
5. Pair of Braces { }:
Every C Program uses a Pair of Curly braces. The left brace indicates beginning of main ( ), the right brace
indicates end of the main ( ).
6. Local Variable Declaration Section:
Variables which are used in main( ) program are declared by using local variable declaration statement.
These variables are available within the block only.

Page 10
PROGRAMMING IN C

Ex: main( )
{
int m=45;
}
7. Executable statements:
This section has Input, Output statements, Arithmetic statements, Control Statements and
Function calling statements.
Examples: i. printf(“Enter values for a and b:”);
ii. c=a+b;
iii. if(a>b)
8. User Defined Functions:
These are sub programs, which are called by a calling statement from main program. A subprogram is a
function; they contain a set of statements to perform a specific task. These are written by user.
Syntax: type function name (parameters)
{
Local declaration;
Executable statements;
return (argument);
}
Example Program: /*Simple Interest Calculation*/
#include<stdio.h> #include<conio.h> main( )
{ Header File Section
int p,t,r; float si; clrscr();
printf(“Enter P,T,R values:”); scanf(“%d%d Main Section
%d”,&p,&t,&r); si=(p*t*r)/100; printf(“Simple Interest
Local Variable Declaration Section
is =
%f”,si); Executable Part
getch();

 FILE USED IN C-PROGRAM:


Each and every file in a computer is recognized by using file extension. For example Word
documents have an extension .doc, spread sheets have an extension .xls in the same way C
programs have an extension .c
Source File (code): Program Name can be any name that must contains extension C. It is
also known as source file. Example: demo. C
Compiling And Executing a C-Program:
Compiling is an operation, which translates a program written in human readable language
into machine language that can be understood by the CPU.
A compiler is itself a program that reads source files written by human and generate
object file that contains machine code.
If you want to compile a c-program select compile option from compile menu or press the key combination
ctrl+F9. If any errors in your source code compiler will give you list of errors with line number with error description.
Page 11
PROGRAMMING IN C

The code available in header files is joined into your code and translated into machine code that means object
code contains not only your code it contains header file code also.
1. To compile the program - Alt+F9
2. To execute the program - Ctrl+F9
3. To see the output - Alt+F5
Object file (code): compiler produces an object code (.obj) if the program does not have any
Errors. Example: demo.obj
Executable file (code): After Completion of Compilation Process, executable files with .exe
extension are created. Example: demo.exe
Source Code (demo.c)
Pre-ProcessorDirective (Header
Files)

Expanded Source Code Compile


Object Code (demo.obj)
Linker(IncludesSystem Libraries)
Executable Code (demo.exe)

 DATA TYPES in „C‟:


C language is rich in its data types. Data types are defined as the building blocks of a C program. C language
supports different types of data types. A data type of a variable tells us three things:
o The type of value that can be stored in a variable.
o The range of values.
o The type of operations that can be performed.

Data Types

Built-in User
derived
or Defined
or
Primary secondary
Characte
Integer Real
r Arrays
int or signed int float 1. char 2. Strings enum
unsigned int double unsigned 3. typedef
char
short int long Structures
double 4. Union
unsigned short int
long int
unsigned long
Figure: Types of Data Types in C

Page 12
PROGRAMMING IN C

Data types are classified into Three Sections:


1. Built-in or Primary or Fundamental Data types
2. Derived Data types
3. User-defined Data types
I. Built-in Data types: The built-in data types are int, float,char, and double. These are
also called as Primary or Fundamental Data types.
Integer Data Types:
Integer data types are used to represent value without decimal point. We can represent signed
values and unsigned values. In integer category we have int, short int, long int as data types.
The size and range of integer data types described in below table.
TYPE Format Specifier SIZE RANGE
short int 1 byte -128 to +127
unsigned short int 1 byte 0 to 255
Int %d 2 bytes -32768 to +32767
unsigned int %u 2 bytes 0 to 65535
long int %ld 4 bytes -2,147,483,648 to +2,147,483,647
unsigned long int %lu 4 bytes 0 to 429,49,67,295
Real (float) Data Type: Floating point numbers are defined in C by the Keyword „float‟.
These data type have at least one digit with a decimal point. These are also signed or
unsigned.
The size and range of float data types described in below table.
TYPE Format Specifier SIZE RANGE
float (6 decimal places) %f 4 bytes 3.4E-38 to 3.4E+38

double( 15 decimal places) %lf 8 bytes 1.7E-308 to 1.7E+308

long double %lf 10 bytes 3.4E-4932 to 1.1E+4932


Character Data Type: By using character data type we can represent single character or
combination of characters called strings. Character data types are either signed or unsigned.
TYPE Format Specifier SIZE RANGE
Char %c (Single) 1 byte -128 to +127
%s (String) 0 to 255

II. Derived Data type: Derived Data types are derived from the Primary data types.
These are used for representing a single value or multiple values. Arrays, Structures,
Unions are some examples for Derived types.
III. User-defined Data types: user can also declare his own types by using
„typedef‟ and „enum‟ data types.

Page 13
PROGRAMMING IN C

 I/O Statements In “C‟:


1. In order to work with dynamic values every programming language input/output statements to read values
from standard input device and provide output to standard output device.
2. In C language there are two types of I/O statements available to work with dynamic values
a. Formatted I/O statements
b. Unformatted I/O statements
Formatted I/O Statements:
1. The functions printf() and scanf() perform formatted output and input statements.
2. They can read data and write data in various formats that you need.
3. The printf() function write data on the standard output device.
4. The scanf() function read data from the standard input device.
5. Both functions can operate on any of the built-in data types.
printf( ):
This function most commonly used function for displaying data of any type.
Syntax: printf(“formatted string” , arguments list );
Example: printf(“ %d ” , a );
Here formatted string consist of group of characters, contains symbols and format
specifiers like %d , %f , %s , %c …etc.
scanf( ):This function can read all the built-in data types and automatically convert
numbers into the proper internal format.
Syntax: scanf( “ formatted string ” , &variable_name);
&(ampersand)  address operator
Example: scanf( “ %d “ , &a);
In the above statement %d represents integer value and &-ampersand represents address
of memory location of variable „a‟.
Unformatted Input and Output Statements:
getc : getc( ) is an exclusive function for reading characters.
putc :Output Writes a character into a stream
gets :Input Reads a string from keyboard. gets is an exclusive function for reading
strings. Also gets( ) function executes faster than scanf( )function. gets( ) function
handles only strings
puts :output Writes string on to the screen. Puts( ) is an exclusive function for
printing the strings
 C Tokens:
Token: Each individual unit or element in a statement is called Token. C language contains
different types of Tokens. C tokens include identifiers, keywords, variables, constants and
operators.
 Operators In C:
An operator is a special symbol which operates one or more operands. The data items that
operators act upon are called Operands. C language supports a rich set of Operators. They
are categorized by several types.

Page 14
PROGRAMMING IN C

1. Arithmetic Operators 2. Relational Operators


3. Logical Operators 4. Bitwise Operators
5. Increment and Decrement Operators 6. Assignment Operators
7. Conditional operator 8. Special Operators
Arithmetic Operators:
Arithmetic operators are used for arithmetic operation like Addition, Subtraction,
Multiplication, Division, modulo division.
Operator Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
Modular Division
%
(remainder)
Note: The difference between division and modular division is division returns quotient
where as modular division returns reminder.
2. Relational Operators: These operators are used to tell the relation between two operands.
The relational operators are used to compare left hand side expression with the right hand
side expression.
Operator Operator Name
> Is greater than
< Is Less than
>= Is Greater than or equal to
<= Is Less than or equal to
== Is Equal to
!= Is Not equal to

3. Logical Operators: These operators are used to check more than one condition at a time.
Operator Operator Name
&& logical AND
|| logical OR
! logical NOT
4. Bitwise Operators: These operators perform manipulations on values in a bit
manner. Bitwise Operators are used to perform operations on binary Digits (0‟s,1‟s).

Page 15
PROGRAMMING IN C

Operator Operator Name


& bit wise AND
| bit wise OR
^ bitwise XOR
<< Left shift
>> Right shift
~ bitwise complement
5.Increment and Decrement Operators:
These Operators are also called as Unary Operators. These operators are used to increment
one value of variable and decrement operator is used to decrease one value of a variable.
Operator Operator Name
++ Increment Operator
-- Decrement Operator
These operators are available in two forms.
a. Prefix Operator: Operator comes before the operand.Ex: ++a; --a;
b. Postfix Operator: Operator comes after the operand. Ex: a++; a--;
In prefix operation first increment/decrement will be done later assignment will be done.
In postfix operation first assignment will be done later increment/decrement will be done.
6. Assignment Operators:
Assignment Operator is used to assign values to the variables.
Ex: c = a + b;
In the above example the addition result is assigned to variable C.
Assignment Operator requires a variable on its left hand side, contains an expression or a
value or another variable on its right hand side.
= Stores the value in right side variable to left hand side variable.
+= Add right hand side value to value in left hand side variable and stores in it.
-= Subtract right hand side value from value in left hand side variable and stores in it.
Multiply right hand side value with left hand side value and store the result in left hand
*=
side variable.
7. Conditional Operator:
Conditional operator is also called as Ternary Operator. It is used in decision making process. ? :
Syntax: condition ? True block statement: False block statement;
Ex: a>b ? printf(“a is big”) : printf(“b is big”);
If condition is true, true block statement will be executed otherwise false block statement will be
executed.
8.Special Operators:
Sizeof operator: sizeof( )
Comma operator: ,
Member Selection operator (dot operator): .
Pointer operator: &,*

Page 16
PROGRAMMING IN C

 Keywords:
Keywords are reserved words in C language. They have pre-defined meaning and are used
for the intended purpose. All keywords must be written in lowercase. (Or) Keywords
(reserved words) are defined by C compiler and each word has different meaning, these
cannot use as names of variables, functions or labels. Standard Keywords are

 Identifiers:
In C-language names of variables, functions, labels and various other user-defined names or
objects are called identifiers.
Rules for defining identifiers:
1. The first character must be an alphabet or an underscore, sub-sequent characters must
be either letters, digits or underscore.
2. No space is allowed in between identifiers and no special characters are also allowed
except underscore.
3. Key Words are not allowed as identifiers.
4. There is no limit of length of an identifier but some compilers will recognize only 8
or 32 characters
 Variables:
Variable is a name given to a memory location where a value is stored. Or A variable can be
thought as a symbolic representation of address of the memory space where values can be
stored, Accessed and changed.
Initialization: The process of assigning initial values to the variable is known as
initialization.
Ex: int k=6;
Rules for variable names:
1. It can contain A-Z, a-z,0-9 and Underscore( _ ).
2. It can not start with a Digit.
3. It can not have any blanks with in a variable name.
4. Turbo C Compiler allows a maximum of 32 characters.
5. variable names can not be Keywords.

Page 17
PROGRAMMING IN C

 Constants: (Literals)
Constant refers to fixed values that the program cannot alter. Constants can be any of the
basic data types. Constants are also called “LITERALS”. Constants are classified into 2
basic types. They are Numeric Constants, Character Constants.
CONSTANTS

Numeric Constants Character Constants

Single String
Integer Real
Character

Figure: Basic Types of Constants in C


I. Numeric Constants
Numeric constants, as the name itself indicates, are those which consist of numerals. They
are further divided into two types:
a. Integer Constants: A whole number is an integer constant. Integer constants do not have
a decimal point. These are further divided into three types depending on the number
systems they belong to. They are:
i. Decimal integer constants
ii. Octal integer constants
iii. Hexadecimal integer constants
Ex: 10,124, 4564,-20 etc (Decimal)
Ex: 0456,037, -0123(Octal)
Ex: 0x8E, 0x456, -0x123, 0x56A (Hexadecimal)

b. Floating Point Constants (real): Floating Point constants require the decimal
point followed by the numbers fractional component.
The real constants also known as floating point constants are written in two forms:
(i) Fractional form
(ii) Exponential form.
i. Fractional Form:
Ex: 456.78,-123.56, 11.23, -2.34 …
ii. Exponential Form: The exponential form offers a convenient way for writing very
large and small real constant. For example, 56000000.00, which can be written as 0.56 x
108 is written as 0.56E8 or 0.56e8 in exponential form. A real constant expressed in
exponential form has two parts: (i) Mantissa part, (ii) Exponent part.
Ex: 7500000000 written as 7.5E9

Page 17
PROGRAMMING IN C

II. Character Constants:


a. Single Character Constant: It is a single character enclosed in single quotes.
Each character has an ASCII value to identify.
Ex: „A‟, „@‟, „55‟,‟98‟ etc
C supports some special backslash character constants that are used in output functions.
Ex: \n (Next line), \t (Horizontal tab), \v (Vertical tab) etc.
b. String Constants: A String is a set of characters enclosed in double
quotes. Ex: “abc”, “c-language”, “Salary is 18000.00”,”2314” etc.
 Type Conversion:
1. Type casting is a mechanism which is used to convert one data type value into another
data type value.
2. If the operands are of different types, the lower type is automatically converted to the
higher type before the operation proceeds.
Implicit Type Casting: It is performed by compiler. It means compiler automatically
converts lower data type values into higher data type values.

int i=10;
float f;
f=i;  implicit type casting

Explicit Type Casting: It means converting higher data type value into lower data type
value. Explicit type casting is performed by the programmer this means we need to write
additional code to convert higher data type value into lower data type value.

Variable = (data type) expression;


1. Example Program for Type Casting:

main( )
{
int a,b;
float c;
printf(“ Enter any two numbers: ”);
scanf(“ %d%d ”, &a, &b);
c= (float) a/b; Type casting
printf(“ Quotient value = %f ”, c);
}

Page 18
PROGRAMMING IN C

Example: 2
main( )
{
int p,t,r,i;
clrscr();
printf(“ Enter p,t,r values: ”);
scanf(“%d%d%d”,&p,&t,&r);
i=(int)(p*t*r)/100;
printf(“Simple Interest = %d”, i);
getch( );
}
Unit-II
Chapter-3: Decision Control and Looping Statements
Control Structures in C:
Normally statements in C program are executed sequentially i.e in the order in which they
are written. This is called sequential execution. We can transfer the control point to a desired
Location is possible with control structures. C allows many kinds of control statements.
I. Conditional (Decision) control structures
· if
· if –else
· nested if– else
· nested else-if
II. Loop (iterative) control structures
· for loop
· while loop
· do - while loop
III. Multi way conditional (case) control structures
· Switch- case
IV. Jumping (branching) control structures
· goto
· break
· return
· continue
 Decision Control Structures:
These are used to express decisions based on Conditions. Decision Control structures are
classified into below types:
1. simple if statement
2. if-else statement
3. Nesting of if..else statement
4. else if ladder statement.

Page 19
PROGRAMMING IN C

1. Simple if statement: (unidirectional)


In simple if, controller initially checks the condition, if the condition is true it executes the
true block statements otherwise it skips the true block statements and executes the statements
after the true block statements. Simple if is also known as Unidirectional Decision control
structure. It is implemented through the keyword „if‟.
[When we need to perform a particular action when a condition gets satisfied, then we
use Unidirectional Decision Control structure.]
Syntax:
if( condition)
{

Statement- Block;
}
statement-x;

Flow Chart:

Example 1: if(age>=18)
printf(“Eligible for Vote”);
Example 2: if(number>0)
printf(“Positive number”);

2. if else statement:(Bidirectional)
This statement has a simple condition with two different blocks one is true block and other
is false block. It is implemented through the keywords „if‟ and „else‟. [When we need to
perform a particular action when a condition gets satisfied and perform a different action if
the condition is not satisfied, then we use Bidirectional decision Control structure].

In this statement first the condition will be checked. If the condition is „true‟, the
statements associated with „if block‟ gets executed, otherwise „else block‟ gets
executed.

Page 20
PROGRAMMING IN C

Syntax:

if( condition)
{
True Block Statements
}
else
{
False Block Statements
}
Statement-x;

Flowchart:

Example: if(age>=18)
printf(“Eligible for Vote”);
else
printf(“Not Eligible for Vote”);
3. Nesting of if-else:
When a series of decisions are involved, we may have to use more than one if, else
statements in nested form. These are used for Multi-way decision making.
Syntax:
if( condition1)
{
if( condition2)
{
True Block statements
}
else
{
False Block Statements
}
}

Page 21
PROGRAMMING IN C

else
{
if( condition3)
{
True Block statements
}
else
{
False Block Statements
}
}
Flowchart:

Example:

Page 22
PROGRAMMING IN C

4. Else if ladder (or) nested else if: Else if ladder statement is used to check more than
one condition on same value. The conditions are evaluated in order, if any condition is true,
the statements associated with it are executed, and terminates the whole chain. The final else
block will be executed if no true block find.
Syntax:

if(condition-1)
{
True Block - 1
}
else if(condition-2)
{
True Block - 2
}
else if(condition3)
{
True Block – 3
}
else if(condition4)
{
True Block - 4
}
else
{
default statement;
}
Example:
if(marks>=95)
{
printf(“A+ Grade”);
}
else if(marks>=85)
{
printf(“A Grade”);
}
else if(marks>=75)
{
printf(“B Grade”);
}
else if(marks>=60)
{
printf(“C Grade”);
}
else
printf(“D Grade”);

Page 23
PROGRAMMING IN C

 Loop Control Structures:


Loop control structures can also be called as iterative or repetitive control structures. When
we need to repeat s set of instructions certain number of times, then we use loop control
structures.
In C there are Three types of Loop Control Structures:
1. while Loop
2. do-while Loop
3. for Loop
I. WHILE LOOP:
1. while statement is also known as “Entry Control Loop”.
2. In this controller first check the condition, if the condition is true then
controller moves to while block and executes the statements.
3. After completing execution of last statement controller again checks the condition.
This process will be repeated until the condition is false.
4. In while loop it checks the condition first and executes the statements later.
So minimum number of execution times of statements is 0.

Syntax:
Initial value;
while(condition)
{
Block of Statements

Increment/decrement;
}
Statement-x;
Flowchart:

Example 1: i=1;
while(i<=40)
{
printf(“%d \t”, i);
i++;

Page 24
PROGRAMMING IN C

Example 2:
i=1;
while(i<=10)
{
printf(“hello”); prints hello 10 times.
i++;
}
2. do-while Loop:
1.do-while loop is also called as “Exit Control Loop”.
2.In this first body of the loop is executed and then condition is checked.
3.If the condition is true then the body of the loop is executed.
4.When the condition becomes false then it will exit from the loop.
5.In do while it executes the statements first and checks the condition later. So
Minimum number of execution times of statements is 1.
Syntax: initial value;
do
{
Statements

Increment/decrement

} while (condition);

Flowchart:

Example:
i=1;

do
{
printf(“%d \t”, i);
i++;

Page 25
PROGRAMMING IN C

while(i<=40);
Example 2:
i=1;
do
{
printf(“hello”); prints hello 10 times.
i++;
} while(i<=10);
3. for Loop: For is a looping control statement in which three expressions were present.
1. Initialization (In this the initial value of the loop is specified, where to start the loop)
2. Condition ( In this condition is specified, when to stop the loop)
3. Increment/Decrement ( In this modification statement, in each iteration how
much increment or decrement is specified)
The three expressions present in for loop are separated by using semicolon (;).
Even in the absence of any expression you need to place semicolon.
Syntax: for(initialization ; condition ; increment/decrement)
{
Statement 1;
Statement 2;

}
Flowchart:

Loop process in for loop:


1. In first iteration for loop executes initialization part and checks the condition.
2. If the condition is true it executes the block of statements then performs
increment/decrement.
3. After performing increment/decrement it checks the condition, if it returns true
executes block of statements otherwise terminate the loop.

Example
: for(i=1;i<=20;i++)
{

Page 26
pri
ntf(
“%
d\
t”,i
);

Page 27
PROGRAMMING IN C

Differences Between while and do-While:


WHILE DO-WHILE
1. While loop is also called as Entry 1. Do-While loop is also called as Exit
Control Loop. Control Loop.
2. In While Loop control first checks the 2. In Do-while loop control first
condition then executes the while executes the while block statements
block statements. and then checks the condition.
3. No Semicolon at the end of condition. 3. There is a semicolon at the end of
condition.
4. Statements in while loop may or may 4. Statements in do while loop get
not get executed. Minimum executed at least once. Minimum
executions are zero executions are one
5. While(condition) 5. do
{ {
Block of statements; Block of statements;
Increment/decrement Increment/decrement
} } while(condition);

Page 27
PROGRAMMING IN C

 Nested Loops:
A loop inside another loop is called as nested loop. When a for statement is executed with in
another for statement, then it is called nested for statement. One for statement within another
for statement is called as Nested for loop.
Syntax: for (initialization; condition; increment/decrement)
Outer Loop
{
--------------------------
for (initialization ; condition ; increment/decrement)
{ Inner Loop
--------------
Statements;
--------------
}
---------------------------
}
When the control reaches the inner loop, only after the complete execution of the inner loop,
the control goes to the modification counter of the outer loop.
With in the inner loop, the outer loop counter variables value remains constant, where as the
inner loop counter variables value keeps changing.
Example:
void main( )
{
int i, j;
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf(“%d,%d\n”,i,j);
}
}
}
Output:
1,1
1,2
1,3
2,1
2,2
2,3
3,1
3,2
3,3

Page 28
PROGRAMMING IN C

 Jump Statements:
Whenever we need to transfer the control from one place to another place in a program then
we use Jump statements.
C supports three Jump Statements
1.break
2. continue
3. goto
break statement:
1. „break‟ is a keyword used to terminate the loop or exit from the block. When break
statement is encountered inside a loop, the control comes out of that loop and resumes at
the next statement following the loop.
2. Sometimes there may be a situation where we want immediate termination of a loop,
bypassing the test condition expression and any remaining statements in the body of the
loop. Break statements can be used with for, while, do-while and switch statement.
The general syntax for break statement is as:
break;
Example:
switch(n)
{
case 1: c=a+b;
break;
case 2: c=a*b;
break;
}
continue statement:
1. „continue‟ is a keyword used for continue the next iteration of the loop.
2. Unlike break which causes the loop to be terminated, the continue statement causes the
loop to be continued with the next iteration.
3. The continue statement tells the controller, “SKIP THE FOLLOWING
STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”.
The general Syntax is for continue statement is:
continue;

Example:
void main()
{
int i;
clrscr();

Page 29
PROGRAMMING IN C

for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
printf(“%d \t”,i);
}
getch( );
}
OUTPUT: 1 2 3 4 6 7 8 9 10
goto statement: goto statement is one of the jumping statement. It is used to transfer the
controller from one location to another location in the program.
Syntax: goto can be used in any of the following forms.

label:
---------------
-------------
goto label;
goto label;
---------------
---------------
label:
Example: /* Even or Odd Number Using goto Statement*/
void main( )
{
int n;
clrscr();
printf("Enter any Integer number:");
scanf("%d",&n);
if(n%2==0)
{
goto even;
}
else
{
goto odd;
}
even:printf("The given number is Even");
return;
odd:printf("The given number is Odd");
}

Page 30
PROGRAMMING IN C

Chapter 4
Functions
Introduction:
 Function Definition:
A function is a self contained block of statements (sub program) that can used to perform a
specific task. Every C program has at least one function, which is main( ), Every function
has a unique name. This name is used to call function from main ( ) function. A function can
be called from within another function.
Generally a function is an independent set of statements that carries out some specific
well defined task. It is written after or before the function main ( ).
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
Syntax:
return_type Function_name(parameters list)
{
--------------
Statements
return (value);(optional)
}
Uses or Advantages of functions:
1. Functions provide code reusability in the program. By calling the same function
several times in the main program, we can achieve reusability of code.
2. Functions provide modular approach means code separation.
3. This allows us to break a large program into smaller one.
4. Functions are used to reduce the programming code.
5. Functions allow calls of other functions within.
6. Function implementation in program will make debugging easy.

Generally User defined Functions have the following components:


o Function prototype or Function Declarations: Declaring of a function can be called
as function prototype. This gives the clear picture of the function i.e which type of
arguments it takes and how many arguments and what will be return value with the
function name. Function prototype is used to describe the function properties or
characteristics to the compiler.
Syntax: return-type function-name (arguments list….);
Example: int max (int num1, int num2); (or) int max (int, int);
o return type: A function may return a value. The return type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return type is the keyword void.

Page 31
PROGRAMMING IN C

o Function Name: This is the actual name of the function. Function name is any user
defined name except keywords.
o Parameters: A parameter is like a placeholder. When a function is invoked, you pass
a value to the parameter. Parameters are optional; that is, a function may contain no
parameters. Argument/parameter type specifies what type of values you are giving
input to the function.
o Function Body: The function body contains a collection of statements that define
what the function does.
o Calling a Function: While creating a C function, you give a definition of what the
function has to do. To use a function, you will have to call that function to perform
the defined task.
When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.
o Actual Arguments/Parameters: The arguments in the function parenthesis at
the place of function call are called as actual arguments/parameters.
Ex: addition (a,b); /* a, b are called actual arguments/parameters*/
o Formal Arguments/Parameters: The arguments/parameters in the function
parenthesis at the place of function definition are called as formal arguments /parameters.
Ex: addition(int x,int y); /*x, y are called as formal arguments/parameters*/
o return statement: return statement is used to send values to main function from the
function definition.
Example 1: /* Addition of Two Numbers by using Function*/
#include<stdio.h>
int addition(int, int); /* function declaration(prototype) */
void main( )
{
int a,b,c;
clrscr();
printf(“Enter a,b values:”);
scanf(“%d%d”,&a,&b);
a=addition(a,b); /* calling of function */
printf(“Sum=%d”,c);
getch();
}
int addition(int x,int y) /* function definition */
{
int z;
z=x+y;
return z;
}

Page 32
PROGRAMMING IN C

 Categories of Functions: In C user defined functions can be written in


four different ways. Based on function return type and arguments list, functions are
categorized into following categories.
1) Function with No Arguments and No Return type
2) Function with Arguments and No Return type
3) Function with No Arguments and Return type
4) Function with Arguments and Return type
1. Function with No arguments and No Return type:
In this category of the function, main program will not send any arguments to the function
and function will not send any values to the main. (Or) a function which does not take any
arguments and does not return any value that function can be said as No Argument, No
Return type function.
Example:
#include<stdio.h>
void addition( );
main()
{
clrscr();
addition();
}
void addition( )
{
int a,b,c;
printf(“Enter a,b values:”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“Additoin result is %d”,c);
}
2. Function with Arguments and No Return type:
In this category of the function, the main program will send argument values to the function
but the function will not return any values.
Here actual argument values are copies into formal parameter variables.
Example: /*Area of a circle*/
#include<stdio.h>
void area(int);
main( )
{
int r;
clrscr();
printf(“Enter radius:”);
scanf(“%d”,&r);
area(r);

Page 33
PROGRAMMING IN C

getch( );
}
void area(int radius)
{
float a;
a=3.141*radius*radius;
printf(“Area=%f”,a);
}
3. Function with No Arguments and Return type:
In this category of function the calling program will not send any arguments but the called
function will return value to the calling program.
Example: int add( );
void main()
{
c=add();
printf(“%d”,c);
}
int add( )
{
int x=10,y=20;
return(x+y);
}
4. Function with Arguments and Return Type:
In this category of function the main function will send argument values to the function and
the function will return some value to the main function.
Example: void main( )
{
int a=10,b=20,c;
c=add (a,b);
printf(“%d”,c);
}
int add(int x,int y)
{
return(x+y);
}

 Passing Parameters (or) Types Function Calling:


The values are passed to the function through the arguments. In C language we can pass
values from calling program/function to called program/function in two types.
1. Call by value
2. Call by reference

Page 34
PROGRAMMING IN C

1. Call By Value:
In call by value mechanism the values of actual arguments at the function call are
copied into the formal arguments of the function definition.
After manipulations in the function definitions changes done in formal arguments will
not affect the actual arguments.
/* swapping of Two numbers using call by value*/
#include<stdio.h>
void swap(int,int);
void main( )
{
int x,y;
clrscr( );
printf(“Enter x,y values:”);
scanf(“%d%d”,&x,&y);
swap(x,y);
printf(“After swapping in main x=%d y=%d”,x,y);
getch();
}
void swap(int x,int y)
{
int z;
z=x;
x=y;
y=z;
printf(“after swapping in function x=%d y=%d”,x,y);
}
2. Call By Reference:
In this mechanism instead of sending argument values to function definition, address of
actual arguments will be send.
The changes made in the formal arguments will affect on actual arguments.
/* swapping of Two numbers using call by reference*/
#include<stdio.h>
#include<conio.h>
void swap(int*,int*);
void main()
{
int x,y;
clrscr();
printf(“Enter x,y values:”);
scanf(“%d%d”,&x,&y);
swap(&x,&y);
printf(“After swapping in main x=%d y=%d”,x,y);

Page 35
PROGRAMMING IN C

getch();
}
void swap(int *x,int *y)
{
int z;
z=*x;
*x=*y;
*y=z;
printf(“after swapping in function x=%d y=%d”,x,y);
}

 Differences Between Call By Value And Call By Reference


Call by Value Call by Reference
 Values of actual arguments will be  The address of actual arguments will
copied into formal arguments. be copies into formal arguments.

 Manipulations done on values.  Manipulations done on addresses.

 Changes in formal arguments will not  Changes in formal arguments will


affect actual arguments. affect actual arguments.
 Recursive Functions:
If a function is called within the same function is said to be recursion. A recursive function is
a condition dependent.
1. A function which calls itself is called as recursive function.
2. It is the process of calling a function by itself, until some condition is satisfied.
3. It is used for repetitive computations in which each action is stated in terms of
previous results.
4. For every recursive function, there must be Base criteria for which the function does
not call itself.
5. Each time the function calls itself (recursive) it must be closer to the base criteria.
In recursive function there should be a condition to terminate the function.
Example: /*Factorial value of a given number using Recursive Function*/
void main( )
{
int n,f;
printf(“Enter a number:”);
scanf(“%d”,&n);
f=factorial(n);
printf(“Factorial = %d”,f);
}

Page 36
PROGRAMMING IN C

int factorial(int n)
{
if(n==1) /*base case*/
return 1;
else
return (n*factorial(n-1)); /*recursive case*/
}
Ex: To find the factorial value of given number (5) the logic is: Logic is = n * fact (n-1)
Fact (5) = 5 * fact (4)
= 5 * 4 * fact (3)
= 5 * 4 * 3 * fact (2)
= 5 * 4 * 3 * 2 * fact (1)
=5*4*3*2*1
Example: 2 /*Generating Fibonacci series Using Recursion*/
#include<stdio.h>
void main()
{
int f,num,i;
clrscr();
printf("Enter how many number do you want in the series:");
scanf("%d",&num);
for(i=0;i<num;i++)
printf("%d\t",fib(i));
getch();
}
int fib(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else
return fib(n-1)+fib(n-2);
}
 Application of Recursion:
 Towers of Hanoi:
The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide
on the pegs.
The disks are varying size, initially placed on one peg with the largest disk on the bottom
with increasingly smaller ones on top. The goal is to move all of the disks from one peg
to another under the following rules:
 We can move only one disk at a time.

Page 37
PROGRAMMING IN C

 We cannot move a large disk on top of smaller one.

 Storage Classes:
To fully define a variable one needs to mention not only its type but also its “storage class”.
In other words, not only do all variables have a data type, they also have a “storage class”.
A variable‟s storage class tells us:
1. Where the variable would be stored.
2. What will be the initial value of the variable, if initial value is not
specifically assigned; i.e., the default initial value.

Page 38
PROGRAMMING IN C

3. What is the scope of the variable; i.e., in which functions the value of the
variable would be available.
4. What is the life of the variable; i.e., how long would the variable exist.
The following are the storage classes in C.
 Automatic storage class
 Register storage class
 Static storage class
 External storage class
1. Automatic Storage Class-(Auto): For all local variables, auto storage class is the
default storage class. These variables get initialized or recreated each time a function is
called. The scope of an auto variable is limited to the function. They get initialized to some
garbage values if no data is give.
Storage : Memory
Default initial value : Garbage value
Scope : Local to the block in which the variable is defined.
Life : Till the control remains within the block in which the variable
is defined.
Example:
void main( )
{
auto int x=10;
printf(“%d”, x);
}
2. Register Storage Class-(Register): For register storage class variables, system allocates
memory in CPU registers. Generally, this is done for fast accessing because the speed of
the Register is high. Register storage class can be applied to local variables only. And
register variables do not have any address.
Storage : CPU Registers
Default initial value : Garbage value
Scope : Local to the block in which the variable is defined.
Life : Till the control remains within the block in which the variable is
defined.
The value stored in a CPU register can always be accessed faster than the one that is stored
in memory.
Example: main( )
{
register int i;
for(i=1;i<=10;i++)
printf(“\n%d”,i);
}

Page 39
PROGRAMMING IN C

3. Static Storage Class-(Static): static variable is local but life as a global variable. A
static variable can be initialized only once. A static variable also gets initialized to “zero”
Automatically.
Storage : Memory
Default initial value : Zero
Scope : Local to the block in which the variable is defined.
Life : Value of the variable persists between different function calls.
Example:
show( );
void main( )
{
int i;
for(i=1;i<=5;i++)
show( );
}
show( )
{
static int j;
j++;
printf(“\n function calling no%d”,j);
}
Output:
function calling no 1
function calling no 2
function calling no 3
function calling no 4
function calling no 5
4. External Storage Class-(Extern): For all global variables this is the storage class. The
scope of this external variable is throughout the program (in main, all modules). Extern
variables get initialized “zero” automatically.
Storage : Memory
Default initial value : Zero
Scope : Global
Life : As long as the program‟s execution doesn‟t come to an end.
External variables are declared outside all functions, they are available to all functions
that use extern variable.
Example:
int x=30;
show( );
main( )
{
printf(“%d”,x); 30

Page 40
PROGRAMMING IN C

show( );
}
show ( )
{
printf(“%d”,x); 30
}

UNIT-III
Chapter-5: Arrays
Introduction:
An array can be defined as a collection of similar (same Data type) elements, stored in
adjacent memory locations that share a common name. To refer to the elements of array we
use index, array of index starts from zero (0).
(Or)
An array is a collection of homogeneous elements of fixed length. Array is set of elements
of similar type, array elements share common name and array elements are stored in
sequential memory locations.
Syntax: data type array_name[ size ];
Example: int a[10];
Advantages of arrays:
 It is capable of storing many elements at a time.
 It allows random access of elements.
Disadvantages of arrays:
 Predetermining the size of array is must
 Memory wastage will be there.
 To delete an element of an array we need to traverse throughout array.
Array Initialization:
Datatype array_name[ ]={ list of values };
Example: int a[ ]={10,20,30,40};
To process large amount of data, C language supports arrays that facilitate efficient
storing, accessing and manipulation of data elements.
We can use arrays to represent not only simple list of values but also table of data in two
or three or more dimensions.
 Types of arrays:
Arrays can be mainly three types One (single) dimensional, Two (double) dimensional and
Multi dimensional
One Dimensional Arrays:
A list of elements can be given one variable name using only one subscript and such
a variable is known as one-dimensional array.

Page 41
PROGRAMMING IN C

Data type specifies the type of elements that will be stored in array.
Size indicates the maximum number of elements that can be stored in the array.
The size of array should be a constant value.
Example: int A[10];
Memory Representation:
10 20 30 40 50 60 70 80 90 100
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Index values are used to represent the array elements.
Index values starts from 0 and end with n-1, where n refers to size of array.
Inserting and retrieving elements in arrays can be done by using for loop.
Example:
void main()
{
int a[10],i;
printf(“Enter elements:”);
for(i=0;i<10;i++)
{
scanf(“%d”,&a[i]);
}
printf(“Elements in the array are:”);
for(i=0;i<10;i++)
{
printf(“%d\t”,a[i]);
}
}
Program: /*Sorting of Array Elements*/
#include<stdio.h>
void main()
{
int a[20],i,j,n,temp=0;
clrscr();
printf("enter n value:");
scanf("%d",&n);
printf("\n enter the array elements:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n the entered elements are:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)

Page 42
PROGRAMMING IN C

{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\n the ascending order is:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}
Program: /*Sum of Array Elements*/
#include<stdio.h>
void main()
{
int a[10],i,n,sum=0;
clrscr();
printf("how many numbers do you want:");
scanf("%d",&n);
printf("enter numbers:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf(" %d\t ",sum);
getch();
}
Program: /*Searching an Element in An Array*/
Linear search: This is also called a sequential search. In this technique we compare the
search key with the elements of the array sequentially till it is found or till the end of array.
#include<stdio.h>
void main( )
{
int a[10],i,key,found=0;
clrscr( );

Page 43
PROGRAMMING IN C

printf(“enter 10 values to array a”);


for(i=0;i<10;i++)
scanf(“%d”,&a[i]);
printf(“enter key element to be search”);
scanf(“%d”,&key);
for(i=0;i<10;i++)
if(a[i]= =key)
{
found=1;
break;
}
if(found==1)
printf(“Key Element found”);
else
printf(“Element Not found”);
getch( );
}

 Two Dimensional Arrays:


A list of items can be given one variable name using two subscripts and such variables are
called two-dimensional arrays.
Two dimensional arrays can represent the data in the form of rows and columns means
taking two indexes. In two dimensional arrays data stored in the form of a Matrix. To work
with two dimensional arrays nested for loops are used.
Syntax: data type array name [row-size] [column-Size]
Example: int A[2][3];

Here array „A‟ can hold maximum of (row x column) 6 elements and 12 bytes of memory
allocated.

Initialization Example: int a[ ] [ ] ={ {1,2,3},{4,5,6},{7,8,9} };

0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
Here
a[0][0]=1 , a[0][1]=2 , a[0][2]=3
a[1][0]=4 , a[1][1]=5 , a[1][2]=6
a[2][0]=7 , a[2][1]=8 , a[2][2]=9

Page 44
PROGRAMMING IN C

Example: Reading Two Dimensional Array


void main()
{
int a[2][2],r,c;
printf(“Enter elements:”);
for(r=0;r<2;r++)
{
for(c=0;c<2;c++)
{
scanf(“%d”,&a[r][c]);
}
}
printf(“Elements are :”);
for(r=0;r<2;r++)
{
for(c=0;c<2;c++)
{
printf(“%d”,a[r][c]);
}
printf(“\n”);
}
}
 Program: /*Addition of Two Matrices*/
#include<stdio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j;
clrscr();
printf("enter the order of matrix A:\n");
scanf("%d%d",&m,&n);
printf("enter the order of matrix B:\n");
scanf("%d%d",&p,&q);
if((m= =p)&&(n= =q))
{
printf("the addition is possible\n");
printf("enter the values into Matrix a:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]); /* Reading values into Matrix a*/

Page 45
PROGRAMMING IN C

printf("enter the values into Matrix b:");


for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]); /* Reading values into Matrix b*/

for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j]; /*Logic for Matrix Addition*/
printf("The Addition of given matrices is \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",c[i][j]); /*Printing Result Matrix c*/
printf("\n");
}
}
else
printf("Addition is not possible");
getch();
}
 Program: /*Matrix Multiplication*/
#include<stdio.h>
void main()
{
int A[5][5],B[5][5],C[5][5],m,n,p,q,i,j,k,sum=0;
clrscr();
printf("enter the order of matrix A:");
scanf("%d%d",&m,&n);
printf("enter the order of matrix B:");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf("the multiplication of matrices is not possible");
}
else
{
printf("\n enter the values of A: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&A[i][j]); /* Reading values into Matrix A*/

Page 46
PROGRAMMING IN C

printf("\n enter values of B:");


for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&B[i][j]); /* Reading values into Matrix B*/

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
for(k=0;k<p;k++)
{
sum=sum+A[i][k]*B[k][j]; /*Logic for Matrix Multiplication*/
}
C[i][j]=sum;
sum=0;
}
}
printf("the multiplication matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d\t",C[i][j]); /*Printing the Result Matrix*/
printf("\n");
}
}
getch();
}

 Sparse Matrices:
In computer programming, a matrix can be defined with a 2-dimensional array. Any array
with 'm' columns and 'n' rows represents an (m x n) matrix. There may be a situation in
which a matrix contains more number of ZERO values than NON-ZERO values. Such
matrix is known as sparse matrix.
For example, consider a matrix of size 5 x 6 containing 6 number of non-zero values.

Page 47
PROGRAMMING IN C

Chapter – 6
Strings
 String:
A string is a collection of characters. In C language array of characters is called string. A
string is terminated by null character (\0).
Example: “C Language” is a string.
In the above example “C Language” is a string. When compiler encounters string, it appends
null character at the end of the string.
C L a n g u a g e \0
Strings are declared as similar to arrays, only difference is that, strings are of character
type.
char a[5]  A[0] A[1] A[2] A[3] A[4]

Strings are also be declared as char x[10];


Initialization Of Strings:
In C, strings can be initialized in different number of ways.
 char c[ ] = “abcd”; or char c[5] = “abcd”;
 char c[ ] = {„a‟,‟b‟,‟c‟,‟d‟};
Strings can also be initialized using pointers.
 char *c=”abcd”;
Program: Write a c program to illustrate how to read strings.
void main()
{
char name[20];
printf(“Enter name:”);
scanf(“%s”,&name);
printf(“Your name is : %s”,name);
getch();
}
Output: Enter name: Dennis Ritchie
Your name is: Dennis
In the above program Ritchie word will be ignore because scanf() function takes only strings
before the occurrence of white space.

Page 48
PROGRAMMING IN C

There are predefined functions gets( ) and puts( ) in C language to read and display strings
respectively.
Program: /*Reading and Printing Multiple Words*/
void main( )
{
char name[20]; printf(“Enter name:”); gets(name); printf(“Your name is :”); puts(name);
getch();
}

Output:
Enter name: Dennis Ritchie
Your name is: Dennis Ritchie
 String Handling/Library Functions:
C supports a large number of string handling functions. String functions (built-in) of C are
declared in the header file #include<string.h>. These functions allows us to work with
strings. some Example are strcpy( ), strcat( ), strlen( ), strrev( ), strlwr( ), strupr( ) strcmp( ).

strlen(string) Calculates the length of the string.


strcpy(string1,string2) Copies string2 into string1.
strcat(string1,string2) Concatenates string2 to string1.
strcmp(string1,string2) Returns 0 if two strings are equal otherwise return a numeric value.
strlwr(string) Converts string into lower case letters.
strupr(string) Converts string into upper case letters.
strrev(string) Reverse the string

If you want to work with string handling functions you have to include “string.h” header file
to your program.
1. Strlen( ): This function is used to find the length of the given string.
Syntax: variable_name = strlen(string);
Example: len=strlen(“Aditya”);
In the above example len contains length of the string i.e., 6.
main()
{

Page 49
PROGRAMMING IN C

char name[20];
int len;
printf(“Enter name:”);
gets(name);
len=strlen(name);
printf(“Length of the string is : %d”,len);
getch();
}
2. Strcpy( ): This function is used to copy one string into another string.
Syntax: strcpy(string1,string2)
Example: strcpy(str1,str2); /* str1, str2 are character arrays.*/
main()
{
char str1[20],str2[100];
printf(“Enter a string:”);
gets(str2);
strcpy(str1,str2);
printf(“String1 is : %s”,str1);
printf(“String2 is : %s”,str2);
getch();
}
3. Strcat( ): This function is used to concatenate two strings and the resultant string will be
stored in the first string.
Syntax: strcat(string1,string2)
main()
{
char str1[20],str2[100];
printf(“Enter string1:”);
gets(str1);
printf(“Enter string2:”);
gets(str2);
strcat(str1,str2);
printf(“String1 is : %s”,str1);
printf(“String2 is : %s”,str2);
getch();
}
Make sure that while concatenating strings the length of the first string must be larger than
the length of the second string.
4. Strcmp( ): This function is used to compare two strings and return 0 if the two strings are
equal, otherwise returns a numerical value.
=0 : if two strings are equal
>0 : if string1 is bigger than string2

Page 50
PROGRAMMING IN C

<0 : if string1 is smaller than string2.


Syntax: strcmp(string1,string2)
main()
{
char str1[20],str2[100];
int res;
printf(“Enter string1:”);
gets(str1);
printf(“Enter string2:”);
gets(str2);
res=strcmp(str1,str2);
if(res = = 0)
{
printf(“Both strings are Equal”);
}
else
{
printf(“Strings are not equal”);
}
getch();
}
5. Strlwr( ): This function is used to convert given string into lowercase letters.
main()
{
char str[20];
printf(“Enter a string:”);
gets(str);
strlwr(str);
printf(“String in lower case letters is : %s”,str1);
getch();
}
6. Strupr( ): This function is used to convert given string into uppercase letters.
main()
{
char str[20];
printf(“Enter a string:”);
gets(str);
strupr(str);
printf(“String in upper case letters is : %s”,str1);
getch();
}

Page 51
PROGRAMMING IN C

7. Strrev( ): This function is used to reverse the given string.


Syntax: strrev(string)
main()
{
char str[20];
printf(“Enter a string:”);
gets(str);
strrev(str);
printf(“Reverse of given String is : %s”,str);
getch();
}
Program: Write a program to check whether the given string is palindrome or not
using string handling functions.
void main()
{
char str1[20],str2[100];
int res;
printf(“Enter a string:”);
gets(str1);
strcpy(str2,str1);
strrev(str1);
res=strcmp(str1,str2);
if(res = = 0)
{
printf(“Given string is Palindrome”);
}
else
{
printf(“Given string is Not Palindrome”);
}
getch();
}

Page 52
PROGRAMMING IN C

 /* String Handling Functions*/


/* program for String Handling Functions in one program*/
void main( )
{
char st1[30],st2[30],st3[30];
int l,n;
clrscr();
printf("Enter the First string :");
gets(st1);
printf("Enter the Second string :");
gets(st2);

l=strlen(st1);
printf("\n Length of First string is:%d", l);
strcpy(st3,st1);
printf("\n copying st1 into st3: %s", st3);
strrev(st3);
printf("\n The Reverse of String 3 is: %s", st3);
n=strcmp(st1,st3);
if(n==0)
printf("\n Both Strings st1,st3 are same");
else
printf("\n st1,st3 are Not same");
strcat(st1, st2);
printf("\n String obtained on Concatenation is: %s", st1);
getch( );
}

Sample Output:
Enter the First string: programming
Enter the Second string: language
Length of First string is: 11
Copying st1 into st3: programming
The Reverse of String 3 is: gnimmargorp
st1, st3 are Not same
String obtained on Concatenation is: programminglanguage

Page 53
PROGRAMMING IN C

UNIT-IV
Chapter 7: Pointers
 Introduction to Pointers:
Pointer: A pointer is a special kind of variable that holds the memory address of a variable
of same type. Pointer is one of the most important features available in C-language.
A pointer is declared by using a de-reference operator “* “ (asterisk).
(Or)
Pointer is a variable which holds the address of simple variable of same type.
To declare a pointer variable we use * operator.
Declaration of pointer variables:
Syntax: datatype *pointer_variable;
Example: int *p;
In the above example „p‟ defined as pointer variable of „int‟ type. Now „p‟ can holds
address of another integer variable.
If you place & symbol before a variable name it returns the address of that variable.
int *p , a=10;
p=&a;
p  stores the address of a;
*p  returns the value stored in address of p.
The * operator: If „p‟ is a pointer variable, then *p gives you the content of the location
pointed to by „p‟.
The & operator: If v is a variable, then &v is the address of the variable.
void main( )
{
int a=10;
int *p;
p=&a;
printf(“value of a is : %d”, a);
printf(“address of a is : %u”, &a);
printf(“value of p : %u”, p);
printf(“address of p : %u”, &p);
printf(“value of a using p : %d”,*p);
getch( );
}
a 10 p 1001

1001 1003

Page 54
PROGRAMMING IN C

o &a represents address of a i.e., 1001


o p represents address of a.
o *p represents value stored in the address in the p i.e., 10
o a represents value in a i.e., 10.
Advantages of Pointers:
1. Pointers reduce the length of the program and complexity of the program.
2. Pointers increase the execution speed of the program. Pointers improve efficiency of
program
3. It allows dynamic memory allocation.
4. It allows call by reference mechanism for function arguments.
5. Pointers can be used to pass the information back and front between a function and its
reference point.
6. Pointers are closely associated with array and provide alternative way to accessing
the individual array elements.
7. Pointers provide convenient way to represent multi-dimensional arrays.
Null Pointer: A Null pointer is defined as a special pointer that points to nowhere in the
memory location.
If it is too early to assign a value to a pointer then it is better to assign NULL to the pointer
as shown below.
int *p=NULL;
This indicates that a pointer variable p does not point to any Memory location.
 Pointer Expression and Pointer Arithmetic :
A pointer in C is an address, which is a numeric value. Therefore, you can perform
arithmetic operations on a pointer just as you can on a numeric value. We can perform
arithmetic operations by using pointers. Such expressions are said to be pointer arithmetic.
Ex: *p1 + *p2; /* p1, p2 are pointer variables*/
Operator ++: Adds sizeof(data type) number of bytes to pointer, so that it points to the next
entry of the data type.
Operator −−: Subtracts sizeof(data type) number of bytes to pointer, so that it points to the
next entry of the data type.
/*program for pointer Arithmetic */
void main( )
{
int x,y,add,sub,mul,div;
int *p1,*p2;
clrscr( );
printf(“ Enter x, y values: ”);
scanf(“%d%d”,&x,&y);

Page 55
PROGRAMMING IN C

p1=&x;
p2=&y;
add=(*p1)+(*p2);
sub=(*p1)-(*p2);
mul=(*p1)*(*p2);
div=(*p1)/(*p2);
printf(“Pointer addition is : %d”,add);
printf(“\n Pointer subtraction is : %d”,sub);
printf(“\n Pointer multiplication is : %d”,mul);
printf(“\n Pointer division is : %d”,div);
getch( );
}
Sample Output:

 Passing Argument to Functions using Pointer


(Or) Pointer with Functions
By using pointers we can manipulate functions, i.e., we can refer the address of function and
even we can access function definition through pointers.
#include<stdio.h>
#include<conio.h>
void swap(int*,int*);
main( )
{
int x,y;
clrscr();
printf(“Enter x,y values:”);
scanf(“%d%d”,&x,&y);
swap(&x,&y);
printf(“After swapping in main x=%d y=%d”,x,y);
getch();
}

Page 56
PROGRAMMING IN C

void swap(int *x,int *y)


{
int z;
z=*x;
*x=*y;
*y=z;
printf(“after swapping in function x=%d y=%d”, x, y);
}
Sample output:

 Array of pointers (Or)Pointer With Arrays


In C Language, we can represent an array by using a pointer variable. Name of the array is
always points to the first element of the array. Array of pointers is a set of pointer
variables that holds address of simple variable of same type.
Example: arr[5];
P=&arr;

p 1000 1002 1004 1006 1008


1000 arr[0] arr[1] arr[2] arr[3] arr[4]

P=&arr;  represents first address block of array i.e., arr[0] is stored in


pointer p.
Now arr[1] is stored in (p+1). We can represent the value in arr[1] by *(p+1). We
can represent address of 1st element with &arr[1] or with (p+1). *(arr+i) is equal
to arr[i].

/*Program for pointer with Arrays*/


void main( )
{
int a[100],i,n;
int *p;
clrscr( );
printf(“Enter array size:”);
scanf(“%d”,&n);
printf(“Enter elements into array:”);

Page 57
PROGRAMMING IN C

for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
p=&a;
printf(“\n Elements in the array are:”);
for(i=0;i<n;i++)
{
printf(“%d \t”, *(p+i));
}
getch( );
}
Sample output:

 Dynamic Memory Allocation (or) Dynamic Memory Management


Dynamic Memory Allocation is a memory allocation method; the memory will be allocated
when the program is executed. Allocating memory at run time is known as Dynamic
Memory Allocation.
The problem with arrays is that, the length of the array is fixed. There may be a chance of
memory overflow or memory under flow.
Dynamic Memory Allocation allows a program to obtain whole memory space while
running the program.
 In Dynamic memory allocation after our purpose is completed we can release the memory
to avoid blocking of the memory.
There are four functions for Dynamic Memory Allocation.
malloc( ) Allocates specified size of bytes and returns a pointer to first byte of allocated
space and assigns garbage value.
calloc( ) Allocates space for an array element, initializes to zero and then returns a
pointer to first block.
realloc( ) Increases or decreases the size of previously allocated space.
free( ) De-allocates the memory that is allocated by using malloc( ) or calloc( )
1. malloc( ):
The name malloc stands for “Memory Allocation”. The malloc( ) reserves a block of
memory of specified size and returns a pointer of type void which can be casted into pointer
of any type. The space is not initialized.
Syntax: ptr=(cast-type*)malloc(byte-size);
Here, ptr is pointer of cast-type.

Page 58
PROGRAMMING IN C

Example:
ptr= (int*)malloc(20* sizeof(int));
20 integer locations are created, when the above line is executed.
Program: /*Dynamic Memory Allocation using malloc( )*/
#include<stdio.h>
void main( )
{
int n,i,*ptr;
clrscr( );
printf("Enter size of array:");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
printf("Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",ptr+i);
}
printf("\n The array elements are:");
for(i=0;i<n;i++)
{
printf("%d\t",*(ptr+i));
}
free(ptr);
getch( );
}

2. calloc( ):
The name calloc( ) stands for “contiguous allocation”. The only difference between
malloc() and calloc() is malloc( ) allocates single block of memory where as calloc( )
allocates multiple blocks of memory and sets all bytes to zero.
calloc( ) uses two arguments. The syntax is
Syntax:
ptr=(cast-type*)calloc(n,sizeof(type));
This statement will allocate contiguous space in memory for an array of n elements.
Example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size
of float.

Page 59
PROGRAMMING IN C

/* program for Dynamic memory allocation using calloc ( ) function*/


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char *mrd;
clrscr();
mrd=calloc(25,sizeof(char)); /* memory is allocated dynamically */
strcpy( mrd,"C Programming Language");
printf("Dynamically allocated memory content is: %s\n", mrd);
free(mrd);
getch();
}
Sample Output:
Dynamically allocated memory content is: C Programming Language
3. realloc( )
If the previously allocated memory is insufficient or more than sufficient then you can
change memory size using realloc( ). realloc( ) uses two arguments. Ptr is a pointer to a
block of memory for which the size is to be altered. new size indicates increased or
decreased size.
Syntax:
ptr=realloc(ptr, new-size);
Here ptr is reallocated with new-size.
/* program for reallocating memory dynamically using realloc( ) function*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char *mrd;
mrd = malloc( 25 * sizeof(char) ); /* memory is allocated dynamically */
strcpy( mrd,"C Programming Langauge");
printf("Dynamically allocated memory content is : %s \n", mrd );
mrd=realloc(mrd,100*sizeof(char)); /* using of realloc function*/
strcpy( mrd,"space is extended upto100 characters");
printf("Resized memory : %s\n", mrd );
free(mrd);

Page 60
PROGRAMMING IN C

getch();
}

Sample Output:

4. free( ):
It De-allocates the memory pointed by the pointer. Dynamically allocated memory using
calloc( ) or malloc( ) does not get return on its own, the programmer must use free( )
explicitly to release space.
Syntax: free (ptr);
This statement de-allocates the space in memory of the pointer ptr.

 Differences between Static And Dynamic Memory Allocation


Static memory allocation Dynamic memory allocation
1. In static memory allocation, 1. In dynamic memory allocation,
memory is allocated while writing memory is allocated while executing
the C program. Actually, user the program. That means at run
requested memory will be allocated
time.
at compile time.
2. Memory size can‟t be
modified while execution. 2. Memory size can be modified while
Example: array execution.
3. Memory is allocated from Stack Example: Linked list
area. 3. Memory is allocated from Heap area.
4. Memory is De-allocated by the
compiler 4. Memory is De-allocated using free( )

Page 61
PROGRAMMING IN C

Chapter: 8
Structures, Union, and Enumerated Data Types
Introduction to Structure:
 Structure:
A structure is a user defined data type. A structure is heterogeneous (different)
collection of related fields. Here fields are called structure elements or structure members.
A structure can be considered as a template used for defining a collection of variables
under a single name. Structures help programmers to group elements of different data types
into a single unit.
Syntax:
struct structure-name struct Books
{ {
Datatype-1 structure-element 1; char char
title[50];
Datatype-2 structure-element 2 char int author[50];
- - - subject[100];
- - - book_id;
Datatype-2 structure-element n;
}; };
 The keyword “struct” is used to define structure.
Variables inside the structure are called structure elements. Structure block can be terminated
with semi-colon.
 By using structure variable we can access structure elements.
 When we declare structure variable, memory allocation takes place.
 Memory allocated to the structure variable is sum of individual elements in the structure.
 The structure elements are accessed using dot (  ) operator. It is also called as Member Selection
operator.
Structure Variable:
Similar to other types of variables, the structure data type variables can be declared using
structure definition.
Syntax: struct structure-name variable-name;
Example: Two Ways to create variable
struct student Another Method:
{ struct student
int rollno; {
char name[20]; int rollno;
float fees;
}; char name[20];
void main( ) float fees;
{ }s;
struct student s;
}

Page 62
PROGRAMMING IN C

Here rollno, name, fees are structure members and “s” is structure variable.
 Structure Example Program
/*Reading and Printing Student Details Using Structure*/
struct student
{
int rollno;
char name[50];
float fees;
};
void main( )
{
struct student s;
clrscr( );
printf("Enter Student rollno, Name, Fees :");
scanf("%d%s%f",&s.rollno,s.name,&s.fees);
printf("STUDENT DETAILS\n");
printf("%d\t %s\t %f",s.rollno,s.name,s.fees);
getch( );
}

 Initializing Structure:
We can initialize structure element values inside curly braces, with each value separated by
(,).
struct student s={10, ”Aditya”, 10000};
The individual elements can also initialize as follows. The structure elements are accessed
using dot (  ) operator. It is also called as Member Selection operator.
s.rno=10;
s.name=”ritchie”;
s.fees=10000;

 Arrays of Structures:
C does not limit a programmer to storing simple data types in an array. User can define
structures as an element of an array.
The general syntax used for declaration of array of structures can be
Syntax: struct structure-name variable-name [size];
Example: struct student s[10];

This defines an array called s that has 10 elements. Each element inside the array will be of
type struct student. Referencing an element in the array is as follows.

Page 63
PROGRAMMING IN C

/* Reading and Printing Students Details using Array of Structures*/


struct student
{
int rollno;
char name[20];
float fees;
};
void main( )
{
struct student s[10];
int i,n;
clrscr( );
printf("How many Students Details you want to Enter:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter Student RollNO,NAME,FEES:\n");
scanf("%d %s %f",&s[i].rollno,s[i].name,&s[i].fees);
}
printf("STUDENT DETAILS\n Rollno\t Name\t Fees");
for(i=0;i<n;i++)
{
printf("\n %d\t%s\t%f",s[i].rollno,s[i].name,s[i].fees);
}
getch( );
}
Sample output:
How many Students Details you want to Enter: 3
Enter Student RollNO,NAME,FEES:
15 Ritchie 50000
Enter Student RollNO,NAME,FEES:
16 Gosling 75000
Enter Student RollNO,NAME,FEES:
17 Babbage 45000
STUDENT DETAILS
Rollno Name Fees
15 Ritchie 50000.000000
16 Gosling 75000.000000
17 Babbage 45000.000000

Page 64
PROGRAMMING IN C

 Nested Structures:
A structure can be embedded within another structure. In other words when a structure
is declared and processed with in another structure then it is called nested structure or
structures within structures.
Structures can be nested in two ways.
1 Using previously defined structure:
struct structure-name1
{
structure element;
- - -
};
struct structure-name2
{
structure element;
- - -
struct structure-name1 variable-name;
};
Example: struct dob
{
int day;
int month;
int year;
};
struct student
{
int rno;
char name[100];
struct dob d;
};
Defining structure variable in another structure can be called as Nested Structure.
2Declare new Structure within another structure
Struct structure-name1
{
Structure element-1;
- - -
Struct structure-name2
{
Structure element
. . .

}var;
}var1;

Page 65
PROGRAMMING IN C

Example: struct student


{
int rno;
char name[20];
struct dob
{
int day;
int month;
int year;
}d;
}s;
The inner structure elements can be linked with the outer structure variable by dot operator.
This can be represented as
Outer-variable  inner-variable  inner-element;
 Structure and Functions:
You can pass a structure as a function argument in very similar way as you pass any other
variable or pointer. You would access structure variables in the similar way as you have
accessed.:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
void printBook( struct Books book );/* function declaration */
void main( )
{
struct Books Book1; /* Declare Book1 of type Book */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
printBook( Book1 );
}
void printBook( struct Books book )
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}

Page 66
PROGRAMMING IN C

UNION
A union is a user-defined data type that allows you to store different data types in same
memory location.
We can define a union by using “union” keyword. The union statement defines new data
type with more than one member for your program.
Syntax:
union union-name
{
union element-1;
union element-2;
- - -
- - -
union element-n;
};
Example
:
union data
{
int i;
float f;
char str[20];
}d;
Here union variable d can store an integer, a floating point number or a string. It means a
single variable i.e., same memory location can be used to store multiple types of data.
The memory occupied by a union will be the largest member memory of the union. In
the above example data d will occupy 20 bytes of memory.
Accessing Union Members:
To access any member of a union we use the member access operator .
By using keyword union we can define union variables.
union union-name variable-name;
Example Program:
union student
{
int rollno;
float fees;
char name[20];
};
void main( )
{
union student s;
clrscr( );
Page 67
Page 68
PROGRAMMING IN C

printf("Enter student Roll number, Fee paid and Name:\n");


scanf("%d %f %s",&s.rollno,&s.fees,s.name);
printf("student roll number:%d",s.rollno);
printf("\n student fee paid :%f",s.fees);
printf("\n student name :%s",s.name);
getch( );
}
Sample output:
Enter student Roll number, Fee paid and Name:
141 25000 Gosling
student roll number:28487 (Garbage value)
student fee paid :1177177866259130610000000000.000000 (Garbage value)
student name :Gosling

 Differences Between Structures And Unions:


1. Keyword struct is used to define 1. Keyword union is used to define union.
structure.
2. Within a structure all members get 2. For union compiler allocates the memory
memory allocated. of the largest among all members.
3. The total size of the structure is the sum 3. The total size of the union is the largest
of size of all structure elements. member size in the union.
4. Within a structure we can access any 4. Within a union we can access most
member at any time. recently stored value. Only one member can
be accessed at a time.
struct structure-name union union-name
{ {
Datatype-1 structure-element 1; Datatype-1 union-element 1;
Datatype-2 structure-element 2; Datatype-2 union-element 2
- - - - - -
Datatype- structure-element n; Data type union-element n;
}variable-name; }variable-name;

5. Several members of a structure can 5. Only the first member of a union can be
initialize at once. initialized.
6. Altering the value of a member will not 6. Altering the value of any of the member
affect other members of the structure. will alter other member values.

Page 69
PROGRAMMING IN C

 Enumerated Data Type:


An enumeration is user-defined data type consist of integer constants and each integer
constant given a name. Using this we can define more than one constant at a time. Keyword
“enum” is used to define enumerated data type.
Syntax: enum type-name {value-1, value-2,……. value-n };
Here type-name is the name of enumerated data type and value-1, value-2 . . . value-n are the
values in the enumeration.
By default value-1 will be equal to 0, value-2 will be 1 and so on,
Enumeration is also a way of defining the user defined data types. It allows declaring string
constants with integer equitant values.
Example1: enum day { sun, mon, tues, weds, thur, fri, sat } d1,
d2; enum day { sun=1, mon, tues, weds, thur, fri=1, sat }
d1;
The values of the enumeration constants will be:
sun 1, mon 2, tues 3, weds 4, thurs 5, fri 1, sat 2
Example 2: enum suit { spades, hearts, clubs, diamonds } s1;
 Example program 1:
void main( )
{
enum colors {red=10,green=20,blue=30};
enum colors c1,c2;
c1=red;
c2=blue;
printf(„‟%d‟‟,c1); /*C1 prints 10
printf(„‟%d‟‟,c2); /*C2 prints 30
}

 Example program 2:
#include<stdio.h>
#include<conio.h>
void main( )
{
enum months{jan=31,feb=28,mar=31,apr=30,may=31,jun=30,jul=31,aug=31,sep=30,
oct=31,nov=30,dec=31};
enum months m1,m2;
m1=apr;
m2=sep;
printf(“\n days in apr=%d”,m1);
printf(“\n days in sep=%d”,m2);
getch( );
}

Page 70
Page 71
PROGRAMMING IN C

 typedef
It is possible to create new names for existing types with „typedef‟ . “typedef” is a Keyword
which is used to define an alias name for a data type. We know that alias names are easier to
refer than the original names. This is frequently used to give shorter or less complicated
names for types, making programming safer and hopefully easier.
Example:
typedef struct
{
char title[20];
int pages;
float price;
}library;

library book1;
library book2;
library book3;

This is an example using „typedef‟ keyword to define library structure so when you want to
create an instance of it you can omit (leave) the keyword struct.

UNIT-V
Chapter 9: Files
 Files: A file represents a sequence of bytes on disk where a group of related data is
stored. File is created for permanent storage of data. By using files data can be stored
on the disks and can be read whenever you want without destroying the data
Types of Files:
There are two types of Files.
1. Text Files : Consists of lines of characters
2. Binary Files: Binary Files stores floating point data.
There are different file organizations occurs in the file
handling.
1. Sequential File access
2. Random Access Files
Sequential File Access:
In this type, data are kept sequential. If we want to read the last record of the file, then
we need to read all the records before the last record.
Random Access Files:
In this type, data can be read and modified randomly. It takes less time as compared to
sequential file.
It is very easy to access the data sequentially from the beginning of file to the end of
the file. But some time we need to access data from the middle or from a particular location
called as direct access or random access.

Page 72
Page 73
PROGRAMMING IN C

To access data from file directly or randomly C Language supports 3 functions.


1. ftell( ): The ftell( ) function returns the current position of the file pointer associated with
the file. Syntax: n=ftell(fp);
2. fseek( ): The fseek( ) function is used to move the file pointer to a desired location within
the file. Syntax: fseek(file-pointer, offset, position);
3. rewind( ): This function takes a file pointer and resets the position to the starting of the
file. Syntax: rewind(file-pointer);
 File Handling Functions (File Operations)
C provides a number of functions that helps to perform basic File Operations. Following are
the functions,
Function Description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the beginning
point
 File Opening Modes(File Modes):
1. w (Write): This mode opens a new file on the disk for writing. If the file already
exists, it will be overwritten without confirmation.
fp=fopen(“data.txt”,”w”);
2. r (Read): This mode opens an existing file for reading. If the file does not exist, it
will return NULL to the file pointer.
fp=fopen(“data.txt”,”r”);
if(fp= =NULL)
printf(“File does not exist”);
3. a (Append): This mode opens an existing file for appending data. If the file does not
exist then new file is created. fp=fopen(“data.txt”,”a”);
4. w+ (write + read): This mode opens an existing file and deletes the content of file.
If the file does not exist a new file will be created otherwise it returns NULL to the
file pointer. fp=fopen(“data.txt”,”w+”);
5. a+ (append + read): This mode opens an existing file for reading and appending
data at the end of the file. fp=fopen(“data.txt”,”a+”);
6. r+ (read + write): This mode opens an existing file for both reading and
writing. fp=fopen(“data.txt”,”r+”);

Page 74
PROGRAMMING IN C

 File Handling Functions (or) File Operations in C


The processing of files has number of operations according to the user‟s requirement.
There are three file operations in C.
1. Naming a file
2. Opening File.
3. Reading data from a file
4. Writing data to File
5. Closing File.
Opening a File:
A File has to be opened before performing read and write operations. Opening a file
creates a link between the operating system and the file functions. The name of the file and
its mode to the operating system should be specifies one important task is carried out by the
FILE structure that is defined in “stdio.h” header file.
Syntax for Opening file:
The fopen( ) function is used to create a new file or to open an existing file.
FILE *fp;
fp=fopen(filename, opening-mode);
Here
File name is the name of the file to be opened.
Mode specifies the purpose of opening the file.
*fp is the file pointer that contains address of the FILE.
Example: fp=fopen(“demo.txt”.”r”);
If the specified file is available, fopen( )returns address of the File otherwise it return NULL.
Closing A File:
The file that is opened from the fopen( ) function should be closed after the
completion of work. This can be done by using fclose( ) function.
Syntax: fclose(file-pointer);
This function close one file at a time. To close all opened files at a time fcloseall( )
function is used.
Syntax: fcloseall( );
This function closes all opened functions and returns number of files closed. It does
not require any arguments.
Reading and Writing Files:
Files have different Input/Output statements used for different purpose. These are used to put
data from variable to file.
Character Input/Output Functions:
Character I/O functions are used to read and write character by character from files.
putc( ): This function is used to write or put a single character to a file.
Syntax: putc(value, file-pointer);
Here value is the variable that contains character data and file-pointer is the location of file,
where data is to be placed.

Page 75
PROGRAMMING IN C

getc( ): This function is used to read or get a single character from a file.
Syntax: v=getc(file-pointer);
Here v is character type variable that contains the character that is read from the file.
String Input/Output Functions:
Strings are the major elements of the character data, which can be handled by the files. There
are mainly two types of string I/O functions.
fputs( ): The purpose of this function is to write a string to the opened file.
Syntax: fputs(“string”,file-pointer);
Here string represents a variable or string value and file-pointer is the address of file.
fgets( ): The purpose of this function is to read a string from the opened file.
Syntax: fgets(string-variable, size, file-pointer);
Here string variable holds the string that is read from file, size specifies number of characters
to be read from file and file pointer is the address of the file.
Formatted Input/Output Functions:
fprintf( ): This function is used to write mixed data type to the file. The mixed data type
are of integer, float, string and characters.
Syntax: fprintf(file-pointer,”control-string”,variable-1,variable-2, …);
File pointer is used to locate the address of file
Control String contains conversion codes for values.
Variables represent data values to be stored into the file.
Example: fprintf(fp,”%d%s%f”,rollno,name,fees);
fscanf( ): This function is used to read mixed data from
file.
Syntax: fscanf(file-pointer,”control-string”,&variable-1,&variable-2, …);
Example: fscanf(fp,”%d%s%f”,&rno,&name,&fees);

/*Writing data to File*/


Program to illustrate the concept of to write mixed data by using fprintf( ).
Example 1:
#include <stdio.h>
void main()
{
FILE *fptr;
char name[20];
int rollno;
float fees;
fptr = fopen("student.txt","w");
printf("\n Enter the Name,rollno,Fees: ");
scanf("%s %d %f",name,&rollno,&fees);

Page 76
Page 77
PROGRAMMING IN C

fprintf(fptr,"%s %d %f",name,rollno,fees);
fclose(fptr);
}
Example 2:

/*Writing Structure Data to File*/


#include<stdio.h>
struct student
{
int no;
char name[20];
};
void main()
{
FILE *fp;
struct student s={126,"Dennis ritchie"};
clrscr();
fp=fopen("students.txt","w");
fprintf(fp,"%d %s",s.no,s.name);
fclose(fp);
}
Output:
126 Dennis Ritchie

Example 3:
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp =fopen("chracter.txt","w");
if(fp==NULL)
printf("file not opened");
else
printf("successfully opened\n");
printf("Input line and press 'EOF' at End:");
while((ch=getchar())!=EOF)
{

Page 78
PROGRAMMING IN C

putc(ch,fp);
}
fclose(fp);
}

 Reading data from File:


Program to the concept of reading mixed data using fscanf( ).
#include< illustrate stdio.h>
void main()
{
FILE *fptr;
char name[25];
int rollno;
float fees;
clrscr();
fptr=fopen("student.txt","r");
fscanf(fptr,"%s %d %f",name,&rollno,&fees);
printf("\n The details in file are:");
printf("%s %d %f",name,rollno,fees);
fclose(fptr);
}

 Detecting End of File(EOF):


void main( )
{
FILE *fp;
char ch;
clrscr( );
fp=fopen(“data.txt”,”r”);
if(fp = = NULL)
{
printf(“File Does not Exist”);
}
while((ch=getc(fp))!=EOF)
{
printf(“%c”,ch);
}
fclose(fp);
getch( );
}

Page 79
PROGRAMMING IN C

Example 2:
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp =fopen("chracter.txt","w");
if(fp==NULL)
printf("file not opened");
else
printf("successfully opened\n");
printf("Input line and press 'EOF' at End:");

while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);
}
 Error Handling:
Error handling During File Operations:
Errors in fopen
If an error occurs in opening a file, then fopen( ) returns NULL.
FILE *p;
p=fopen(“abc.txt”, ”r”);
if (p==NULL)
{
printf(“Error in opening file”);
}
Errors may occur due to following reasons
1. If we try to open a file in read mode and If the file doesn‟t exists or we do not have
read permission on that file.
2. If we try to create a file but there is no space on disk or we don‟t have write permissions.
3. If we try to create a file that already exists and we don‟t have permission to delete that file.
4. Operating system limits the number of files that can be opened at a time and we are trying
to open more files than that number.
5. If you try to open the file having an invalid name.
Command Line Arguments: Main function in C Language consists of two arguments or parameters
called command line arguments. Name itself indicates that these arguments are send from command
prompt. The following are the two arguments. argc argv[ ]

Page 76

You might also like