Sie sind auf Seite 1von 38

C++ PROGRAMMING

INTRODUCTION The C++ programming language was developed at AT & T Bell Laboratories in the early 1980s by Bjarne Stroustrup. He found some limitations in C and decided to extend the language by adding features from his favourite language, Simula 67. Simula 67 was one of the earliest object oriented languages. Thus he added a concept called class with C and called it C with Classes. But the name C++ was coined by Rick Mascitti where ++ is the increment operator in C. C++ CHARACTER SET Character set is a set of valid characters that a language can recognize. The characters in C++ are grouped into the following categories: 1) LETTERS: All uppercase (A-Z) and lowercase (a-z) alphabets are permissible characters. 2) DIGITS: All numerals (0-9) and all its unique combinations are valid in C++. 3) SPECIAL SYMBOLS: Space + - * / ^ \ ( ) { } [ ] = ! < > , # $ % ; : & @ ? _(underscore) 4) WHITE SPACES: Blank space, Horizontal tab, Carriage return ( ), new line etc. 5) OTHER CHARACTERS: C++ can process any of the 256 ASCII characters. TOKENS Tokens are the smallest individual units in a program. It is also known as lexical units or lexical elements. C++ has the following tokens: 1) KEYWORDS: Keywords are certain reserved words that convey a special meaning to the language compiler. These are reserved for special purposes and must not be used as identifiers. eg: int, break, while, if, goto etc. 2) IDENTIFIERS: Identifiers are fundamental building blocks of a program. These are the names given to different parts of the program like variables, objects, classes, functions, arrays etc. An identifier is an arbitrarily long sequence of letters and digits with a letter as the first character. The underscore ( _ ) counts as a letter. C++ is case sensitive as it treats Upper and lower case characters differently. eg: a, sum, emp_id, num2 etc. 3) LITERALS: Literals (constants) are data items that never change their value during the execution of a program. C++ allows several kinds of literals: CONSTANTS NUMERIC CONSTANTS INTEGER CONSTANTS FLOATING POINT CONSTANTS CHARACTER CONSTANTS SINGLE CHARACTER CONSTANTS STRING CONSTANTS

a) INTEGER CONSTANTS : Integer constants are whole numbers without any fractional part. An integer constant must have at least one digit and must not contain any decimal point. It may contain either + or sign. A number with no sign is assumed to be positive. Commas cannot appear in an integer constant. C++ allows decimal, octal and hexadecimal integer constants. i) Decimal Integer Constants: An integer constant consisting of a sequence of digits 1

(0-9) is taken to eg: 1234, 5,-17 etc.

be

decimal

integer

constant

unless

it

begins

with

0.

ii) Octal Integer Constants: A sequence of digits starting with 0 is taken to be an octal integer constant. For instance, decimal integer 8 will be written as 010 as octal integer and decimal integer 12 will be written as 014 as octal integer. iii) Hexadecimal Integer Constants: A sequence of digits preceded by 0x or 0X is taken to be a hexadecimal integer. For instance, decimal 12 will be written as 0XC as hexadecimal integer. b) FLOATING POINT CONSTANTS: Floating point constants are numbers having fractional part. Floating constants are also called real constants. A real constant in fractional form must have at least one digit before and after the decimal point. It may also have either + or sign preceding it. A real constant with no sign is assumed to be positive. eg: 2.0, -13.5, -0.00625 etc. c) SINGLE CHARACTER CONSTANTS : A character constant is one character enclosed in single quotes. The value of a single character constant is the numerical value (ASCII) of the character in the machines character set. For instance, the value of c will be 99 and the value of A will be 65. C++ allows us to have certain nongraphic characters in character constants. They are characters that cannot be typed directly from keyboard (backspace, tabs, carriage return etc). These nongraphic characters can be represented by using escape sequences. An escape sequence is represented by a backslash ( \ ) followed by one or more characters. An escape sequence represents a single character and hence consumes 1 Byte in ASCII representation. eg: \n (new line), \t(horizontal tab), \0 (Null) etc. d) STRING CONSTANTS : A string constant is a sequence of characters enclosed in double quotes. It is treated as a character array. The benefit of an array is that each character of the string can be dealt with separately. The characters in this array may be letters of the alphabet, numbers, special symbols or even blank space. Each string literal is by default added with a special character \0 which makes the end of a string. \0 is a single character. Thus the size of a string is the number of characters plus one for the termination. eg: ARUN, Kevin Mathew, KL-03, 145 etc. (ARUN will actually be represented as ARUN\0 in the memory i.e along with the terminator character). 4) OPERATORS: Operators are tokens that trigger some computation when applied to variables and other objects in an expression. It is symbol that tells the computer to perform certain operations. C++ operators can be classified as follows: a)
ARITHMETIC OPERATORS : Arithmetic operators are used to perform arithmetic

operations like addition (+), subtraction (-), multiplication (*), division (/) and modulation (%). But note that the operands of a modulus operation must be integers. All the above operators require two operands and are called binary operators. eg: a+b, a-b, a*b, a/b, a% b etc. (A statement which contains an arithmetic operator is called arithmetic expression)

b) RELATIONAL OPERATORS: Relational operators check the relation between two operands. They are used to compare two quantities and depending on their relation, take certain decisions. C++ provides six relational operators: Operator Meaning > greater than < lesser than >= greater than or equal to <= less than or equal to == equal to != not equal to A statement contains at least one relational operator is called a relational expression. A relational expression contains either a true or a false value. (a>b), (a!=b) etc. are some examples of relational expressions. c) LOGICAL OPERATORS: It combines multiple relational expressions together and thus forms a single logical expression. An expression which contains two or more relational expression is called a logical expression. The result of a logical expression is always true (1) or false (0). C++ provides 3 logical operators. They are && (AND), || (OR) and ! (NOT). The logical operators && and || are used when we want to test more than one conditions and make decisions. A logical AND expression has a value 1 (TRUE) when both the relational expressions are TRUE. While a logical OR expression has a value 1 when either one of the relational expressions is TRUE. But the logical NOT operator negates the value of an expression, i.e., if the given expression is TRUE, then NOT operator converts it into FALSE and vice versa. eg: !(a>b) means a<b or a=b d) CONDITIONAL OPERATOR: It is also called ternary operator as it requires three expressions. The general form of a conditional operator is: (expression 1)? expression 2: expression 3; Expression 1 is evaluated first and if it is true, the value of whole expression is the value of expression 2 and if it is false, then the value of the whole expression is the value of expression 3. e) sizeof() OPERATOR: This operator returns the memory size of a variable in bytes. It has the following two forms: sizeof(variable name) or sizeof(data type) f)
SCOPE RESOLUTION OPERATOR:

:: (class member operator) ++, - -

g) INCREMENT / DECREMENT OPERATOR: h) ASSIGNMENT OPERATORS :

+ =, - =, * =, / =, % =

5) PUNCTUATORS: They are also known as separators and are used to separate out different sections of the program. The following characters are used as punctuators in C++: [ ] { } ( ) , ; : # * = Brackets [ ] Parentheses ( ) Opening and closing brackets indicate single and multidimensional array subscripts. eg: int a[10]; char name[20]; Opening and closing parentheses indicate function calls and function parameters. Parentheses also group expressions and isolate conditional expressions. eg: clrscr(), for(int i=1; i<=10; i++) 3

Curly Braces { } Comma , Semicolon ; Colon : Pound sign # Asterisk * Equal to sign = Ellipsis

Opening and closing braces indicate the start and end of a compound statement or a function. It is used as a separator in a function argument list. eg: pow(5,2) It is used as a statement terminator. Every executable statement is terminated by a semicolon. It indicates a labeled statement. The pound sign (#) is used for preprocessor directives. It is used for pointer declaration. It is also used as the multiplication operator. It is used for variable initialization and as assignment operator in expressions. Ellipsis () are used in the formal argument lists of function prototypes to indicate a variable number of arguments (which means the argument list may contain any number of arguments and of any type)

DATA TYPES IN C++ Data can be of many types like character, integer, real, string etc. Anything enclosed in single quotes represents character data in C++. Numbers without fractions represent integer data. Numbers with fractions represent real data and anything enclosed in double quotes represents a string. C++ data types are of two types: a) Fundamental types b) Derived types

There are five atomic (fundamental) data types in C++: char, int, float, double and void that represent character, integer, floating point, double floating point and valueless data respectively. Derived types are constructed from the fundamental types. Arrays, functions, pointers, classes, structures, unions, enumerations etc. are some examples of derived data types in C+ +.
FUNDAMENTAL DATA TYPES

a) int Integers are whole numbers without any decimal part. Integers are represented in C+ + by int data type. An identifier declared as int cannot have fractional part. The size of an integer variable is 2 Bytes and the value ranges from -32768 to 32767. b) char Characters can store any member of the C++ character set. An identifier declared as char becomes a character variable. The size of a char variable is 1 Byte. c) float A number having a fractional part is a floating point number. An identifier declared as float becomes a floating point variable and can hold floating point numbers. Floating point numbers have two advantages over integers. First, they can represent values between the integers. Second, they can represent a much greater range of values. But floating point operations are usually slower than integer operations. The size of a float variable is 4 Bytes and the value ranges from 3.4x10-38 to 3.4x1038. d) double The data type double is also used for handling floating point numbers. But it is treated as a distinct type because it occupies twice as much memory as type float and stores floating point numbers with much larger range and precision. It stands for double precision floating point. It is used when type float is insufficient to store a data value and thus it is larger and slower than type float. The size of a double variable is 8 Bytes and the value ranges from 1.7x10-308 to 1.7x10308. e) void The void type specifies an empty set of values. It is used as the return type for functions that do not return a value. No object (variable) of type void may be declared. 4

VARIABLES Variables represent named storage locations, whose values can be manipulated during program execution. A variable name may consist of letters, digits and underscore character subject to the following conditions. a) A variable name must begin with a letter. b) A variable name should not be more than 8 characters. c) Uppercase letters are entirely different from lowercase letters. d) A variable name should not be a keyword. e) White space is not allowed. There are two values associated with a variable: 1) Its data value, stored at some location in memory. This is sometimes referred to as a variables rvalue. 2) Its location value; that is, the address in memory at which its data value is stored. This is sometimes referred to as a variables lvalue. a Data value 10 c 25 variables name Here rvalue of a is 10 and lvalue is 100 memory address

100 101 102 103 104


DECLARATION OF VARIABLES

After choosing suitable variable names, we must declare the variables using any of the fundamental data types of C++. 1) It tells the compiler what the variable name is 2) It specifies what type of data the variable will hold. Note that every variable must be declared before they are used in the program. The syntax is: Data type variable name; eg: int a; char ch; float amount; double income; FEATURES OF A C++ PROGRAM # include<iostream.h> #include<conio.h> void main() { clrscr(); cout<<WELCOME TO C++; getch(); } The first section of the program instructs the compiler to include certain header files like iostream.h, conio.h etc., in which iostream.h defines basic i/o facilities. The next section void main() defines a function called main. It is known as the driver function. The return type void suggests that the function main() doesnt return a value to the operating system (operating system invokes the main() function). Empty parenthesis suggests that the main() function doesnt receive any value from the operating system. Curly braces { and } are used to express the body of the main() function. Every C++ program must have the following features: 1) Every C++ program must have a function named main(). 2) Program execution begins at the first statement of main() and continues by sequentially executing the statements within main(). 3) Every executable statement in C++ must be terminated by a semicolon. 4) Every variable in the program must be declared before they are used. 5

5) Compiler directives such as include and define are special instructions to the compiler and they do not end with a semicolon. 6) When braces are used to group statements, make sure that the opening brace has a corresponding closing brace. USING I/O OPERATORS Input coming from the users terminal (keyboard), referred to as standard input is tied to the predefined iostream cin and output directed to the users terminal, referred to as standard output, is tied to the predefined iostream cout.
OUTPUT OPERATOR <<

The output operator (<<) also called stream insertion operator is used to direct a value to standard output. When we use the escape sequence \n (the newline character), it causes the successive output to be directed to the next line. We can also use the keyword endl as an alternative to \n. eg: int a=10, b=20, c=30; cout<<a<<\n<<b<<\n<<c; or cout<<a<<endl<<b<<endl<<c;
INPUT OPERATOR >>

The input operator (>>), also known as stream extraction operator is used to read a value from standard input. eg: int a,b,c; cin>>a>>b>>c;
CASCADING OF I/O OPERATORS

The multiple use of input or output operators (>> or <<) in one statement is called cascading of I/O operators. The statement using multiple output operators is said to be cascading output operator and the statement involving multiple use of input operators is said to be cascading input operator. eg: cout<<a<<b<<c; // cascading output operator cin>>a>>b>>c; // cascading input operator
FORMATTING OUTPUT

Formatting output is important in the development of output screens, which can be easily read and understood. C++ offers several I/O manipulators. Two of these I/O manipulators are setw() and setprecision(). In order to use these manipulators, we must include header file iomanip.h.
setw() manipulator

The setw() manipulator sets the width of the field assigned for the output. It takes the size of the field (in number of characters) as a parameter. eg: cout<<setw(10)<<HELLO; generates the following output on the screen(each underscore represents a blank space) _ _ _ _ _ HELLO The setw() manipulator does not stick from one cout statement to the next. For example, if we want to right justify three numbers within an 8-space field, we will need to repeat setw() for each value. Eg: cout<<setw(8)<<22<<endl; cout<<setw(8)<<4444<<endl; cout<<setw(8)<<666666<<endl; The output will be: 22 4444 6

666666
setprecision() manipulator

The setprecision() manipulator is used to set the number of decimal places to be displayed. eg: cout<<setprecision(2)<<3.1415; will display 3.14 on the screen. COMMENTS IN A C++ PROGRAM Comments are pieces of code that the compiler discards or ignores or simply does not execute. The purpose of comments is only to allow the programmer to insert some notes or descriptions to enhance readability or understandability of the program. There are two ways to insert comments in C++ programs: i) Single line comments with //. The comments that begin with // are single line comments. The compiler simply ignores everything following // in that same line. ii) Multiline or block comments with /* and */. The block comments, mark the beginning of comment with /* and end with */. That means, everything that falls between /* and */ is considered a comment even though it is spread across many lines. C++ SHORTHANDS C++ offers special shorthands that simplify the coding of a certain type of assignment statement. For example a=a+10; can be written as a+=10;. The operators +=, -=, *=, /= and %= are some shorthand operators in C++ and are called arithmetic assignment operators. They combine an arithmetic operator and an assignment operator. TYPE CONVERSION When constants and variables of different types are mixed in an expression, they are converted to the same type. The process of converting one predefined type into another is called type conversion. C++ facilitates two types of type conversion: i) Implicit type conversion: An implicit type conversion is performed by the compiler without programmers intervention. An implicit conversion is applied generally whenever different data types are intermixed in an expression. The C++ compiler converts all operands upto the type of the largest operand, which is called type promotion. For example if an arithmetic expression contains one integer and one float as its operands, then compiler converts integer operand to the type float. eg: int i; float fl; double db; long double ld; result = (ch / i) int + (fl * db) double (fl + i) float + (ld fl); long double

double

double long double

ii)

Explicit type conversion: An explicit type conversion is user-defined that forces an expression to be of specific type. The explicit conversion of an operand to a specific type is called type casting. syntax: (data type) expression; For example, to make sure that the expression (x+y/2) evaluates to type float, we can write: cout<<(float)(x+y/2);

FLOW OF CONTROL Generally a program executes its statements from beginning to end. But not many programs execute all their statements in strict order from beginning to end. Most programs decide what to do in response to changing circumstances. These programs not only store data but they also manipulate data in terms of consolidation, rearranging, modifying etc. To perform these tasks, C++ provides some tools (statements). Such statements are called program control statements. STATEMENTS Statements are the instructions given to the computer to perform any kind of action, be it data movements, be it making decisions or be it repeating actions. Statements form the smallest executable unit within a program. Statements are terminated with a semicolon. COMPOUND STATEMENT (BLOCK) A compound statement in C++ is a sequence of statements enclosed by a pair of curly braces. For instance, { statement 1; statement 2; . . . statement n; } represents a compound statement. A compound statement is also known as a block. A compound statement or a block is treated as a single unit and may appear anywhere in the program. STATEMENT FLOW CONTROL In a program, statements may be executed sequentially, selectively or iteratively. 1) SEQUENCE: The sequence construct means the statements are being executed sequentially. This represents the default flow of statement. Statement 1 Statement 2 Statement 3

Every C++ program begins with the first statement of main(). Each statement in turn is executed. When the final statement of main() is executed, the program is done. This construct specifies the normal flow of control in a program and is the simplest one. In C++, the main() is also called driver function as it drives the program. 2) SELECTION: The selection construct means the execution of statement(s) depending upon a condition-test. If a condition evaluates to true, a course of action (a set of statements) associated with true part is executed otherwise another course of action is followed. This construct is also called decision construct because it helps in making decision about which set of statements is to be executed.

true block true condition statement 1 statement 2

false statement 1 false block statement 2

3) ITERATION: The iteration construct means repetition of a set of statements depending upon a condition test. Till the time a condition is true, a set of statements are repeated again and again. As soon as the condition becomes false, the repetition stops. The iteration construct is also called looping construct.

false condition true statement 1 loop body statement 2

The set of statements that are repeated again and again is called the body of the loop. The condition on which the execution or exit of the loop depends is called the exit condition or test condition. Selection and iteration constructs depend upon a conditional expression that determines what course of action is to be taken. A conditional expression evaluates to either true(1) or false(0). SELECTION STATEMENTS The selection statements allow to choose the set of instructions for execution depending upon an expressions truth value. C++ provides two types of selection statements: if and switch. In addition, in certain circumstances, conditional operator can be used as an alternative to if statement. 1) simple if An if statement tests a particular condition; if the condition evaluates to true, a course of action is followed. Otherwise the course of action is ignored. The syntax is: if(test expression) { statement; } where a statement may consist of a single statement or a compound statement. The expression must be enclosed in parentheses.

test exp

false

true body of if eg: if(ch== ) spaces++; it checks whether the character variable ch stores a space or not; if it does, the number of spaces are incremented by 1. 2) if else An if - else statement tests a particular condition; if the condition evaluates to true, a course of action associated with true part is executed, otherwise a course of action associated with false part is executed. The syntax is: if(test expression) { true block statement(s); } else { false block statement(s); } 10

test exp

false

body of else

true body of if eg: int a,b; cin>>a>>b; if(a>b) cout<<a is largest; else cout<<b is largest; 3) if else if ladder A common programming construct in C++ is the if else if ladder, which is used when multiple decisions are involved. The syntax is: if(test expression 1) statement block1; else if(test expression 2) statement block 2; else . . .If(test expression n) statement block n; else default statement(s); The expressions are evaluated from top to downwards. As soon as an expression evaluates to true, the statement(s) associated with it is executed and the rest of the ladder is bypassed and the control is transferred to the next statement immediately following the ladder. When all the n conditions become false, then the final else statement containing the default statement is executed. false test exp 1 statement block1 false test exp 2 true true

default statement

statement block2

11

eg: char ch; ch=getchar(); if(ch>=65&&ch<=90) cout<<Uppercase; else if(ch>=97&&ch<=122) cout<<Lowercase; else if(ch>=48&&ch<=57) cout<<Digit; else cout<<Special character; 4) Nested if: A nested if is an if that has another if in its ifs body or in its elses body. The general form is: if(test expression 1) { if(test expression 2) { . . . If(test expression n) true statement n; } else . . statement 2; else statement 1; else default statement; test exp 2 false

true test exp 1

false

default statement

statement block2

statement block1

If test expression 1 is false, then default statement will be executed, otherwise it continues to perform the second test. If condition 2 is true, then statement 2 will be executed, otherwise if it is false, then statement 1 will be executed. eg: int unit; float charge; if(unit>200) { if(unit>400) { if(unit>600) { charge=380+(unit-600); } else charge=220+(unit-400)*.80; 12

} else charge=100+(unit-200)*.60; } else charge=unit*.50; Conditional operator An alternative to if else C++ has an operator that can be used as an alternative to if statement. The general form of a conditional operator is: (expression 1)?expression 2: expression 3; expression 1 is evaluated, if it is true, expression 2 gets executed (i.e., its value becomes the value of the entire expression) otherwise expression 3 gets executed (i.e., its value now becomes the value of the entire expression). This operator is also called ternary operator. eg: int a,b; cin>>a>>b; (a>b)?cout<<a<< is larger:cout<<b<< is larger; OR int max=(a>b)?a:b; cout<<max<< is larger; COMPARING if and CONDITIONAL OPERATOR 1) Compared to if-else statement, conditional operator offers more concise, clean and compact code, but it is less obvious as compared to if. 2) Another difference is that the conditional operator cannot support compound statements in its true part or false part, whereas if is more flexible. 3) When conditional operator is used in its nested form, it becomes complex and difficult to understand. SWITCH STATEMENT C++ provides a multiple branch selection statement known as switch. This selection statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed. The syntax is: switch(expression / variable) { case constant1: 13

statement block 1; break; case constant2: statement block 2; break; . . . case constant n: statement block n; break; default: default statement(s); break; } When the switch is executed, the value of the expression is compared with the values of the case constants. If a case is found that matches to the value of the expression, then the block of statements associated with that case are executed. The break statement at the end of each block indicates the end of a particular case and causes an exit from the switch statement. The default case is optional. When present, it will be executed if the value of the expression doesnt match with any of the case values. A switch case can have up to 257 case statements. While using switch, put the most common cases first. unnecessary comparisons and thereby wastage of CPU time may be avoided. eg: int day; cin>>day; switch(day) { case 1: cout<<Sunday; break; case 2: cout<<Monday; . . 14 This way

case 7: cout<<Saturday; break; default: cout<<Invalid day; } THE NESTED SWITCH If a switch case statement comes within the body of another switch case, then it is known as nested switch. The switch which comes first is known as outer switch and the other is known as inner switch. IMPORTANT THINGS ABOUT SWITCH CASE 1. A switch statement can only work for equality comparisons. 2. No two case labels in the same switch can have identical values. But, in case of nested switch, the case constants of the inner and outer switch can contain common values. 3. If character constants are used in the switch statement, they are automatically converted to their integers (i.e., their equivalent ASCII codes). COMPARING SWITCH & IF ELSE The switch and if else are selection statements and they both let us select an alternative out of given many alternatives by testing an expression. However there are some differences in their operations. 1. Switch can only test for equality whereas if can evaluate a relational or logical expression i.e., multiple conditions. 2. The switch statement selects its branches by testing the value of same variable (against a set of constants) whereas the if-else construction lets us use a series of expressions that may involve unrelated variables and complex expressions. 3. The if else is more versatile of the two statements. For instance, if else can handle ranges whereas switch cannot. Each switch case label must be a single value. 4. The if else statement can handle floating point tests also apart from handling integer and character tests whereas a switch cannot handle floating point tests. The case labels of switch must be an integer or a character.

15

5. The switch case label value must be a constant. So, if two or more variables are to be compared, use if else. ITERATION STATEMENTS The iteration statements allow a set of instructions to be performed repeatedly until a certain condition is fulfilled. They are also called loops or looping statements. C++ provides three kinds of loops- while loop, for loop and do-while loop; where while and for are entrycontrolled loops and do-while is the exit-controlled loop. ELEMENTS THAT CONTROL A LOOP Every loop has its elements that control and governs its execution. Generally a loop has four elements that have different purposes. They are: 1) Initialization Expression: Every loop must have a loop control variable. Before entering in a loop, its control variable(s) must be initialized. The initialization of control variable takes place under initialization expression. It gives the very first value of the loop control variable. The initialization expression is executed only once in a program. 2) Test Expression: The test expression is an expression whose truth value decides whether the body of the loop will be executed or not. If the test expression evaluates to true, the loop body gets executed, otherwise the loop is terminated. In an entry-controlled loop, the test expression is evaluated before entering into a loop whereas in an exit-controlled loop, the test expression is evaluated before exiting from the loop. 3) Update Expression: the update expression(s) change the value(s) of loop control variable(s). it is executed at the end of each loop after the loop body is executed. 4) The body of the loop: The statements that are executed repeatedly form the body of the loop. In an entry-controlled loop, first the test expression is evaluated and if it is true, the body of the loop is executed; otherwise the loop is terminated. In an exit-controlled loop, the body of the loop is executed first and then the test expression is evaluated. So in the case of exit-controlled loop, even if the given test expression is false, we can execute the loop body at least once. a) while loop syntax: initialization of control variable; while(test expression) { body of the loop; update expression;

16

initialization exp } false test exp exit from the loop

true body of the loop

update exp

The body of the while loop may contain a single statement, a compound statement or an empty statement. The loop iterates while the test expression evaluates to true. When the expression becomes false, the program control passes to the next statement after the loop body. In a while loop, control variable should be initialized before the loop begins and it should be updated inside the body of the while. VARIATIONS IN A WHILE LOOP A while loop can also have several variations. It can be empty loop or an infinite loop. An empty loop does not contain any statement in its body. For example: int a=0; while(++a<=10);when the value of a becomes 11 it stops the iteration. A while loop can be infinite if we forget to write the update expression inside its body. For example: int j=1; while(j<=10) cout<<j; j++; Here loop body contains a single statement and the increment statement j++ is not included in the loops body. So the value of j remains the same and loop can never terminate. 17

b) for loop: The for loop is the easiest to understand of the C++ loops. All its loop control elements are gathered in one place, while in other loops, they are scattered about the program. The general form of the for loop statement is: for(initialization expression(s); test expression; update expression(s)) { body of the loop; }

eg: for(int i=1; i<=10; i++) { cout<<I; } WORKING OF FOR LOOP 1. Firstly, initialization expression is executed, which gives the first value to the loop control variable. 2. Then, the test expression is evaluated. 3. Since, the test expression is true, the body of the loop is executed. 4. After executing the loop body, the update expression is executed which changes the value of loop control variable. 5. After the update expression is executed, the test expression is again evaluated. If it is true the sequence is repeated otherwise the loop terminates. The for Loop Variations 1. Multiple initialization and update expressions- A for loop may contain multiple initialization and/or multiple update expressions. These multiple expressions must be separated by commas. These multiple expressions are executed in sequence. 2. Optional expressions- In a for loop, initialization expression, test expression and update expressions are optional i.e., we can skip any or all of these expressions. Possibility 1 2 3 4 Initialization Test exp 0 0 1 0 0 1 0 0 18 Update exp 0 0 0 1

5 1 1 0 6 0 1 1 7 1 0 1 8 1 1 1 3. Infinite loop: An infinite for loop can be created by omitting the test expression or by giving the invalid update expression. 4. Empty loop: If the for loop does not contain any statement in its loop body, it is said to be an empty loop. In such cases, a C++ loop contains an empty statement i.e,. a null statement (;). eg: for(int i=1; i<=10; i++); Note that if we put a semicolon after fors parenthesis, it repeats only for counting the control variable. And if put a block of statements after such a loop, it is not part of a for loop. For example, for( int i=1;i<=10;i++); { cout<<i; cout<<\n; } 5. Declaration of variables in the loop C++ allows to declare variables inside the body of a for loop. But note that such variables can be accessed only in the block where it has been declared. The program area inside which a variable can be accessed, is called variables scope. c) The do-while Loop The do-while loop is an exit-controlled loop i.e., it evaluates its test expression at the bottom of the loop after executing its loop body statements. loop body at least once. syntax: do { body of the loop } while(test expression); 19 So the advantage of do while loop is that even if the given test expression is false, it can execute the This is not body of for loop for loop is empty loop.

Nested Loop A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop, the inner loop must terminate before the outer loop. While working with nested loops, the value of outer loop variable will change only after the inner loop is completely finished. JUMP STATEMENTS The jump statements unconditionally transfer program control within a function. C++ has four statements that perform an unconditional branch: return, goto, break and continue. We can use return and goto anywhere in the program whereas break and continue are used inside smallest enclosing like loops etc. In addition to the above four, C++ provides a standard library function exit( ) that helps us to break out of a program. 1) The goto statement: A goto statement can transfer the program control anywhere in the program. The target destination of a goto statement is marked by a label. The target label and goto must appear in the same function. The syntax is: goto label; . . . label: where label is a user supplied identifier and can appear either before or after goto. For example: int a=0; start: cout<<++a; if(a<50) goto start; A label may not immediately precede a closing brace. For example: { . . .goto last; . . . 20

last: } // wrong. A label is preceding the closing brace

To handle this constraint, a null statement (;) may be used that follows the label as shown below. { . . .goto last; . . . last: ; // Now it is correct. } Note that if a label appears just before closing brace, a null statement must follow the label. Also, a goto statement may not jump forward over a variable declaration. instance: void main( ) { . . . goto last; char ch=a; // wrong jumping over a variable definition. . . . last: . } The forward jumping over a variable definition is possible only if the variable definition is occurring in a block and the entire block is jumped over, such as shown below: void main( ) { 21 For

. . .goto last; . . { char ch=a; . . . } last: } 2) The break statement The break statement enables a program to skip over part of the code. A break statement terminates the smallest enclosing like while, do-while, for and switch statements. Execution resumes at the statement immediately following the body of the terminated statement. If a break statement appears in a nested-loop structure, then it causes an exit from only the very loop it appears in. The following figure explains the working of a break statement. while(test expression) { statement 1; if(val>2000) break; . . . statement 2; } statement3; for(init; test exp; update exp) { statement1; if(val>2000) break; statement 2; } Statement 3; do { statement 1; if(val>2000) break; statement 2; } while(test expression); // correct now

A break statement skips the rest of the loop and jumps over to the statement following the loop. 3) The continue statement

22

The continue is another jump statement like the break statement as both the statements skip over a part of the code. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.

while(test expression) { statement 1; if(val>2000) continue; . . statement 2; } statement3;

for(init; test exp; update exp) { statement1; if(val>2000) continue; statement 2; } Statement 3;

do { statement 1; if(val>2000) continue; statement 2; } while(test expression);

In a for loop, continue causes the next iteration by updating the variable and then causing the test expressions evaluation. passes to the conditional tests. 4) The exit( ) function We can break out of a program using the exit( ) function. This function causes the program to terminate as soon as it is encountered, no matter where it appears in the program. The exit function does not have any return value. Its argument, which is 0 is returned to the operating system. Generally, the value 0 signifies a successful termination and any other number indicates some error. The exit( ) function has been defined under a header file process.h which must be included in a program that uses exit( ) function. ARRAYS USER-DEFINED / STRUCTURED DATA TYPE An array is a collection of variables of the same type that are referenced by a common name. In C++, all arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Arrays can have data items of simple types like int or float, or even of user-defined types like structures and objects. Arrays are very much useful in a case where quite many elements of the same types need to be stored and processed. The element numbers in [ ] are called subscripts or indices. The subscript or index of an element designates its position in the arrays ordering. But in a while and do-while loops, the program control

23

TYPES OF ARRAYS Arrays are of different types: (i) one-dimensional arrays, comprised of finite homogeneous elements, (ii) multi-dimensional arrays, comprised of elements each of which is itself an array. A two-dimensional array is the simplest of multidimensional arrays. Single Dimensional Arrays The simplest form of an array is a single dimensional array. The array is given a name and its elements are referred to by their subscripts or indices. C++ arrays index numbering starts with 0. Like other variables in C++, an array must be declared before it can be used to store information. The syntax is: data type array variable name[size]; where type declares the base type of the array, which is the type of each element in the array. The array name specifies the name with which the array will be referenced and size defines how many elements the array will hold. The size must be an integer value. The data type of array elements is known as the base type of the array. eg: int a[10]; float avg[50]; double income[100]; char name[20];

Memory representation of Single Dimension Arrays Single dimension arrays are essentially lists of information of the same type and their elements are stored in contiguous memory location in their index order. For instance, an array grade of type char with 8 elements declared as char grade[8]; will have the element grade[0] at the first allocated memory location, grade[1] at the next memory location, grade[2] at the next and so forth. Since grade is a char type array, each element size is 1 byte. grade[0] grade[1] grade[2] grade[3] grade[4] grade[5] grade[6] grade[7] grade address 1000 1001 1002 1003 1004 1005 1006 1007 An eight-element character array beginning at location 1000.

If we have an int array age with 5 elements declared as int age[5]; its each element will have 2 bytes for its storage. age[0] age[1] age[2] 24 age[3] age[4]

age 5000 5002 5004 5006 5008 A five-element integer array beginning at location 5000

The amount of memory required to store an array is directly related to its type and size. The total memory size of a single dimension array can be calculated using the equation: total bytes = sizeof (data type) x size of array. For example, a float array z[5] takes 20 bytes for its storage. (5 x 4=20, where 4 is size of float and 5 is total number of elements in the array). STRING AS AN ARRAY C++ does not have a string data type rather it implements strings as singledimension character arrays. A string is defined as a character array that is terminated by a null character \0. For this reason, the character arrays are declared one character longer than the largest string they can hold. Syntax: char variable name[size]; eg: char name[20]; char grade[10];

Individual characters of a string can be easily accessed as they make the elements of the character array. The index 0 refers to the first character, the index 1 to the second and so forth. The end of a string is determined by checking for null character (\0). STRING AND CHARACTER RELATED FUNCTIONS C++ library supports a large number of character and string functions. To support character functions, we must include the header file ctype.h and for string functions, string.h header file is used.

Character Functions (ctype.h)

25

1) isalnum( ) this function is used to check whether the given character is an alphabet (either uppercase or lower case) or a digit. It returns nonzero if its argument is a letter or a digit. If the character is not an alphanumeric, it returns zero. syntax: isalnum(character variable / character constant) eg: char ch; cin>>ch; if(isalnum(ch)) cout<<Alphanumeric; else cout<<Special character; 2) isalpha( ) It checks whether the given character is an alphabet (either uppercase or lowercase). It returns nonzero if its argument is an alphabet, otherwise it returns zero. syntax: isalpha(character variable / character constant) eg: char ch; cin>>ch; if(isalpha(ch)) cout<<Alphabet; else cout<<Not an alphabet; 3) isupper( ) - It checks whether the given character is an uppercase alphabet. It returns nonzero if its argument is an uppercase alphabet, otherwise it returns zero. syntax: isupper(character variable / character constant)

eg: char ch; cin>>ch; if(isupper(ch)) cout<<Uppercase Alphabet;

26

else cout<<Not an Uppercase Alphabet; 4) islower( ) - It checks whether the given character is a lowercase alphabet. It returns nonzero if its argument is a lowercase alphabet, otherwise it returns zero. syntax: islower(character variable / character constant) eg: char ch; cin>>ch; if(islower(ch)) cout<<Lowercase Alphabet; else cout<<Not a Lowercase Alphabet; 5) isdigit( ) - It checks whether the given character is a digit (0-9). It returns nonzero if its argument is a digit, otherwise it returns zero. syntax: isdigit(character variable / character constant) eg: char ch; cin>>ch; if(isdigit(ch)) cout<<Single Digit; else cout<<Not a digit; 6) isspace( ) - It checks whether the given character is a blank space. It returns nonzero if its argument is a space, otherwise it returns zero. Note that C++ standard input stream object cin always ignores spaces. So we can use getch( ) or getche( ) or getchar( ) functions to input a space. (getchar( ) function is defined under the header file stdio.h and we can also use the function putchar( ) (instead of cout) to print a character). The difference between getch( ) and getche( ) is that both these functions accept a single character from keyboard; getche( ) displays the character at the same time but getch( ) does not display it on the screen. syntax: isspace(character variable / character constant) 27

eg: char ch; cin>>ch; if(isspace(ch)) cout<<Space; else cout<<Not a space; 7) ispunct( ) It checks whether the given character is a special symbol. It returns nonzero if its argument is a special character, otherwise it returns zero. syntax: ispunct(character variable / character constant)

eg: char ch; cin>>ch; if(ispunct(ch)) cout<<Special character; else cout<<Not a special character; 8) toupper( ) This function returns the uppercase equivalent of a given character, if the character is a lowercase alphabet; otherwise the character is returned unchanged. syntax: toupper(character variable / character constant) eg: char ch =a; ch=toupper(ch)); cout<<ch; 9) tolower( ) - This function returns the lowercase equivalent of a given character, if the character is an uppercase alphabet; otherwise the character is returned unchanged. syntax: tolower(character variable / character constant) eg: char ch =A; 28

ch=tolower(ch)) cout<<ch; String Functions (string.h) 1) strlen( ) It stands for string length. It returns the number of characters present in the given string. Notice that it returns an integer value. syntax strlen(string variable or string constant); eg: char name[25]; int l; l=strlen(name); cout<<No. of characters in <<name<< = <<l; 2) strcpy( ) It stands for string copy. It is used to copy the value of one string to another string. syntax strcpy(string1, string2); Here, string 1 is the destination string and string 2 is the source string. The size of destination string should be large enough to receive the contents of source string. eg: char s1[25],s2[25]; gets(s1); strcpy(s2,s1); cout<<s2; 3) strrev( ) It stands for string reverse. Using this function we can make the reversed form of a given string. syntax strrev(string variable / string constant);

eg: char s1[25]; gets(s1); strrev(s1); cout<<Reversed string is <<s1; 29

4) strcmp( ) It stands for string compare. Using this function we can easily check whether the given two strings are same or not. It alphabetically compares two strings and returns ve value if string 1 is less than string 2; zero if string 1 is equal to string 2; and +ve value if string 1 is greater than string 2. syntax strcmp(string1,string2); eg: char s1[25], s2[25]; gets(s1); gets(s2); if(strcmp(s2,s1)==0) cout<<Strings are same; Note that there is another function strcmpi( ), which is also used to compare two strings. But the difference is that strcmp( ) is case sensitive while strcmpi( ) is not case sensitive. 5) strcat( ) It stands for string catenation. This function concatenates a copy of second string to first string. Note that string 1 should be large enough to hold the contents of both string 1 and string 2. syntax strcat(string 1, string 2); eg - char s1[25] =good, s2[10]=morning; strcat(s1,s2); cout<<New string is <<s1; Two Dimensional (2-D) Arrays A two-dimensional array is an array in which each element is itself an array. Two dimensional arrays are used in the situation where a table of values is to be stored. We can think this table consisting of r rows and c columns containing r x c elements (the number of elements in a 2-D array can be determined by multiplying number of rows with number of columns). The general form of a 2-D array declaration in C++ is as follows: data type array variable name[row size][column size]; eg: int sales[5][12]; float salary[10][12]; char name[50][20]; 30

In the above example, the array sales have 5 elements sales[0], sales[1], sales[2], sales[3] and sales[4] each of which is itself an int array with 12 elements. The elements of sales are referred to as sales[0][0], sales[0][1], and so forth. Processing 2-D Arrays To read or process a 2-D array, we need to use nested loops. One loop processes the rows and other the columns. If outer loop is for rows and inner loop is for columns, then for each row index, all columns are processed and then the same process is repeated for next row index. Memory Representation of Two Dimensional Array Two dimensional arrays are stored in a row column matrix, where the first index indicates the row and the second indicates the column. which they are actually stored in memory. The amount of storage required to hold a two dimensional array is also dependent upon its base type, number of rows and number of columns. The formula to calculate total number of bytes required by a two dimensional array is: total bytes = number of rows x number of columns x size of (base type) Array Initialization C++ provides the facility of array initialization at the time of declaration. The general form of array initialization is: Data type array variable name[row size][column size]={value1, value 2, . . . value n}; eg: int a[5]={1,2,3,4,5}; char name[10]=saps; int a[3][3]={1,2,3,4,5,6,7,8,9}; int b[3][3]={{1,2,3},{4,5,6},{7,8,9}}, char name[5]={s,a,p,s,\0}; This means the second index changes faster than the first index when accessing the elements in the array in the order in

char day[3][10]={Sunday,Monday,Tuesday}; Unsized Array Initialization C++ allows us to skip the size of the array in an array initialization statement. In such situation, C++ automatically calculates the dimension by counting the initializers present.

31

Syntax: data type array variable name[ ] ={value 1, value 2, .. value n}; eg: int val[ ]={2,3,4,5,6,7,8}; float amt[ ]={2341.50,1900.65,3986.75}; Like one dimensional arrays, two dimensional arrays can also be initialized in unsized manner. However, only the first index can be skipped, the second index must be given. eg: int cube[ ] [2]={1,2,3,4,5,6};

STRUCTURES A structure is a grouping of several variables under one name. Sometimes, some logically related elements need to be treated under one unit. For instance, the elements storing a students information (e.g., rollno, name, class, marks, grade) need to be processed together under one roof. Similarly, elements keeping a dates information (e.g., day, month and year) need to be processed together. To handle such situations, C++ offers structures. Structures are one of the two important building blocks in the understanding of classes and objects. A structure is a collection of data while a class is a collection of data and functions. In other words, a structure plus related functions make a class. Technically there is no difference between a structure and a class. In fact, a structure is a class declared with keyword struct and by default all members are public whereas all members are private by default in a class. The general form of a structure definition is: struct { data member 1; data member 2; . . data member n: }; tagname eg: struct student { int rno; char name[25]; int tot; float avg; char grade[10]; };

DECLARING A STRUCTURE VARIABLE We can declare the structure variable at the time of its structure declaration or after the structure declaration. If we want to declare a structure variable at the time of structure declaration, then declare that variable before the semicolon at the very end of the structure declaration. Otherwise use the following syntax: 32

tag name variable name; eg: If we want to declare a variable s1 of type student, then we can write: struct student { int rno; char name[15]; int tot; float avg; char grade[5]; }s1; OR student s1; REFERENCING STRUCTURE ELEMENTS Once a structure variable has been defined, its members can be accessed through the use of . (dot) operator. The syntax is: structure variable.element name For example, if we want to input the name of the student s1, then we can write: gets(s1.name); rno name tot avg grade

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116117 118 119 120 121 122 123 124 125 126 127

Memory allocation of variable s1 of type student Note that here each element in the structure occupies separate memory and the size of a structure variable is the sum of the memory sizes of all the elements in that structure. For example in the case of s1(rno 2 bytes, name 15 bytes, tot 2 bytes, avg 4 bytes and grade 5 bytes) the memory size will be 28 bytes. INITIALIZING STRUCTURE ELEMENTS The elements of a structure can be initialized either separately, using separate assignment statements or jointly, using the notation similar to array initialization.

33

eg: s1.rno=1; strcpy(s1.name,Anoop Krishnan); s1.tot=298; s1.avg=58.6; strcpy(s1.grade,B+); OR student s1={1,Anoop Krishnan,298,58.6,B+}; Please note that the second form of structure initialization can be used only when the structure variable is defined. In this case, the values to be assigned to the structure members are surrounded by curly braces and separated by commas. The first value is assigned to the first member, the second to the second member and so on. STRUCTURE ASSIGNMENT Objects (variables) of one structure type can be assigned, passed as function arguments and returned as the result from a function. Note that one structure variable can be assigned to another only when they are of the same structure type. If we try to assign a variable of one structure type to a variable of another type, the compiler will report an error. Two structure types are different even when they have the same type of members. For example, struct one { int a; }; one s1; two s2; cin>>s1.a; s2=s1; //error. Type mismatch Only assignment is possible for two similar structures. Other operations, such as comparisons (== and !=) are not defined for similar structures. struct two { int a; };

34

A structure may be local, if defined within a function. That is no function other than the one which defines it can access it. A structure may be global (to all functions within a program) if defined outside all functions. That is, any function can then access it. NESTED STRUCTURE A structure element may either complex or simple. The simple elements are any of the fundamental data types of C++. However, a structure may consist of complex elements like arrays, structures etc. A structure consisting of such complex elements is called a complex structure. If a structure declaration or a structure variable declaration comes within another structure, then it is known as nested structure (structure within a structure). eg: struct address { char hname[20]; char place[20]; char city[20]; char state[20]; }; struct employee { int empno; char name[25]; char desig[15]; address ad; float bs; }emp; Note that while defining nested structures, just make sure that inner structures are defined before outer structures. ACCESSING NESTED STRUCTURE MEMBERS The members of structures are accessed using. (dot) operator. To access the member of a nested structure, the following syntax is used: outer structure variable.inner structure variable.element name; For example, to access the city member of address structure, which is an element of another structure employee, we can write: emp.ad.city; // ad is a structure variable of type address and it is a member of another structure employee

35

While initializing a structure within structures, the elements of inner structures have themselves been enclosed in { }. employee emp={101,Ashok,Manager,{sopanam,pattom,Tvm,Kerala},20000.00}; STRUCTURES AND ARRAYS The structures and array both are C++ derived data types. While arrays are collections of analogous elements, structures assemble dissimilar elements under one roof. Thus both the array and the structure allow several values to be treated together as a single data object. The arrays and structures can be combined together to form complex data objects. There may be structures contained within an array; also there may be an array as an element of a structure. ARRAYS OF STRUCTURE To declare an array of structures, we must first define a structure and then declare an array variable of that type. To access a specific structure, index the structure name. An array of structures may even contain nested structures. eg: struct student { int rno; char name[15]; int tot; float avg; char grade[5]; }s[100]; To display the grade of last student, we can write: cout<<s[99].grade; ARRAYS WITHIN STRUCTURES When a structure element happens to be an array, it is treated in the same way as arrays are treated. The only additional thing to be kept in mind is that, to access it, its structure name followed by a dot (.) and the array name is to be given. eg: struct student { int rno; char name[20]; int marks[5]; }learner; 36

To reference marks of 3rd subject of structure learner, we can write: learner.marks[2]; The array in a structure may even be two-dimensional also. UNION A union is a memory location that is shred by two or more different variables, generally of different types. Defining a union is similar to defining a structure. The keyword union is used for declaring and creating a union. For example: union student { int rno; char name[25]; int tot; float avg; } st; In the union st, rno, name, tot and avg share the same memory location and the size of a union variable is the memory size of the element in the union, which requires largest memory. Here the memory size of st is 25 bytes (size of the element name).

name rno
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

tot avg Memory Representation of a union variable

37

38

Das könnte Ihnen auch gefallen