Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
35 views

C Programming

c programming

Uploaded by

Shaheena Begum
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

C Programming

c programming

Uploaded by

Shaheena Begum
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 212

C- Programming

 Computer: It is an electronic device, which accepts the


input from user, Process the data, gives a output User.

 Common Operating Machine Purposely Used for


Technological and Educational Research.
 Computer = Arithmetic ,Logical Unit + Control Unit.
 Language
 Programming Language
Types of Language:
1. Machine /Low level Language

2. Middle level Language/ Assembly Language

3. High level Language/User Oriented

Language

Example : C, CPP, JAVA, PYTHON


C programming language
Developed By - Dennis Ritchie
Year - 1972
Bell Telephone Laboratories
Features:
1. Modularity- Ability to breakdown a large module into
manageable sub modules .

2. Portability- To install the software in different platform

3. Extendibility- Ability to extend the existing software by adding


new features

4. Speed-
Uses of C :
 UNIX Operating System was Developed by Using “C” Language
 Developing database Systems
 Graphics Packages
 Spread Sheets
 Word Processors
 Office automation
 Scientific/Engineering Applications
 CAD/CAM Applications
Programming Methodologies:
1. Analysis the problem
2. Identify the variable needed
3.Design the solution
4.Writing the Code or program
5.Testing the program(checking the errors)
6.Correcting the errors
7.Execute or run

Algorithm, Flowchart, Programming code


Algorithm

A set of rules to be followed to solve a problem.


(Or)
Step by step procedure for solving the problem.

Example:
Step1: Start
Step2: Input / Read the value a, b , c
Step3: c = a+b
Step4:Print / Display c
Step5: Stop
FlowChart :
Flowchart is a graphical representation of an algorithm.

Terminal Start
Start
and Stop

Read a and Input /Output


b

Sum= Process
a+b

Display sum
Display Sum

Stop
Character Set :
Combination of Alphabets, Digits and Special characters
used to makes a information.
Alphabets : Uppercase Letters – A,B,C….. Z
Lowercase Letters - a,b,c……
z
Digits: 0,1,2, 3, 4, 5, 6 ,7, 8, 9.
Special characters: + Plus Sign - Minus Sign , Comma

* Asterisk / Slash
= Equal to
@ At Symbol < Less Than
: Colon
; Semicolon
C tokens

 The smallest element /unit in the C language


is the token. It may be a single character or a
sequence of characters to form a single item .

 Keywords
 Identifiers
 Variable
 Constants
 Operators
 Special symbols
 Strings
Keywords

 Keywords are also called as reserved words.


 Keywords have predefined uses and cannot be used
for any other purpose in a C program.
 There are 32 keywords defined in C.
 They are always written in lower case.
 int, float, double, char…and so on.
htkeso
ytTw
lh
o
iC
fn
e
latb
o
igdlrs

auto doubleint struct

break else long switch

char externreturn union

const floatshort unsigned

continuefor signed void


Identifiers
The name given by the user/programmer to the variables, types,
functions, and labels in program.

Rules for forming identifiers:

•C Keywords//reserved words cannot be used as identifiers.


•The first character should be an alphabet or underscore.
•Subsequent characters may be any combination of letters, digits
and underscores.
•Special characters are not allowed
•Can contain up to 31 characters
•Blank spaces are not permitted
Examplesofvalididentifiers:

sumOfRoots1and2
_XYZ
maxThrowsPerTurn
TURNS_PER_GAME
R2D2

Examplesofinvalididentifiers:
2hotToHandel//doesnotstartwtihaeltter
NetPay//contan
i saspace
ALPHA;BETA//contan i sann i vad
ilcharacter;
Variable

a value or a name given to the memory location.


Each variable has its own name called variable name. name starts from
letter or underscore
Rules:
The first character in the Variable name must be an alphabet ,
followed by a number of
digits or underscores
The variable name should not be a keyword
It should not be of length more than 31 characters
Constant
A constant is a variable whose value cannot be changed
throughout the program

Integral ( ex:10 -356)


Numeric Constant
Real (ex:4600.5 -0.963)

Types

Single Character ( ex:‘A’ ‘*’)


Character Constant

String (ex:“A”, “CSC”)


Data Types

Primary Datatype Secondary Datatype

Character char Structure struct


Integer int Union union
Float float Pointer *
Double double Enum enum
Escape Sequence
Escape sequences are specified as the first argument in
Output Statement. They are always preceded with a
backslash
C Program Structure

#include<stdio.h> Preprocessor Directives (Incl. header File)


int a; Global Variable Declarations;
void main() or int main() main function
{
int x,y; Local Variable Declarations
Printf(“given x value is %d”&x);
Scanf(%d,&x); read the input
/*result displayed*/ Comment Line
Return 0;
}Note :
Every “C” Statements should end with Semicolon(;)
Preprocessor directives are the instructions given to the
compiler.
Syntax : #include<headerfilename.h>

Examples: #include<stdio.h>
#include<conio.h>
Stdio -> Standard Input/Output
Conio -> Console Input/Output
Void -> Keyword. It Means Returns Nothing.
main() -> It is a function name which can be used to
indicate the beginning of the program
execution
Irrespective of the number of functions in a
program, the operating system always passes
control to main () when a C program is executed.

The function name is always followed by


parentheses – ()
Delimiters: { }

The function definition is followed by


an open open curly brace - {
This curly brace signals the beginning
of the function.
Comment Line /* */

Compiler ignores them.

In C comment begins with /* and are


terminated with */ . in case the comment
contaims multiple lines.
Processor Directives

 Preprocessor directives are the instructions given to the


compiler.

 They are not translated into machine language, but are


operated upon directly by the compiler before the
compiling process begins.

 Preprocessor directives begin with a # (hash)

 Preprocessor directives are often placed in the beginning


of a program before the main() is declared.
Header File
A lot of library functions are subdivided into number of groups.
This groups are called Header files

Syntax :
#include<headerfilename.h>
Examples:
#include<stdio.h>
#include<conio.h>
Stdio -> Standard Input/Output
Conio -> Console Input/Output
Void -> Keyword. It Means Returns Nothing.
main() -> It is a function name which can be used to
indicate the beginning of the program
execution
CONSOLE INPUT OUTPUT OPERATIONS

All console I/O functions produce only text based outputs.

OUTPUT INPUT

PRINTF SCANF

printf(“control
string”,variable1,variable2…..);
scanf(“control string”, &variable1, &variable2…..);
Operators

 Arithmetic Operator: +, -, *,/, %


 Relational Operator : <, >, <=, >=, ==, !=
 Logical Operator : &&,||,!
 Assignment Operator: = ,+=,*=,
 Increment and Decrement Operator :++, --
 Conditional Operator : Expression1 ? Expression 2:expression
3
 Bitwise Operator :Used in applications which require manipulation of
individual bits within a word of memory ~, << , >>, &,|,^
Arithmetic Operator:
Operator Meaning
Example
+ Addition
x=10,y=5 x+y -> 15

- Subtraction
X-y -> 5

* Multiplication
X*y -> 50

/ Division
x/y -> 2

% Modulo Division
Relational Operators
Relational operators are used to test the relationship
between two variables or constant
Operator Meaning Example
Result value

< Less Than x=10,y=5


X<y False 0

> Greater Than X>y


True 1

<= Less than or Equal to X<=y


False 0

>= Greater than or equal to X>=y


True 1

!= Not Equal to X!=y


Logical Operators
Logical operators are used to combine two or more relational expressions.
This operator is used to test more than one condition at a time.

Operator Meaning Example Result

&& Logical And When x=9, z=9 True


(x>=5) &&
(z==‘9’)

|| Logical Or (X>=6) || (z==‘a’) True

! Logical Not !(x>8) False


Increment / Decrement Operators (++,--)

Operator Meaning Syntax Example Result

++ Unary Plus Variablename++; (or) X=10; X=11


++ variable name; X++;

-- Unary Minus Variablename--; (or) X=10; X=9


-- variable name; X--;
The Assignment Operator

In C, the assignment operator(=) can be used for


assigning a value to a variable
Sy nt ax :

v ar i abl e_na me = ex pressi o n ;

LeftHand side variable RightHand Side value

Assignment
operator
Shorthand of Assignment Operator
Syntax:
Variablename <arithmetic Operator>=Expression;
Simple Assignment Operators Equivalent Shorthand Assignment
Operators

x=x+1 x += 1

y=y-1 y-=1

z=z*(x+y) z *= (x+y)

Y=y/(x+y) Y /= (x+y)

X=x%z X %= z
Conditional Operators (?:)
Simple conditional operations can be carried out with the
conditional operator(?:)

Syntax:
Expression1 ? Expression 2:expression 3
Condition True Part False Part

#include<stdio.h>
void main() OUTPUT
{ The Result
int a=10,b=5,c; is 10
C=(a>b)?a:b;
printf(“The Result is %d",c);
}
BitWise Operators
Used in applications which require
manipulation of individual bits within a
word of memory
Operators Meaning

~ One’s Complement

<< Left Shift

>> Right Shift

& Bitwise AND

| Bitwise OR

^ Bitwise X-OR
Special Operators
Operators Meaning Example

, Comma Operator Z=(x=5,y=6,x+y)

* Pointer indirection Operator

& Address Operator scanf(“%d”,&no);

-> Arrow Operator in Structure

. Dot Operator in Structure

# String Sizing Operator #include<stdio.h


(prepocessor) >
## Token passing Director
/* Bitwise Operator Examples */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,ans,and;
clrscr();
printf("\n Enter A Number");
scanf("%d",&a);
b=1;
ans=a&b;
printf("\n The Result of AND Operation with 1");
if(ans==0)
printf("\n Rightmost bit is OFF");
else
printf("\n Rightmost bit is ON");
and=a/b;
printf("\n The Result of OR Operation with 1");
printf("\n Rightmost bit is ON and the result is %d",and);
getch();
}
String Based I/O Operations

gets() & Puts() are used to perform Input output


operations on a string
syntax :
gets(variablename);
puts(variablename);
Unformatted I/O Statement

Characters can be read and written in C using the


following functions.

FUCTION OPERATION
getchar() Reads a character from the Keyboard, waits for carriage return

getche() Reads a character with echo; does not wait for carriage return not
defined by ANSI, but a common extension.

getch() Reads a character without echo, does not wait for carriage
return, not defined by ANSI, but a common extension.

putchar() Writes a character to the screen


get() Reads a String from the keyboard
put() Writes a string to the screen
Type Conversion
This is used to convert one data type to another data type. The
automatic type conversions for evaluating an expression are given
below -

For example,
Reading decimal ,octal and hexadecimal numbers

#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("\n Enter No in decimal");
scanf("%d",&a);
printf("\n u Entered %d\n",a);

printf("\n Enter No in octal");


scanf("%o",&a);
printf("\n u Entered %o or %d in decimal\n",a,a);

printf("\n Enter No in Hexadecimal");


scanf("%x",&a);
printf("\n u Entered %x or %d\n",a,a);
getch();
}
The sizeof operator

sizeof is a unary compile-time operator

The use of the sizeof operator shall be clear


from the following example -
Control Flow Structure :
The term flow of control refers to the order in which a
program’s statement are executed. Every programming language
supports three control flow structures namely

 Sequence
 Selection
 Iteration
Sequential Control Structure :
It is also called Linear programming. In this method, the
program will have statements that are placed sequentially and
there is no decision involved in the process.

/*Illustration to find the circumference and area of a circle :*/


#include<stdio.h>
#include<conio.h>
main()
{
float radius,circum, area;
float pi=3.1416;
clrscr();
printf(“\nEnter value for radius :”);
scanf(“%f”,&radius);
circum=2*pi*radius;
area=pi*radius*radius;
printf(“\nThe circumference of the circle is %f”,circum);
printf(“\nThe area of the circle is %f”,area);
getch();
Selective Control Structure :
The if statement :

The if statement is used to specify conditional execution of


program statement. When an if statement is encountered,
condition is evaluated and if its value is true, the statement is
executed. The general format of the statement is

Syntax :

if ( condition )
{
program statements;
}
/* Illustration to find the biggest of two number */
#include<stdio.h>
#include<conio.h>
main()
{
int value1, value2, big;
clrscr();
printf(“\n Enter the number values : ”);
scanf(“%d%d”,&value1,&value2);
big=value1;
if(value1<value2)
big=value2;
printf(“\n The bigger number is %d”, big);
getch();
}
if-else statement :
The if-else statement directs the computer to select a
sequence of one or more instructions based on the result of
comparison. When two groups of statements are given and it is
desired that one them be executed if some condition is true and
the other group be executed if that condition is not true.

Syntax :

if (expression)
{
program statements;
}
else
{
program statements;
}
/* Illustration to display whether the number is even or odd */

#include<stdio.h>
#include<conio.h>
main()
{
int number;
clrscr();
printf(“\n Enter the number : ”);
scanf(“%d”,&number);
if(number % 2 = = 0)
printf(“\n The number is Even”);
else
printf(“\n The number is Odd”);
getch();
}
if-else-if statement :
This construction is called if-else-chain. Each condition is evaluated in
order and if any condition is true, the corresponding statement is executed and
the remainder of the chain is terminated.

Syntax :

if (condition1)
Statment1;
else if(conditon2)
Statement2;
else
Statement3;
/* Illustration to find the status of an individual : */
#include<stdio.h>
#include<conio.h>
main()
{
int age;
clrscr();
printf(“\n Enter the age :”);
scanf(“%d”,&age);
if(age>=1 && age<18)
printf(“\n The individual is a minor”);
else if(age>=18 && age<40)
printf(“\n The individual is a major”);
else if(age>=40 && age<120)
printf(“\n The individual is a adult”);
else
printf(“\nInvalid age entered”);
getch();
}
Switch case statements
It is an alternative to the if-else chain. It compares to each of switch
cases and when the match is found, execution begins with the statement
immediately following the match.
Syntax :
switch(expression)
{
case value_1:
statment1;
break;
case value_2:
statement2;
break;


default:
statement n;
break;
}
/* Illustration to switch statement */

#include<stdio.h>
#include<conio.h>
main()
{
char choice;
clrscr();
printf(“\n Enter a character :”);
scanf(“%c”,&choice);
switch(choice)
{
case ‘a’:
printf(“\n The character is ovel”);
break;
case ‘e’:
printf(“\n The character is ovel”);
break;
case ‘i’:
printf(“\n The character is ovel”);
break;
case ‘o’:
printf(“\n The character is ovel”);
break;
case ‘u’:
printf(“\n The character is ovel”);
break;
default :
printf(“\n Invalid character”);
break;
}
getch();
}
Iterative Control Structure :
The ‘C’ language has the ability to repeat the same calculation on
sequence of instruction again & again.

The While Construct :


It is used repeat the same instruction until the given condition is true.
Once the condition become false it stops the repetition.

Syntax :
while(expression)
{
statement;
}
/* Illustration to print the numbers from 1 to 10 */

#include<stdio.h>
#include<conio.h>
main()
{
int n=1;
clrscr();
while(n<=10)
{
printf(“\n%d”,n);
n++;
}
getch();
}
The Do While Construct :
In this construct the statements in the loop are executed &
the testing is done at the end of the loop.

Syntax :

Do
{
Statements;
} while(expression);
/* Illustration to print the numbers from 10 to 1 */

#include<stdio.h>
#include<conio.h>
main()
{
int n=10;
clrscr();
do
{
printf(“\n%d”,n);
n--;
}while(n>=1);
getch();
}
for Loop Construct :
It is also a looping statement which include all the expressions in the
same line i.e., initialization, condition, increment/decrement.

Syntax :

for(initialization; condition; incr/decr)


{
statements;
}
/* Illustration to print the table of a number */

#include<stdio.h>
#include<conio.h>
main()
{
int n,i;
clrscr();
printf(“\n Enter a number :”);
scanf(“%d”,&n);
for(i=1;i<=10;i++)
{
printf(“\n %d”,n*i);
}
getch();
}
Break Statement :
The break statement transfers the control to the end of the construct.
It is used to terminate the inner most loop.
/* Illustration to break the loop */
#include<stdio.h>
#include<conio.h>
main()
{
int k;
clrscr();
for(k=1;k<=10;k++)
{
printf(“\n %d”,k);
if(k==5)
{
printf(“\n Break….”);
break;
}
}
getch();
}
Continue Statement
It works almost opposite way of the ‘break’ statement. It forces the
next iteration of the loop to take place.
/* Illustration to continue the loop */
#include<stdio.h>
#include<conio.h>
main()
{
int k;
clrscr();
for(k=1;k<=10;k++)
{
printf(“\n %d”,k);
if(k==5)
{
printf(“\n Continue….”);
continue;
}
}
getch();
}
The goto Statement

The C goto statement has label as its object. When goto


statement executes, control transfers to the C statement that
follows the label where it is defined.
/* Illustration to goto the loop */
#include<stdio.h>
#include<conio.h>
main()
{
int k;
clrscr();
for(k=1;k<=10;k++)
{
printf(“\n %d”,k);
if(k==5)
{
goto kpl;
}
}
kpl:
printf(“\n Your Control is Here”);
getch();
}
ARRAY
Array is defined as a set of homogeneous data items. (or)
An Array is a group of elements that share a common name that
are differentiated from one another by their positions within the
array

Datatype arrayname[subscript];
int a [];

1) Array name should be a valid “C” variable


2) Array name should be unique
3) The elements in the array should be of same type
4) Subscript (array size) cannot be negative
5) Subscript must always be an integer
TYPES OF ARRAY
Strings Arrays
A string can be defined as a character type array, which is
terminated by a null character.

Output -
Single or One Dimensional
Arrays
Arrays whose elements are specified by one subscript
are called One dimensional array or linear array.
Syntax :
datatype arrayname[size];
For Example :

Note :
By default array index should starts with zero (0)
Write a program for entering data Array Initialization
into an array & Reading data from
an array
#include<stdio.h>
#include<stdio.h>
void main() #include<conio.h>
{ void main()
int arr[10],I,n; {
printf("\n ENter N Elements"); int a[5]={10,20,30,40,50};
scanf("%d",&n); int i;
for(i=0;i<n;i++) clrscr();
{ for(i=0;i<5;i++)
printf("enter arr[%d]=",i);
{
scanf("%d",&arr[i]);
} printf("%d\n",a[i]);
for(i=0;i<n;i++) }
{ getch();
printf("%d\n",arr[i]); }
}
}
10
Enter N Elements : 2 20
3
5 30
Enter arr[0] : 2
3 40
Enter arr[1] : 5
50
Enter arr[2] : 3
Write a “C” program to sort the given number is in
ascending order using one dimensional array
#include<stdio.h>
void main()
{
int i,j,n, a[10],temp;
printf("\n size of vector=");
scanf("%d",&n);
printf("vector elements:");
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("\n\nElements in asending order is=\n");
for(i=0;i<n;i++)
printf("%8.2d",a[i]);
printf("\n\nElements in descending order is=\n");
for(i=n-1;i>=0;i--)
printf("%8.2d",a[i]);
getch();
}
Two Dimensional Arrays
A Arrays whose elements are specified by two subscript
such as row and column are called two dimensional array or
linear array.
Row  means horizontally
Column  means vertically

A two - dimensional array looks like a school time-table


consisting of rows and columns.
A two – dimensional array is declared as -
Two Dimensional Array Initialization

The result of the above assignment will be as follows :


Write a “C” program to perform Write a “C” program to perform the
the addition of two matrices subtraction of two matrices
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int a[3][3],b[3][3],c[3][3],i,j; int a[3][3],b[3][3],c[3][3],i,j;
printf("Input A - Matrix\n"); printf("Input A - Matrix\n");
for(i=0;i<3;i++) for(i=0;i<3;i++)
for(j=0;j<3;j++) for(j=0;j<3;j++)
scanf("%d",&a[i][j]); scanf("%d",&a[i][j]);
printf("Input B - Matrix\n"); printf("Input B - Matrix\n");
for(i=0;i<3;i++) for(i=0;i<3;i++)
for(j=0;j<3;j++) for(j=0;j<3;j++)
scanf("%d",&b[i][j]); scanf("%d",&b[i][j]);
for(i=0;i<3;i++) for(i=0;i<3;i++)
for(j=0;j<3;j++) for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j]; c[i][j]=a[i][j]-b[i][j];
printf("Sum of A and B Matrix=\ printf("Sum of A and B Matrix=\n");
n"); for(i=0;i<3;++i)
for(i=0;i<3;++i) {
{ for(j=0;j<3;++j)
for(j=0;j<3;++j) printf("%5d",c[i][j]);
printf("%5d",c[i][j]); printf("\n");
printf("\n"); }
} }
}
Write a “C” program to sort the given Write a “C” program to perform matrix
names in Alphabetical order using One multiplication using two dimensional array
dimensional array #include<stdio.h>
#include<stdio.h> void main()
#include<string.h> {
void main() int a[10][10],b[10][10],c[10]
{ [10],i,j,m,n,p,q,k;
int i,j,n; printf("Input row and column of A matrix \
char a[10][10],temp[10]; n");
printf("\n Enter the N Values"); scanf("%d %d",&n,&m);
scanf("%d",&n); printf(" Input row and column of B matrix \
printf("Enter the Names one by one :\ n");
n"); scanf("%d %d",&p,&q);
for(i=0;i<n;i++) if(n==q){
{ printf(" Matrices can be Multiplied: \n");
scanf("%s",&a[i]); printf(" Input A-matrix \n");
} for(i=0;i<n;++i)
for(i=0;i<n-1;i++) for(j=0;j<m;++j)
for(j=i+1;j<n;j++) scanf("%d",&a[i][j]);
if((strcmp(a[i],a[j]))>0) printf(" Input B-matrix \n");
{ for(i=0;i<p;++i)
strcpy(temp,a[i]); for(j=0;j<q;++j)
strcpy(a[i],a[j]); scanf("%d",&b[i][j]);
strcpy(a[j],temp); printf("The resultant matrix is\t:\n");
} for(i=0;i<n;++i){
printf("The Names in Alphabetical for(j=0;j<m;++j){
Order is =\n"); c[i][j]=0;
for(i=0;i<n;i++) for(k=0;k<m;++k)
printf("\n%s",a[i]); c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
} printf("%5d",c[i][j]);}
printf("\n");}}
For example:
Suppose two matrixes A and B of size of 2 x 2 and 2 x 3 respectively:
Write a “C” program to find the
largest and smallest numbers given
in the array
#include<stdio.h>
void main()
{
int i,n;
float a[20],large,small;
printf("\nEnter the N values=");
scanf("%d",&n);
printf("Enter the values one by
one :\n");
for(i=0;i<n;i++){
scanf("%f",&a[i]);}
large=a[0];
for(i=1;i<n;i++){
if(a[i]>large)
large=a[i];}
small=a[0];
for(i=1;i<n;i++){
if(a[i]<small)
small=a[i];}
printf("Largest element is = %6.2f\
n",large);
printf("Smallest element = %6.2f\
n",small);
}
FUNCTION
WHAT IS A FUNCTION
A function in C language is a block of code that performs a specific
task. It has a name and it is reusable i.e. it can be executed from as
many different parts in a C Program as required. It also optionally
returns a value to the calling program

A program separate from the main program that


executes a series of operations that occurs multiple
times during the machining cycle. Subprograms
shorten and simplify manual programming.
Function advantages

 Program development made easy : Work can be divided among project


members thus implementation can be completed in parallel.

 Program testing becomes easy : Easy to locate and isolate a faulty


function for further investigation

 Code sharing becomes possible : A function may be used later by many


other programs this means that a c programmer can use function written
by others, instead of starting over from scratch.

 Code re-usability increases : A function can be used to keep away from


rewriting the same block of codes which we are going use two or more
locations in a program. This is especially useful if the code involved is
long or complicated.
FUNCTION ADVANTAGES

Increases program readability : It makes possible top down


modular programming. In this style of programming, the high
level logic of the overall problem is solved first while the details
of each lower level functions is addressed later.
The length of the source program can be reduced by using
functions at appropriate places.

Function facilitates procedural abstraction : Once a function


is written, it serves as a black box. All that a programmer would
have to know to invoke a function would be to know its name,
and the parameters that it expects

Functions facilitate the factoring of code : Every C program


consists of one main( ) function typically invoking other functions,
each having a well-defined functionality.
scanf()
printf() A series of
gets() Instructions that are
puts() to be executed more
than once
USER DEFINED FUNCTION :
SYNTAX :
retu_datatype func_name(arguments)
{
Body of the function
statements;
return;
}

call the function from main() :


syntax :
func_name(arguments );
#include<stdio.h>
void hai() //definition
{
printf(" Welcome to functions\n");
printf("Good Morning\n");
}
void main()
{
clrscr();
printf("Main, Welcome to functions\n");
hai(); //calling
printf("Bye");
getch();
}
expression
The return statement is used to return from a function.

It causes execution to return to the point at which the


call to the function was made.
The return statement can have a value with it, which it
returns to the program.
CATEGORY OF FUN CTION
(Based on Return values and passing
Arguments)

 NO ARGUMENT NO RETURN VALUES


 ARGUMENT BUT NO RETURN VALUES
 NO ARGUMENT WITH RETURN VALUES
 WITH ARGUMENT WITH RETURN VALUES
/* To perform Addition of two numbers */
/* NO ARGUMENT NO RETURN VALUES */

#include<stdio.h>
void add(); void add()
void main() {
{ int a,b,c;
add(); printf("Enter two numbers\n");
printf("Prg ends"); scanf("%d%d",&a,&b);
add(); c=a+b;
} printf("The sum is %d\n",c);
}
/* To perform Addition of two numbers */
/* WITH ARGUMENT BUT NO RETURN VALUES*/
#include<stdio.h>
void add(int,int);
void main()
{
int x,y;
printf("Enter two number");
scanf("\t\t%d %d",&x,&y);
add(x,y); /* Actual Arguments */
}
void add(int a,int b) /* Formal Arguments */
{
int c=a+b;
printf("\t\tThe C Value is %d",c);
}
/* To perform Addition of two numbers
Without Argument and With Return values */
#include<stdio.h>
#include<conio.h>
int add(); //declaration
void main()
{
int c;
c=add(); /* Return Variable - c */
printf("The sum of two numbers is %d",c);
}
int add()
{
int a,b,c;
printf("Enter two Numbers=");
scanf("%d %d",&a,&b);
c=a+b;
return(c);
}
/* To perform Addition of two numbers
With Argument and With Return values */
#include<stdio.h>
int add(int,int); //Function prototype declaration
void main()
{
int c;
printf("Enter two Numbers=");
scanf("%d %d",&a,&b);
c=add(a,b); /* Actual Arguments */
printf("The sum of two numbers is %d",c);
}
int add(int x,int y) /* Formal arguments */
{
int c;
c=x+y;
return(c);
}
PASSING PARAMETERS
Passing Value to a function
Functions communicate with each other by passing
arguments.
It can be passed in Two Ways
1. Call By Value
2. Call by Reference
Passing
Parameter
s

Call by
Call by
value
reference
CALL BY VALUE

 The values are passed through temporary


variables. Any manipulation to be done only on these
temporary variables.

 The called function does not access the actual


memory location of the original variable and
therefore cannot change its value.
CALL BY REFERENCE

Call by reference means passing the address


of a variable where the actual value is stored.
The called function uses the value stored in
the passed address; any changes to it DO
affect the source variable.
/*CALL BY REFERENCE as well as to swap 2 numbers
using pointers */
#include<stdio.h>
void swap(int *,int *);
void main()
{
int a,b;
printf("\nEnter the numbers to swap");
scanf("%d %d",&a,&b);
printf("The values before swapping :");
printf("\n%d %d",a,b);
swap; (&a,&b)
}
/* CALL BY VALUE EXAMPLE*/
#include<stdio.h>
void add(int,int);
void main()
{
int x,y; Enter two number
printf("Enter two number"); = 60
20
scanf("\t\t%d %d",&x,&y); The C Value is 80
add(x,y);
}
void add(int a,int b)
{
int c=a+b;
printf("\t\tThe C Value is %d",c);
}
Functions are easier to write and understand

 The arguments are separated by commas


 The body of the function may consist of one or many statements

 It cannot be defined within another function


 Function prototype is a function declaration that specifies the
data types of the arguments
 Calling one function from within another is said to be nesting of
Function calls
 main() returns an integer which is generally the operating
system
Pointers
Pointer is the variable which stores the address of the
another variable
Declaration of pointer :
syntax : datatype *pointername;
Example :
int *ptr;
char *pt;
Using a Pointer Variable
2000
int x;
12
x = 12; x

3000
int* ptr;
2000
ptr = &x; ptr

NOTE: Because ptr holds the address of x,


we say that ptr “points to” x

PRADEEP
Assigning data to the pointer variable

syntax :
pointervariablename=&variablename;

For Example : Variable Value


int *a,b=10; Address
a=&b; Quantity
20
500
int *p,quantity=20;
500
p=&quantity;
P 5048
For Example :
#include<stdio.h>
void main()
{
int val=100;
printf("%u\n",&val);
printf("%d\n",val);
printf("%d\n",*(&val));
}
Why are Pointers Used ?
 To pass arrays & strings more conveniently from one function

to another
 To manipulate arrays more easily by moving pointers to
them, Instead of moving the arrays themselves
 To allocate memory and access it (Dynamic Memory
Allocation)
 To create complex data structures such as Linked List, Where
one data structure must contain references to other data
structures
Advantages:
 Pointers reduce the length and complexity of a program.
 They increase the execution speed.
 The use of a pointer array to character strings results in saving of

data storage space in memory.


 The function pointer can be used to call a function
 Pointer arrays give a convenient method for storing strings
Many of the ‘C’ Built-in functions that work with strings use Pointers
It provides a way of accessing a variable without referring to the

variable directly
#include<stdio.h>
#include<conio.h>
void main()
{
int n=10;
int *ptr;
ptr=&n;
printf("Value of n is %d",n);
printf("\nAddress of n is %x",&n);
printf("\nAddres of pointer is %x",ptr);
printf("\nvalue stored in pointer is %d",*ptr);
getch();
}
Example 2
#include<stdio.h>
#include<stdlib.h>
#define size 10
void main()
{
char name[size];
char *i;
printf("\n Enter your name ");
gets(name);
i=name;
printf("\n Now printing your name
is :");
while(*i != '\0')
{
printf("%c",*i);
i++;
}
}
Explain how the variable can be accessed by
pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
float a,*b;
clrscr();
printf("\n Enter the radius of the circle");
scanf("%d",&r);
a=3.14*r*r;
b=&a;
printf("\n The value of a=%f",a);
printf("\n The value of a=%u",&a);
printf("\n The value of b=%u",b);
printf("\n The value of a=%f",*b);
getch();
}
Pointer Arithmetic
Addition and subtraction are the only operations that can be
performed on pointers.

Take a look at the following example :

Let var be an integer type variable


having the value 500 and stored at the
address 1000.

Then ptr_var has the value 1000 stored in it. Since integers are 4
bytes long, after the expression “ptr_var++;” ptr_var will have the
value as 1004 and not 1001.
Pointer Increment process example
#include<stdio.h>
#include<conio.h>
void main()
{
int *ptr; //static memory allocation
clrscr();
ptr=(int *) malloc(sizeof(int));
*ptr=100;
printf("\n%u\n",ptr); //address of ptr
printf("\n%d\n",*ptr);
ptr++; // increment 2 bytes
*ptr=101;
printf("\n%d\n",*ptr);
free(ptr);
getch();
}

/* Note : int *ptr=100 means 100 is a


address
*ptr=100 or 101 means 100 is a value */
HINTS
Each time a pointer is incremented, it points to the memory
location of the next element of its base type.
Each time it is decremented it points to the location of the
previous element.
All other pointers will increase or decrease depending on the
length of the data type they are pointing to.

Two pointers can be compared in a relational expression provided


both the pointers are pointing to variables of the same type.
Increment & Decrement Operations Using Pointer
#include<stdio.h>
void main()
{
int i=100,*iptr;
float f=122.354,*fptr;
char c='d',*cptr;
iptr=&i;
fptr=&f;
cptr=&c;
printf("The values of the variables");
printf("\n%d",*iptr);
printf("\n%f",*fptr);
printf("\n%c",*cptr);
printf("\nStarting Address");
printf("\n%u",iptr);
printf("\n%u",fptr);
printf("\n%u",cptr);
iptr++;
fptr++;
cptr++;
printf("\nPointer Incrementing");
printf("\n%u",iptr);
printf("\n%u",fptr);
printf("\n%u",cptr);
iptr--;
fptr--;
cptr--;
printf("\nPointer Decrementing");
printf("\n%u",iptr);
printf("\n%u",fptr);
printf("\n%u",cptr);
getch();
}
The Pointer Special
Operators

&  Returns the memory


address of the operand

*  It is the complement of
&. It returns the value
contained in the memory
location pointed to by the
pointer variable’s value
Write a C program to find the length of the string Using Pointer
#include<stdio.h>
#include<string.h>
void main()
{
char *text[20],*pt;
int len;
pt=*text;
printf("Enter the string");
scanf("%s",*text);
while(*pt!='\0')
{
putchar(*pt++);
}
len=pt -*text;
printf("\nLength of the string is %d",len);
}
/*Add Two Numbers using pointers*/

#include<stdio.h>
void main()
{
int a,b,*c=&a,*d=&b;
printf(“Enter two numbers to be summed");
scanf("%d %d",&a,&b);
printf(“The sum of two numbers=%d",c + d);
getch();
}
Pointers With
Arrays
The address of an array element can be expressed in two
ways :
By writing the actual array element preceded by the
ambersand (&) sign.
By writing an expression in which the subscript is added to the
array name.
Array Using Pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int b[100],*iptr;
iptr=&b;
clrscr();
printf("The initial value of iptr is %u\n",iptr);
iptr++;
printf("Incremented value of iptr is %u\n",iptr);
getch();
}
POINTERS IN ARRAYS
Example 2
#include<stdio.h>
#include<conio.h>
void main()
{ 10
int arr[]={10,20,30,40};
int *ptr,i; 20
clrscr();
30
ptr=arr; // same as &arr[0];
printf("\n The Result of the array is 40
");
for(i=0;i<4;i++)
{
printf("%d\n",*ptr);
ptr++;
}
getch();
}
Pointers as Function Arguments
When pointers are passed to a function :

The address of the data item is passed and thus the function can
freely access the contents of that address from within the function

In this way, function arguments permit data-items to be altered in


the calling routine and the function.

When the arguments are pointers or arrays, a call by reference is


made to the function as opposed to a call by value for the variable
arguments.
FUNCTION POINTER EXAMPLE /* Invoke the func. Addition */
#include<stdio.h> val=(function) (20,100);
#include<conio.h>
printf("\n Addition result =
int (* function) (int,int); /*function %d",val);
pointer prototype */
/* assign the function subtraction
int addition(int a,int b) into the function pointer */
{ function=subtraction;
return a+b;
} /* invoke the func. subtraction &
syntax for function pointer call */
int subtraction(int a,int b)
{ val=(function) (200,100);
return a-b; printf("\nSubtraction result =
} %d",val);
void main() getch();
{ }
int val;
/* assign the func. addition into the
function pointer */
function=addition;
Pointers To Structures

Pointers to structures are allowed in C, but there are some


special aspects to structure pointers that a user of pointers to
structures must be aware of.
The following statement declares ptr as a pointer to data of
that type -

Struct book *ptr;l


How the structure can be ptr=&st;
accessed by a pointer printf("\n display the details using
variable structure variables");
#include<stdio.h>
#include<stdlib.h> printf( "%d %s %f", st.roll_no,
struct student st.name, st.marks);
{
int roll_no; printf("\n display the details using
char name[20]; pointer variables");
float marks; printf( "%d %s %f",ptr->roll_no,
}st; ptr->name, ptr->marks);
void main() }
{
struct student *ptr; void print_rec(int r,char n[ ],float m)
printf("\n \t Enter the record"); {
printf("\n Enter the Roll Number"); printf("\n You have Entered Following
scanf("%d",&st.roll_no); record");
printf("\n %d %s %f",r,n,m);
printf("\n Enter the Name"); }
scanf("%s",st.name);

printf("\n Enter the Marks");


Pointers & Strings
Using strings as pointers can be explained with the help of the
Enter a Sentence : We all live in a yellow submarine

Enter character to search for Y

String starts at address : 65420

First occurrence of the character is at address: 65437

Position of first occurrence (starting from 0) is : 17


String
 It can be defined as a group characters which is terminated by a NULL
 Each character of a string occupies one byte and last character of a
string is always the character ‘\0’
 \0  Null character and it stands for a character with a value
of zero

String Function
strcpy() strlwr()
strcat() strcmp()
strlen() strcmpi() String.h

Strupr() strrev()
Strcpy() function :
It copies the contents of one string into another string.
Syntax : strcpy(string1,string2); string1 is destination
string, string2 is source string.
#include<stdio.h>
#include<string.h>
void main()
{
char str[25],cpy[25];
printf("\n Enter a String");
gets(str);
Strcpy(cpy,str);
printf("\n The source string is %s",str);
printf("\n The copied string is %s",cpy);
}
Enter a String : PRATHAP
The Source string is : PRATHAP
OUTPUT
The Copied string is : PRATHAP
Strcat() function :
it concatenates the source string at the end of the target
string
Syntax : strcat(string1,string2);string1 target string, string2

source string
#include<stdio.h>
#include<string.h>
void main()
{
char str[25],str1[25];
printf("\n Enter a String");
gets(str);
printf("\n Enter another String");
gets(str1);
printf("\n The concatenated string is %s",strcat(str,str1));
} Enter a String : GOOD
OUTPUT Enter another String : MORNING
The Concatenated string is : GOOD
MORNING
Strcmp() function :
It compares two strings to find whether the strings are equal or not.
Syntax : strcmp(string1,string2);

#include<stdio.h>
#include<string.h> Return values
void main()
0  Equal
{
char str[25],str1[25]; 1 
int x; string1>string2
printf("\n Enter a String"); -1 
gets(str); string1<string2
printf("\n Enter another String");
gets(str1);
x=strcmp(str,str1);
If(x==0)
printf(“\n Strings are equal”);
else if(x>0)
printf("\n The string1 %s is greater than string2 %s”,str,str1);
else
printf("\n The string2 %s is greater than string1 %s”,str1,str);
}
Enter a String : JAIKUMAR
OUTPUT Enter another String : SASIKUMAR
The string2 SASIKUMAR is greater than string1
Strcmpi() function :
It compares two strings without regard to case to find whether the strings are
equal or not. ( i  ignorecase)
Syntax : strcmpi(string1,string2);
#include<stdio.h>
#include<string.h>
void main()
{
char str[25],str1[25];
int x;
printf("\n Enter a String");
gets(str);
printf("\n Enter another String");
gets(str1);
X=strcmpi(str,str1);
if(x==0)
printf(“\n The two Strings are equal”);
else if(x>0)
printf("\n The string1 %s is greater than string2 %s”,str,str1);
else
printf("\n The string2 %s is greater than string1 %s”,str1,str);
}
Enter a String : COMPUTER
OUTPUT Enter another String : computer
the Two strings are equal
strrev() function :
used to reverse a string. It takes only one argument.

Syntax : strrev(string);

#include<stdio.h>
#include<string.h>
void main()
{
char str[25];
printf("\n Enter a String");
gets(str);
printf("\n The Reversed string is %s",strrev(str));
}
OUTPUT Enter a String : TAMMU
The reversed string is : UMMAT
strupr() function :
used to convert a string to uppercase. It takes only one
argument.

Syntax : strupr(string);

#include<stdio.h>
#include<string.h>
void main()
{
char str[25];
printf("\n Enter a String");
gets(str);
printf("\n The case changed string is %s",strupr(str));
}

OUTPUT Enter a String : prathap


The case changed string is : PRATHAP
strlwr() function :
used to convert a string to Lowercase. It takes only one
argument.

Syntax : strlwr(string);

#include<stdio.h>
#include<string.h>
void main()
{
char str[25];
printf("\n Enter a String");
gets(str);
printf("\n The case changed string is %s",strlwr(str));
}

OUTPUT Enter a String : TAMMU


The case changed string is : tammu
strlen() function :
used to count the number of characters present in a
string. It takes only one argument.

Syntax : int variablename=strlen(string);

#include<stdio.h>
#include<string.h>
void main()
{
char str[25];
printf("\n Enter a String");
gets(str);
printf("\n The length of the string is %d",strlen(str));
}

OUTPUT Enter a String : LAPTOP


The length of the string is : 7
Session Summary

 Strings can be read through scanf() and gets() functions

 Any copy of characters specified within double quotes is a string constant

 Strings can also be read a character by character using the functions scanf() and getchar()

etc.,

 The strcat() concatenates the second argument with the content of first argument

 strcmp() compares two strings to find whether the strings are equal or not.

 The strrev() reverses the string passed as arguments


Storage Classes

Every ‘C’ variable has a characteristic called its Storage


Class.
All variables have datatype and storage classes

BASED ON
 Keyword
 Where it is
Declared
 Storage Area
 Default Initial
value
 Lifetime of a
variable
1. Local or Auto or Internal variable
2. External or Global variable
3. Static variable
4. Register Variable
LOCAL VARIABLE
LOCAL VARIABLE

Auto variable are always declared within a function and they are
local to the function in which they are declared. Hence they are
also named as local variables

Keyword : auto
Declaration : Inside the function
Storage Area : Stack
Initial Value : Garbage value (At the time of compilation compiler
assigns any value)
Lifetime : Upto that function only
Example : void function1()
{
auto int x; (or) int x;
int m=10;
#include<stdio.h> printf("%d\n",m);
void function1();
void function2(); }

void main() void function2()


{ {
int m=1000;
function2(); int m=100;
printf("%d\n",m); function1();
} printf("%d\n",m);

}
GLOBAL VARIABLE
GLOBAL VARIABLE

A variable which can be access with in a function and


outside the
main function. These variables are also named as
Global variables or External variables

Keyword : extern
Declaration : Outside of the main() function
Storage Area : CPU–memory
Initial Value : zero
Lifetime : Upto the entire program
Example : void function1() {
k=k+10;
int x; (or) printf("%d\n",k); }
main() void function2()
{
main() k=k+1000;
{ { extern int printf("%d\n",k);
}
x; void function3()
} } {
k=k+10;
printf("%d\n",k); }
#include<stdio.h>
int k; //global variable
void function1();
void function2();
void function3();
void main()
{
k=20;
function1();
function2();
function3();
Static Variable
Static Variable

This variable static is constant and the value is continued


in all the
steps.
Keyword : static
Declaration : Inside the function
Storage Area : CPU – memory
Initial Value : Zero
Lifetime : The value of the variable persists between
different function calls.
Example :
static int x;
void stat() //definition
{
/* To print the value of x */ static int x=0;
printf("x=%d\n",x);
#include<stdio.h> x=x+1;
void stat(); }

void main()
{
int i;
for(i=1;i<=5;i++) 0
stat(); //calling 1
} 2
3
4
/* Example 2 */
#include<stdio.h>
#include<conio.h>
void incre(); /* Function
prototype declaration */
void main()
{
clrscr(); OUTPUT
incre();
incre();
incre();
getch(); The character Stored in
} x is A
The character Stored in
void incre() x is B
{
The character Stored in
static char x=65;
x is C
printf("\n The character
stored in x is %c",x++);
}
Register
Variable
Register Variable
These variables are stored in CPU registers and hence they can be
accessed faster than the one which is stored in memory.
Keyword : register
Declaration : Inside the function
Storage Area : CPU - Register
Initial Value : Garbage value(At the time of compilation compiler
assigns any value)
Lifetime : Upto that function only
Example : register int x;
Note :
register double x; register float y;
Registers are usually a 16bit therefore it
cannot hold a float or double data type value which require 32 & 64 bytes
respectively for storing a value. But the compiler would treat as automatic
variables
void swap(int *e,int *f)
{
int *temp;
*temp=*e;
*e=*f;
*f=*temp;
printf("\n The swapped values are %d %d",*e,*f);
}

Enter the numbers to swap = 5 NOTE :


6
The values before swapping : 5 6 &  Address of
The swapped values are : 6 5
*  Content of
#include<stdio.h>
#include<conio.h>
void main()
{
-899
register int x;
(Garbage Value)
clrscr();
printf("\n The value is
%d",x);
getch();
}
Session Summary
A function is a self contained program segment (block of

statements) that performs some specific well defined task.

Three steps in using a function are defining a function, prviding a

prototype and calling the function.

 Return statement is used to return the information from the

function to the calling portion of the program

 Scope of a variable is defined as the region over which the

variable is visible or valid.


Structure
Structure are collection of different datatype
grouped together under a single variable name for
convienient handling. 'struct' is a keyword, struct type is a
name which identifies the structure.
syntax : struct <structure name or tagname>
{
datatype member1;
datatype member2;
};
struct book
{
int pages;
char bookname[10];
char author[20];
float price;
};
J A V A H A U N T E R 467

Book Name Author Name


Pages
Individual structure type variables can be declared as follows:

Syntax :
struct structurename variable1, variable2, ..... variable n;

Example
Struct book b1; /* b1 is a structure variable name */

Member variables can be accessed using the dot or period operator as


follows:

Syntax :
Stru_variablename.membername;

Example
B1.pages=400;
B1.price=450.00;
Write a Program the create the Account Details using Structure?
#include<stdio.h>
struct amount
{
int ac_no;
char name[10];
int balance;
};
void main()
{
struct amount v;
printf("\nEnter the account Details");
scanf("%d%s%d",&v.ac_no,&v.name, &v.balance);
printf("The values are %d%s%d",v.ac_no,
v.name, v.balance);
printf("%d",sizeof(struct amount));
}
Initializing Structures
Like variables and arrays, structure variables can be initialized at the
beginning of the program.
The variable emp1 and emp2 of the type employee can be initialized
when it is declared as

Consider the following program :


Write a program to create student structure
#include<stdio.h>
struct stud
{
int id;
char name[20];
int mark1,mark2,mark3;
int total;
int avg;
}b;
void main()
{
printf("\nEnter the student details");
scanf("%d %s %d %d %d",&b.id,&b.name,
&b.mark1,&b.mark2,&b.mark3);
b.total=b.mark1+b.mark2+b.mark3;
b.avg=b.total/3;
printf("%d %s %d %d %d",b.id,b.name, b.mark1, b.mark2, b.mark3);
}
struct employee emp1 =
{346, "Abraham" };

struct employee emp2 =


{347, "John" };
Arrays of Structure

Array of structures are defined as a group of


data of different data types stored in a consecutive
memory location with a common variable name.

For Example,
struct employee
{
int empno;
char
empname[20];
char
deptname[10];
float salary;
}emp[5];
Passing Structures as Arguments
A structure variable can be passed as an argument to another
function

This is a useful facility and it is used to pass groups of


logically related data items together instead of passing them
one by one.
/*PASSING STRUCTURES TO FUNCTION ARGUMENTS*/
#include<stdio.h>
struct record
{
char *name;
int acct_no;
char acct_type;
float bal;
};
struct record fun(struct record);
void main(){
struct record c;
printf("\n Enter Details");
scanf("%s%d%c%f",c.name,&c.acct_no, &c.acct_type, &c.bal);
c=fun(c); //calling
printf("\n%s %d %c %f",c.name,c.acct_no,c.acct_type,c.bal);
}
struct record fun(struct record r)
{
r.name="Raja";
r.acct_no=1567;
r.acct_type='R';
r.balance=900.00;
return(r);
}
Passing the structure member
as a parameter to the printf("\n Enter the Marks");
function scanf("%f",&st.marks);
#include<stdio.h> print_rec(st.roll_no,st.name,st.ma
#include<stdlib.h> rks);
typedef struct stud printf("\n Do U Want to store the
{ More record ");
int roll_no; ans=getche();
char name[20]; }while(ans=='y');
float marks; }
}student;
student st; void print_rec(int r,char n[],float
void print_rec(int,char [],float); m)
void main() {
{ printf("\n You have Entered
char ans; Following record");
clrscr(); printf("\n %d %s %f",r,n,m);
do }
{
printf("\n \t Enter the record");
printf("\n Enter the Roll
Number");
scanf("%d",&st.roll_no);
Nested Structure
A structure within another structure is called Nesting of structures.The
declaration of the embedded structure must appear before the declaration of
the outer structure.

Example
Struct date
{
int month;
int day;
int year;
};
struct account
{
int acc_no;
char name[40];
char acc_type;
float balance;
struct date dob;
} customer;
/* NESTED STRUCTURES
A structure within another
scanf("%d",&s.sno);
structure */
printf("enter the sname\n");
#include<stdio.h>
scanf("%s",s.sname);
struct dob {
printf("enter the dob\n");
int date;
scanf("%d%d%d %c",&s.sdob.date,
int month;
&s.sdob.month,&s.sdob.year,&s.sex);
int year; };
printf("%d\t %s\t %d %d %d \t %c",
struct stud{
s.sno, s.sname, s.sdob.date,
int sno;
s.sdob.month, s.sdob.year, s.sex);
char sname[10];
getch();
struct dob sdob;
}
char sex; };
void main()
{
struct stud s;
clrscr();
printf("enter the sno\n");
Session Summary

 The keyword “struct” begins the structure definition followed by the


tag(i.e strcture name) within the braces the structure members are
declared

The structure definition create a new data type that can be used to
declare variables.

 A member of structure is always referred and accessed using the


member access operator(.) via the structure variable name

 A structure containing a member that is a pointer to the same structure


type is called as a self referential structure.

 The structure pointer operator () is used when accessing a member of a


structure via a pointer to the structure
Unions are collection of different datatype grouped
together under a single variable name for convienient
handling.
syntax : union <union name >
{
datatype member1;
datatype member2;
};
union book
{
int pages;
char bookname[10];
char author[20];
float price;
};
For Example :
#include<stdio.h>
union amount
{
int ac_no;
char name[10];
char city [20];
int bal;
}a;
void main()
{
printf("Enter the account Details:\n");
scanf("%d%s%d",&a.ac_no, &a.name, &a.state, &a.bal);
printf(“%d\n%s\n%d\n", a.ac_no, a.name, a.city, a.bal);
printf("%d\n",sizeof(union amount));
getch();
}
/* For Example 2 */
#include<stdio.h>
#include<conio.h>
void main()
{
union a
{
int i;
char ch[2];
}a1;
a1.i=150;
clrscr();
printf("%d %c
%c",a1.i,a1.ch[0],a1.ch[1]);
getch();
}
OUTPUT :
150 ã
Example 3 :

#include<stdio.h>
union amount
{
int acct_no;
int acct_type;
char name[10];
char street[50];
char city_state[20];
int balance;
}a;
void main()
{
printf("Enter the account Details:\n");
scanf("%d%d%s%s%d“ ,
&a.acct_no,&a.acct_type,&a.name,&a.city_state,&a.balance);
printf("The values are %d\n%d\n%s\n%s\n%d\n", a.acct_no,
a.acct_type, a.name, a.city_state, a.balance);*/
printf("%d\n",sizeof(union amount));
}
Structure Arrays
It is an single entity representing a It is an single entity representing a Collection of
Collection of variables of different data variables of same data types
types
Individual entries in a structure are called Individual entries in a array are called array
Members elements
The members of a structure are not stored The members of a array are stored in sequence of
in sequence of memory locations memory locations

All the members of a structure can be Only the first member of an array can be
initialized initialized
Individual structure elements are referred Individual array elements are accessed by its
through the use of .(dot or membership) name followed by the square braces[] within
operator which the index is placed
Initialization of elements can be done only Initialization of elements can be done during array
during structure definition declaration
Structure definition reserve enough Array declaration reserve enough memory space
memory space for its members for its elements
The keyword ‘struct’ tells us what we are There is no keyword to represent arrays
dealing with structure
Structure Union
Keyword : struct Keyword : union
Each member in a structure occupies and All the members of a union use the same memory
uses its own memory space space
More memory space is required since each Less memory space is required since all member
member is stored in a separate memory is stored in the same memory locations
locations
All the members of a structure can be Only any one member of an union can be
initialized initialized
The variables that make up the structure The variables that make up the union are called
are called Structure variable union variable

Individual structure elements are referred Individual union elements are referred through
through the use of .(dot or membership) the use of .(dot or membership ) operator
operator

Structure is a user-defined data type. Union is a user-defined data type.


Possible to have one structure within Unions within union is possible
another structure
Session Summary

 The union is another compound data type may hold the variables of
different types and sizes with the compiler keeping track of the size.

The memory space reserved for a union members is large enough to store
its largest member

 The keyword “union” begins the union declaration followed by the tag
(i.e., union name)

 Within the braces union members are declared


Dynamic Memory
Allocations
[ It is the process of allocating
memory during Runtime (Execution
Time) ]
Dynamic Memory Management Technique
 Used to allocate additional memory space or to
release the unwanted memory space at runtime
 Used to optimize the use of storage space
 The programmer can allocate memory whenever he
decides and releases it after using the memory

malloc()
calloc()
alloc.h
realloc()
free()
Used to allocate a contiguous block of
memory in bytes.

Ptr_name= (*cast type) malloc(int


size*sizeof(int));
Example 1:
ptr=(int*)malloc(4*sizeof(int));

Note :
If the memory allocation is success it returns the
starting address else if returns NULL
Used to free (release or deallocate) the block of
unused or already used memory

free(pointer_variable);

Example 1:
ptr=(int*)malloc(4*sizeof(int));
free(ptr);
/* malloc() Function Example */
#include<stdio.h>
#include<alloc.h>
#include<process.h>
void main()
{
char *str;
if((str=(char *)malloc(10))==NULL){
printf("Not enough memory to allocate buffer\n");
exit(1);}
strcpy(str,"Helloworld");
printf("String is %s\n",str);
free(str);
}
String is
HelloWorld
malloc() Example 2
#include<stdio.h>
#include<conio.h>
void main()
{
int *ptr; //static memory allocation
clrscr();
ptr=(int *) malloc(sizeof(int));
*ptr=100;
printf("\n%u\n",ptr); //address of ptr
printf("\n%d\n",*ptr);
free(ptr);
getch();
}

/* note : int *ptr=100 means 100 is a address


*ptr=100 means 100 is a value */
To allocate memory using *sptr=500;
malloc and deallocate using
free sptr=startptr; /*assign the address of first
#include<stdio.h> data into the sptr; */
#include<alloc.h> for(i=0;i<5;i++)
void main() {
{ printf("%d\n",*sptr);
int *sptr,i; sptr++;
int *startptr; }
sptr=(int *) malloc(sizeof(int)*5); sptr=startptr;
startptr=sptr; /*startptr maintain the base
address(Ist Address) */ free(sptr); /* take sometime for deallocation
*sptr=100; */
sptr++;
sptr=NULL; /* so assign the null value
*sptr=200; you can't retrieve the data */
sptr++;
startptr=NULL;
*sptr=400; }
sptr++;

*sptr=300;
Allocating Memory
The following example uses a two-dimensional array to record
marks of 5 students for 10 subjects.
It uses pointers and malloc() function, to assign memory.
Pointer Increment process
*ptr=300;
but malloc allocates memory
ptr++; // increment 2 bytes
only for 4 bytes
printf("\n ptr 4= %d\n",*ptr);
#include<stdio.h>
free(ptr);
#include<conio.h>
getch();
void main()
}
{
int *ptr; //static memory allocation
clrscr();
ptr=(int *) malloc(sizeof(int)*2);
//allocate 4 bytes
*ptr=100;
ptr++; // increment 2 bytes
printf("\n ptr 1= %d\n",*ptr);
*ptr=150;
ptr++;
printf("\n ptr 2= %d\n",*ptr);

*ptr=200;
ptr++;
printf("\n ptr 3= %d\n",*ptr);
calloc() used to allocate multiple blocks of
contiguous memory in bytes. All the blocks are of
same size.

Ptr_name= (*cast type) calloc(No.of blocks,int


size);

Example 1:
ptr=(int*)calloc(5,sizeof(int));
On execution of this function 5 memory blocks of size 4 bytes
are allocated and the starting address of the first byte is assigned to the
pointer ptr of type int
/* Calloc() Function example */
#include<stdio.h>
#include<string.h>
#include<alloc.h>
void main()
{
char *str=NULL;
str=(char *)calloc(20,sizeof(char));
strcpy(str,"Welcome to world");
printf("String is %s\n",str);
free(str);
}

String is Welcome to
World
This function used to increase or decrease
the size of memory already allocated by using
malloc() or calloc() function

Void * realloc(void* pointer,size_t size);

Here,
pointer − The pointer which is pointing the previously
allocated memory block by malloc or calloc.
size − The new size of memory block.
Here is an example of realloc() in C language,
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
printf("\nError! memory not
allocated.");
exit(0);
}
printf("\nEnter elements of array :
");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
p = (int*) realloc(p, 6);
printf("\nEnter elements of array :
");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
//REALLOC() FUNCTION EXAMPLE
#include<stdio.h>
#include<string.h>
#include<alloc.h>
void main()
{
char *str;
str=(char *)malloc(5);
strcpy(str,"Kalai");
printf("String is %s\n Address is %u\n",str,str);
str=(char *)realloc(str,5);
strcpy(str,"Sangeetha");
printf("String is %s\n New Address is %u\n",str,str);
free(str);
}

String is Kalai address is 65524


String is Sangeetha address is
65524
Session Summary

 Like all variables a pointer must be declared before they are used

 The indirection (or) the deferencing operator is used to access the value
of an address in a pointer

 The three values that can be used to initialize a pointer are zero, null
and address

 A pointer that has not been initialized is referred to as the dangling


pointer

 Arrays are automatically passed by reference since the value of the


array name is the address of the array

 Call by reference is the process of calling a function using pointers to


pass the address as argument must include a pointer as its parameter.
Files
A file may be anything from a disk file to a terminal or a printer.

A file is associated with a stream by performing an open operation


and is disassociated from a stream by a close operation.

All files are automatically closed when the program, using them,
terminates, normally by main() returning to the operating system
or by a call to exit().

Files are not closed when a program crashes


File :
A file is a place on the disk where a group of related data is stored simply
defined as “Collection of related information”

Types of Files:
1. Text File (or) Sequential File
2. Binary File (or) Random File

Text File :
It is a Sequence of characters. It can be organised into lines terminated by a
newline character.
Binary File :
It is a Sequence of Bytes with one-to-one correspondence to those in the
external device, that is there are no character translations.
Also the number of bytes written (or read) is the same as the number on
the external device.
It do not have any flags to indicate the end of the file. It can be
determined by the size of the file.
Basic file operations
 Naming a file
 Opening a file
 Reading data from a file
 Writing data to a file
 Closing a file
Function Operation
Name
fopen() Creates a new file
Opens an existing file
fclose() Closes a file which has been opened
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads an integer from a file
putw() Writes an integer to a file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file(bytes)
rewind() Set the position to the begining of the file
It is a pointer to a structure which contains
the information about the file
FILE *file
pointername;
FILE *fp;

FILE pointername = fopen(“filename”, “file


mode”);

fp=fopen(“emp.dat”,
”w”);
Mode Name Meaning
w Open a text file for Writing
r Open a text file for Reading
a Append to a text file
rb Open a binary(random) file for reading
wb Create a binary(random) file for Writing
ab Append to a binary(random) file
r+ Open a text file for Read/Write
w+ Create a text file for Read/Write
a+ Append or create a text file for Read/Write
r+b Open a binary(random) file for read/write
w+b Create a binary(random) file for read/write
a+b Append a binary(random) file for read/write

fclose(filepointer
name);
fclose(fp);
Writing a character
The function used for writing characters to a file, that was
previously opened using fopen(), is fputc().
Syntax :

Reading a character
The fgetc() function is used for reading characters from a file
opened in read mode, using fopen().

Syntax :
String Input / Output
fputs() and fgets(), which write and read character strings to
and from disk file.

The Syntax for the above functions are -


fprintf() and fscanf()
These functions are similar to printf() and scanf() except that
they operate with files.

Syntax

int fprintf(FILE *fp, const char *control_string, …);

int fscanf(FILE *fp, const char *control_string, …);


rewind() function
The rewind() function resets the file position indicator to the
beginning of the file.

The syntax for rewind() is :

The prototype for the rewind() is available in stdio.h


// Program uses fgets() to get a String // Program uses fputs() to send a
from the File String to a File
#include<stdio.h> #include<stdio.h>
#include<conio.h>
void main()
#include<conio.h>
{ void main()
FILE *fp; {
char s[80],n[25]; FILE *fp;
int c; char s[80];
clrscr(); clrscr();
printf("\n Enter Your Filename :"); fp=fopen("t1.txt","w");
gets(n);
fp=fopen(n,"r");
if(fp==NULL)
if(fp==NULL) {
{ printf("\n Cannot open a File");
printf("\n Cannot open a File"); exit(1);
exit(0); }
} printf("\n Enter Your Text\n");
c=0; while(strcmp(gets(s),"end")!=0)
printf("\n The Contents of your file is\n");
while(fgets(s,80,fp)!=NULL)
{
{ fputs(s,fp);
printf("%s",s); }
c++; puts("Data Can Be Updated
} Sucessfully");
printf("Total Lines :%d\n\n",c); getch();
fclose(fp); }
getch();
}
// Program uses fgetc() to get a // Program uses fputc() to send a
character from the File character to an ASCII File
#include<stdio.h> #include<stdio.h>
void main() #include<conio.h>
{ void main()
FILE *fp; {
char s[80]; FILE *fptr;
int i,ch; char strptr[]="This Is a Test \0";
fp=fopen("first.dat","r"); char *p;
if(fp==NULL) clrscr();
{ fptr=fopen("first.dat","w");
printf("\n Unable to open the if(fptr==NULL)
File"); {
exit(0); printf("\n Unable to open the File");
} exit();
ch=fgetc(fp); }
for(i=0;i<80 && ch!=EOF;i++) for(p=strptr; *p != '\0';p++)
{ {
s[i]=ch; fputc(*p,fptr);
ch=fgetc(fp); }
} getch();
s[i]='\0'; }
printf("\n %s",s);
fclose(fp);
}
// file creation : writing data to a file
#include<stdio.h> Read the contents from the file
#include<conio.h> #include<stdio.h>
FILE *fp; #include<conio.h>
void main() FILE *fp;
{ void main()
char name[20];
{
int no;
int sal; char c;
fp=fopen("emp.dat","w"); clrscr();
if(fp != NULL) if((fp=fopen("emp.dat","r"))!
{ =NULL)
printf("\nEnter the number:");
scanf("%d",&no); {
printf("\nEnter the name:");
while((c=getc(fp))!=EOF)
scanf("%s",&name);
printf("\nEnter the salary:"); putc(c,stdout);
scanf("%d",&sal); }
fprintf(fp,"The no is %d\n",no); else
fprintf(fp,"The name is %s\n",name); {
fprintf(fp,"The salary is %d\n",sal); printf("Error in opening a file");
printf("\n Suceesfully Created");
}
}
else
{ fclose(fp);
printf("\n File Cannot Opened"); getch();
exit(0); }
}
fclose(fp);
}
Append the Data to an Existing
File
#include<stdio.h>
FILE *fp;
void main()
{
char name[20];
long int no;
long int sal;
if((fp=fopen (“emp.dat","a"))!
=NULL)
{
printf("\n enter the number:");
scanf("%d",&no);
printf("\n enter the name:");
scanf("%s",name);
printf("\n enter the salary:");
scanf("%d",&sal);
fprintf(fp,"the no is %d\n", no);
fprintf(fp, "the name is %s\
n",name);
Write a “C” Program to add, View ,Modify and Delete Records in Electricity Board Bill
Preparation using Random File
printf("\n 1. Add Record
#include<stdio.h ");
> printf("\n 2.View goto MENU;
#include<stdlib.h Record"); }
> printf("\n 3.Delete a void add_record()
#include<conio.h Record"); {
> printf("\n 4.Modify a struct electric r;
#include<dos.h> record"); FILE *eb;
void printf("\n 5.Terminate char flag;
add_record(); the Program"); eb=fopen("eb.dat","ab+");
void CHOICE : clrscr();
view_record(); printf("\n Enter your do
void choice "); {
modify_record(); scanf("%d",&ch); printf("\n Enter Details");
void del_record(); if((ch<1) && (ch>5)) scanf("%ld %s %s %f
{ %f",&r.scno,r.pname,r.area,&r.pre_rea
struct electric goto CHOICE; ding,&r.cur_reading);
{ } fwrite(&r,sizeof(r),1,eb);
long int scno; switch(ch) fflush(stdin);
char pname[30]; { printf("\n Add another record [y/n];");
char area[20]; case 1:add_record(); flag=getchar();
float cur_reading; break; }while(toupper(flag)=='Y');
float pre_reading; case 2:view_record(); fclose(eb);
}; break; }
case 3:del_record();
void view_record() clrscr();
{ printf("\n The File datas Are \n\
struct electric r; n");
FILE *eb; printf("%ld %s %s %f
char flag; %f",r.scno,r.pname,r.area,r.pre_re
eb=fopen("eb.dat","rb+"); ading,r.cur_reading);
clrscr(); fflush(stdin);
while((fread(&r,sizeof(r),1,eb)!=NULL)) printf("\n Are U Sure to Delete
{ this record[Y/N]:");
printf("\n The File datas Are \n\n"); ch=getchar();
printf("%ld %s %s %f if(toupper(ch)=='Y')
%f",r.scno,r.pname,r.area,r.pre_reading,r.cur_r {
eading); fwrite(&r,sizeof(r),1,temp);
} continue;
} }
void del_record() }
{ else
struct electric r; {
FILE *eb,*temp; fwrite(&r,sizeof(r),1,temp);
long int no; }
char ch; }
temp=fopen("temp.dat","wb+"); remove("eb.dat");
eb=fopen("eb.dat","rb+"); rename("temp.dat","eb.dat");
clrscr(); remove("temp.dat");
printf("\n Enter the Number to Delete :"); fclose(eb);
scanf("%ld",&no); fclose(temp);
while((fread(&r,sizeof(r),1,eb)!=NULL)) return;
{ }
if(r.scno==no)
{
void modify_record()
{
struct electric r; scanf("%ld %s %s %f
FILE *eb; %f",&r.scno,r.pname,
long int no,pos; r.area,&r.pre_reading,&r.cur_reading);
char ch; fseek(eb,0,pos);
eb=fopen("eb.dat","rb+"); fwrite(&r,sizeof(r),1,eb);
clrscr(); puts("Record Updated Sucessfully");
printf("\n Enter the Service Number to getch();
modify :"); }
scanf("%ld",&no); }
while(eb!=NULL) else
{ {
pos=ftell(eb); puts("Service Number Not Found");
fread(&r,sizeof(r),1,eb); }
if(r.scno==no) fclose(eb);
{ return;
clrscr(); }
printf("\n The File datas Are \n\n"); }
printf("%ld %s %s %f
%f",r.scno,r.pname,r.area,r.pre_reading,r.cu
r_reading);
fflush(stdin);
printf("\n Are U Sure to Modify this
record[Y/N]:");
ch=getchar();
if(toupper(ch)=='Y')
{
printf("\n Enter Details");
 fopen() opens a stream for use and links a file with that stream
 fclose() closes a stream that was opened by a call to fopen()
 fputc()is used to write characters,fgetc() is used to read characters from an
open file
 fputs is used to write group of characters(string) fgets() is used to read
group of characters from an open file
 feof() is used to indicate end-of-file when the file is opened for binary
operations
 rewind() function resets the file position indicator to the beginning of the file
 fprintf() is used to write any type of informations (any datatype) to an
file,fscanf() is used to read any type of informations from an open file.
 The ftell() used to indicate the current position of file pointer
 The fseek() is used to set the position of filepointer which we can desired
Preprocessor Directives
Preprocessor directives are instructions given to the compiler.
They begin with a # sign and can be placed anywhere in the
program but usually they are placed in the beginning of a
program.
Some of the preprocessor directives

# if # elif
# ifdef # include
# indef # define
# else # undef
# define
The # define directive contains two parts : an identifier and a
string that is to be substituted for the identifier, each time the
identifier is encountered in the source file.

The identifier and string are separated by a space.

The identifier can be referred to as the macro name and the


string as the macro substitution.
Conditional Compilation
Directives
Example for Compiler Directives printf("hai");
#define N putchar('\n') N;
#define mul(x,y) ((x)*(y)) printf("%d",mul(2,3));
#define mysqrt(x) ((x) * (x)) N;
printf("%d",mysqrt(4));
#ifdef N
N;
#define FORMAT N,N
#endif printf("%s | %s | Line Number :
%d",__FILE__,__DATE__,__LINE__);
#ifdef FORMAT NF;
#undef FORMAT NNN;
#define NF N,printf("hai"),N }
#endif

#ifdef NF hai
#ifndef FORMAT
6
#define NNN N,printf("new"),N
#endif 16
#endif Compi~1.c | Feb 16 2008 | Line
#include <stdio.h> Number : 29
void main() hai
{ new
The const Keyword
It can be used to achieve almost the same effect as #define
when creating constants.

Variables of type const can be given an initial value, but


cannot be changed through the program.
Example :
Session Summary

 Storage of information to be read from or written on a auxillary memory


device is stored in the form of file.

 The data structure of a file is defined in stdio.h which creates a buffer


area to store data in a file for reading as well as writing

 Function fscanf() & fprintf() are used to perform I/O operations in file

 Function fgetc() & fputc() are used to perform Character I/O operations

in file

 Function fgets() & fputs() are used to perform String I/O operations in
file

 Function fseek() used to index a file and can be used to increment or


decrement the file pointer by any number of position in a file.

You might also like