32 views

Uploaded by Pa Wa N

c++

save

You are on page 1of 28

1. C++ Language

1.1

1.2

1.3

1.4

1.5

1.6

1.7

1.8

1.9

Introduction

Basics of a C++ program

Variables

Constants

Data types

Operators

Expressions

Structure of a C++ program

Turbo C++ screen layout

Exercise

2. Statements

2.1

2.2

2.3

2.4

2.5

**Input and output statements
**

Control statements

If…Else statement

Switch case statement

Programs

Exercise

3. Control statements

3.1 While statement

3.2 Do..while statement

3.3 For statement

3.4 Rules of FOR loop

3.5 Programs

Exercise

4. Functions

4.1 Library functions

4.2 String functions

4.3 Programs

Exercise

1. C++ Language

1.1 Introduction to C++ language

C++ was developed by Bjarne Stroustrup in the year 1979. It C++ combines the features

of low level and high level programming languages. It is the extension of C Language and it was

originally called as C with Classes and then it was renamed as C++. It is the most popular

programming language widely used all over the world on different platforms and operating

systems. It is mainly used for designing system software like compiler, interpreter, utilities, client

applications, device drivers and video games etc. As the C++ is an extension of C, it is more

compatible with C and it runs any type of C program smoothly.

Advantages of C++ language

a.

b.

c.

d.

e.

**It is a low level and system implementation language
**

It has a relatively clear and mature standard

C++ command are much familiar and user friendly

C++ programs are very fast and efficient compared to other high level language programs

A program written in C++ language can be run on any computer without any modification.

This is called portability of the programs

f. The object oriented programming language feature helps to create and simulate real time

entities in the programming model.

g. C++ provides rich set of library functions for variety of purpose; it also allows adding our

own functions as library functions.

Disadvantages

a.

b.

c.

d.

**It is not a pure object oriented language
**

Does not provide strong data type checking

Difficult to develop graphic applications like GUI

Does not support dynamic memory allocation like pointers in C++

**Steps in Learning C++ Language
**

Like any communication language, you should learn all the basic concepts of C++ language

thoroughly. The instructions of C++ language describe the usage of keywords with constants or

variables. A program represents the set of instructions to solve a particular problem. A bug is

called an error in the program and debugs stands for correcting the errors of the program. The

term software stands for set of programs and documentation about a problem.

Let us demonstrate the steps in learning C++ language as flowchart.

Prepare your mind to

Learn C++ language

**Read Character set of
**

C++ Language

Read variables,

Constants and keywords

Introduction to C++ for class XI by P.N

2

2 Introduction to C++ for class XI by P.. Some of the commonly used keywords are as follows Auto Break Case Char Const Continue Default Do Double Else Float For Goto If Int Long Return Short Signed Switch Unsigned Void While Main Table 3. Horizontal tab. Category Symbols Alphabets/Letters A to Z a to z Digits 0 to 9 Special symbols ‘“.:. new line and form feed Table 3. carriage return.?!/\|~_$%#&^*-+ <>()[]{}= White spaces Blank space.2 Basics of C++ Language Character set of C++ Language A character is the basic unit of any language that represents words. The following table summarizes the character set of C++ language. numbers or expressions. All the keywords must be written in small letters. Statements are written using these keywords. There are 32 keywords available in standard C++ language.1 Keywords Keywords are the basic reserved words of C++ language that cannot be changed or used for other purposes.N 3 .Practice syntax of Statements and functions Create program For the problem Run the program Yes Modify the program Is there any Bug? No Observe the output Of the program Figure 3.1 1.

is not allowed Capital letters are allowed as identifiers But accepts only the first 8 characters Underscores are allowed Table 3. name[]=”adhavan” Table 3. Identifier identifies the data stored in memory locations by a unique address. You can use either upper case or lower case.b.y.b=40. x=20. Some of the basic types of variables are given below Variable type Declaration format Example values Integer int a.3 Note: You can declare specific type of integer or the lengthy format of real numbers using the suitable keywords given in the later sections. The type of the variable depends upon the data what we are assigning to the variable. String char name[20]. a=20. the remaining characters are ignored. The formal definition of a variable is that it is a quantity whose value can be changed during the execution of the program.N 4 .8876.3 Identifiers or Variables It refers to the user defined names consisting of letters and digits. mainly serves for identifying the variables. The character underscore is used to link between two words of long identifiers e. It is advised to give meaningful names for the variables so that they can be easily identified in the lengthy program. Types of Variables C++ language provides rich set of data types for declaring variables. Some versions of C++ accepts upto 40 characters. Rules for defining a variable is as follows a.4 Introduction to C++ for class XI by P. Real float x. structures etc.56. y=0. arrays. functions. But all those variables should be declared at the beginning itself.average 1person name-age TOTAL identifier_1 si_ci_int Invalid Invalid Invalid Invalid Valid Valid Valid Keyword cannot be used Comma is not allowed First character is given as digit . A variable name can be up to 8 characters long. Character char choice choice = ‘y’. A variable can contain alphabets. In case of more than 8 characters. digits and underscore b. Example The following table contains variables and also states whether it is valid or invalid with reason. but the lower case letters are commonly used f. The first character of the variable must be an alphabet d. c. Variable gross_sal pay1 $name net salary Valid/Invalid Valid Valid Invalid Invalid Reason Underscore is allowed Number is allowed First character must be alphabet Blank space is not allowed return sum.1.

This can be used for arithmetic calculations. -4354. 0. 0X0. 0X148A. Example: -8421. 4123. Introduction to C++ for class XI by P. These are explained in data types topic. Example: 0456.4 CONSTANTS A constant in C++ language is a quantity whose value cannot be changed during the execution of the program. 0. There are two types of numeric constants such as integer and real.2 Let us see each of the above mentioned constants in detail.N 5 . You can also restrict the usage of integer constants to small or big using its sub types.1. Numeric constants Digits and decimal point form a numeric constant. +9993 Octal It consists of digits 0 through 7 with leading 0. Decimal It consists of digits 0 through 9. Example: 2922. preceded by an optional + or – sign. 0. 05731 Hexadecimal It consists of digits 0 through 9 and A through F. double and e-notation. A real number can be given in three different ways namely float. 10001 An integer number can also be given in the following three formats. Real or Float A number with decimal point is called floating-point number. 0x1243 The decimal type of integer constant is mostly used in our programs. These digits are preceded by 0X or 0x. The different types of constants in C++ language are as follows CONSTANTS Numeric Integer Real Decimal Octal Hexa Character Single Structured String Array Pointer structure union Figure 3. Integer constant A number without decimal point is called integer constant. 20331. Example: 0xbc8.

The letter e stands for base 10. Special characters are also not allowed. Example: 1010132. ‘1’ is 49…. It denotes the ASCII value of the character and it can be used in calculations also. Example: 23.N 6 . -0.232323. Exponent part must have at least one digit.4442. Comma’s or blank spaces are not allowed in constants e. The range of real constants expressed in exponential form is –3. “kalpakkam”. The letter e is used to separate mantissa and exponent. Exponent part specifies the power value and the sign of the power.3333 Rules for numeric constant a. Integer constants should be written without decimal point and real numbers must have decimal point c. Example: “ATOMIC ENERGY SCHOOL”. digit or symbol enclosed in a single quote is called character constant. 2. ‘B’ is 66…. Default is positive sign. real part and sign of the number. similarly the value of ‘a’ is 97. -1010010233. A number can be written as either positive or negative using + or – sign.33234 +123. A numeric constant must have at least one digit b. -0. Single character An alphabet. String constant Set of characters enclosed within double quotes is termed as string constants. It changes to the double format.’z’ is 122.’9’ is 57. -0. It represents base 10.343e+23 Rules for writing exponent component 1.4e38. They are as follows a. ‘Z’ is 90. +12345. Example: 1.99847. Example: ‘A’ ‘0’ ‘+’ ‘?’ ‘a’ The ASCII value of the character ‘A’ is 65. The value of digit ‘0’ is 48.23e23. Character constant It is classified into single character and string. A blank space (ASCII value is 32) is also called a character. ‘b’ is 98……. Mantissa may have a positive or negative sign. “Narasimman” Introduction to C++ for class XI by P. The general format of e-notation is as follows Mantissa e Exponent Where mantissa part consists of integer part. d.3423 Double It uses eight bytes for storage and it can be used to represent big or small numbers.343e-10.Float It uses four bytes for its storage and it can take values ranging from ___ to ____. The absence of the sign indicates the power is positive.000044500033.4e38 to 3. The default sign is positive. 0. 4. 3. E-Notation It is a special kind of real number that helps to process very big or very small numbers.

756e-05 Valid Exponential form 5. Data types of C++ language are mainly used to classify the data into different category for its storage and retrieval in memory. this is equivalent to My father”s aim was to educate me well.56e9. Example The following table shows some of the valid and invalid constants with reason.4e-38 to 3.5 Data types Data is a fact about people or a thing.5 1. The following table summarizes the different data types that can be used for both variables and constants as described in the previous sections. Escape sequences can be used to substitute the additional double quote in string constant.4e+38 8 (64 bits) Introduction to C++ for class XI by P.234 Invalid Comma is not allowed -99. digit or special character enclosed within a single quotes( ' ).Rules for writing character constants a. The memory requirement of data type decides the possible range of values for that particular type of variable or constant. For example “My father\”s aim was to educate me well”. Ex. 7 . Character constant should contain at most one character c.8797 Valid Real constant 25.4 Invalid Invalid Valid Invalid Invalid Valid Valid Invalid Blank space is not allowed Special character is not allowed Hexadecimal integer Beyond the range of integer Exponent value must be integer Exponential form Long integer form Two decimal points are not allowed Table 3.44. A string constant is a sequence of characters enclosed within double quotes. A character constant is either a single alphabet. e. Constant Valid/Invalid Reason 458921U Valid U represents unsigned integer constant 15.6 41e8 834343L 2343. ‘#’ b. Data type char short int int unsigned int long int float Double Bytes required 1 (8 bits) 1 (8 bits) 2 (16 bits) 2 (16 bits) Purpose Range of values To store a single character To represent small integer To represent integer quantity To represent only positive integers Any single character -128 to 127 -32768 to 32767 0 to 65535 4 (32 bits) 4 (32 bits) To represent big integer numbers To represent a floating point number ( precision is 8 digits) To represent a very big or small real number( precision is 16 digits) -231 to 2 31-1 3. A character constant has an equivalent integer value but the string constants does not have the equal value.N A real number with 16 digits precision.5e 4 #78. d.45 0XAB78 -67543 89.

Logical operators d. The different categories of operators are as follows a. Arithmetic operators All of the mathematical operations are performed using the arithmetic operators. It combines operators. Also specify the invalid format. Mathematical expression Multiply x with –y Add –x with –y ab/c ax2+bx+c a-b / c*d C++ Language format x* (-y) (-x)+(-y) a*b/c a*x*x+b*x+c (a-b)/(c*d) Invalid format x*-y -x+-y Ab/c ax2+b*x+c a-b/c*d Table 4. constants. 2. The following table summarizes the arithmetic operators Purpose Addition Subtraction Multiplication Division Remainder (after integer division) Operator + * / % Example a+b c-d-e A*b*d b/10 10%3 Table 4. The data elements that operate on operators are called operands. Introduction to C++ for class XI by P. 4. Arithmetic operators b.N 8 . so POW function can be used to calculate power value.6 Operators Operators play an important role in the expressions. a. 5.1. 3. Let us evaluate the following expressions Expression A+b a-b-10 a*b*2 A/b 10%3 Result 35 5 500 2.No.1 Example 1 Suppose that a and b are integer variables whose values are 25 and 10 respectively. S. C++ does not support foe exponentiation.5 5 Example 2 Represent the following mathematical expression in C++ language. 1.2 Some important points about arithmetic operators a. Unary operators e. variables. Assignment operators The operators of each category are explained below. Most of the operators require two operands and some operators can operate on single operand also. Relational operators c. array elements and function references to form an expression.

c. The result of relational operator is either true or false.0 is 3.N Operator && || ! Table 4. since the decimal point is truncated. The result of the relational expression is either true or false. not 3. Integer Arithmetic If two operands are integers then the operation is called integer arithmetic and the result obtained will also be the integer. Real arithmetic The operation involving real operands is called real arithmetic. For example –x+-y is not valid.2. Relational operators Relational operators are used to compare two quantities such as constants. No two consecutive operators are allowed. however you can write it as –x+(-y) c. Logical operators C++ language provides three logical operators such as and (&&). b. But the result of the expression is float. a>b. Evaluate the following operations.3 Example Suppose that a and b are two variables whose values are 25 and 75 respectively.333 e. The result of 16/5 is 3.0/3. otherwise it gives the result as 0. These operators are mainly used to combine two or more relational expressions.22 b. the result of this condition is true because 25 < (75+50) is true (a+b)==100. The result of 10. variables and arithmetic expressions. For example the result of 150/10. a. the result is true since (75+25) is equal to 100. Purpose Greater than Less than Greater than or equal to Less than or equal to Equal to Not equal to Operator > < >= <= == != Example a>b age<18 Mark>=35 x<=y x==20 x!=y Table 4. if one operand is real and the other is integer then it is called mixed mode arithmetic. (a!=b). It takes a single operand. d. the result is true since 25 is not equal to 75. or (||) and not (!). The operator not (!) is used to negate the given quantity or expression.0 is 14.3 Example (a>b)&&(a>c) (sex==”f”)||(age>18) !(x==5) 9 . The following table summarizes the logical operators Purpose Combine both Either or Negate the quantity Introduction to C++ for class XI by P. (25>75) the result of this condition is false a<(b+50). Mixed-mode arithmetic In an expression. The uses of various relational operators are given below. d. If the result of the operator is true then it returns the value as non-zero.b.

In the second line of Example 1. COBOL. either basic pay >7000 or net salary > 10000 Ans: (basicpay>7000) || (netsalary>10000) c. Let us consider two examples for both the operators. The operators so far discussed takes two operands but unary operator takes only one operand for its execution. So the value of pn is 16 and kal is 17. The following table gives the used of three different unary operators Purpose Operator Increment ++ Decrement -Unary minus The logical operator ! (not) also works like unary operator. pn=++kal. The unary minus operator is used to negate the operand and it can be used as predecessor to the operand. is equal to kal = kal+1. kal = 16.N 10 . pn=++kal. if not grade is equal to ‘D’ Ans: !(grade==”D”) The following truth table gives the result of logical expression containing logical operators A True True False False B True False True False A && B True False False False A || B True True True False !A False False True True Table 4. the value of kal is first incremented and then assigned to the variable pn. pn = kal. The increment operator ++ increments the value of the variables by one. b. The equivalent statement for increment operator is as follows a. Introduction to C++ for class XI by P. Example 1 Example 2 kal=16.Example Write the following problems in C++ expression form using relational and logical operators a. both maths and science are greater than 70 Ans: maths>70 && science>70 b. is equal to pn = kal. So the value of kal is 17 and pn is 17. kal = kal+1. In the second line of Example 2. the value of kal is first assigned to the variable pn and then the value of kal is incrementted.4 Unary operators It is a special kind of operators and these are not available in other languages like BASIC. pn=kal++. The increment and decrement operators can be used either before or after the operands. pn=kal++. similarly the decrement operator decreases the value by one. FORTRAN etc.

An expression consisting of ternary operators (? : ) is called conditional operator. bonus = (sal>5000)?2500:3500 If the condition.Assignment operator This operator is mainly used to store the result of an expression to a variable. The general format of assignment operator is as follows Variable op = Expression Where op is a binary operator and it is also known as short hand assignment operator. You can also assign the result of either e2 or e3 to a variable in the following format Variable = e1 ? e2 : e3 Here if the result of the expression e1 is true then e2 is evaluated and its value is assigned to variable at the left side. Examples 1. Short hand expression a+=b a-=10 a*=(a+b) a%=b b/=2. Example a=b=c=23. This follows right to left associative while executive the expression. Sal>5000.5 a=a*a Result 15 0 150 0 2 100 Conditional operator It replaces the if.5 a*=a Equivalent simple expression a=a+10 a=a-10 a=a*(a+b) a=a%b b=b/2. The common assignment operator is = (equal to ) sign. Here e1 must produce the result as either true ( non zero ) or false (0). otherwise 3500 is assigned to bonus. otherwise e3 is executed. The general format of this expression e1 ? e2 : e3 where e1. If the result of e1 is true then e2 is executed. ie.N 11 . simplifies the expression and easy to read.else construct by a single line using conditional operator. Suppose if the condition is true then the output is “Eligible for voting”. x = x+5 can be written as x+=5. Introduction to C++ for class XI by P. Note: Assigning same value to more than one variable is known as multiple assignment statement. The above syntax is equal to Variable = Variable op Expression For example. otherwise the result is “Not eligible for voting”. (age>18)?printf(“\nEligible for voting”):printf(“\nNot eligible for voting”). is true then the value 2500 is assigned to the variable bonus. b and c. Suppose that a and b are two integer variables whose values are 10 and 5 respectively. e2 and e3 are called expressions. Execution: First the expression e1 is evaluated. The following table gives the result of various expressions involving shorthand operator. The shorthand operator method of writing expression is more efficient. it assigns the value 23 to the variables a. 2..

Logical expressions Let us discuss each of these expressions in detail Arithmetic expression It represents the mathematical expressions in easy manner. function references etc.7 Expressions Expressions are the backbone for any type of calculations in the program. The general format of this expression is as follows Operand1 <AO> Operand2 Where operand1 and operand2 can be variables.+ --b c d a/b + b/c + c/d b2-4ac sqrt(b*b-4*a*c) x1/4 pow(x. The arithmetic expression in the assignment statement form is as follows Variable = Arithmetic Expression Let us consider some of the mathematical expressions and its equivalent C++ expressions. constants or it can be the reference of any function. Hierarchy of Arithmetic expressions The order followed in executing the operators in an expression is as follows a. The result of the arithmetic expression is always a finite number. Mathematical expression C++ language expression ax2+bx+c a*x*x+b*x+c -b --2a -b/(2*a) a b c --. Expressions make use of several quantities such as operands.+ --. They are a. It is interesting to note that all such expressions are executed in ALU device of CPU. Every operator requires minimum two operands for its execution (except unary operators and not(!) operator). It consists of two or more operands with one or more operators. constants.1/4) It is necessary to assign value for the variables before it is used in the expression. Relational expressions c. constants or any other quantities.1. Arithmetic expressions combine arithmetic operators with variables. In C++ language. variables.N 12 . expressions are classified into the following three categories. Expressions in innermost parenthesis is executed Introduction to C++ for class XI by P. Arithmetic expression is evaluated from left to right b. Arithmetic expressions b.

constants or arithmetic expressions and RO is relational operator. Relational expression a>b a>(b+c) 5*b < (a+c) 2 a +b2 > (a+b)2 Execution Result 10>20 20>(10+5) 50<(20+15) 500>900 True True False False Logical expression It is also called as Boolean expression. Y = a/c + b*c . The general format of relational expression is Operand1 <RO> Operand2 Where operand1 and operand2 can be a variable. Evaluate the following relational expression and find the final result of each. Introduction to C++ for class XI by P. The general format of logical expression is Operand1 <LO> Operand2 Where operand1 and operand2 are the relational expressions and LO is a logical operator. b=3 and c=2.( a%b ) + b/c Let us calculate the value of Y using the hierarchy rule Step 1: Y = 5/3 + 3*2 – (5%3) + 3/2 Step 2: Y = 5/3 + 3*2 – 2 + 3/2 Step 3: Y = 1. Note: If an operand is arithmetic expression. Example Consider the following expression for the values of a=5.1 Relational Expression An expression consisting of operands and relational operator is termed as relational expression. Example Let us consider a=20. Function references are executed d. It compares two relational expressions.6 + 6 – 2 +1.c.1 – 2 The result is 7. It helps to compare two quantities and produces the result as either true (non-zero) or false (zero). Finally addition and subtraction is performed.5 Step 4: Y= 9. Evaluate the following relational expression and find the result. b=7 and c=20. first it is evaluated then the result is compared. Example Let a=5. b= 10 and c=5. The operands of logical expression must produce the result as either true or false. since this expression also produces the result as either true or false.N 13 . Multiplication and division is performed e.

instructions.h> Header section #define phi 3. area=phi*r*r. -- Declaration section clrscr().N 14 . Introduction to C++ for class XI by P. cout<<“\nEnter the radius value :”. definitions and includes etc. Declaration section Variables and function declaration Executable statements Statements. cir=2*phi*r. Functions/Subprograms User defined functions Body of the loop In the above structure.14 main() { float radius. getch(). } Let us consider an example program to illustrate the structure of a C++ program Program: To find the area and circumference of a circle. Executable statements section cout<<“\nThe area of the circle is = “<<area.8 Structure of a C++ program The lessons so far you have studied dealt with the basics of C++ language such as constants. A program in C++ language consists of set of blocks or sections. As you studied earlier. variables. } Do you find it difficult to understand? No problem. area. Result False False True decision statements such as IF. program is nothing but set of instructions that solves a problem. 1. Sections Header section Contents Comments. cir. The structure of the body of the program is as follows main() { declaration of variable. The structure of a C++ program is given below. operators and expressions. You will learn all commands and formats in the forthcoming lessons. #include <iostream.h> #include <conio. function section calling etc. cout<<“\nThe circumference of a circle = “<<cir. ----------Instruction/executable part. cin>>radius.Logical expression Execution (a+b)>c && b>c False && True a<b || b<c False || Flase b>a && b>c True && True Note: Both relational and logical expressions are used with do…while and while statements. only the body of the program is compulsory and the other sections are optional. Let us turn our focus towards the programming side.

To execute a file.N 15 . It helps to create the executable version of a program.obj is created. The basic environment of Turbo C++ is called Integrated Development Environment (IDE). It is also called as intermediate file.9 Turbo screen layout Turbo C++ contains a built-in screen editor as part of the compiler. Example: average.CPP. Introduction to C++ for class XI by P.obj Linking It is the process of linking the object code with the code of the library functions that are used by the same program. By typing EXIT. Some of the important commands of Turbo C++ are as follows Key/Command F10 F2 / Alt+FSave F3 / Alt+FL Alt+FN Alt+X F1 F9 Ctrl+F9 Purpose To activate the menu bar To save a file Load a file To create a new file Exit turbo C++ editor To get help facility about Turbo c To compile a source file To compile and run a file Select FileOS Shell to exit from C++ temporarily and goes to the DOS prompt. The steps involved in compilation process is as follows a. just type the name of the file (eg.CPP. The resultant file is called executable file and that has the extension as . It provides various tools like menu bar. it returns to the Turbo editor. c:\>average) in the prompt.EXE Example: average. It is created in turbo editor with an extension . Source code creation Source code is a program consisting of statements of C++ language. status bar.exe Executing Once the EXE file is created it can run in any folder on any machine without the help of turbo C++ compiler also. b. Steps involved while running a program A C++ compiler is system software that converts a C++ program into machine language program. an object file with an extension . scroll bar and editing area at one screen. d.c Compiling A source program is compiled to debug the errors. The starting screen of turbo C++ is loaded by giving the command tc from the turbo C++ files folder (Usually TC folder). if any errors are occurred then that is displayed in the screen. Example: average. After removing all the errors. Source code creation Compiling Linking Executing Every step uses several programs of C++ compiler to complete the step. you can change the name of the file while saving the file.1. By default the turbo editor gives the file name as NONAME. c.

cin>>x>>y. 2. v2 and v3 are variables for which data will be given. cin>> function The cin (Console Input) function is used to accept input from the user to the variables.14 etc.75 or 10 20 or 10 12. It uses extraction operator (>>) to assign data into the variable. b=20. STATEMENTS An instruction with its parameter is called as statements in C++ language. Data can be supplied to the variables in the following ways a. For example.N 16 . The instructions of C++ language are classified into three types such as input. cout << "Enter two numbers : ". The different ways to supply data for the variables of scanf are as follows Scanf statement format cin>>a>>b>>c cin>>a>>c>>d Data input methods 10 20 12. The term input refers to reading data from the standard input devices.y. cin function In the assignment method values are directly assigned to the variables in the program itself.h>. The second cin function method helps to supply data in an interactive method at the run time of the program.75 20 12.75 and d=”NETHRA”. The syntax of cin function is cin>>v1>>v2>>v3. processing refers to set of executable statements for calculation and output refers to producing result on standard output device. Assignment statement b. phi=3. c=12.75 10 12.5. data must be separated by blank space(s) or by separate line. processing and output. r=5. These are placed in the body of the program or function.75 NETHRA Rules for cin statement Variable must be separated by >> sign Data reading is aborted when data does not match to the variables The data which are not read in the current line is assigned to the next cin statement Introduction to C++ for class XI by P. Let a=10. where v1. Some of the functions for each of this category are described here. Entering data While giving data to the variables of cin statements. It is made available to the program by including <iostream.2.1 Input and output statements Input function C++ language provides set of functions for assigning value to the variables. Example int x.

the appropriate block of statements is executed based on the result of the logical test. file or printer. These statements can be used mainly for the following purpose Branching After performing logical test.Output statement Output statements are used to display the result of any calculation in the screen. But in some circumstances it may be required to repeat set of statements depending upon the condition being tested. Example: If…else statement Selection It is a special kind of branching that selects one group of statements from the available set of statements. \b etc. can be used to get appropriate space etc in the output. Example: for statement. while and do…while Introduction to C++ for class XI by P. This is known as branching.N 17 . The general format of printf function is as follows cout<<”Message” or cout<<”Message”<<variable The insertion operator(<<) inserts the data that follows into the standard console device (eg. The most common output statement used in C++ language is cout function.2 Control statements Programs so far we discussed use simple statements and every statement is executed only once. The escape sequence of characters like \n. Example: Switch…case Looping The set of statements is repeated continuously until the given logical condition is satisfied. cout<<”\nResult : a \t b”. This function transforms the result or data from the memory to the standard output device. cout<<”\n My name is “<<name<<” and I am studying in “<<class<<” th standard”.Monitor) here Message can be any text enclosed in double quotes(“ “) and the variable refers to the name of the variable whose value is to be printed. \t. The control statements of C++ language helps to decide the order of the execution based on certain condition. It is used to display the captions (messages) and the result of any numerical calculations. cout<<a<<”\t”<<b. cout function It is a standard output function in C++ language. Some of the control string characters are as follows \n \t \a ---- to print data in a new line to leave one tab space ( normally 5 spaces) to create beep sound Example: cout<<”\n Hello Everybody……”. 2.

Condition is either relational or logical expression and it must be placed in parenthesis and the statement parts contain one or more executable C++ statement.x1. b. otherwise the statement part 2 is executed. if (age>18) printf(“\n Eligible for voting”). Introduction to C++ for class XI by P. } statement part-2. which uses either relational or logical expression.”PASS”)==0) && average>75) printf(“You got distinction”).} d. x2=(-b-sqrt(d))/2*a. if((a>b)&&(a>c)) { big=a.2. The general format of if statement is as follows if (condition) { statement part-1. if(mark1<35 || mark2<35 || mark3<35) printf(“\nThe result is fail”).3 The if-else statement It is a logical conditional statement. printf(“root 1= %f root 2 = %f”. if ((b*b-4*a*c)>0) { x1=(-b+ sqrt(d))/2*a.x2).N 18 . c. } e. Example a. Flowchart is condition ? True Statement part-1 False Statement part-2 Execution First the expression is evaluated to check whether it is true (non-zero) or false (zero) and then the statement part 1 is executed if the value is true. It executes one of the two possible block of statements based on the result of the condition given in the if statement. if ((strcmp(result.

else printf(“\n The given number is odd). Execution After evaluating the condition of if statement. The general format is as follows if (condition) { statement part-1. Introduction to C++ for class XI by P. else printf(“The number is non-zero”). b.0 c. If the result of the expression is false then it executes the statement part-2 and then it goes to statement part-3.N 19 . Flowchart for if-else is condition ? False Statement part-1 True Statement part-2 Statement part-3 Example a. d. if the result is true then the statement part-1 is executed and then control is transferred to statement part-3. if(sex==’M’) { tax = (grosspay-70000)*20/100. } else { statement part-2. } else tax=0. if(b>c) printf(“\nB is the biggest number”). if(n==0) printf(“The number is zero”). else printf(“\nC is the biggest number”).if-else format The extended version of if statement is the if-else format. if(n%2 ==0) printf(“\n The given number is even”). } statement part-3.

The two different nested if statement is as follows Syntax 1 Syntax 2 if (condition-1) { if(condition-2) { statements. } } else { statements. case vn : …….. The general format of switch statement is as follows switch(exp) { case v1 : ……. This selection is based on the expression given in the switch statement.Nested if-else statement An if-else statement within another if statement is called nested if statement. default : ……. It helps to select a particular group of statements among several groups of statements.. The else part is optional in if statement Any number of nesting is allowed If condition contains more than one clause in expression then it must be given in parenthesis. The result of the condition should be either zero(false) or non-zero(true) Statements can be either single or compound. break. } else { statements. } Introduction to C++ for class XI by P. case v2 : ……. You can nest any number of if statements in if part.. break. A single switch statement can be used to replace the nested if statements. 2. } else { statements.. } if (condition-1) { statements. break.4 The switch Statement The switch statement is a multiple branching statement. } else { if(condition-2) { statements. } } Rules of if-else statement The condition of the if statement should be either relational or logical expression. break. In case of more than one statements enclose within the braces ({ }).N 20 . else part or in both.

If no match is found in between v1 to vn then the statements given in default part will be executed. Control statements 3. which can be simple or compound statement. The statements in the body of the loop are an executable statement(s). If it is a character type then the equivalent integer value is considered Break statement between case labels transfers control out of switch statement. it should be enclosed in the curly braces. The case labels (prefixes) v1. If the condition becomes false then it goes to the statement following the while statement. The general format of while statement is while (condition) { ……… statements.1 The While statement It is a looping statement that executes set of statements repeatedly until some condition has been satisfied. otherwise it executes the consecutive case blocks also If none of the case labels are matching with case expression then the default part is executed The case labels must be unique Switch is an alternate statement for nested if statement 3. control is passed to the Rules of switch statement The expression in switch statement must produce the result as integer value. Introduction to C++ for class XI by P. Execution The statements in the body of the loop are executed repeatedly as long as the condition in the while statement is true ( non zero ).N 21 .In switch statement exp stands for expression. Execution First the value of the expression is calculated and then it is compared with the case label starting from v1 to vn. If a match is found then the set of statements of that case label is executed till the break statement. ……… } Condition is a relational or logical expression that should produce the result as either true or false. In case of more than one statement. it can be a variable or arithmetic expression but the result should be a integer value. The break statement is used to exit out of switch statement and the following statement of switch. v2…vn cab be a integer value or character constant. The default statement is optional.

A semicolon must be given at the end of the condition. So it is assured that at least one time the body of the loop is executed.N 22 .2 The do-while statement This is also a looping statement similar to while statement except that the condition is placed at the end of the loop. This is repeated continuously as long as the condition in the while statement is true ( non zero ). 3. If it is true then again the body of the loop is executed. The general format of do-while statement is do { ……… statements.Flowchart is condition ? True False Statement in body of the loop Rules of while statement Condition in while should produce the result as either true or false More than one statement in the body of the loop must be enclosed in braces Break statement can be used to come out of while if necessary. Flowchart Statement in body of the loop True is condition? False Introduction to C++ for class XI by P. Execution First the statements in the body of the loop are executed then the condition is tested. Condition is a relational or logical expression that should produce the result as either true or false. If the condition becomes false then it goes to the statement following the while statement. ……… } while (condition).

i++) printf("\n AEJC. statements …………. MUMBAI "). i<10.3 The for Statement The for loop is the most commonly used statement in many programs for repeated calculations. The following code will print AEJC. Flowchart of for loop control= exp1/Variable is Condition exp1 vs exp2 ? False True Execute the body of the loop control = increment exp1 variable with exp3 Introduction to C++ for class XI by P. If the statement block is only one statement.Difference between while and do-while While Condition is placed at the beginning of the loop Body of the loop is executed only when condition is true It is used more frequently in many programs do-while Condition is placed at the end of the loop At least once the body of the loop is executed without testing condition Used rarely 3. The for statement consists of three important parameters namely initialization (exp1). It increments the counter variable automatically. test condition (exp2) and increment(exp3). MUMBAI times: for (i=0. The general format of for statement is for (exp1.exp3) { …………. the braces are not necessary. exp2 and exp3 are the expressions and these are called loop controlled parameters. } exp1. The for loop works well where the number of iterations of the loop is known before the loop is entered.exp2.N 23 .

Go to step (b) and repeat this procedure as long as the condition is true. Example: i=10. initial value is assigned to index or control variable b. It is called null statement. so loop is never terminated 6. { printf(“%d”. i=0.) for(.) printf(“%d”.).i). } 4.j++) printf(“%d %d”. Example: for(i=0. here the body of the loop contains just semicolon (. First the expression-1 of for loop is evaluated ie.j++) { printf(“%d %d”. The value of index variable is tested with expression-2 c. Inner loop Outer loop } } Introduction to C++ for class XI by P. A for loop can be used to create time delay in the program by executing null statement Example: for(i=0. i=0. ) {printf(“%d”.j=100. i++.j=5.j--) printf(“%d %d”. More than one variable can be initialized in the for loop separated by commas. i++).i++) { for(j=1. . for(. d.i++) for(. if(i>100) break.i).j).i.j<10. A for loop within another for loop is termed as nested loop.i++). A for loop without any section and without break point in the body of the loop is called as indefinite loop. . i<=10.i<5.j). } i++. Expression-2 in the for loop is called test condition and it can be a compound relational or logical expression.i. 3. { printf(“%d”. j<10. 2. We can also omit one or more expressions in the for loop Example 1 Example 2 Example 3 i=0. If the result of above step is true then the body of the loop is executed. Now the index value is incremented with the help of expression-3.Execution a. Example for(i=0. 3.4 Rules of for loop 1. 5.i++. otherwise the control is transferred to the statement that follows for loop.i<=1000. i<=100 && j>10.j).i.N 24 . Example: for(i=10. The body of the loop does not contain break.i++.i). i<=10. for( .i).

} } On executing example 1 coding. it produces the result as 3. Some of the common header files are as follows S. exit. Example for(i=0.i).i<=10.i<5. 1 and 2. else else printf(“%d”. Example for(i=1.7. if((i%7)==0) break.i++) for(i=0. Example 1 Example 2 for(i=0.i++) { printf(“%d”. clrscr. 9. the control is transferred out of the loop. <iostream. 5. break. 12. 15 and 18. Every for statement in the nested loop should have unique index variable.N Standard input and output functions Console input and output functions Mathematical and trigonometric functions String manipulation functions Standard library functions Time related functions cin / cout getch.i). These functions also called as built-in functions or ready-made functions.i<10. Control can be transferred at any point from the for loop to some other part of the program using break statement. pow strlen. But the continue statement is used to skip the remaining part of the loop and continues with the next cycle or iteration of the same loop. gotoxy abs. atof time. The compiler of C++ language evaluates these functions when called in the program and the results are returned.i). 3. The general format of library function is function(arguments) Every function requires arguments that can be a variable.i++) { { if(i%3!=0) if((i%3)==0) continue. clock 25 . sqrt. difftime.i<=20. <string. } 8. 6.i++) This is not valid { printf(“%d %d”.h> 4.h> <conio. constant or expression. On executing break statement.h> <math. Every function is a pre-written program that is stored in the form of header files. Functions 4.1 Library functions The C++ language supports for several types of library functions for variety of purposes.h> <time.h> <stdlib.h> Introduction to C++ for class XI by P. strcat rand.i. } Break vs Continue The continue statement can be used in any loop statement like break. 6.i).i++) { for(i=1. printf(“%d”. The result type of a function varies from function to function. 4. strcpy. 2.No Header file Used for Example functions 1. The second example produces the result as 0.i<=20.

rand function It returns a random number as the result. abs(456). sqrt function This function is used to find the square root of the given value. where x is a floating point number.10. The pow(x. Example a. 1.0. ceil(-5. abs function It produces the absolute value of the given number. The result of abs(0) is 0 Note: The function fabs() is used to find the absolute value of the floating point number.0 b.2) gives the result as 49.y) where the arguments are float numbers. The argument of the sqrt function must be a non-negative real quantity. A random number is a number. fmod(99. sqrt(81.0) gives the result as 27. the result is 232 b. the result is 456 c. The general format of this command is ceil(x). It is used in several places where the samples are to be tested with large number of data.6) gives the result as –5 6. Example a. ceil(7. The general format of this function is fmod(x.y) is equivalent to xy Example a. which cannot be predicted. 3. Introduction to C++ for class XI by P. where x is a integer number. Example a.0) produces the result as 9 b. fmod function This function is used to find the remainder of a number divided by another number.0) gives the result as 9. Suppose that if the argument is a positive number then it remains same. where x and y are of floating point numbers. fmod(100.Some of the most useful library functions are explained. abs(-232). Example a.10.0) gives the result as 0.0 4. Suppose that if the value of x is negative number then the C++ compiler produces the error message. x=5. The general format of the abs function is abs(x).N 26 . The general format of the function is rand(). the smallest integer greater than or equal to the given number.0 b. sqrt(b*b-4*a*c) 2.0. The general format of this command is pow(x.9) gives the result as 8 b. It divides the value of x by y and gives the remainder as result. If the number is negative then it gives the equivalent positive number. that is. pow(3.3. The general format is sqrt(x).y). ceil function It returns the ceiling value. pow(x+2.0 5. pow function The function pow stands for power. the important point to note here is that it does not take any parameter.

). } data_type is the data type of the result to be returned. srand(3455) rand() gives the result as 16837 7. Introduction to C++ for class XI by P. It helps to implement the modular programming concept in the programming. cos(x) tan(x) exp(x) Argument type Used for Real value in the form of radians --do---do-Real value To find the sine value of x Example To find the cosine value of y To find the tangent value of x Calculates exponent value of x User Defined Function / Functions in C++ A function in C++ allows the user to define own functions. it depends upon the machine and compiler. Parameters are the variables that receive data from the calling place. hence only data type can also be specified. rand() gives the value as 346. the name of the variable is optional. Function name sin(x) 2.. srand(645) rand() gives the result as 26759 b. 4. statements …………. void indicates it returns NULL. name is the name of the function by which it will be possible to call the function. parameter2. 3. . A function is defined in some part of the program with block of statements and it can be called from any part of the program. statements is the body of the function and it must be enclosed by {} Function Prototype It is the declaration of the function at the beginning of the program with its data-type. Trigonometric functions Some of the trigonometric functions and usage are given below S.No 1. The body of the function need not be given. It helps to instruct the compiler that the actual function definition may be defined in some other point of the program. Example a.Example a. name of the function and parameters followed by semicolon. Note: The function srand(x) is used to initialize the random number with a seed value.The general format of the function is as follows Data_type name ( parameter1.. The general format of the function is Data_type name ( parameter1. .) { …………. so that for every seed it generates a different random number.N 27 ... All parameters must be separated by commas and declared by the corresponding data type. In the place of parameter. parameter2.

The data type of the value to be returned is decided based on the data type given in the declaration of the function. ncr=fact(n)/(fact(r)*fact(n-r)). Same function can be called any number of times in the program as follows Variable = name(arguments) or name(arguments). For Each call) A function with void data type cannot return any value. ------. cout <<"Enter the number whose factorial has to be calculated" << endl.> int factorial(int k). -----. Return statement It returns the result to the calling place of the program.Function prototype void main () { int n. Eg. fact=factorial(n).Function call A function can be called from any part of the program just by the name of the function with its proper arguments. } int factorial(int k) ------. A program can have any number of return statements but it can return only one value at a time (ie. Scope of the variables The visibility of the variables in the function or program is termed as scope of the variable. --. constants or simple expressions.fact.return statement with a value else { for(i=1. It refers to the availability of the variables in different parts of the program.i<=k. fact(n).function declaration { int i=0. return(0). cin >> n1. } return(f). Example: #include<iostream.i++) { f=f*i.N 28 .call to function factorial cout << "The factorial of " << n << " is : " << fact << endl. if(n<=1) { return(1).f=1. Name refers to the name of the function and arguments refer to the name of the variable.return statement with a value } } Introduction to C++ for class XI by P. } --.

- Ch05 Loops[1]Uploaded bybelenj1
- CS504 Quiz Solved by CS-BoyUploaded byhassan_m2222
- Edx C# CourseUploaded byPavan Sai
- INTRODUCTION TO MATLAB CHAPTER nO.04Uploaded byAmjad Shah
- Python Tutorial Feb 152012Uploaded byfareenarn
- 4) Repetition Control Structure (Part 1)Uploaded byBear ZOobear
- PLSQL_4_4Uploaded byssmile
- CONTROL STATEMENTUploaded byaslinayaya
- Programming Logic and Design sixth editionUploaded byorxanrzayev
- Return to BasicsUploaded byKangyerka András
- VB Control StructuresUploaded byJobin Sebastian
- DUploaded byParethe Vn
- Tutorial #10 – VBScript Basics Tutorial 2Uploaded bymanu2020
- MATLAB (1)Uploaded byalexisthe
- IWD 1124 - C++ Programming 2-2008-2009 - Mr SuUploaded byapi-3701691
- NetLinx.LanguageReferenceGuideUploaded byVenkatesh Babu
- Vi Srm UniversityUploaded bysuresh3441
- PLSQL_s05_l03Uploaded byGhilic
- Visual Basic Language CompanionUploaded byBob Zilla
- JQuery FundamentalsUploaded byIsaack Hlatshwayo
- Python1Uploaded byAvinash Rallapalli
- Exceptions.pptxUploaded byDanuzia Elena Anusca