PYQs

You might also like

Download as pdf
Download as pdf
You are on page 1of 68
CHAPTER Programming Concepts Le ea or aes CHt Introduction i. C++ isan Object Oriented Programming (OOP) language. ii, Itwas developed by Bjame Strusrup in 1982. iii, Is an extension of Procedure oriented language C. Concepts of OOP were added to C language and renamed as Co iv. The instructions in C++ language uses English like words ‘with different symbols and digits, with C+ + @ Note : Following table is for reference. Students are not supposed to remember all of them. ‘Table 3.1.1: Keywords in CH auto [break [ease [char [const | [continue |default [do [double [etse enum [extem [float | for 010 it [ie long register [return [ston [signed [sizeof [static | struct switch [typedef | union | unsigned | void volatile | while asm_—[eatch [class [delete | friend |intine Dl 3.1 TOKENS new | operator| private] protected | public | template | this| throw [try | virtual 3.1.1 What is Token ? Every language uses some words, letters or symbols ‘Which have some meaning and some purpose in & program or in ‘an instruction, They are collectively called as Tokens. ‘Tokens can be predefined words, symbols or user defined words or names. ‘Thus, smallest meaningful part of an instruction is called asa token i Identifiers : Name given to any part of a program. eg, variable nam: Keywords : Predefined words ofa language. Operators : Symbols or words which perforin some actions ina program. funetion names et iv. Constants: Fixed prodefined values (e.g. numbers) 2. Keywords of C++ i. Keywords are the Reserved or Special words in a given computer language, fi, These words have predefined meaning and are used for partiular purpose ina language. iii, These words should be used for their predefined purpose only E iv. Keywords can't be used as identifiers. eg. variable name ‘can't bean int oF static (sD-12") int, static, private virtual, ete, are keywords of C+ 3.1.3 Identifiers i. Identifier is a name given to any programming. entity (by programmer) like variable, function, aray ete. ii, Identifier ie, name should follow following rules: 4. Name can consist of Alphabets, digits or underscore (_) symbol b. Name can’t start with digit. Names can’t be repeated iii, Any name must be predefined before its use. marks, Sum, Al, b_dS, _a2 .. are valid names ab, rao, SY. Hgame ... ae invalid names 4 Literals in C+ + (Constants ) i. Literals (i.e. constants) are the fixed values. There are two types of constants : Predefined constants and User Defined ii, Value of constants can't be changed during. program ‘execution and compiler knows the values of the constants, at compile time. Predefined constants “These are numeric or tent values i, Integer constants (Integer Literals) : t's an integer- valued number. eg. 124, 453, 0, 560050, 7 ... any integer value Computer Science -1 ji, Floating-point constants (Real Constants) (floating point Literals): It is a base 10 number having either a decimal point or an exponent, 5.06, 3E7, 34E4 ,7.0, 00 iii, Character constants (Character Literals) constant isa single character enclosed in single quotation marks. Eg A’s'p! “E''4, $89, +, 57, + *(opace) ete (Programming Concepts with C++)...Page no (3-2) 3.1.5 Backslash Constants (Escape Sequences) i. These are the combination of backslash (\) symbol and few other characters, ii, Used in format string to format or change the output eg. stands for new line (or line break) iii, Escape sequences are used in output instruction, Following list shows escape sequences a. Character constants have integer values (codes) that are defined by a particular computer's character set. Essape Char__Meaning ‘ b, Each character (key of keyboard) is associated with a code 2 Bev tine called as ASCII code. —- Tab ir Cartage return “© Note: Every character (1, alphabet, digit, etc) is Single quote(’) represented in computer as a number called as pear Backslash character code (called as ASCII Code). The codes & Double gi 5 range from 0 to 127. e.g. character ‘a' has code 97, 7 Ae Sepa character 'B’ has code 66 etc. String Constants (String Literals): String is sequence of | int a=65) b=40! ‘one or more characters enclosed in double quote( “ ") cout << “ONEW"; signs. Iecan consist of any characters supported by the character set of C+ ie. letiers, digits, spaces, symbols, et. 8. Thus, user name, password, address are string (Le. text) type dat, Eg “Hello!!!” , “Roll No: 1234", “5278”, “a", b, Strings is a text data, and they don't have any numeric values, ‘Symbolic constants (user defined constants) i, Symbolic constants are defined by using Pre-processor ‘commands as follows, define name value eg. define RATE 10.5 ii, They are also called as Macros. In C++ macros can be simple formulas to. eg. #efine MULT(a,b) a%b int x4, y=3, 2 then, 2= MULT(XY)} stands for: 2=x*y; iii, One can define a constant using const keyword using following synian, const DataType name = vale 8 const float RATE = 10.5; iv. Above line defines a constant with name RATE and fixed value 10.5 ¥. Symbolic constants are normally defined atthe beginning ofa program, vi. When a program is compiled, each occurrence of constants name is replaced by its value. (stD-12") cout << TWOWTHREE” ; cout << *\"Four” in” cout << “Five”: Output ONE TWO THREE“Four” Five D> 3.2 SIMPLE C++ PROGRAM 1 Structure of C+ + Program | Deters \ge MRS ERIE csr Gace a Tens @ Note: C++ programs can be writen in Older software like Turbo C++ or new Software like Dev (C++. Program logic and core part remains the same. In this book Programs are written using new Software, Refer to two example programs given in next topics, A typical C++ program will have following structure: iL Header files to include i, Global constants and Variables fil. Class Declarations or class Definitions iv. Member function definitions ¥. Some Non-member funetions (e.g, Normal functions like C) Main program ie. main ) function. Computer Science -| i. Assmallest C+ program ean be writen with only main() to perform some tas, Or it can be written with some fun write in C programming, eg. A.C+ program to display sum of 2 numbers: ons and main( ) as we fi, A smallest C+ program can be writen with only main() to perform some task Or it can be written with some funetions and main( ) as we ‘write in C programming, eg. ACH program to display sum of 2 numbers: * Program written in Turbo C+. #inclide © Header files #include void main) { ab; © Variables for input celiser( ); € clears screen (display) cout<< “Enter two numbers :” ; Coutput command cin>>a>>b; € input command +b; € variable ¢ defined here cout<< “Sum =" < € Header file int main( ) 4 € Variables for input + Coutput command cin>> a>>b; © input command int c= a+b; € variable ¢ defined here cout<< “Sun =" << 0; € Output sum return 0: int a, ccout<< “Enter two numbers + Output (same in both software ) Enleriwo numbers : 5. 7 Sum = 12 Do 3.3. DATA TYPES OF C++ Q List the different types of data of data types used in C++ with example. Datatype specifies how dara will be sored (\e. organized) in ‘computer's memory and what all operations ar possible on it ji, Inevery computer language there are some keywords (e.. in C++ we have int, float), which represent some data- type of the language. (s1D-12") (Programming Concepts with C+4)...Page no (3-3) ‘The C++ Primary data types are listed below. Hoy en tale e ype ced h Co wa ca fe et ee en (AoE Dens) Primitivedata | Derived | User-defined types pes ‘ypes char (1 byte) anay Serutare im @ortbyes) | Poimer Union float (4bytesy | Function | Enumeration double (§ bytes) lass void (no size) Primary Data Types in C++ (Or Explain Primitive / Ba: Types) i. Primitive datatypes ae built-in types ofa language. ii, . Their memory size is fixed. iii, These are simple types and hold one value at atime. iv. There are mainly § different Primary data types as shown in the above table. (these are also called as Scalar Types, since they hold one value at time.) 3.3.1 Type Modifiers (Type Qualifiers) These are the keywords that are used with basic data-types to mention exact Type and Nature ofthe variables, constants. i, The keywords are: shor, long, signed and unsigned, ii, They specify the numeric range of working and/or size of| the variables. iit, Also, ype qualifiers mention whether a variable can hold negative value or not. iv, eg unsigned int a; //here, ‘a’ is defined as int, that can hod only zero or #ve values v. Two type modifiers can he used at a time ( one out of signed/unsigned and the other from long/short) in a variable declaration. eg. unsigned long int m; OR unsigned long m; shed | The signed variable can hold negative value as well as positive value. This is a default type ‘modifier for all the basic data types. The keyword ean be used with int or char datatype to declare a signed variable. (All basic variables are by default signed variables) Funsigned | 1: mentions that the variable can't hold | negative value, The keyword can be used with int or char data type to declare an unsigned variable, (Assigning a negative value to unsigned variables won't generate compile esr.) Computer Science -| (Programming Concepts with C++)...Page no (3-4) Tong “The Keyword can be used with int or double types to mention their size. Along int is always of size 4 bytes and a long double of size 10 bytes Default int size for some C++ versions is 4 bytes. Thus, in those versions, it has default ‘ype modifier i along. The keyword is applicable only foran int type which declares an int of size 2 bytes. Default int size in older C++was 2 bytes. Thus, in those versions int is by default shor int. iii, Each operand can bea single valu, variable oran expression. eg P=M+N/K iv. In above expression P, M, N and K are the operands and ‘operators are + (for addition) and / (for division) also = operator is for assigning value of right side expression tothe left hand side variable, ¥. According to the syntax used for the operators in any expression, operators of C ean be broadly classified into ‘Three types. 3.5.1 Example any Six Operators in C+ + Dp 3.4 DEFINING VARIABLES IN C+ + Defining variables in C++ Variables can be defined at any stage in a program. Variable must be defined, before its use, with proper data-ype, Typical syntax for defining a var i. Defining a variable ble is a5 follows, Syntax DataType VariableNamel, VariableName2... eg. inta; float b, ¢ Hl. Defining and initializing a variable Syntax : DatalType VariableNamel =valuel, ‘VariableName=value2, eg. int 2-10; float iii, Defining and dynamic variables initialization of Here, @ variable is defined an assigned value of some ‘expression in same statement, Syntax : DatalType VariableName = Expression; im 9-3, b=4; im ¢=(atb)*2; double m= sait{ay; //store square root ofa in m D1 3.5 OPERATORS IN C++ [[e. Baoan ciferent operator used in Co= J i Operators are some symbols or keywords that are used in program instructions to perform some operations like Arithmetie, Logical ete. ii, _ Operators work with one or more Operands. (s10-12") ELE “@ Note : For such question write any explain six with syntax, and example. Arithmetic Operators i, There are following S main arithmetic operators. + Addition , - Subtraction, * Multipli Division and % Mod(remainder) fi, The arithmetic operators (+, -, /,* and others) have same meaning asin arithmetic iii, The % operator is fr integer operands only iv, Itresults into remainder ofthe integer division eg. B%5>3 20%4>0 2%532 3.5.2 Increment/Decrement Operators i Inerement operator is denoted by ++ and deerement bj ‘The operators are used to increment or decrement value of | variable by | eg, If int a=10; ii, Then increment operator i used in Following two ways, ss++; called Post-increment (Post-fix operation ) called Pre-increment (Pre-fix operation ) ili. In both the cases the value of an operand is incremented by eg intk aakH + Hi: J =10, 9; Here, Kk inerements afer instruction, so k-3 increments before the instruction, so j=1I1, Hence 3.5.3 Assignment Operators i. Assignnient operators are used to assign value of an ‘expression to a variable on the lef side of it. ‘Simple assignment : Here the RHS value is assigned to LLHS variable. RHS ean be a value (i.e. constant), variable for any expression Variable = Expression ; ‘Compound assignment operators : The operators have a following form, Variable Operator = Expression ; eg AT=P+Q > AW A*(PHQ) A=PIQR, A= A~(P*QR): and s0 on, Computer Science - | 3.5.4 Relational Operators i, These operators aro used to compare (numeric) values of two variables or expressions and produce result of | comparison, fi, They always produce 1 (Je. True) oF O (ie. False) as a result of comparison, ‘The operators are, lessthan, <= less than or equal to, > greater than >= Greater than or equal 0 Equality operators ‘The operators are used to test equalityinequaity between ‘the numeric values. = Equal to Consider int a=10, 6-20; results into false ie. 0 b==2* a; results into ime ie. 1 Not equal to bb!=2 * a; results into false ie. 0 3.5.5 Logical Operators Logical operators operate on two operands, which are ‘normally logical or relational expressions, to produce a result that is either True(1) or Fase(0) && Logical AND ‘The result of an expression is True (ie. 1) if both the ‘operands have value True else result is false Syntax : Operand] && Operand2. Il Logical on The result of an expression is True (i.e. 1) if any one or both the operands have value True, Syntax : Operaid] || Operand2 1 Logical NOT i. The value of the operand is negated. (Le. true becomes false and false becomes true) ii, Isa unary operator. Syntax !Operand i. In all above syntax operands can be expressions (or values) which result into logical values true / alse Examples of Logical operations Assume, int m=S,n™=12,p=7 (sT0-12") (Programming Concepts with C++)...Page no (3+5) 1. (m> is also called as Extraction operator. It is used to extract (receive! input ) data to some device like keyboard, file ete. It works like an Input operator. (explained in derail i further ropes). iii, To complete the answer write example program with cin and cout 3.5.8 sizeof( ) Operator i saeof Gives size of the operand in bytes(not applicable for ‘void’ ) eg. intans; Computer Science - | (Programming Concepts with C++)...Page no (3-8) 3.5.9 Operators Specific to C++ In addition to this C+ has following Operators which are used in Object Oriented programs. ‘® Note: These operators require knowledge of OOP. and some other topics specific to C++. i. We will discuss these operators inthe due course. ‘Those operators ae listed here just for continuity ofthe topic. < Insertion operator > Extraction operator Scope resolution operator ot Pointer to member opersior new Memory allocation operator delete memory release operator 10 Memory Management Operators io memory management operators avaiable | in C++ and state its use in one line. i @ Explain the use of Scope resolution Operator and Memory. management operators in Cr+ with ‘examples. (April 2023, 4 Marks)} | | i. I's keyword and operator of C++ ii, The operator is used to allocate (reserve) memory for one ‘or more variables . (or one or more objects) iii, The operator allocates memory required for the variables ‘and returns starting memory address of the block. iv. Thus, it works with pointers and memory address. ¥. It is used for dynamic memory allocation delete i, _I’sakeyword and operator of C++. fi, Tt ig used to release i.e. ffee the memory allocated (ce, reserved) for one or more variables. iii, The memory allocated by ‘new operator must be released by using delete operator, else it ereate serious memory usage issues. (details and programs related to this are in Chapter Virtual functions) 3.5.11 Scope Resolution Operator ( :: ) ere Q Explain the use of scope resolution operator in C++ with examples, ‘The operator is used in different places for ifferent purposes, given as follows Working with global variables: Is used to resolve naming conflicts between Global and Local variables of functions. (sT0-12") ® Note : Variables defined in a Function or Block are When a local variable ofa finetion and global variable of program have same name, to access global variable we use Scope resolution operator before its name. called 2s Local variables of the function or block. These are accessible only in the function or block in which they are defined, Variables which are Not defined in block or function are called as Global variables and they are accessible in entre program. b. If local and global variables have same name then in the function, program work with local variables by default ‘cout<<"Local var =" << s <), iii, We can input multiple values of any type (Numeric, Characters, String ) using the ein object. Syntax : ‘cin >> varibalel >> varibale >> eg. inta, bs float m; cin>> a>>b>>m; @ Note: In case of String Le. text data cin can input conly one word. Hence, to input multi-word string we i. C+ provides two objects : cin and cout for data input and ‘output respectively. i, Header file ostream. : The file has some code, constants, declarations that @ programmer needs to use for data inpuvousput. fil, To use cin and cout we need to include this header file in ‘our program. fv. cout + It is used for console output using insertion (Sperar (<<) pecan ¥. One can output multiple values of any type (Numeric (Characters, String) using cout. (sTD-12") operators ee delete Use getine( ) function. Mulplcaive +1 % LioR ages E TOE 1: Far ding puting) sing it we coe ing) — = a ccin.getline( a, 50); ... Where ‘a’ is a string variable, 50 is Relational eo Ea ‘maximum no of characters to input. Eguality oS LwoR ¥.Itean input one string of one or more wards a tine Bitwise And & LR Bitwise XOr BS LioR Do 3.8 DATA TYPE CASTING |Bitwise Or IL |LtoR Ps Logical And ee Lio i. When any expression works, the variables involved in Logical Or i LioR calculations ean be same or diferent types. ceric an ir | TORE Rwok ii, While evaluating the expressions, one type of operand is idbacaat a BuO treated asthe other type (or converted to other ype), if & required. aaa ; ae fii, This type conversions can be done by C- or user. iv, Accordingly there are following two types. 1, Implicit (Automatic) Type conversion a, When an arithmetic expression or assignment operation is executed, C++ converts one Type of Operand to another Type of operand if required. This is called as Implicit type ‘conversion (or Automatic type conversion). b, Some of the rules of automatic type conversion are as follows, Same type of operands ‘An arithmetic operation between two same Types of values results into the same type of value ', eg, operation between the two int values will result into int value and an operation between two float values will, always result into float value. (Programming Concepts with C++)...Page no (3-8) Computer Scionce - | eg inta-10,b-% then, afb ... will result into 3, Also, 94... result into 2 which is an integer value. 2.5/1.25 ... will result 2.0 25/20 ... will result 1.25 Different type of operands Whea there is an arithmetic operation between different types of Operands, C+ internally converts the smaller datatype (range-wise) operand to bigger datatype ‘operand (range wise) and the Data type of the resultant will be bigger of the two Operands eg. int A float B=4;, then A/B. ... will esult into 2.5 While evaluating the expression, C++ converts value of variable A into flost (because the other operand is a float i.e bigger data-ype of the two). And thus the operation is done between the two floats and the result is a float type value Assignment Operation When one type of value is assigned to the other type of variable, the right hand side value is converted tothe left hand side variable datatype (.e. promoted or demoted to the LHS. variable type). If eft side variable is of smaller datatype than the result of expression, then it may not receive the same value as RHS. Also for any ofthe above operations the datatypes should be compatible to each other. ¢. int, float, char ean work together. But we can't operate user defined types with basic types or arrays. Also arrays and basie types are also. not compatible Explicit type Conversion: (Type Casting) We can write a statement which explicitly converts one type of value to another if needed. ‘The Type Cast operator docs this. Such type of conversion is called Explicit ype Conversion (or Casting) The syntax for type casting is (typejvalue ‘Where the value can be value of an expression, a variable or a constant, and type can be any data type in C+ eg int a=10, fost k; k= (float a+b + ey6; Here value of (a+b + c) is evaluated as 1 (ie. an int) and the casting operator (flat) converts the value 15 into float. ‘Then the operation is done between float and int (i. 6). [Now the int value 6 is converted to float before division (by C+4) and the result will bea float valuetie. 2.5) In any of the above type conversions, the variable, for hich type vonversion is applied, is never affected. viii, Type conversion can be used with for compatible data- types only eg, int to float, or float to int or long int ete are valid Using above type conversion we can't do. conversion between primitive and user defined types. It can be done using special user defined conversion using OOP techniques. In case OOP, one can type cast objects if they are related ‘ith inheritance. Thus, base class object and derived class object can be type casted into one another using type casting, Also, pointers can be type-casted for compatible datatype pointers and pointers for Base and Derived clas. Dy 3.9 MANIPULATORS 4 Manipulators are the special functions that can be included. jn output statements to alter the format ofthe output. ‘The data is displayed in diferent format but the data is not ‘changed by the manipulators Table below shows some of the commonly used ‘manipulator functions. To use the manipulators, the file iomanip.h must be included in the program, “Manipulators Purpose setw( int w) Sets the field width o w. setprecisionint p) Sets a number of digits of precision to . setfil(char ch) Sets the fill character toch, hex ‘Tums On the hex flags uppercase() [Tums on the upperease A Manipulators provide same features as that of the ios ‘member functions. ‘Some manipulators are more convenient to use than their counterparts in the class ios. For example one or more manipulators can be used in one statement to format the output as shown in following example, Program 3.9.4: Working of Manipulators using namespace stds Hineluce int { main 0) int a = 100, float b = 25.2887, n = 123.345: cout <> pl >> als cout<<"Emter price, qty of another item:"s (stD-12") cin >> p25 > qi total = pl®ql + p2%q2; cout<<"Total=" << votal < int main() { cin >> num: l= num / 100; 3 = mum % 10; 2 = (num/10) % 10; sum = dl + d2 + di ‘cout <<"Sum of digit return O; i Output Enter a number 13 of digits i from keyboard and find_greatest_number | Mit using coven conic. EEC | using namespace std ‘Hinclude int main() { int abosmn: cout<<"Enter three numbers 2 cin >> a>>b>>0: a>b2arb; mee>ntern cout< <"Largest no, =" << m; rotun Os Computer Science -I output Enter three numbers :20 40 32 “Largest no, =40 Dy 3.11 CONTROL STATEMENTS Control Statements Introduction By default program executes instructions from top 10 bottom i.e. sequentially without skipping any instructions or ‘without repeating any instructions Control statements are used to change the sequential flow of program, There are two types of selection statements i. Selection statements ii, Looping/teration statements fii. Jump statements 3.11.1 Selection / Decision Statements Statements are as follows: i. if statement Symtax : iff condition } statement Here, ‘condition’ is any statement, commonly logical or relational expression, that results into trueie. 1) of false (elo). ‘And ‘statement’ can be one or more C++ statements Ifthe condition results into true, the statement part works, ‘otherwise the statement is skipped and program proceeds with further par, il, if-else Syntax : iff condition ) Statement] else Statement2 If the condition results into true, then statement! works, otherwise the statement2 works and program proceeds ‘with further par, Program 3.11 check whether it Input 2 positive integer values and '3a leap year or not using namespace std Hinclude- int main() { (Programming Concepts with C++)...Page no (3-10) cout <<"Enter # number cin> > no: iff (not400 { 88 no%100! | | ( noda- cout<<"Itis a leap year"s ) clse 4 cout<<"NOT leap yeat"s } return 0; } Example Outputs 1. Enter a number :2015 NOT aleap year 2. Enter a number : 2016 tis a leap year if-else-if : ( if else ladder ) Syntax if{ condition! ) Statement! else if( condition?) statement2 (condition3) statement’ else statement 4. Here, according to conditions one ofthe statements works. Program checks conditions from top. When any condition has true value, corresponding statement works and others are skipped without checking conditions Program 3.11.2 : Input a characier and check i's a digit or alphabet or other character using namespace std | #include ‘nt main) re char ch; couts< “Enter a character cin>>ch iffch> ="0'&&eh< { cout<<"Tk is a Digit’; Leh: (st-12") Computer Science - 1 (Program 19 Concepts with C++)...Page no (3-11) ( 0ut << “It is an Alphabet’; } else ( cout< int main() { int no; ehrson()s cout<<"Enter a numbers"; switeh( no ) { cease 1: eout<< "Monday"; break; cease 2: cout<< "Tuesday": beaks cease 3: cout<< "Wednesday": breaks cease 4 cout<< "Thursday" breaks cease 5 cout-<< "Friday": break: cease 6 : cout<< "Saturday break: ‘case Teout<< "Sunday"; breaks ‘default :eout<< "Invalid number's } retum 0; t Example Outputs 1 Enter a number :3 Wednesday a Enter a number :15 Tnvalid number 11.2 Iteration Statements (Loping Statements ) ‘These statements are used to repeat some part of program. 7 while satement ii, do-wbile statement for statement while Syntax : ‘whilo( condition } Staten a. Here, the statements are repeated til the condition is true. ‘When condition becomes false, the program proceeds with the further part. Computer Science - | ‘Program 3.11.4 : Input an integer and Find sum of is digits using namespace std ; ‘H#inelude int main() { int no, sum=t ds cout<<"Enter @ number cing < no; while( no != 0) } Example Output Enter a number : 673 Sum of digits= 16 Il. do-while statement Similar to ‘while’ statement this is also a loop control statement. The syntax is as follows, do £ statements } while(condition) ; <= Note the semicolon b. Here the statement part is executed repeatedly till the condition is tru, lil, for statement 4. This is very commonly use Iteration (looping) statement. ‘The syntax of the statement i as follows, for (expressionl : expression 2 expression 3 ) { Statement : } b. The statement part in the curly braces executes repeatedly Lill the expression? is tru. Here, expression! is. usually a variable initialization, expression? is some condition and expression3 is usually @ Statement that changes value ofthe looping variable, (s10-12") (Programming Concepts with C++)...Page no (3-12) ‘Write a program to find the factorial of a number. ch 04, 08, 17, Oct. 04, 09, 12, April 2022.5 Marks) using namespace std : #include int main) 4 int nis oat f= 1; //to store big value ccout<<"Enter a number:"; fori=1; i<=nsit+) coul<<"Factorial: return 05 } Example Output : Enter a number Factorial = 120.0 Program 3.11.5 : Write C++ program to find a factorial Of integers from 1 to 5. EOE ks) using namespacestd : include int main() 1; //toans for(i=1si< =n i+ +) { Pris } coutc { a) int m0, i; cout<<"Enter a number :"; cin> >nos fot wD sit +) iM(i> nol2) ret cout <<"It is a Prime number": cout << "Its Not prime number"; 1m 05 Computer Science (Programming Concepts with C+4)...Page no (3-14) Example Outputs Program 3.12.1 : Program to Input a number and check | |[ Program 3.12.3 : Program to checking whether a whether itis a positive, negative or zero. character is a Vowel, Consonant, digit or other character to input a character and (s1D-12") Computer Science -1 Program 3.12.4 : Program to display all factors of 2 sven number. namespace std; ‘include main() int num, cout<< inter a number": coul< <"Factor while( num > 1) { 4a" iff num %d == 0) { vout<< d << endl: ‘num = num fds } else ditty d return 0; 3 Output nter a nuinber:75 [eoard Exam Question Q__ White an Object Oriented Program in C++ 10 read an integer number and find out the sum ofall the eer racaa ie cimcesun asses 1) TTT using namespace std; #include int main() { int num. , sum=" o cout<<"Enter a number"; t= num: while ¢ { ) d=1% 10; sum= sum + d; t= 1/10; y ‘cout< <"Sum of digits= "<< sum; return 0: + (Programming Concepts with C+4)...Page no (3-15) Output Enter a number:5482 ee ee Spaiadome rune) REMOTES | using namespace stds Hinclude int main() 4 int num ,d rey=0 ,t; cout<< Enter a number's while( ¢!= 0) { d=1%l ev 10+ ds 110; y if( rev = um) cout<<"It isu palindrome”; else ‘cout<<"It is Nota palindrome”: return } Output Enter « number:2552 Iie a palindrome Enter a number:3442 Ik is Not a palindrome Program 3.12.6 : Display table of a given number. 2.9. for number= 4 4arts4 using namespace std; include int main() { nt mum 515 ccout<<"Enter a number"; cout<<"Table of” << num << endl; for i= 1:1<= 10; i++) (s7D-12") Computer Science - (rogramming Concepis with C++). .Page no (3-16) { [ 1 ee get-out <— | | 9 awaeenceepocamim deny = elec ol| endl; | 45 terms ofthe Fibbanac series i ¥ fag (March 04, 07, 17, Oct. 08, 11.22, April23, 5 Marks) return 0; + ? using namespace td Satie #include ce) Entera number:3 ( Table of 3 int igo ‘cout numbers \n"; fon i 1i++) { eesti ants bein) xn coiers of | one [(varch16, 5 Mare using namespace std Hinclude cout < ns with 100 atthe place of nin following program cout<<"Fibonacei series \n": for(i mee) ig ames 4 ‘include cout < anny it main) a=b; { b fae a, oer : int i, ng ote: cout<<"Enter ni ) cin>> sae fom Isic mit) irereaney sum = sum + is Fibonacei series : 0 coul<-<"Sum =" << cus 1 eet, 1 } 2 i output 5 Hang 8 Sum =1.58819 (STD-12") Computer Science - | (Programming Concepts wth C++)...Page no (3-17) | Pe 1 @ Write a program to find GCD of two numbers { \(March 06, 08, 11, 14, Oct. 04, 05, 17, 5 Marks) using namespace std: #i inelude int main) 4 int aby ged.is ile cout<<"Enter 2 integers"; cin>> a >> b; for( i= 1; 1<= a; i++) cout <"CD_ return 0; ¥ << god Output Program 3.12.6 : Display following pattarn for n lines. (input) 1 2 123 1234 using namespace std; #include int main() { int ijn cout<< fox ++) { fox j { cant < je } oul << endl: Li< i++) y return 0; ) (s1D-12") ‘Output Enter a:S 1 2 123. 1234 12345. Program 3.12.7 : Display following pattem for n lines. (inout n) 1234 123 2 1 using namespace sid: include int main() { int ijn cout <"Enter ns" ein>> ny fon { for j=si<= { coute< ji } cout< < endl itt) 1 retwin O: } Output Enter nit 1234 123 2 1 Program 3.12.8 : Display following pattem for n lines, (input) Enter n4 using namespace td; include int maing) { Computer Science «| (Programming Concepts with O++)...Page no (3-18) int igen cout< <"Enter ni"; i++) cout<<"*: /i print one speae } for j=15 1<: { its) eout<<" "5/11 space afier* } coul<< endl } retum 0: } output Enter nl Program 3.129 10 50. Display all prime numbers from using namespace sid: include int ain() { int no,i ‘cout<<"1 to 50 Prime numbers\n"s for( no=1 ; no<=50; not +) 4 forfi=2i<=no/2 ; i++) { ino %i==0) { breaks } , iffi> no/2 ) cout< > p03) (/input number in 4 element of p pik] =pl3k: i Assign value of forth element 10 element plk-+1]= pl3] + pl0}; // assign sum of "and 1* element 10" element. Declaring Array and initializing array elements 1. We can declare and initialize some or all its elements to some values. eg. int af 5]={ 4,5,-2, 10,8}; Or float bf 10]={32, 5,-1.2, Or int mf] = {2,5,-3.10.3,5)) Computer Science -| (Programming Concepts wth C++)...Page no (3-19) ii, In the last declaration array length = number of elements here 6 iil, Assigning more elements than array size is error. float b{3] = { 32, 5,-1.2, 125,89}; is compiler error. ® Note : For processing (@.9. input/output, arthmetic operations) array elements efficiently and easily we tuse some looping statement with some variable that works lke array index, eg. 10 display all the values in above array ‘a" we can ‘write for" loop as shown, eat Aray ements"; fori =0:3<5:14-+) {come afi Je“ } Output Anayelemenis:4 5-2 10 8 Hinelude int maing) { i af], is me counters for even and odd nos ‘cout<< “Enter 5 numbers\n”: if{ ali] %2==0) ett else d++-#5 // increment odd count inerement even count : coul-<<"Even no, count=" << e< int main) { int a6), i eout'<<"Enter 6 mumbers:\n": for{ i=0: <6: i++) cin >> ali: cout<<"Odd numbersin": for{ i=0; <6; i++) { if ( fi] %2 == 1) cout < int main() { int 20}, ni: oat sum ‘cout'<<"Enter n: >> coul<<"Enter "<< n <<" numbers:\1' fox i=0: i> afi: 1 ins i++) fox i= { sum = sum +l coul<<'Sum ="<< sum << "in"; avg = sum /n: ‘cout<<"Average ="<< avg return O: Computer Science - | (Programming Concepts with C+)...Page no (3-20) Output { a m if( ali] > largest) a H Bictseabee oo me } } =| eee ee j ‘cout< <"Index ="<< index ; 1Q_ Write a program in C++ that inputs and stores 10 | oS a | rcan lary anaptiaaeiiciicnen | | int main) { int af10}, cout'<<"Enter 10 numberss\n"s for i=0; 1<10; i++} cin >> afil: cout <<"Reverse Order sins for 1=9;1>=0; i ) { com << afi] << “\ } return O; } Output Enter 10 numberst 107125 4203.8 15 25 Reverse Onder: 25 1583204512710 Program 9.13.4 ; Find largest number and lis index in array of integer. Input n numbers in array, (max value of n should 50) (Oct. 04, Oct. 06, Oct. 09, Oct. 11, Oct. 15, ‘using namespace sid: include int main() { int [50], n, i indes, largest; cout< <"Enter n cout <<"Enter"<> afi; largest = ali] for 5=0s ins i++) (sT-12") Enter 7 numbers: 20 10 4030 5 53.45 Largest no, =53 Index =5 Program 3.13.5; Search agiven number in an array. Output the index of the number. If number not found ‘write message accordingly. Input n numbers in array. (max value of n should 50) ‘® Note : Since array size not mentioned, students can assume any fixed size or input n from user as done in previous examples, using namespace sid: include int main() { int a6}, num, i ind out'<-<"Enter 6 numbers: Tox for{ 1=0: 1<6: i++ ) { iff afi] == num ) { index break } } ii ==0) cout <"Number Not found"; else eout'<<"Index ="< < index 5 return 0: Computer Science -| (Programming Concepts wth C+4)..Page no (3-24) Output 1 include Enter 6 numbers: ne 10 12 6 8 20.25 { Enter a no. to search:6 ing al40}, wats Index =2 out <"Enter ns Gates cin>>n: cout <<"Enter “<< n << * numbers\n" Enter 6 numbers: 10 20 15 30 40 25 Entera no, tosearch:37 Number Not found Write an Object Oriented Program in C to read a set of 10 numbers and store it as an one dimensional array; again read a number ‘o’ and. ‘check whether the number ‘d’ is present in the array, if it fs so, print out how many times the number ‘d's repeated in the array. using namespace std; #includle int maing { int [10]. i, count cout<<"Enter 10 numbers:in"s for{ i=0: 1<10: i++ ) cin >> alils il ali] { ‘count +3 y ‘cout<<"No. is repeated ="<< count <<“ times” ; return 0; ? Output 1 Enter 10 numbers: 15 12 15 6 8 20 6 95 15 16 Enter a no, to search: 15 No. is repeated 3 times Program 9.13.6: Sort n numbers in array in ascending order. (Bubble sort method) CEO fo fox( last =n-1 + last™O; last) { for(i { iff afi+1] 3.14 STRINGS Definition : String isa sequence of characters i. In C++, a character sequence writen in double quotation (7) symbols is called as string ii, The characters can be alphabets, ‘white-spaces et. iil, At the end of string one special character is appended ‘automatically. The character is called as Null character and written as “0 digits, symbols, (stD-12") Computer Scien iv, The null characteris an indication of end of string, The ASCII code for 0" is 0, ¥. To work with text data like user name, password, address, employee's designation or department we use strings in our programs. vi String constant is made up of one or more characters enclosed in double quotation sign as shown below, “Hello” ,“Rs.12,050", “a , “James Bond” , “132” vil. Here first string has 5 characters, second las 9 characters and third string bas 1 character, fourth has 10 characters and the last as 3 characters, vili, Let's consider a string “ABHI". I is stored in computer's ‘memory as follows” TG Fabia jx. Thus, Sting is nothing but an Array of Characters, x. We use char array to store and process string values in programs. 3.14.1 St 101 ‘Assume, char a[S0]; // Array to store string Input string i, cin>> a... inputs a word. Can be used to input name, password ete fi, cin.getline( a, $0); Inputs Maximum 49 characters ( given no -1) or tll enter key i hit in array ‘a’ and adds Null character. inputs multiple words Output string 1. coute=Wl 8 aff}<=" || afi]>='A' 86 afi] <= 7) ptt: cele iff a> det: se iff afi ath clse thts && afi] <= 9) (STD-12") [Board Exam Question [(March 14, Oct. 09, 1 Paar Computer Science - | { if (ali) count +: J cout<<"Count of spaces =" << count ; retum O: t Output Biter a string ‘This is some data Count of spaces [ace 1 U Gusta che poaran sa: wilfead ssw of | el count the numberof words ina text | | Cae) using namespace std: Hinclude Hinelude char a[100}; inti, count =0:, cout < <"Enter a string 2 cin.getline(a , 100): int len = strlen(a); if lit 1) count-+ +5 "A ality] } cout<<"Count of words =" << count; return Os } Output Enter a string ‘this Count of words =4 mumbai ety Program 3.14.3 string to uppercase. Convert first leter of every word in a using namespace std Hinelude Hincludesetypeh> #include int-main() { char a[100]; int ig cout <"Entera string": (Programming Concepts wth C++)...Page no (3-24) cin.getline(a , 100); int len = strlen(a): 40] = touppert 0) js fox(i=0; 1 < lens i++) { if( afi] ==") afi+1] = toupper( ali+1]}: } cout<<"Modified string =" << a: return O: Output Entera string ahis is mumbai elty Modified string =This Is Mumbai City [QW a progam n Coe to accep sting from | > keyboard and copy sting into another sting | sou sng tebe uncon (oct. 14, 15, 5 Marks) ‘using namespace sid: include int main’) a ‘char a[ 100), b100}; int 1=0; cout< <"Enter a string cin.getline(a , 100); while( afi] != "0° //eopy string till end { i}: /eopy ith char (/ next char index } fi] = 0's // end the string cout<<"copied string =" < #includesetypesh> #inclide int main) { char 3[89]: ‘eout<<"Enter string 2" ngetline(a, 80); int len = strlen(a); 21 < len i++ ) ') WVith is space cout<<"Modified string =" < {nt main { nt af10} 5, largests cout<<"Enter 10 numbers’ fori=0t i< 10;5++) cin>> ali langost = afi for(i=0:5< 10;i++) 4 if{ ali] > largest) { largest = ali: y t cot <<"Largest no. retum 0; "<< largest <<"! t (s1D-12") (Programming Concepts with C++)...Page no (3-25) Output Enter 10 numbers: 20 10 4030 5 58 35 5045 40 Largest no. =53 Dy 3.15 FUNCTIONS i. Function is a selcontent program segment, with some name, which performs its predefined task, whenever itis called (invoked). ii, Like any other element of a program, function also has fil. There are two types of funetions in C+ a. Library funetions, a. Library Funetions User defined functions The built- in functions existing in a Programming language are called as Library Functions of that language. eg, built in functions of C++ are print), sqrt), strlen, pow() ete, ‘We need to lear the working of these functions before using them, b, User Defined functions 1. The functions defined by Programmer in a program. are called user defined functions. We (ic. users) can define funetions according to our rogram requirement. 15.1 Working with user Defined Functions i, Commonly for defining and using function, we need tue steps T,_ Declaring a finction 2. Defining a function 3 Calling i. using the function. 1). Function Definiti Defining a Function) Syntax : for defining a funetion in our program: Retum-type Fumotion_name (Parameter_List ) { statements retum expression : i Different paris of above syntax are explained below. i, funetion_name is @ name of @ function. It follows the rules of naming an identifier. ii, Return-type is a datatype ofa value that function returns to the calling function iii, Retum-type can be any data-type of C#+(basic data-type, pointer, user-defined datatype) Function in C++ can retum any type of value except for array iv, Function can retur only one value. vy. The value returned from a function ean be collected in a variable in the calling function and ean be used for further processing. ‘Computer Science - | vi Parameter_List Its « comma separated list of variables in round braves ofa form (Type argl, Type arg2, Type arg’... vii, These variables are collectively called as Function Arguments or Formal Parameters. vii, These parameters receive the values ffom a code that calls this fumetion. Arguments can be any date-ype supported by C++: jx. Arguments are optional (but open-close parenthesis are compulsory) : x. Statements : These are C++ statements like input, expressions, loops etc. The statements writen in the function body execute when the function is called. The group of statements is supposed to perform some task ‘This statement stops execution of current fiction and program control is transfered to calling function. This statement is also used to retum single value from current function to the calling function, xi return: retum is keyword of C+, xii, The return statement is optional. xiii, Ithas following syntax, a. Transfer control to calling function >. Transfer control to calling function and retum value of ‘expression to calling function ‘elum expression; xiv. The expression part in a return statement ein be any expression, but it must evaluate to the retumtype ‘mentioned inthe first line of function definition, Xv. Multiple return statements Can be present in a funtion but function should be defined in such a way that only one of them should execute, xvi. Ifthe fumetion doesn’t return any value then the function return ‘ype must be void, Such function that doesn’t retarn any value is called as void function, xvii, If retumntype is not mentioned the C++ compiler will assume the function returns an int type. % Note: One program can consists of multiple user defined functions. In small programs function using namespace std ; float average(int, int, int); /unction prototype int maind) { ‘int a=10, b=20, a float £= average( a, b,c); // Function call coute<“Ayg="<< f retum Os float average(int p, int q, int x) // Function definition { Formal flaot vs | Paramsters| v= (ptq+r)/30; return v4 , (sto.12") ‘Computer Science. Output Avg = 15.0 One can call function in following ways (if it Not void) ee {Calling a function in cout statement to output the result. cout<< “Average=" << average(a, . ¢); E: fi, Calling a function as part of an expression. ‘will ourpu, Average: £=a>averagela, b,c): Here, f= 25 iii, We can call « funetion with expression or values as parameters. T= averagel avb, a8); Here, f= 16 3.15.2 Different ways of Passing Parameters to Functions Explain ‘call by value and ‘call by Reference’ with ‘one example of each. | i (arch 04,07, 08, 2 Marks, Oct. 06,3 Marks What is call by value? ‘What isthe difference between them ? Passing parameters by Value:(call by value) Here, funetion arguments (i.e. formal parameters) are simple variables and Not reference variables. b. When fiction is called, Values of actual parameters are passed to function, e. Formal parameters are new variables and they only receive values of actual parameters 4, Thus, formal parameters are ‘not related to actual parameters If any changes are made in the values of formal parameters, then these changes are Not done in actual parameters. Drawback a. Since, formal parameters receive copy of actual parameters, the size ofboth is same. b. Thus, same amount of extra memory is required for formal parameters Program| lustrate Call by Valu ising’ namespace Std include void demo{ int y) { yoy +5: ‘cout<<"In function value="<< y < using namespace std : void demo( int&y ) { yeyts: ‘cout< Amm( int no ;_//function declaration int maing) { int num; cout<<"Enter a number: " cin>> num: Anm( num); {/funetion call retum O; void Arm(int no) // Function d= 1% 10; sum-+ d®d*d; 1105 + if( sum == no) cout<<"Its Armstrong number" else cout <<"ts not an Armstrong number"; } output Enter a number: 153 Its Armstrong number Program 3.15.6 : Define a function to find lar three numbers and return it tof Note : function is defined before maing) using namespace stds #include int Largest(int a, int b, int) t int ms iff a>b &8 a>c) (s1-12")

You might also like