C Language
C Language
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 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
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
Read x and y
Read A and B
False True
Sum=A + B If x>y
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
Page 7
PROGRAMMING IN C
Page 8
PROGRAMMING IN C
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();
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)
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
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
Page 14
PROGRAMMING IN C
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
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
Single String
Integer Real
Character
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
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.
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
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
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:
Example
: for(i=1;i<=20;i++)
{
Page 26
pri
ntf(
“%
d\
t”,i
);
Page 27
PROGRAMMING IN C
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.
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
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);
}
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);
}
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
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
Here array „A‟ can hold maximum of (row x column) 6 elements and 12 bytes of memory
allocated.
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
Page 45
PROGRAMMING IN C
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
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]
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( ).
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
Page 51
PROGRAMMING IN C
Page 52
PROGRAMMING IN C
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
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:
Page 56
PROGRAMMING IN C
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:
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
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.
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
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.
2Declare new Structure within another structure
Struct structure-name1
{
Structure element-1;
- - -
Struct structure-name2
{
Structure element
. . .
}var;
}var1;
Page 65
PROGRAMMING IN C
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
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
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
Page 74
PROGRAMMING IN C
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);
Page 76
Page 77
PROGRAMMING IN C
fprintf(fptr,"%s %d %f",name,rollno,fees);
fclose(fptr);
}
Example 2:
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);
}
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