0% found this document useful (0 votes)
20 views50 pages

PPS Unit 1

Programing problem solving unit 1 by ik Gujral punjab technical university jalandhar

Uploaded by

jhatrilok275
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
20 views50 pages

PPS Unit 1

Programing problem solving unit 1 by ik Gujral punjab technical university jalandhar

Uploaded by

jhatrilok275
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 50
Unit 1 Introduction to Programming (4 lectures) Introduction to components of computer system (disks, memory, processor, where a program is stored and executed, operating system, compilers ete.) — (1 lecture). Idea of Algorithm: steps to solve logical and numerical problems. Representation of Algorithm: Flowchart/Pseudocode with examples, (1 lecture) From algorithms to programs; source code, variables (with data types) variables and memory locations, Syntax and Logical Errors in compilation, object and executable cade- (2 leetures) Unit 2 Arithmetic expressions and precedence (2 lectures) Conditional Branching and Loops (6 lectures) Writing and evaluation of conditionals and consequent branching (3 lectures) Iteration and loops (3 lectures) Unit 3 Arrays (6 lectures) Arrays ( }-D), Character arrays and Strings Unit 4 Basic Algorithms (6 lectures) Searching, Basic Sorting Algorithms (Bubble, Insertion and Selection), Finding roots of equations, notion of order of complexity through example programs (no formal definition required) Unit Function (5 lectures) Functions (including using builtin libraries), Parameter passing in functions, callby value, Passing arrays to functions: idea of eall by reference Unit 6 Recursion (4-5 lectures) Recursion, as a different way of solving problems. Example programs, such as Finding Factorial, Fibonacci series, Ackerman function etc. Quick sort or Merge sort. Unit 7 ‘Structure (4 leetures) Structures, Defining structures and Array of Structures, Unit 8 Pointers (2 lectures) Idea of pointers, Defining pointers, Use of Pointers in self-referential structures, notion of linked list (no implementation) 2.0 Introduction ‘C’ is high level language and is the upgraded version of another language (Basic Combined Program Language). C language was designed at Bell laboratories in the early 1970's by Dennis Ritchie. C being popular in the modern computer world can be used in Mathematical Scientific, Engineering and Commercial applications The most popular Operating system UNIX is written in C language. This language also has the features of low level languages and hence called as “System Programming Language” Features of C language + Simple, versatile, general purpose language * Ithas rich set of Operators ¢ Program execution are fast and efficient * Can easily manipulates with bits, bytes and addresses * Varieties of data types are available * Separate compilation of functions is possible and such functions can be called by any C program * Block- structured language * Can be applied in System programming areas like operating systems, compilers & Interpreters, Assembles, Text Editors, Print Spoolers, Network Drivers, Modern Programs, Data Bases, Language Interpreters, Utilities etc. 2.1 Character Set The character set is the fundamental raw-material for any language. Like natural languages, computer languages will also have well defined character-set, which is useful to build the programs. The C language consists of two character sets namely — source character set execution character set. Source character set is useful to construct the statements in the source program. Execution character set is employed at the time of execution of h program. 1. Source character set : This type of character set includes three types of characters namely alphabets, Decimals and special symbols. i Alphabets : Ato Z,a to z and Underscore(_ ) ii, Decimal digits: 0to9 ii, Special symbols: +-*/%% =& !() { } [] “etc 2. Execution character set: This set of characters are also called as non-graphic characters because these are invisible and cannot be printed or displayed directly. These characters will have effect only when the program being executed. These characters are represented by a back slash (\) followed by a character. Result at the time of execution \n Transfers the active position of curso: to the initial position of next line Null \O (zero) \t Horizontal Tab] Transfers the active position of curso’ to the next Horizontal Tab Transfers the active position of curso! to the next Vertical Tab \v \f Transfers the active position of curso! to the next logical page Transfers the active position of curso: to the initial position of current line} 2.2 Strueture of a ‘C? Program “The Complete athutire of C program is “The basic components of program are: + main. + pairofbraves ( ) + declarations and saxements + userdefined functions: Preprocessor Statements: These statements begin with # symbol They are called preprocessor directives. These statements direct the C preprocessor {o include header files and also symbolic constants in to C program, Some of the preprocessor statements are ‘includes tio. i>: forthe standard inpuvoutput functions ‘fincludectest.h>: forfile incsion of header fle Test. ‘define NULL 0: for defining symbolic constant NULL Global Declarations: Variables or functions whose existence isknown in the main() function and other user defined functions are called! slobal variables (oc functions) and their declarations js called global declaration. This declaration should be made before main() ete. ‘main(: Asthe name itselfindicstes it sthe main fanction ofeveryC program. Execution of program tars from main 0. No C programis executed without ‘main( function. It should be written in lowerease letiers and should not be terminated bya semicolon. It callsother Library functions user defined functions, ‘There must be one and only one main() function in every C program. Braces: Every C program uses a pair of curly braces ((,}0. The left brace indicates beginning of main() function. On the other hand, the right brace indicates end of the main() function. The braces can also be used to indicate the beginning and end of user-defined functions and compound statements. Declarations: It is part of C program where all the variables, urrays, functions etc, used in the C programare declared and may be initialized with, their basic data types. Statements: These are instructions to the specific operations, They may be input-output statements, arithmetic statements, control statements and other statements. They are also including comments Paper = 1 Programming in © 2 ‘User-defined functions: These are subprograms, Generally, subprogtam isa function, and they contain a set of statements to performa specific task: "These are written by the user; hence the name is user-defined functions, They may be written before or after the main() function. 2.3 Data Types in ‘C? Bes types ott Derived Data Type vit Amy Serstae—Uvion Fomor Char towger Fat Double Type det Enum ‘The built-in data types and their extensions is the subject of this chapter. ‘Derived datatypes suchas arrays, structures, union and pointers and user defined data types such as typedef and enum, Basic Data Types ‘There are four basic data types in C language. They are Integer data, character data, floating point data and double data types. a, Character data: Any character of the ASCII character set can be considered as a character datatypes and its maximum size can be I byte or 8 byte long. ‘Char’ isthe keyword used to represent character datatype in. Char ~ a single byte size, capable of holding one character. b. Integer data: The keyword ‘int’ stands for the integer data type in C and its size is either 16 or 32 bits. The integer data type can again be classified as 1. Longint- Jong integer with more digits 2. Short int- short integer with fewer digits 3. Unsigned int - Unsigned integer Eas Conger Science wd Engineering 4, Unsigned short int - Unsigned short integer 5. Unsigned Jong int ~Unsigned long integer As above, the qualifiers like short, long, signed or unsigned can be applied to basic data types to derive new data types. int- an Integer with the natural size of the host machine. «. Floating point data: ~The numbers which re stored in loating point representation with mantisaand exponent ar called floating point (real) numbers ‘These numbers cam be deckared as “float” in float— Single precision floating point number value 4. Double data :- Double isu keyword in to represent double precision ‘lating point numbers. double Double ~ precision floating point number value. Data Kindsin C ‘Various data kinds that can be included in any C program can fallin to the following. a, Constants/Literals b. Reserve Words Keywords, . Delimeters Variables Identifiers ‘a, Constang/Literals: Constants are those, which do not change, during the execution of the program. Constants may be categorized in to: + Numeric Constants + Character Constants + String Constants 1. Numeric Constants Numeric constants, as the name itselfindicates, are those which consist of ‘numerals, an optional sign and an optional period. They are further divided imo tworypes: (a) Imceger Constants (b) Real Constants a. Integer Constants Paper =f Programming A whole nuniber isan integer constant Integer constants do not have a ‘decimal point. These are further divided ito three types depending on the number systems they belong to, They are i. Decimal integer constants ii Octalinteger constants i Hexadecimal integer constants i. A decimal integer constant is characterized by the following, properties + his sequence of one or more digits (10...9], the symbols of decimal number system. i, A decimal properties: + Itisasequence of one or more digits ((0..9}, the symbols of decimal number system). iteger constant is characterized by the following + Ttmayhave an optional + orsign, Inthe absence of'sgn, the constant ‘+ Commas and blank spaces are not permitted + Itshould not have « period as part oft. ‘Some examples of valid decimal integer constants: 436 123 ‘Some examples of invalid decimal integer constants: 4.56- Decimal points not permissible ‘Commasare not permitted fi, An octal integer constant is characterized by the following properties ‘+ Itisasequence of one or more digits (0...7}, symbols of octal number ster). ‘+ Temayhave an optional + or ~sign. Inthe absence of sign, the constant is assumed to be positive + Itshould start with the digit 0 + Commns and blank spaces are not permitted. + Itshould not have a period aspart oft, Some examples of valid octal integer constants: a 0456 0123 +0123 Some examples ofinvalid octal integer constants: (04.56 - Decimal point is not permissible ied X34 -x isnot permissible symbol (04,56- Commas are not per 568 - 8 is not apermissible symbol ii, An hexadecimal integer constant is characterized by the following properties fii, An hexadecimal integer constant is characterized by the following properties Si Itisa sequence of one or more symbols ([0...9]LA....2. the symbols ‘of Hexadecimal number system), Ttmayhave an optional +or- sign. Inthe absence of sign, the constant is assumed to be positive. {It should start with the symbols OX or Ox. Commas and blank spaces are not permitted e-should not have a period as part oft. fom: examples of Valid hexadecimal integer constants: oxas6 -0x123 On56A, OxB78 ‘Somte examples of invalid hexadecimal integer constants Ox.56 - Decimal point isnot permissible Ox4,56~ Commas are not permitted, b, Real Constants The real constants also known as floating point constants are written in ‘two forme: ip ihn a (Fractional form, (i) Exponential form. i. Fractional Form ‘The real constants in Fractional form are characterized by the following characteristic “Must have atleast one digit. ‘Must have a decimal point, “May be positive or negative and inthe absence of sign taken as positive, “Must not contain blanks or commasiin between digi “May be represented in exponential form, ifthe yalue is too higher or too low. ‘Some examples of valid real constants: 456.78 23.56 ‘Some examples of valid real constants 456.78 =123.56 Some examples ofinvalid real eonstants: 4.56- Blank spaces are not permitted 4,56- Commas arenot permitted 456 - Decimal point missing 4i, Exponential Form ‘The exponential form offers a convenient way for writing very large and small real constant. For example, 56000000.00, which ean be written as 0.56 +, 108 i written as 0,5688 or 0.56e8 in exponential form, 0,000000234, which can be writen as 0.234 * 10° is written as 0.234-6 oF 0.234e-6inexponential form The leer E ore stand for exponential form. ‘A eal constant expressed in exponential form has two pats: (i) Mantissa pat, (i) Exponent part, Mantissts the part ofthe real constant to the Itt of £ ‘or e, and the Exponent of areal constant isto the right of ore. Mamtissa and Exponent ofthe above two number are shown below. Manisa + Exngrent] Mantise | Expprent ose | £6 | 02% | E% Tapatar Nene Teer In the above examples, 0.56 and 0.234 are the mantissa parts of the first and second numbers, respectively. and 8 and -6 are the exponent parts of the first and second number, respectively ‘The real constants in exponential form and characterized by the following characteristics: +The mantissa must have at east one digit. ‘+The mantissa followed by the letter B or eand the exponent + The exponent must have at east one digit and must be an integer: + Asign forthe exponent is optional Some examples of valid real constants: 3E4 23e-6 03486 ‘Some examples ofinvatid real constants Some examples of invalid real constants: 23E - No digit specified for exponent 2304.5 - Exponent should not be a fraction 23,4e5 - Commas are not allowed 256*e8- * not allowed 1. //Wap to print simple message. #include #include void main() { printf(" Get Well Soon"); clrser(); getch(); } What Does Computer Mean? A computer is a machine or device that performs processes, calculations and operations based on instructions provided by a software or hardware program. It has the ability to accept data (input), process it, and then produce outputs. Computers can also store data for later uses in appropriate storage devices, and retrieve whenever it is necessary. Modern computers are electronic devices used for a variety of purposes ranging from browsing the web, writing documents, editing videos, creating applications, playing video games, etc. They are designed to execute applications and provide a variety of solutions by combining integrated hardware and software components. ‘A pes of computers folow the same este logical sucure and prt te converting row Ut est information SNe. Operation 1 Thott ouput Desegton ereing dt one ‘haya al for Performing saree ‘ol eertinson prodicnguseta tee ore use in| oan ontoeyere 5 Sate Rate ve Serene we tos Input Unit “This unit contains devices with the help of “which we enter data into the computer. Tis Luni creates 8 link between the user and the computer; The input devices translate the information into @ form understandable by the computer. CPU (Central Processing Unit) CPU is considered as the brain of the computer. CPU performs all types of data processing operations. It stores data, Imermediate results, and instructions. (program). It controls the operation of all parts of the computer. CPU itself has the following three ‘components ~ © ALU (Arithmetic Logic Unit) © Memory Unit © Control Unit Output Unit The output unit consists of devices with the help of which we get the information from ‘the computer. This unit isa link between the computer and the users. Output devices translate the computer's output into a form Understandable by the users, Disk storage (also sometimes called drive storage) is a general category of storage mechanisms where data is recorded by various electronic, magnetic, optical, or mechanical changes to a surface layer of one or more rotating disks. A disk drive is a device implementing such a storage mechanism. Notable types are the hard disk drive (HDD) containing a non-removable disk, the floppy disk drive (FDD) and its removable floppy disk, and various optical disc drives (ODD) and associated optical disc media. Floppy disks ¢ atl 3.5inch floppy disk A floppy disk" (or diskette) is a form of magnetic data storage; thin, flexible, soft, flat piece of mylar plastic, packaged in a 3.5 inch plastic case. The reason it was called a floppy is because obsolete (Band 5.25 inch formats) types would “flop” as you waved them. Floppy disks were invented by IBM and were a popular form of data storage from the 1970's to the 1990's. The key to thelr Zip disks , Zip disk A zip drive is a secondary storage device that uses zip disks. Zip disks are cartridges similar to floppy disks but capable of storing 70-500 times more memory. Zip disks are disks with a special high quality magnetic coating that have a capacity of 100, 250, or 750 MB [4]. Hard drives so A hard-disk drive (HDD) is a non-volatile device used for storage, located inside the computer case. Like the floppy drive, it holds its data on rotating platters with a magnetic upper exterior which are changed or read by electromagnetic tipped arms that move over the disk as it spins. Tape drives & A tape drive is a storage device that uses a streaming magnetic tape to store data. Instead of allowing random-access to data, tape drives only allow sequential-access to data. It must wind between reels to find any particular piece of data at any given time. How a Computer Executes (Runs) a Program memory (RAM) i Compsetaly ety The frat ning te computer needs to dot ater the oper te om te Rar daciomeman mena, ‘Mtr he operating sytem loaded to man ‘memory yeah excite 3 programs apliaten software) you. This (Cua doe by ching double iki, Crtpping he pega oresponang Icon ror exarpe ts sy youclk on he Icon of your forte word provessor Th ‘ston ede your computer lad (or apy) te wor processing preram Frm Jourhora ek tthe mammary so the 6 Remember Programs aresoreon Scones storoge cee: seh = rd disk Wier you stale Brogan on yur comput the roam sway eoped your ord dk ut when yu exe © program he progam scoped {ace} rom yourhara dk the fran mera copy the progam 'secetee Compiler, Computer software that translates (compiles) source code written in a high-level language (e.g., C++) into a set of machine-language instructions that can be understood by a digital computer’s CPU. Compilers are very large programs, with error- checking and other abilities. Some compilers translate high-level language into an intermediate assembly language, which is then translated (assembled) into machine code by an assembly program or assembler. Other compilers generate machine language directly, Compilation Error Features of Compilers Correctness ‘= Speed of compilation + Preserve the correct the meaning of, the code ‘+ The speed of the target code ‘+ Recognize legal and illegal program constructs * Good error reporting/handling = Code debugging help Types of Compiler Following are the different types of Compiler: ‘+ Single Pass Compilers, ‘+ Two Pass Compilers + Multipass Compilers ‘Single Pass Compiler Sing as Comalier Single Pass Compiler In single pass Compiler source code directly transforms into machine code, For example, Pascal language. ‘Two Pass Comy ‘Two Pass Compiler ‘Two pass Compiler's divided into two sections, viz. 1. Frontend: It maps legal code into Intermediate Representation (IR) 2, Backend: it maps IR onto the target machine Multipass Compilers Multipass Compilers The multipass compiler processes the source code or syntax tree of a program several times. It divided a large program into multiple small programs and process them. It develops multiple intermediate codes. All of these multipass take the output of the previous phase as an input. So it requires less memory. Itis also known as ‘Wide Compiler’ Tasks of Compiler Main tasks performed bythe Compiler sr ae BE neg taste OF a + ranks up theupthe source progam ino piees and impose grammatia structure onthe + Allows you toconstrutthe desired target program rom theintemete representation and alo creat the symbol able Compiles source code and detects Manage storage ofall variables and codes Suppor fr separate compilation Read, anayae the ete program, and trenslate to semanticaly equivalent Translating the source code into object code depending upon the ype of machine We need a system which can act as an intermediary and manage all the processes and resources present in the system. ‘An Operating System can be defined as an interface between user and hardware. It is responsible for the execution of all the processes, Resource Allocation, CPU management, File Management and many other tasks. The purpose of an operating system is to provide an environment in which a user can execute programs in convenient and efficient manner. Characteristics of Operating ‘Systems Let us now dscuse some ofthe important characteristic etre of operating eter + Device Management: The opera system ops rack fal the devs, Sti a0 alle he netOutut centrale at secides which process gets the dee, + Fle Management I locates and who gts theresouce + Job Accounting hes ak of ne and reeouces used by vious obs or ses + Eor-deteting Aids: These contin rmetods that nolo the production of amps aces, eror messages, ad other debugging and erordetecing mathode + Memory Management: tkeepe wacko he eo allocates the meme when & processor program request proces or rogram requests + Processor Management It allocates the processor toa process and then = sllocstes the processor when tis no longer requiedor the ob done. + Contra on System Performance: records the delays between the request fora service ane the syste + Security: prevents unauthorzed acess te programs and data using passwords or some kind of protection technique + Convenience: An OS makes 8 computer + effleteney: An 0S allows the computer system resources tobe used ecient. + Ability to Evolve: 05 should be ‘conatruetedin such 8 way aso pet he effective development testing and Introduction of new system functions atthe le without intrering wth service. + Throughput An 0S should be constcted so that t can ge maximum throughput (Number of asks per unit ime ‘The process operating system as. User Inertoce: 2. System and application programs 8. Operating sytem 4 Horna Every generalpurpse computer consists of hardware, an operating. system(s}, system programs, and application programs. The hardware const of memory, CPU, ALU, YO evices, peripheral devices, and. storage Gevices. The system program consiets of compilers, loaders, ets, 0S, etc. The application program consists of business ‘roprams and databace programs. ‘Source code isthe C program that you write in your ‘editor and save with a'.C” extension, Which Is un- ‘compiled (when written for the first time or Whenever a change is made init and saved). Object code isthe output of a compiler after it processes the source code. The abject cade ie usually a machine cade, also called a machine language, which can be understood directly by 8 ‘specific type of CPU (central processing unl), such ‘28x86 (.e, Intel compatible) or PowerPC. However, some compilers are designed to convert source ‘code nto an assembly language or some other ‘another programming language. An assembly language ie @ human eadable notation using the ‘mnemonics (mnemonics 2 symbolic name for a ‘single executable machine language instruction called an opcode) n the ISA (Instruction Set ‘Achitecture) of that particular CPU Executable (also called the Binary) s the output of 9 linker after it processes the object code. A machine ‘code file canbe immediately executable (Le, runnable as a program), ort might require linking vith other object code files (e.g libraries) to produce ‘a complete executable program. ‘pune apeeensniy pre ae peat ‘ssaars em frst mame oncom ‘Styne on ‘évnagPwcar| Rencartomde pfu settee cima 2 The hatininndmeamotermmcttpt ner Reaho seapat nantaceag eee natnne pe suk Datetmses tmnt crop inp tena pne nk eeas ages are to be joined with each other. The partsto be joined are indicated by the circle. Oo OO g. Off-page connectors: This connector represents a break in the path of flowchart which is too large to fit on a single page. It is similar to on-page connector. The connector symbol marks where the algorithm ends on the first page and where it continues on the second. 2. Dron stwsinsbetzettegal ne =a LEZ a. od. Se 2, ra wc aay ee oo 0 lo eet 4s ocompnysns toner anus tents cxpirescenrg a Cte ma se ‘Stef emang ups Sm stowage Snape isi wae ‘mesogenic pt ‘Seen nr mminheeoeom n ‘Sees pean ernest ‘ores tmnernnsba ihe ‘Avner Eye a ange spare ‘variable is nothing but a name given toa storage area that our programs can manipulate. Each variable in Chas a specific type, which determines the siz and layout of the varable's memory, the range of values that canbe stored within that ‘memory; and the set of operations that can be ‘applied tothe variable ‘The name ofa variable can be composed of letters, digits, andthe underscore character. It ‘must begin wth either a letter or an underscore Upper and lowercase letters are distinct because C Is case-sensitive, Based on the basic types explained in the previous chapter there willbe the fellowing basic variable types ~ ‘StNo. Type & Description car Typealy a single octt(one byte). This Is aninteger type, {nt The most natural size of intege forthe ‘machine. 3 float A single precision floating point value double A double precision floating point value. 5 void Represents the absence of type q Variable Definition in © how much storage to crestor the variable, A ‘ele detention species aaa type and ‘ypeas follows Her pa mst be avai C datatype ning Char w chant ost, double, bool er any use eine abject and viable He nay cont of ver rere erties sepested by ‘commas. Some vob dctaratins ae shown hee ie “Te na tk elves and tines the ‘varies ac whieh inset the completo {reate vats named and ot pen arabes canbe nized assed an nal al inte delraton The nite onsets ff an equal sign flowed bys constant expression tetolows Some examples are - extern int d // declaration int d = 3, f $ // definition a byte z = 22; // definition a char x = 'x'; // the variable " w an " wu Lvalues and Rvalues in C ‘There are two kinds of expressions in © ~ + Ivalue ~ Expressions that refer toa memory location are called “value” expressions. An Ivalue may appear as either the left-hand or righthand side ofan assignment. + value ~ The term ralue refers toa data value thats stored at some address in memory. An ‘nalue is an expression that cannot have 3 value assigned tot which means anrvalue may appear on the righthand side but not on the lefthand side of an assignment. Variables are Walues and o they may appear on the lethand side of an assignment, Numeric literals are values and s0 they may not be ‘assigned and cannot appear on the left-hand side, Take 3 look atthe following valid and invalid statements ~ Ant g = 20; // valid staterent 10 = 20; // invalid statement; would genera Lvalues and Rvalues in C ‘There are two kinds of expressions in © ~ + Ivalue ~ Expressions that refer toa memory location are called “value” expressions. An Ivalue may appear as either the left-hand or righthand side ofan assignment. + value ~ The term ralue refers toa data value thats stored at some address in memory. An ‘nalue is an expression that cannot have 3 value assigned tot which means anrvalue may appear on the righthand side but not on the lefthand side of an assignment. Variables are Walues and o they may appear on the lethand side of an assignment, Numeric literals are values and s0 they may not be ‘assigned and cannot appear on the left-hand side, Take 3 look atthe following valid and invalid statements ~ Ant g = 20; // valid staterent 10 = 20; // invalid statement; would genera = What is a syntax enor? '* Can you list some common syntax errors? "+ What isa logic (ological ror)? Fe% (a) Syntax ‘Alanguages have a set of rues for how words and sentences should be structured. ‘These rules are collectively known as the language syntax. In.computer programming, syntax serves the same purpose, defining how declarations, functions, commands, and other statements should be arranged, (b) Syntax errors, ‘A syntax error is an error inthe source code of a program. Since computer programs must {olow strict syntax to compile corecly any aspects ofthe code that do not conform to the syntax of the programming language will produce a syntax eror. ‘Syntax errors are small grammatical mistakes, sometimes inited to a single character. For example, a missing semicolon atthe end of aline or an extra bracket atthe end of a function may produce a syntax error. (c) Logic errors. ‘Alogic error (or logical ero is a ‘bug’ or mistake in a program's source code that results in incorrect or unexpected behaviour. Its a type of runtime error that may simply produce the wrong output or may cause a program to crash while running.

You might also like