You are on page 1of 65

C Language

Set of programs are called as language


Computer languages
1. Low level languages (machine Language)
2. Assembly languages (Nuemonics)
3. High level languages

Compiler:
It checks the entire source program and if it is error free, produces a complete object
program.
Source program- Retained for modifications and corrections
Object program- Loaded into the computer’s memory for execution.

Interpreter:
It translates one statement at a time and if it is error free executes the instructions and
so on.

Difference between compiler & interpreter


Compiler Interpreter
1. Error correction (called debugging) is here error correction issimpler
Somewhat tedious. Since it produces an error
.because it is done in stages
list for the entire program before execution of
even the first instruction can begin.
2. Programs are executed fastly. Here, it takes more time for execution, because a
statement has to be translated every time
the program is executed
Execution of a program:
This is basically a two step process.
1. The source program is first compiled.
2. Then it is converted into object program and loaded into memory

Programming Techniques
Three types of techniques:
1. Top down approach->Ex: C-language
2. Bottom Up approach -> Ex: C++
3. Modular Programming

History of C:
Year Language Developed By Remarks
1960 ALGOL International committee too general,
Too abstract
1963 CPL Cambridge University Hard to Learn
Difficult to
implement
1967 BCPL Martin Lichards at Too specific
Cambridge University could deal
with only specific problems

1970 B Ken Thampson at Too specific could


AT&T’S Bell Labs deal with only
specific problems
1972 C Dennis Ritchie at Host
generality of
AT&T’s Bell labs BCPL & B
Restored.

C is a Middle Level Language:


Reason:
Basically programming Languages are classified into two categories
1. Problem oriented language: [HLL-High Level Language]
i) Design to give a better program efficiency.
ii) Faster Program development.
2. Machine Oriented Language: [LLL-Low Level Language]
i) Design to give a better Machine efficiency.
ii) Faster Program execution
C is designed to satisfy these two conditions. Hence, it is called as Middle level
Language.
C is a Structured Programming Language:
Reason:
Structured programs used only 3 basic constructs.
1. Sequential structure- Steps are performs one after another in succession. (Step by step
action)
2. Selection Structure – Implemented with an If then else (or) case statement.
3. Repetition Structure – Implemented with a for, while (or) Repeated statements.

Features of C:
1. Economy of expressions
2. Modern control flow and structures
3. Rich set of operators.

Characteristics of C:
1. Size of Language
2. Modern Control structures [if statement, if… else statement, case statement, while loop, for
loop, do…while loop]
3. Bitwise control
4. Pointer Implementation
Uses of C:
1. System Applications:
a) Operating System
b) Interpreters
c) Editors
d) Assembly Programs
e) Compilers
2. Database Systems
3. Graphics Package
4. Spread sheet
5. Word processors
6. CAD/CAM applications
7. Office Automations
8. Scientific and Engineering applications
C-Character sets:
A to Z
1 to 9
a to z
Special characters:
+ - * /(division) %(Modulus) #(hash) $(dollar) ~(tilde) {}(curly brackets) ()(Open and
Close brackets) [](square brackets) , . ; : ’ ” _ @(at) ? < > ! & (ambersand) ^ (exponent) \
(backslash) | (Pipe symbol)

Data Types:

Data Types

Primary Data Types Secondary Data Types


(Or) (Or)
Built in data Types User defined Data Types

1. Integer 1. Arrays
2. Float 2. Pointers
3. Character 3. Structures
4. Double 4. Unions
5. Void (meaning less data) 5. Enums
Primary Data Types:
1. Integer:
A Positive or Negative whole Number
2. Float:
A number having decimal point (either positive or negative)
3. Character:
A single character represented within single quote.
4. Double:
Floating Point Number having exponent
5. Void:
Meaning less data.
Secondary Data types:
1. Arrays:
It is a collection of similar / like data types, which occupies the adjacent memory
location.
2. Pointers:
It is a special type of variable which is used to store the address of another variable
3. Structures:
It is a collection of unlike data types which occupies the adjacent memory location.
4. Unions:
It is same as structure but uses the same memory location.
5. Enums
This gives us an opportunity to define our own data types and determine what values it
can take.
Constants:
A value that does not change.
C Constant

Character type Numeric type

Character constant string integer real


Constant constant constant

Unsigned long short integer Float Double

Integer Constant
This is an integer quantity
Rules for constructing Integer constant
1. It must have at least one digit
2. It must not have a decimal point
3. It could be either positive or negative.
4. If no sign precedes an integer constant it is assumed positive.
5. No commas or blanks are allowed within an integer constant.
6. Range -32768 to +32767
7. It occupies two bytes
e.g.:
425,-68,78

Long Integer
1. It occupies 4 bytes
2. Range -2,14,74,83,648 to +2,14,74,83,647
e.g.:
3456789,-2345897

Short integers
Ordinary integers

Unsigned Integer
If we declare an integer as unsigned, the range will change to 0 to 65535. Declaring this
will free the 16th bit and is used to store the number. It occupies two bytes in memory
E.g.:
89, 67.
Long unsigned Integer
1. Range 0 to 4294967295
2. It occupies two bytes.
E.g.:
567897, 5683452
Note
By default, a short int is an unsigned short integer and a long integer is an unsigned long
integer.

Real constants
It is often called as floating point constant. It occupies four bytes in memory
Rules for constructing real constant expressed in fractional form
1. It must have at least one digital
2. It must have a decimal point.
3. It could be either positive or negative.
4. Default sign is positive.
5. No commas are blanks are allowed within a real constant.
E.g.:
+325.34,-35.78
Rules for constructing real constant expressed in exponential form
1. Mantissa part and exponent part should be separated by a letter e.
2. Mantissa part may have a Positive or negative sign.
3. Default sign of mantissa part is positive.
4. The exponent must have at least one digit, which must be a positive or a negative integer.
Default sign is positive.
5. Range -3.4e38 to +3.4e38
Double
Real constant with a precision of 16 digits are called as double constant. It occupies 8
bytes in memory.
Character constant
It is a single character enclosed within single quotes.
Range -128 to +127
It occupies one byte in the memory.
E.g.:
‘a’ ,’7’
String constant
Collection of characters enclosed within double quotes is called as string constant.
String constant are terminated by a null (‘\0’) character.
E.g.:
“hello” , “4567”

Variable:
A name given to the memory location where the constant value is stored in the memory.

Rules for constructing variable Names


1. Variable name is any combination of 1 to 8 alphabets, digits or underscores.
2. First character must be an alphabet
3. No commas or blank spaces are allowed within a variable name.
4. No special symbols other than an underscore can be used in a variable name.

Variable Declaration:
Syntax:
data type variable name;
Eg:
int a;
float b;
char c;
char name[30];
int a, b;

Scope of variables
Local – Available only to certain selected statements in the program. It is defined inside a
function
Global – It is accessible to all the statements in the function. It is declared outside the
function.

C keywords
Keywords are the words whose meaning has already been explained to the C compiler.
It cannot be used as variable names. There are 32 keywords available in C.
They are

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

C-PROGRAM

It is collection of functions. Every C program must have a main ( ). The program


execution starts from the main function. A function name is always followed by a pair of
parantheses ().Apart from these each C-Compiler provides a library of around 200 predefined
functions and macros designed for use in C Programs.
For using these functions, certain files must be included in the program which makes call
to these functions. These files are known as header files. It contains macro definitions and
function declarations. It has an extension .h. The statements within a function are always
enclosed within a pair of curly brackets { }.
Some Common Header files:
1. stdio.h –Contains standard Input and output functions
2. conio.h – Contains console Input and output functions
3. math.h – Contains Mathematical functions
4. string.h – Contains string Input and output functions
5. graphics.h – Contains graphical functions

Escape sequences
Certain ASCII characters are unprintable, which means they are not displayed on the
screen or printer. Those characters perform other functions aside from displaying text. Escape
sequences usually consist of a backslash and a letter or a combination of a digit. An escape
sequence is regarded as a single character and is therefore valid as a character constant.
Escape sequences are typically used to specify actions such as carriage return and tab
movements on terminals and printers. The commonly used escape sequences are listed below.
Escape sequences Represents
\a Bell (alert)
\b Backspace
\f Form feed
\n new line
\r Carriage Return
\t Horizontal tab
\v Vertical tab
\’ Single quotation Mark
\’’ Double Quotation Mark
\? Literal Quotation Mark
\\ Backslash
\0 NullString Terminate

Format of a C Program:
#include<header file>
main()
{
Variable declarations;
clrscr();
Program statements;
getch();
}
Ex:
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,sum;
clrscr();
printf(“Enter the values for a and b:”);
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“Sum=%d”,sum);
getch();
}
Standard Input and Output Functions:
Standard Input function:
scanf( )
Syntax:
scanf(“format string”, list of address variable);
Definition:
This function accepts the input value from the keyboard and stores it into the
corresponding memory location.
Ex:
scanf(“%d”,&a);
scanf(“%f%f”s,&a,&b);
Conversion character:
%d  Data item is a decimal integer
%f  Data item is a floating point value
%s  Data item is a string
%c  Data item is a character
%lf  Data item is a double
%ld  Data item is a long integer.
&  Address Operator
2. Standard output function:
printf( )
Syntax:
printf(“format string”, list of variables);
Description:
This function prints the given output on the screen.
Ex:
printf(“%d”,sum);
printf(“Enter the values for a and b”);
printf(“Sum=%d”,sum);

Ex 1:
Program for Addition:
#include<stdio.h>
#include<conio.h>
main( )
{
int a,b,sum;
clrscr();
printf(“Enter the values for a&b:”);
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“Sum=%d”,sum);
getch( );
}
Character Input Output function:
Single character Input function:
getchar( );
Syntax:
Variable name=getchar( );
Description:
This function inputs a single character from the keyboard and converts it into the
equivalent ASCII value.

Ex:
C=’A’
C=getchar( );
Single character Output function:
putchar( );
Description:
This function converts the ASCII value of a single character and displays the result on
the monitor.
Syntax:
Putchar(variable name);
Ex:
putchar(a);
Ex: 2
Program for converting uppercase character into lowercase letter:
#include<stdio.h>
#include<conio.h>
main()
{
int c;
clrscr();
printf(“Enter an upper case letter”);
c=getchar();
printf(“Lowercase=”);
putchar(c+32);
getch();
}
Standard string Input output functions:
Standard String Input Function:
gets( );
Syntax:
Variable name=gets( );
Description:
This function inputs the string given in the keyboard and stores it into the corresponding
memory location.
Ex:
Name=”Kavitha”
Name=gets( );
Standard String Output function:
puts( );
Syntax:
puts(variable name);
Description:
This function prints the string on the monitor.
Ex: 3
#include<stdio.h>
#include<conio.h>
main( )
{
char name[30];
clrscr( );
puts(“Enter your name”);
gets(name);
puts(“Your Name is:”);
puts(name);
getch();
}

Operators:
Five types:
1. Arithmetic operators
2. Unary Operators
3. Relational and Logical Operators
4. Assignment Operators
5. Conditional Operators
1. Arithmetic Operators:
To do arithmetical calculations.
1. +  Addition
2. -  Subtraction
3. *  Multiplication
4. /  Division (Quotient)
5. %  Division (Reminder)

2. Unary Operators:
1. --  Unary Minus (To represent Negative Number)
2. ++  Increment Operator
Two types
1. Preincrement operatorEx: ++i
2. Post increment OperatorEx: i++
3. --  Decrement Operator
Two Types
1. Predecrement OperatorEx:--i
2. Post decrement OperatorEx:i--
4. sizeof  To print the size of data types.

Ex: 4
#include<stdio.h>
#include<conio.h>
main()
{
int i=1;
clrscr();
printf(“i=%d\n”,i);
printf(“i=%d\n”,++i);
printf(“i=%d\n”,i);
getch();
}
Similarly do this program by changing i++,--i,i--)

Ex:4
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf(“Integer=%d\n”,sizeof(int));
printf(“Float=%d\n”,sizeof(float));
printf(“Character=%d\n”,sizeof(char));
printf(“Double=%d”,sizeof(double));
getch();
}

3.Relational Operators
>  greater than
<  less than
>=  greater than or equal to
<=  less than or equal to
==  perfectly equal to
!=  not equal to
Logical Operators
&&  logiacl and
||  logical or
!  logical not

4. Assignment operator
=
It is used to assign values to a variable.
Syntax:
Identifier=expression;
Eg:
A=2
B=5.6

5. Conditional Operator
It is also called as ternary operator.
Syntax:
expression 1? expression 2 : expression 3;
Here expression 1 is evaluated first and if it is true, expression 2 is evaluated and assign the
value to expression 3.
If expression is false, then expression 2 is not evaluated, and the initial value is assigned
to expression 3.
Eg: 5
#include<stdio.h>
#include<conio.h>
main()
{
int num,absolute;
clrscr();
printf(“Enter any no:”);
scanf(“%d”,&num);
absolute=(num<0)?-num:num;
printf(“Absolute value=%d”,absolute);
getch();
}

Hierarchy of Operators
1.Parantheses
2. Unary Operators
3. Multiplication and division
4. Subtraction and addition
5. Relational operator
6...Equality checking
7. Logical operations
8. Conditional checking
9. Assignment operator

Type casting
Converting one data type to another is called as casting. For sometimes certain
variables declared as float might be required as int for some expressions. For that purpose the
cast is used.
General form
(data type) expression
Eg:
Let a, b are float variables and c integer variable
If we want to use a and b as int in some expression then we can change this as follows
((int)(a+b))+c;
Here a+b is converted to int and then added with c. After the execution of this expression and b
will be returned as float variables.

Control Statements

It determines the flow of control in a program.

Control statements

Conditional control statements Unconditional control statements

1. simple if statement 1. go to statement


2. if else statement 2. continue
3. Nested if statement 3. break
4. Switch case statement

5. Looping statements
1.for statement
2. while statement
3. do while statement

Conditional control statements


1. simple if statement
Syntax:
If (condition)
Statements;
E.g.:

#include<stdio.h>
#include<conio.h>
main()
{
int pos;
clrscr();
printf(“Enter a no:”);
scanf(“%d”,&pos);
if (pos>0)
printf(“The given no is a positive number”);
getch();
}

2. if else if statement
syntax:
if (condition)
statements;
else
statements;
eg:
#include<stdio.h>
#include<conio.h>
main()
{
int pos;
clrscr();
printf(“Enter any no:”);
scanf(“%d”,&pos);
if (pos>0)
printf(“The given no is a positive no”);
else
printf(“The given no is a negative no”);
getch();
}
3.Nested if statement
syntax:
if (condition)
statements;
elseif (condition)
statements;
else
statements;

eg:
#include<stdio.h>
#include<conio.h>
main()
{
int pos;
clrscr();
printf(“Enter any no:”);
scanf(“%d”,&pos);
if(pos>0)&&(pos!=0)
printf(“The given no is a positive no”);
elseif(pos<0)&&(pos!=0)
printf(“The given no is a negative no”);
else
printf(“The given no is a zero);
getch();
}
4. switch case statement
It allows us to make a decision from the number of choices .The keyword case is
followed by an integer constant or a character constant.
First, the expression is evaluated and if the value matches any one of the case
statement then the corresponding statement is evaluated. If there is no match then the
statements below, default is evaluated.
Syntax:
switch(expression)
{
case 1:
statements;
break;
case 2:
statements;
break;
case 3:
statements;
break;
default:
statements;
}
eg:
#include<stdio.h>
#include<conio.h>
main()
{
char code;
clrscr();
printf(“Enter a code[a/m/p]:”);
scanf(“%c”,&code);
switch(code)
{
case ‘a’ :
printf(“Accounts staff”);
break;
case ‘m’ :
printf (“Management staff”);
break;
case ‘p’ :
printf (Purchase staff”);
break;
default :
printf (“Invalid choice ! Try again”);
}
getch();
}

Looping statements
1. for loop
syntax:
for (expression 1 ; expression 2; expression 3)
statements;
where
expression 1  initialization statement
expression 2  condition checking statement
expression 3  increment or decrement operator

eg:
#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
clrscr();
printf(“Enter the range:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
printf(“i=%d\n”,i);
getch();
}

2. while loop
syntax:
while ( condition)
{
statements;
}
eg:
#include<stdio.h>
#include<conio.h>
main()
{
int n,i=0;
clrscr();
printf(“Enter the range:”);
scanf(“%d”,&n);
while(i<n)
{
printf(“i=%d\n”,i);
i++;
}
getch();
}

3. do……. While loop


The do while statement test the condition after having executed the statements within
the loop.
This means it will executes the statements at least once even if the condition fails for the
first time itself.
syntax:
do
{
statements;
} while(condition);
eg:
#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
clrscr();
printf(“Enter the range:”);
scanf(“%d”,&n);
do
{
printf(“i=%d\n”,i);
i++;
}while(i<n);
getch();
}

Unconditional control statements


1. break statement
It is used to terminate from the loop.This statement is used with for, do while,switch case
statements.
Eg:
#include<stdio.h>
#include<conio.h>
main()
{
int x=1;
clrscr();
while (x<=10)
{
printf(“x=%d\n”,x);
if(x==5)
break;
x++;
}
getch();
}

2. continue statement
This statement will take the control to the beginning of the loop.It can be included only in
a while, do while, for statement.

3. goto statement
It transfers the control to anywhere in the program. Avoid using this statement.
Some important programs
1. Program for Factorial
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,f=1;
clrscr();
printf("Enter any no:");
scanf("%d",&n);
for(i=1;i<=n;i++)
f=f*i;
printf("Factorial value=%d\n",f);
getch();
}
2. Program to count the number of digits
#include<stdio.h>
#include<conio.h>
main()
{
int n,c=0;
clrscr();
printf("Enter a no:");
scanf("%d",&n);
while(n!=0)
{
n=n/10;
c++;
}
printf("The total no of digits are:%d",c);
getch();
}
3. Program to reverse a given no
#include<stdio.h>
#include<conio.h>
main()
{
int x,rev=0,rem,i;
clrscr();
printf("Enter the value to be reversed:");
scanf("%d",&x);
while(x>0)
{
rem=x%10;
rev=rev*10+rem;
x/=10;
}
printf("The reversed no is %d",rev);
getch();
}
4. Program to check the given no is prime or not
#include<stdio.h>
#include<conio.h>
main()
{
int n,i;
clrscr();
printf("Enter the no:");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i!=0)
continue;
else
break;
}
if(i==n)
printf("The given no is a prime number");
else
printf("The given number is not a prime number");
getch();
}
5. Program to generate Fibonacci series
#include<stdio.h>
#include<conio.h>
main()
{
int a=0,b=1,c,i,n;
clrscr();
printf("Enter the range:");
scanf("%d",&n);
printf("%d\t",a);
printf("%d\t",b);
for(i=3;i<n;i++)
{
c=a+b;
a=b;
b=c;
printf("%d\t",c);
}
getch();
}
6. Program to find the sum of n natural numbers
#include<stdio.h>
#include<conio.h>
main()
{
int i,n,sum=0;
clrscr();
printf("Enter the range:");
scanf("%d",&n);
for(i=1;i<=n;i++)
sum=sum+i;
printf("Sum of %d natural numbers are %d",n,sum);
getch();
}
7. Program to find the sum of digits
#include<stdio.h>
#include<conio.h>
main()
{
int n,sum=0,a;
clrscr();
printf("Enter the value to sum:");
scanf("%d",&n);
while(n>0)
{
a=n%10;
sum=sum+a;
n=n/10;
}
printf("The summed digit is %d",sum);
getch();
}
8. Program to check the given no is Armstrong or not
#include<stdio.h>
#include<conio.h>
main()
{
int n,j,s=0,a;
clrscr();
printf("Enter a no:");
scanf("%d",&n);
j=n;
while(n>0)
{
a=n%10;
s=s+a*a*a;
n=n/10;
}
if(s==j)
printf("The given no is an armstrong no");
else
printf("The given no is not an armstrong no");
getch();
}
9. Program to generate prime numbers
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,j;
clrscr();
printf("Enter the range:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=2;j<=i;j++)
{
if(i%j!=0)
continue;
else
break;
}
if(j==i)
printf("%d\t",i);
else
continue;
}
getch();
}
program to generate Armstrong Numbers from 1 to 1000:

#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,i,j,n1,r;
clrscr();
printf("Enter range");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=0;
n1=i;
j=n1;
while(j>0)
{
r=j%10;
sum=sum+(r*r*r);
j=j/10;
}
if(n1==sum)
printf("%d\t",n1);
else
continue;
}
getch();
}

Array
Array is nothing but a collection of like data types. These similar elements could
be all ints, or all floats, or all chars etc. Usually the array of characters is called a string,
whereas an array of ints or floats is called simply an array.
Array Declaration
Syntax:
data type variable name[dimension];
e.g.:
int a[10];
float c[5];
char name[40];
Accessing elements of an array
We can access array elements by using a subscript. This subscript variable can
take different values and hence can refer to the different elements in the array in turn.
Points to remember.
1. An array is a collection of similar elements.
2. The first element in the array is numbered 0, so the last element is less then the size
of the array.
3. An array is also known as the subscripted variable.
4. Before using an array its type and dimension must be declared.
5. An array elements are always stored in adjacent memory location.
6. Array starts from the 0th location.
Two types of array
1. Single dimensional array.
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
int mark[10],avg,n,sum=0,i;
clrscr();
printf("Enter how many nos:");
scanf("%d",&n);
for(i=0;i<n;i++) /* store datas in an array */
{
printf("Enter marks one by one:");
scanf("%d",&mark[i]);
}
for(i=0;i<n;i++)
sum=sum+mark[i]; /* read data from an array */
avg=sum/n;
printf("Average marks=%d",avg);
getch();
}
Array Initialization
1. If the array elements are not given any specific values, they are supposed to contain
garbage values.
2. If the array is initialized where it is declared, mentioning the dimension of the array is
optional.
3. If the array is initialized where it is declared, its storage class must be either static or
extern.
e.g.:
---
int num[6]={2,4,3,4};
int num[] = { 2,4,4,7,8};
2. Two dimensional array
A two dimensional array is also called as matrix.
Declaration
Syntax:
data type variable name[ row dimension] [ column dimension];
e.g.:
int a[3][3];
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
int stud[4][2];
int i.j;
clrscr();
for(i=0;i<=3;i++)
{
printf(“Enter roll no and marks:”);
scanf(“%d%d”,&stud[i][0],&stud[i][1]);
}
for(i=0;i<=3;i++)
printf(“%d\t%d\n”,stud[i][0],stud[i][1]);
getch();
}

The array elements are being stored and accessed row wise.
Initializing a 2 dimensional array
While initializing an array it is necessary to mention the second (column)
dimension, whereas the first dimension (row) is optional.
e.g.:
int student [4] [2] = {
{124,89},
{125,90},
{145,90}
};
Multidimensional Array
A three dimensional array can be thoght of as an array of arrays. In practice, one
rarely uses this array.
E.g.:
int stud [2] [2] [2] = {
{
{2,3},
{4,8},
{ 8,10}
},
{
{ 3,8},
{9,7},
{7,5}
}
};

Strings or Character Arrays


A string constant is a one-dimensional array of characters terminated by a null.
E.g.:

char name [] = { ‘k’,’a’,’v’,’I’,’t’,h’,’a’,’\0’};


or
char name[10] = “Kavitha”;
eg:
----
#include<stdio.h>
#include<conio.h>
main()
{
char name[10]="Lavanya";
int i=0;
clrscr();
while(name[i]!='\0')
{
printf("%c",name[i]);
i=i+1;
}
getch();
}
Note
1. The length of the string should not exceed the dimension of the character arry.
2. scanf() is not capable of receiving multiword strings. So in that case we can use gets
() instead of scanf ().
Some important programs
Matrix addition
#include<stdio.h>
#include<conio.h>
main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("Enter the first matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:",i+1);
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("Enter the second matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:",i+1);
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}
clrscr();
printf("The Matrix Addition is below\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("\t%d",c[i][j]);
}
printf("\n");
}
getch();
}

Matrix multiplication
#include<stdio.h>
#include<conio.h>
main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
clrscr();
printf("Enter the first matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:\n",i+1);
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("Enter the second matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:\n",i+1);
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}
clrscr();
printf("The matrix multiplication is below\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][i];
}
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
Program to find the Maximum of n numbers
#include<stdio.h>
#include<conio.h>
main()
{
int a[10],big,i,n;
clrscr();
printf("Enter no of values:");
scanf("%d",&n);
printf("Enter the values one by one:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
big=a[0];
for(i=1;i<n;i++)
{
if(big<a[i])
{
big=a[i];
}
}
printf("Biggest no is:\n");
printf("%d\n",big);
getch();
}

Program for ascending order


#include<stdio.h>
#include<conio.h>
main()
{
int a[10],temp,i,j,n;
clrscr();
printf("Enter the no of values:\n");
scanf("%d",&n);
printf("Enter the values:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Ascending order values \n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
getch();
}

Structures
Structures are collection of unlike data types. Like arrays, structure elements are stored
in contiguous memory locations.
There are two steps to define a structure.
1. Declaration of a structure.
2. Accessing of structure elements.
Declaring a structure
Syntax:
struct structure name
{
struct element 1;
struct element 2;
struct element 3;
};
e.g.:
struct book
{
char bookname[25];
float price;
int bookno;
};

Accessing structure elements


We can access structure elements by using a dot operator. Before the dot there must
always be a structure variable and after a dot there must always be a structure element.
E.g.:
Struct book
{
char name[10];
int pages;
float price;
};
struct book b;
e.g.:
b.name
b.pages
b.price
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
struct book
{
char name[25];
int pages;
float price;

};
struct book b1,b2;
clrscr();
printf("Enter the first book details:\n");
scanf("%s%f%d",b1.name,&b1.price,&b1.pages);
printf("Enter the second book details:\n");
scanf("%s%f%d",b2.name,&b2.price,&b2.pages);
printf("Book details\n");
printf("Name=%s\nPrice=%f\nPages=%d\n",b1.name,b1.price,b1.pages);
printf("Name=%s\nPrice=%f\nPages=%d",b2.name,b2.price,b2.pages);
getch();
}

Like array variables, structure variables are also directly initialized where they are created.
E.g.:
Struct book
{
char name[2];
float price;
int pages;
};
struct book b1={“Basic”,150.40,230};
struct book b2={“C++”,140.60,250};
Array of structures
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
struct book
{
char name[25];
int pages;
int price;
};
struct book b[10];
int i,n;
clrscr();
printf("Enter how many books:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the name,pages,price:\n");
scanf("%s%d%d",b[i].name,&b[i].pages,&b[i].price);
}
for(i=0;i<n;i++)
printf("Name=%s\nPages=%d\nPrice=%d\n",b[i].name,b[i].pages,b[i].price);
getch();
}
Structures within structures ( Nested structure)
eg:
#include<stdio.h>
#include<conio.h>
main()
{
struct address
{
char phone[15];
char city[25];
int pin;
};
struct emp
{
char name[25];
struct address a;
};
struct emp e={"Kavitha","530146","nagpur",10};
clrscr();
printf("Name=%s\nPhone=%s\n",e.name,e.a.phone);
printf("City=%s\nPin=%d",e.a.city,e.a.pin);
getch();
}
Uses of structures
strcutures are used in variety of applications .The most important are in the database
management system.
Unions
Unions are similar to structures 0.The main difference between these two is a structure
enables us to treat a no of different variables stored at different places in memory. A union
enables us to treat the same space in memory at a no of different variables.
Uses of unions
They are useful for applications involving multiple elements , where values need not be
assigned to all the elements at any one of time
Enumerated data types
This gives us an opportunity to invent our own data type and define what values the
variable of this data type can take. The format of the enum definition is similar to that of a
structure.
E.g.:
Enum mar_status
{
single,
married,
divorced,
widowed
};
enum mar_status person 1, person 2;
Like structures, it has two parts:
1. The first part declares the data type and specifies its possible values. These values are called
“enumerators”.
2. The second part declares variables of this data type.
Uses of enum data types
It is used in areas where the values of the variables are known already in advance.
Functions

Definition
Function is a self-contained block of programs that performs a coherent task of some
kind... Every C program can be thought of as a collection of these functions.
There are two types of functions
1. Library functions e.g.: printf() , scanf()
2. User defined functions
User defined functions can be broadly divided into two types
1. Functions without arguments
2. Functions with arguments
1. Functions without arguments
Implementation
Three steps
1. Function prototype declaration
Syntax:
return type function name ();
e.g.:
void message();
void italy();
int sum();
2. Function calling
Syntax:
function name();
e.g.:
----
message();
italy();
sum();
3. Function Definition
Syntax:
return type function name ()
{
body of the function;
}
e.g.:
void message()
{
printf(“Welcome to Functions”);
}
e.g.:
#include<stdio.h>
#include<conio.h>
void message();
void main()
{
clrscr();
printf("I am in main function\n");
message();
getch();
}
void message()
{
printf("Welcome to c program");
}
Points to remember
1. C program is a collection of one or more functions.
2. If a program function only one function it must be main().
3. Program execution always begin with main().
4. There is no limit on the number of functions that might be present in a C program.
E.g.:
#include<stdio.h>
#include<conio.h>
void message();
void usage();
void main()
{
clrscr();
printf("I am in main function\n");
message();
usage();
printf("I am back in main");
getch();
}
void message()
{
printf("I am in message\n");
}
void usage()
{
printf("I am in usage\n");
}
5. Each of the function is called in a sequence specified by the function calls in the main().
6. After each function has done its thing, its control returns to main().
7. A function gets called when a function name is followed by a semicolon.
8. A function is defined when function name is followed by a pair of braces in which one or more
statements may present.
9. Any function can be called from any other function. Even main() can be called from other
function. For e.g.
main()
{
message();
}
message()
{
printf(“I am in C \n”);
main();
}
e.g.:
#include<stdio.h>
#include<conio.h>
void italy();
void brazil();
void main()
{
clrscr();
printf("I am in main function\n");
italy();
printf("I am back in main function");
getch();
}
void italy()
{
printf("Welcome to italy\n");
brazil();
printf("I am back in italy\n");
}
void brazil()
{
printf("I am in brazil\n");
}
10. A function can be called any no of times.
11. The order in which the functions are defined in the program and the order in which they are
called need not necessarily be same.
12. A function can call itself. Such a process is called “recursion”.
13. A function can be called from the other function, but a function cannot be defined in another
function.
Advantages of using functions
1. Writing functions avoids rewriting the same code repeatedly.
2. Using functions it is easier to write programs and keep track of what they are doing.
Functions with arguments
Sometimes we want to communicate between the calling function and the called
function. This is done by using argument.
The mechanism used to convey information to the function is the argument. The
arguments are sometimes also called ‘parameters’.
There are two types of arguments.
1. Actual arguments.
2. Formal arguments.
We must declare the type of the arguments through type declaration statements before
beginning with the statements in the functions.
Syntax:
return type function name(data type arg1, data type arg2,….data type arg n)
{
statements;
}
Similarly, we can call a function in two ways.
1. call by value
2. Call by reference.
Call by value
Definition
It is a method of passing a photocopy of the values to the calling functions.
E.g.:
#include<stdio.h>
#include<conio.h>
int add(int x,int y);
void main()
{
int a,b,sum;
clrscr();
printf("Enter any two nos:");
scanf("%d%d",&a,&b);
sum=add(a,b);
printf("Sum=%d\n",sum);
getch();
}
int add(int x,int y)
{ int z;
z=x+y;
return(z);
}
Points to remember
1. In the above program we are passing a photocopy of the value a, b to the function add(). In
add() these values get collected in the variables x and y.
2. The variables a and b is called as actual arguments. whereas the variables x and y are called
as formal arguments.. Any number of arguments can be passed to a function being called.
However, the type, order and number of the actual and formal arguments must always be same.
3. If we want to return some values to the main function then it is done by using the return
statement. The return statement serves two purposes.
a) On executing the return statement, it immediately transfers the control back to the
calling program.
b) It returns the value present in the parentheses, after return to the calling program.
4. There is no restriction on the number of return statements that may be present in a function.
In addition, the return statement need not always be present at the end is called function.
e.g.:
#include<stdio.h>
#include<conio.h>
int code(int d);
void main()
{
int c;
char letter;
clrscr();
printf("Enter a character:");
c=getchar();
letter=code(c);
printf("Letter=%c",letter);
getch();
}
int code(int d)
{
if(d>=65&&d<=97)
return(d+32);
else
return(d);
}

5. Whenever the control returns from a function some value is definitely returned. If we want the
called function should not return any value in that case, we must mention so by using the
keyword void.
6. A function can return one value at a time.
7. If the return statement does not contain any argument then it will return a garbage value.
8. If the value of the formal argument is changed in the called function, the corresponding
change does not take place in the calling function.
E.g.:
#include<stdio.h>
#include<conio.h>
void num(int b);
void main()
{
int a=20;
clrscr();
num(a);
printf("A=%d",a);
getch();
}
void num(int b)
{
int b=60;
printf("B=%d\n",b);
}
Function declaration and prototypes
Eg:
#include<stdio.h>
#include<conio.h>
float square(float x);
void main()
{
float a,b;
clrscr();
printf("Enter any no:");
scanf("%f",&a);
b=square(a);
printf("Square of %f is %f",a,b);
getch();
}
float square(float x)
{
float y;
y=x*x;
return(y);
}
Scope rule of function
This is decided depending upon the variable, where it is declared.
If the variable is declared inside a function then it is called as local variables, and the
corresponding values of the variables are available within that function only.
If the variable is declared outside a function, then it is called as global variables or
external variable and the corresponding values of the variable are available all over the function.
Calling functions with arrays
Array elements can be passed to a function by calling the function by value or by
reference.
In the call by value, we pass values of array elements to the function, whereas in the call
by reference we pass addresses of array elements to the function.
e.g.:

#include<stdio.h>
#include<conio.h>
void display(int m);
void main()
{
int i;
int marks[]={50,60,70,80,90};
clrscr();
for(i=0;i<5;i++)
display(marks[i]);
getch();
}
void display(int m)
{
printf("%d\n",m);
}
Recursive function
A function can call itself . A function is called ‘recursive’ if a statement within the body of
a function can call the same function. Sometimes called as circular definition. Recursion is thus
the process of defining something in terms of itself.
e.g.:
#include<stdio.h>
#include<conio.h>
int rec(int x);
void main()
{
int a,fact;
clrscr();
printf("Enter any no:");
scanf("%d",&a);
fact=rec(a);
printf("Factorial value=%d",fact);
getch();
}
int rec(int x)
{
int f;
if(x==1)
return(1);
else
f=x*rec(x-1);
return(f);
}
Storage classes in C
A variable in storage class tells us
1. Where the variable would be stored.
2. What will be the initial value of the variable if the initial value is not specifically assigned? (i.e .
. . the default initial vale).
3. Scope of the variable. I.e. in which functions the value of the variable would be available.
4. Life of the variable. i.e. How long would the variable exist.
There are four type of storage class in C.
1. Automatic storage class
2. Register storage class
3. Static storage class
4. External storage class.
1. Automatic storage class
Storage  Memory
Default initial value  an unpredictable value, which is often called as garbage
value.
Scope  Local to the block in which the variable is defined
Life  Till the control remains within the block in which it is
defined.
Eg: 1.
#include<studio.h>
#include<conio.h>
void main ()
{
auto int i;
Clrscr();
printf("i=%d",i);
getch();
}
e.g.: 2
#include<stdio.h>
#include<conio.h>
void main()
{
auto int i=3;
clrscr();
{
{
{
printf("i=%d\n",i);
}
printf("i=%d\n",i);
}
printf("i=%d\n",i);
}
getch();
}
eg: 3
#include<stdio.h>
#include<conio.h>
void main()
{
auto int i=3;
clrscr();
{
auto int i=2;
{
auto int i=1;
printf("i=%d\n",i);
}
printf("i=%d\n",i);
}
printf("i=%d\n",i);
getch();
}
2. Register storage class
Storage  CPU registers
Default initial value  garbage value
Scope  local to the block in which it is defined.
Life  till the control remains within the block in which it is
defined.
e.g.:
---
#include<stdio.h>
#include<conio.h>
void main()
{
register int i;
clrscr();
for(i=1;i<6;i++)
printf("i=%d\n",i);
getch();
}
3. Static storage class
Storage  memory
Default initial value  zero
Scope  local to the block in which it is defined
Life  value of the variable persists between different function
calls.
e.g.:
#include<stdio.h>
#include<conio.h>
void increment();
void main()
{
clrscr();
increment();
increment();
increment();
getch();
}
void increment()
{
static int i=1;
printf("i=%d\n",i);
i=i+1;
}

4. External storage class


Storage  memory
Default initial value  zero
Scope  global
Life  as long as the program does not end.
e.g.:
#include<stdio.h>
#include<conio.h>
int i;
void increment();
void decrement();
void main()
{
clrscr();
printf("i=%d\n",i);
increment();
increment();
decrement();
decrement();
getch();

}
void increment()
{
i=i+1;
printf("i=%d\n",i);
}
void decrement()
{
i=i-1;
printf("i=%d\n",i);
}

Advantages of using storage classes


1. Economise the memory space consumed by the variables.
2. Improve the speed of execution of the program.
Rules for using storage class
1. Use static storage class only if we want the value of a variable to persist between different
function calls.
e.g.:
---
Recursive function.
2. Use register storage class for only those variables, which are being very often used in the
program.
e.g.:
---
Loop counters.
3. Use external storage class for only those variables, which are being used by almost all the
functions in the program.
4. If we do not have any of the express needs mentioned above then use automatic storage
class.
Note
------
Default storage class of a variable is automatic.

Pointers
Pointers are special variables that contain addresses. I.e. it represents the location of a
data item, such as variable or an array element.
Like normal variables, pointer variables should be declared in the beginning of the program.
Pointer Declaration
Syntax:
data type *variable name;
e.g.:
Int *a;
float *cd;
char *name;
Operators in pointers
& - address of operator
* - value at address operator.
E.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
clrscr();
printf("%d\n",i);
printf("%d\n",&i);
getch();
}

Pointer Expressions
Pointer assignment
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *j;
j=&i;
clrscr();
printf("%d\n",i);
printf("%d\n",j);
printf("%d\n",&i);
printf("%d\n",&j);
printf("%d\n",*j);
printf("%d",*(&i));
getch();
}
Pointer Arithmetic
1. Addition of a no to a pointer.
2. Subtraction of one pointer from another pointer.
3. Subtraction of a no from a pointer
4. Comparing two pointers pointing to the objects of the same type.
1. Addition of a no to a pointer
e.g.: 1
#include<stdio.h>
#include<conio.h>
void main()
{
int i=4,*j,*k;
j=&i;
k=&j;
clrscr();
printf("%d\n",i);
printf("%d\n",j);
printf("%d\n",k);
j=j+1;
k=j+3;
printf("%d\n",j);
printf("%d\n",k);
getch();
}
Eg: 2
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3,*x;
float j=1.5,*y;
char k='c',*z;
clrscr();
printf("%d\n",i);
printf("%f\n",j);
printf("%c\n",k);
x=&i;
y=&j;
z=&k;
printf("%d\n",x);
printf("%d\n",y);
printf("%d\n",z);
x++;;
y++;
z++;
printf("%d\n",x);
printf("%d\n",y);
printf("%d",z);
getch();
}
2. Subtraction of a no from a pointer
e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=4,*j;
j=&i;
clrscr();
printf("%d\n",j);
printf("%d\n",&j);
j=j-2;
printf("%d\n",j);
j=j-5;
printf("%d",j);
getch();
}
3. Subtracting one pointer from another pointer
e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int arr[]={10,20,30,40,67,74};
int *i,*j;
i=&arr[1];
j=&arr[5];
clrscr();
printf("%d\t%d",j-i,*j-*i);
getch();
}
Note:
Here both the pointers should point to the same array.
4. Comparing two pointers pointing to the objects of the same type
e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int arr[]={10,20,30,40,50,60};
int *j,*k;
j=&arr[4];
k=&arr[0]+4;
clrscr();
if(j==k)
printf("The two pointers point to the same location");
else
printf("The two pointer points to the different location");
getch();
}
Pointers and Arrays
e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int num[]={24,34,12,44,56,78};
int i=0,*j;
j=&num[0];
clrscr();
while(i<=5)
{
printf("%d\t",j);
printf("%d\n",*j);
i++;
j++;
}
getch();
}
Calling functions with pointers
Call by reference
Here the addresses of actual arguments in the calling function are copied into formal arguments
of the called function.
The advantage of using call by reference is we can alter the actual arguments. However,
in call by value we cannot achieve this.
Using call by reference, we can make a function return more than one value at a time,
which is not possible ordinarily.
E.g.:
#include<stdio.h>
#include<conio.h>
void swap(int *x,int *y);
void main()
{
int a=10,b=20;
clrscr();
printf("Before swapping\n");
printf("a=%d\n",a);
printf("b=%d\n",b);
swap(&a,&b);
printf("After swapping\n");
printf("a=%d\n",a);
printf("b=%d\n",b);
getch();
}
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Calling functions with arrays (call by reference)
e.g.:
#include<stdio.h>
#include<conio.h>
void display(int *n);
void main()
{
static int num[]={55,78,90,78,80,50,79};
int i;
clrscr();
for(i=0;i<=6;i++)
display(&num[i]);
getch();
}
void display(int *n)
{
printf("%d\n",*n);
}
Passing an entire array toa function
e.g.:
#include<stdio.h>
#include<conio.h>
void display(int *j,int n);
void main()
{
static int num[]={50,60,70,80,90,100,110};
clrscr();
display(&num[0],7);
getch();
}
void display(int *j,int n)
{
int i=1;
while(i<=n)
{
printf("Element=%d\n",*j);
i++;
j++;
}
}

Accessing array elemnets in different ways


e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int num[]={40,50,60,70,80,90};
int i=0;
clrscr();
while(i<=5)
{
printf("%d\t",&num[i]);
printf("%d\t",num[i]);
printf("%d\t",*(num+i));
printf("%d\t",i[num]);
printf("%d\n",*(i+num));
i++;
}
getch();
}
Pointers versus arrays
E.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static char arr[10]="Nagpur";
char *s="Nagpur";
clrscr();
printf("%s\n",arr);
printf("%s",s);
getch();
}

First difference
In the above program Nagpur gets stored in arr[] and the base address of it is stored in
s.
Second difference
E.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int arr[10]="Nagpur";
char *s="Nagpur";
clrscr();
s++;
printf("%s\n",s);
arr++;
printf("%s",arr);
getch();
}
Here the Output of s is agpur but the output of an arr is an error message.i.e the compiler
assumes us that we are attempting to change its base address.
Third difference
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
static char arr[]="Nagpur";
char *s="Nagpur";
clrscr();
printf("Size of arr=%d\n",sizeof(arr));
printf("Size of s=%d",sizeof(s));
getch();
}

Another difference between arrays and pointers are the way the size of operator treats them.
In the above program, size of arr is 7 and size of s is 2.
Pointers and two-dimensional arrays
e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int stud[5][2]={
{101,80},
{102,90},
{103,78},
{104,87},
{105,69},
};
int i,j;
clrscr();
for(i=0;i<=4;i++)
{
for(j=0;j<=1;j++)
printf("%d\t",*(*(stud+i)+j));
printf("\n");
}
getch();
}
Array of pointers
Array of pointers is nothing but collection of addresses.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int *arr[4];
int i=31,j=5,k=19,l=71,m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
clrscr();
for(m=0;m<=3;m++)
{
printf("%d\t",arr[m]);
printf("%d\n",*(arr[m]));
}
getch();
}

Array of pointers can even contain the addresses of other arrays.


E.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int a[]={0,1,2,3,4};
static int *p[]={a,a+1,a+2,a+3,a+4};
clrscr();
printf("%d\t%d\t%d",p,*p,*(*p));
getch();
}
Array of pointers is very popular used for storing several strings in memory.
eg:
Static char *names[]={
“kavitha”,
“anitha”,
“harini”,
};
Limitations of array of pointers to strings
1. When we are using an array of pointers to strings we can initialize the strings at the place
where we are declaring, the array. But we cannot receive the strings from keyboard using
scanf().
2. When we are declaring the array it contains garbage value.
Pointers to pointers
e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *j;
int **k;
j=&i;
k=&j;
clrscr();
printf("%d\n",i);
printf("%d\n",&i);
printf("%d\n",j);
printf("%d\n",&j);
printf("%d\n",*j);
printf("%d\n",k);
printf("%d\n",&k);
printf("%d\n",*k);
printf("%d\n",*(&i));
printf("%d",**k);
getch();
}
Pointers to functions
eg:1
#include<stdio.h>
#include<conio.h>
void main()
{
void display();
clrscr();
printf("%d\n",display);
display();
getch();
}
void display()
{
printf("Test for function");
}
EG:2
#include<stdio.h>
#include<conio.h>
void main()
{
void display();
void (*funcptr)();
clrscr();
funcptr=display;
printf("%d\n",funcptr);
(*funcptr)();
getch();
}
void display()
{
puts("Hello");
}
Uses
1. To write memory resident programs.
2.To write viruses or vaccines to remove the viruses
Passing structure elements to functions
1. Passing individual structure elements
e.g.:
#include<stdio.h>
#include<conio.h>
void display(char *s,char *t,int n);
void main()
{
struct book
{
char name[25];
char author[25];
int bno;
};
static struct book b1={"C","Balagurusamy",120};
clrscr();
display(b1.name,b1.author,b1.bno);
getch();
}
void display(char *s,char *t,int n)
{
printf("%s\n%s\n%d",s,t,n);
}

2. Passing entire structure to a function


eg:
#include<stdio.h>
#include<conio.h>
struct book
{
char name[25];
char author[25];
int bno;
};
void display(struct book b);
void main()
{
static struct book b1={"C","Balagurusamy",120};
clrscr();
display(b1);
getch();
}
void display(b)
struct book b;
{
printf("%s\n%s\n%d",b.name,b.author,b.bno);
}

Structure pointers
A pointer pointing to a structure is known as structure pointer
E.g.
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[25];
char author[25];
int bno;
};
static struct book b1={"C","Balagurusamy",120};
struct book *ptr;
ptr=&b1;
clrscr();
printf("%s\n%s\n%d\n",b1.name,b1.author,b1.bno);
printf("%s\n%s\n%d",ptr->name,ptr->author,ptr->bno);
getch();
}

Passing address to a structure variable


#include<stdio.h>
#include<conio.h>
struct book
{
char name[25];
char author[25];
int bno;
};
void display(struct book *b);
void main()
{
static struct book b1={"C","Balagurusamy",120};
clrscr();
display(&b1);
getch();
}
void display(b)
struct book *b;
{
printf("%s\n%s\n%d",b->name,b->author,b->bno);
}

Dynamic Memory allocation


Dynamic memory allocation is the process of allocating memory at the run time.
1. malloc()
Declaration
void *malloc(unsigned int size);
Description
This function allocates space dynamically from the free memory area of memory not
being used by the program.
Argument list
unsigned int size – size is the no of bytes.
Return values
1. void * - This is newly allocated memory’s starting address.
2. (void *) NULL – If the function fails it returns a NULL value.

2. free()
Declaration
void free(void *p);
Description
This function returns previously allocated memory that has to be released, it can be
reused as a subsequent call to malloc().
Argument list
1. void *p – This is the starting address if the previously allocated memory that has to be
released.
2. (void *)NULL – It returns if the functions fails.
E.g.:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>
void main()
{
int *intptr,ctr;
intptr=(int*)malloc(10*sizeof(int));
clrscr();
if(intptr==NULL)
{
printf("Out of memory");
exit(0);
}
for(ctr=0;ctr<10;ctr++)
*(intptr+ctr)=ctr+1;
for(ctr=0;ctr<10;ctr++)
printf("%d\n",*(intptr+ctr));
getch();
}

3.calloc()
Declaration
(void *)calloc(unsigned int number, unsigned int element size);
Description
This functions allocates space dynamically for an array described by its arguments. The
space allocated is cleared.
Argument list
unsigned int no elements
This will be multiplied by the size of element,
Unsigned int element size –
This is the size of the element.
Return values
void * - This is the newly allocated memory’s starting address,
(void *)NULL – this is returned if the function fails.
E.g.:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>
#include<math.h>
void main()
{
double *sptr,*eptr,*cnt;
unsigned int n;
clrscr();
printf("Enter the range:");
scanf("%d",&n);
sptr=(double*)calloc(n,sizeof(double));
if(sptr==NULL)
{
printf("Out of memory");
exit(0);
}
eptr=sptr+n;
for(cnt=sptr;cnt<eptr;cnt++)
*cnt=sqrt((double)(cnt-sptr));
printf("\n X \t Sqrt(X) =\n\n");
for(cnt=sptr;cnt<eptr;cnt++)
printf("%d\t%f\n",(cnt-sptr),*cnt);
free((void *)sptr);
getch();
}
Difference between malloc and calloc functions
malloc() calloc()
1. Here the default initial value Here the default initial
is zero value is a garbage value
2. Here only one argument is used. Here two arguments are used

4. realloc()
syntax:
(void *) realloc (ptr, unsigned int size);
Description
This function is used to increase or reduced the allocated block of memory that was
allocated using malloc or calloc function.
Argument list
1.void *ptr – This is the return value from the last call to calloc or malloc functions
2. unsigned int size – this is the size of the new region in bytes.
Return values
void * - starting address of the block of the memory.
( void * ) NULL – this will be returned if the function fails.
E.g.:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>
#include<math.h>
void main()
{
double *sptr,*eptr,*cnt;
clrscr();
sptr=(double*)calloc(6,sizeof(double));
if(sptr==NULL)
{
printf("Out of memory");
exit(0);
}
eptr=sptr+6;
for(cnt=sptr;cnt<eptr;cnt++)
*cnt=sqrt((double)(cnt-sptr));
printf("\n X \t Sqrt(X) =\n\n");
for(cnt=sptr;cnt<eptr;cnt++)
printf("%d\t%f\n",(cnt-sptr),*cnt);
free((void *)sptr);
printf("Reallocate larger block of memory\n");
sptr=(double*)realloc((void*)sptr,10*sizeof(double));
eptr=sptr+10;
for(cnt=sptr;cnt<eptr;cnt++)
*cnt=sqrt((double)(cnt-sptr));
printf("\n X \t Sqrt(X) =\n\n");
for(cnt=sptr;cnt<eptr;cnt++)
printf("%d\t%f\n",(cnt-sptr),*cnt);
free((void *)sptr);
getch();
}
Files

collection of informations or data


Two types
1. Stream oriented data files
2. System oriented data files.
Stream oriented data files
1. Text files
4. close
Establishing a buffer area
The buffer area is a area, where information is temporarily stored while being transferred
between the computer’s memory and the dta file.
Syntax:
FILE *ptr;
Where
FILE – special structure type that establishes the buffer area.
ptr - pointer variable.
Opening a file
fopen()
syntax:
(FILE *) fopen(filename,mode);
This function opens a file and establishes a current offset within the file.
Argument List
1. (char *) filename – starting address of the character string describing the name of the file.
2. (char *) mode – describes the action to be performed on the file and governs the initial offset
in the file.
Return values
1. FILE * - Returned for successful open
2. ( FILE *) NULL – returned if the file cannot open.
File opening modes
Mode Operations possible
1. “r” reading from a file.
2. “w” writing to the file
3. “a” appending new contents at the end of the file.
4. “r+” reading existing contents,writing new contents,modifying existing contents of the file.
5. “w+” writing new contents, reading them back and modifying contents of the file.
6.”a+” reading existing contents, appending new contents to end of file, cannot modify existing
contents.
2. Closing a file
fclose()
syntax:
int fclose(file pointer);
This function closes the specified file and releases any of the file pointer. If the program
exists without closing a file the system will automatically close the file through proper calls to
function fclose().
Argument list
1. (FILE *) stream – This is the return value for the fopen() and is used to identify which file is
closed
Return values
1. 0 – for succesful file closing.
2. EOF – this means an error was encountered.
eg:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
clrsscr();
fptr=fopen("Sample.txt","w");
if(fptr==NULL)
{
puts("Cannot open file");
exit(0);
}
fclose(fptr);
getch();
}
Processing a data file
1. Writing to a file
fprintf(), fputs(), fputc() are used to write datas into the files.
1.fputc()
This function writes a single character to the file at the current position.
Syntax:
Int fputc(c,stream);
Argument list
1. int c – character to be written
2. stream – pointer to file structure.
Return values
1. int – the value of character return.
2. EOF – indicates an error
eg:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *textfile;
char str,ch;
char filename[15];
clrscr();
puts("Enter a file name:");
gets(filename);
tesxtfile=fopen(filename,"w");
if(textfile==NULL)
{
puts("Cannot open file");
exit(0);
}
printf("Enter file contents [Press ^ to stop] \n");
do
{
str=getchar();
fputc(str,textfile);
}while(str!='^');
fclose(textfile);
getch();
}

2.fputs()
It copies string to the output file at the current position. The terminating character null is not
copied.
Syntax:
Int fputs(str,stream);
Argument list
1. char * str – pointer to the string to be output.
2. stream – file pointer.
Return values
1. int ( > 0) – positive value if successful.
2. EOF – error.
Eg:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
FILE *fp;
char s[120];
char filename[15];
clrscr();
puts("Enter a file name:");
gets(filename);
fp=fopen(filename,"w");
if(fp==NULL)
{
puts("Cannot open file");
exit(0);
}
printf("Enter file contents [Press 'end' to stop] \n");
while(strcmp(gets(s),"end")!=0)
fputs(s,fp);
fclose(fp);
getch();
}
3. fprintf()
This function prints the formatted data into the fiile.
Syntax:
Int fprintf(stream,format,argument);
Argument list
1. stream – file pointer
2. format – format string
3.arguments – list of variables.
Return values
1. int ( > 0) – positive value for successful
2. (<0) – negative value for unsuccessful.
Eg:
---
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
char name[40],filename[15];
char ans='y';
int age;
float bs;
clrscr();
puts("Enter a filename:");
gets(filename);
fp=fopen(filename,"w");
if(fp==NULL)
{
puts("cannot open file");
exit(0);
}
while(ans=='Y'||ans=='y')
{
printf("Enter name,age,basic pay:\n");
scanf("%s%d%f",name,&age,&bs);
fprintf(fp,"%s%d%f\n",name,age,bs);
printf("Another employee(y/n):");
fflush(stdin);
scanf("%c",&ans);
}
fclose(fp);
getch();
}

Reading from a file

fscanf(),fgetc(), fgets().
1. fgetc()
syntax:
int fgetc(stream);
It reads a single character from the current position of the file associated with the stream.
Argument list
1. stream – file pointer.
Return values
1. int – value of character read.
2. EOF – indicates an error.
Eg:
---
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char filename[15];
char str;
clrscr();
puts("Enter a file name:");
gets(filename);
fptr=fopen(filename,"r");
if(fptr==NULL)
{
puts("Cannot open file");
exit(0);
}
str=fgetc(fptr);
while(str!=EOF)
{
putchar(str);
str=fgetc(fptr);
}
fclose(fptr);
getch();
}
2. fgets()
syntax:
char *fgets(str,n,stream);
This reads a string from the input stream argument and stores it in str.
Argument list
1. char *str – storage location of data.
2. int n – no of chracters stored.
3. stream – file pointer.
Return values
char – string address of str.
NULL – error.
Eg:
---
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
char line[251];
FILE *fp1,*fp2;
char filename1[15],filename2[15];
clrscr();
puts("Enter source filename:");
gets(filename1);
puts("Enter target filename:");
gets(filename2);
fp1=fopen(filename1,"r");
if(fp1==NULL)
{
puts("Cannot open file");
exit(0);
}
fp2=fopen(filename2,"w");
if(fp2==NULL)
{
puts("Cannot open file");
exit(0);
}
while(fgets(line,251,fp1)!=NULL)
{
fputs(line,fp2);
printf("\n%s",line);
}
fclose(fp1);
fclose(fp2);
getch();
}0
3.fscanf()
syntax:
int fscanf(stream,format,argument);
It reads the formatted data from a stream.
Argument list
1. stream – file pointer.
2. format – format control string
3. argument- list of address variables.
Return values
1. int > 0 – no of strings that were successfully converted and assigned.
2. 0 – no values were assigned.
EOF – error.
eg:
---
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
char filename[15];
int age;
float bs;
char name[25];
clrscr();
puts("Enter a filename:");
gets(filename);
fp=fopen(filename,"r");
if(fp==NULL)
{
puts("Cannot open file");
exit(0);
}
while(fscanf(fp,"%s%d%f",name,&age,&bs)!=EOF)
printf("%s\n%d\n%f\n",name,age,bs);
fclose(fp);
getch();
}

Random Access using files


1. fseek()
syntax:
fseek(fp,unsigned int no,unsigned int no);
It shifts the position of the pointer.
Arguments
1. fp – file pointer.
2. unsigned int no – long int which specifies the no of bytes that has to be shifted.
3. unsined int no – an integer specifiying the position of the file pointer from where the pointer
would be shifted.
Values of offset
0– beginning of the file.
1 – current position
2 – end of the file.
Return values
0 – successful
1 – unsuccessful

1. fseek(fp,0,0);
2. fseek(fp,5,0);
3. fseek(fp,-2,1);
4.fseek(fp,-4,2);
2. ftell()
It returns the current offset position in the file.
For eg as soon as the file is opened , this function returns 1.
Syntax:
Long int position = ftell(filepointer);
3. rewind()
This function enables repositioning of the
pointer at the beginning of the file.
Syntax:
Rewind(filepointer);
File I/O using structures
For reading and writing a whole record in structure format character I/o and line I/O
function will not help.
Writing records on to file
fwrite()
It allows a structure to be written as a whole into a file.
Syntax:
fwrite(&structure, size of one record, no of records,file pointer);
Arguments
1. & structure – passes the address of the data to be written to the function.
2.sizeof – size of the data to be written.
3.no of records – no of records to be written . Any no of records can be written using one
fwrite().
4. file pointer – file pointer.
Eg:
fwrite( & emp1, sizeof(struct employee), 1, fp);
ex:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct employee
{
char name[20];
int rollno;
float salary;
}emp1;
void main()
{
FILE *fp;
char filename[15];
char ans='y';
clrscr();
puts("Enter a file name:");
gets(filename);
fp=fopen(filename,"r");
if(fp==NULL)
{
puts("Cannot open file");
exit(0);
}
while(ans=='y')
{
printf("Enter structure details:");
scanf("%s%d%f",emp1.name,&emp1.rollno,&emp1.salary);
fwrite(&emp1,sizeof(struct employee),1,fp);
printf("Another employee:");
fflush(stdin);
scanf("%c",&ans);
}
fclose(fp);
getch();
}
Reading records from file
fread()
It reads enables records to be read as a whole from files.
Syntax:
Similar to fwrite()
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct employee
{
char name[20];
int rollno;
float salary;
}emp1;
void main()
{
FILE *fp;
char filename[15];
char ans='y';
clrscr();
puts("Enter a file name:");
gets(filename);
fp=fopen(filename,"r");
if(fp==NULL)
{
puts("Cannot open file");
exit(0);
}
while(fread(&emp1,sizeof(struct employee),1,fp)==1)
{
printf("Name=%s\t",emp1.name);
printf("Rollno=%d\t",emp1.rollno);
printf("Salary=%f\n",emp1.salary);
}

fclose(fp);
getch();
}
Command line arguments:
The arguments that we pass on to main() at the command prompt are called command
line arguments. The function main() can have two arguments namely argc and argv. Out of
these arvgv is an array of pointers to strings and argc is an int whose value is equal to the
number of strings to which argv points. When the program is is executed, the strings on the
command line are passed to main.
Ex:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main(int argc,char *argv[])
{
FILE *fsource,*ftarget;
char ch;
if(argc==3)
{
fsource=fopen(argv[1],"r");
ftarget=fopen(argv[2],"w");
ch=fgetc(fsource);
while(ch!=EOF)
{
fputc(ch,ftarget);
ch=fgetc(fsource);
}
fcloseall();
}
else
{
printf("Wrong no of parameters(s)\n");
exit(1);
}
getch();
}

Linked List

A linked list is a collection of structures, called data items or nodes. Linked list are used
for two purposes.
1. To create arrays of unknown size of memory. If the amount of storage is known in advance
then a simple array can be used..If the actual size of the array is not known then linked list can
be used.
2. It is used for the disk file storage of databases.A linked list allows to insert and delete items
quickly and easily without rearranging the entire disk file.
Advantages of linked list
1. It is not necessary to known the number of elements and allocate memory in advance.
Memory can be allocated as and when necessary.
2. Insertions and deletions can be handled efficiently without restructuring the list.
Points to remember
------------------------
1. A linked list is a collection of nodes.The way the two nodes are odered is not dictated by their
physical placementbut rather by the links that connect them.
2. Each nodes in the list contains of two parts.
the first part contains information fields.
the second part consists of a link pointer.
3.the start of the list is in a constant location. It contains the address of the first node in the list
thus keeping track of the beginning of the list.
4. The first node ocntains the address of the next node , which contains the address of the next
node and so on.Thus each node points to the next node.
5. The last node in the list contains a NULL address indiacting that no more nodes are in the list.
Types of linked list
1. Single linked list
Each node contains data and a single pointer link which attaches it to the next node in the list.

Head Node
Basic Operations in a Singly Linked List
The basic operations are
1. List creation
2. Node insertion
3. Node Deletion
4. List traversal

2. double linked list


Each node conatins data and two pointer links , one pointing to the next node and the other
pointing to the previous node in the list.

Circular Linked List


Each node contains data and either one or two pointers links but the last node in the list will be
pointing to the beginning of the list.

Stack
A stack is derived from linear lists which in tern as ordered collection of elements. It has
a special feature that insertion and deletion of elements can be done only at one end called Top
of Stack(TOP). It operates Last in First out (LIFO) fashion.
The stack has two basic operations such as PUSH and POP. It can be implemented by
using arrays or pointers.

Starting Address

5 5020 25 6080 35 NULL

5000 5020 6080


PUSH: Inserting an element into the stack.
POP : Deleting an element fro the stack.
Queues:
Queues are also non-primitive data structures just like stack but has First-in-First
Out(FIFO) operation. In a queue, new elements are added to the queue from one end called
REAR end, and deleted from other end called FRONT.

E1 E2 E3 E4 E5 E6

Front Rear
Trees:
A tree is a non-linear data structure in which the data items are arranged or stored
in a sorted sequence of finite sets of data items. Trees are used to represent the hierarchical
relationships between various data elements.
Properties:
1. Tree has a top of the hierarchy called root node.
2. The subsets of a tree are itself forms a tree called sub tree.
3. The tree grows towards bottom by increasing the levels of hierarchy.
4. The nodes at the bottom level are called leafs of the tree.
C-Preprocessor
The C program is often known as ‘Source Code’. The Preprocessor works on the source
code and creates ‘Expanded Source Code’. If the source code is stored in a file PR1.c, then the
expanded source code gets stored in a file PR1.I.
Some of the Preprocessor directives are:
a) Macro expansion
b) File Inclusion
c) Conditional compilation
d) Miscellaneous directives
Macro Expansion
#define upper 25
This statement is called ‘macro definition’ or more commonly, just a ‘macro’.
During Processing, the preprocessor replaces every occurrence of upper in the program with
25. Here is another example of macro definition.
#include<stdio.h>
#include<conio.h>
#define PI 3.1415
main()
{
float r=6.25;
float area;
area=PI*r*r;
printf(“\n Area of circle = %f”,area);
getch();
}
A # define directive is many a times used to define operators.
#include<stdio.h>
#include<conio.h>
#define And &&
#define Or ||
main()
{
int f=1,x=4,y=90;
clrscr();
if((f<5) And (x<=20 Or y<=45))
printf("\n Your PC will always work fine....");
else
printf("\n In front of the maintenance man");
getch();
}
3. Conditional compilation:
If we want, have the compiler skip over part of a source code by inserting the
preprocessing commands #ifdef and #endif, which have the general form:
#ifdef macroname
statement 1;
statement 2;
statement 3;
#endif

ex:
main()
{
#ifdef INTEL
code suitable for a Intel PC
#else
code suitable for a Motorola PC
#endif
code common to both the computers
}

#if defined(NEARPOINTERS)
space = farcoreleft();
#elif defined(FARPOINTERS)
space = coreleft();
#else
#error Unsupported memory model
#endif

Example 2:
#ifdef DEBUG
printf("Total space %d\n", space);
#endif

Example 3:
#ifndef Quiet
PrintDiagnostics();
#endif
Miscellaneous Directives:
There are two more preprocessor directives available, though they are not very commonly used.
They are
a)#undef
b)# pragma

#undef Directive:
On some occasions it may be desirable to cause a defined name to become ‘undefined’.
This can be accomplished by means of #undef Directive. In order to undefined a macro that has
been earlier # defined, the directive

#undef macro template


ex:
# define PENTIUM
printf(“This is my first preprocessor”);
#undef PENTIUM

#pragma directive:
This directive is another special purpose directive that we can use to turn on or off
certain features. Pragma vary from one compiler to another.
a)#pragma startup and # pragma exit:
These directives allow us to specify functions that are called upon program
startup(before main()) or program exit(before the program terminates)
Ex:
Void fun1();
Void fun2();
#pragma startup fun1
#pragma exit fun2
main()
{
prinf(“\n inside main”);
}
void fun1()
{
print(“\n Inside fun1”);
}
void fun2()
{
printf(“\n Inside fun2”);
}
b)#pragma warn:
On compilation the compiler reports errors and warnings in the program, if any. Errors
provide the programmer with no options, apart from correcting them. Warnings on the other
hand offer the programmer a hint or suggestion that something may be wrong with a particular
piece of code. Two common situations when warnings are displayed are as under.
If we have written code that the compiler’s designers consider bad c programming practice .
For example, if a function does not return a value then it should be declared as void.
If we have written code that might cause run-time errors, such as assigning a value to an
uninitialised pointer.

You might also like