CLASS XI D NOTES

GENERAL

C++ Tokens: In C++, a token is the smallest individual unit in a program. For example if we say char var = ‘a’. it declares var to be a character variable which stores a character ‘a’ to it. Here char, var, ‘=’, ‘a’ and semi colon (;) all are tokens. C++ has the following tokens.

(1) Keyword:-Words with special meaning to computer.

(2) Constants:- Data items that never change their value.

(3) Identifiers: Variables which stores data (memory address)

(4) Operators: Operators on data

a) arithmetic +,-,/,*,%

b) Stream extraction (>)- get from and insertion (<) put to.

c) (Relational >,<, <=, >=, = =, !=)

d) (Logical &(AND), ||(OR) ,!(NOT))

e) (Increment and decrement ( ++, --)

f) (Conditional ?: Ternary operator)

Basic data types: Data types are means to identify the type of data and associated operations of handling it. They are of 2 types:

Fundamental data types: Data types that are not composed of other data types.

int(2) , long int (4), unsigned int (2)- takes whole number,

float(4), double(8) ,long double(10)- takes decimal numbers,

char(1)- take a character e.e char ch=’A’; or char ch=65 both are same ( because char are often treated as integers as they are represented with their ASCII values in memory and ASCII are numbers and it is easy to change numbers into binary)

void – It specifies empty set of values.

Derived data types: From fundamental other data types can be derived.

(1) Array: - Can store more than one element of same type. They can be one, two or much dimensional.

(2) Function: Sub-programs are called functions.

Data type modifiers:- Basic data types may have various modifiers preceding them.

Signed, unsigned, long, short to character and integer base types. When data type modifiers appear before a data type, the meaning of data type is changed in the sense that its size is affected thereby affecting minimal range of values the data type can represent. For e.g int can have values in range -32768 to +32767 but when modifier unsigned is used then range becomes 0 to 65535( So unsigned int is twice as large as signed int) and if long is used then range becomes -2147483648 to +2147483647.

#include<iostream.h>: The header file iostream.h is included in every C++ program to implement input/output facilities. I/O facilities are not defined within C++ language, but rather are implemented through a component of C++ standard library. It instructs the compiler to include the contents of the file enclosed within angular brackets into the source file.

Header files provides declarations of the function prototypes, class definitions etc. It supports modularity. Various functions that help perform I/O operations and some other operations, which can’t be directly performed using C++ basic statements, are stored together in form of a library, the standard library. These stored functions can be called and used for the desired operations by including the desired library file into the program.

Constants: The keyword const is used to make an object constant instead of a variable. E.g const int pi=3.1414; //no body can change this constant pi.

Variable: It is a named memory location, whose values can be changed during program run. Any variable is associated with 2 values:

a)  Lvalue: Its address in memory

b)  Rvalue: Its data value stored at some location in memory.

Rules for naming a Variable:

1.Variable names in Visual C++ can range from 1 to 255 characters. To make variable names portable to other environments stay within a 1 to 31 character range.

2.All variable names must begin with a letter of the alphabet or an
underscore( _ ). For beginning programmers, it may be easier to begin all variable names with a letter of the alphabet.

3.After the first initial letter, variable names can also contain letters and numbers. No spaces or special characters, however, are allowed.

4. Uppercase characters are distinct from lowercase characters.

5. You cannot use a C++ keyword (reserved word) as a variable name.

6. The best naming convention is to choose a variable name that will tell the reader of the program what the variable represents.

Avariable can be declared in 3 ways:

a)  Uninitialized variable: e.g int val

b)  Initialized variable: e.g. int val=10;

c)  Dynamically initialized variable e.g. int c=a+b;

Reference Variable: It is an alias name for a previously defined variable. The usage of it is that the same data object can be referred to by two names and these names can be used interchangeably. Eg.

int total = 7; int & sum = total;

Here sum is declared as a reference.

Both sum and total represents same variable.

Formatting Output: stew(), setprecision() belongs to <iomanip.h>

setw()- Sets the width of field assigned for output. E.g cout<setw(50)<”R”;

setprecision()- It sets the total no. of decimals places to be displayed. cout<setprecision(5)<12.56789234;

The Statements in C++

1) Declaration statement: It declares a variable of different types eg. int a.

2) Assignment statement: It assigns a value eg. A=10

3) Input/output statements: cin>var; cout<var; (It accepts/reads the data from user and prints/writes to file/monitor.)

4) Control Statement: A program consists of series statements. The sequence in which these are executed may be determined during the run time depending upon some intermediate result. Control statement determine if the control is to be transferred to any statement other than one following the current one if, else – if, while, do-while, and for are control statement.

Use of I/O Operations: In C++ input/output devices are treated as files; files are treated as a sequence of stream of bytes. Streams used for input/output are

(1) cin (console input)

(2) cout(console output)

(3) cerr (standard error stream)

Cascading of I/O Operators: If multiple insertion (or put to) operators are used within the same line of output statement, this is known as cascading of output operators. eg. cout<a<b<c++<d; similarly, if multiple extraction (get from) operators are used within the same line of input statement, this is known as cascading of input operators eg. cin>a>b; The extraction operator ignores all white space between two consecutive input values.

Statements: are the instruction given to the computer. It is smallest executable unit within C++ program.

Compound Statement: is a sequence of statements enclosed by a pair of braces {}.

Conditional Control/decision statement/selection statements – Normally statement are executed top to bottom. If the operational flow of control has to be altered, then selection statement is used.

2 Type of section Statements: if (single condition) and switch (multiple) in certain cases, conditional operator?: can be used as alternative to if statement.

Dangling Else statement: If in nested if the number of if’s are more than else then else goes with the preceding unmatched if statement.

e..g if(condition 1)

------

if(condition 2)

------

else //this else is dangling as to attach with which if

------

Here else attaches with preceding unmatched if

Role of Compiler: It is to checks code for correctness.

Types of Errors

1.  Syntax Errors: When rules of a programming language are misused e.e c=a+b (semicolon is missing)

2.  Semantic Errors: When statements are not meaningful. E.g instead of c=a+b; a+b=c is written

3.  Type Errors: If wrong type of data is given then type error is signalled by the compiler. E.g char a=”si”;

4.  Run Time Errors: Error occurs during execution of a program. E.g division by zero c=a/b; if b is 0.

5.  Logical Error: Error in logic so the output you get is not the desired result. E.g program to find even numbers but according to your logic it is finding odd numbers.

Main(): Every C++ program must have a function named main(). It is the driver function. The program execution begins at main() and ends at main(). So, if main() is missing there shall be no execution of the statements.

Comments: It is a piece 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 2 ways

v  Single Line Comments: e.g. // This is a comment

v  Multi Line comments: e.g. /* This is

a comment */

Type Conversion: It is the process of converting one predefined type into other. In C++ two types of conversion take place.

1. Implicit Conversion: It is performed by the compiler automatically. It is generally applied when a mixed mode expression is evaluated so that there is no lose of information. The C++ compiler converts all operand up to the type of the largest operand, also known as type promotion.e.g cout<’a’+1 (will result in 98)

2. Explicit Conversion: It is performed by the user depending upon the need. The expression is converted to the specific type. This is also known as type casting. E.g. (type)expression , int sum,n; float avg; avg=(float)sum/n;

Type compatibility: In an assignment statements variables of one type can be used with variables of another type applying the rules of type conversion. The type on the right side of an assignment statement is converted into the type on the left. E.g int a=3.5; then a will have only 3 as a data type is integer.

Escape Sequences: An escape sequence is a combination of a character and a code extension character. These are non graphic characters that cannot be typed directly from keyboard e.g ‘\n’ These are normally used to control printed output. E.g. ‘\n’(gives newline), ‘\t’(gives tab spacing)

Scope of a Variable :The parts of the program in which a variable can be accessed is known as variable scope. A variable cab be accessed only in the block where it has been declared e.g main{ int a; } a can be accessed wihtin main any where after its declaration.

Iteration Statement: allows a set of instructions to be performed repeatedly until a certain condition is fulfilled. It is also called as looking statement. C++ provides for loop, while loop and do ….. while loop.

Infinite Loop: which goes endlessly e.g. for(;;) or for(int j=25;;j--)

Empty loop: A loop that does not contain any statement in its loop bodye.g. for(int i=1;i<=10;i++); (putting a semicolon makes it as empty or null statement in a loop so nothing gets executed in a loop)

While / Do..while
Entry controlled loop (condition is checked at entry point) / Exit controlled loop(condition is checked at exit point)
If the condition is false the loop body will not be executed at all / Irrespective of the condition the loop will be executed atleast once
e.g. int i=1;
while(i<=5)
{ cout<”mcs”;
i++;
} / e.g. int i=1;
do
{ cout<”mcs”;
i++;
} while(i<=5);
Break (Jump statement) / Continue (Jump statement)
Break when encountered , it skips part of the code below in the loop and comes out of the loop or switch . In a nested loop it comes out of inner most loop. / Continue when encountered , it skips part of the code below in the loop and forces the next iteration and does not come out of the loop
e.g. for(int i=1;i<=5;i++)
{ cout<i;
if(i==3)
break;
} / for(int i=1;i<=5;i++)
{ cout<i;
if(i==3)
continue;
}

exit(0) Function: It causes the program to terminate. It is included in <stdlib.h> or < process.h> file. Its argument is generally 0 which is error level number which goes to operating system indicating successful termination and any other number indicates some error.

exit (int exitcode);

The exitcode is used by some operating systems and may be used by calling programs.

It can have two status

EXIT_FAILURE(non zero) EXIT_SUCESS (0)

Jumping statement: Unconditionally transfer program control within a function: C++ has four statement

1. return// will be done in functions

2. goto -It unconditionally transfers the control to a part of code addressed by a labelname, instead of executing the next statement in the sequence.

3. break

4. continue

int n=10;
loop:
cout < n < ", ";
n--;
if (n>0)
goto loop;
cout < "FIRE!\n"; / e.g. void main() // Example of goto
{ int a,b; char ch;
a1: cin>a>b;
cout<”after addition”<a+b;
cout<”do you want to continue”;
cin>ch;
if(ch==’y’);
goto a1;
}

Difference between ‘a’ and “a” in C++: ‘a’ is character constant/literal and size is 1 byte whereas “a” is string constant and size is 2 bytes (one for a and other for ‘\0’ where every string is terminated by ‘\0’).

Sizeof() operator- It is a unary operator. It gives you size in bytes of the data or data type specified. E.g int a=4; cout<sizeof(a)<sizeof(float);

Conditional/ Ternary Operator- It requires 3 operands . It is used to replace if-else logic situations. E.g. Condition ? expression1 : expression 2;

If condition is true then expression1 is evaluated otherwise expression2 is evaluated .

Random(n)- It belongs to stdlib.h. It generates any random number between 0 to n-1 where n is the integer number.

Switch- If you have a large decision tree, and all the decisions depend on the value of the same variable, switch statement is suitable instead of if..else or else..if statement. It works for integer and character value

switch (expression )

{ case constant 1:

statement 1; break;

case constant 2:

statement 2; break;

default: statemet 3;

}

break is needed to come out of switch. In absence of break all other cases will be executed no matter whether it is true or false till break is encountered or switch comes to an end.

default case is executed when none of the cases match. It is not mandatory. It need not to be the last statement, can be put anywhere.

Stdio.h / String.h / Math.h / Stdlib.h / ctype.h
getc, gets,puts
putc, putchar, putw, getw , remove, rename, fflush, fopen, fclose, remind, fread, fscanf, fseek, ftell, fwrite / strlen , strlwr, strupr, strcpy, strcat, strchr, strcmp, strcmpi, strrev, / abs, pow10
sqrt, log10, tan, tanh, frexp, atan, ceil, cabs, cos, exp, floor, log, poly, pow, sin, fabs / exit, atoi, atol, atof, free,itoa , qsort, randomize, rand, div, random, malloc, calloc / tolower, toupper, isalnum, isascii, isdigit, iscntrl, isgraph, islower, ispunct, isupper, toascii,
Iomanip.h
Setw(), setprecision() / Conio.h
clrscr(),getch(), getche(),

Increment Operator (++): It increases the value of a variable by 1.