1 introduction&basics
TRANSCRIPT
-
8/6/2019 1 Introduction&Basics
1/42
INTRODUCTION TO COMPUTERS
What is a Computer?Historically, a computer, broadly defined, as an electronic device that
helped in computation counting, calculating, addition, multiplying, dividingetc. As you might guess from the word compu-tation computer is defined.
Today computer is an electronic device that stores , manipulates andanalyzes the information.Block Diagram of a computer
1
CentralProcessing
Unit(CPU)
INPUT UNIT OUTPUT UNIT
CONTROL UNIT
ARTHEMATIC &
LOGIC UNIT
(ALU)
MAIN MEMORYINPUT UNITOUPUT UNIT
SECONDARY STORAGE
-
8/6/2019 1 Introduction&Basics
2/42
1. INPUT UNIT:It obtains information (data and programs) from various input
devices and place this information at the disposal of the other unitsso that information may be processed. Most information is entered into
computer today through keyboard and mouse devices. Information canalso enter by speaking and by scanning images. Some of other inputdevices are touch screen (used in ATMs), joystick, electronic pen etc
2. CENTRAL PROCESSING UNIT:It is the mind and heart combined with the central nervous
system of a computer. So the CPU performs functions similar to themind, heart of a human body. It consists of three components
1) Arithmetic & Logic Unit (ALU)2) Storage devices
a. Main memoryb. Secondary memory3) Control Unit
The functions of CPU are to:-
(i) Stores data as well as instructions.(ii) Controls the sequence of operations as per the stored
instructions.(iii) Issue commands to all parts of the computer system.(iv) Carry out data processing and send results to output
2.1 Arithmetic and Logic Unit (A.L.U):It operates on the data available in the main memory and sends
them back after processing, once again to the main memory A.L.U performstwo functions
1) It carries out arithmetical operations like addition, subtraction,multiplication and division .
2) It performs certain logical actions based on AND and OR functions.2.2 Control Unit:
The control unit directs all operations inside the computer. It is
known as nerve centre of the computer because it controls and coordinatesall hardware operations i.e. those of the CPU and input-output devices. Itsactions are
1. It gives command to transfer data from the input device to thememory to ALU.
2
-
8/6/2019 1 Introduction&Basics
3/42
2. It also transfers the results from ALU to the memory and onto theoutput device for printing.
3. It stores the program in the memory, takes instructions one by one,understands them and issues appropriate commands to the other
units.4. It fetches the required instructions from the main storage.2.3.1 Primary Memory:
It is also called as main memory because, like the human memory it isable to store information, which can be recalled or accessed when required.The program of instructions has to be stored in the main memory in order tomake it work automatically.
Any item of data or any instruction stored in this memory can beretrieved by the computer at high speed. The modern computer does this in
nano seconds. Main high speed memory limited in size and very costly to buy.Examples: RAM(Random access memeory)2.3.2 Secondary Memory:
These are also known as extended or auxiliary memory. These arethe devices that hold the mass of information, which may be transferredduring processing. These devices are used for permanent storage of data. Ascompared to the primary memory, it has a much larger capacity, but is not asfast. The computer thus takes slightly more time to retrieve from secondarystorage. While retrieval from the main memory needs just a few nano-
seconds, it may take milliseconds. But secondary storage is virtuallyunlimited in size and is much cheaper than main memory.Example: Hard disk, Compact disks (CDs)
3. OUTPUT UNIT:The result of any computer processing has to be communicated to the
user. Output devices translate the computers output into a formunderstandable to human beings. Some of the output devices are displayscreen, printer etc.HARDWARE:
It is a general term used to represent the physical and tangiblecomponents of the computer itself i.e. those components which can betouched and seen. It includes
(1) Input devices(2) Output devices(3) Central processing Unit(4) Storage devices
3
-
8/6/2019 1 Introduction&Basics
4/42
SOFTWARE:It is a general term to describe all the forms of programs associated
with a computer. Without software, a computer is like a human body with outa soul. There are
Four major categories of software(1) Operating systems(2)Utility programs(3)Language processors(4)Application programs
OPERATING SYSTEM: It is the interface between the user and the computer
hardware . These programs are in-built into the computer and are used togovern the control of the computer hardware components, such as
processors, memory devices and input/output devices. Examples: MS-DOS, Win-9X, Solaris ,Unix , Linux.MACHINE LANGUAGE:
Computer is an electronic device which can understand only pulseand no-pulse (1 and 0) conditions. Therefore, the instructions given to thecomputer and the data fed to it must be written using binary numbers 1 and0. A program written in binary coded form(0s and 1s) which can be directlyfed to computer for execution is known as MACHINE LANGUAGE andrepresents the lowest level of programming.
Computers are not identical in design. Therefore, each computer hasits own machine language. It is very hard to understand and remember thevarious combinations of 0s and 1s representing numerous data andinstructions. It takes more time to write programs and to debug. Thusmachine language programs are difficult to write and maintain.
Also, since every computer has its own machine language, theprogrammer cannot communicate with other computers if he does not knowits machine language.Advantage : 1) It executes very fast.Disadvantage : 1) It is very hard to develop an application or program.ASSEMBLY LANGUAGE:
To ease the programmers burden, mnemonic operation codes weredeveloped. One of the first steps in improving the program preparationprocess was to replace the numeric language operation codes withmnemonics.
4
-
8/6/2019 1 Introduction&Basics
5/42
Thus, an assembly language uses mnemonic codes(abbreviations)rather than numeric codes(as used in machine lang).For example
ADD CP SPSUB CP SP
As the computer understands only machine language instructions, aprogram written in assembly language must be translated into machinelanguage before it can be executed. This translation is done by anotherprogram called ASSEMBLER. For example
SUB CP SP0111111 011111111111 000000111111Assembly language has several advantages over machine language.
These programs are easy to write and modify than machine languageprograms. However, assembly language is again a machine oriented language
and the program has to be different for different machines.ASSEMBLER: An assembly language can be translated into a machine languageby replacing the mnemonic and symbolic information by its numericequivalent. A program which converts an assembly language program into amachine language program is called an assembler .HIGH LEVEL LANGUAGES: A set of languages have been devised which are very close to ournative (English) language. Such a set of languages is called HIGH LEVEL
LANGUAGES. A program has to be translated into machine language beforethe computer can perform all operations specified by this language. Specialprograms called language processors are available to do this job. Thesespecial programs accept the user program and check each statement and, ifit is grammatically correct, produce a corresponding set of machine languageinstructions. Language processors are also known as translators .(Compilersand Interpreters )
The most important characteristic of high level language is that it ismachine independent. The advantage is it is easy to develop an
application(program) using HLLs then ALs and MLL and the disadvantage isits take extra time for conversion and thus are less efficient as comparedto the machine language programs.
5
-
8/6/2019 1 Introduction&Basics
6/42
COMPILER:A high level language can also be converted into a machine language by
a program called compiler.A compiler checks the entire user-written program (known as the
source program) and, if error free, produces a complete program in machinelanguage (known as object program). The source program is retained forpossible modifications and corrections and the object program is loaded intothe computers memory for execution.NOTE: Compiler is software not hardware.INTERPRETER: An interpreter does a similar job but in a different style. Theinterpreter (as the name implies) translates one statement at a time and, iferror-free, executes the instruction. This continues till the last statement
in the program has been translated and executed. Thus, the interpretertranslates and executes the first instruction before it goes to thesecond, while a compiler translates the whole program beforeexecution can begin .The major differences between them are:a) Error Correction is much simpler in the case of an interpreter.b) Interpreter take more time for the execution of a program compared to
compilers because a statement has to be translated every time theprogram is executed.
HISTORY OF C:C language was developed by Dennis Ritchie at AT & T Bell
Laboratories in USA during 1971-72.C language evolved fromBasic combined programming language
(BCPL) (developed by Martin Richards for writing operating systemsoftware and compilers in 1967) and B (developed by Ken Thomson fordeveloping UNIX operation system in 1970).CHARACTERSTICS OF C LANGUAGE:
1) Modularity2) Extendibility3) Portability4) Speed5) Flexibility
6
-
8/6/2019 1 Introduction&Basics
7/42
MODULARITY: Modularity means ability to break down large modules in to manageablesub-modules. The programming language which supports modularity is calledmodular programming languages(C is modular programming language).
ADVANTAGES:1) Since many programmers involved in developing the project, the projectcan be complete with in the give time if each module is assigned to oneprogrammer.
2) Debugging becomes easier and faster.3) Software maintenance becomes easier.EXTENDIBILITY:
It is the ability to extend the existing software by adding new featureis called extendibility. C softwares can be extended.
PORTABILITY:It is the ability to port(install) the existing software indifferentplatforms. C software can be installed in any platform.PLATFORM:
A computer running under a specific operating system iscalled Platform.
e.g windows platform, linux platformFLEXIBILITY: One of the reasons C be flexible is keywords. ANSI ( American
National Standard Institute ) C has 32 keywords which forms the basicbuilding of C language.Since the programmer know when and where to apply these reserve
words they will have complete control over the language which leads toflexibility.SPEED:
**WHY C LANGUAGE CALLED MIDDLE LEVEL LANGUAGE?**Though C is a high level language, it is often referred to as middle
level language because programs written in C language run at the speeds
matching to that of programs written in assembly language.The speed of the C language programs is very fast. Thats thereason C language is used in system softwares (programs interact with thehardware e.g.. device drivers and operating systems).Note: The C compiler is developed in C language and UNIX operatingsystem
developed using C language.
7
-
8/6/2019 1 Introduction&Basics
8/42
-
8/6/2019 1 Introduction&Basics
9/42
C programs typically go through six phases to be executed .These areEdit, preprocess , compile, link, load and executes .
The first phase consists of editing a file. This is accomplished with aneditor program. C/C++ integrated program development environment
software packages such as Borland C and Turbo C for pcs and compatibleshave built-in editors that are smoothly integrated into the programmingenvironment. The programmer types a C program with the editor and makescorrections if necessary, then storing the program on a secondary storagedevice such as a disk. C program file names should end with the .Cextension.
Next, the programmer gives the command ( Alt+f9 ) to compile theprogram. The compiler translates the C program into machine language code(also referred to as object code). In a C system, a preprocessor program
executes automatically before the compilers translation phase begins. TheC preprocessor obeys special commands called preprocessor directiveswhich indicate that certain manipulations are to be performed on theprogram before compilation. The preprocessor is automatically invoked bythe compiler before the program is converted to machine language.
The next phase is called linking. C programs typically containreferences to functions defined elsewhere, such as in the standard librariesor in the private libraries of groups of programmers working on a particularproject. Linker links the object code with the required functions to produce
an executable code.The next phase is loading. Before a program can be executed, theprogram must first be placed in memory. This is done by the loader, whichtakes the executable code from disk and loads in to the memory. Additionalcomponents from shared libraries that support the program are also loadedby the loader.
Finally, the computer under the control of the CPU executes theprogram one instruction at a time. After executing the program we get therequired output.THE C STANDARD LIBRARY: C programs consist of modules or pieces called functions. You canprogram all the functions you need to form a C program, but most Cprogrammers take the advantage of a rich collection of existing functionscalled C Standard Library . Thus, there are really two pieces to learningthe C. The first is learning the C language itself and the second is learninghow to use the functions in the standard C library. The standard C librarys
9
-
8/6/2019 1 Introduction&Basics
10/42
required reading for programmers who need a deep understanding of thelibrary functions, how to implement them and how to use them to writeportable code.
e.g. printf and scanf functions are defined in std I/O library.
pow(a, b) and sqrt (n) defined in math header file.getch (); is defined in conio.h
INTRODUCTION TO C PROGRAMMINGSTEPS IN LEARNING C:
C CHARACTER SET:A Character denotes any alphabet, digit or special symbol used to
represent information. There are 255 characters defined in c. Everycharacter is represented with an ASCII value.ASCII- AMERICAN STANDARD CODE FORINFORMATION INTERCHANGE
CHARACTERS SYMBOLS ASCII VALUES
ALPHABETS
A,B,C..Z
a,b,c,z
65-90
97-122
DIGITS
0,1,2,3,..9 48-57
SPECIALSYMBOLS
~,!,@,#,$,%,^,&,*,(,),_,+,
|,`,.,>,
-
8/6/2019 1 Introduction&Basics
11/42
CONSTANTS: C constants are divided into two categories:
(1) Primary constants(2) Secondary constants
INTEGER CONSTATNTSa) An Integer constant must have at least one digit.b) It must not have a decimal point.c) It can be either positive or negative.d) If no sign precedes it considers as positive no.e) No commas or blanks are allowed within an integer constant.f) The allowable range for integer constants is -32768 to 32767.
Valid-Ex: 426 Invalid - 546.89 (decimal point)+789 10,000 (comma is present)-3456 20 000(blank is present)
REAL CONSTANTS a) A Real constants must have at least one digit.
b) It may or may not have a decimal point.c) It can be either positive or negative.d) If no signs precede it considers as positive no.e) No commas or blanks are allowed within a real constant.EX: 325.345
-345.322
11
C CONSTANTS
Primary Constants Secondary Constants
1) Integer Constants2) Real Constants3) Character Cons4) String Constants
Array
Pointer StructureUnionEnum etc;
-
8/6/2019 1 Introduction&Basics
12/42
CHARACTER CONSTANTS A character constant is a single alphabet, a single digit or a singlespecial symbol enclosed with in (single inverted commas).
a) The maximum length of a character constant can be 1 character. If
more than 1 characters it is not a character constant.Valid Examples: a Invalid : ab1 34% 2a&
NOTE: Character constant stored in 1 byte SRTING CONSTANTS : A single character or group of characters enclosed in (double
quotes) is called as string constant.Examples: a ab Hello 2345 NOTE: String constants stored in 2 bytes. DATATYPES: C language is rich in its data types. The variety of data types availableallows the programmer to select the type appropriate to the needs to theapplication.
The fundamental data types defined in C are DATA TYPE RANGE
char -128 to 127int -32768 to 32767float 3.4e-38 to 3.4e+38double 1.7e-308 to 1.7e+308
VARIABLE: An entity that may vary during program execution is calleda variable.
VARIABLE NAMES:Variable names are the names given to memory locations(variables).
These locations can contain integer, real or character constants.
An integer variable can hold only an integer constant, a real variablecan hold only a real constant and a character variable can hold only acharacter constant.RULES FOR CONSTRUCTING VARIABLE NAMES:
(a) A variable name is any combination of alphabets, numbers and only aspecial character underscore(_) is allowed.
(b) The length of the variable name should not exceed 31 characters.
12
-
8/6/2019 1 Introduction&Basics
13/42
-
8/6/2019 1 Introduction&Basics
14/42
Output : Welcome to C.Line 1: Begin with /* and end with */ indicating with these two linesare a comment. Programmers insert comments to document programs andimprove program readability. Comments do not cause the computer to
perform any action when the program is run. Comments are ignored by the Ccompiler and do not produce any machine language object code. Commentsalso help other people read and understand (purpose of the program).Line 2: This line tells the compiler to include the contents of standardinput/output header file ( stdio.h ) in the program. This header file containsinformation and declarations used by the compiler when compiling standardinput/output library functions such as printf and scanf .Line 3: main () Main is a special function defined in C. Every program musthave main() function. The program execution starts from this function. Themain function can be located anywhere in the program but the generalpractice is to place it as the first function for better readability.Line 4: The left brace {, must begin the body of every function. Acorresponding right brace must end each function. This pair of braces andthe portion of the program between the braces are called a block.Line 5: printf instructs the computer to perform an action, namely toprint on the screen the string of characters between double quotes.Note: Every C statement must end with semicolon; this ; acts as astatement terminator.C is a case-sensitive language and not space sensitive. Case-sensitive means upper case and lower case are different. All Cstatements are entered in small case letters only. C has nospecific rules for the position at which a statement is to bewritten. Thats why it is often called a free-form language .e.g.. If u write Main () it gives error. Give main ().
If we give printf (welcome to c); it is error freebecause it is free-form language.
14
-
8/6/2019 1 Introduction&Basics
15/42
1) /* Addition Program */2) #include3) void main()4) {
5) int integer1,integer2,sum; /* Declaration of variables */6) printf(Enter first integer\n); /* Prompt */7) scanf(%d,&integer1); /* read an integer */8) printf(Enter second integer\n); /* prompt */9) scanf(%d,&integer2); /*read an integer */10) sum=integer1+integer2; /*assignment of sum */11) printf(Sum is %d \n,sum); /* Print Sum */12) } /* End of the program */int integer1,integer2,sum;
It is declaration of variables. The words integer1 , integer2and sum are the names of variables. A variable is a location in memorywhere a value can be stored for use by a program. This declaration specifiesthat the variables integer1 , integer2 and sum are of type int which meansthat this variables will hold integer values i.e.. whole numbers such as7,0,2345 etc(but not 2.3,0.987). All variable must be declared with a nameand a data type immediately after the left brace that begins the body ofmain before they can be used in a program.Note : In C Uninitialized variables contains garbage values.
scanf() function:Syntax: scanf(format specifier, list of addresses of variables);e.g scanf(%d,&a);
%c character data%d integer data%f float data
The ampersand symbol & before each variable name is an operator thatspecifies the variable names address . We must always use this operator,otherwise unexpected results may occur.
Note : Dont use escape sequences in scanf function;MEMORAY CONCEPTS:Variable names such as integer1, integer2 and sum correspond to
locations of the computers memory. Every variable has a name, a type and avalue.
15
-
8/6/2019 1 Introduction&Basics
16/42
In the above program when the statement scanf(%d,&integer1);
is executed, the value typed by the user is place into a memory location towhich the name integer1 has assigned. Suppose user enters the number 10 as
the value for integer1. The computer will place 10 into location integer1 asshown below. Integer1 integer1
After declaring integer1 After taking value from the keyboard. integer2
Suppose if user enters 20 in 2nd
Once the program has obtained values for integer1 and integer2, itadds these values and places the sum into the variable sum. The statementSum= integer1 + integer2 ; occurs the calculated sum of
integer1 and integer2 is place into location sum (destroying the value thatmay already in sum i.e garbage value).
Sum
printf(): Syntax : printf(format string, list of variables);e.g printf(%d, a);
In the above program if printf(Sum is %d,sum); occurs it printsthe corresponding value in the variable sum i.e 30.ARTHEMATIC IN C: C evaluates arithmetic expressions in a precise sequence determinedby the following rules of precedence.1) Expression or portions of expressions contained within pairs of
parenthesis are evaluated first. Thus, parenthesis may be used to forcethe order of evaluation to occur in any sequence desired by theprogrammer. Parenthesis are said to be at the highest level ofprecedence. In cases of nested, or embedded, parenthesis, theexpression in the innermost pair of parenthesis is evaluated first.
2) Multiplication, division and modulus operations are evaluated next. If anexpression contains several multiplication, division and modulus
16
Garbagevalue
10
20
30
-
8/6/2019 1 Introduction&Basics
17/42
operations, evaluation starts proceeds from left to right. Multiplication,division and modulus are said to be on the same level of precedence.
3) Addition and subtraction operations are evaluated last. If an expressioncontains several addition and substraction operations, evaluation
precedes form left to right. Addition and substraction also have thesame level of precedence.Examples:
1. Algebra: a+b+c+d+e5
C: (a+b+c+d+e)/5;The parenthesis is required because division has higher precedence
then addition. If the parenthesis are not their it first calculates e/5 andadd from left to right.
2. Algebra: y=mx+cC : y=m*x+c;In this parenthesis is not required. The multiplication evaluates firstbecause multiplication has higher precedence then addition.3. z = p * r % q + w / x y
6 1 2 4 3 5 This expression evaluates in the order given above. Themultiplication, division and modulus are evalutes first in left-to-right order.Since they have high precedence than addition and substraction. The
addition and substraction evalutes next. These are also evaluates from leftto right. Last operation(i.e 6th) is assignment.4. y = a * x / x + b * x - c;
Suppose a=2 b=3 c=7 and x = 5Step 1 : y = 2 * 5 / 5 + 3 * 5 - 7; (left most multiplication)
Step 2 : y = 10 / 5 + 3 * 5 - 7; (left most division)Step 3 : y = 2 + 3 * 5 - 7; (multi before addition)Step 4 : y = 2 + 15 - 7; (leftmost addition)
Step 5 : y = 17 - 7; (last substraction)Step 6 : y = 10;
DECESION MAKINGEquality and Relational Operators
Executable C statements either performs actions(such ascalculations or input or output of data) or make decisions. We might make
17
-
8/6/2019 1 Introduction&Basics
18/42
a decision in a program, for example, to determine if a person is passedor failed in an exam. To check the condition(for example in if controlstructure) we use Equality and Relational operators.
Equality Operator== x == y x is equal to y!= x != y x is not eqaual to y
Relation Operator> x > y x is greater than y< x < y x is less than y>= x>=y x is grater than or equal to y
-
8/6/2019 1 Introduction&Basics
19/42
be able to break the problem into the simple steps so that you can describethese steps in the language.
In simple cases, you would be able to do it straightaway. With somepractice, most of the simple or even medium sized problems can be directly
coded into the computer language. But when you have really complicatedproblems on hand, you need to analyze it step by step. Further, such ananalysis will also help you remember what you have done and modify, ifnecessary, at a much later date. Also, if some other person wants to know
your sequence of reasoning, obviously it should be possible for you todescribe your logic in simple, unambiguous steps. Because of all thesereasons, it is highly essential to develop some form of intermediarymechanism to describe the problem on hand as a sequence of steps, whichcan be later converted to a program. There are two such commonly used and
universally accepted methods of describing the solution processi) The Flow Charts andii) The Algorithms
FLOW CHART: As the name suggests, it is a chart to describe the flow ofthe solution process. You breakup the solution into simple steps and connectthem to describe the flow so that the last of these blocks leads you to thesolution.
We briefly describe the commonly used symbols to represent theseblocks and how to combine them to form the solution.1. Terminal: This symbol is used in the beginning and at
the end of the flow chart. Here the beginning and theend refer to the logical beginning and the logical endof the sequence of operations. Start, Stop, End, orExit is Written inside the symbol to indicate the typeof terminal. For example the beginning of the flowchart is represented as given here
2. Input/Output : The symbol parallelogram is used forreading or writing of data. This symbol is used for alltypes of input and output, such as floppy reading,printing, magnetic tape reading or writing, or diskreading or writing, etc. The brief description of theoperation is written inside the symbol. For example,reading a record can be represented as given here.
19
STAR T
READ ARECORD
-
8/6/2019 1 Introduction&Basics
20/42
3. Processing: The symbol rectangle is used forprocessing operations, i.e. for arithmetic computations
(addition, substraction, multiplication, division) ormoving the data from one location or core storage toanother location. For example, the computations ofPME (percentage of marks in English) can berepresented as given here.
4. Decision : The diamond shaped symbol is used forrepresenting a decision point. It indicates that acondition is to be tested and one of the alternative
paths is to be followed. For exaple, PME can becompared 40 (for deciding whether it is more or lessor equal to 40) and can be represented as follows:
PME> 40NO
PME
-
8/6/2019 1 Introduction&Basics
21/42
6. Connector: A small circle is called the connector, andis used to show the entry to or exit from the logical
path of a flow char. In fact, this symbol replaces thelong flowlines connecting the different parts of aflowchart on the same page. One symbol shows wherethe branching of flow is done whereas the othersymbol shows the entry of the flow. Inside the symbolthe name of the entry or exit point is written.
7. Preparation: This symbol is used for the house-keeping operations. All those operations, which aredone before starting the actual processing of data,come in this category. For example, setting thenumber of students to zero before processing of datastarts.
8. Predefined : This symbol indicates that a routine orprocess, which is shown in the flowchart separately, is
executed at this position. Normally when a specificprocess is used at different logical paths then the useof this symbol provides the simplicity in the flowchart.
9. Offpage Connector: This symbol is used in place ofconnector when the exit and the corresponding entrypoint are shown on different pages in the flowchart.
10. Annotation, Comments: This symbol provides thefacility of writing more description of an operation.When the space inside a symbol is not sufficient towrite the details, then this symbol is used. The dottedline between the symbol and flow chart shows thepoint to which it relates.
21
a
-
8/6/2019 1 Introduction&Basics
22/42
ALGORITHMS: The other concept is the algorithm. It is a step by stepdescription of the problem in a language similar to English, but not in fullsentences, but as a set of commands. Some of the examples below will
classify the concepts.Example a: Simple interest is calculated using the formula SI = (P * T * R) /100
Step 1: START
Step 2: Read P T and R
Step 3: Calculate I = P * R* T /100
Step 4 : Write I
Step 5 : End
22
START
INPUTVALUESFOR P, T &R CALCULATEI= P * T *R
100PRINTVALUEFOR I
END
-
8/6/2019 1 Introduction&Basics
23/42
Example b) Victor Construction Company plans to give a 5% year-end Bonusto each of its employees earning Rs. 5,000 or more per year, and a fixed Rs.250 bonus to the other employees. The flowchart and algorithm for
calculation the Bonus for an employee is as shown in figure
NOYES
Step 1: START
Step 2: Read SALARY ofan
employee
Step 3: If Salary isGreater than or
Equal to 5,000then
Step 4 : CalculateBonus = 0.5 *
SalaryElse
Step 5 : Calculate Bonus =250
Endif
Step 6 : Write Bonus ofEmployee
Step 7 : End
23
START
INPUT SALARY OFAN EMPLOYEE
OUTPUTBONUS
END
Test ?SALARY >5000
BONUS =0.05 *
SALARYBONUS = 250
-
8/6/2019 1 Introduction&Basics
24/42
Example c) The flowchart and algorithm for adding the integers from 1 to 10
NoYES
Step 1: Start
Step 2 : Initialize SUM=0 andN=1
Step 3: If N is greater than 10then
Step 4 : Print SUMStep 5 : Stop
Step 6: CalculateSUM=SUM+N
N = N+1Endif
Step 7: Go to Step 3
PSEUDO CODE: Pseudo code is an artificial and informal language that helpsprogrammers develop algorithms. Pseudo Code is similar to everyday English;it is convenient and user-friendly although it is not an actual computerprogramming language.
Pseudo code programs are not actually executed on computers.Rather, they merely help the programmers think out a program beforeattempting to write it in a programming language such as C.
Example: If students percentage is greater than 40Print passed
ElsePrint failed
CONTROL STRUCTURES: They are three control structures in C
1) Sequence structure2) Selection structure3) Repetition structure
24
START
SUM = 0
Test?
N>10
SUM = SUM + N N = N + 1
PRINTSUM
END
-
8/6/2019 1 Introduction&Basics
25/42
SEQUENCE STRUCTURE: This is default structure. Unless directedotherwise(means selection and repetition), the computer automaticallyexecutes C statements one after the other in the order in which they are
written.SELECTION STRUCTURE: C provides three types of selection structures.1) if selection structure2) if/else selection structure
a) Conditional operator (ternary operator)3) switch selection structure
if selection structure :if selection structure either performs (selects) an action if a
condition is true or skips the action if the condition is false. It is also
called single-selection structure because it selects or ignores a singleaction.
The statement block may be a single statement or a group ofstatements. If the condition is true, the statement block will beexecuted; otherwise the statement-block will be skipped and theexecution will jump to the statement-x. Remember, when the condition istrue both the statement-block and the statement-x executes insequence.
Note that in c a non-zero value is considered to true and,whereas zero is considered to be false . We check the condition usingrelational and equivalent operators. The relationsexpressions(x>y,x
-
8/6/2019 1 Introduction&Basics
26/42
printf(%d, z);z=x>y; /*Expression is false it returns 0 to z */
printf(%d,z);}
output : 1 and 0Example:int x=5, y=10;if(xy) if(0)/* 0 means false*/{ {
cannot executes these stmts }because condition is false.
}We can use arithmetic expressions in the if statement. For example
all the following if statements are valid.
1) if(3+2)printf(This works);
2) if(a=10)printf(This also works);
3) if(-5)printf( even this works);
In the first if, the expression 3+2 is evaluate to 5 since 5 is a non-zero it is considered to be true. Hence the printf executed.
In the second if, 10 gets assigned to a so the if is now reduced to if is nowreduced to if(10). Since 10 is non-zero, it is true hence again printf() getsexecuted.
In the third if, -5 is a non-zero number, hence true. So again printf() goesto work. In place of -5 even if a float like 3.14 were used it is considered tobe true. So the issue is not whether a number is integer or float , orwhether it is positive or negative. Issue is whether it is zero or non-zero .
26
-
8/6/2019 1 Introduction&Basics
27/42
Example: #include#includevoid main()
{
int num1,num2;printf(Enter the numbers\n);scanf(%d %d,&num1,&num2);if(num1==num2)printf(%d is equal to %d,num1,num2);if(num1>num2)printf(%d is greater than %d,num1,num2);if(num1
-
8/6/2019 1 Introduction&Basics
28/42
/* program to find whether a number is even or odd */#include#includevoid main()
{ int a;clrscr();printf(Enter the no\n); OUTPUT :Enter the no 21scanf(%d,n); The no is oddif(a%2==0)printf(The %d is even);elseprintf(The %d is odd);
getch();}Nested if/else statement: When a series of decisions involved, we may haveto use more than one ifelse statement. If we write an entire if-elseconstruct within either the body of the if statement or the body of an elsestatement. This is called nestingofif
If the condition1 is false, the statement 3 will be executed; otherwiseit continues to perform the second test. If the condition 2 is true, the
28
If(condition 1){
if(condition 2){
statement 1;}else{
statement 2;}
}
else{statement 3;}
-
8/6/2019 1 Introduction&Basics
29/42
statement 1 is evaluated; otherwise the statement 2 well be evaluatedand then the control is transferred outside.
Example:
/*Program to find greatest of three nos */
#include#includevoid main(){
int a,b,c;clrscr();printf(Enter the values\n);
scanf(%d %d %d,&a,&b,&c);if(a>b){
if(a>c)printf(%d is greater,a);
elseprintf(%d is greater,c);
}else{
if(b>c)printf( %d is greater, b);elseprintf( % d is greater, c);
}getch();}
Else-if Ladder: There is another way of putting ifs together when multipathdecisions are involved. A multipath decision is a chain of ifs in which thestatement associated with else is an if
29
-
8/6/2019 1 Introduction&Basics
30/42
Example:/*program to calculate roots of quadratic equations*/#include#include#includevoid main(){
int a,b,c;float r1,r2,d;clrscr();printf("Enter the coefficients of equation\n");scanf("%d %d %d",&a,&b,&c);d=(b*b)-(4*a*c);if(d
-
8/6/2019 1 Introduction&Basics
31/42
printf("Roots are equal\n");r1=-b/(2*a);r2=r1;printf("r1=%f r2=%f",r1,r2);
}else if(d>0){
printf("Roots are real");r1=(-b+sqrt(d))/(2*a);r2=(-b-sqrt(d))/(2*a);printf("r1=%f r2=%f",r1,r2);
}getch();
}Logical Operators: C provides logical operators that may be used to form morecomplex condition by combining simple conditions. The logical operators are
&& logical AND|| logical OR! logical NOT
Like the simple relational expressions(x>y), a logical expression also
yields a value of zero or one.AND operator:(cond1&&cond2)
If both conditions are true the output of the logical AND expressionis true(i.e it returns 1) and if any of the condition is false the output isfalse(i.e. it returns 0)Example:
Void main(){
char ch;clrscr();printf(Enter any character\n);scanf(%c,&ch);if(ch>=65 && ch=97 && ch
-
8/6/2019 1 Introduction&Basics
32/42
printf(U entered small alphabet\n);else if(ch>=48 && ch
-
8/6/2019 1 Introduction&Basics
33/42
int a,b;clrscr();printf("enter two no");scanf("%d %d",&a,&b);
if(!(a>b)) /*Here if the condtion a>b is true the total !(a>b)printf("%d is greater",b); becomes false*/elseprintf("%d is greater",a);getch();
}Conditional Operator:( Ternary Operator)
The C language has an unusual operator, useful for making two-waydecisions. This operator is a combination of ? and : and takes three
operands(therefore called as ternary operator ). This operator ispopularly known as the conditional operator. The general form of use of theconditional operator is as follows:
The conditional expression is evaluated first. If the result isnonzero(true) expression1 is evaluated and returned, otherwiseexpression 2 is evaluated and its value is returned.Example:1) #include< stdio.h> 2)#include
#include #includevoid main() void main(){ {
int a,b,c; int a,b,c,max;clrscr(); clrscr();printf(Enter two nos\n); printf(Enter three nos\n);scnaf(%d %d,&a,&b); scanf(%d %d %d,&a,&b,&c);c = (a>b?a:b); max=(a>b?(a>c?a:c):(b>c?b:c));printf(%d is greater,c); printf(%d is greater,max);
getch(); getch();} }
OUTPUT: Enter two nos OUTPUT: Enter three nos56 78 34 55 2378 is greater 55 is greater.
33
conditional expression ? expression1:expression2
-
8/6/2019 1 Introduction&Basics
34/42
Switch Statement: The switch selection structure performs one of many different actionsdepending on the value of an expression. The switch structure is calledmultiple-selection structure because it selects among many different
actions. Switch (expression){
case const1:block-1;break;
case const2:block-2;break;
..default :
default block;break;
}statement-x;
The expression is an integer expression or characters.const1,const2. are constant expressions(evaluable to an integral constant)
and are known as case labels. Each of these values should be unique within aswitch statement. block-1 , block-2... are statements lists and maycontain zero or more statements. There is no need to put braces aroundthese blocks. Note that case labels end with a colon(:)
When the switch is executed, the values of the expression issuccessively compared against the values const1, const2.... if a case is foundwhose value matches with the value of the expression, then the block ofstatements that follows the case are executed.
The break statement at the end of each block signals the end of a
particular case and causes an exit from the switch statement, transferringthe 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. Ifnot present, no action take place if all matches fail and the control goes tothe statement-x.
34
-
8/6/2019 1 Introduction&Basics
35/42
Example:/* Calculator program using switch case */#include#include
void main(){int a,b,c,n;clrscr();printf(Enter two nos\n);scanf(%d %d, &a,&b);printf(1.Addition\n2.Substration\n3.Multiplication\n4.Divisionscanf(%d,n)switch(n)
{ case 1:c=a+b;break;case 2:c=a-b; break;case 3:c=a*b; break;case 4:c=a/b;break;default: printf(Invalid Number\n);
}printf(%d,c);getch();
}I ncrement and Decrement Operators:
C has two very useful operators called increment and decrementoperators.
The operator ++ add 1 and operator -- subtracts 1. Both are unaryoperators (because we are operating on one operand).
preincrement - ++m equivalent topostincrement - m++ m=m+1; or m+=1;predecrement - --m equivalent topostdecrement - m-- m=m-1; or m+=1;
we use increment and decrement statements in for and while loopsextensively.
When m++ and ++m mean the same thing when they form statementsindependently, they behave differently when they are used in expressions onthe right-hand side of an assignment statement. Consider the followingprograms:
35
-
8/6/2019 1 Introduction&Basics
36/42
1) #include 2) #include#include #includevoid main() void main(){ {
int i=5; int i=5,j;clrscr(); clrscr();++i; j=++i;printf(%d\t,i); printf(%d %d \n,i,j);i=5; i=5;i++; j=i++;printf(%d,i); printf(%d %d,i,j);getch(); getch();
} }
Output: 6 6 Output: 6 66 5
If we observe the second program for preincrement of i first i isincrementing and afterwards it is assigning to j and in the postincrementcase first the value of i is assigned to j (i.e 5) and afterwards the value inthe i is incrementing. Therefore we get the output 6 6 and 6 5.Repetition Structure:
C provides three repetition structures1) while loop2) do-while loop3) for
A loop is a group of instructions the computer executes repeatedly whilesome loop-continuation condition remains true.WHILE LOOP: The basic format of while loop is
The while is entry-controlled loop statement. The test-
condition is evaluated and if the condition is true then the body of the loopis executed. After execution of the body, the test-condition is once againevaluated and if it is true, the body is executed once again. This process of
36
While(condition){
body of loop}
-
8/6/2019 1 Introduction&Basics
37/42
repeated execution of the body continues until the test-condition finallybecomes false and the control is transferred out of the loop. On exit, theprogram continues with the statements. The braces needed only if the bodycontains one or more statements.
#include#includevoid main(){
int fact=1,i=1,n;clrscr();printf("Enter the number\n");scanf("%d",&n);
while(i
-
8/6/2019 1 Introduction&Basics
38/42
to execute the body of the loop before the test is performed. Suchsituations can be handled with the help of the do statement.
On reaching the do statement, the program proceeds to evaluatesthe body of the loop first. At the end of the loop, the test-condition in the
while is evaluated. If the condition is true, the program continues toevaluates the body of the loop once again. This process continues as long asthe condition is true. When the condition become false, the loop will beterminated and the control goes to the statement that appears immediatelyafter the while condition.Example: #include
#includevoid main()
{ int a,b,c,n;clrscr();do{
printf(Enter two nos\n);scanf(%d %d, &a,&b);printf(1.Addition\n2.Substration\n3.Multiplication
\n4.Division\n5.Exit\n);
scanf(%d,&n);switch(n){
case 1:c=a+b;printf(%d,c);break;case 2:c=a-b; printf(%d,c);break;case 3:c=a*b; printf(%d,c);break;case 4:c=a/b; printf(%d,c);break;
}
} while(n
-
8/6/2019 1 Introduction&Basics
39/42
FOR Statement :The for loop is anathor entry-controlled loop that provides a more
concise loop control structure.for(initialization; test-condition; increment)
The execution of the for statement is as follows:1) Initialization of the control variables is done first, usingassignment statements such as i=1 and count=0. The variablei and count are known as loop-control variables.
2) The value of the control variable is tested using the test-condition. The test-condition is a relational expression, suchas i
-
8/6/2019 1 Introduction&Basics
40/42
getch();}
BREAK :
When the break statement is encountered inside a loop, the loopis immediately exited and the program continues with the statementimmediately following the loop. When the loops are nested, the break wouldonly exit from the loop containing it. That is, break will exit only a singleloop.
Example:
#include#includevoid main(){
int i;clrscr();for(i=1;i
-
8/6/2019 1 Introduction&Basics
41/42
Broke out of the loop at x==5
CONTINUE:
When the continue statement is encountered in the loop, as thename implies, it causes the loop to be continued with the next iterationafter skipping any statements in between. The continue statement tells thecompiler, SKIP THE FOLLOWING STATEMENTS AND CONTINUE THENEXT ITERATION . The format of the continue statement is
continue;In while and do loops, continue causes the control to go directly to the
test-condition and then to continue the iteration process. In the case offor loop, the increment section of the loop is executed before the test-condition is evaluated.
Example: #include
#includevoid main(){
int i;clrscr();for(i=1;i
-
8/6/2019 1 Introduction&Basics
42/42
Used continue to skip printing the value 5