Transcript
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 1/811
INTERNAL COMMANDS
CLS (Clear Screen)
CLS
Clears (erases) the screen.
COPY
COPY [/Y|-Y] [/A][/B] [d:][path]filename [/A][/B] [d:][path][filename][/V]orCOPY [/Y|-Y][/A][/B][d:][path]filename+[d:][path]filename[...][d:][path][filename] [/V]
Copies and appends files.
DATE
DATE mm-dd-yy
Displays and/or sets the system date.
DEL (ERASE)
DEL (ERASE) [d:][path]filename [/P]
Deletes (erases) files from disk.
CHDIR
CHDIR (CD) [d:]pathCHDIR (CD)[..]
Displays working (current) directory and/or changes to a differentdirectory.
DIRDIR [d:][path][filename] [/A:(attributes)] [/O:(order)][/B][/C][/CH][/L][/S][/P][/W]
Displays directory of files and directories stored on disk.
DOS
DOS=[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 whetheror not the upper memory blocks will be used.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 2/812
MKDIR( MD)
MKDIR (MD) [d:]path
Creates a new subdirectory.
RMDIR (RD)
RMDIR (RD) [d:]path
Removes a subdirectory.
PROMPT
PROMPT [prompt text] [options]
Changes the DOS command prompt.
REM REM [comment]
Used in batch files and in the CONFIG.SYS file to insert remarks (that will not be acted on).TIME
TIME hh:mm[:ss][.cc][A|P]
Displays current time setting of system clock and provides a way for youto reset the time.
TYPE TYPE [d:][path]filename
Displays the contents of a file.VER
VER
Displays the DOS version number.VERIFY
VERIFY on|off
Turns on the verify mode; the program checks all copying operations toassure that files are copied correctly .VOL
VOL [d:]
Displays a disk's volume label.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 3/813
EXTERNAL COMMANDS
APPEND
APPEND ; APPEND [d:]path[;][d:]path[...] APPEND [/X:on|off][/path:on|off] [/E]
Displays or sets the search path for data files. DOS will search thespecified path(s) if the file is not found in the current path.
ATTRIB
ATTRIB [d:][path]filename [/S]
ATTRIB [+R|-R] [+A|-A] [+S|-S] [+H|-H] [d:][path]filename
[/S]
Sets or displays the read-only, archive, system, and hidden attributesof a file or directory.
CHKDSK
CHKDSK [d:][path][filename] [/F][/V]
Checks a disk and provides a file and memory status report .
DEFRAG
DEFRAG [d:] [/F][/S[:]order] [/B][/skiphigh
[/LCD|/BW|/GO] [/H]
DEFRAG [d:] [/V][/B][/skiphigh] [/LCD]|/BW|/GO] [/H]
Optimizes disk performance by reorganizing the files on the disk.
DELTREE
DELTREE [/Y] [d:]path [d:]path[...]
Deletes (erases) a directory including all files and subdirectories that are
in it.
DISKCOMP DISKCOMP [d:] [d:][/1][/8]
Compares the contents of two diskettes.
DOSKEY
DOSKEY [reinstall][/bufsize=size][/macros][/history][/insert|/overstrike][macroname=[text]]
Loads the Doskey program into memory which can be used to recallDOS commands so that you can edit them.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 4/814
DISKCOPY
DISKCOPY [d:] [d:][/1][/V][/M]
Makes an exact copy of a diskette.
EDIT
EDIT [d:][path]filename [/B][/G][/H][/NOHI]
Starts the MS-DOS editor, a text editor used to create and edit ASCII
text files.
FASTHELP
FASTHELP [command][command] /?
Displays a list of DOS commands with a brief explanation of each. FASTOPEN
FASTOPEN d:[=n][/X]
Keeps track of the locations of files for fast access.
FDISK
FDISK [/status]
Prepares a fixed disk to accept DOS files for storage.
FORMAT
FORMAT d:[/1][/4][/8][/F:(size)] [/N:(sectors)][/T:(tracks)][/B|/S][/C][/V:(label)] [/Q][/U][/V]
Formats a disk to accept DOS files.
MOVE
MOVE [/Y|/-Y] [d:][path]filename[,[d:][path]filename[...]] destination
Moves one or more files to the location you specify. Can also be used torename directories.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 5/815
PRINT [/B:(buffersize)] [/D:(device)] [/M:(maxtick)] [/Q:(value][/S:(timeslice)][/U:(busytick)] [/C][/P][/T] [d:][path][filename] [...]
Queues and prints data files.
SCANDISK
SCANDISK [d: [d: . ..]|/all][/checkonly|/autofix[/nosave]|/custom][/surface][/mono][/nosummay]SCANDISK volume-name[/checkonly|/autofix[/nosave]|/custom][/mono][/nosummary]
SCANDISK /fragment [d:][path]filenameSCANDISK /undo [undo-d:][/mono]
Starts the Microsoft ScanDisk program which is a disk analysis andrepair tool used to check a drive for errors and correct any problemsthat it finds.
TREE
TREE [d:][path] [/A][/F]
Displays directory paths and (optionally) files in each subdirectory.
XCOPY
XCOPY [d:][path]filename [d:][path][filename] [/A][/D:(date)][/E][/M][/P][/S][/V][/W][Y\-Y]Copies directories, subdirectories, and files.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 6/816
INTRODUCTION TO ‘C’ LANGUAGE
„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.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 7/817
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.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 8/818
Loading Turbo C:
Menu Options in Menu Bar:
File
Edit
Compile
Run
Project
Options Debug
Break/Watch
To Open Menu options -> Press Alt and follow by highlightedcharacter Alt + FFile Menu Options:
Load
Pick
New
Save Write to
Directory
Change dir
OS Shell
Quit
Alt + F + L or F3 For Opening an exist file
Alt + F + P or Alt + F3 For Opening an recent files
Alt + F + N For Opening a Blank Screen
Alt + F + S or Alt + F2 For Opening Alt + F + W To Create a Duplicate file
Alt + F + D To Open a file from any Drive orDirectory
Alt + F + C To Change Current Source Path
Alt + F + O To quit from C temporarily
Alt + F + Q or Alt + X To exit from C Permanent
To Compile a C program: -
To Run a C Program: -
To Display User Screen: - Alt + F5
To Remove Messages: - Alt + P + R
With out Hard disk
A:\> TC
F:\LIT1> TC
With hard disk
C:\> CD TC
C:\TC> CD BIN
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 9/819
Points of Remember:1. Every C Program requests a main () function the place main () is
where the program execution begins.2. The execution of a function begins of the opening brace of the
function and ends at the corresponding closing brace.3. „C‟ programs are written in lower case letters, how ever uppercase
are used for symbolic names and out put strings.4. All the words in a program line must be separate from each other
by at least one space.5. Every program statement in the „C‟ program must end with a
semicolon (;).6. All variables must be declared frothier data types before they are
used in the program.7. We must make sure to include header files using # (hash) include
directing when the program referred to special names and
functions that if does not defined.8. Compiler directives such as defined and include of special
instructions to the compiler to help it compile a program they donot end with a; (semicolon).
9. The sign # of compiler must be appearing in the first column of the line.
10. When braces are used to group statements, make sure that eachopening brace has a corresponding closing brace.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 10/8110
STRUCTURE OF C PROGRAM:C program is a collection of one or more functions. Every
function is a collection of statements, performs some specific task. Thestructure of C program is
---------------- Comments------------------------ Preprocessor directives (or ) linking section---------------- Global variables--------main( ){
------------ Local variables------------ Statements------------
}funtion1(){
-------
------- Local variables-------------- Statements-------
}functionn (){
-------------- Local variables
-------
------- Statements-------
}
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 11/8111
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.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 12/8112
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
String Constant string %sOctal Constant %oHexa Decimal Constant %h
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
default goto sizeof voliailedo if static while
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 13/8113
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.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 14/8114
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();
}
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 15/8115
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(\).
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 16/8116
OPERATORS AND EXPRESSIONS
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.
Ex: 15/10.0 = 1.514/10.0 = 1.4
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 17/8117
2.Relational Operators:The comparisons can be done with the help of Relational
Operators. There are six relational operators in C. They are:
Operators Meaning< is less than<= is less than or equal to> is greater than>= is greater than or equal to= = is equal to!= is not equal to
Ex: If A=6, B=9 A>B FalseB>A True
3.Logical Operators:In addition to Relational Operators, „C‟ has the following Logical
Operators.
Operators Meaning&& AND| | OR ! NOT
4.Assignment Operators: Assignment Operators are used to assign the result to a variable.
The usual assignment operator is “=” we can utilize these Operators intwo ways as following below.
Assignment Operator Short hand Operator A=A+1 A+=1 A=A-1 A- =1 A=A*(n+1) A*=(n+1) A=A\(n+1) A\=(n+1)
A=A%B A%=B
The use of shorthand assignment operators has 3 advantages.1. What appear on the right hand side need not be repeated and
therefore it becomes easier to write.2. The statement is easier to read.3. The statement is more efficient.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 18/8118
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
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 19/8119
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
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 20/8120
Aim: program for type conversion techniquesTheory:Type conversion TechniquesIn C, we can convert one type to another type in 3 ways
1. Conversion by Assignment2. Type conversion in Expression3. Using Cast operator
1. Conversion by Assignment If the types of values at the right and left in the assignment
statement are different.The type of value of the expression at the right is automatically
converted intoThe type of the variable at left.
When the type at left is larger than right, the process cause noproblems.
When the type at left is smaller than the right, data loss may occur.
2. Type Conversion in Expression When constants and variables of different types are mixed in anexpression, they are converted to the same type.
All char and short int are converted into int. All floats are converted to doubles. For all operand pairs, if one of the operand is a long double, the
other operand is converted to long double. If one of the operand is double , other is converted into double.
3. Using Cast operator The value of an expression can be converted into another data
type by using a cast operator. The cast operator format is
(cast_data type) expression;Source code:Program for Conversion by Assignment
main( ){
int x = 5;
float y = 2.5;x = y;printf(“ Value of x is %d”, x);
}
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 21/8121
Program for Type Conversion in Expressionmain( ){
short int a = 5;int b = 2500;float c = 250.13;float d = 100.07;float x;x = a + b + c + d ;printf(“the value of x is %f”, x) ;
}
program for Using Cast operator
main( ){
int a = 100;int b = 24;printf(“%f \n”, (float)x/y) ; printf(“%f \n”, (int)x/y) ;
}
0utput for Conversion by Assignment Value of x is 2
Output for Type Conversion in Expressionthe value of x is 2855.200
Output for Cast operator4.166674
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 22/8122
Aim: Program for simple if statement
Theory:
• Used to execute or skip one or group of the statements for aparticular condition.
• Executes group of statements if condition is true.• Skip them if condition is false.• The Syntax of if statement is
Syntax:if(condition){
statements ;
… }next statement;
Source code:#include<stdio.h>main(){int age;printf(“Enter age of candidate:\n”);
scanf(“%d”,&age); if(age > 17)printf(“Eligible for voting”); }Output:
Enter age of candidate:40Eligible for voting
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 23/8123
Aim : Program for if –else statement
Theory:
• if.. else statement is used to execute one group of the statements if condition is true or other group of statements if condition is false.
• The syntax of if..else statement isSyntax:
if (condition){
statements block1;}
else
{statements block2;}next statements;
Source code:
#include<stdio.h>main(){int num;printf(“Enter any number:\n”); scanf(“%d”,&num); if(num % 2 ==0)printf(“Even”); elseprintf(“odd”); }
Output:
Enter any number:8Even
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 24/8124
Aim : Program for Largest of the Three numbers using Nested if .. else
Statement
Theory:• Suppose if block or else block contains another if statement or
if..else statement, the construct is known as Nested if .. ElseStatement.
• Useful when series of decisions are invoked.if(expression1){
if(expression2){
block -1
}else{
block -2}
}
else{
if(expression3){
block -3
}else{
block -4}
} statement x;
Source code:#include<stdio.h>main()
{int a, b, c;printf(“Enter a, b, c :\n”); scanf(“%d%d%d”,&a,&b,&c); if(a>b){
if(a>c)printf(“a is largest”); elseprintf(“c is largest”);
}else{
if(b>c)printf(“b is largest”); elseprintf(“c is largest”);
}}Output:Enter a, b, c :
89 69 98c is largest
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 25/8125
Aim:Program for else … if ladder
Program to read customer name,number and consumed unitsand print the amount under below conditions.
Consumption Units Rate of charge
0-200 Rs.0.50 per unit201-400 Rs.100+Rs.0.65 per unit excess of
200401-600 Rs.230+Rs.0.85 per unit excess of
400601 and above Rs.390+Ss.1.00 per unit excess of
600Theory:
• In this construct, the conditions are evaluated downwards from
top (of the ladder)• As soon as true condition is found, statements associated with it
are executed and the control is transferred to statement-x(skipping rest of ladder)
• If n conditions are false, final else containing the default-statement will be executed.
Syntax:if(condition1)statement-1;
else if(condition2)statement-2;else if(condition3)
statement-3;. . .. . .else if(condition n)
statement-n;else
default-statement;
statement-x;
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 26/8126
Source code:#include<stdio.h>main(){int units;float charges;printf(“Enter units consumed:\n”); scanf(“%d”,&units); if(units > 600)charges = 390 + (units – 600);else if(units > 400)
charges = 230 + 0.80 * (units – 400);else if(units > 200)
charges = 100 + 0.65 * (units – 200);else
charges = 0.50 * units;printf(“The charges are Rs. %f”, charges); }
Output:Enter units consumed:100The charges are Rs. 50.0
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 27/8127
Aim : Program to find larger between 2 numbers. Using ConditionalOperator
or The ? : Operator
Theory:
• Ueful to make two-way decisions.• Combination of ? and :• It takes three operands.
Syntax:
Conditional Expression ? Expr1 : Expr2
The Conditional Expression is evaluated first. If its value is true (1), value of Expr1 is returnedElse the value of Expr2 is returned
Source code:
#include<stdio.h>main(){int a, b, larger;
printf(“Enter a, b values:\n”); scanf(“%d%d”,&a, &b); larger = (a>b) ? a : b;printf(“Larger is %d”, larger); }
Output:
Enter a, b values:20 35
Larger is 35
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 28/8128
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‟:
{printf(“vowel”); break;
}
default:{printf(“not vowel”); }
}}Output:
Enter any character:k
not vowel
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 29/8129
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;
elsegoto yz;xy: printf(“it is even”); return;
yz: printf(“it is odd”); }
Output:Enter any number:45
it is odd
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 30/8130
Aim : program to print the reverse of the given number using while
loop
Theory:
It is a top-tested loop. It is used when number of iterations are not known in
advance. The minimum iteration in this loop is “zero”.
Syntax: while (condition){
body of the loop;}
statements-x;Explanation:
If condition is true, execute the body of the loop. This loop must contain at least one altering statement to exit from
loop otherwise it becomes an infinite loop. If condition is false, then the statement following the loop is
executed (statement-x)Source code:
#include<stdio.h>main()
{int n,s=0,d;clrscr();printf("Enter the n value\n");scanf("%d",&n);
while(n!=0){d=n%10;s=s*10+d;n=n/10;
}printf("The reverse of the given number is = %d",s);getch();}
Output:
Enter the n value 4532
The reverse of the given number is =2354
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 31/8131
Aim : Program to check weather the given number is palindrome or not
using do-while
Theory:
It is another loop statement . It is also called as bottom tested loop. The minimum number of iterations in this
loop is „1‟. Syntax:
do{ body of the loop;}
while (condition);
Explanation: If condition is true, statements in between do and while are
executed repeatedly. If condition is false, loop exits and executes next statement
Source code:#include<stdio.h>main(){int n,s=0,d,k;clrscr();
printf("Enter the n value\n");scanf("%d",&n);k=n;do{d=n%10;s=s*10+d;n/=10;} while(n!=0);if(s==k)
printf("The given number is palindrome");elseprintf("The given number is not a palindrome");getch();}
Output:
Enter the n value: 121
The given number is palindrome
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 32/8132
Aim: Program to find the factorial of the given number using for loop
Theory:
The for loop works well where the number of iterations of the loop is
known before the loop is entered. The head of the loop consists of three parts separated by semicolons.
The first is run before the loop is entered. This is usually theinitialisation of the loop variable.
The second is a test, the loop is exited when this returns false. The third is a statement to be run every time the loop body is
completed. This is usually an increment of the loop counter.
Syntax:
for (<initialization>; <condition>; <increment/decrement>){
------------ body of the loop------
}Initialization :- Is used to set the tool control variable to an initial
value.Condition :- Is an expression that is tested each time the looprepeats.
Increment or decrement statement :- increment/decrementsthe loop control variable.
Source code:
#include<stdio.h>main(){
int i,fact=1,n;clrscr();printf("Enter the value of n");
scanf("%d",&n);for(i=2;i<=n;i++)fact*=i;printf("The factorial of %d is %d",n,fact);getch();
}
Output:
Enter the value of n : 4
The factorial of 4 is 24
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 33/8133
Aim: Sample program for break statement.
Theory:
Break statement:
Break is used to exit from a loop or a switch, control passing to
the first statement beyond the loop or a switch.
With loops, break can be used to force an early exit from the loop,
or to implement a loop with a test to exit in the middle of the loop
body.
Source code:
#include<stdio.h>
main( ){
int n;printf (“Enter the number”); scanf (“%d”, &n);
while (n<10){
if (n==3){
printf(“ using break statements”);
break;}printf(“number =%d \n”,n);
}}
Output:Enter the number 4
Number =4
Enter the number 3
Using break statements
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 34/8134
Aim: Sample program for continue statement.
Theory:
continue statement is used to skip a part of the loop and execute
the loop again from the beginning .
It is used in while, do..while and for loops only.
Source code:
#include<stdio.h>main( ){int marks , i=1,sum=0;clrscr( );
while(i<=10){
printf (“Enter the marks”); scanf (“%d”,&marks); if (marks<0|| marks>100)continue;sum= sum + marks;
i=i+1;
}}Output:Enter the marks : 60
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 35/8135
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 = ");
scanf("%d",&key);for(i=1;i<=n;i++){
if(a[i]==key)k=0;
}if(k==0)
printf("Searching is successful\n");else
printf("Searching is Unsuccessful");
getch();}
Output:
Enter the value of n 6
Enter the elements 7 8 9 6 5 4
Enter the key element =6
Searching is successful
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 36/8136
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++){
for(j=0;j<n;j++)scanf("%d",&b[i][j]);
printf("\n");}for(i=0;i<m;i++){
for(j=0;j<n;j++){
c[i][j]=a[i][j]+b[i][j];}
}printf("The addition of the matrices\n");
for(i=0;i<m;i++){
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 37/8137
for(j=0;j<n;j++){
printf("%d\t",c[i][j]);}
printf("\n");}getch();
}
Output:Enter the row and coloumn numbers 2 2
Enter the elements of matrix a :1 2 3 4
Enter the elements of matrix b :5 6 7 8
The addition of the matrices 6 8 10 12
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 38/8138
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.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 39/8139
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:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 40/8140
Aim: Program for the strcmp( ) Function
Theory:
This function is used to check whether two strings are same ornot.
If both the strings are same it return a 0 or else it returns thenumeric difference between the ASCII values of nonmatchingcharacters
e.q. the following program
Source Code:# include <stdio.h>#include<string,h>main( ){char string1 [ ] = “orange”; char string2 [ ] = “banana”; printf(“%d\n”, strcmp(string1, string2)); printf(“%d\n”, strcmp(string2, “banana”); printf(“%d”, strcmp(string1, “Orange”)); getch( );}
Output:13032
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 41/8141
Aim : Program for the strcpy()
Theory:The function copies one string to another
Source code:# include <stdio.h>#include<string.h>main( ){char source [ ] = “orange”; char target [20];strcpy(target, source);clrscr( );
printf(“source: %s\n”, source); printf(“target:%s”, target); getch( );}
Outputsource : orangetarget : orange
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 42/8142
Aim: Program for the strcat() function.
Theory:
This function concatenates the source string at the end of thetarget string
e.g, “Bombay” and “Nagpur” on concatenation would result in toa string “Bombay Nagpur”.
Source code:#include<stdio.h>#include<string.h>
Void main( ){char source [ ] = “Folks”; char target [30] = “Hello”; strcat(target, source);printf(“\n source string = %s”, source); printf(“\n target string = %s”, target); }
Output:source string = folkstarget string = Hello folks
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 43/8143
Aim: Write a program for Functions with no arguments and no return values. Theory:
• A self contained sub program that performs a specific well definedtask.
• Library functions or Built-in functions: Already available in C
language.
• User defined functions: Developed by user for performing aspecific task.
Syntax of function:return-type function-name(datatype arg1,datatype arg 2,…datatype arg n) {
local variable declarations;statement sequence;return(expression);
}• Return type specifies the type of value the function returns.• If no type is specified the function is assumed to return integer
type.• Rules applied for naming the variables will be applied for function
names also.• With in parenthesis argument list is specified with their type.
Function call techniques:Parameters can be passed to a function in two ways
• Call by value• Call by reference
Call by value:• Actual arguments are copied into the corresponding formal
arguments.• Changes done to the formal parameters have no effect on the
actual parameters because actual parameters and formalparameters have separate memory locations.
Call by reference:• Instead of values, only address of the actual parameters is passed
to the formal parameters.• Formal parameters are pointer variables and they point to the
same memory locations of the corresponding actual parameters.• So any changes done to the formal parameters effect the actual
parameters.• We use call by value mechanism if a single value has to be
returned.• When more than one value is desired we use call by reference
mechanism to indirectly transfer the resulting values back to thecalling function.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 44/8144
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++){
f3=f1+f2;printf("%d\n",f3);f1=f2;f2=f3;
}getch();}
Output:0 1 1 2 3 5 8
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 45/8145
Aim: Functions with arguments and no return values
Theory:
• Functions can have parameters, hence calling function can
send data to the called function but it cannot return any valueto the calling function.
Source code:
main ( ){int a = 10, b=20;swapy (a,b);printf (“\na = % d b = % d”, a,b);
}swapy (int x, int y){int t;t = x;x = y;
y = t;printf ( “\n x = % d y = % d” , x, y); }Output:
The output of the above program would be;x = 20 y = 10a =10 b =2
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 46/8146
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
Sum of two nos is : 15
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 47/8147
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)
return(1);else if(x>0)
f=x*fact(x-1);
return(f);}Output:5Factorial of number 5 is 120
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 48/8148
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 :-
a=&count;c=*a; places the value of count in c;
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 49/8149
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.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 50/8150
Source code:#include<stdio.h>#include<alloc.h>main(){
int *a,*b;clrscr();printf("enter value of a: ");scanf("%d",a);printf("\nenter value of b: ");scanf("%d",b);*a=*a+*b;*b=*a-*b;
*a=*a-*b;printf("\nThe values are interchanged a=%d,b=%d",*a,*b);getch();
}
Output:Enter value of a: 5
Enter value of b : 7The values are inter changed a=7 b=5
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 51/8151
Pointer arithmetic:• As in case of variables arithmetic operations can be performed on
pointers.• Addition and subtraction operations are possible on pointers.• Postfix, prefix, increment, decrement operations are also possible
on pointers.• In variables postfix, prefix, increment, or decrement means
addition or s subtraction by one.• In pointer variables they mean addition or subtraction of bytes
that pointer data type holds, with the value that the pointer variable contains.
Operations on pointer variables• Addition of a number to a pointer variable.
Example:p++;k=k+3; /* p,k are pointer variables */
• Subtraction of a number from a pointer variable.Example :
p--;• Subtraction of one pointer from another pointer
Example:p-k;
• Comparison of two pointerExample :
if(p==k)printf(“ both are pointing to same location”);
Operations not allowed on pointers• Addition of two pointers.• Multiplication of a pointer with a constant.• Division of a pointer with a constant.
Example on pointer arithmeticint var,*ptr;ptr=&var;
var=1500;• Let var be an integer variable having a value 1500 and stored at
address 1000.• ptr has the value 1000.• After the expression ptr++,
ptr contains 1002 and not 1001.• Because each time ptr is incremented, it will point to the next
integer and since integers are two bytes long, ptr will increment by 2 and the same is true for decrements.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 52/8152
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.
Source code:#include<stdio.h>main()
{char *names[]={“Hemanth”,”sirisha”,”sridevi”}; char *temp;printf(“original %s%s”,names[1],names[2]); temp=names[1];names[1]=names[2];names[2]=temp;printf(“new %s%s”,names[1],names[2]);}
Output:
Original : Sirisha SrideviNew : Sridevi Sirisha
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 53/8153
Aim: Program to square of the given number using functionsusing pointers
Theory :Pointers and Functions
A pointer to a function contains the address of the function inmemory.
A pointer to a function is simply a pointer whose value is theaddress of the function name.
Pointers are often passed to a function as arguments.Syntax of pointer to a function is
return-type (*ptr)(); ptr is a pointer to a function which returns the value of type
return-type
Example:int (*ptr)(int);
where ptr is a pointer to a function that receives an integerparameter and returns a value of type integer.
Parenthesis around *ptr is necessary, because „*‟ has a lowerprecedence than parenthesis enclosing the function.
Source code:#include<stdio.h>float fun(float);
main(){float x,value;printf(“Enter the value of x:\t”); scanf(“%f”,&x);
value=(*fun)(x); /* function is called through pointer */printf(“Square x:%f”,value); }
float fun(float y){
return(y*y);}
Output:Enter the value of x : 6Square x : 36
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 54/8154
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.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 55/8155
calloc() function
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.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 56/8156
Source Code:#include<stdio.h>#include<malloc.h>#define length 40main(){
char *s1,*s2,*s3,c;int i,j,k;clrscr();s1=(char *) malloc(length*sizeof(char));s2=(char *) malloc(length*sizeof(char));s3=(char *) malloc(length*sizeof(char));printf("\nenter string-1: ");scanf("%s",s1);
printf("\nenter string-2: ");scanf("%s",s2);i=0;
while(*(s1+i) != '\0'){
*(s3+i) =*(s1+i);i++;
}k=0;
while(*(s2+k) != '\0')
{*(s3+i+k)=*(s2+k);k++;
}printf("\nConcatenated string is........");printf("%s\n",s3);getch();
}Output:
Enter string -1: shanmukhaEnter String-2: srinivasaraoConcatenated string is ……….. : shanmukha srinivasarao
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 57/8157
Aim: Program example for the pointers to pointers
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 ); }
Output:
i j k 3 6485 32766485 3276 7234
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 58/8158
Structure : It is a collection of data elements which are of different types that
are logically grouped together. They are referenced under same name. It is heterogeneous. Data elements are stored in contiguous memory locations.
Example:struct emp
{
int empno;float sal;char gender;
};empno, sal and gender are called members of structure
Declaration of Structure Variable(s) Once the structure is defined ,you can declare a structure variable
Syntax:struct tagname structurevariable(s);
Example:struct emp e; Struct emp is data type called derived data type When structure variable is declared memory is allocated for
members of structure.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 59/8159
Combined Definition & Declaration
Structure definition and Structure variable declaration can be combined
together.
struct emp /*structure definition*/{
int empno;float sal;char gender;
} s;
struct{
int empno;float sal;char gender;
} s; Tagname is optional when structure variable is declared at the
time of defining the structure itself. Accessing Structure Members
Dot(.) operator is used to access membersSyntax:
Structurevariable.membername;
Example e.empno; gives content of empno
e.sal; gives content of sal
e.gender; gives content of gender
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 60/8160
Aim: Write a program using structure to print the student details.
Source code:
#include<stdio.h>struct st{
char name[20],street[20],fname[20],town[20];int hno;
}a;main(){
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
Street : gollapalemTown : chirala
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 61/8161
Aim: Write a program using initialization of structure elements to printstudent detailsTheory:
Members can be initialized at the time of defining the structure ordeclaration of structure variable
Syntax :struct tagname variable={value1,value2,…valuen};
ExampleMethod 1) struct emp e={1000,60000.50,‟M‟};
Method 2) struct emp e={1000,60000.50,
„M‟ };
Method 3) struct emp{
int empno;float sal;char gender;}e={1000,60000.50,‟M‟};
Source Code:#include<stdio.h>struct student
{Char pinno;Char name;Int age;Char sex;Float height;Float weight;};main(){
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();
}
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 62/8162
Output:Enter the student detailsPin no : 10103-CM-001Name : srinu
Age : 30Sex :MHeight :5.3
Weight :70
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 63/8163
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:
struct entry {charfname[10];charlname[12];char phone[8];};
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:
#include<stdio.h>struct stud{
char name[20],qfn[20],fname[20],town[20];char street[20];float tpn;
};main(){
Struct stud per[10];int i,n,j;float stpn;clrscr();printf("\nENTER NO. OF PERSONS u WISH");scanf("%d",&n);
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 64/8164
for(i=0;i<n;i++){
clrscr();printf("\nENTER DETAILS OF A PERSON -
%d\n\n",i+1);printf("Enter name : ");scanf("%s",per[i].name);printf("Enter Father's name: ");scanf("%s",per[i].fname);printf("Enter Qualification: ");scanf("%s",per[i].qfn);printf("Enter Street: ");scanf("%s",per[i].street);printf("Enter Town: ");
scanf("%s",per[i].town);printf("\nEnter Telephone: ");scanf("%f",&per[i].tpn);
}printf("\nenter telephone no. U want to search: ");scanf("%f",&stpn);clrscr();for(i=0;i<n;i++){
if(stpn==per[i].tpn)
{printf("\n\n\t\t\t THE PERSON IS FOUND FOR
T.P.No.%5.0f\n",stpn);for(j=0;j<80;j++) printf("þ");printf("\n\t\t\t NAME : %s ",per[i].name);printf("\n\t\t\t FATHER'S NAME : %s ",per[i].fname);printf("\n\t\t\t QUALIFICATION : %s ",per[i].qfn);printf("\n\t\t\t STREET : %s ",per[i].street);printf("\n\t\t\t TOWN : %s ",per[i].town);
break;
}else j=0;}if(j==0) printf("\nNO PERSON WITH T.P.No
%5.0f",stpn);getch();
}Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 65/8165
Aim : Write a program to calculate the size of the structureTheory:
Sum of sizes of its membersExamplestruct emp
{int empno;float sal;char gender;
};struct emp e;sizeof(e) or sizeof(struct emp)=2+4+1=7 bytes
Source code:
#include <stdio.h>Struct sample{Char a;Int b;Float c;Long l;};
Void main(){Struct sample s;Printf(“size of structure =%d”, sizeof(s)); }Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 66/8166
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");
printf("Enter Date: ");scanf("%d",&per.d.dd);printf("Enter Month: ");scanf("%d",&per.d.mm);printf("Enter Year: ");scanf("%d",&per.d.yy);printf("\nEnter Telephone: ");scanf("%f",&per.tpn);
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 67/8167
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);
printf("\n\t\t\tTELEPHONE NO. : %5.0f",per.tpn);getch();
}Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 68/8168
Aim : Write program example for the Passing Structures as Argumentsto FunctionsTheory:
Structures can be passed to a function in 3 waysPassing structure elements to a function.
Any ordinary variables can be passed to a function. Members of a structure variable can also be passed to a
function.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 69/8169
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);}
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 70/8170
Returning structure from a function A function can return int, float, char etc., Similarly a function can also return structure.
Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 71/8171
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);
}Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 72/8172
Aim: Write a program unionTheory:
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); }
Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 73/8173
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‟
File *fp;Fp=fopen(“st.dat”,‟w‟);
Fprintf(fp,”%[^\n]”,”rajan”);
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 74/8174
Fclose:The last step is to close the file after the desired manipulation. This isdone by thelibrary function fclose.Syntax:
fclose(fp);
Aim : write a program to create a file of biodata of students with name„st.dat‟. Source code:#include<stdio.h>#include<string.h>Tpedef struct{Int day;
Int month;Int year;}date;Typedef Struct{char name(30);char place(30);int age;date birthdate;}biodata;
Main(){File *fp;
biodata student;fp=fopen(“st.dat”,‟w‟); Printf(“Input data”); Scanf(“%[^\n]”,student.name); Scanf(“%[^\n]”,student.place); Scanf(“%d”,&student.age); Scanf(“%d”,&student.birthdate.day);
Scanf (“%d”,&student.birthdate.month): Scanf(“%d”,&student.birthdate.year); Fprintf(fp,”%s%s%d%d%d%d”,student.name,student.place,student.
age,student.birthdate.day, student.birthdate.month,student.birthdate.year)Fclose(fp);}Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 75/8175
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); }
Fclose(fp);}Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 76/8176
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");
while((c=getc(fp))!=EOF){
printf("%c",c);}fclose(fp);getch();
}
Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 77/8177
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
{Int day;Int month;Int year;}date;Typedef Struct{char name(30);char place(30);int age;
date birthdate;}biodata;Main(){File *fp;
biodata student;fp=fopen(“st.dat”,‟r+‟); fscanf(fp,”%s”,student.name); printf(“%s”,student.name); fclose(fp);
}Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 78/8178
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
{Int day;Int month;Int year;}date;Typedef Struct{char name(30);char place(30);int age;
date birthdate;}biodata;Main(){File *fp;fp=fopen(“st.dat”,‟a+‟)
biodata student;Printf(“Input data”); Scanf(“%[^\n]”,student.name); Scanf(“%[^\n]”,student.place);
Scanf(“%d”,&student.age); Scanf(“%d”,&student.birthdate.day); Scanf(“%d”,&student.birthdate.month): Scanf(“%d”,&student.birthdate.year);Fwrite(&student,sizeof(record),1,fp);Fclose(fp);}
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 79/8179
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+‟)
biodata student;fread(&student,sizeof(record),1,fp);printf(“%s\n”,student.name);
printf(“%s\n]”,student.place); printf(“%d\n”,&student.age); printf(“%d\n”,&student.birthdate.day); printf(“%d\n”,&student.birthdate.month): printf(“%d\n”,&student.birthdate.year); fclose(fp);}
Output:
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 80/8180
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.
7/29/2019 c Lab Manual JNTUK I BTECH
http://slidepdf.com/reader/full/c-lab-manual-jntuk-i-btech 81/81
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);
fseek(fp,(n-1)*sizeof(emp),0);freed(&emp,sizeof(emp),1,fp);printf("%s\t,emp.name);printf("%d\t",emp.age);printf("%f\n",emp.sal);fclose(fp);getch();}
Output:
top related