You are on page 1of 81

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] or COPY [/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:]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. 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 whether or not the upper memory blocks will be used.

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 you to 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 to assure that files are copied correctly. VOL VOL [d:] Displays a disk's volume label.

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 the specified 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 attributes of 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 recall DOS commands so that you can edit them.

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 to rename directories.

PRINT 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][/nos ummay] SCANDISK volumename[/checkonly|/autofix[/nosave]|/custom][/mono][/nosummary] SCANDISK /fragment [d:][path]filename SCANDISK /undo [undo-d:][/mono] Starts the Microsoft ScanDisk program which is a disk analysis and repair tool used to check a drive for errors and correct any problems that 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.

INTRODUCTION TO C LANGUAGE C seems a strange name for a programming language. But this strange sounding language is one of the most popular computer languages today. C was an offspring of the Basic Combined Programming Language (BCPL) developed by Martin Richards in 1967. In 1970 a system engineer called Khen Thomson modified BCPL and for the modified version he has given the name B, the first letter of BCPL one the UNIX operating system. Around 1972 another System engineer called 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 level language. It is a middle level language. It doesn't mean it is supporting few of high and low level features. The real meaning is it supports complete features of high level and low level. So using C language programmer can develop system level and application level programming. Importance of C: The increasing popularity of C is probably due to its many desirable qualities. It is a robust language thats richest of built-in functions and operators can be used to write any complex program. The C 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 faster than BASIC. For example, a program to increment a variable from 0 to 15,000 takes about one second in C, while it takes more than 50 seconds in on compiler BASIC. There are only 32 keywords; several standard functions are available which can be used for developed programs. C is highly portable. This means that C programs written for one computer can be run on another with little or no modification. Portability is important if we plan to use a new computer with a different 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 set of guidelines later in this book, when we start writing our own C programs. 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 the calculations is an absolute necessity in any computer program. 2.Clarity:- It refers to the overall readability of the program, with particular emphasize on its underlying logic. If a program is clearly written, it should be possible for another programmer to follow the program logic without undue effort. I should also be possible for the original 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 the design of C is the development of clear, readable programs through an orderly 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 the overall program objectives. In fact, it may be desirable to sacrifice a certain amount of computational efficiency in order to maintain a relatively simple, straightforward program structure. 4.Efficiency:- It is concerned with execution speed and efficient memory 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. In such 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 implement each 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 facilitates program alterations. 6.Generality: - Usually we will want a program to be as general as possible, within reasonable limits. For example, we may design a program to read in the values of certain key parameters rather than placing fixed values into the program. As a rule, a considerable amount of generality can be obtained with very little additional programming effort.

Loading Turbo C: With out Hard disk A:\> TC F:\LIT1> TC Menu Options in Menu Bar: File Edit Compile Run Project Options Debug Break/Watch

With hard disk C:\> CD TC C:\TC> CD BIN C:\TC\BIN> TC

To Open Menu options -> Press Alt and follow by highlighted character Alt + F File 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 or Directory 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

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 do not 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 each opening brace has a corresponding closing brace.

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. The structure of C program is --------------- Comments ---------------------- Preprocessor directives (or ) linking section --------------- Global variables -------main( ) { ----------- Local variables ----------- Statements ----------} funtion1() { ------------- Local variables ------------- Statements ------} functionn () { ------------- Local variables ------------- Statements ------}

10

In C program comments are used for documentation purpose. When used carefully, comments can be very helpful clarifying what the complete program is about, what a specific group of statements is meant to accomplish, or what one line is intended to do. Comments can be taken between /* and */. It may be anywhere in the program. If a comment is too long to be contained on one line, it can be continued across two or more lines as shown below. /*this comment is to show a comment that extends over two lines*/. Preprocessor directives are 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, so it is necessary to declare them globally. Those variables are called as global 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 types 2. Derived data types 3. 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. The integer constant occupies 2 bytes in memory. Floating Point Constant: - Such as distance, heights, temperature, price etc.. These quantities are represented by numbers containing fractional like 10.943 such nos called floating points or real constants. This constant occupies 4 bytes in memory. Size of precision part is 6 digits. 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 size range of precision part is 14 digits. Long Double Constant:- This constant occupies 10 bytes (80 bits) in memory.

11

Single Character Constant:- The single character constant is a single character enclosed with in a pair of single quote marks. This constant occupies 8 bits (1 byte) in memory. Ex:- a , 5, * String Constant:- The string constant is a group of characters that enclosed in double quotes ( ) . The characters may be letters, no and special characters. Ex:- ICT , C Language , 06-10-2002
Data Type Name Declaration symbol Single Character char %c Unsigned Character unsigned char %c Enumarated enum Integer Constant int, short int %d Unsigned Integer unsigned int %u Long Integer Constant long, Long int %ld 214,74,83,647 Unsigned Long Integer unsigned long int 429,49,67,295 Floating Point Constant float %f Double Point Constant double 10308 Long Double Point long double 104932 String Constant string Octal Constant Hexa Decimal Constant %lf %Lf %s %o %h Data Range Limits -128 to 127 0 to 255 -32,768 to 32,767 -32,768 to 32,767 0 to 65,535 -214,74,83,648 to %ul 0 to

3.4 X 10-38 to 3.4 X 1038 1.7 X 10-308 to 1.7 X 3.4 X 10-4932 to 1.1 X

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 the user. These words should not be used as identifier/variables in programs. The following are c reserved words: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void voliaile while

12

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 and underscore. 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 is 2. It specifies what type of data the variable will hold. The declaration of variables must be done before they are used in the 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 done through functions only. Input/output operations enable the communications between the program and the user. In many of the computer languages the input/output operations are done through statements. But in C language Input and output operations are done through functions.

13

Input Functions: Input data can be entered into the memory from a standard input device. C provides the scanf() function for entering input data. This function accepts all types of data as int(numeric, character, string). The general form of scanf() is given below. scanf("Conversion specification", variable1, variable2...variable); This function should have at least two parameters. First parameter is control string which is conversion specification character. It should be within double quotes. This conversion specification character may be one or more, it depends on the number of variables. The other parameters are variable names. In the scanf() at least one variable name should be present. Each variable name must be preceded by an ampersand (&). This gives the starting address of the variable name in memory. Note:- Comments are not allowed in scanf(). Conversion specifications are used to provide the type and size of the data. Each conversion specification 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 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); 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(); }

14

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 normal interpretation of a string. Escape Sequence Meaning Result \a Bell(alert) Produce a beep sound for alert. \b \n \r \t \v tab \0 \ backslash(\). \ backslash(\). \\ backslash(\). Backspace Moves the cursor to the previous position of the current line. New line Moves the cursor to the next line. Carriage return Moves the cursor to the beginning of the current line. Horizontal Tab Moves the cursor to next horizontal tab position. Vertical tab Moves the cursor to next vertical position. Null Null Single Quote Present a single quote with Double Quote Backslash Present a double quote with Present a character with

15

OPERATORS AND EXPRESSIONS An Operator is a symbol that tells the computer to perform mathematical or logical manipulation. C Operators can be classified into a number of categories. They include: 1. 2. 3. 4. 5. 6. 7. 8. Arithmetic Operators Relational Operators Logical Operators Assignment Operators Increment and decrement Operators Conditional Operators Bit wise Operators 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 integer operands is called Integer arithmetic. Ex: 14 + 2 = 16 12/3 = 4 14%3 = 2 Real Arithmetic: An Arithmetic Operation involving only real operands is called real arithmetic. Ex: 6.0/7.0 = 0.857143 1.0/3.0 = 0.333333 Mixed-Mode Arithmetic: When one of the operand is real and the other integer is mixed-mode arithmetic. Ex: 15/10.0 = 1.5 14/10.0 = 1.4

16

2.Relational Operators: The comparisons can be done with the help of Relational Operators. There are six relational operators in C. They are: Operators < <= > >= == != Ex: If A=6, B=9 A>B False B>A True 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

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 in two 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.

17

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 Operand m++ or ++m is equal to m=m+1 or m+=1 m- - 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 ~ 1s 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 operand occupies. 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

18

Aim: Program to convert Fahrenheit into Celsius Using printf and scanf functions Theory: Input Functions: Input data can be entered into the memory from a standard input device. C provides the scanf() function for entering input data. This function accepts all types of data as int(numeric, character, string). The general form of scanf() is given below. scanf("Conversion specification", variable1, variable2...variable); This function should have at least two parameters. First parameter is control string which is conversion specification character. It should be within double quotes. This conversion specification character may be one or more, it depends on the number of variables. The other parameters are variable names. In the scanf() at least one variable name should be present. Each variable name must be preceded by an ampersand (&). This gives the starting address of the variable name in memory. 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.5 temp in celsius is 34.16

19

Aim: program for type conversion techniques Theory: Type conversion Techniques In C, we can convert one type to another type in 3 ways 1. Conversion by Assignment 2. Type conversion in Expression 3. 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 into The type of the variable at left. When the type at left is larger than right, the process cause no problems. 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 an expression, 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); }

20

Program for Type Conversion in Expression main( ) { 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 Expression the value of x is 2855.200 Output for Cast operator 4.16667 4

21

Aim: Theory:

Program for simple if statement

Used to execute or skip one or group of the statements for a particular 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: 40 Eligible for voting

22

Aim : Theory:

Program for if else statement

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 is Syntax: 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); else printf(odd); } Output: Enter any number: 8 Even

23

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 .. Else Statement. Useful when series of decisions are invoked. if(expression1) else { { if(expression2) if(expression3) { { block -1 block -3 } } else else { { block -2 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); else printf(c is largest); } else { if(b>c) printf(b is largest); else printf(c is largest); }} Output: Enter a, b, c : 89 69 98 c is largest

24

Aim:Program for else if ladder Program to read customer name,number and consumed units and print the amount under below conditions. Consumption Units Rate of charge 0-200 Rs.0.50 per unit 201-400 Rs.100+Rs.0.65 per unit excess of 200 401-600 Rs.230+Rs.0.85 per unit excess of 400 601 and above Rs.390+Ss.1.00 per unit excess of 600 Theory: 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 defaultstatement 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;

25

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: 100 The charges are Rs. 50.0

26

Aim : Program to find larger between 2 numbers. Using Conditional Operator 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 returned Else 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

27

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

28

Aim: program to find whether the given number is even or odd using unconditional 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; else goto yz; xy: printf(it is even); return; yz: printf(it is odd); } Output: Enter any number: 45 it is odd

29

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 advance. The minimum iteration in this loop is zero. known in

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

30

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"); else printf("The given number is not a palindrome"); getch(); } Output: Enter the n value: 121 The given number is palindrome

31

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 the initialisation 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 loop repeats. Increment or decrement statement :- increment/decrements the 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

32

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

33

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

34

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

35

Aim: Program to find the addition of two matrices using two dimensional 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++) {

36

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

37

Aim: Write program to find the sum of elements in an array using initialization of array. Theory: Array elements can be initialized within their declaration statements 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 is defined. Unlike automatic variables static variable retains values throughout the life of the program, i.e. if a function is exited and then 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 the program. Static variable is declared by using thekeyword static.

38

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 = f1 f1= f ; return (f ) ; } Output:

39

Aim: Program for the strcmp( ) Function Theory: This function is used to check whether two strings are same or not. If both the strings are same it return a 0 or else it returns the numeric difference between the ASCII values of nonmatching characters 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: 13 0 32

40

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( ); } Output source : orange target : orange

41

Aim: Program for the strcat() function. Theory: This function concatenates the source string at the end of the target string e.g, Bombay and Nagpur on concatenation would result in to a 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 = folks target string = Hello folks

42

Aim: Write a program for Functions with no arguments and no return values. Theory: A self contained sub program that performs a specific well defined task. Library functions or Built-in functions: Already available in C language. User defined functions: Developed by user for performing a specific 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 formal parameters 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 the calling function.

43

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

44

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 value to 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 = 10 a =10 b =2

45

Aim: Functions with arguments and return values Theory: Since functions have parameters, the calling function can send data to the called function. The called function can return the resultant value to calling function 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 Enter the second number Sum of two nos is :6 :9 : 15

46

Aim: write a factorial of the given number using recursion function methods Theory: A function is recursive if a statement in the body of the function calls 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 are popped 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: 5 Factorial of number 5 is 120

47

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 to another 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 known as the Dereferencing 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;

48

Declaring a pointer Syntax : 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 an assignment 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.

49

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 : 7 The values are inter changed a=7 b=5

50

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 pointer Example : 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 arithmetic int 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.

51

Aim: Program to interchange elements of character array using pointers Theory: Pointers and Arrays An array of pointers is an array that contains pointers as its elements. Pointer arrays give a convenient method for storing strings. As strings are character arrays, each array element is a charactertype pointer that points to a separate string. Suppose the following strings are to be stored in a character-type array. Bombay Delhi Madras Kolkata Hyderabad The above strings can be stored in a two dimensional charactertype 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 using city[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 Sridevi New : Sridevi Sirisha

52

Aim: Program to square of the given number using functions using pointers Theory: Pointers and Functions A pointer to a function contains the address of the function in memory. A pointer to a function is simply a pointer whose value is the address 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 integer parameter and returns a value of type integer. Parenthesis around *ptr is necessary, because * has a lower precedence 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 Square x :6 : 36

53

Aim: Program using program to concatenation of two strings using pointers. Theory: Dynamic memory allocation can be done using the following functions The malloc() function The calloc() function The free() function The realloc() function Sizeof() Operator Before 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 type or data object. It is not a library function but a keyword which returns the size of the operand in bytes. Example: sizeof(char) is 1 sizeof(int) is 2 sizeof(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.e 10*2=20 bytes) and the starting address of the first byte is assigned 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.

54

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.

55

Source Code: #include<stdio.h> #include<malloc.h> #define length 40 main() { 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: shanmukha Enter String-2: srinivasarao Concatenated string is .. : shanmukha srinivasarao

56

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 pointers 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 3 6485 j 6485 3276 k 3276 7234

57

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.

58

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 members Syntax: Structurevariable.membername; Example e.empno; gives content of empno e.sal; gives content of sal e.gender; gives content of gender

59

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 elements Enter the name of the student: srinu Enter the father name: narasimharao Enter the street: gollapalem Enter house Number: 11-9-66/1 Enter Town : chirala Name : srinu Fathers name: narasimharao House number: 11-9-66/1 Street : gollapalem Town : chirala

60

Aim: Write a program using initialization of structure elements to print student details Theory: Members can be initialized at the time of defining the structure or declaration of structure variable Syntax : struct tagname variable={value1,value2,valuen}; Example Method 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(); }

61

Output: Enter the student details Pin no : 10103-CM-001 Name : srinu Age : 30 Sex :M Height :5.3 Weight :70

62

Aim: write a program using array of structure to print the person details Theory: Arrays of Structures arrays of structures are very powerful programming tools. structure definition can be tailored to fit the data your program needs to work with. Usually a program needs to work with more than one instance of the data. For example, in a program to maintain a list of phone numbers, you can define a structure to hold each person's name and number: struct entry { char fname[10]; char lname[12]; char phone[8]; }; A phone list must hold many entries, however, so a single instance of the entry structure isn't of much use. What you need is an array of structures of type entry. After the structure has been defined, you can declare an array as follows: struct entry list[1000]; This statement declares an array named list that contains 1,000 elements. Each element is a structure of type entry and is identified by subscript like other array element types. Each of these structures has three 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);

63

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:

64

Aim : Write a program to calculate the size of the structure Theory: Sum of sizes of its members Example struct 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:

65

Aim : Write a program to print the person details using nexted structure 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);

66

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:

67

Aim : Write program example for the Passing Structures as Arguments to Functions Theory: Structures can be passed to a function in 3 ways Passing 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.

68

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); }

69

Returning structure from a function A function can return int, float, char etc., Similarly a function can also return structure.

Output:

70

Aim : Write a program example for the pointer to a structure. Theory: Pointer variable that can hold stating address of a structure variable Syntax: 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:

71

Aim: Write a program union Theory: Unions, like structure contain members, whose individual data types may vary. This is a is major distinction between them in terms of storage .In structures each member has its own storage location, where as all the members of a union use the same location.Like structures, a union can be declared using the keyword 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:

72

Files Data Files Data Files are to store data on the memory device permanently and to access whenever is required. There are two types of data files 1 Stream Oriented data files 2 System Oriented data files Stream oriented data files are either text files or unformatted files. System oriented data files are more closely related to computers operating system and more complicated to work with. In this session we go through stream oriented data files. Opening and Closing data files The first step is to create a buffer area where information is stored temporarily before passing to computer memory. It is done by writing File *fp; Here fp is the pointer variable to indicate the beginning of the buffer area and called stream pointer . The next step is to open a data file specifying the type i.e. read only file , write only file , read /write file. This is done by using the library function fopen syntax fp=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 not exist 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 file does not 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);

73

Fclose: The last step is to close the file after the desired manipulation. This is done by the library 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:

74

Aim:To write a set of numbers to a file. Source code: #include<stdio.h> main() { file *fp; Int n; float x fp=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:

75

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 to handle one character at a time. Assume that a file is opened with mode w and file point fpt. Then, the statement fputc(c,fpt); Writes the character contained in the character variable c to the file associated with FILE pointer fpt. Similarly getc is used to read character from a file that has been opened in read mode. For example, the statement C = fgetc(fp2); Would read character from file whose file pointer is fp2. the file pointer moves 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:

76

Aim : For reading formatted data from a file we use the function fscanf Theory: Processing formatted data File To read formatted data from a file we have to follow all the various steps that discussed above. The file should be opened with read mode. To open the existing file 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:

77

Aim: Write a program to write biodata to a file using processing unformatted data files Theory: Processing Unformatted data files For reading and writing unformatted data to files we use the library functions fread and 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 file 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; 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); }

78

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; 53 Main() { 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:

79

RANDOM ACCESS TO FILES : There are occasions however, when we are interested in accessing only a particular part of a file and not in reading the other parts. This can be achieved with the help of the function fseek, ftell and rewind available in the library. ftell : ftell take a file pointer and returns a number of type long that corresponds to the current portion. This function is useful in saving the current position of a file, which can be used in the program. It takes the following form. N =ftell(fp); N would give the relative offset (n bytes) of the current position. This means 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 than once. 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 type long and position is an integer number. The offset specifies the number of bytes(position) to be moved from the location specified by position. The position can take one of the following three values : 0 beginning of file 1 current position 2 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 to move beyond the file boundaries and error occurs and fseek returns.

80

Aim : Write a program on Random access file concept Source 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:

81

You might also like