You are on page 1of 24
CH is an object-oriented programming language developed by Bjarne Stroustrup at AT&T Bell Laboratories in early 1980s. As CH is a successor of the C language, +0 initially it was called °C with classes’ but Tater Rick Mascitti called it C++. Actually, on to C++ 7 Fundamentals for Writing a C++ Program Writing Programs using C++ Flow of Control Iteration Statements or Looping Statemen in C++ “ “ 4 t ‘Stroustrup used the features of one of the first object oriented languages Simula 67 to improye the language called C. FUNDAMENTALS FOR WRITING A C++ PROGRAM Like any other computer language, C++ has some rules and conventions that need to be followed. Let us go through them one by one. Character Set C++ recognises the following as a valid set of characters of the language. . Digits—includes 0 to 9 1. Alphabet—includes A to Z,atoz 2 3. Special characters—ineludes space ( )[ @ Ts i> 4. White space characters—includes Blank space, Horizontal tab —, Carriage return —!, New Line and Form feed. 5. Other characters—any of the other characters not mentioned above but are included in the list of extended ASCII Set of 256 characters is also recognised. Token A token is the smallest identifiable individual unit ofa program. It is made up of one or more characters of the character set. Tokens are also known as lexical units of a program. “Info Hub | ‘Anerican Standard Code for Information Interchange (abbreviated as ASCII) is o standard _ code for representing characters as numbers, with _ each character assigned a number from 0 to 127. The superset of ASCII is called extended ASCII or high ASCII which contains the representation of another 128 characters making 256 standard Codes avcilable. The ASCII code of space is 32, digits 0 to 9 are represented with 48 th Letters A to Z are represented with 65 through 90 and a to z from 97 through 122. = Tokens are of the following types, 1, Keywords: These tokens are aoe are r Served words that instruct the compiler to perfo ee ae ha ca continue, default, do, double, else, fi ed . s “t, void, while, true and false are some of the keywords, : a ogrammer given name: a re a (ane ames or aliases given to the different parts: im, Kenta Se !© name variables, funetions, classes Obj ) ‘am. Identifiers can be named according to follow a 3 f according to following rules: 5 letters, digits, or underscore : (b) First character should be a letter ined tasks. break, case. nt, Jor ina pr (a) Can comprise (c) Names are case-sensitive (d) Reserved words and key rc Is and keywords of C++ cannot 3. Literals: These ane are constants Whose value remains sam noe alu se i remains same all throughout the p 5 (a) Integers—These are whole numbers wi "4 fccemtiereineemreniis positive. These are represented with in Gulijpe Soe ee ene ope hele S373 eae rype. Some valid examples of this (b) Floating —These are real constants and are used to represent numbers with fractional values with a decimal point . Like integers these can also be positive or negative. These may be represented with “float’ or ‘double’ datatypes. Some valid examples of this type include 8372.9, +0.001, —345.12. (c) Character—These represent one character enclosed within single quotes. These may be represented with ‘char’ datatype. Some valid examples of this type include ‘A’, 'z’ or escape sequences. The non-graphic characters that cannot be entered through the keyboard are called escape sequences and include tab, return, backspace and so on. The escape sequences may be represented by a backslash(\) followed by a predefined set of one or more characters. For example, “ib represents the backspace, \n’ the newline, “the tab space and 0" represents null, Other escape sequences are also available, (@) Sirings—are a sequence of characters enclosed within double quotes. Each string is automatically added a null character ("\0") atthe end of the string. Thi sharacter terminates the string. Some valid examples ofthis type include “xy2", “Pearson 2017’ and so on. (©) Boolean—This type has only two values true or false, This is represented by the Boolean datatype. () Null—This literal has no value n represented by null. 4. Punctuators: These are Se tokens. (} (Dla ween are some xa vot even space or 0. This means nothing, This is parators that are used to identify and isolate the different les of punctuators. 5, Operators: Operator is a token that initialises an operation on oper ndsin eh expression. For example, Exp = a+b (in this example + is a8 0D oe th at i sty Gum operstion ona and b). An expression is a combination OF OPeTm” Sad operand, Operands are the values on which the operator works, For example, Exp = a+b, Here. and b are operands and + is the operator. Operators can be of the following types (a) Mathematical operators: These ope operands. +, -* , %and / are examples of this (b) Compound operator: These opera’ Table 5.| Some common Meaning ed to perform arithmetic operation o, ors are US alled shorthand operator ‘compound operators ener en re Ere Tenn ns i oe ‘Add? toa para Subiract 2 from a a=a-2 mai Multiply a by 2 a ae Divide a by 2 a Sn Divide x by 2 and find outits remainder a= a%2 ‘These operators are used to give an increment or (c) Increment/decrement operator: +a (both are used to increase decrement of one (1) to its operand. For example: a+ or + the value of aby 1) and ~ ~a or a~ ~ (both are used to decrease the value of a by 1), The difference between the two is in case of pre increment (++a) or pre decrement (—-a), the value is first changed and then used in the expression whereas in case of post-increment (a++) or post-decrement (a--), the value is first used in the expression and then changed. ++ and —— operator can be used as postfix or as prefix operator which has no effect if used as an independent statement. However, if it is used as part of an expression, the prefix operator will be operated and then the expression will be evaluated, whereas the post-fix operator will be evaluated later. For example, in the statement x =a+(b++), a will be added to b and then stored in x and then the value of will be incremented. If the same expression is written as x = a+(++), then the b will incremented and then added to a and stored in x. (d) Relational operator: These operators are used to establish relation between two operands. The common relational operator and their meaning is as follows. : a Greater than - S Less than i Equal to : = Greater than equal to 3 ‘Less than equal to. : = Not equal to (e) Loglea operat (fy Assis (y) Cone Operators on that op (a) Und (b) Bin (c) Ter ope Datatyp Data in should s memory two typ LF fi Vai foll (c) Logical operator: There operators and their meg (0) Assignment operator (g) Conditional operator (2): This is used to assign This is used to cheek on the basis of le er of on that operators are of the following types: a a “a variable or a constant to a variable. Operators can also be classified fora condition (a) Unary work on only one opera Ly One operand like +. Fo or example, +¥a, a~— (b) Binary me work on two operands like +. For example, a4 5 (©) Ternary: work on three operands like (conditioned ee a operators). For example, a>b?a:b The operators inside () are performed. first within an Datatype expression. Data in programming languages are stored in variables To create a variable, the variable should support an inbuilt datatype. The variable is a name given to a particular location in the memory and the value stored in a variable can be altered during program execution. C+ offers two types of data types 1, Fundamental type: Which are not composed of any other data type, that is, int, char, float and void. 2. Derived data type: Which are made up of fundamental data type, that is, array, function, class, union and so on. The datatypes supported in C++ are listed below Pate pe Sica Ha in 2 32768 to 32767 a 1 False and true / 0 and 1 ee i =128 to 127 ie 4 =2,147,483,648t02,147,483,617 a 4 34 «10% to 3.4 * 10" = (Precision 7) 8 1.7 x 10° to 1.7 x 10 double Cases 10 34-« 10° to 1.1 10% Jong double eaaW) 2 0 t0 65,535 ee stared before using them in the program. The declaration is done in the Variables have tobe declared beter este intn following way: datatype variabls @Td.,>>3Noo ue 10u0 ©: equa OM FUpCnege fums‘q/e quy #()z08270 } (Qureu ptoa epnqouty epntoury :C wpsBo1g “449 ur surmsoud may v no 2 80.197] pnjou 9q ysnu juoutayers ( )yoio® oyp ‘MOpULA [PUTLUID) 10 ne oma - ndino xp sXejdsip woo. Burystuy soye pur 3 : p09 aaunos ay o} Yoeq sUATON IL pmbaam 2 es -pasn ag sn sowezado [pus oy ‘2u NOU 4) 04 NdiNO 1xAU 94 2 Aon Geiser moet eins ea) apr otros xp uy dino snoqaoud Kus soj0 0) J: PUB 4/ UOONIEG swuowiares ay) Bussojaua £q poppe aq uv sjusuoD ouy] ajdyinyy “siuaLUTOD aut] 2/5 40} ij, UM WoUDIS a4) Burxyoid ) Aw st ‘shejdsip wuowioyeys yeu a4] “sorUoW 94 Peounouosd) ino» yuouw1syR)s noo Fu MHL (1) stsoxpuazed Bursojo Furyoyow v aany pinous UaeiBoxd 10 vonoury 940.01 BuiBuo|9q siuswoyeys dry Suryousps009 ay yiim surBoq sume u WMO AMOK D8249 0} NOK smo 10 >> sasn Ay Sujdstp uot Q) sissquaied Ruuod 18.0) pasn a. N99X9 LuMToad lo. L194 JON J iNdiNO Bur me and cit have been initialised ay double 8 they Tam €0 Wap 10 Numbers using wt '¥ may hold fractional values, Program $: Prog: mporary variable, 4o ’ r void main () temp out <<" enter two numbers in>> nl>>n2 ut<< “numbers before swapping are ”< #include void main() ( clrscr() int nl,n2 rs” cout <<“enter two numbe id WwowWers punodiiod, aj3u1s PHEA +499 Kay uowres uo) seach [euoneIeY/teorSo-yanouypuy kuy uontpuo y ‘oroyan Piomsoy aaa Suawayeys (wourpuo) jr ‘SMO|]O} SU SI XEIUAS ay ‘ony st WONIPUOD payeioosse an pronaons WSteHS PeveIposse amy “Sep uswSIES Uoro}os vst suauaroys 77-1 ‘an} SP UDYR} St aN]RA OsOz~ HOH PUE as|ey SE HOE) SI o1az pu payenyeAa ag 11m worssaidxo qj uatp ‘wostreduuro9 104 pasn a: ue ssoreiado [euOHE[ax OU J] “UoR|pUOD asjpy Jo ann spfa1é 1oupL9 ‘pys ‘sroresodo [euonejas Butsn ying worssexdxa ue s1 uorpuod 10 uorssaida ay uorupuos tuo Supusdap UoNNdaxe soy syuawIDWeIs Jo Js v ASOOYO 0} MOT[E sTudWHA}eIs UOND2IAs ay ++ Ul squauiaye9s jo13U05 UoR2aIa5 quowares ATIHM OC *£ qoWOeIS TTA "TZ quowaweis YOr “T 449 UT squoWayD}s SuIdoo] 40 sjuauo}Eys uoREIIT 7 quowarels HOLIMS “S aoyesado [euonpuos “F quowiayns 41 porsou “¢ juowoawes ASTA Al °Z quoworers 41 “L 4-45 ur siuaurayers Jonu0d WOHD9}9S 7 snus aq wea quouayes teord Jo WoRNIOx? orgy ut s9pzo op 0} si2}at fonuos JO NOLL JOULNOI IO MOT ( eQueae ore butddeas 2033” szequnu,,>>3N0o {gu-TusTa feu= Tete ssyuauroyeys SULMO||OF sursn a P9pi0 ayy, paunioyiad ose siusUTOTEIS WeIBOs zur>tur>» fgueTustt 1, >>3ned exe burdens ezogeq szequnu,>>3) 4 tguc> Turi -pacejdsip st yinsax ayn pure Aqqeauanbos > pue q yim pazedisos si “usu ys2Bre] ay 9g 01 poumsse st e 4s “Joquinu 1soreai# oy) 105 159) pue Joyo au) s9ye aU0 posn are syuwayes st jenuonbos “ase9 siyp uy i$ ere ‘ ()yp3e5 #28T>>,: ou 38e6ze7 u\,>>3n09 | (2>2eT) 37 fq= xey (@zet) 31 =o foxcacceccuts aa ; Te oan, *FRT‘O‘Q’e aur , Ourew 30, Uorw02=pmtourg 10 af8uis ++9/9 PHTEA tae pees uorssaidxq eae ate : a : “ary sqquamiaye3s asia GD >. sc 5u023215 (worrpuos) 51 “wonse JO asinod urey29 B SMO]IOJ II “saseD HO Ut ‘SI BUA ‘aS|eF SI UONIPUOD PayEIOOSSE UAYM PEMOT]OJ Os[e si uORDe Ue au9q yng ‘ft 3¥T] IsNf JUOUIZIes UONIIIIS B OS[E SI SIU] “MMauMaIOIS IST 4] “poresued st indie ou pur pakejdsip si oSessour ou “astmson “pokedsip st aBessour om) wom “sro Tenbo 10 wey soyeas3 si Be au 51 Alinyssacons urexBoxd ay; pue 4309 p> 0 Jodoq! ue yeIy sayrudis yr >307 er= ‘ory. uorssaudxg [v01307 /1P eqyuomayers + THUdMIA}EIS, (WOHIPUCD) :smo|]0y sv st soyezodo simp Jo xujuds [esouNs OL TOMS 2s]0 Voy {Jt Jo quowrooeydau st 11 pue sorwsodo Areuso} pafqes ose St SIU :4oppsado puorpucy “panty aq) Stowe z9quny ysodsv] oy} skvjdsip pue zsn ay wos siadoyuy penbaun eos) s}deoov wreidoud oAoge ayy f | xequnu 38eB28T O43 ST . >>9>>3n00 ((a<0) 93 (e<9)) 37 este {,FequMU 3S8B22T 843 ST , >>G>>an0o ((2>e>>4n00 ((e>IN00 fo‘q’e aut ) ()ureu pros opnrout # gy minsso4d SUOHIpUOD afdyjnut yo ajdueXd * 9818} oe suontpuos 38 OG J Su pue jt parnsoxs 94 j11m Tmowraress “any axe yiog jt uoAa pur on. ZHOHIPUED 40 [YORPUOD so4p19 41 oe 94 [Il THuowores “ajduiexa 9404 payngaxe 24 IM ZiuaWA}e}s soseo doyjo ype ur pue ony a Painoaxa CHONPUOD pue |uoL pod ayp YyI0q J! P>! omy uy 74 ILM Truaworys ‘adurexa axoge out Ul oe) SHuowye}s sqauawiaye§ aso Suaua;2s (Quon spud) |) juo} PUOD)) Fy e ((uoy PUD) »p2p ({UOF SUONIpUoD opdyyynun soy XESS he Program Il: # include void main() { int a/b,max coutc<"Please enter two numbers eind>a>>b7 maxza>b?a:b/ cout< void main() { ant a,b,c,max? cout<<”Please enter three numbers”; cind>a>>b>c; max=a>b? (a>c?ac) : (b>c?b:¢) + cout< jinclude nt main () int day coutc<'\n Enter day number or a day ing weap wee) m>day switch (day) case 1 cout<<"\n Monday"; break; case 2 cout<<"\n Tuesday"; break case 3 cout<<"\n Wednesday” break; case 4 cout<<"\n Thursday"; break case 5 cout<<"\n Friday"; break case 6 cout<<"\n Saturday"; break case 7 cout<<"\n Sunday break; default: cout<<"\n Wrong Choice: ..- Setch () ; Teturn 0 Here, the day number is entered and put as a switch Vani With the other constants from 1 to 7 and acts "umber from 1 to 7, then the default case is execute 7 and acts according Try again"; able. This variable is then compared ly. If this day does not match any INC++ ING STATEMENTS ITERATION STATEMENTS OR pee Janguage that allows US TOEXECK ang ar structure in a programming Tines again and agai. Ibis also knoyq ‘A loop is a particular struc a few lines of code repetitively iteration. It makes an action eas ic objecti loop is: ‘Thus, the basic objective of @ me Z to execute some lines of code ee io » lines are executed, and ; er of times those 4 to keep a track of the numt Bae 7 tobe able to stop the execution when requ! Ss ee ving the numberof times these Tines will be executed, wena “Since we are talking about recording “Mrocourrences. This variable that ats ay have I count the numbs able that Hobie s variable thw vvirol variable and keeps a track of the repetitions. We will ry pee sis ce! | control the behaviour of the loop participating i ariable wil variable as an LCV. This variable wi : PP in varton tha will decide whether to execute the line again or fo stop the execution, without writing those ier to do multiple times Parts of a Loop A loop has the following parts: ion of the loop control variable (LCV). 1. Init 2. Conditional expression that checks whether the LCV satisfies the required condition or not. 3. Updation of the LCV which ensures that the counter is either incremented or decremented, 4. Body of the loop which contains all the line(s) of code that should be repeated. In loops, the loop control variable is initialised first. After initialisation, the control flows to the body of the loop where the instructions are executed. The loop control Variable is then updated. The condition for successful continuation of loop is checked in the next step. If the Condition is true, then the body of the loop is executed daz. Thi process continues il the condition i alse us, the body of the lo we ae loop is executed more than once Bae | (Sian ] =e ee Accumulators are variables having a Store the values of certain ; S0 operations within a | the already existing value. Thus, the accumulare cee loop is completed. G oat iP completed. Generally, an accumulator is inital Pecial purpose. They accumulate a Y Tewrite new values after consider? The 2 a The f For st you. The s} Orde general form of an accumulator sUM=SUM + COUNTER The or + PROD = PROD * rhe following loops are available in ¢ ee 1. for statement while 2. while statement 3. do while statement jement: This loop is basicalh For statement: P ically used when the c fe he number of iterations is exactly known to rhe syntax is as follows: ndit for(initializatior rementidecrement) Statement; OR Initializa for( ; condition ; increment/decrement) statement; OR initialization; for(; condition ;) f statement; increment/decrement; Order of Execution: Thitatisation ple of While loop psa tream> Ex; jpoclude eee tncludeciostrean> 4 int main(y =0 eee int mo wnile(x< do { ett r+; cout<< x coutc< x; , 1 while (r<5) ; return 0) return 0 } } Break statement: Break statement is a loop prematurely and send the control n unconditional statement, it is used to terminate any at the very first statement following that Joop. Syntax break; Break statement can be used as an unconditional statement as well as a conditional statement. Examples of Break as an Unconditional Statement / inside do-while loop // inside while 1cop RE ro ee finclude #include #include int main() oe int main() { { { int x; ee int x x=0; for (x=1;x<=100 ;x++) x20; while (x<100) t do { cout< 4£(050) ai break; break; ) coutc ‘Do While loop Pncludasiostream finclude void main() int number, fact=1 Coutc< “enter a number cin>Snumber for(int isnunber;i>1,4 ct=factes "TiS Prime « OF not umber /2:4+4 essble by any m ; weber from 2 to number/2 [ff «+ Loop: a structure that allows execution of © «Accumulator: special variables that store bs ‘a Tine or a few lines of code repetitively | some values within a loop. The previous : without writing those lines again and again i values are also added with the new value 7 Aloop makes an action easier 10 repeatedly. / A loop is also known as iteration. 7 Intialsation, condition, updation a BOSD if the condition is false? ASSESSMENT ZONE ae least once even. (d) None of the above A, Chopie the correctamswers cuted at | (¢) do..while loop ing loop wi ? 1. Which of the followi (b) while loop nany times for loop executed how many (d)49 © j=0;5<1005/-j+2) will be exe (951 2. The loop for(j=03 (b) 50 100 e executed? © 11 the following be 3. How many times wi x=10; do { couts 2. 2. Hinclude void main( ) Void main( i ( char ch=’P! int choice; eit cnich) cin>>choice; : switch (choice) int c = 5+4 case 1: cout<<"choice is < Void main( ) { int choic Sin>>choice Switch (choice) “Else of Switch Selection statement + ttcan work only with integers or characten 10. Type of error Down ; Oe elon present in conio.h header file 3. Present if the false condition has to be chest 4. Anon-finite loop 6. Adatatype which supports fractional values 8. Each condition of switch 9. This can hold only whole numbers % \. Sequential programs and conditional programs, rvgram to print ‘Hello World’. rogram to print your name, * = program to add two numbers and display the given numbers and the sum. + Write a program to find the product of two numbers and display the given numbers and the product, re! Ww Ww Write a program to find the area of square. Waite a program to convert Fahrenheit to Celsius, B. Selection statements 1. Write a program in C+ to read th ie total marks obtait Grade of the student in that subject ined by a student in a subject. Find out the The criteria for calculating grades is as follows: er) Greater than 99 {shan or equal io 90 but greater than 39 tes than or equal to 80 but preter than 70 £285 than oF equal 70 but greater than Less than 60 = Write : *Program to check ifthe given characteris a vowel w Loop based programs “ Aide: from 30 t 10 inn . =e ¢ of the source code file’ the he es used, What commands are present in the header file conto. * Explain th hantsm of this program. s he dry run and output of the program Hf eee

You might also like