Date post: | 17-May-2015 |
Category: |
Education |
Upload: | selvam-edwin |
View: | 2,773 times |
Download: | 0 times |
=======0======================================
Year 1972 at Bell telephone laboratories (AT
&T) by DENNIS RITCHIE.
Features of ‘C’ language:
1. it is a flexible high level structured program language
2. it includes the features of low level language like assembly
language.
3. it is much faster and efficient.
4. it has a number of built-in functions, which makes the
programming task simple
The ‘C’ language is used for developing:
1. database system.
2. graphics packages.
3. scientific and engineering applications.
Format of C program:
Headerfile include
Main()
{
variable declaration;
program statements;
}
Ex:
#include<stdio.h>
main()
{
printf(“god is great”);
}
Keywords:
Keywords are words belongs to C language. The users have no
right to change its meaning.
Ex:
auto, goto, if, int, while, do, switch, case, char, else…..
Datatype:
TYPE SIZE(bits) RANGE
char 8 -128 to 127
unsigned char 8 0 to 255
int 16 -32,768 to 32,767
unsigned int 16 0 to 65,535
long int 32 -2,147,483,648 to
2,147,483,647
unsigned long int 32 0 to 4,294,967,295
float 32 3,4E-38 to 3,4E+38
double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932 to 1.1E+4932
Variables:
C variable refers to the name given to the memory location to
store data. A particular memory location is given only one name.
Yet this name is called a variable because this memory location
can store sequence of different values during the execution of the
same program.
Rules:
1. a variable name is formed with alphabets, digits and a special
character underscore( _ )
2. the first character must be an alphabet.
3. no special characters are used other than underscore
4. both upper case and lower case letters are used.
Declaration variables:
Syntax:
Data-type list of variables;
Ex:
int x,y,z;
initializing variables:
syntax:
data-type variable=initial value;
Ex:
int a=10;
float b=43.3;
comment statement:
comment statements are non-executable statements.
1. single line statement //
2. paragraph statement /* */
OPERATORS:
An operator is a symbol which represents some operation that
can be performed on data. There are eight operators available in C
to carry out the operations. They are
1. arithmetic operators
2. relational operators
3. logical operators
4. short hand assignment operators
5. conditional operators
Arithmetic operators:
Arithmetic operators are used to do arithmetic calculations.
There are 2 types
(i) binary operators
(ii) unary operators
Binary operator:
BO need two operands for operations.
Operator operation Ex
+ addition x=5+6
- subtraction x=10-5
* multiplication x=5*4
/ division x=5/3 =1
% modulo operator x=5%3 =2
Unary operators:
UO need only one operands for operation.
Operator operation Ex
++ increment i++
-- decrement i—
Relational operators:
RO are used to find out the relationship between two
operands. They are
Operator operation Ex
> greater than a>b
< less than a<b
>= greater than equal to a<=b
<= less than equal to a>=b
= = equal to a= =b
!= not equal to a!=b
Logical operators:
LO are used to find out the relationship between two or more
relational expressions. They are
Operator operation Ex
&& AND (a>b)&&(a>c)
|| OR (a>b)||(a>c)
Short-hand assignment operators:
SHAO are operators which are used to simplify the coding
of certain type of assignment statement.
The general form is
Variable operator = expression
Variable = user define name
Operator = +,-,*,/,%
Ex:
Operator operation Ex
+= value of LHS variable
will be added to the x = x +10can be
RHS value and is written as x+=10
Assigned to LHS variable
Conditional Operators:
The CO ? and : are used to build simple conditional
expression. It has three operands. So it is called ternary operator.
The general form is
Expression1 ? expression2: expression3;
Expression1 is evaluated first. If it is true expression2 is
evaluated.if expression1 if false expression3 is evaluated.
Ex:
Sum = a>b ? a: b;
Input statement:
Scanf () function:
Scanf () is used to give data to the variables using keyboard.
The general form is
Scanf (“control string”, &variable1, ….&variable n);
Ex:
Scanf(“%d”,&a);
This statement reads a integer data and assigns to variable a
Output statement:
Printf () function:
Printf () is used to output the results of the program to the user
through VDU.
The general form is
Printf(“control string”, list);
Conversion character table:
C single character
D decimal integer
F floating point value
H short-integer
S string
CONTROL STATEMENTS:
1. Unconditional statements
2. Conditional (or) Decision making statements
3. Looping Statement
Unconditional Statement:
1. goto statement
goto statement is used to transfer the program control
unconditionally from one point to another.
The general form is:
goto label;
The label is the name given to the point where the control has to be
transferred
The general form is
Label:statement;
Conditional Statement:
CO are used to skip or to execute a group of statements based
on the result of some condition.
1. if statement
2. if….else statement
3. else….if ladder
4. nested if statement
5. switch statement
(i) Simple if statement:
Simple if statement is used to execute or skip one statement or
group of statements for a particular condition.
The general form is
If(test condition)
{
statement block;
}
next statement;
Ex:
#include<stdio.h>
void main()
{
int mark;
char grade;
scanf(“%d %c”, &mark, &grade);
if(grade = =’a’)
{
mark=mark+10;
}
printf(“%d”,mark);
}
(ii) if….else statement:
if…else statement is used to execute one group of statements if the
test condition is true or other group if the test condition is false.
The general form is
If(test condition)
{
statement block-1;
}
else
{
statement block-2;
}
next statement;
Ex:
#include<stdio.h>
void main()
{
int mark;
scanf(“%d”, &mark);
if(mark=>35)
printf(“pass”);
else
printf(“fail”);
}
(iii) else…..if ladder:
else….if ladder statement is used to take multiway decision. This
statement is formed by joining if….else statement in which each
else conditions another if….else
The general form is
If(test condition-1)
{
statement block-1;
}
else if(test condition-2)
{
statement block-2;
}
…………………………
………………………
…………….
else if(test condition-n)
{
statement block-n;
}
else
default statement;
next statement;
Ex:
#include<stdio.h>
void main()
{
int day;
printf(“give a number between 1 to 7\n”);
scanf(“%d”, &day);
if(day= =1)
printf(“sunday\n”);
if(day= =2)
printf(“Monday\n”);
if(day= =3)
printf(“tuesday\n”);
if(day= =4)
printf(“wednesday\n”);
if(day= =5)
printf(“thursday\n”);
if(day= =6)
printf(“friday\n”);
if(day= =7)
printf(“saturday\n”);
else
printf(“enter the currect value”\n);
}
Nested if….else statement:
This statement is formed by joining if….else statements
either in the if block or in the else block or both
The general form is:
If(test condition-1)
{
if(test condition-2)
{
statement block-1;
}
else
{
statement block-2;
}
else
{
statement block-3;
}
next statement;
when this statement is executed, the computer first evaluates the
value of test condition-1. if it is false control will be transferred to
statement block-3. if it is true test condition-2 is evaluated. If it is
true statement block-1 is executed and control is transferred to next
statement else statement block-2 is executed and control is
transferred to next statement.
Ex:
#include<stdio.h>
main()
{
int a,b,c;
printf(“enter 3 no”);
scanf(“%d %d%d”, &a,&b,&c);
if(a>b)
{
if(a>c)
printf(“A is big=%d”,a);
else
printf(“B is big=%d”,c);
}
else
{
if(b>c)
printf(“B is big=%d”,b);
else
printf(“C is big=%d”,c);
}
}
Switch Statement:
Switch statement is an extension of if…..else statement. This
permits any number of branches.
The general forms:
Switch (expression)
{
case label-1:
statement block-1;
break;
case label-2:
statement block-2;
break;
…………………………..
…………………………..
case label-n:
statement block-n;
break;
default:
default statement;
break;
}
next statement
Ex:
#include<stdio.h>
main()
{
int day;
printf(“Enter the no 1 to 7\n”);
scanf(“%d”, &day);
switch(day)
{
case 1:
printf(“Sunday \n”);
break;
case 2:
printf(“Monday \n”);
break;
case 3:
printf(“Tuesday \n”);
break;
case 4:
printf(“Wednesday \n”);
break;
case 5:
printf(“Thursday \n”);
break;
case 6:
printf(“Friday \n”);
break;
case 7:
printf(“Saturday \n”);
break;
default:
printf(“Enter the currect no:\n”);
break;
}
}
LOOPING STATEMENTS:
Looping statements are used to execute a group of statements
repeatedly until some condition is satisfied. The looping
statements are
1. while statement
2. do…while statement
3. for statement
While statement:
First evaluates the test condition. If the value is false, the
control is transferred to next statement. If the value is true, then the
body of the loop is executed repetedly until the test condition
becomes false. When the test condition becomes false the control
is transferred to next statement.
The general form is:
While(test condition)
{
body of the loop;
}
next statement;
Ex:
#include<stdio.h>
main()
{
int I;
I=1;
While(I<5)
{
printf(“god is love”);
I++;
}
}
Do…While statement
When this statement is executed the body of the loop is
executed first. Then the test condition is evaluated. If the value is
false, the control is transferred to the next statement. If the value is
true the body of the loop is executed repeatedly until the test
condition becomes false. When the test condition becomes false
the control is transferred to the next statement.
The general form is:
Do
{
body of the loop;
}
while(test condition);
next statement;
Ex:
#include<stdio.h>
main()
{
int I;
I=1;
Do
{
printf(“god is love”);
I++;
}
while(I<5)
}
For Statement:
For statement is used to execute a statement or a group of
statements repeatedly for a known number of times.
The general form is:
For(initial condition; test condition; increment or decrement)
{
body of the loop;
}
next statement;
Ex:
#include<stdio.h>
main()
{
int I, sum;
sum=0;
for(I=1; I<=50; I++)
{
sum=sum+I;
}
printf(“sum=%d”,sum);
}
Arrays:
An array is defined as a group of related data items that share
a common name. In computers we store information in the
memory by giving names to them. These names are called
variables.
Subscripted Variables:
The variables which are used to represent the individual data
in the memory are called subscripted variables
The general form is:
Array-name[subscript]
One dimensional arrays:
An array name with only one subscript is known as one
dimensional array.
Ex:
A [10], name [30], …
Declaration of one dimensional array:
Arrays must be declared before it is used like other variables.
The general form is
Data-type array-name [size];
Ex:
Int mark[100]
Array initialization:
We can assign initial values to the array just like we assign
values to variables when they are declared.
The general form is:
Static data-type array-name [size] = { list of values};
Ex:
1. Static int mark[3] ={65,87,78};
2. static int mark[5] ={65,87,78};
3. static float mark[]={65,87,78, 65,87,78};
Ex: smallest no:
#include<stdio.h>
main()
{
int I,n,a[10],small;
printf(“Give the 10 value”);
scanf(“%d”, &n);
for(I=0; I<n; I++)
scanf(“%d”, &a[I]);
small=a[0];
for(I=1; I<n;I++)
{
if(a[I] < small)
small=a[I];
printf(“The small value is:%d”,small);
}
}
Table handling:
An one dimensional array may be horizontal or vertical. In
some applications it is necessary to represent data in horizontal
(rows) as well as in vertical (columns). This type of representation
is said to be in tabular form. A two dimensional array is needed to
represent a table in memory.
Two dimensional array
An array with two subscripts is known as two dimensional
array.
The general form is
Array-name[subscript1][subscript2]
Ex:
A[2][2]
Declaration of 2-D array:
Like one dimentional arrays two dimentional arrays must be
declared before it is used like other variables.
The general form is:
Data-type array-name[row size][column size];
Ex:
Int mark[5][2]
Array initialization:
Like one dimensional arrays we can assign initial values to
2-D arrays when they are declared.
The genearal form is:
Static data-type array-name [row size] [column size]={list of
values};
Ex:
1. Static int mark[3][2]={1,2,3,4,5,6};
2. Static int mark[3][2]={{1,2}, {3,4}, {5,6}};
Ex:
#include<stdio.h>
void main()
{
int i,j;
int a[2][2], b[2][2], c[2][2];
printf(“Enter the A matrix no:”);
for(I=0;I<2;I++)
for(j=0;j<2;j++)
scanf(“%d”, &a[I][j]);
printf(“Enter the B matrix no:”);
for(I=0;I<2;I++)
for(j=0;j<2;j++)
scanf(“%d”, &b[I][j]);
for(I=0;I<2;I++)
for(j=0;j<2;j++)
c[I][j]=a[I][j]-b[I][j];
printf(“\n result of matrix is\n”);
for(I=0;I<2;I++)
{
for(j=0;j<2;j++)
printf(“%d”,c[I][j]);
printf(“\n”);
}
}
STRING:
Any group of characters enclosed in double quotes is a string
constant. A string is an array of characters terminated by a null
character.
Declaring String:
The string that can hold an array of characters can be
declared as
Char variable_name [size];
Ex:
Char name [10], book [10];
Initializing String:
A character array can be initialized by a string constant,
resulting in the first element of the array being set to first character
in the string, the second element to the second character and so on.
The array also receives the terminating ‘\o’ in the string constant
Ex:
Char name [9]=”computer”;
Char name [9]={‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’,’\o’}
Reading String:
1. By using scanf () function:
2. By using getchar () function:
3. By using gets () function:
3. By using loops
By using scanf () function:
The scanf () function with format string %s can be used to
read a string from the user.
Ex:
Main()
{
char name[10];
scanf(“%s”, name);
}
The disadvantage of scanf () function is that there is no way
to read a multi-word string into a single character array variable.
The scanf () function terminates its input when it encounters a
blank space
By using gets () function:
The gets () function with the array name can also be used to
read a string from the user. The gets () function overcomes the
disadvantage of the scanf () function, since it can read a string of
any length with any number of blank spaces and tabs.
Ex:
Main()
{
char name [10];
gets (name);
}
By using loops:
We know that a string is an array of characters, hence a string
can also be read, character by character from the user by using
loops.
STRING LIBRARY FUNCTION:
1. strcpy() - copies a string into another string
2. strcat() - appends one string at the end of another string
4. strcmp()- compares two string
5. strlen() - finds length of a string
6. strrev() - reverse a string
The strlen () function:
The strlen() function returns the count of number of
characters stored in a string.
Syntax: x=strlen(str);
#include<stdio.h>
#include<string.h>
void main()
{
char str[10];
printf(“Enter a string:”);
gets(str);
printf(“The length of the string is %d”, strlen(str));
}
The strcpy() function:
The strcpy() function is used to copy the contents of one
string to another. The general form is
Strcpy(string1,string2);
Ex:
#include<stdio.h>
#include<string.h>
void main()
{
char str[10],cpy[10];
printf(“Enter a string:”);
gets(str);
strcpy(cpy,str);
printf(“The source string is %s”,str);
printf(“The copied string is %s”,cpy);
}
The strcat() function:
The strcat() function concatenates the source string at the end
of the target string. The strcat() function takes two arguments for
concatenating.
The general form is:
Strcat(string1, string2);
Ex:
#include<stdio.h>
#include<string.h>
void main()
{
char str [10],cat [10];
printf(“Enter a string:”);
gets(str);
printf(“Enter another string:”);
gets(cat);
strcat(str,cat);
printf(“The concatenated string is :%s”,str);
}
The strrev() function:
The strrev() function is used to reverse a string. This function
takes only one argument.
The general form is:
X=strrev(string);
Ex:
#include<stdio.h>
#include<string.h>
void main()
{
char x[10];
printf(“Enter the string:”);
gets(x);
printf(“The reversed string is :%s”,strrev(x));
}
The strcmp() function:
The strcmp() function compares two strings to find whether
the strings are equal or not.
The general form is:
Strcmp(string1,string2);
Ex:
#include<stdio.h>
#include<string.h>
void main()
{
char str[10],cmp[10];
int x;
printf(“Enter a string:”);
gets(str);
printf(“Enter another string:”);
gets(cmp);
x=strcmp(str,cmp);
if(x = = 0)
puts(“Strings are equal”);
else if (x>0)
printf(“String %s is greater than string %s”, str, cmp);
else
printf(“String %s is greater than string %s”, cmp, str);
}
FUNCTION:
A function is a self-contained program segment that performs
some specific well-defined task when called. Function break large
computing tasks in to smaller ones. C programs generally consist
of many small functions rather than few big ones. Every c program
consists of one or more functions, but there should be at least one
function which must be main ().
C functions may be classified into two categories namely
1. user-defined functions
2. library function
The main () function that we have seen so far in the programs is an
example of an user-defined function.
Printf (), scanf (), etc.. are the examples of library functions.
Ex:
#include<stdio.h>
void func();
void main()
{
printf(“\n Inside main function”);
func();
printf(“\n again inside main function”);
}
void func()
{
printf(“\n inside func function”);
}
Defining a Function:
A function definition consists of two parts.
1. argument declaration
2. body of the function
Syntax:
Return-type function-name (argument list) ->argument decla
{
declarations;
statements; ->body fun
return(expression);
}
Ex:
Int add (int x, int y)
{
Int z;
Z=x+y;
Return (z);
}
TYPE OF FUNCTION:
A function depending upon the arguments present or not and
whether a value is returned or not. There are 4 types of classified
1. Function with no arguments and no return values.
2. Function with no arguments and return values
3. Function with arguments and no return values.
4. Function with arguments and return values.
Function With No Arguments And No Return Values:
In this type of function no value is passed from the caller
function to the called function and no value is returned to the
caller function from called function.
Ex:
#include<stdio.h>
void main()
{
void message ();
printf(“\n I am in main function);
message();
printf(“\n I am back in main function”);
getch();
}
void message()
{
printf(“\n\n I am in user defined function”);
return;
}
Function With No Arguments And Return Values:
In this type of function no value is passed from the caller
function to the called function (user defined function) but some
value is returned to the caller function from the called function.
Ex:
#include<stdio.h>
main()
{
float f;
clrscr();
f=area();
printf(“\n the area is %f”,f);
getch();
}
float area()
{
float a,b,area;
printf(“\n enter the length and breadth of a rectangle:”);
scanf(“%f %f ”, &a, &b);
area = a*b;
return(area);
}
Function With Arguments And No Return Values:
In this type of function, some values are passed from the
caller function and no values are returned to the caller function
from the called function.
Ex:
#include<stdio.h>
main()
{
float a,b;
void area_rectangle (float, float);
clrscr();
printf(“\n enter the length & breadth:”);
scanf(“%f %f”, &a, &b);
area_rectangle (a,b);
getch();
}
void area_rectangle(x,y)
float x,y;
{
float area;
area=x*y;
printf(“\n area of rectangle is %f”, area);
return;
}
Function With Arguments And Return Values:
In this type of functions some values are passed to the called
function from the caller function and some values are passed back
to the caller function from the called function.
Ex:
#include <stdio.h>
main ()
{
float area(float, float), f,b,h;
clrscr();
printf(“\n enter the breadth and height of a triangle:”);
scanf(“%f %f”, &b, &h);
f=area(b,h);
printf(“\n the area is %f”,f);
getch();
}
float area(float b, float h)
{
float area;
area=b*h;
return(area);
}
Example for Type of Function’s:
/* FUNCTION WITH NO ARGUMENTS AND NO RETURN
VALUES
#include<stdio.h>
#include<conio.h>
void name();
void main()
{
clrscr();
name();
getch();
}
void name()
{
char empname[25];
printf("Enter the employee name:");
scanf("%s", empname);
printf("The employee name is %s", empname);
}
FUNCTION WITH RETURN VALUES AND NO ARGUMENTS
#include<stdio.h>
#include<conio.h>
int sum();
void main()
{
clrscr();
printf("is %d", sum());
getch();
}
int sum()
{
int i,n,result=0;
printf("Enter the limit:");
scanf("%d", &n);
printf("Sum of even numbers within %d", n);
for(i=2;i<=n;i+=2)
{
result +=i;
}
return(result);
}
FUNCTION WITH ARGUMENTS AND NO RETURNVALUES
#include<stdio.h>
#include<conio.h>
void simple(float,float,int);
float principal,rate;
int year;
void main()
{
clrscr();
printf("Enter principal, rate of interest & no. of years \n");
scanf("%f %f %d", &principal, &rate, &year);
simple(principal,rate,year);
getch();
}
void simple(float principal, float rate, int year)
{
float simple_interest=0.0;
simple_interest = (principal * rate * year)/100;
printf("The simple interest is %.2f", simple_interest);
}
FUNCTION WITH ARGUMENTS AND RETURN VALUES
#include<stdio.h>
#include<conio.h>
int sum(int x);
void main()
{
int n;
clrscr();
printf("Enter the limit:");
scanf("%d", &n);
printf("Sum of first %d natural numbers is %d", n, sum(n));
getch();
}
int sum(int x)
{
int i, result=0;
for(i=1; i<=x;i++)
result +=i;
return(result);
}
RECURSION:
In c it is possible to call a function. Recursion is a process by
which a function calls itself repeatedly until some specified
condition has been satisfied. A function is called recursive if a
statement within the body of a function calls the same function.
Recursion is a process of defining something in terms of itself.
Ex:
#include<stdio.h>
Long fact (long);
void main()
{
long num, fac;
printf(“Enter a number:”);
scanf(“%ld”, &num);
fac=fact(num);
printf(“The factorial of %ld is %ld”, num, fac);
}
long fact (long x)
{
if(x<=1)
return (1);
else
return(x * fact(x-1));
}
NESTED OF FUNCTION:
We have seen programs using functions called only from the
main() function. But there are situations, where functions other
than main() can call any other function(s) used in the program.
This process is referred as nested of functions.
Ex:
#include<stdio.h>
void func_1 ();
void func_2 ();
void main ()
{
printf(“\n inside main function”);
func_1 ();
printf(“\n again inside main function”);
}
void func_1 ()
{
printf(“\n inside function 1”);
func_2 ();
printf(“\n again inside function 1”);
}
void func_2 ()
{
printf(“\n inside function 2”);
}
STORAGE CLASSES:
The variables are associated with certain properties such as
scope and lifetime in a program. By scope of a variable means that
the portions of the program in which it can be used. The lifetime of
a variable is the period of time during which the value is available
in memory.
The four different storage class
1. automatic storage class
2. external storage class
3. static storage class
4. register storage class
AUTOMATIC STORAGE CLASS
Variables defined inside a block and are local to the block in
which they are declared, are refered as automatic variables as local
variables. Automatic variables can only be accessed by the block
in which they are declared. Any another block cannot access its
value.
Ex:
#include<stdio.h>
#include<conio.h>
/*void main()
{
auto int x=5;
{
auto int x=4;
{
auto int x=3;
clrscr();
printf("%d \t",x);
}
printf("%d \t",x);
}
printf("%d \t",x);
getch();
}
EXTERNAL STORAGE CLASS:
Variables that are both alive and active throughout the entire
program are called as external variables also refered as global
variables. Global variables can be accessed by any function in the
program. Global variables are also stored in the memory. When an
external variable is not initialized it takes a value of zero.
Ex:
int value;
void main()
{
value = 100;
clrscr();
test1();
test2();
test3();
printf("%d\n", value);
getch();
}
test1()
{
value += 100;
printf("%d\n", value);
}
test2()
{
value = 1000;
printf("%d\n", value);
}
test3()
{
value += 100;
printf("%d\n", value);
}
STATIC STORAGE CLASS:
The world static in general refers to anything that is insert to
change. In a program if static variables are declared within
individual blocks they are local to the block in which they are
declared. The static variables retain their values throughout the life
of the program.
Ex:
void main()
{
clrscr();
sum();
sum();
sum();
sum();
getch();
}
sum()
{
static int x=1;
printf("%d", x);
x=x+1;
}*/
REGISTER STORAGE CLASS:
The register storage class is similar to the auto storage class
since the variables defined inside a block are local to the block in
which it is specified. Register variable can only be accessed by the
block in which it is declared. Its value cannot be accessed by any
other function
Ex:
void main()
{
register int x;
clrscr();
for (x=1; x<=10; x++)
printf("%d",x);
getch();
}
STRUCTURES:
A structure is a collection of one or more variables grouped
under a single name for easy manipulation. The variables in a
structure, unlike those in an array, can be of different variable
types. A structure can contain any of C’s data types, including
arrays and other structures. Each variable within a structure is
called a member of the structure.
Defining a structure:
A structure definition contains keyword struct and a user
defined structure-name followed by the members of the structure
with in braces.
The general form is:
Struct structure-name
{
data-type member-1;
data-type member-2;
……………..
…………….
data-type member-n;
};
Ex:
Struct student
{
int no;
int age;
char sex;
};
Structure declaration:
Structure declaration means defining variables to the already
defined structure. We can define variables in two ways.
1. variable definition along with the structure definition
2. variable definition using structure-name any where in the
program
The first general form is:
Struct structure-name
{
data-type member-1;
data-type member-2;
……………..
…………….
data-type member-n;
} variable-1, variable-2,…….variable-n;
Ex:
Struct student
{
int no;
int age;
char sex;
}s1,s2,s3;
The second general form is:
Struct structure-name
{
data-type member-1;
data-type member-2;
……………..
…………….
data-type member-n;
};
structure-name variable-1, variable-2,…….variable-n;
Ex:
Struct student
{
int no;
int age;
char sex;
};
student s1, s2, s3;
Giving values to structure members:
Dot operator or member operator ‘.’ Is used to give data to
the structure variables individual members.
The general form is;
Structure variable . member-name
The variable name with a period and the member name is
used like any ordinary variable
Ex:
Struct student
{
int no;
int age;
char sex;
}s1;
the above declaration has a variable s1 having three
members. The values or data to the members of the variable can
be given by any one of the following method.
(i) using keyword;
scanf(“%d”, &s1.no);
scnaf(“%d”, &s1.age);
scanf(“%c”,&s1.sex);
(ii) using assignment statement:
s1.no = 100;
s1.age = 18;
s1.sex = ‘m’;
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
struct emp
{
char sex;
int no;
float salary;
}d1;
clrscr();
printf("Give the values to the members\n");
printf("Give the sex.......");
scanf("%c", &d1.sex);
printf("Give the number....");
scanf("%d", &d1.no);
printf("Give the salary....");
scanf("%f", &d1.salary);
printf("\n");
printf("Employee - details \n");
printf("Sex: %c\n", d1.sex);
printf("Number: %d\n", d1.no);
printf("Salary: %f\n", d1.salary);
getch();
}
Array of Structures:
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 called an array of structures.
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int no;
int age;
char sex;
};
struct student s1[2];
int i;
clrscr();
for(i=0;i<2;i++)
{
printf("Enter number,age,sex\n");
scanf("%d %d %c", &s1[i].no, &s1[i].age, &s1[i].sex);
}
for(i=0;i<2;i++)
printf("%d %d %c\n", s1[i].no, s1[i].age, s1[i].sex);
getch();
}
Structures with structures [Nested Structure]:
When a structure is declared as a member of another
structure then it is called structure within structure or nested
structure.
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
struct hostel_detail
{
int hostel_room_no;
char food;
int deposit_amount;
};
struct student
{
char name[10];
int no;
char branch[5];
struct hostel_detail h1;
};
static struct student s1={"Raja", 100, "Ct", 10, 'v', 2000};
clrscr();
printf("%s %d %s %d %c %d", s1.name, s1.no, s1.branch,
s1.h1.hostel_room_no,
s1.h1.food, s1.h1.deposit_amount);
getch();
}
Passing Entire Structure To Function:
In this method, the entire structure is passed as an argument
to the function. Note that when using a structure as a parameter,
remember that the type of the argument in the function call
statement must match the type of a parameter (list if any), in the
function prototype. Since the function is working on a copy of the
structure, any changes made to the structure members within the
function are not reflected in the orginal structure.
Ex:
#include<stdio.h>
#include<conio.h>
void employ(struct employee emp);
struct employee
{
int empno;
char empname[10];
}emp1;
void main()
{
printf("Enter employee no and name:");
scanf("%d %s", &emp1.empno, emp1.empname);
employ(emp1);
}
void employ(struct employee emp)
{
printf("\n the employee no is :%d", emp.empno);
printf("\n the employee name is:%s", emp.empname);
}
FILES
Files are used for permanent storage of large amount of data.
A file can be used to write and/or read data from a disk. File
handling in C is very simple, since it essentially treats a file as just
a stream of characters and allows input and output in a file.
So far we used scanf and printf function to read and write data to
and from the computers through the console. If computers deal
with large amount of data as input and output (read, write) then
both methods are not efficient. The best way is to use files to give
data to the computers and get data from the computers.
Defining a File:
A file is defined as FILE in the header file stdio.h therefore
all files should be declared as type FILE before they are used.
The general form is:
FILE *pointer variable;
Opening a File:
Before we read from a file or write to a file, we must open
the file. Opening establishes a link between the program and the
operating system.
The general form is:
FILE *pointer variable;
Pointer variable = fopen (“file name”, “mode”);
Ex:
FILE *a;
a = fopen (“exam.txt”, “r”);
Closing the file:
An opened file must be closed after all operations on it have
been completed.
The general form is:
fclose (pointer variable);
Ex:
……………….
……………….
FILE *a, *b;
a= fopen(“exam.txt”, “r”);
b= fopen(“exam.txt”,”w”);
…………………..
………………….
fclose(a);
fclose(b);
Reading a file:
fscanf function is used to read data from a file.
The general form is:
fscanf(pointer variable, “control string”,list);
Ex:
fscanf(a, “%d%d”, &x,&y);
Writing to a file:
fprintf function is used to write data into a file
The general form is:
fprintf (pointer variable, “control string”,list);
Ex:
fprintf(a,”%d%d”, x,y);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int empno;
char empname[20],deptname[20];
FILE *ptr;
clrscr();
ptr=fopen("exam.dat","w");
printf("Enter ename, eno and edept:");
scanf("%s %d %s", &empname, &empno, &deptname);
fprintf(ptr, "%s %d %s",empname, empno, deptname);
fclose(ptr);
ptr=fopen("exam.dat","r");
fscanf(ptr, "%s %d %s", &empname, &empno, &deptname);
printf("\n Employee Name:%s", empname);
printf("\n Employee Number:%d", empno);
printf("\n Department Name:%s", deptname);
fclose(ptr);
getch();
}
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int c;
FILE *fptr;
clrscr();
printf("Enter the text to store in the file\n");
fptr=fopen("example.txt","w");
while((c=getc(stdin))!=EOF)
fputc(c,fptr);
fclose(fptr);
printf("\n the contents of the file is \n");
fptr=fopen("example.txt","r");
do
{
c=fgetc(fptr);
putchar(c);
}
while (c!= EOF);
fclose(fptr);
getch();
}
Random Access Function:
Reading and writing operations on any file are normally
sequential. This is achieved by a system-controlled pointer, which
points the position immediately, after the last character is read or
written. Which points the position immediately, after the last
character is read or written. However, with the help of random
access functions a C programmer can move the file pointer to any
desired position in the file
One advantage of a random access file over other files is that,
a character can be written or read from the file by specifying the
exact location where the operation is to take place.
The random access functions used in a file are
1. the fseek() function
2. the ftell() function
3. the rewind() function
The fseek() Function:
The fseek() function is used to move the file pointer to any
desired location within a file. It can be used to increment or
decrement the file pointer by any number of positions in the file.
The general form is:
fseek (fptr, long int offset, int position);
Ex:
fseek (fptr, 5L, 0);
The Position:
Value Meaning
0 Beginning of the file
1 Current position of the file
2 End of the file
The ftell() Function:
The ftell() function returns the current position of the file
pointer in the file.
The general form is:
ftell(fptr);
The rewind () function:
The rewind () function resets the file pointer to the beginning
of the file.
The general form is:
rewind (fptr);
Merging Two Files:
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
char *a;
FILE *f1, *f2, *f3;
clrscr();
f1=fopen("student.txt","w");
printf("Enter the content of file1\n");
gets(a);
fputs(a,f1);
fclose(f1);
f2=fopen("student1.txt","w");
printf("Enter the content of file2\n");
gets(a);
fputs(a,f2);
fclose(f2);
f1=fopen("student.txt","r");
f3=fopen("student2.txt","w");
printf("\n the content of file1 is \n");
while (fgets(a, strlen(a)+1,f1)!=NULL)
{
fputs(a,f3);
printf("%s",a);
}
fclose(f1);
fclose(f3);
f2=fopen("student1.txt","r");
f3=fopen("student2.txt","a");
printf("\n The content of file2 is \n");
while(fgets(a,strlen(a)+1,f2)!=NULL)
{
fputs(a,f3);
printf("%s",a);
}
fclose(f2);
fclose(f3);
f3=fopen("student2.txt","r");
printf("\n the content of file3 is \n");
while (fgets (a, strlen(a) + 1,f3)!=NULL)
printf("%s",a);
getch();
}
POINTERS:
A pointer is a variable, which represents the location (not the
value) of a data item, such as a variable or an array element.
Advantages:
1. pointers increase the execution speed of the program.
2. pointers reduce the length and complexity of a program.
3. pointers enable us to access a variable that is defined outside
the pointers are used to pass information back and forth
between a function and its reference point.
Pointer declaration:
All pointer variables must be declared before it is used in the
program like other variable.
The general form is:
Data-type * variable;
Assigning the address of the variable to pointer variable:
The address of the variables can be got with the help of the
address operator &. The operator & immediately preceding a
variable returns the address of the variable associated with it.
Ex:
int *a;
int x;
a = &x;
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b=10, *ptr;
clrscr();
ptr=&a;
printf("\n initial values a=%d &b=%d",a,b);
b=*ptr;
printf("\n changed values a=%d &b=%d",a,b);
printf("\n value of ptr is %d", ptr);
getch();
}
Pointers and Array:
An array is actually a pointer to its 0th element. Dereferencing
the array name will give the value stored in the 0th element of the
array.
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,a[25],*ptr;
clrscr();
printf("Enter the number of elements:");
scanf("%d", &n);
printf("Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
*ptr=a[0];
for(i=0;i<n;i++)
if(a[i]>*ptr)
*ptr=a[i];
printf("The biggest element in the array is %d",*ptr);
getch();
}
Pointer to Function:
A pointer to a function contains the address of the funcntion
in memory. A function, like a variable has an address location in
the memory, therefore it is possible to declare a pointer to a
function,
Ex:
#include<stdio.h>
#include<conio.h>
int sum(int (*) (int),int);
int square(int);
void main()
{
int num;
clrscr();
printf("Enter any integer:");
scanf("%d", &num);
printf("The sum of squares of first %d numbers is %d", num,
sum(square, num));
}
int sum(int (*fptr)(), int n)
{
int add, i;
for(i=1;i<=n;i++)
add += (*fptr) (i);
return 0;
}
int square (int i)
{
getch();
return(i*i);
}