2.9k likes | 2.91k Views
C – PROGRAMMING By Dr. K. Srinivasu Principal, PVP Siddhartha Institute of Technology. Evolution of computers :.
E N D
C – PROGRAMMING By Dr. K. Srinivasu Principal, PVP Siddhartha Institute of Technology
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.
First Generation (1951-1959): The first electronic general purpose computer ‘THE ENIAC ’ [ Electronic Numerical Integrator And Computer ]. It occupied 1500 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.
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.
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
Third Generation(1964-1970) 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
Fourth Generation (1970-1990) 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.
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
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.
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.
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)
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 - 1 Mega Byte (2e10*2e10 Bytes) 1024MBs - 1 Giga Byte (2e10*2e10*2e10 Bytes) The size of the computer’s memory is usually expressed in KB’s and MB’s
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.
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…..
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
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
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.
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
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.
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
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:-
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)
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.
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
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.
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: 0 to 9
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
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
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)
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)
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
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
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 17.548. Such numbers are called real(floating point) constants. A real number may also be expressed in exponential (or scientific) notation. For example, the value 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiply by 10 *10 The general form is mantessa e exponent Range : 1.7e–38 to 1.7e+38
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 \0 null
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.
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
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 –32768 to 32767 (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.
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
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*/ ……………….. ……………….. }
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;
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
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.
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 .
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=3 Expression Value a+b 13 a-b 7 a*b 30 a/b 3 a%b 1
If v1=12.5 v2=2 Expression Value v1+v2 14.5 v1-v2 10.5 v1*v2 25.0 v1/v2 6.25 If r1=-0.66 r2=4.5 r1+r2 3.84 r1-r2 -5.16 r1*r2 -2.97 r1/r2 -0.146667 If i=7,f=5.5,c=119 (i+c)-(2*f/5) = (7+119)-(2*5.5/5) = 126-(2*1.1) = 123.8
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 = 2.51428 –5.2 = -2.68571 b. 2*x/(3*y) = 2*8.8/10.5 = 17.6/10.5 = 1.67619 .
2*x/3*y = 2*8.8/3*3.5 = 17.6/3*3.5 = 5.8666*3.5 =20.5333 2*y+3*(x-z) = 2*3.5 + 3*(8.8+5.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 = 5+56-48*1/3 = 5+56-48/3 = 5+56-16 =45 9 –12/(3+3)*(2-1) = 9-12/6*1= 9-2*1 =7
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.
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=3 Expression Interpretation value i<j true 1 (i+j)>=k true 1 (j+k)>(i+5) false 0 k!=3 false 0 j==2 true 1 simple relational expression contain only one relational operator and takes the following form ae-1 relational operator ae-2
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 1 (i>=6)|| (c==119) true 1 (f<11)&&(i>100) false 0 (f>5) true 1 !(f>5) false 0 i<=3 false 0 !(i<=3) true 1 i>(f+1) true 1 !(i>(f+1)) false 0