Download presentation
Presentation is loading. Please wait.
Published byBeatrix Johnston Modified over 7 years ago
1
Principal, PVP Siddhartha Institute of Technology
C – PROGRAMMING By Dr. K. Srinivasu Principal, PVP Siddhartha Institute of Technology
2
Evolution of computers:
The history of the evolution of computers begin thousands of years ago with the ABACUS, the world’s oldest known computing device. It was used by the Chinese as early as 600 B.C and is still in use today. MARK I (1944): First computer capable of automatically performing a long sequence of arithmetical and logical operations. It was a huge machine of 50ft long , 8ft high and 3 ft deep and weighed many tons. The machine contained 300 mechanical switches , 7 lakh 50 thousand electronic components and 500 miles of wire. It was controlled by punch paper tape. The first computer Attanasoff- Berry Computer (ABC computer) developed by John V.Attanasoff and his student Clifford Berry of UNIVAC-I in 1951.
3
First Generation ( ): The first electronic general purpose computer ‘THE ENIAC ’ [ Electronic Numerical Integrator And Computer ]. It occupied sq.ft of floor space and weighed 30 tons. 19 thousand vacuum tubes and tens of thousands of other electronic components were used. It consumed so much electricity it actually dimmed the lights of the city of Philadelphia when it was turned on. Vacuum tubes replaced RELAYS commercial computer industry began with the introduction.
4
Second Generation (1959-1964):
With the invention of transistor at BELL labs in 1948 it became clear transistors would quickly replace vacuum tubes. They were smaller, more reliable used less energy and gave off very little heat. In addition to computers with transistors operated much faster than those with vacuum tubes. In late 50’s and early 60’s when second generation computers were being developed there was a software being developed , there was a software explosion. A number of High level languages were developed. COBOL (Common Business Oriented Language), FORTRAN (FORmula TRANslation), ALGOL (ALGOrithemic Language) were developed during second generation period only.
5
1. Multiprogramming : Several users to share the machine jointly
2. Time Sharing :A method of sharing a computer in which tens or 100/s of users can access the central computer through terminals 3. Speed: Increased speed and reliability reduced size. Processing speed upto 3 million instructions per second In 1964 I.B.M [ International Business Machine] Improved secondary storage devices were developed
6
Third Generation( ) Integrated Circuits were introduced in which the equivalent of hundred and even thousands of transistors could be placed on a small SILICON CHIP. Use of these chips in third generation computers reduced cost, size and power requirements for electronic circuits
7
Beyond fourth generation Computers:
L.S.I [Large Scale Integrated Circuits] with many thousands of transistors on a single silicon chip were developed I.B.M 370 was introduced Microprocessors were introduced Micro computer came into existence Beyond fourth generation Computers: A new generation of computers called the fifth generation has already been conceived.In fact , these computers have been thought to be much more user friendly i.e they will have a user oriented human-machine interface. These machines will be increasingly used for non-numeric data processing such as symbol manipulation and Artificial Intelligence(AI).In fact, what we are heading towards is an intelligent machine, i.e a machine that thinks.
8
About the Computer A computer system in general has four hardware components namely : Input devices Central Processing Unit(CPU) Output devices Secondary/Auxiliary storage devices 1.Input Devices: Convert data and program instructions into a format that is understandable by the computer Input unit is that part of a computer to which the information is fed. The function of the input unit is to read the information contained in the program and transmit to CPU
9
2. Central Processing Unit (CPU):
The central processing unit shortly called as CPU is the heart of the computer system since the actual computation work is carried out in this. It links the input and output units together. The CPU internally consists of three units Arithmetic and Logic Unit (ALU) Control Unit (CU) Storage Unit Arithmetic and Logic Unit (ALU) Performs the arithmetic operations of addition,subtraction, multiplication and division and also performs logical decisions(>,<,>=,<=,<>) and the results thus obtained are supplied back to the memory where they are stored in separate locations for future retrieval.
10
Control Unit (CU) Control unit co-ordinates the operations of the other two units. It consists of electronic circuits. It obtains instructions from the main memory interprets them, decides the action to be taken and directs other units to execute them. It keeps to check a correct information flow in the computer system. Normally the instructions are executed sequentially (one after the other) in the machine. In order to execute a program the computer control unit examines each program instruction in memory starting with the first and sends out the command signals appropriate for carrying out the instruction.
11
Main Storage or Primary Storage
Main Storage is divided into a series of locations each of which may contain either a data item or an instruction . Every location has an address and a value. The location address is used by the computer to refer to a particular location just as a street address is used to refer to a particular house. The value is stored in the location , just as a certain person lives in a house at particular address. It stores information that arrives via the Input Unit so that this information is available to the ALU when the actual calculations are to be performed. It also retains the results of ALU’s calculations until they can be presented to the user via the output unit Main Storage is measured in Kilo Bytes(kb)/Mega Bytes(mb)
12
BIT is an abbreviation of Binary digIT and is the smallest unit of information.
A string of fourt bits is called a NIBBLE A string of eight bits is called a BYTE The smallest unit of data that we can normally handle is a character also called BYTE. 4 Bits NIBBLE 8 Bits BYTE 1024 BYTES - 1 Kilo Byte ( 2e10 Bytes) 1024 KBs Mega Byte (2e10*2e10 Bytes) 1024MBs Giga Byte (2e10*2e10*2e10 Bytes) The size of the computer’s memory is usually expressed in KB’s and MB’s
13
Eg:- The memory of a personal computer has a computer of 16MB
Eg:- The memory of a personal computer has a computer of 16MB. Thus as many as 16*1024*1024=1,67,77,216 characters or instructions can be stored in the computer’s memory. If the entire memory is used to represent character data , then over 2,00,000 names and addresses can be stored within the computer at any time assuming so characters for each name and address. If the memory is used to represent numeric data rather than names and addresses, then more than 4 million individual numbers can be stored at any one time, assuming each numeric quality requires 4 bytes of memory.
14
4. Secondary Storage 0r Auxiliary Storage devices:
Main storage is used to retain active information , but because it is relatively expensive most information is kept in the less costly secondary storage Eg:- Magnetic Tapes, Floppies, Hard Disk etc…..
15
Mini Floppy Diskettes(Disks)
Mini Floppy Disks are 5.25 inch disks . There are two types of minifloppies. The first type known as Double Sided Double Density (DSDD or 2SDD) disks store 360kb of data. Double sided means the disk is used on both sides. The second type is known as Double Sided High Density (DSHD/2SHD) and can store 1.2 MB of data. Visibly , there is no difference between the two types and one has to see the label on the disk to know whether it is a 360KB or 1.2 MB floppy
16
Differences between Main Memory and Auxiliary Memory
Micro Floppy Diskettes: Micro Floppy Diskettes are 3.5inch size disks. There are two types of microfloppies. The first type can store 720KB of data and is known as Double Sided Double Density (DSDD/2SDD). The second type can store 1.44 MB of data. Visibly, there is no difference between two types of microfloppies. One has to see the label to know whether it is a 720KB or 1.44MB disk. The speed of floppy disk drive is in the order of 366rpm with a transfer rate of 20KB per second. Differences between Main Memory and Auxiliary Memory
17
What is an Operating System (OS)
An Operating system (OS)is an organized set of collection of software programs that controls the overall operation of the computer system. It controls and directs the flow of data and instruction from one part of computer to another. A computer itself is nothing but a collection of various hardware devices such as the keyboard , the visual display unit, the CPU etc. It is the operating system that makes these independent hardware devices, although inter connected by cables, a single entity which is both easy to use and manage. OS acts as an interface between the user and the computer system. It is only due to the presence of the OS that the user does not have to bother about the technical details and the functional aspects of each of the hardware components of the system. All he needs to do is to present the problem to the OS in a language that can be understood by the OS and get the results.
18
MS-DOS(Micro Soft Disk Operating System)
MS-DOS was developed to run with the Intel 8088 chip. IBM developed its own version of MS-DOS calling it PC-DOS. One great advantage of this is that any package written to run under MS-DOS is able to be used on a variety of different machines which use the same OS. UNIX UNIX is multi-user cost of the machine is shared by many users. Availability of shared data-databases System access from remote places through MODEMS 2. Multi –tasking capability concurrent running of more than one program no built in constraint on degree of concurrent work
19
3. Portability Most of the UNIX –OS can be easily transported to other machine Application programs in HLL like C, PASCAL etc are easily transported across unix systems. ROM (Read Only Memory) It is a hardware memory chip that has been preloaded with software. The computer reads the program in ROM and executes it, but it cannot modify the programs in ROM. Major portions of OS are placed in ROM , benefit is security. Because ROM can’t be modified, the OS cannot be altered. Popular application of ROM is to contain a special program called BOOT STRAP LOADER when power is turned on or reset button is pressed, the computer automatically copies the BOOT STRAP LOADER from RAM to RAM and begins executing it.
20
The BOOT STRAP LOADER then reads in a fresh copy of the OS from disk and the computer begins executing the OS. IF the OS in RAM is destroyed by a mal functioning user program the user must reboot the OS in order to proceed. RAM(Random Access Memory/Primary Memory/User Memory) Data can be both read from and return to RAM. IT is a volatile memory and is used for temporary storage of data or programs Compiler Compiler is a translator program used to translate the programs written in a HLL into a machine language. While carrying out the translation work,the compiler scans all the lines of the program as a precondition and detects all the syntactical errors, if any. When there are no errors it translates the program and gives the signal accordingly
21
Interpreter An Interpreter which is also a translator program like compiler,used to translate a program written in HLL into machine language. But the difference between a compiler and an interpreter is that an interpreter translates a program line by line and notifies the errors then and there itself. Whereas a compiler translates the entire program as a whole. So naturally the speed of translation is slower in the case of interpreter. Compiler and Interpreters are available for languages like Basic, APL, Pascal etc. But languages like Fortran,Cobol,C etc use only compilers. Eg:-
22
Interpreter: Minute by minute speech by a North Indian politician. Suppose a North Indian politician comes to A.P for campaigning he does not know telugu. So translator is necessary. The politician speaks in Hindi and the translator simultaneously gives the speech in Telugu. In this process less memory is needed but more time is taken Compiler Speech after speech. More memory is needed but less time is taken in this process. ( If there are any repetitions in the speech they are deducted and on the whole the speech will be given)
23
C seems a strange name for a programming language
C seems a strange name for a programming language. But this strange sounding language is one of the most popular computing languages today. C was an off spring of the ‘Basic Combined Programming Language (BCPL)’ called B, developed in 1960’s at Cambridge University. B language was modified by Dennis Ritchie and was implemented by Bell Laboratories in 1972. The new language was named C. Since it was developed along with the UNIX operating system, it is strongly associated with UNIX. This operating system which was also developed at bell Laboratories was coded almost entirely in C.
24
Basic Structure of C programs
Documentation Section Link Section Definition Section Global declaration Section Main( ) Function Section { Declaration Part Executable Part } Subprogram Section Function 1 Function 2 Function n
25
The Documentation section consists of a set of comment lines giving the name of the program, the author and other details which the programmer would like to use later. The Link section provides instructions to the compiler to link functions from the system library Definition section defines all symbolic constants There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section. Main function contains two parts , declaration part and executable part. The declaration part declares all the variables used in the executable part, there is atleast one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening braces and ends at the closing brace.
26
The Subprogram section contains all the user defined functions that are called in the main function. User defined functions are generally placed immediately after the main function although they may appear in any order. All sections, except the main function section may be absent when they are not required. Character set of C 1.Letters 2.Digits 3.Special characters 4.white spaces 1. Letters : Upper case A to Z Lower case a to z 2. Digits: to 9
27
3.Special characters: , comma ~ tilde ( left paranthesis . period _ under score ) right paranthesis ; semicolon $ dollar sign [ left brackets : colon % percent sign ] right brackets ? question mark # number sign { left brace ‘ apostrophe & ampersand } right brace “ quotation mark ^ caret * asterisk ! exclaimatic mark minus sign plus sign | vertical bar / slash < less than \ back slash > greater than
28
4. White spaces: Blank spaces Horizontal tab Carriage return New line Form feed Vertical tab Indentifiers & keywords Every word in C program is either classified as an identifier or a keyword Identifiers: Indentifiers are program elements and the name itself suggests , are used to identify or name variables, symbolic constants, functions etc
29
The underscore(_) is considered a letter
RULES: Identifier names must be a sequence of letters and digits and must begin with a letter The underscore(_) is considered a letter Names should not be the same as a keyword C is case sensitive i.e upper and lower case letters are treated differently. Thus the names rate, RATE denote different identifiers. In general we use lower case letters for a variable and function names and uppercase for constants. Maximum number of characters in an identifier should be 14 or 40 (depends on the compiler)
30
Eg:- Pakistan basic_pay x _temperature area india12 747boeing - should not start with a number “ x “ illegal character (“) order-no – illegal character (-) error flag - illegal character (blank space)
31
Keywords There are certain reserved words, called keywords, that have standard predefined meaning in c. These keywords can be used only for their intended purpose, they cannot be used as programmer defined identifiers auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while
32
Note that keywords are all lowercase
Note that keywords are all lowercase. Since uppercase and lowercase characters are not equivalent ,it is possible to utilise an uppercase keyword as an identifier. Normally it is considered a poor programming practice. Constants, Variables and Expressions There are four basic types of constants in C. They are integer constants, floating_point constants,character constants and string constants. RULES: 1.Commas and blank spaces cannot be included within the constant . 2.Constant cab be preceded by a minus (-) 3.The value of a constant cannot exceed specified minimum and maximum bounds
33
Real Constants Integer numbers are inadequate to represent quantities that vary continously, such as distances, heights, temperatures, prices and so on. There quantities are represented by numbers containing fractional parts like Such numbers are called real(floating point) constants. A real number may also be expressed in exponential (or scientific) notation. For example, the value may be written as e2 in exponential notation. e2 means multiply by 10 *10 The general form is mantessa e exponent Range : e–38 to e+38
34
Single Character constants: A character constant is a single character , enclosed in apostrophes (i.e single quotation marks) Eg:- ‘A’ , ‘x’ , ‘3’, ‘?’ Back slash character constants/ Escape sequences Constant Meaning \a bell(alert) \b backspace \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \’ single quote \” double quote \? question mark \\ back slash \ null
35
String Constants: A string constant consists of any number of consecutive character enclosed in double quotation marks. Eg:- “hello” ,”1987” , “well done” , “ ?…!”, “ j+3”, “x” Variable: Variable is the name of a storage location where a data item can be stored. A variable is an identifier that is used to represent some specified type of information within a designated portion of the program. The data must be assigned to the variable at some point in the program. The data item can then be accessed later in the program simply by referring to the variable name. A variable name can be chosen by the programmer in a meaningful way so as to reflect its function or names in the program.
36
Some examples of such names are:
Average, height,total,counter_1, class_strength 1.They must begin with a letter. 2.The length should not be normally more than eight characters 3.Uppercase and lowercase are significant. i.e the variable total is not same as TOTAL or Total 4. The variables name should not be a keyword. 5. White space is not allowed Data types and their sizes 1.Primary/ Fundamental data types 2.User- defined data types 3.Derived data types 4. Empty data set
37
i.integer types (int) Integers are whole numbers with a range of values supported by a particular machine. Generally integers occupy one word of storage and since the word sizes of machines vary , the size of an integer that can be stored depends on the computer. Range of integer is – to (i.e –2e15 to +2e15-1) A signed integer uses are bit for sign and 15 bits for the magnitude of the number.In order to provide some control over the range of numbers and storage space , C has three classes of integer storage, namely short int, int and long int in both signed and unsigned form ii. floating point types(float) Floating point numbers are stored in 4 types with 6 digits of precision.
38
iii. large floating points types with greater accuracy (double )
when the accuracy provided by a float number is not sufficient , the type double can be used to define the number. A double data type number uses 64 bits giving a precision of 14 digits. These are known as double precision numbers. The double type represents the same data type that a float represents but with greater precision. To extend the precision further , we may use long double which uses 80 bits. iv. character types (char) A single character can be defined as a character (char) type data. Characters are usually stored in 1 byte (8 bits) of internal storage. The qualifier signed or unsigned may be explicitly applied to char. While unsigned characters have values between 0 to 255. Signed characters have values for –128 to 127
39
How to declare primary data types?
Data-type V1,V2………Vn V1, V2……..Vn are the names of the variables . Variables are separated by commas. A declaration statement must end with a semicolon. Eg: Main() { float x,y; int code; short int count; long int amount; double deviation; unsigned n; char c; /*computational statements*/ ……………….. }
40
User- defined data types
The user- defined data type identifier can be used to declare variables. typedef type identifier; where type refers to any one of the primary data type (int,float,double,char). Eg: typedef int units; typedef float marks; units and marks can be used declare variables as units batch1,batch2; marks name1,name2;
41
Operators and Expressions
An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. C operators can be classified into a number of categories . They include Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operators Bitwise operators Special operators
42
Arithmetic Operators : The arithmetic operators perform arithmetic operations.
Operator purpose addition or unary plus subtraction or unary minus multiplication / division % modulo division/ remainder after integer division The data item that operates act upon are called operands. The operands acted upon by arithmetic operators must represent numeric values. The remainder operator (%) requires that both operands be integers and the second operand be non- zero.
43
Similiarly the division operator(/) requires that the
second operand be non-zero. Division of one integer quantity by another integer is referred to as integer division. This operation always results in a truncated quotient. On the other hand, if a division operation is carried out with two floating point numbers or with are floating point number and integer, the result will be a floating point quotient. The operators within C are grouped heirarchically according to their precedence. Among the arithmetic operators *,/ and % fall into one precedence group and +,- fall into another .
44
The first group has a higher precedence than the second
The first group has a higher precedence than the second. Thus multiplication, division and remainder operations will be carried out before addition and subtraction. Another important consideration is the order in which consecutive operations within the same precedence group are carried out. This is known as associativity with each of precedence groups described above, the associativity is left to right. i.e * / % (precedence level1) (precedence level2) Associativity is from left to right If a=10 b= Expression Value a+b a-b a*b a/b a%b
45
If v1=12.5 v2=2 Expression Value
If r1= r2= r1+r r1-r r1*r r1/r If i=7,f=5.5,c= (i+c)-(2*f/5) = (7+119)-(2*5.5/5) = 126-(2*1.1) =
46
If i=8,j=15,k=4 2*((i%5)*(4+(j-3)/(k+2)))
= 2*((8%5)*(4+(15-3)/(4+2))) = 2*(3*(4+12/6)) = 2*(3*(4+2)) = 2*3*6 = 36 if x=8.8,y=3.5, z= -5.2 a. (x/y)+z = (8.8/3.5)-5.2 = –5.2 = b. 2*x/(3*y) = 2*8.8/10.5 = 17.6/ =
47
2*x/3*y = 2*8.8/3*3.5 = 17.6/3*3.5 = *3.5 = 2*y+3*(x-z) = 2* *( ) = 7.0+3*14 =49 if i =8,j=5 2*((i/5)+(4*(j-3))%(i+j-2)) = 2*(1+(4*2)%11) = 2*(1+8%11) = 2*(1+8) =2*9=18 5+8*7 –24*2*1/3 = *1/3 = /3 = =45 9 –12/(3+3)*(2-1) = 9-12/6*1= 9-2*1 =7
48
Relational Operators We often compare two quantities and depending on their relation , take certain decisions. For example, we may compare the age of two persons or the price of two items and so on. These comparisions can be done with the help of relational operators. Operator 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 The relational operators <,<=,>,>= are of the first precedence group and the equality operators ==,!= fall into a separate precedence group.
49
These six operators are used to form logical expressions which represent conditions that are either true or false. The resulting expressions will be of type integer, since true is represented by the integer value 1 and false is represented by the value 0 If I=1,j=2,k= Expression Interpretation value i<j true (i+j)>=k true (j+k)>(i+5) false k!= false j== true simple relational expression contain only one relational operator and takes the following form ae-1 relational operator ae-2
50
3.Logical Operators In addition to relational operators , C contains three logical operators also called logical operators. Operator meaning && logical AND || logical OR ! logical NOT if I=7 , f=5.5 ,c = 119 Expression Interpretation Value (i>=6)&&(c==119) true (i>=6)|| (c==119) true (f<11)&&(i>100) false (f>5) true !(f>5) false i<= false !(i<=3) true i>(f+1) true !(i>(f+1)) false
51
4.Assignment operators Assignment operators are used to assign the result of an expression to a variable. C has a set of short hand assignment operators of the form V op = Exp Where V is a variable Op is arithmetic operator Exp is a expression Shorthand assignment operators Statement with simple assignment operator statement with shorthand operator a=a a+=1 a=a a-=1 a=a*(n+1) a*=n+1 a=a/(n+1) a/=(n+1) a=a%b a%=b
52
5.Increment and decrement operators:
C has two very useful operators not generally found in other languages. These are the increment and decrement operators and -- The operator ++ adds 1 to the operand and while – subtracts 1 from the operand. ++ increment operator pre increment post increment --decrement operator pre decrement post decrement a=15 printf(“\n a=%d”,++a) ; increment a and then print printf(“\n a=%d”,a++) ; printf first and increment later printf(“\n a=%d”,--a); decrement a and then print printf(“\n a=%d”,a--); print first and decrement later
53
6. Conditional Operator Simple conditional operations can be carried out with the conditional operator ( ? : ) .An expression that makes use of the conditional operator is called a conditional expression. A conditional expression is written in the form Exp1 ? Exp2 : Exp3 Expression 1 is evaluated first, if it is true then the expression2 is evaluated .If expression1 is false expression3 is evaluated. Note that only one of the embedded expressions either expression2 or expression3 is evaluated when determining the value of a conditional expression. Eg: x=(a>b) ? a: b if (a>b) x=a else x=b
54
7.Bitwise operators : C has a distinction of supporting special operators known as bitwise operators for manipulation of data at bit level. These operators are used for testing the bits, or shifting them right or left. Bitwise operators may not be applied to float or double Bitwise operators Operator meaning & bitwise AND | bitwise OR ^ bitwise exclusive OR << shift left >> shift right ~ one’s compliment
55
8.Special Operators Special operators of interest such as comma operator, size of operator Comma operator: The comma operator can be used to link the related expression together. A comma linked list of expressions are evaluated left to right and the value of right most expression in the value of the combined expression. Eg:- value = (x=10,y=5,x+y); First assigns the value of 10 to x , then assigns 5 to y and finally assigns 15 to value Sizeof operator The sizeof operator returns the number of bytes the operand occupies. The operand may be variable , a constant or a data type qualifier m= sizeof(sum); n = sizeof(long int); k= sizeof(int);
56
Type cast operator / coercian operator (coerce=force)
avg =sum/n = 50/3 =16 (accuracy is lost) =50/(float)3 = 2. x= x=(int)16.5 = 16 USE OF CASTS Example Action X=(int) is converted to integer by truncation A=(int)21.3/(int) evaluated as 21/4 and the result will be 5 B= (double)sum/n division is done in floating point mode Y=(int)(a+b) the result of (a+b) is converted to integer Z= (int)a+b a is converted to integer and then added to b P= cos((double)x) converts x to double before using it
57
Over all operator precedence groups
Operator Category Operators Associativity Unary operators ! size of R to L Arithmetic multiply * / % L to R Divide and remainder Arithmetic add and subtract L to R Relational operators <,<=,>,>= L to R Equality operators ==,!= L to R Logical AND && L to R Logical OR || L to R Conditional operator ?: R to L Assignment operators = += -= *= /= %= R to L
58
Type conversion rules These rules apply to arithmetic operations between two operators with dissimilar data types. If one of the operands is long double the other will be converted to long double and the result will be long double Otherwise,if one of the operands is double , the other will be converted to double and the result be double otherwise, if one of the operands is float,the other will be converted to float and the result will be float otherwise, if one of the operands is unsigned longint, the other will be converted to unsigned long int and the result will be unsigned long int. otherwise, if one of the operands is long int and the other is unsigned int, then if unsigned int can be converted to long int , the unsigned int operand will be converted as such and the result will be long int.
59
otherwise,both operands will be converted to unsigned long int and the result will be unsigned long int Otherwise if one of the operands is unsigned int, the other will be converted to long int and the result will be long int. Otherwise, if one of the operands is unsigned int, the other will be converted to unsigned int and the result will be unsigned int. If none of the above conditions applies, then both operands will be converted to int and the result will be int. Assignment rules A floating point value may be truncated if assigned to an integer identifier A double precision value may be rounded if assigned to a floating point identifier An integer quantity may be altered if it is assigned to a shorter integer identifier or to a character identifier
60
Input / Output functions
An input/output function can be accessed from anywhere within a program simply by writing the function name, followed by a list of arguments enclosed by paranthesis Scanf Printf Getchar Putchar Gets Puts Entering Input –data (the Scanf function) Input data can be entered into the computer from a standard input device by means of the C library function scanf. This function can be used to enter any combination of numerical values,single characters and strings . The function returns the number of data items that have been entered successfully . In generall terms , the scanf function is written as Scanf (control string , arg1,arg2,……….argn)
61
Where control string refers to a string containing certain required formatting information and arg1,arg2,…………..argn are arguments that represent the individual input data items. The arguments are written as variables or arrays, whose types match the corresponding character groups in the control string. Each variable name must be preceded by an ampersand(&). However, array names should not begin with an ampersand. Commonly used conversion characters for Data input Character Meaning c data item is a single character d data item is a decimal integer e data item is a floating point value f data item is a floating point value g data item is a floating point value h data item is a short integer i data item is a decimal, hexa decimal or octal integer
62
o data item is an octal integer
s data item is a string followed by a whitespace character u data item is an unsigned decimal integer. x data item is a hexadecimal integer […] data item is a string which may include white space characters Eg: #include<stdio.h> main() { char item[20]; int partno; float cost; scanf(“%s%d%f”,item,&partno,&cost); }
63
Within the scanf function , the control string is “%s%d%f”
Within the scanf function , the control string is “%s%d%f”. It contains three character groups. The first character group,%s indicates that the first argument(item) represents a string . The second character group %d indicates that the second argument (&part no) represents a decimal integer value and the third character group %f indicates that the third argument (&cost) represents a floating point value. Notice that the numerical variables part no and cost are preceded by ampersands within the scanf function. An ampersand does not precede item, however , since item is an array name. Suppose C program contains the following statements #include<stdio.h> main() { char line[80]; scanf(“%[^/n]”,line); }
64
Notice the blank space preceding %[^/n] to ignore any unwanted characters that may have been entered previously. When the scanf function is executed, a string of undetermined length (but more than 79 characters will be entered from the standard input device and assigned to line. There will be no restrictions on the characters that comprise the string , except that they all fit on one line. For example , the string C is a very good language and easy to understand #Include<stdio.h> main() { int a,b,c; scanf(“%3d%3d%3d”,&a,&b,&c); }
65
when the program is executed, these integer quantities will be enetered from the standard input device. #include<stdio.h> main() { int i; float x; char c; scanf(“%3d %8.3f %c”,&i,&x,&c) ; } i= c=t
66
Writing output –data the PRINTF function
Output data can be written from the computer onto a standard output device using the library function PRINTF. This function can be used to output any combination of numerical values, singlecharacters and strings i.e the PRINTF function moves data from the computer’s memory to the standard output device,whereas the scanf function enters data from the standard input device and stores it in the computer’s memory. Printf function is written as Printf(control string, arg1,arg2,…………argn) Where control string refers to a string that contains formatting information and arg1,arg2…argn are arguments that represent the individual output data items. The arguments can be written as constants , single variable or array names or more complex expressions
67
Conversion Character (for data output) Meaning
c data item is displayed as a single character d data item is displayed as a signed decimal integer e data item is displayed as floating point value with an exponent f data item is displayed as a floating point value without an exponent g data item is displayed as a floating point value using either e-type or f-type conversion depending on value. Trailing zeros and trailing decimal point will not be displayed i data item is displayed as a signed decimal integer o data item is displayed as an octal integer, without a leading zero s data item is displayed as a string u data item is displayed s an unsigned decimal integer x data item is displayed as a hexadecimal integer
68
#include<stdio.h>
#include<math.h> main() { float i=2.0,j=3.0; printf(“%f%f%f%f”,i,j,i+j,sqrt(i+j)); } Reading and writing a line of text { char line[80]; scanf(“%[^\n]”,line); printf(“%s”,line); }
69
The format specification for printing an integer number is %wd
Where w specifies the minimum field width for the output The output of a real number may be displayed in decimal notation using the following format specification %w.pf The integer w indicates the minimum number of positions that are to be used for the display of the value and the integer p indicates the number of digits to be displayed after the decimal point the value when displayed is rounded to p decimal places and printed in the field of w columns.
70
3. A single character can be displayed in a desired position using the format %wc
The character will be displayed right justified in the field of w columns 4. The format specifications for outputting strings is similar to that of real number. It is of the form %w.ps where w specifies the field wdth and p instructs that only the first p characters of the string are to be displayed. Eg: %s New Delhi %5s New D %20.10s New Delhi Single character input - the getchar() function Single characters can be entered into the computer using C library function getchar. The getchar function returns a single character from a standard input device.
71
Character variable = getchar()
Where character variable refers to same previously declared character variable Eg: char c; C= getchar(); Single character output – the putchar() function Single characters can be displayed using C library function putchar. This function is complementary to the character input function getchar. The putchar function like getchar is a part of the standard C I/O library. It transmits a single character to a standard output device Putchar(character variable) Eg:- Char c; Putchar(c);
72
Gets( ) and puts( ) function
C contains a number of other library functions that permit some form of data transfer into or out of the computer. The gets and puts functions facilitate the transfer of strings between the computer and the standard input/output devices. Each of these functions accepts a single argument. The argument must be a data item that represents a string (e.g a character array). The string my include white spaces characters. In the case of gets(), the string will be entered from the keyboard and will terminate with a newline character (i.e the string will end when the user presses the enter key). The gets and puts functions offer simple alternatives to the use of scanf and printf for reading and displaying strings as illustrated in the following example
73
Eg:- #include<stdio.h> main() { char line[80]; gets(line); puts(line); } This program uses gets and puts rather than scanf and printf to transfer the line of text into and out of the computer
74
PREPROCESSOR DIRECTIVES
Directive Function #define Defines a macro substitution #undef Undefines a macro #include Specifies the files to be included #ifdef Tests for a macro definition #endif Specifies the end of #if #ifndef Tests whether a macro is not defined #if Tests a compile time condition #else Specifies alternatives when #if test fails #define count 100 #define false 0 #define subjects 6 #define pi #define capital “DELHI”
75
#include<filename>
#include is a preprocessor statement filename is a header file Header files included in C are <ctype.h> character testing and conversion function <math.h> mathematical function <stdio.h> standard I/O library function <stdlib.h> utility functions such as string conversions, routines memory allocation routines , random number generated etc <string.h> string manipulation functions <time.h> time manipulation function
76
Library functions The C language is accompanied by a number of library functions that carry out various commonly used operations or calculations. There are library functions that carry out various commonly used operations or calculations. There are library functions that carry out standard input/output operations(Eg:- read and write characters read and write numbers, open and close files test for end of file etc) functions that perform operations on characters (Eg convert from lower - to –uppercases, test to see if a character is upper case etc) functions that perform operations on strings(Eg copy a string, compare strings, concatenate strings etc) and functions that carry out various mathematical calculations (Eg evaluate trigonometric ,logarithmic and exponential function, compute absolute values, square roots etc).A library function is accessed simply by writing the function name, followed by a list of arguments that represent information being passed to the function. The arguments must be enclosed in parenthesis and separated by commas. The arguments can be constants, variable names or more complex expressions. The parenthesis must be present , even if there are no arguments.
77
Library functions Mathematical functionsLogarithmic functionsTrigonometric functionsinput/output functionscharacter manipulation functions Function Data type returned Task <ctype.h> isalnum (c ) int determine if arguments is alphanumeric. Return nonzero value if true;0 otherwise isalpha (c ) int determine if argument is alphabetic. Return nonzero value if true. 0 otherwise isascii(c) int determine if argument is an ascii character Return nonzero value if true. 0 otherwise iscntrl( c) int determine if argument is an ascii control character . Return nonzero value if true. 0 otherwise isdigit ( c) int determine argument is a decimal digit. Return nonzero value if true.0 otherwise
78
isgraph(c ) int determine if argument is a graphic printing ascii
isgraph(c ) int determine if argument is a graphic printing ascii character Return nonzero value if true.0 otherwise islower(c ) int determine if argument is lowercase. Return nonzero value if true. 0 otherwise isodigit ( c) int determine if argument is an octal digit. Return nonzero value if true.0 otherwise isprint (c ) int determine if argument is a printing ASCII character. Return non zero value if true. 0 otherwise Ispunct( c) int determine if argument is a punctuation character. Return non zero value if true. 0 otherwise isspace(c ) int determine if argument is white space character. Return isupper(c ) int determine if argument is uppercase. Return nonzero value if true. 0 otherwise isxdigit ( c) int determine if argument is a hexadecimal digit. Return non zero value if true. 0 otherwise toascii (c ) int convert value of argument to ASCII tolower (c ) int convert letter to lower case toupper( c) int convert letter to upper case.
79
<math.h> acos(d) double return the arc cosine of d asin(d) double return the arc sine of d atan(d) double return the arc tangent of d atan2(d1,d2) double return the arc tangent of d1/d2 ceil( d) double return a value rounded upto the next higher integer cos(d) double return the cosine of d cosh(d) double return hyperbolic cosine of d. exp(d) double raise e to the power d fabs(d) double return the absolute value of d floor(d) double return a value rounded down to the next lower integer fmod(d1,d2) double return the remainder of d1/d2 labs(l) long int return absolute value of 1. log(d) double return the natural logarithm of d. log10(d) double return the logarithm (base 10) of d. pow(d1,d2) double return d1 raised to the d2 power. Sin(d) double return the sine of d Sinh(d) double return the hyperbolic sine of d. Sqrt(d) double return the square root of d Tan (d) double return the tangent of d Tanh(d) double return the hyperbolic tangent of d
80
<stdio.h> fclose(f) int close file f. Return 0 if file is successfully closed feof(f) int determine if an end of ile condition has been reached. If so, return a nonzero value. Otherwise return 0 fgetc(f) int enter a single character form file f. fgets(s,i,f) char enter string s, containing i characters, from the file f fopen(s1,s2) file open a file named s1 of type s2. Return a pointer to the file fprintf(f,…) int send data items to file f fputc(c,f) int send a single character to file f fread(s,i1,i2,f) int enter i2 data items,each of size i bytes,from file f to string s fscanf(f,…) int enter data items from file f fseek( f,l,i) int move the pointer for file f a distance 1bytes from location i ftell(f) long int return the current pointer position within file f fwrite(s,i1,i2,f) int send i2 data items,each of size i1 bytes from string s to file f getc(f) int enter a single character from file f getchar( void) int enter a single character from thr standard input device gets(s) char enter string s from the standard input device printf(…) int send data items to the standard output device putc(c,f) int send a single character to file f putchar(c) int send a single character to the standard output device puts(s) int send string s to the standard output device rewind(f) void move the pointer to the beginning of file f scanf(…) int enter data items from the standard input device
81
/* CONVERSION OF FAHRENHEIT INTO CELSIUS (fareinht.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { float f,c; clrscr(); printf("\n enter the fahrenheit temperature: "); scanf("%f",&f); c=(5.0/9.0)*(f-32); printf("\n the temperature in celsius is : %f",c); }
82
/*LARGEST OF THREE GIVEN NUMBERS (large3.c) */
#include<stdio.h> main() { float a,b,c,big; printf("\n Input the values of a,b,c"); scanf("%f%f%f",&a,&b,&c); big=a; if (b>big) big=b; if (c>big) big=c; printf("\n largest of three numbers= %f",big); }
83
/* CONVERSION OF LOWER CASE CHARACTER TO ITS UPPER CASE (lowtoup.c)*/
#include<stdio.h> #include<ctype.h> main() { char alphabet; printf(" enter an alphabet"); alphabet=getchar(); if (islower(alphabet)>0) putchar(toupper(alphabet)); else putchar(tolower(alphabet)); }
84
/* fibonacci numbers using goto (fibgoto.c)
#include<stdio.h> main() { int fib=0,i=0,a=1,n; printf("\n enter the maximum limit of n:"); scanf("%d",&n); label: printf("\n %d",fib); i=a; a=fib; fib=i+a; if (fib<n) goto label; }
85
/* INCOME TAX */ #include<stdio.h> #include<conio.h> main() { float basic,da,hra,gross,tpi,tax,savings,pf,lic,nsc,others,taxded; printf("\n enter the basic"); scanf("%f",&basic); da=basic*0.36; hra=basic*0.15; gross=basic+da+hra;
86
tpi=gross-20000; if (tpi<= ) tax=0; else if ((tpi>50000) && (tpi<=150000)) tax=tpi*0.1; else tax=tpi*0.2; printf("\n enter pf,lic,nsc,others"); scanf("%f%f%f%f",&pf,&lic,&nsc,&others); savings=pf+lic+nsc+others; taxded=savings*0.20; tax=tax-taxded; if (tax<=0) printf("\n there is no need of paying the tax"); else printf("\n tax to be paid = %f",tax); }
87
/* NEWTON RAPHSON METHOD
for the function (x*x*x)-(4*x*x)+x+6 (newtonra.c) */ #include<stdio.h> #include<math.h> #include<conio.h> main() { int x0; double x,x1,h,fx,dfx; clrscr(); printf("\n enter the expected root"); scanf("%d",&x0); x=x0; repeat: { fx=(x*x*x)-(4*x*x)+x+6; dfx=(3*x*x)-(8*x)+1; x1=x-(fx/dfx); h=fabs(x1-x); x=x1; printf("\n x=%f f(x)=%f",x,fx); } if (fabs(h)> ) goto repeat; printf("\n root of the given function is = %f",x);
88
/* CLASS OF AN INPUT CHARACTER */
#include<stdio.h> #include<ctype.h> main() { char character; printf("\n press any key"); character=getchar(); if (isalpha(character)>0) printf("\n the character is a letter"); else if (isdigit(character)>0) printf("\n the character is a digit"); else printf("\n the character is not alphanumeric"); }
89
Control statements Conditional execution / BranchingLooping SelectionIfwhileswitchif-elsedo whileforIf statement If statement can be implemented in different forms depending on the complexity of conditions to be tested 1.simple if statement 2.if…else statement 3.nested if…else statement 4.else if ladder 1.Simple if statement The general form of a simple if statement is if (test expression) { statement –block; } statement –x;
90
the statement block may be a single statement or a group of statements
the statement block may be a single statement or a group of statements . If the test expression is true, the statement –block will be executed . Otherwise the statement –block will be skipped and execution will jump to the statement-x. Remember , when the condition is true both the statement – block and the statement-x are executed in sequence.
91
/*PRIME NUMBER CHECKING (prime.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int n,k=2; clrscr(); printf("\n enter the number to be checked"); scanf("%d",&n); if (n==2) printf("\n given number is prime \n"); goto end; }
92
repeat: if(n%k==0) { printf("\n given number is not prime"); goto end; } k=k+1; if(k<=sqrt(n)) goto repeat; } printf("\n given number is prime \n"); end: }
93
/* PALENDROME NUMBER CHECKING (palen.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int n,l,rn=0; clrscr(); printf("\n enter the number to be checked"); scanf("%d",&n); l=n; repeat: rn=rn*10+n%10; n=n/10; if(n!=0) goto repeat; if (l==rn) printf ("\n the given number is palendrome"); else printf("\n given number is not palendrome"); }
94
2.if…else statement The general form of an if statement which excludes the else clause is If ( expression) { true-statement (s); } else { false-statement(s); } statement-x; If the expression is true then true-statement(s) will be executed . Otherwise i.e if expression is false then false-statement(s) will be executed.
95
3.Nested if…else statements
When a series of decisions are involved we may have to use more than one if…else statement in nested form as follows if (testcondition1) { if (test condition 2) statement(s); } else statement-x;
96
4.else if ladder There is another way of putting ifs together when multipath decisions are involved . A multipath decision is a chain of ifs in which the statement associated with each else is an is. The general form is: if (condition 1) statement1; else if (condition 2) statement2; else if (condition 3) statement3; else if (condition 4) statement n; else default – statement; statement-x;
97
/. ELECTRICITY BILL @ 1-50 Rs. 1. 35 51-200 Rs. 2. 95 201-400 Rs. 4
/* ELECTRICITY Rs Rs Rs above 400 Rs.5.25 (elecbill.c)*/ #include<stdio.h> #include<math.h> #include<conio.h> main() { int scno,lmr,cmr,units; float bill; clrscr(); printf("\n ENTER THE CONNECTION NUMBER :"); scanf("%d",&scno); printf("\n ENTER THE LAST METER READING AND THE CURRENT METER READING :"); scanf("%d \t %d",&lmr,&cmr); units=cmr-lmr; if (units>1 && units<=50) bill=units*1.35; else if (units>=51 && units <=200) bill=67.50+(units-50)*2.95;
98
else if (units>=201 && units<=400) bill=510+(units-200)*4.50;
else bill=1410 +(units-400)*5.25; clrscr(); printf("\n A.P.STATE ELECTRICITY BOARD"); printf("\n A.P.TRANSCO"); printf("\n "); printf("\n SCNO LMR CMR UNITS BILL "); printf("\n "); printf("\n %d %d %d %d %8.2f",scno,lmr,cmr,units,bill); }
99
/* TYPE OF THE TRIANGLE FORMED BY THE GIVEN 3 SIDES */
#include<stdio.h> main() { float a,b,c; printf("\n enter the values of a,b,c"); scanf("%f%f%f",&a,&b,&c); if (((a+b)>c) && ((b+c)>a) && ((c+a)>b)) printf("\n the 3 sides form a triangle"); if ((a==b) && (b==c)) printf("\n the triangle formed is an equilateral"); if (((a==b)&&(a!=c)) || ((b==c)&&(b!=a)) || ((c==a)&&(c!=b)))
100
printf("\n the triangle formed is isosceles");
if (((a*a)==(b*b)+(c*c)) || ((b*b)==(c*c)+(a*a)) || ((c==a) && (c!=b))) printf("\n triangle formed is right angled"); else if (((a*a)>(b*b)+(c*c)) || ((b*b)>(c*c)+(a*a)) || ((c*c)>(a*a)+(b*b))) printf("\n triangle formed is obtuse"); else printf("\n triangle is acute"); if ((a!=b) && (b!=c) && (c!=a)) printf("\n triangle formed is scalene"); } else printf("\n the given sides do not form a triangle");
101
switch statement The switch statement causes a particular group of statements to be chosen from several available groups. The selection is based upon the current value of an expression which is included within the switch statement is: switch (expression) { case label1: statement(s); break; case label2: default : }
102
statement-x; The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transfering the control to the statement-x following the switch. The default is an optional case. When present, it will be executed if the value of the expression does not match with any of the case values. If not present , no action takes places if all matches fail and the control goes to the statement-x.
103
Tips on switch statement
The case labels need not be arranged in any order but the case labels have to be unique. We can use character values in case and switch. We can mix integer and character constants in different cases of a switch Even if there are multiple statements to be executed in each case , there is no need to enclose these within a pair of brackets. If we have no default case, then the program simply breaks out of the entire switch and continues with the next instruction that follows the control structure. The break statement when used in a switch takes the control outside the switch. However , use of continue will not take the control to the beginning of switch. In principles a switch may occur within another switch but in practice it is rarely done. Such statements are called nested switch statements. Sometimes there may not be any statement in some of the cases in switch, but still they might be useful. The switch statement is very useful while writing menu driven programs.
104
/* ROOTS OF A QUADRATIC EQUATION (quadratc.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int choice; float a,b,c,disc,r1,r2,real,imag; clrscr(); printf("\n ENTER THE COEFFICIENTS OF THE FUNCTION"); scanf("%f%f%f",&a,&b,&c); disc=(b*b)-(4*a*c); if (disc>0) choice=1; if (disc==0) choice=2; if (disc<0) choice=3;
105
switch(choice) { case 1: printf("\n THE ROOTS ARE REAL AND UNEQUAL"); r1=(-b+sqrt(disc))/(2*a); r2=(-b-sqrt(disc))/(2*a); printf("\n THE ROOTS ARE %f \t %f ",r1,r2); break; case 2: printf("\n THE ROOTS ARE REAL AND EQUAL"); r1=-b/(2*a); r2=r1; printf("\n THE ROOTS ARE %f \t %f",r1,r2); break; case 3: printf("\n THE ROOTS ARE IMAGINARY"); real=-b/(2*a); imag=sqrt(-disc)/(2*a);
106
printf("\n THE ROOTS ARE %f+%fi \t %f-%fi",real,imag,real,imag);
break; }
107
/* DISCOUNT.C upto 50,000 >50000 and <1lakh >1lakh LAXMI PUBS % % % DEEPTHI PUBS % 15% % TATA Mc.GRAWHILL 2% 4% % SULTAN CHAND % 20% % */ #include<stdio.h> main() { int choice; float amount,discount,nett; clrscr(); printf("\n enter the amount"); scanf("%f",&amount); printf("\n 1.Laxmi pubs"); printf("\n 2.Deepthi pubs"); printf("\n 3.Tata Mc.graw");
108
printf("\n 4.Chand"); printf("\n enter your choice"); scanf("%d",&choice); switch(choice) { case 1: if (amount<50000) discount=0.05; else if(amount<100000) discount=0.1; else discount=0.15; break; case 2: if (amount<50000) discount=0.1; else if(amount<100000) discount=0.15; else discount=0.25;
109
case 3: if (amount<50000) discount=0.02; else if(amount<100000) discount=0.04; else discount=0.08; break; case 4: if (amount<50000) discount=0.15; else if(amount<100000) discount=0.2; else discount=0.30; defualt : printf("\n wrong choice, try again"); } nett=amount-(amount*discount); printf("\n Actual amount=%f", amount); printf("\n Amount you have to pay after discount=%f",nett);
110
While The simplest of all the looping structures in C is the while statements The basic format of the while statement is While (test condition) { body of the loop } The while is an entry controlled loop statement. The test condition is evaluated and if the condition is true , then the body of the loop is executed . After execution of the body , the test – condition is once again evaluated and if it is true the body is executed once again . This process of repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statement immediately after the body of the loop. The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements. The braces are needed only if the body contains two or more statements. However, it is a good practice to use braces even if the body has only one statement.
111
/* SUM OF THE DIGITS IN A GIVEN NUMBER (sumdigit.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { long int num,sum=0,rem; clrscr(); printf("\n ENTER THE NUMBER"); scanf("%ld",&num); while(num>9) rem=num%10; sum=sum+rem; num=num/10; } sum=sum+num; printf("\nSUM OF THE DIGITS OF THE GIVEN NUMBER IS:%ld",sum); }
112
/* IMAGE OF A GIVEN NUMBER (numrev.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int num,rem; clrscr(); printf("\n ENTER THE NUMBER \n"); scanf("%d",&num); printf("\n IMAGE OF THE GIVEN NUMBER IS:\n"); while(num>9) rem=num%10; printf("%d",rem); num=num/10; } printf("%d",num); }
113
/* FIBONACCI SERIES 1,1,2,3,5,8,13,….(FIB.C)
#include<stdio.h> #include<math.h> #include<conio.h> main() { int fib,i=1,a=0,n; clrscr(); printf("\n enter the maximum limit of the fibonacci numbers"); scanf("%d",&n); fib=i+a; while (fib<n) printf("\n %d",fib); i=a; a=fib; } }
114
/* TO GENERATE STAR PYRAMID OF RIGHT ANGLED TYPE (tristar.c)*/
#include<stdio.h> #include<conio.h> main() { char star='*'; int k,n,c; k=25; n=1; clrscr(); while(n<=20) printf(" "); c=1; while(c<=n) printf("%c",star); c=c+1; }
115
#include<stdio.h> main() { int r1,r2;
printf("\n"); n=n+1; k=k-1; } /* TO GENERATE ODDS BETWEEN TWO GIVEN NUMBERS (odds.c)*/ #include<stdio.h> main() { int r1,r2; printf("\n enter any two numbers"); scanf("%d%d",&r1,&r2); while(r1<=r2) if (r1%2!=0) printf("\n %d",r1); r1++;
116
/* SUM OF THE DIGITS IN A GIVEN NUMBER (sumdigit.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { long int num,sum=0,rem; clrscr(); printf("\n ENTER THE NUMBER"); scanf("%ld",&num); while(num>0) rem=num%10; sum=sum+rem; num=num/10; } printf("\nSUM OF THE DIGITS OF THE GIVEN NUMBER IS:%ld",sum);
117
Do – while The general form of the do while statement is Do { body of the loop; } while (test condition); On reaching the do statement , the program proceeds to evaluate the body of the loop first. At the end of the loop , the test – condition in the while statement is evaluated . If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. Since the test – condition is evaluated at the bottom of the loop, the do-while construct provides an exit controlled loop and therefore the body of the loop is always executed atleast once.
118
Test Expr. exit Body of the loop
119
/* SUM OF THE DIGITS IN A GIVEN NUMBER (sumdigit.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { long int num,sum=0,rem; clrscr(); printf("\n ENTER THE NUMBER"); scanf("%ld",&num); while(num>9) rem=num%10; sum=sum+rem; num=num/10; } sum=sum+num; printf("\nSUM OF THE DIGITS OF THE GIVEN NUMBER IS:%ld",sum);
120
/* IMAGE OF A GIVEN NUMBER (numrev.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int num,rem; clrscr(); printf("\n ENTER THE NUMBER \n"); scanf("%d",&num); printf("\n IMAGE OF THE GIVEN NUMBER IS:\n"); while(num>9) rem=num%10; printf("%d",rem); num=num/10; } printf("%d",num);
121
/* FIBONACCI SERIES 1,1,2,3,5,8,13,….(FIB.C)
#include<stdio.h> #include<math.h> #include<conio.h> main() { int fib,i=1,a=0,n; clrscr(); printf("\n enter the maximum limit of the fibonacci numbers"); scanf("%d",&n); fib=i+a; while (fib<n) printf("\n %d",fib); i=a; a=fib; }
122
/* TO GENERATE STAR PYRAMID OF RIGHT ANGLED TYPE (tristar.c)*/
#include<stdio.h> #include<conio.h> main() { char star='*'; int k,n,c; k=25; n=1; clrscr(); while(n<=20) printf(" "); c=1; while(c<=n) printf("%c",star); c=c+1; } printf("\n"); n=n+1; k=k-1; } }
123
/* TO GENERATE ODDS BETWEEN TWO GIVEN NUMBERS (odds.c)*/
#include<stdio.h> main() { int r1,r2; printf("\n enter any two numbers"); scanf("%d%d",&r1,&r2); while(r1<=r2) if (r1%2!=0) printf("\n %d",r1); r1++; } /* SUM OF THE DIGITS IN A GIVEN NUMBER (sumdigit.c)*/ #include<math.h> #include<conio.h> long int num,sum=0,rem; clrscr(); printf("\n ENTER THE NUMBER"); scanf("%ld",&num); while(num>0) rem=num%10; sum=sum+rem; num=num/10; printf("\nSUM OF THE DIGITS OF THE GIVEN NUMBER IS:%ld",sum);
124
The general form of the do while statement is Do { body of the loop; }
while (test condition); On reaching the do statement , the program proceeds to evaluate the body of the loop first. At the end of the loop , the test – condition in the while statement is evaluated . If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. Since the test – condition is evaluated at the bottom of the loop, the do-while construct provides an exit controlled loop and therefore the body of the loop is always executed atleast once. Body of the loop Test Expr. exit
125
/* armstrong number below 1000 */
#include<stdio.h> main() { int num=1,rem,n,temp,sum; printf("\n enter the maximum limit"); scanf("%d",&n); do sum=0; temp=num; while(temp>0) rem=temp%10; sum+=rem*rem*rem; temp=temp/10; } if (sum==num) printf("\t %d",num); num++; while (num<=n); INPUT: enter the maximum limit 1000 OUTPUT:
126
For statement The for loop is another entry controlled loop that provides a more concise loop control structure . The general form of the for loop is For (initialization ; test condition ; update expression) { body of the loop } One of the important points about the for loop is that all the three actions , namely initialization , testing and incrementing are placed in the for statement itself, thus making them visible to the programmers and users in one place. Initialization The control variable is initialized. This part is executed once before executing the body of the loop. 2. Test condition The value of the control variable is tested and if the control variable is tested and if found true, the body of the loop is executed , otherwise the loop is terminated. This expression is evaluated before every execution of the loop body. 3.Update expression (increment/decrement) After executing the last statement in the for loop , the control is transferred back to the for statement. The control variable is updated using an expression , such as j++ and the test expression is evaluated to see if it is true before executing the body of the loop.
127
initialization Test Expr. exit Update Expr.
128
/* TO CHECK WHETHER THE GIVEN NUMBER IS PERFECT OR NOT (perfect.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int n,k,sum; clrscr(); printf("\n enter the number to be checked"); scanf("%d",&n); for(k=1,sum=0;k<=n/2;k++) if (n%k==0) sum+=k; if (sum==n) printf("\n %d is perfect",n); else printf("\n %d is not perfect",n); }
129
/*IMAGE OF A GIVEN NUMBER using for loop (revnum.c) */
#include<stdio.h> #include<math.h> #include<conio.h> main() { long int n,rn=0; clrscr(); printf("\n enter the number to reversed"); scanf("%ld",&n); for(;n!=0;n=n/10) rn=rn*10+n%10; printf("\n reversed number is %ld ",rn); }
130
/* TO CONSTRUCT PYRAMID OF DIGITS (pyramid.c)*/
#include<stdio.h> #include<conio.h> main() { int p,m,q,n; clrscr(); printf("\n ENTER THE NO.OF LINES (n<=9)\n"); scanf("%d",&n); for(p=1;p<=n;p++) for(q=1;q<=n-p;q++) printf(" ");/* no.of spaces 4 */ m=p; for(q=1;q<=p;q++) printf("%4d",m++); m=m-2; for(q=1;q<p;q++) printf("%4d",m--); printf("\n\n"); } printf("\n");
131
/* TO CONSTRUCT REVERSE PYRAMID OF DIGITS (revpyram.c)*/
#include<stdio.h> #include<conio.h> main() { int p,q,r,t,s; clrscr(); printf("\n ENTER THE NO.OF LINES IN A PYRAMID BELOW 10:\n"); scanf("%d",&t); printf("%d\n\n",t); printf("\t REVERSE PYRAMID OF DIGITS \n\n"); for(p=t;p>1;p--) printf(" ");/* no.of spaces 40 */ for(r=0;r<=p*4;r++) printf("\b"); for(q=p;q<=(2*p)-1;q++) printf("%4d",q); for(s=(2*p)-2;s>=p;s--) printf("%4d",s); printf("\n\n"); }
132
printf(" %d\n",p);/* spaces 36*/
} /* TO CONSTRUCT PASCAL'S TRIANGLE (pastri.c)*/ #include<stdio.h> #include<conio.h> main() { int binom=1,p,q=0,r,x; clrscr(); printf("\n ENTER THE NO.OF ROWS \n"); scanf("%d",&p); clrscr(); printf("PASCAL'S TRIANGLE:\n"); while(q<p) { for(r=40-3*q;r>0;--r) printf(" "); for(x=0;x<=q;x++) { if((x==0)||(q==0)) binom=1; else binom=(binom*(q-x+1))/x; printf("%6d",binom); } /* for */ printf("\n"); q; } /* while */
133
/*PERFECT NUMBERS IN A GIVEN RANGE (perfects.c)*/
#include<stdio.h> main() { int n1,n2,num,c,n; printf("\n enter the lower limit and upper limit"); scanf("%d%d",&n1,&n2); for(num=n1;num<=n2;num++) c=1; for(n=2;n<num;n++) if((num%n)==0) c=c+n; if(c==num) printf("\t %d",num); }}
134
/* SIN(X) series (sinx.c) */
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,k=0; float xx,x,s=0.0,den=1.0,term; clrscr(); printf("\n\n\n\n\n * SIN(X)*\n\n\n"); printf("\n enter the value in degrees"); scanf("%f",&x); xx=x; x=x*3.14/180.0; for(i=1;i<18;i+=2,den=den*i*(i-1),k++) { term=pow(-1,k)*pow(x,i)/den; s+=term; if (fabs(term)< ) break; } printf("\n calculated value is %f",s); printf("\n sin(%f)= %f",xx, sin(x)); }
135
/*COS(X) series cosx.c */
#include<conio.h> #include<math.h> main() { int i,k=1; float xx,x,s=1.0,den=2,term; clrscr(); printf("\n\n\n\n * COS(X) *\n\n\n"); printf("\n enter the value of x in degrees"); scanf("%f",&x); xx=x; x=x*3.14/180.0; for(i=2;i<18;i+=2,den=den*i*(i-1),k++) term=pow(-1,k)*pow(x,i)/den; s+=term; if (fabs(term)< ) break; } printf("\n calculated value is %f",s); printf("\n cos(%f)=%f",xx,cos(x));
136
/* EXP(X) series (expx.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i; float x,s=1.0,den=1.0; clrscr(); printf("\n\n\n\n * EXP(X) *\n\n\n\n\n"); printf("\n enter the value of x :"); scanf("%f",&x); for(i=1;i<18;i++,den=den*i) s=s+pow(x,i)/den; printf("\n calculated value is %f ",s); printf("\n exp(%f)=%f",x,exp(x)); }
137
/* HORNER'S METHOD (horner.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int n,i; float y,x,a[10]; clrscr(); printf("\n enter the degree of the polynomial"); scanf("%d",&n); printf("\n enter the values of x"); scanf("%f",&x); printf("\n enter %d coefficients in the polynomial",n+1); for(i=0;i<=n;i++) scanf("%f",&a[i]); y=a[0]; for(i=1;i<=n;i++) y=y*x+a[i]; printf("\n y=%f",y); }
138
/* G.C.D AND L.C.M OF TWO GIVEN NUMBERS (gcdlcm.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int m,n,r,prod,lcm; clrscr(); printf("\n enter any two numbers to calculate g.c.d and l.c.m"); scanf("%d %d",&m,&n); prod=m*n; if (m<n) r=m;
139
m=n; n=r; } r=m%n; for(;r!=0;) { m=n; n=r; r=m%n; } lcm=prod/n; printf("\n gcd=%d \t lcm= %d ",n,lcm); }
140
/* AMICABLE NUMBERS: two numbers each of which is equal to the sum of all the exact divisors of the except the number itself. Eg:- 220 and 284 are amicable numbers. For 220 the exact divisors are : = 284 For 284 the exact divisors are : = 220 GENERATING AMICABLES BELOW A GIVEN NUMBER (amics.c)*/ #include<stdio.h> #include<conio.h> main() { int n1,n2,i,j,n,p,q,x,y,sumx,sumy; clrscr(); printf("\n enter any number"); scanf("%d",&n); for (i=1;i<=n;i++)
141
sumx=0; n1=i; x=i; for(p=1;p<x;p++) if ((x%p)==0) sumx+=p; for(j=1;j<=n;j++) if (sumx==j) { sumy=0; n2=j; y=j; for(q=1;q<y;q++) if ((y%q)==0) sumy+=q; } if (n1==n2) continue; if ((n1==sumy) && (n2==sumx)) printf("\n %d %d",x,y);
142
/* FACTORIAL USING FOR LOOP (fact.c) */
#include<stdio.h> main() { int n,i; long int fact=1; clrscr(); printf("enter the value of n "); scanf("%d",&n); for(i=1;i<=n;i++) fact*=i; printf("fact=%ld",fact); }
143
/* TO GENERATE STAR PYRAMID OF RIGHT ANGLED TYPE (tri.c)*/
#include<stdio.h> #include<conio.h> main() { int n,c; clrscr(); for(n=1;n<=10;n++) for(c=1;c<=n;c++) printf("*"); printf("\n"); }
144
/*PALENDROMES BETWEEN 100 AND 1000 (pal100&k.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,n; clrscr(); for(i=1;i<=9;i++) printf("\n"); for(j=1;j<=9;j++) n=i*100+j*10+i; printf("%d \t ",n); } } }
145
/* SIMPSON'S 1/3 RULE (simpson.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int n,i; float a,b,h,s=0,k=4,result; clrscr(); printf("\n enter the values of a,b,n"); scanf("%f %f %d",&a,&b,&n); h=(b-a)/n; for(i=1;i<n;i++,k=6.0-k) s=k/1+((a+i*h)*(a+i*h)); s+=(1.0/(1+a*a))+(1.0/(1+b*b)); result=s*h/3.0; printf("\n %f ",result); }
146
/* TRAPEZOIDAL'S RULE (trapzoid.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int n,i; float a,b,h,s=0,k=4,result; clrscr(); printf("\n enter the values of a,b,n"); scanf("%f %f %d",&a,&b,&n); h=(b-a)/n; for(i=1;i<n;i++,k=6.0-k) s=k/1+((a+i*h)*(a+i*h)); s+=(1.0/(1+a*a))+(1.0/(1+b*b)); result=s*h/3.0; printf("\n %f ",result); }
147
/* SUM OF THE DIVISORS OF A GIVEN NUMBER (sumdiv.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int n,k=1,sum=0; clrscr(); printf("\n enter the number"); scanf("%d",&n); for(;k<=n/2;k++) if (n%k==0) { sum+=k; } sum+=n; printf("\n sum of the divisors of the given number is %d",sum); }
148
/*PRIME NUMBERS IN A GIVEN RANGE (primes.c)*/
#include<stdio.h> main() { int n1,n2,num,c,n; printf("\n enter the lower limit and upper limit"); scanf("%d%d",&n1,&n2); for(num=n1;num<=n2;num++) { c=0; for(n=2;n<num;n++) if((num%n)==0) c=c+1; if(c==0) printf("\t %d",num); }
149
Comparision of the three loops
For while do For(n=1;n<=10;n++) n= n=1 { while (n<=10) do { { } ……………… } } while (n<=10)
150
Without any embedded expressions or statements .
Break statement A break statement terminates the execution of the loop and the control is transferred to the statement immediately following the loop. The break statement is used to terminate loops or to exit from a switch . It can be used within a for , while, do-while or switch statement. The break statement is written as Break ; Without any embedded expressions or statements . Cond in the loop loopon break
151
Continue statement The continue statement is used to bypass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. Instead , the remaining loop statements are skipped and the computation proceeds directly to the next pass through the loop. This statement is written as, Continue ; without any embedded statements or expressions. The flow chart of the continue statement is given as
152
/* ARITHMATIC MEAN OF NON NEGATIVE NUMBERS (meannn.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int count,n,pos=0; float x,average,sum=0.0; clrscr(); printf("\n ENTER THE NO.OF OBSERVATIONS :"); scanf("%d",&n); printf("\n ENTER THE OSERVATIONS: \n"); for(count=1;count<=n;count++)
153
printf("x="); scanf("%f",&x); if (x<0) continue; sum+=x; pos=pos+1; } average=sum/pos; printf("\n ARITHMETIC MEAN OF ONLY NON NEGATIVE OBSERVATIONS=%f",average);
154
Functions The complex problem may be decomposed into small or easily manageable parts. Each small module is called a function .The functions are very useful to read, write, debug, modify and are easy to use in the main program. The main advantages of using a function are ---- simple to write correctly a small function ---- easy to read , write and debug a function ---- easier to maintain or modify such a function ---- small functions tend to be self documenting and highly readable ---- a function may be called any number of times in any place with different parameters ---- a function is a self – contained program segment that carries out some specific , well defined task Generally , a function will process information that is passed to it from the calling portion of the program and return a single value . Information is passed to the function via special identifiers called arguments (also called parameters) and returned via the return statement .
155
Category of functions Category 1: Functions with no arguments and no return values Category 2: Functions with arguments and no return values Category 3: Functions with arguments and return values Category 1: No arguments and no return values When a function has no arguments , it does not receive any data from the calling function. Similarly, when it does not return a value , the calling function does not receive any data from the called function. In effect , there is no data transfer between the calling function and the called function.
156
#include<stdio.h>
main() { printline(); hello(); printline(); } printline() { printf(“\n “); hello() printf(“\n Hello! How do you do ?”);
157
Category 2: Functions with arguments and no return values
We should ensure that the function call has matching arguments . In case, the actual arguments are more than the formal arguments(m>n), the extra actual arguments are discarded. On the other hand, if the actual arguments are less than the formal arguments, the unmatched formal arguments are initialized to some garbage values. Any mismatch in data type may also result in passing of garbage values. Remember no error message will be generated. While the formal arguments must be valid variable names, the actual arguments may be variable names, expressions or constants. The variables used in actual arguments must be assigned values before the function call is made. Remember that , when a function call is made , only a copy of the values of actual arguments is passed into the called function. What occurs inside the function will have no effect on the variables used in the actual argument list
158
There may be several different calls to the same function from various places with a program. The actual arguments must correspond to the formal arguments in the function definition. i.e the number of actual arguments must be the same as the number of formal arguments, and each actual argument must be of the same data type as its corresponding formal argument.
159
/* SIMPLE INTEREST using function (simpint.c)*/
#include<stdio.h> main() { float principal,inrate; int period; printf("\n Enter principal amount,interest rate, period"); scanf("%f%f%d",&principal,&inrate,&period); value(principal,inrate,period); } value (p,r,n) float p,r; int n; { float interest,total; interest = p*n*r/100; total =p+interest; printf("\n The total =%f",total);
160
Category 3: Arguments with return values
The function value receives data from the calling function through arguments, but does not send back any value. Rather, it displays the results of calculations at the terminal. However, we may not always wish to have the result of a function displayed. We may use it in the calling function for further processing moreover to assure a high degree of portability between programs, a function should generally be coded without involving any I/O operations. Different programs may require different output formats for displaying results . There shortcoming can be overcome by handing over the result of a function to its calling function where the returned value can be used as required by the program. A self contained and independent function should behave like a ‘black box’ that receives a predefined form of input and outputs a desired value.
161
/* SIMPLE INTEREST using function (simpint.c)*/
#include<stdio.h> main() { float principal,inrate; int period; printf("\n Enter principal amount,interest rate, period"); scanf("%f%f%d",&principal,&inrate,&period); value(principal,inrate,period); } value (p,r,n) float p,r; int n; float interest,total; interest = p*n*r/100; total =p+interest; printf("\n The total =%f",total);
162
/* TO FIND THE FACTORIAL using function (facfun.c) */
#include<stdio.h> main() { int x,n; printf("\n Enter any integer number"); scanf("%d",&n); x=fact(n); printf("\n value of %d and its factorial %d",n,x); } int fact(int n) { int i,value=1; if (n==1) return(value); else { for(i=1;i<=n;i++) value=value*i; return(value); } }
163
/* BINOMIAL COEFFICIENT USING FUNCTION (ncr.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { long int n,r,nft,rft,nrft,ncr; long int fact(long int l); clrscr(); printf("\n enter the valus of n & r"); scanf("%ld %ld",&n,&r); nft=fact(n); rft=fact(r); nrft=fact(n-r); ncr=nft/(rft*nrft); printf("\n ncr= %ld",ncr); }
164
long int fact (long int l)
{ int k=1; long int lfact=1; for(;k<=l;k++) lfact*=k; return(lfact); }
165
RECURSION Recursion is process by which a function call itself repeatedly until some specified condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms of a previous result. In order to solve a problem recursively , two conditions must be satisfied. First the problem must be written in a recursive form and second the problem statement must include a stopping condition. Eg:- suppose we wish to calculate the factorial of a positive integer quantity, we would normally express this problem as n!=1*2*3*…….n, where n is a specified positive integer. However, we can also express this problem in another way, by writing n!=n*(n-1)! This is a recursive statement of the problem, in which the desired action (the calculation of n!) is expressed in terms of a previous result [ the value of (n-1)! , which is assumed to be known ]. Also we know that 1!=1 by definition . This last expression provides a stopping condition for the recursion.
166
/* FACTORIAL USING RECURSIVE (recursiv.c)*/
#include<stdio.h> long int factorial(int n); main() { int n; printf("\n enter the number"); scanf("%d",&n); printf("n!=%ld",factorial(n)); } long int factorial (int n) if (n<=1) return(1); else return(n*factorial(n-1));
167
Comparision of iteration and recursion
Any iterative function consists of four parts: Initialization: The decision parameter is set to an initial value , or more precisely , the loop variable is initialized. Other pre-defined variables are also initialized. Decision: The decision parameter is used to determine whether further looping is necessary . The loop variable is compared , and based an the outcome , the loop is executed again . The test performed on the loop variable may not be the only condition; other relational expression may also participate in the decision. Computation: The necessary computation is performed within the loop Update : The decision parameter is updated and a transfer is made to the next iteration. The loop variable is incremented / decremented. It may also result in a set of variables being modified. For a recursive function
168
Initialization: The variables in the form of arguments are passed on to the function
Decision: The argument values are used to determine whether further recursive calls are required. Computation: The necessary computation is performed using the local variables and the parameters at the current depth . Update: The update is done so that the variables can be used for further recursive calls. Recursion exists because of the recursive nature of the process or because of the recursive structure of the data to be processed. For some cases , they recursive solution may be simpler than iteration.
169
Arrays An array is a sequence of data in memory , where in all the data are of the same type and are placed in physically adjacent locations. Foe example, a sequence of 10 integers stored one after another in memory represents an array . Note that a string can be considered as a sequence of characters (an array of characters). Many applications require the processing of multiple data items that have common characteristics (e.g a set of numerical data represented by x1,x2,………xn). In such situations it is often convenient to place the data items into an array where they will all share the same name (eg x). The individual data items can be characters, integers, floating point numbers etc. However they may all be of the same type and same storage class. Each array element is referred to by specifying the array name followed by one or more subscripts with each subscript enclosed in square brackets. Each subscript must be expressed as a non negative integer. In a n-element array, the array elements are X[0],x[1],x[2]………x[n-1]. The value of each subscript can be expressed as an integer constant, an integer variable or a more complex integer expression. X[0] X[1] X[2]
170
The number of subscripts determines the dimensionality of the array
The number of subscripts determines the dimensionality of the array . For example x[i] refers to an element in the one-dimensional array y[i][j] refers to an element in the to-dimensional array Defining an array Arrays are defined in the same manner as ordinary variables , except that each array name must be accompanied by a size specification. For a one dimensional array , the size is specified by a positive integer expression enclosed in square brackets. The expression is usually written as a positive integer constant. In general one dimensional array definition may be expressed as Data –type array[expression]; Eg:- int x[100]; char tesxt[80]; char message[25]; float n[12];
171
Eg: float x[6] = {0,0.25,0,-0.5,0,0}; Char color[3] = { ‘R’,’E’,’D’}; Eg: all individual array elements that are not assigned explicit initial values will automatically be set to zero. This includes the remaining elements of an array in which some elements have been assigned non-zero values. Static digit[10]={3,4,5}; The result on an element – by – element basis are as follows. digit[0]=3 , digit[1]=4 , digit[2]=5, digit[3]=0 ,digit[4]=0, digit[5]=0 , digit[6]=0 , digit[7]=0, digit[8]=0 ,digit[9]=0. Strings(i.e character arrays) are handled somewhat differently. There is a provision for the null character \0, which automatically added at the end of every string. The array definition should be written as char color[4] = “red”; (or) char color[ ] = “red”;
172
/* STANDARD DEVIATION (sd.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,n; float x[20],sx=0.0,xbar,sxx=0.0,sd,var; clrscr(); printf("\n enter how many number of observations are there?"); scanf("%d",&n); printf("\n enter the observations"); for(i=0;i<n;i++)
173
scanf("%f",&x[i]); sx=sx+x[i]; } xbar=sx/n; for(i=0;i<n;i++) sxx+=(x[i]-xbar)*(x[i]-xbar); var=sxx/n; sd=sqrt(var); printf("\n the mean is %f",xbar); printf("\n the standard deviations of the given number id %f",sd);
174
/* SORTING OF NUMBERS (asc.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,n; float x[10],temp; clrscr(); printf("\n How many no.of observations are there?"); scanf("%d",&n); for(i=0;i<n;i++) scanf("%f",&x[i]); for(i=0;i<(n-1);i++) for(j=i+1;j<n;j++) if (x[i]>x[j]) temp=x[i]; x[i]=x[j]; x[j]=temp; } printf("\n SORTED LIST IS :\n"); for(i=0;i<n;i++) printf("%f \t",x[i]); printf("\n\n smallest is = %f \t biggest is = %f",x[0],x[n-1]);
175
/*MEDIAN(median.c) C: you have to start your i and j loops with 1*/
#include<stdio.h> main() { int i,j,n; float median,a[50],temp; printf("\n How many observations are there?"); scanf("%d",&n); printf("\n Enter the observations"); for(i=0;i<n;i++) scanf("%f",&a[i]); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++)
176
if (a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } for(i=0;i<n;i++) printf("\n %f",a[i]); if (n%2==0) median=(a[(n-1)/2]+a[(n-1)/2+1])/2.0; else median=a[(n-1)/2]; printf("\n The median is = %f",median);
177
/*MODE(mode.c) C: you have to start your i and j loops with 1*/
#include<stdio.h> main() { int i,j,n,pos; float mode,big,a[50],c[50]; printf("\n How many observations are there?"); scanf("%d",&n); printf("\n Enter the observations"); for(i=1;i<=n;i++) scanf("%f",&a[i]); for(i=1;i<=n-1;i++) c[i]=0;
178
for(j=i+1;j<=n;j++)
if (a[i]==a[j]) c[i]+=1; } big=c[1]; pos=1; for(i=2;i<=n;i++) if (big<c[i]) { big=c[i]; pos=i; } if (c[i]==1) printf("\n there is no mode value"); printf("\n the mode of the given element is %f",a[pos]);
179
/*BIGGEST OF THE GIVEN ARRAY (bigofn.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int x[99],big,i,n; printf("\n enter how many observations are there?"); scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&x[i]); big=x[0]; for(i=1;i<n;i++) if (big<x[i]) big = x[i]; printf("\n %d ",big); }
180
/* INSERT AN ELEMENT INTO THE ARRAY (menu5i.c) */
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,k,n,pos; float a[50],number; printf("\n How many observations are there ?"); scanf("%d",&n); printf("\n enter the observations"); for(i=0;i<n;i++) scanf("%f",&a[i]); printf("\n Enter the element to inserted ");
181
scanf("%f",&number); printf("\n Enter the position of the number to be entered "); scanf("%d",&pos); n=n+1; for(k=n;k>=pos;k--) a[k]=a[k-1]; pos=pos-1; a[pos]=number; for(i=0;i<n;i++) printf("%6.2f",a[i]); }
182
/* DELETE AN ELEMENT FROM THE ARRAY (menu5ii.c) */
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,k,n,pos,flag=0,num; float a[50],number; clrscr(); printf("\n How many observations are there ?"); scanf("%d",&n); printf("\n Enter the observations"); for(i=0;i<n;i++) scanf("%f",&a[i]); printf("\n Enter the element to be deleted "); scanf("%f",&number);
183
for(i=0;i<n;i++) if (a[i]==number) { flag=1; n=n-1; for(k=i;k<n;k++) a[k]=a[k+1]; } if (flag==0) printf("\n Element is not found in the array"); else printf("\n Array after deletion is :"); printf("\n %6.2f",a[i]); }
184
/* TO PRINT ELEMENTS IN REVERSE ORDER (menu5iv.c) */
#include<stdio.h> #include<math.h> #include<conio.h> main() { long int rn,a[50]; int i,n; clrscr(); printf("\n How many number of observations are there?"); scanf("%d",&n); printf("\n Enter the number the observations"); for(i=0;i<n;i++) scanf("%ld",&a[i]); printf("\n The reversed numbers of the given observations are:"); { rn=0; for(;a[i]!=0;a[i]=a[i]/10) rn=rn*10+a[i]%10; printf("\n %ld ",rn); } }
185
/* TO REMOVE DUPLICATES FROM THE ARRAY (menu5vi.c) */
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,k,n,pos,flag=0,num; float a[50],number; clrscr(); printf("\n How many observations are there ?"); scanf("%d",&n); num=n; printf("\n Enter the observations"); for(i=0;i<n;i++) scanf("%f",&a[i]); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if (a[i]==a[j])
186
{ flag=1; n=n-1; for(k=j;k<n;k++) a[k]=a[k+1]; j=j-1; } if (flag==0) printf("\n There are no duplicates in the array"); else { printf("\n The array has %d duplicates",num-n); printf("\n Array after deleting duplicates is :"); for(i=0;i<n;i++) printf("\n %6.2f",a[i]); }
187
#include<stdio.h> #include<math.h> #include<conio.h>
/* HARMONIC MEAN FOR UNGROUPED DATA (harmean.c)*/ #include<stdio.h> #include<math.h> #include<conio.h> main() { int i,n; float x[20],sumx=0.0,hm; clrscr(); printf("\n ENTER THE NO.OF OBSERVATIONS :"); scanf("%d",&n); printf("\n ENTER THE OSERVATIONS: \n"); for(i=0;i<n;i++) { scanf("%f",&x[i]); sumx+=(1/x[i]); } hm=n/sumx; printf("\n HARMONIC MEAN OF THE GIVEN OSERVATIONS= %f",hm); }
188
/* HORNER'S METHOD (horner.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int n,i; float y,x,a[10]; clrscr(); printf("\n enter the degree of the polynomial"); scanf("%d",&n); printf("\n enter the values of x"); scanf("%f",&x); printf("\n enter %d coefficients in the polynomial",n+1); for(i=0;i<=n;i++) scanf("%f",&a[i]); y=a[0]; for(i=1;i<=n;i++) y=y*x+a[i]; printf("\n y=%f",y); }
189
/* GEOMETRIC MEAN FOR UNGROUPED DATA (geomean.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,n; float x[20],sumx=0.0,gm; clrscr(); printf("\n ENTER THE NO.OF OBSERVATIONS :"); scanf("%d",&n); printf("\n ENTER THE OBSERVATIONS ONE BY ONE: \n"); for(i=1;i<=n;i++) { scanf("%f",&x[i]); sumx+=log10(x[i]); } sumx=sumx/n; gm=pow(10,sumx); printf("\n GEOMETRIC MEAN OF THE GIVEN OBSERVATIONS= %f",gm); }
190
PROGRAMS OF TWO DIMENSIONAL ARRAYS
/* MATRIX SUM (matsum.c)*/ #include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,m,n,p,q; float a[5][5],b[5][5],c[5][5]; clrscr(); printf("\n ENTER THE SIZE OF THE FIRST MATRIX (m*n) \n "); scanf("%d %d",&m,&n); printf("\n ENTER THE FIRST MATRIX : \n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%f",&a[i][j]); printf("\n ENTER THE SIZE OF THE SECOND MATRIX (p*q)\n"); scanf("%d%d",&p,&q); printf("\n ENTER THE SECOND MATRIX: \n"); for(i=0;i<p;i++) for(j=0;j<q;j++) scanf("%f",&b[i][j]); if ((m==p) && (n==q)) {
191
/* MATRIX NORM AND TRACE (normtrac.c)*/
/* TRACE= sum of the diagonal elements*/ /* NORM= sqrt(sum of the square of each element in a matrix) */ #include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,n; float a[5][5],trace=0,norm=0; clrscr(); printf("\n ENTER THE SIZE OF THE SQUARE MATRIX (n) \n "); scanf("%d",&n); printf("\n ENTER THE VALUES IN THE MATRIX : \n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { scanf("%f",&a[i][j]);
192
norm=norm+a[i][j]*a[i][j];
} for(i=1;i<=n;i++) for(j=1;j<=n;j++) if(i==j) trace=trace+a[i][j]; norm=sqrt(norm); printf("\n TRACE= %f, NORM= %f", trace, norm);
193
/* MATRIX TRANSPOSE (menu6iii.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,m,n; float a[5][5],b[5][5]; clrscr(); printf("\n ENTER THE SIZE OF THE MATRIX (m*n)\n "); scanf("%d %d",&m,&n); printf("\n ENTER THE VALUES OF THE MATRIX : \n"); for(i=1;i<=m;i++) for(j=1;j<=n;j++)
194
scanf("%f",&a[i][j]); printf("\n TRANSPOSE OF A GIVEN MATRIX IS : \n"); for(i=1;i<=n;i++) { printf("\n"); for(j=1;j<=m;j++) b[i][j]=a[j][i]; printf("%f \t ",b[i][j]); } } }
195
/* MATRIX MULTIPLICATION (matmul.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,k,m,n,p,q; float a[5][5],b[5][5],c[5][5]; clrscr(); printf("\n ENTER THE SIZE OF THE FIRST MATRIX (m*n)\n "); scanf("%d%d",&m,&n); printf("\n ENTER THE SIZE OF THE SECOND MATRIX (p*q)\n"); scanf("%d%d",&p,&q); if (n!=p) printf("\n MATRIX MULTIPLICATION IS NOT POSSIBLE\n"); else {
196
printf("\n ENTER THE FIRST MATRIX : \n");
for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%f",&a[i][j]); printf("\n ENTER THE SECOND MATRIX: \n"); for(i=0;i<p;i++) for(j=0;j<q;j++) scanf("%f",&b[i][j]); printf("\n THE MULTIPLICATION OF THE GIVEN MATRICES IS: \n"); { printf("\n"); { c[i][j]=0; for(k=0;k<n;k++) c[i][j]+=a[i][k]*b[k][j]; printf("%f \t ",c[i][j]); } } } }
197
/* ASCENDING ORDER OF A SPECIFIC ROW (ascrocol.c)*/
#include<stdio.h> main() { int i,j,m,n,sr,sc; float a[5][5],temp; printf("\n ENTER THE SIZE OF THE MATRIX \n "); scanf("%d%d",&m,&n); printf("\n ENTER THE MATRIX : \n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%f",&a[i][j]); printf("\nENTER THE ROW TO BE ARRANGED IN THE ASCENDING ORDER\n"); scanf("%d",&sr);
198
sr--; for(i=0;i<m;i++) for(j=i+1;j<n;j++) if (a[sr][i]>a[sr][j]) { temp=a[sr][i]; a[sr][i]=a[sr][j]; a[sr][j]=temp; } printf("\n"); for(j=0;j<n;j++) printf("\t %f ",a[i][j]); } }
199
/* SUM ROW, SUM COLUMN (menu6v.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,m,n; float a[5][5]; printf("\n ENTER THE SIZE OF THE MATRIX (m*n)\n "); scanf("%d%d",&m,&n); printf("\n ENTER THE MATRIX : \n"); for(i=1;i<=m;i++) for(j=1;j<=n;j++) scanf("%f",&a[i][j]); { a[i][n+1]=0.0;
200
a[i][n+1]+=a[i][j]; } for(j=1;j<=n;j++) { a[m+1][j]=0; for(i=1;i<=m;i++) a[m+1][j]+=a[i][j]; } for(i=1;i<=m+1;i++) { printf("\n"); for(j=1;j<=n+1;j++) if(i==m+1 && j==n+1) printf(" "); else printf("\t %8.2f",a[i][j]); } }
201
/* BIGGEST AND SMALLEST ELEMENTS AMONG THE
VALUES IN THE GIVEN MATRIX (bigsmofm.c) */ #include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,m,n,row,col,row1,col1; float a[5][5],big,small; clrscr(); printf("\n ENTER THE SIZE OF THE MATRIX \n "); scanf("%d%d",&m,&n); printf("\n ENTER THE VALUES IN THE MATRIX : \n"); for(i=0;i<m;i++) for(j=0;j<n;j++)
202
scanf("%f",&a[i][j]); big=a[0][0]; row=0;col=0;
small=a[0][0];row1=0;col1=0; for(i=0;i<m;i++) for(j=0;j<n;j++) { if(big < a[i][j]) { big=a[i][j]; row=i; col=j; } if (small>a[i][j]) { small=a[i][j]; row1=i; col1=j; } } printf("\nBIG VALUE=%f AND ITS POSITION IS %dROW,%dCOL",big,row+1,col+1); printf("\nSMALL VALUE=%f AND ITS POSITION IS %dROW %dCOL",small,row1+1,col1+1); }
203
/* MATRIX SYMMETRIC (matsym.c) */
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,m,n,c=0; float a[5][5],b[5][5]; clrscr(); printf("\n ENTER THE SIZE OF THE MATRIX (m*n)\n "); scanf("%d %d",&m,&n); printf("\n ENTER THE VALUES OF THE MATRIX : \n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%f",&a[i][j]); printf("\n TRANSPOSE OF A GIVEN MATRIX IS : \n"); for(i=0;i<n;i++) {
204
printf("\n"); for(j=0;j<m;j++) { b[i][j]=a[j][i]; printf("%f \t ",b[i][j]); } } if(m==n) /*if given matrix is not square matrix we can't check symmetricity*/ { for(i=0;i<m;i++) for(j=0;j<n;j++) if (a[i][j]==b[i][j]) c=c+1; if(c==(m*n)) printf("\n\n\n THE GIVEN MATRIX IS SYMMETRIC \n"); else printf("\n\n\n\n THE GIVEN MATRIX IS NOT SYMMETRIC \n"); } else printf("\n given matrix is not symmetric");
205
/* ORTHOGONAL MATRIX (matorth.c) */
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,k,m,n,flag=0; float a[5][5],b[5][5],c[5][5]; clrscr(); printf("\n ENTER THE SIZE OF THE MATRIX (m*n)\n "); scanf("%d%d",&m,&n); printf("\n ENTER THE VALUES OF THE MATRIX : \n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%f",&a[i][j]); printf("\n TRANSPOSE OF A GIVEN MATRIX IS : \n"); for(i=0;i<n;i++)
206
{ printf("\n"); for(j=0;j<m;j++) { b[i][j]=a[j][i]; printf("%f \t ",b[i][j]); } } printf("\n\n\n MATRIX * MATRIX TRANSPOSE"); for(i=0;i<m;i++) { printf("\n"); { c[i][j]=0; for(k=0;k<n;k++) c[i][j]=c[i][j]+a[i][k]*b[k][j]; printf("\t %f",c[i][j]); } }
207
{ if ((i!=j) && (c[i][j]==0)) flag+=1;
} if (flag==(m*m)) printf("\n GIVEN MATRIX IS ORTHOGONAL"); else printf("\n GIVEN MATRIX IS NOT ORTHOGONAL");
208
/* INTERCHANGE TWO SPECIFIC ROWS (interows.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,m,n,p,q; float a[5][5],b[5][5]; clrscr(); printf("\n ENTER THE SIZE OF THE MATRIX (m*n) \n "); scanf("%d%d",&m,&n); printf("\n ENTER THE MATRIX : \n"); for(i=0;i<m;i++) for(j=0;j<n;j++) { scanf("%f",&a[i][j]); b[i][j]=a[i][j]; } printf("\n ENTER THE ROWS THAT ARE TO BE INTERCHANGED\n");
209
scanf("%d%d",&p,&q); p--; q--;
for(i=0;i<m;i++) for(j=0;j<n;j++) { if (i==p) a[i][j]=b[q][j]; if (i==q) a[i][j]=b[p][j]; } printf("\n THE MATRIX AFTER INTERCHANGEING THE TWO ROWS IS:"); { printf("\n"); printf("%f \t ",a[i][j]); } }
210
/* SUM ROW, SUM COLUMN (sumrocol.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,m,n; float a[5][5]; clrscr(); printf("\n ENTER THE SIZE OF THE MATRIX (m*n)\n "); scanf("%d%d",&m,&n); printf("\n ENTER THE MATRIX : \n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%f",&a[i][j]); { a[i][n]=0.0; a[i][n]+=a[i][j]; }
211
for(j=0;j<n;j++) { a[m][j]=0; for(i=0;i<m;i++) a[m][j]+=a[i][j]; } for(i=0;i<=m;i++) { printf("\n"); for(j=0;j<=n;j++) if(i==m && j==n) printf(" "); else printf("\t %8.2f",a[i][j]); } }
212
/* determinant of a square matrix*/
#include<stdio.h> #include<math.h> float a[5][5],ratio,det=1.0; int i,j,k,n; void interchange(int k); void main() { clrscr(); printf("\n enter the size of the square matrix(n)"); scanf("%d",&n); printf("=n enter the elements"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%f",&a[i][j]); for(k=0;k<n-1;k++)
213
/* determinant of a square matrix*/
#include<stdio.h> #include<math.h> float a[5][5],ratio,det=1.0; int i,j,k,n; void interchange(int k); void main() { clrscr(); printf("\n enter the size of the square matrix(n)"); scanf("%d",&n); printf("=n enter the elements"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%f",&a[i][j]); for(k=0;k<n-1;k++)
214
if (a[k][k]==0) { interchange(k); det=-det; } { det=0.0; printf("\n the determinant of the given matrix : %f",det); } for(i=k+1;i<n;i++) ratio=a[i][k]/a[k][k]; for(j=k;j<n;j++) a[i][j]=a[i][j]-ratio*a[k][j]; }
215
for(i=0;i<n;i++) det*=a[i][i]; printf("\n determinant =%f",det); } void interchange(int k) { int flag=0,p; float temp; for(i=k+1;i<n;i++) if(a[i][k]!=0) { flag=1; break; } if (flag==1) { for(p=k;p<n;p++) temp=a[k][p]; a[k][p]=a[i][p]; a[i][p]=temp; } } }
216
Passing arrays to functions
An entire array can be passed to a function as an argument . The manner in which the array is passed differs markedly from that of an ordinary variable. To pass an array to a function , the array name must appear by itself without brackets or subscripts as an actual argument within the function call. The corresponding formal argument is written in the same manner , though it must be declared as an array within the formal argument declarations. When declaring a one-dimensional array as a formal argument , the array name is written with a pair of empty square brackets. The size of the array is not specified within the formal argument declaration. Some care is required when writing function prototypes that include array arguments. A empty pair o square brackets must follow e name of each array argument, thus indicating that the argument in an array.
217
However some care is required when passing multidimensional arrays to a function . In particular , the formal argument declaration within the function definition must include explicit size specifications in all of the subscript positions except the first. These size specifications must be consistent with the corresponding size specifications in the calling program. The first subscript positions may be written as an empty pair of square brackets , as with a one-dimensional array. The corresponding function prototypes must be written in the same manner.
218
#include<stdio.h> #include<math.h> #include<conio.h>
/* PASSING ARRAYS TO FUNCTIONS */ #include<stdio.h> #include<math.h> #include<conio.h> float mean(float a[]); int i,n; void main() { float a[90]; printf("\n How many obvs?"); scanf("%d",&n); printf("\n enter the obvs:"); for(i=0;i<n;i++) scanf("%f",&a[i]); printf("\n mean=%f",mean(a)); } float mean(float a[]) { float sum=0; sum+=a[i]; return(sum/n); }
219
/* PASSING TWO DIMENSIONAL ARRAY TO THE FUNCTION*/
#include<stdio.h> #include<math.h> #include<conio.h> void addition(int a[][10], int b[][10]); int i,j,m,n,p,q; void main() { int a[10][10],b[10][10],ch; clrscr(); printf("\n ENTER THE SIZE OF THE FIRST MATRIX (m*n) \n "); scanf("%d %d",&m,&n); printf("\n ENTER THE FIRST MATRIX : \n"); for(i=0;i<m;i++) for(j=0;j<n;j++)
220
scanf("%d",&a[i][j]); printf("\n ENTER THE SIZE OF THE SECOND MATRIX (p*q)\n"); scanf("%d%d",&p,&q); printf("\n ENTER THE SECOND MATRIX: \n"); for(i=0;i<p;i++) for(j=0;j<q;j++) scanf("%d",&b[i][j]); if ((m==p) && (n==q)) { addition(a,b); } else printf("\n addition is not possible"); } void addition(int a[][10], int b[][10]) { int c[10][10]; for(i=0;i<m;i++) { printf("\n");
221
for(j=0;j<n;j++) { c[i][j]=a[i][j]+b[i][j]; printf("%d \t ",c[i][j]); } } }
222
CHARACTER STRINGS Character strings are often used to build meaningful and readable programs. The common operations performed on character strings are Reading and writing strings Combining strings together Copying one string to another Comparing strings for equality Extracting a portion of a string Strings are arrays of characters i.e they are characters arranged one after another in the memory. To mark the end of the string C uses the null character Strings in C are enclosed within double quotes.
223
Eg:- #include<stdio.h>
main() { int i; char names[5][10]={“RAMPRASAD”,”PRASAD”, ”PRASANTH”,”PRAKASH”,”ANAND”}; for(i=0;<5;i++) printf(“|n %s”,names[i]); } 1 2 3 4 5 6 7 8 9 R A M P S D \0 N T H K
224
/*NO.OF CHARACTERS ,NO.OF VOWELS IN A SENTENCE (vowels.c)*/
#include<ctype.h> #include<string.h> main() { int nc=0,nv=0,i; char c,v[]={'a','e','i','o','u'}; printf("\n enter the sentence and at end put ."); while ((c=getchar())!='.') { nc++; for(i=0;i<5;i++) if(c==v[i]) nv++; } printf("\n no.of characters=%d , no.of.vowels=%d",nc,nv); }
225
/* TO CHECK WHETHER THE WORD IS PALENDROME OR NOT ([palword.c)*/
#include<stdio.h> #include<math.h> #include<string.h> #include<ctype.h> #include<conio.h> main() { int i,j,n,flag=0; char cr,c[20]; clrscr(); printf("\n ENTER THE WORD TO CHECKED\n"); for(n=0;(cr=getchar())!='\n';n++) c[n]=cr; for(i=0,j=(n-1);i<(n-1)/2;i++,j--) if (c[i]!=c[j]) { flag=1; break; } if (flag==0) printf("\n palendrome"); else printf("\n not palendrome"); }
226
/* SORTING OF NAMES (sortname.c)*/
#include<stdio.h> #include<string.h> #include<ctype.h> main() { int i,j,n,m; char c,name[10][20],temp[20]; scanf("%d%d",&m,&n); /*for(i=0;i<m;i++) for(j=0;j<n;j++) name[i][j]=' '; */ for(i=0;i<m;i++) { for(j=0;(c=getchar())!='\n';j++) name[i][j]=c; name[i][j]='\0'; }
227
for(i=0;i<(m-1);i++)
for(j=i+1;j<m;j++) if (strcmp(name[i],name[j])>0) { strcpy(temp,name[i]); strcpy(name[i],name[j]); strcpy(name[j],temp); } for(i=0;i<m;i++) { printf("\n"); for(j=0;name[i][j]!='\0';j++) printf("%c",name[i][j]); } }
228
Consider the declaration int i=5;
POINTERS Consider the declaration int i=5; This declaration tells the C compiler to Reserve space in memory to hold the integer value. Associate the name I with this memory location Store the value 5 at this location We can represent i‘s location in the memory by the following memory map i location name 5 value at location location address
229
Here & used in the program is “address of” operator
Eg:- Main() { int =5; printf(“\n address of i= %u”,&i); printf(“\n value of i = %d”,i); printf(“\n value of i =%d”,*(&i)); } Here & used in the program is “address of” operator * used in the program is “value at address” operator or “indirection” operator Eg: Main() { int i=5; int *j; j=&i; printf(“\n address of i=%u”,&i); printf(“\n value of I=%d”,*(&i)); printf(“\n address of i=%u”,j); printf(“\n value of i=%d”,*j); }
230
Relationship between pv and v is
pv = &v; v = *pv; Eg: int *alpha; char *ch; float *s; Here alpha , ch , s are declared variables i.e variables capable of holding addresses. i.e alpha is going to contain the address of an integer value. ch is going to contain the address of a character value. s is going to contain the address of a float value. A pointer is a variable that represents the location of a data item such as a variable or an array element. All variables that can be accessed directly by heir names can also be accessed indirectly by means of pointers.
231
Pointer arithmetic The size of the data type which the pointer variable points to is the number of bytes accessed in memory when the pointer variable is dereferenced using the indirection operator. The size of the pointer variable is thus dependent on the data type of the variable ‘pointed to’ by the pointer A pointer to an int accesses 2 bytes of memory A pointer to a char accesses 1 byte of memory A pointer to a float accesses 4 bytes of memory A pointer to double accesses 8 bytes of memory
232
Call by value /* TO SWAP TWO NUMBERS (swap.c)*/ /* function with arguments and no return values*/ #include<stdio.h> void main() { int x,y; printf("\n input any two numbers"); scanf("%d%d",&x,&y); printf("\n before swapping : %d %d",x,y); swap(x,y); printf("\n after swapping : %d %d",x,y); } swap(int a,int b) { int temp; temp=a; a=b; b=temp; }
233
Call by reference /* TO SWAP TWO NUMBERS (swap.c)*/ /* function with arguments and no return values*/ #include<stdio.h> void main() { int x,y; printf("\n input any two numbers"); scanf("%d%d",&x,&y); printf("\n before swapping : %d %d",x,y); swap(&x,&y); printf("\n after swapping : %d %d",x,y); } swap(int *a,int *b) { int temp; temp=*a; *a=*b; *b=temp; }
234
/* STANDARD DEVIATION using pointer(sd_poi.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,n; float *x,sx=0.0,xbar,sxx=0.0,sd,var; clrscr(); printf("\n enter how many number of observations are there?"); scanf("%d",&n); x=(float *)malloc(n*sizeof(float)); printf("\n enter the observations"); for(i=0;i<n;i++) { scanf("%f",(x+i)); sx+=*(x+i); }
235
xbar=sx/n; for(i=0;i<n;i++) sxx+=((*(x+i)-xbar)*(*(x+i)-xbar)); sd=sqrt(sxx/n); printf("\n the mean is %f",xbar); printf("\n the standard deviations of the given number id %f",sd); }
236
/* SORTING THE NUMBERS IN THE ASC.ORDER USING POINTER CONCEPT (asc_poi.c)*/
#include<stdio.h> #include<math.h> main() { int i,j,n,*x,temp; printf("\n HOW MANY NUMBER OF OBSERVATIONS ARE THERE ?"); scanf("%d",&n); x=(int *)malloc(n*sizeof(int)); printf("\n ENTER THE OBSERVATIONS"); for(i=1;i<=n;i++) scanf("%d",(x+i)); for(i=1;i<=n-1;i++) for(j=i+1;j<=n;j++)
237
if (*(x+i) > *(x+j))
{ temp=*(x+j); *(x+j)=*(x+i); *(x+i)=temp; } printf("\n THE SORTED LIST IS :"); for(i=1;i<=n;i++) printf("\n %d",*(x+i));
238
/*SUM OF THE TWO MATRICES USING POINTER CONCEPT (matsum_p.c) */
#include<stdio.h> #include<math.h> #include<alloc.h> #include<conio.h> main() { float *a[5],*b[5],*c[5],t; int m,n,i,j; clrscr(); printf("\n ENTER THE ORDER OF THE MATRICES (m*n):"); scanf("%d%d",&m,&n); printf("\n enter any float value"); scanf("%f",&t); for(i=0;i<m;i++) { a[i]=(float *)malloc(n*sizeof(float)); b[i]=(float *)malloc(n*sizeof(float)); c[i]=(float *)malloc(n*sizeof(float)); }
239
printf("\n ENTER THE FIRST MATRIX :\n ");
for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%f",(a[i]+j)); printf("\n ENTER THE SECOND MATRIX:\n "); scanf("%f",(b[i]+j)); { printf("\n"); { *(c[i]+j)=*(a[i]+j) + *(b[i]+j); printf("\t %f",*(c[i]+j)); } } }
240
/*PRODUCT OF THE TWO MATRICES USING POINTER CONCEPT (matmul_p.c) */
#include<stdio.h> #include<math.h> #include<conio.h> main() { float *a[20],*b[20],*c[20],f; int m,n,i,j,k,p,q; clrscr(); printf("\n ENTER THE ORDER OF THE FIRST MATRIX (m*n):"); scanf("%d%d",&m,&n); printf("\n enter any value for f"); scanf("%f",&f); for(i=1;i<=m;i++) a[i]=malloc(n*sizeof(float)); printf("\n ENTER THE ORDER OF THE SECOND MATRIX (p*q):");
241
scanf("%d%d",&p,&q); for(i=1;i<=p;i++) b[i]=(float *)malloc(q*sizeof(float)); for(i=1;i<=m;i++) c[i]=(float *)malloc(q*sizeof(float)); if(n!=p) printf("\n THE MATRIX MULTIPLICATION IS NOT POSSIBLE \n"); else { printf("\n ENTER THE FIRST MATRIX :\n"); for(j=1;j<=n;j++) scanf("%f",(a[i]+j)); printf("\n ENTER THE SECOND MATRIX:\n "); for(j=1;j<=q;j++) scanf("%f",(b[i]+j));
242
printf("\n THE PRODUCT OF THE TWO MATRICES IS : \n\n");
for(i=1;i<=m;i++) { printf("\n"); for(j=1;j<=q;j++) *(c[i]+j)=0; for(k=1;k<=n;k++) *(c[i]+j)+=*(a[i]+k) * *(b[k]+j); printf("\t %f",*(c[i]+j)); } } } }
243
/* MATRIX TRANSPOSE USING POINTER CONCEPT (matran_p.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { int i,j,m,n; int *a[5],*b[5]; clrscr(); printf("\n ENTER THE SIZE OF THE MATRIX (m*n)\n "); scanf("%d%d",&m,&n); for(i=1;i<=m;i++) { a[i]=(int *)malloc(n*sizeof(int)); b[i]=(int *)malloc(n*sizeof(int)); } printf("\n ENTER THE VALUES OF THE MATRIX : \n"); for(j=1;j<=n;j++)
244
scanf("%d",(a[i]+j)); printf("\n TRANSPOSE OF A GIVEN MATRIX IS : \n"); for(i=1;i<=n;i++) { printf("\n"); for(j=1;j<=m;j++) *(b[i]+j)=*(a[j]+i); printf("%d \t ",*(b[i]+j)); } } }
245
Linear search/ sequential search
This is the simplest known for searching a table for a particular record. In Linear or sequential search we start with the first available record. i.e the record that comes first. If this is required record then our search is over, else we take up the second record and see if this is the record that we need. If this too is not the required record then we pick up the third record. This process of considering the next record will go on till we find the required record or all the records in the table are exhausted. The performance of a search algorithm can be measured by counting the number of comparisons taken to find a given record. For measuring the performance , we must take into consideration the two case, I) the worst case and ii) average case for finding the average case performance, we find out the number of comparisons needed in the worst case and best case.
246
Now in the best case we need only one comparison while in the worst case we need n comparisons so that for the average case we shall be needing (N+1)/2 comparisons. Since for both the average case and worst case of comparisons is proportional to the number of records N, thus we say that the average search time for this method is of O(N), that is of order of N. Binary search Binary search is called so because on each search the table to be searched is divided into two parts. One of which is ignored as it will not contain the required element. One essential condition for the binary search is that the table which is to be searched should be arranged in alphabetic or numerical order. This is absolutely necessary for this method to work.
247
Binary search In Binary search we start by taking a look at the approximate middle element. If the number of elements in the table is odd then the middle element is considered . In case the table has even number of elements then the last element of the first half is taken into consideration. If the value is greater than the element to be searched than we discard the first half of the table and start again by taking the second half of the table. We keep on looking for the middle element of the table and keep on discarding either he first or the second half of the table depending on the result of the comparison of the middle element and the element to be searched till we find the required element or when the table cannot be further subdivided.
248
Selection sort Selection sort is one of the easiest ways to sort a table. As the name implies , the underlying principle is that of selection . Beginning with the first record , a search is performed to find the smallest element in the table. This smallest element then interchanged with the first record of the table. So now the smallest record or element is in the right position. Then we search for the second smallest element in the table and replace it with the second element of the table. Thus by now we have placed two elements of the table in their correct positions . This process of searching for the next smallest element of the table and its proper positioning continues till the table is exhausted and all element or records have been placed in the desired ascending order.
249
Bubble sort Bubble sort is a simple sorting technique. Adjacent elements are compared . If they are not in order , they are swapped . For example while sorting in ascending order , the element with the largest value will move to the end of the array in the first pass. After the first pass , since the element with the largest value has reached its final position, the size of the array to be sorted reduces by 1. This process goes on till all elements are in their respective positions . The time complexity of bubble sort is O ( n2 ). Since the motion of smaller elements of the table resembles the motion of air bubbles in a liquid , the method is called bubble sort.
250
#include<stdio.h>
main() { int b[10],j=0,i,n,flag=0; float a[100],num; printf("\n enter the value of n"); scanf("%d",&n); printf("\n enter the values one by one"); for(i=0;i<n;i++) scanf("%f",&a[i]); printf("\n enter the number to be searched"); scanf("%f",&num); if (a[i]==num) { flag=1; b[j]=i+1; j++; } if (flag==0) printf("\n the number not found"); else { printf("\n the number found at the following position(s)"); for(i=0;i<j;i++) printf("\t %d",b[i]); }
251
/* BINARY SEARCH (binsearh.c)*/
#include<stdio.h> #include<math.h> #include<conio.h> main() { float a[99],x; int i,n,up,low,mid; clrscr(); printf("\n ENTER THE NO.OF ELEMENTS \n"); scanf("%d",&n); printf("\n ENTER THE OBSERVATIONS IN THE ASCENDING ORDER \n"); for(i=0;i<n;i++) scanf("%f",&a[i]); printf("\n GIVE THE NUMBER TO BE FOUND OUT \n "); scanf("%f",&x);
252
low=0; up=n-1; do { mid=(up+low)/2; printf("\n %d",mid); if (x>a[mid]) low=mid+1; else up=mid-1; } while ((x!=a[mid]) && (low<=up)); if (x==a[mid]) printf("\n THE POSITION OF %f IS %d",x,mid+1); else printf("\n GIVEN NUMBER IS NOT IN THE ARRAY"); }
253
STRUCTURE We know that Array is a data structure whose elements are all of the same data type, whereas in structure the individual elements can differ in type. Thus a single structure might contain integer elements , floating point elements and character elements. Pointer, arrays and other structures can also be included as elements within a structure . The individual structure elements are referred to as members. Structure declarations are somewhat more complicated than array declarations , since a structure must be defined in terms of its individual members. In general terms , the composition of a structure may be defined as
254
Struct tag { member 1; member 2; ……….. member n; };
255
In this declaration , struct is required keyword, tag is a name that identifies structures of this type. And member1, member2, ………member n are individual member declaration. Eg:- A single catalog card from a library may be represented by the following ndividual variables. Struct card { char title[30]; char author[30]; int catalognum; int copies; }; It is also possible to combine the declaration of the structure composition with that of the structure variables as Struct tag {
256
Unions Unions , like structures contain members whose individual data types may differ from one another. However he members within a union all share the same storage area within a structure is assigned its own unique storage area. Thus unions are used to conserve memory . They are useful for applications involving multiple members, where values need not be assigned to all of the members at any one time. Difference between structures and unions The amount of memory required to store a structure variable is the sum of sizes of all the members in addition to the padding bytes that may be provided by the compiler . On the other hand incase of a Union , the amount of memory required is the same as that required by its largest member.
257
Eg:- #include<stdio.h> struct employee { char name[25]; int idno; float salary; }; union desig { char name[25]; int idno; float salary; }; void main() { printf(“\n size of the structure is %d”,sizeof(employee)); printf(“\n size of the union is %d”,sizeof(desig)); }
258
Operations on members While all the structure members can be accessed at any point of time , only one member of a union ma be accessed at any given time. This is because at any instant only one of the union variables will have a meaningful value. Only that member which is last written can be read. At this point other variables ill contain garbage. It is the responsibility of the programmer to keep track of the active variable (i.e the variable which was last accessed).
259
Operations on a Union Union has all the features provided to a structure except for minor changes which are consequence of he memory sharing properties of a union. This is made evident by the following operations on unions which are legal An union variable can be assigned to another union variable A union variable can be passed to a function as a parameter The address of the union variable can be extracted by using the address of operator(&) A function can accept and return a union or a pointer to a union
260
/*struct1.c */ include<stdio.h> #include<math.h> main() { struct { char title[10]; float price; int pages; } b1; printf("\n enter the title of the book"); scanf("%s",b1.title); printf("\n enter the price"); scanf("%f",&b1.price); printf("\n enter the pages"); scanf("%d",&b1.pages); printf("\n %s %f %d",b1.title,b1.price,b1.pages); }
261
/*struct2.c */ #include<stdio.h> void main() { struct student char regdno[5],name[80],remark[5]; float maths,phy,chem,total,perc; } ; struct student s[10]; int i,n; float temp; printf("\n temp"); scanf("%f",&temp);
262
printf("\n enter the no of students in the class");
scanf("%d",&n); printf("\n enter the regdno,name,maths,physics,chemistry"); for(i=0;i<n;i++) { scanf("%s%s%f%f%f",s[i].regdno,s[i].name,&s[i].maths,&s[i].phy,&s[i].chem); s[i].total=s[i].maths+s[i].phy+s[i].chem; s[i].perc=(s[i].total/300.0)*100.0; if (s[i].perc<40) strcpy(s[i] } for(i=1;i<=n;i++) printf("%f%f%f%f%f",s[i].maths,s[i].phy,s[i].chem,s[i].total,s[i].perc); }
263
/*struct3.c*/ #include<stdio.h> #include<string.h> void main() { struct library { char title[50],author[50]; int catlogno,copies; } ; struct library l[100]; int i,j,n; char t[50]; float temp; printf("\n temp"); scanf("%f",&temp); printf("\n enter the no of books "); scanf("%d",&n);
264
printf("\n enter the title,author,catlogno,copies");
for(i=0;i<n;i++) scanf("%s%s%d%d",l[i].title,l[i].author,&l[i].catlogno,&l[i].copies); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if (strcmp(l[i].author,l[j].author)>0) { strcpy(t,l[i].author); strcpy (l[i].author,l[j].author); strcpy (l[j].author,t); } printf("\n %s %s %d %d",l[i].title,l[i].author,l[i].catlogno,l[i].copies); }
265
/*struct4.c*/ #include<stdio.h> #include<string.h> void main() { struct library { char title[50],author[50]; int catlogno,copies; }; struct library *l,*t; int i,j,n; float temp; printf("\n temp"); scanf("%f",&temp); printf("\n enter the no of books "); scanf("%d",&n); printf("\n enter the title,author,catlogno,copies"); for(i=0;i<n;i++) scanf("%s%s%d%d",l[i].title,l[i].author,&l[i].catlogno,&l[i].copies); for(i=0;i<n-1;i++)
266
for(j=i+1;j<n;j++)
if (strcmp(*(l+i)->author,*(l+j)->author)) strcpy(t,l[i].author); strcpy (l[i].author,l[j].author); strcpy (l[j].author,t); } for(i=0;i<n;i++) printf("\n %s %s %d %d",l[i].title,l[i].author,l[i].catlogno,l[i].copies); } /* MENU13 (menu13.c)*/ #include<stdio.h> #include<stdlib.h> struct date { int dd; int mm; int yyyy; }; struct stud { char name[20]; int rno,rank;
267
struct date dob; }; struct stud s[100]; struct stud *st1,*st2; void read(); void sortnames(); void sortdob(); void sortnames_dob(); void swap(struct stud *st1,struct stud *st2); int i,n; void main() { int ch; char c; do {printf("\n MENU-13"); printf("\n 1. READ STUDENT DATA"); printf("\n 2. SORTING NAMES"); printf("\n 3. SORTING DOB"); printf("\n 4. SORTING NAMES & DOB");
268
printf("\n 5. exit"); printf("\n Enter your choice"); scanf("%d",&ch); switch(ch) { case 1: clrscr();read();break; case 2: clrscr();sortnames();break; case 3: clrscr();sortdob();break; case 4: clrscr();sortnames_dob();break; case 5: exit(0);break; default : printf("\n wrong entry, Try again"); } ch=getchar(); } while(ch!=5); } void read() {
269
printf("\n How many students");
scanf("%d",&n); for(i=0;i<n;i++) { printf("\n ROLL NO:"); scanf("%d",&s[i].rno); printf("\n NAME:"); scanf("%s",s[i].name); printf("\n RANK:"); scanf("%d",&s[i].rank); printf("\n DATE OF BIRTH( dd-mm-yyyy)"); scanf("%2d-%2d-%4d",&s[i].dob.dd,&s[i].dob.mm,&s[i].dob.yyyy); } } void sortnames() { int j; for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if (strcmp(s[i].name,s[j].name)>0) swap(&s[i],&s[j]);
270
printf("\n RNO NAME RANK DATE OF BIRTH");
for(i=0;i<n;i++) {printf("\n %d %s %d %2d-%2d-%4d",s[i].rno,s[i].name,s[i].rank,s[i].dob.dd,s[i].dob.mm, s[i].dob.yyyy); } } void sortdob() { int j; for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) {if(s[i].dob.yyyy==s[j].dob.yyyy) if(s[i].dob.mm==s[j].dob.mm) { if (s[i].dob.dd>s[j].dob.dd) swap(&s[i],&s[j]); }
271
else { if(s[i].dob.mm>s[j].dob.mm) swap(&s[i],&s[j]); } { if(s[i].dob.yyyy>s[j].dob.yyyy) swap(&s[i],&s[j]); } }
272
printf("\n RNO NAME RANK DATE OF BIRTH");
for(i=0;i<n;i++) { printf("\n %d %s %d %2d-%2d-%4d",s[i].rno,s[i].name,s[i].rank,s[i].dob.dd,s[i].dob.mm, s[i].dob.yyyy); } void sortnames_dob() int j; for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if (strcmp(s[i].name,s[j].name)>0) swap(&s[i],&s[j]); else if (strcmp(s[i].name,s[j].name)==0)
273
printf("\n RNO NAME RANK DATE OF BIRTH");
{ if (s[i].dob.yyyy==s[j].dob.yyyy) if (s[i].dob.mm==s[j].dob.mm) if(s[i].dob.dd>s[j].dob.dd) swap(&s[i],&s[j]); if (s[i].dob.mm>s[j].dob.mm) swap(&s[i],&s[j]); if (s[i].dob.yyyy>s[j].dob.yyyy) swap(&s[i],&s[j]); } printf("\n RNO NAME RANK DATE OF BIRTH"); printf("\n "); for(i=0;i<n;i++) printf("\n %d %s %d %2d-%2d-%4d",s[i].rno,s[i].name,s[i].rank,s[i].dob.dd,s[i].dob.mm,
274
s[i].dob.yyyy); } } } void swap(struct stud *st1,struct stud *st2) { struct stud t; t=*st1; *st1=*st2; *st2=t; }
275
FILES FILE I/O is always done in a program in the following sequence Open the file Read from or write to the file Close the file Opening the files Before performing any FILE I/O , the file must be opened. While opening the FILE, the following are specified The name of the FILE The manner in which it should be opened (i.e for reading, writing, both reading and writing , appending at the end of the FILE , over writing the FILE etc) The function fopen is used to open a file. It accepts two strings. The first is name of the file and the second is the mode in which it should be opened. The general format for declaring and opening a FILE is
276
The first statement declares the variable fp as a pointer o the data type FILE. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This pointer which contains all the information about the file is subsequently used as a communication link between the system and the program. The second statement also specifies the purpose of opening this file . The mode does this job . mode can be of the following r open the file for reading only w open the file for writing only a open the file for appending
277
Writing to files The fprintf function writes the variable to the file . Just as printf writes to the screen , the function fprintf writes to a file. The only difference is that fprintf accepts extra parameter i.e a pointer to the FILE structure return by fopen. The function puts outputs a string, adding a new line character at the end and putc outputs a single character. Similarly there exists functions fputs and fputc for using strings and characters into a FILE. The functions fputs and fputc accept a pointer o the FILE structure as the first parameter, in addition to the string or character to be output.
278
Having opened the file and written it we need to close the file
Having opened the file and written it we need to close the file. This is done by calling the function fclose with he pointer returned by fopen. Eg 1:- Void main() { int I; FILE *fp; fp = fopen(“outfile1.dat”,”w”); printf(“\n input an integer”): scanf(“%d”,&I); fprintf(fp,”%d”,I); fclose(fp); }
279
Eg 2:- Void main() { FILE *fp; fp = fopen(“outfile2.dat”,”w”); fputs(fp,”string written to file”); fputc(fp,’c’); fclose(fp); } Reading from files The functions scanf, gets and getc are used o read from the standard input. To read from a file the functions fscanf,fgets and fgetc are used . All these functions accept a FILE pointer as their first parameter , in addition to the parameters required by the standard input functions.
280
Void main() { int i; FILE *fp; fp = fopen(“outfile1.dat”,”r”): fscanf(fp,”%d”,i); printf(“the integer in outfle1.dat is %d”,i); fclose(fp); } Closing files During a write to a file , the data written is not put on the disk immediately. It is stored in a buffer. When the buffer is full , all its contents are actually written to the disk. The process of emptying the buffer by writing its contents to disk is called flushing the buffer. Closing the file flushes the buffer and releases the space taken by the FILE structure which is returned by fopen. Operating systems normally impose a limit on the number of files that cab be opened by a process at a time . Hence closing a file means that another can be opened n its place.
281
Block read & Block write
fwrite & fread fwrite(const void *ptr, size_t size, size_t n, FILE * stream); fread(const void *ptr, size_t size, size_t n, FILE * stream); Argument meaning ptr pointer to the data to be written size length of each item of data n number of data items to be appended stream specifies output file on end _of _ file they return 0.
282
/*fil1.c */ #include<stdio.h> #include<stdlib.h> void main() { FILE *fptr1,*fptr2,*fptr3; int i,x; fptr1=fopen("number.dat","wb"); for(i=0;i<10;i++) { scanf("%d",&x); putw(x,fptr1); } fclose(fptr1); fptr1=fopen("number.dat","rb"); fptr2=fopen("even.dat","wb");
283
fptr3=fopen("odd.dat","wb");
while(!feof(fptr1)) { x=getw(fptr1); if(x%2==0) putw(x,fptr2); else putw(x,fptr3); } fclose(fptr1); fclose(fptr2); fclose(fptr3); fptr2=fopen("even.dat","rb"); while (!feof(fptr2)) { printf("\n"); x=getw(fptr2); printf("%d",x); }
284
fclose(fptr2); fptr3=fopen("odd.dat","rb"); while (feof(fptr3)==0) { printf("\n"); x=getw(fptr3); printf("%d",x); } fclose(fptr3);
285
/* TO CALCULATE PERCENTAGE OF MARKS IN A FILE (fil2.c) */
#include<stdio.h> #include<conio.h> main() { int n,i; FILE *fptr; struct student { int rollno; int bt101; int bt102; int bt103; int total; float perc; char name[10]; }; struct student s1; fptr=fopen("student.dat","w"); clrscr(); printf("\n How many students are there");
286
scanf("%d",&n); for(i=0;i<n;i++) { printf("\n rollno,name,bt101,bt102,bt103"); scanf("%d %s %d %d %d",&s1.rollno,s1.name,&s1.bt101,&s1.bt102,&s1.bt103); s1.total=s1.bt101+s1.bt102+s1.bt103; s1.perc=s1.total/3.0; fwrite(&s1,sizeof(s1),1,fptr); } fclose(fptr); clrscr(); printf("\n P.V.P. SIDDHARTHA INSTITUTE OF TECHNOLOGY");
287
printf("\n VIJAYAWADA");
printf("\n LIST OF MARKS OF THE STUDENTS \n\n"); printf("\n rollno name bt101 bt102 bt103 total perc"); printf("\n "); fptr=fopen("student.dat","r"); while(fread(&s1,sizeof(s1),1,fptr)==1) { printf("\n %d %s %d %d %d %d %f",s1.rollno,s1.name,s1.bt101,s1.bt102,s1.bt103, s1.total,s1.perc); } fclose(fptr); }
288
/*fil3.c */ #include<stdio.h> void main() { FILE *f1,*f2,*f3; int x,i,n; printf("\n how many obvs are there"); scanf("%d",&n); f1=fopen("number.dat","w"); for(i=0;i<n;i++) scanf("%d",&x); fprintf(f1,"%d",x); }
289
fclose(f1); f1=fopen("number.dat","r"); f2=fopen("even.dat","w"); f3=fopen("odd.dat","w"); while(!feof(f1)) { x=getw(f1); if (x%2==0) putw(x,f2); else putw(x,f3); } fclose(f2); fclose(f3); printf("\n contents of evendata are"); f2=fopen("even.dat","r");
290
while(!feof(f2)) { x=getw(f2); printf("\n %d",x); } fclose(f2); f3=fopen("odd.dat","r"); printf("\n contents of odddata are"); while(!feof(f3)) { x=getw(f3); printf("\n %d",x); } fclose(f3); }
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.