1 INTERNAL COMMANDS CLS (Clear Screen) CLS Clears (erases) the screen. COPYCOPY [/Y|-Y] [/A][/B] [d:][path]filename [/A][/B] [d:][path][filename] [/V] or COPY [/Y|-Y][/A][/B] [d:][path]filename+[d:][path]filename[. ..][d:][path][filename] [/V] Copies and appends files. DATEDATE mm-dd-yyDisplays and/or se ts the system date . DEL (ERASE) DEL (ERASE) [d:][path]filename [/P] Deletes (erases) files from disk. CHDIR CHDIR (CD) [d:]path CHDIR (CD)[..] Displays working (current) directory and/or changes to a different directory. DIR DIR [d:][path][filename] [/A:(attributes)] [/O:(order)] [/B][/C][/CH][/L][/S][/P][/W] Displays directory of files and directories stored on disk. DOSDOS=[high|low],[umb|noumb] Used in the CONFIG.SYS file to specify the memory location for DOS. It is used to load DOS into the upper memory area and to specify whether or not the upper memory blocks will be used.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
„C’ seems a strange name for a programming language. But thisstrange sounding language is one of the most popular computerlanguages today. „C‟ was an offspring of the Basic CombinedProgramming Language (BCPL) developed by Martin Richards in 1967.In 1970 a system engineer called Khen Thomson modified BCPL and forthe modified version he has given the name „B‟, the first letter of BCPLone the UNIX operating system. Around 1972 another System engineercalled Dennis Ritchie modified BCPL and he has given the name as „C’,the second letter of BCPL.
C language is not a high level language and not a low levellanguage. It is a middle level language. It doesn't mean it is supportingfew of high and low level features. The real meaning is it supports
complete features of high level and low level. So using C languageprogrammer can develop system level and application levelprogramming.
Importance of ‘C’:
The increasing popularity of „C‟ is probably due to its many desirable qualities. It is a robust language that‟s richest of built-infunctions and operators can be used to write any complex program. TheC compiler combines the capabilities of an assembly language with
features of high-level language and therefore it is well suited for writing both system software and application software.
Programs written in „C‟ an efficient and fast. This is due to its variety of data types and powerful operators. It is many times fasterthan BASIC. For example, a program to increment a variable from 0 to15,000 takes about one second in C, while it takes more than 50 secondsin on compiler BASIC.
There are only 32 keywords; several standard functions areavailable which can be used for developed programs.
„C‟ is highly portable. This means that C programs written for onecomputer can be run on another with little or no modification.Portability is important if we plan to use a new computer with adifferent operating system.
Desirable Program Characteristics:These characteristics apply to programs that are written in any
programming language, not just C. They can provide us with a useful setof guidelines later in this book, when we start writing our own Cprograms.
1.Integrity: - This refers to the accuracy of the calculations. It should be clear that all other program enhancements would be meaningless if the calculations were not carried out correctly. Thus, the integrity of thecalculations is an absolute necessity in any computer program.2.Clarity:- It refers to the overall readability of the program, withparticular emphasize on its underlying logic. If a program is clearly
written, it should be possible for another programmer to follow theprogram logic without undue effort. I should also be possible for theoriginal author to follow his or her own program after being away from
the program for an extended period of time. One of the objectives in thedesign of C is the development of clear, readable programs through anorderly and disciplined approach to programming.
3.Simplicity:- The clarity and accuracy of a program are usually enhanced by keeping things as simple as possible, consistent with theoverall program objectives. In fact, it may be desirable to sacrifice acertain amount of computational efficiency in order to maintain arelatively simple, straightforward program structure.
4.Efficiency:- It is concerned with execution speed and efficientmemory utilization. These are generally important goals, though they should not be obtained at the expense of clarity or simplicity. Many complex programs require a tradeoff between these characteristics. Insuch situations, experience and common sense are key factors.
5.Modularity: - Many programs can be broken down into a series of identifiable subtasks. It is good programming practice to implementeach of these subtasks as a program module. In C, such modules are
written as functions. The use of a modular programming structure
enhances the accuracy and clarity of a program, and it facilitatesprogram alterations.
6.Generality: - Usually we will want a program to be as general aspossible, within reasonable limits. For example, we may design aprogram to read in the values of certain key parameters rather thanplacing fixed values into the program. As a rule, a considerable amountof generality can be obtained with very little additional programmingeffort.
In C program comments are used for documentation purpose. When used carefully, comments can be very helpful clarifying what thecomplete program is about, what a specific group of statements is meantto accomplish, or what one line is intended to do. Comments can betaken between /* and */. It may be anywhere in the program. If acomment is too long to be contained on one line, it can be continuedacross two or more lines as shown below. /*this comment is to show a comment that extends over two lines*/. Preprocessor directivesare executed before the C source code passes through compiler. Mostly used preprocessor directives are #include and #define.
It may be possible that some variables used in many functions, soit is necessary to declare them globally. Those variables are called asglobal variables. Every C program has one more function.DATA TYPES:
In C language has three types of data types available. They are:1. Fundamental or Basic data types2. Derived data types3. Abstracted data types (User defined data types)
Fundamental Data Types:Integer Constant:- An integer constant reference to a sequence of digits that may or may not be with a minus(-) sign.
Ex:- 1001, 100, -9, 1
Spaces, Commas and non digit characters are not permitted. Theinteger constant occupies 2 bytes in memory.
Floating Point Constant: - Such as distance, heights, temperature,price etc.. These quantities are represented by numbers containingfractional like 10.943 such no‟s called floating points or real constants.This constant occupies 4 bytes in memory. Size of precision part is 6digits.
Ex :- 0.009, -78.543
Long Integer Constant:- This constant occupies 4 bytes in memory and the size range is -214,74,83,648 to +214,74,83,647.
Double Constant:- This constant occupies 8 byes in memory and sizerange of precision part is 14 digits.
Long Double Constant:- This constant occupies 10 bytes (80 bits) inmemory.
Single Character Constant:- The single character constant is a singlecharacter enclosed with in a pair of single quote marks. This constantoccupies 8 bits (1 byte) in memory.Ex:- „a‟ , „5‟, „*‟
String Constant:- The string constant is a group of characters thatenclosed in double quotes (“ “) . The characters may be letters, no andspecial characters.Ex:- “ICT” , “C Language” , “06-10-2002”
Data Type Name Declaration symbol Data Range LimitsSingle Character char %c -128 to 127Unsigned Character unsigned char %c 0 to 255Enumarated enum - -32,768 to 32,767Integer Constant int, short int %d -32,768 to 32,767
Unsigned Integer unsigned int %u 0 to 65,535Long Integer Constant long, Long int %ld -214,74,83,648 to214,74,83,647Unsigned Long Integer unsigned long int %ul 0 to429,49,67,295Floating Point Constant float %f 3.4 X 10-38 to 3.4 X 1038 Double Point Constant double %lf 1.7 X 10-308 to 1.7 X10308Long Double Point long double %Lf 3.4 X 10-4932 to 1.1 X104932
Constants: A constant is an entity whose value does not change during
program execution. Constants are of five different types: integer,floating point, character, string and enumeration.
Reserved Words/ Key Words:
Keywords have predefined meaning and cannot be changed by theuser. These words should not be used as identifier/variables inprograms. The following are c reserved words:
auto double int struct break else long switchcase enum register typedef char extern return unionconst float short unsignedcontinue for signed void
Variables/Identifiers: Variable is a name that can be used to store values. These
variables can take different values but one at a time. These values can be changed during execution. The following are rules while naming a variable:
1. The only characters that are allowed are alphabets, digits andunderscore.
2. The first character must be an alphabet or underscore.3. There is no limit for the length of an identifier, but some "C"
compliers restrict the length of an identifier to be 8 characters. ANSI recognizes 31 characters.
4. Reserved words cannot be an identifier.5. Lower case or upper case letters are significant.
Declaration of Variables: After designing suitable variable names, we must declare them to
the compiler, Declaration does two things.
1. It tells the compiler what the variable name is2. It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used inthe program.
Syntax:
<type> v1,v2,v3, . . . ,vn ; v1,v2,v3, . . . ,vn are the name of variables.
Ex:int count;long total;int a,b,c;
Input and Output Functions:Functions are subprograms written to do tasks of a big program.
C language is a function oriented language. Many tasks are donethrough functions only. Input/output operations enable thecommunications between the program and the user. In many of thecomputer languages the input/output operations are done throughstatements. But in C language Input and output operations are donethrough functions.
Input Functions:Input data can be entered into the memory from a standard input
device. C provides the scanf() function for entering input data. Thisfunction accepts all types of data as int(numeric, character, string). Thegeneral form of scanf() is given below.
scanf("Conversion specification", variable1, variable2...variable);This function should have at least two parameters. First parameter iscontrol string which is conversion specification character. It should be
within double quotes. This conversion specification character may beone or more, it depends on the number of variables. The otherparameters are variable names. In the scanf() at least one variablename should be present. Each variable name must be preceded by anampersand (&). This gives the starting address of the variable name inmemory.
Note:- Comments are not allowed in scanf(). Conversion specificationsare used to provide the type and size of the data. Each conversionspecification must begin with a percent sign(%).
Syntax: -scanf(“%d”,&a); scanf(“%s”,name);
Output Functions:
This printf() function allows to display all types of data. At thetime of program execution, printf() interprets and display values given.The general form of printf() is given below.
printf("Conversion specs with comments", var1,var2..var n);
Example: Program to find area of a triangle giving its sides.
#include<stdio.h>
main(){
int s1,s2,s3,s,area;clrscr();printf("Enter sides of the triangle\n");scanf("%d%d%d",&s1,&s2,&s3);s=(s1+s2+s3)/3;area=sqrt(s*(s-s1)*(s-s2)*(s-s3));printf("The area fo the triangle %d\n",area);getch();
Escape Sequences (Control Characters):The meaning of these characters is interpreted at the time of
execution. These are also known as Execution Characters. Backslash (\)is considered an 'escape' character, it causes an escape from the normalinterpretation of a string.
Escape Sequence Meaning Result \a Bell(alert) Produce a beep sound for alert.
\b Backspace Moves the cursor to the previousposition of the current line.
\n New line Moves the cursor to the next line.\r Carriage return Moves the cursor to the beginning
of the current line.\t Horizontal Tab Moves the cursor to next horizontal
tab position.\v Vertical tab Moves the cursor to next vertical
tab position.\0 Null Null
\‟ Single Quote Present a single quote with backslash(\).
\” Double Quote Present a double quote with backslash(\).
\\ Backslash Present a character with backslash(\).
An Operator is a symbol that tells the computer to performmathematical or logical manipulation. „C‟ Operators can be classifiedinto a number of categories. They include:
1. Arithmetic Operators2. Relational Operators3. Logical Operators4. Assignment Operators5. Increment and decrement Operators6. Conditional Operators7. Bit wise Operators8. Special Operators
1. Arithmetic Operators:There are five arithmetic operators in C. They are:
Operator Meaning+ Addition or unary plus- Subtraction or unary minus* Multiplication/ Division% modulo division
These Operators are three types as:
Integer Arithmetic: An Arithmetic Operation involving only integeroperands is called Integer arithmetic.
Ex: 14 + 2 = 1612/3 = 414%3 = 2
Real Arithmetic: An Arithmetic Operation involving only real
operands is called real arithmetic.
Ex: 6.0/7.0 = 0.8571431.0/3.0 = 0.333333
Mixed-Mode Arithmetic: When one of the operand is real and theother integer is mixed-mode arithmetic.
5.Increment and Decrement Operators: We use the increment and Decrement Statements in “For” and
“While” loops. The following are increment and Decrement Operators.+ + and - -
The operator + + adds 1 to the Operand.The Operator - - subtracts from the Operandm++ or ++m is equal to m=m+1 or m+=1m- - or - -m is equal to m=m-1 or m- =1
6.Conditional Operators:Conditional operator is a pair of “ ?: ” is available in „C‟ to
construct conditional expressions of the form.exp1?exp 2:exp 3;
Where exp1, exp2 and exp3 are expressions.exp1 is evaluated first if it is true then the exp2 is evaluated and
becomes the value of the exp. If exp1 is false, exp3 is evaluated and its value becomes the value of exp.
Note: That only one of the exp either exp2 or exp3 is evaluated.Ex: a=10 b=15
X=(a>b)?a:b;In this example, x will be assigned the value of b.
7.Bit wise Operators: The following are Bit wise Operators.Operator Meaning
& Bit Wise AND| Bit Wise OR ^ Bit Wise Exclusive OR << Shift Left>> Shift Right~ 1‟s Compliment
Special Operators:
Some special Operators such as comma Operators, size of operator and pointer Operators (& and *)
Comma operator: For Example, value = (a=15,b=9,a+b);
From the example first assign 15 to a, 9 to b finally assign 24 to value.
Sizeof operator: The sizeof writes the no. Of bytes the operandoccupies.
Ex: M = size of (SUM); Pointer operator: Pointer operator (& and *)
With the help of & operator, we can determine the address of
variable. Ex: & quantity * Tells the variable name is a pointer variable. Ex: *name
Aim: Program to convert Fahrenheit into Celsius Using printf andscanf functions
Theory:Input Functions:
Input data can be entered into the memory from a standard inputdevice. C provides the scanf() function for entering input data. Thisfunction accepts all types of data as int(numeric, character, string). Thegeneral form of scanf() is given below.
scanf("Conversion specification", variable1, variable2...variable);This function should have at least two parameters. First parameter iscontrol string which is conversion specification character. It should be
within double quotes. This conversion specification character may beone or more, it depends on the number of variables. The otherparameters are variable names. In the scanf() at least one variable
name should be present. Each variable name must be preceded by anampersand (&). This gives the starting address of the variable name inmemory.
Output Functions:This printf() function allows to display all types of data. At the
time of program execution, printf() interprets and display values given.The general form of printf() is given below.
printf("Conversion specs with comments", var1,var2..var n);
Source code:#include<stdio.h>main(){float cel, fahr;printf(“Enter temperature in fahr:”); scanf(“%f”,&fahr); cel=(fahr-32)*5 / 9;printf(“temp in celsius is %f”, cel); }
Output:Enter temperature in fahr:93.5temp in celsius is 34.16
Aim : Program whether the given character is vowel or not using
switch statement
Theory:
• It is multi-way branch statement.• It is useful when there is a possibility to make a choice from a
number of options.• It evaluates the expression and then looks for its value in the case
constants.• If the value matches with case constant, that particular case
statements are executed.• If not the default is executed.• Here switch, case, default are keywords.• Upon encountering the break statement, switch statement is
terminated and goes out of the switch block.Source code:
#include<stdio.h>main(){char ch;printf(“Enter any character\n”); ch = getchar();switch(ch)
{case „a‟ : case „e‟ : case „i‟ : case „o‟: case „u‟:
Aim: program to find whether the given number is even or odd usingunconditional statement(goto)Theory:
• This control is transferred without checking any condition.• In C, it is done by using goto Statement.• goto statement passes the control to anywhere in the program.• It requires a label in order to identify the place where the branch
is to be made.• Label may be any valid identifier and must be followed by colon
(:)Syntax :
goto label;
main(){
statement ;. . .goto xyz;. . .
xyz: statement;. . .
}
Source Code:
#include<stdio.h>main(){int num;printf(“Enter any number\n”); scanf(“%d”, &num); if(num%2 == 0)goto xy;
Aim: Program to search an element by linear search using single
dimensional array.
Theory:
Array is a collection of data elements of the same type.
Whose elements are specified by one subscript that array is called
One-dimensional array.
General form of one-dimensional array:datatype variable_name [size];
Source code:
#include<stdio.h>
main(){
int a[80],n,i,key,k=1;clrscr();printf("Enter the value of n\n");scanf("%d",&n);printf("Enter the elements\n");for(i=1;i<=n;i++)scanf("%d",&a[i]);printf("Enter the key element = ");
Aim: Program to find the addition of two matrices using twodimensional arrays.
Theory: An array whose elements are specified by two subscripts is called
a Two dimensional array. General form of Two-dimensional array
datatype variable_name [size] [size];
Source code:
#include<stdio.h>
main(){int a[80][80],b[80][80],c[80][80],m,n,i,j;clrscr();printf("Enter the row and coloumn numbers\n ");scanf("%d%d",&m,&n);printf("Enter the elements of matrix a\n");for(i=0;i<m;i++){
for(j=0;j<n;j++)
{ scanf("%d",&a[i][j]);}
printf("\n");}printf("Enter the elements of thematrix b\n");for(i=0;i<m;i++){
Aim: Write program to find the sum of elements in an array using
initialization of array.
Theory:
Array elements can be initialized within their declarationstatements in the same manner as variables.
The initialization elements must be included with in braces { }.
General form of initialization of array Datatype variable name [size]={list of values};
The values in the list are separated by commas. Example:
int a[5]={2,3,5,6,7};
Source Code:#include<stdio.h>main(){
int n,i,sum=0,a[5]={5,15,9,4,1};clrscr();for(i=0;i<5;i++)
sum=sum+a[i];
printf("The sum of the elements in the list= %d",sum);getch();
} Aim: Program for the static variable
Theory:
It is, like automatic variable, local to functions is which it isdefined.Unlike automatic variables static variable retains valuesthroughout the life of the program, i.e. if a function is exited andthen re-entered at a later time the static variables defined within
the function will retain their former values. Thus this feature of static variables allows functions to retain
information permanently through out the execution of theprogram.
Static variable is declared by using thekeyword static.
Source code:# include<stdio.h>long int Fibonacci (int count )main(){int i, m=20;for (i =1 ; i < m ; ++i)printf( “%ld\t”,fibonacci(i)); }long int Fibonacci (int count ){static long int f1=1, f2=1 ;long int f ;
f = (count < 3 ) ? 1 : f1 + f2 ;f2 = f1f1= f ;return (f ) ;}Output:
Types of user defined functions• Functions with no arguments and no return values.• Functions with arguments but no return values.• Functions with arguments and return values.
Functions with no arguments and no return values.• As the function fun() has no arguments, main() cannot send any
data to fun().• Since fun() has no return statement it cannot return any value to
main().Syntax:
main(){
----fun()
---}fun(){---
}
Source code:#include<stdio.h>
Void fun();
main(){fun();}
Fun(){int f1=0,f2=1,f3,n,i;clrscr();printf("Enter the value of n\n");scanf("%d",&n);
printf("The fibonacci series is\n");printf("%d\n%d\n",f1,f2);for(i=0;i<n;i++){
Aim: Functions with arguments and return valuesTheory:
• Since functions have parameters, the calling function can senddata to the called function.
• The called function can return the resultant value to callingfunction with the use of return statement.Source code:#include<stdio.h>#include<conio.h>int sum(int,int);main()
{int x,y,z;clrscr();printf("Enter first number");scanf("%d",&x);printf("Enter second number");scanf("%",&y);z=sum(x,y);printf("Sum of two nos is %d",z);
}
int sum(int a,int b){
int sum=0;sum=a+b;return (sum);
}
Output:Enter the first number : 6Enter the second number : 9
Aim: write a factorial of the given number using recursionfunction methodsTheory :
• A function is recursive if a statement in the body of the functioncalls itself.
• It is the process of defining something in terms of itself.• Recursive function is 1) Clear 2) Short 3)Contains simple
programs.• When a recursive program is executed the recursive function calls
are not executed immediately. Rather, they are placed on a stack until the condition that terminates the recursion is encountered.The function calls are then executed in reverse order, as they arepopped off the stack.
Source code:
#include<stdio.h>
int fact(int);
main(){int n;
scanf(“%d”,&n); printf(“factorial of number %d is %d\n”,n,fact(n)); }int fact (int x){int f =1;if(x==1)
Aim: Write a program swapping two numbers using pointers.
Theory :• A pointer is a variable that holds the memory address of another
variable.• Example
• „x‟ is a variable with value 10 and is stored at location 1000 and y is another variable which stores the address 1000 at location
1020, since variable y holds the address of variable x we say that y points to x.
Uses of Pointers To return more than one value from a function. To pass arrays and 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 create complex data structures, such as linked lists and binary
trees, where one data structure must contain references toanother data structure.
To communicate information about memory. Pointers are used for saving memory. With pointers, data manipulation is done with addresses, so the
execution time is less. Pointers provide us dynamic memory allocation.
Address and De-referencing operators C provides two unary operators „&‟ and „*‟ for manipulating data
using pointers. „&‟ is known as the addressing operator. „*‟ is k nown as the De-referencing operator or Indirection operator „&‟ is read as “address off”. When used with a variable, „&‟ returns the address of the variable.
Example:a=&count;
The address of the variable count is placed in a. „*‟ is read as “the value at address” When used with a variable, „*‟ returns the value of the variable Example :-
Declaring a pointerSyntax :Type-name *pointer name;
Example :int *ptr;
• means that ptr is a pointer variable.• ptr can be used to point to variables of type int.
Declaring a variable• The operator * does not distribute to all variable names in a
declaration.Example :
int *p1,p2;
p1 is a pointer variable, which can point to integer data.p2 is an integer variable.
Pointer declaration• Each pointer must be declared with the * prefixed to the name.
Example :int *p1,*p2;
declares p1, p2 as pointer variables that can point to integer data.Pointer assignment
• A pointer variable can be used on the right hand side of anassignment statement to assign its value to another pointer.
Example :
#include<stdio.h>main(){
int a,*p1,*p2;p1=&a;p2=p1;printf(“%d%d”,p1,p2);}
Initializing a pointer• Pointers should be initialized when they are declared OR in an
assignment statement.• A pointer may be initialized to 0, null or an address.• A pointer with the value null points to nothing.• Initializing a pointer to 0 is same as initializing it to null.
Example:int p1,*ptr=&p1;
Here we declared two variables p1 and a pointer variable ptr. Pointer variable ptr is initialized with the address of p1.
Aim: Program to interchange elements of character array usingpointers
Theory :Pointers and Arrays
An array of pointers is an array that contains pointers as it‟selements.
Pointer arrays give a convenient method for storing strings. As strings are character arrays, each array element is a character-
type pointer that points to a separate string. Suppose the following strings are to be stored in a character-type
array.Bombay DelhiMadras
KolkataHyderabad
The above strings can be stored in a two dimensional character-type array declared as
char city[5][12]; Note that city contains 5 rows to accommodate the five strings. Each row must be large enough to store at least 12 characters as
well as the null character(„\0‟) at the end. It is not necessary to include the maximum string size with in the
array declaration. A specified amount of memory will be allocated for each string
later in the program usingcity[i]=(char *)malloc(12 * size of(char));
Reasons for using array of pointers to store strings are Efficient use of available memory. Manipulation of strings is easier. Long strings can be stored with minimum effort.
Aim: Program using program to concatenation of two strings usingpointers.
Theory :Dynamic memory allocation can be done using the following functions
The malloc() function The calloc() function The free() function The realloc() function
Sizeof() OperatorBefore describing the above functions let us first understand the sizeof operator.
It is a unary operator that is used to obtain the size of a data typeor data object.
It is not a library function but a keyword which returns the size of the operand in bytes.
Example:sizeof(char) is 1sizeof(int) is 2sizeof(float) is 4
malloc() function This is used to allocate a contiguous block of memory in bytes and
gives the starting address to a pointer variable.Syntax:
ptr=(data-type *) malloc (size); where data-type says the type of pointer returned by malloc() and
size specifies the required size of memory in bytes.Example:
ptr=(int *) malloc(10); On execution of this 10 bytes of memory space is allocated and the
starting address of the first byte is assigned to the pointer ptr of type int.
Example:ptr= (int *) malloc (10*size of(int));
This allocates memory space 10 times the size of an integer(i.e10*2=20 bytes) and the starting address of the first byte isassigned to the pointer ptr of type integer.
If sufficient memory is available, malloc() allocates memory and
returns the starting address otherwise it returns null.
Storage space allocated dynamically has no name and therefore
its contents can be accessed only through a pointer.
This function is used to allocate multiple blocks of contiguous
memory in bytes. All blocks are of same size.
Syntax:ptr=(data-type *) calloc(n,size);
where ptr is a pointer variable already defined. data-type is the type of the pointer returned by calloc. „n‟ is the number of memory blocks. „size‟ is the required size of each block.
Example:
ptr=(int *) calloc(5,2); This allocates 5 memory blocks of size 2 bytes and returns the
starting address of the first byte to the pointer variable ptr. calloc() function is generally used for allocating memory space for
arrays and structures.free() function This is used to free (release or de allocate) the block of unused or
already used memory.Syntax:
free(ptr); Where ptr is a pointer variable that contains base address of the
memory block,created by malloc() or calloc().Example:ptr= (int *)malloc((10);free(ptr); The first statement allocates memory space of 10 bytes and
returns the starting address to pointer variable ptr. The second statement frees the allocated memory.realloc() function This function is used to increase or decrease the size of memory
already allocated by using malloc() or calloc() function.Syntax:new-ptr= realloc(old-ptr,new-size); where new-ptr is a pointer variable already defined. old-ptr is the pointer variable used in malloc() or calloc(). new-size is the size of new memory needed.Example:
y=(int *) malloc(10);x=realloc(y,30); First statement allocates memory size of 10 bytes and returns the
starting address of the memory to pointer variable y. Second statement reallocates already allocated space to 30 bytes.
Theory :Pointer we know is a variable which contains address of another
variable.Now this variable itself could be another pointer.These we now have a pointer which contains another pointer‟s address.Source code:main (){int i = 3 ;int * j ;int * * k ;
j = & i ;k = & j ;printf (“\n address of i = % \d”, & i ); printf (“\n address of i = % \d”, j ); printf (“\n address of i = % \d”, * k ); printf (“\n address of j = % \d”, & j ); printf (“\n address of j = % \d”, k ); printf (“\n address of k = % \d”, & k ); printf (“\n address of k = % \d”, &k ); }
clrscr();printf("\nEnter the structer elements");printf("\nEnter the name of the student: ");scanf("%s",a.name);printf("Enter the Father's name: ");scanf("%s",a.fname);printf("Enter the Street: ");scanf("%s",a.street);printf("Enter House Number: ");scanf("%d",&a.hno);
printf("Enter Town: ");scanf("%s",a.town);clrscr();printf("\n\n\n\t\t\tNAME : %s",a.name);printf("\n\t\t\tFATHER'S NAME : %s",a.fname);printf("\n\t\t\tHOUSE NUMBER : %d",a.hno);printf("\n\t\t\tSTREET : %s",a.street);printf("\n\t\t\tTOWN : %s",a.town);getch();
}
Output:Enter the structure elementsEnter the name of the student: srinuEnter the father name: narasimharaoEnter the street: gollapalemEnter house Number: 11-9-66/1Enter Town : chiralaName : srinuFather‟s name: narasimharao House number: 11-9-66/1
Student st ={“10103-CM-001”,”srinu”,30,‟M‟,5.3,70}; clrscr();printf("\nEnter student details are\n");printf("\n\n\n\t\t\tPin no : %s",a.name);printf("\n\t\t\t NAME : %s",a.fname);printf("\n\t\t\t age : %d",a.hno);printf("\n\t\t\t sex : %c",a.hno);printf("\n\t\t\tHeight : %s",a.street);printf("\n\t\t\tWeight : %s",a.town);getch();
Aim: write a program using array of structure to print the person detailsTheory: Arrays of Structures
arrays of structures are very powerful programming tools.
structure definition can be tailored to fit the data your programneeds to work with. Usually a program needs to work with morethan one instance of the data. For example, in a program tomaintain a list of phone numbers, you can define a structure tohold each person's name and number:
A phone list must hold many entries, however, so a singleinstance of the entry structure isn't of much use. What you need isan array of structures of type entry. After the structure has beendefined, you can declare an array as follows:
struct entry list[1000];This statement declares an array named list that contains 1,000elements. Each element is a structure of type entry and is identified by subscript like other array element types. Each of these structures hasthree elements, each of which is an array of type char.Source code:
Aim : Write a program to print the person details using nextedstructure
Theory: Structure in a structure is called nested structure Inner structure must be defined first Outer structure is defined next Inner structure members can be accessed
Outer structure name . Inner structure name . member Complex data types can be created
Source code:#include<stdio.h>struct dob{
int mm,yy,dd;} d;struct stud{
char name[20],qfn[20],fname[20];float tpn;
struct dob d;}per;main(){
int i;clrscr();printf("\nENTER DETAILS OF A PERSON\n\n");printf("Enter name : ");scanf("%s",per.name);printf("Enter Father's name: ");scanf("%s",per.fname);printf("Enter Qualification: ");scanf("%s",per.qfn);printf("\nEnter DATE OF BIRTH\n");
clrscr();printf("\n\n\t\t\t DETAILS OF PERSON \n");for(i=0;i<80;i++) printf("|");printf("\n\t\t\tNAME : %s",per.name);printf("\n\t\t\tFATHER'S NAME : %s",per.fname);printf("\n\t\t\tQUALIFICATION : %s",per.qfn);
printf("\n\t\t\tDATE OF BIRTH : %2d - %2d -%4d",per.d.dd,per.d.mm,per.d.yy);
Passing entire structure to a function. We can pass int, float, char etc., variables to a function as
its arguments. A structure variable can also be passed to a function as its
argument.
Passing address of the structure to a function. Starting addresses of variables can be passed to a function. Starting address of the structure variable can also be passed
to a function.
Structure can be manipulated using pointer.#include <stdio.h>Struct book {Char title[20];Char author[20];Int pages;Float price;}
Void main()
{Struct book b={“c”,”shanmukh”,500,250.4); Struct book *p;P= &b;Printf(“ %s\t%s\t%d\t%f”,p->title.p->author,p->pages,p->price);}
Aim : Write a program example for the pointer to a structure.
Theory: Pointer variable that can hold stating address of a structure
variableSyntax:
struct tagname *pointervariable(s);
Address of the member – &pointervariable->member
Content of the member – pointer variable->member
Example:struct sample
{char a;int b;float c;};
struct sample s={„A‟,100,5.5}; struct sample *p;/*p is a pointer to structure*/ p=&s; /*starting address of s is stored in p*/ assume 1000 is starting address of s &p->a gives address of a i.e 1000 &p->b gives address of b i.e 1001 &p->c gives address of c i.e 1003 p->a gives content of a i.e A p->b gives content of b i.e 100 p->c gives content of c i.e 5.5
Source code:#include <stdio.h>Struct book {Char title[20];Char author[20];Int pages;Float price;}
Void main(){Struct book b={“c”,”shanmukh”,500,250.4); Struct book *p;P= &b;Printf(“ %s\t%s\t%d\t%f”,p->title.p->author,p->pages,p->price);
Unions, like structure contain members, whose individual datatypes may vary. This is a is major distinction between them interms of storage .In structures each member has its own storagelocation, where as all the members of a union use the samelocation.Like structures, a union can be declared using thekeyword union is follows:
union item{int m;float x;char c;} code;This declares a variable code of type union item.The union contains item members, each with a different date type.However, we can use only one of them at a time.This is due to the fact that only one location is allocated for a union
variable, irrespective of its size Source code:# include <stdio.h>main( )
{union{int one;char two;} val;
val. one = 300;printf(“val. one = %d \n”, val. one); printf(“val. two = %d \n”, val. two); }
FilesData FilesData Files are to store data on the memory device permanently and toaccess
whenever is required.There are two types of data files1 Stream Oriented data files2 System Oriented data filesStream oriented data files are either text files or unformatted files.System oriented data files are more closely related to computer‟soperating system and more complicated to work with. In this session wego through stream oriented data files.Opening and Closing data files
The first step is to create a buffer area where information is storedtemporarily before passing to computer memory. It is done by
writingFile *fp;
Here fp is the pointer variable to indicate the beginning of the buffer area andcalled stream pointer .
The next step is to open a data file specifying the type i.e. readonly file , write only file , read /write file. This is done by using thelibrary function fopen
syntaxfp=fopen(filename,filetype)the filetype can be
1. „r‟ ( to open an existing file for reading only) 2. „w‟ ( to open a new file for writing only. If file with filename
exists,it will be destroyed and a new file is created in its place)3. „a‟ ( to open an existing file for appending. If the file name does
notexist a new file with that file name will be created)
4. „r+‟ ( to open an existing file for both reading and writing) 5. „w+‟ ( to open a new file for reading and writing. If the file exists
with that name, it will be destroyed and a new one will be created with that name)
6. „a+‟ ( to open an existing file for reading and writing. If the filedoesnot exist a new file will be created).
Fprintf:For writing formatted data to a file we use the function fprintf.Syntax : Fprintf(fp,”conversion string”, value); Ex: To write the name “rajan” to the file named „st.dat‟
Aim:To write a set of numbers to a file.Source code:#include<stdio.h>main(){file *fp;Int n; float xfp=fopen(“num.dat”,‟w‟); Printf(“Input the number of numbers”); Scanf(“%d”,&n); For(i=1;i<=n;++i){Scanf(“%d”,&x); Fprintf(fp,”%f \n”,x); }
Aim: program to 'getc' and putc' functions.Theory:
THE GETC AND PUTC FUNCTIONS :The simplest file i/o functions are fgetc and fputc. These are used tohandle one character at a time. Assume that a file is opened with mode
w and file point fpt. Then, the statementfputc(c,fpt);
Writes the character contained in the character variable c to the fileassociated with FILE pointer fpt. Similarly getc is used to read characterfrom a file that has been opened in read mode. For example, thestatementC = fgetc(fp2);
Would read character from file whose file pointer is fp2. the file pointermoves by one character position for every operation of getc and putc.The getc will have been reached. Therefore, the reading should be
terminated when EOF is encountered. Source code:
#include<stdio.h>main(){
FILE *fp;char c;clrscr();fp=fopen("TEXT","w");
printf("Enter text - Terminate with ctrl+z\n"); while((c=getchar())!=EOF){
putc(c,fp);}fclose(fp);printf("\nDisplaying text from file......\n\n");fp=fopen("TEXT","r");
Aim : For reading formatted data from a file we use the function fscanf Theory:Processing formatted data FileTo read formatted data from a file we have to follow all the various stepsthatdiscussed above. The file should be opened with read mode. To open theexistingfile „st.dat‟ write the following syntax file *fp;fp=fopen(“st.dat”, „r+‟); Source code:Tpedef struct
Aim: Write a program to write biodata to a file using processingunformatted data filesTheory:
Processing Unformatted data filesFor reading and writing unformatted data to files we use the library functions freadand fwrite in the place of fscanf and fprintf.The syntax for writing data to file „st.dat‟ with stream pointer fp is Fwrite(&student, sizeof(record),1,fp);Here student is the structure of type biodata
Source code:To write biodata to a fileTpedef struct
Aim :Write a program to read biodata from the file.Source code:Tpedef struct{Int day;Int month;Int year;}date;Typedef Struct{char name(30);char place(30);int age;
date birthdate;}biodata;53Main(){File *fp;fp=fopen(“st.dat”,‟a+‟)
RANDOM ACCESS TO FILES :There are occasions however, when we are interested in accessing only aparticular part of a file and not in reading the other parts. This can beachieved with the help of the function fseek, ftell and rewind available inthe library.ftell :ftell take a file pointer and returns a number of type long thatcorresponds to the current portion. This function is useful in saving thecurrent position of a file, which can be used in the program. It takes thefollowing form.
N =ftell(fp);N would give the relative offset (n bytes) of the current position. Thismeans that n bytes have already bean read.
rewind :rewind takes a file pointer and resets the position to the start of the file.For example the statement :
Rewind(fp);N=ftell(fp);
Would assign to fp because the file position has been set to the start of the file by rewind. This function helps us in reading a file more thanonce. Without having to close and open the file.fseek :fseek function is used to move the position to a desired location within
the file. It takes the following form.Fseek(fpt, offset, position)Fpt is a pointer to file concerned. Offset is a number of variable of typelong and position is an integer number. The offset specifies the numberof bytes(position) to be moved from the location specified by position.The position can take one of the following three values :
0 beginning of file1 current position2 end of file
The offset may be positive, meaning move forward and negative,meaning move backwards.
When the operation is successful, fseek returns a zero. If we attempt tomove beyond the file boundaries and error occurs and fseek returns.
Aim : Write a program on Random access file conceptSource code:#include<stdio.h>#include<conio.h>#include<stdlib.h>struct emprecord{char name[30];int age;float sal;}emp;
void main(){
int n;FILE *fp;fp=fopen("employee.dat","rb");if (fp==NULL){printf("/n error in opening file");exit(1);}printf("enter the record no to be read");scanf("%d",&n);