- 1 -

UNIT 1 ( Expected No of Questions : 02)

Chapter 1 : C++ Programming Basics:

Introduction to object orientation

(Refer unit 5 )

Functions

(Refer unit 3)

History and evolution:

C++ is an object oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA , in the early 1980’s. C++

is an extension of C with a major addition of the class construct feature of Simula67. Since the class was a major addition to the original C language, Stroustrup initially called the new language ‘C with classes’. However in later in 1983, the name was changed to C++. The idea of C++ comes from the increment operator ++, thereby suggesting that C++ is an incremental version of C++.

Let us begin with a simple example of c++ program:

#include <iostream>

using namespace std;

int main()

{

// this is an example of c++ program to illustrate some of its features

cout < “c++ is better than c”;

return 0;

}

Program Featuers:

Comments:

C++ supports two types of comments

  1. c style comment ( /* */) or multi line comment

Anything enclosed within a pair of /* and */ is treated as comment.

E.g: /* this is an example of c++ program to illustrate some of its features

cout < “c++ is better than c”;

*/

during compilation ,compiler just ignores the code between /* and */

  1. // (double slash) or single line comment

C++ introduces a new comment symbol //(double slash). Comment starts with a double slash and terminate at the end of the line. A comment may start anywhere in the line, and whatever follows till the end of the line is ignored.

Eg:

// this is an example of c++ program to illustrate some of its features

Return type of main()

In C++, main() returns an integer type value to the operating system. There fore every main() in c++ should end with return(0) statement; otherwise a warning error might occur. Since main() returns an integer type value, return type for main() is explicitly specified as int. Note that that the default return type for all functions in c++ is int. the following main without type and return will run with a warning:

main(){

………..

……….

}

Namespace:

using namespace std;

This tells the compiler to use the std namespace. Namespaces are recent addition to C++. A namespace creates a declarative region in which various program elements can be placed. The using statement informs the compiler that you want to use std namespace. This is the namespace in which the entire Standard C++ Library is declared. By using the stdnamespace you simplify access to the standard library.

The iostream file

We have used the following #include directive in the program:

#include <iostream>

This directive causes the preprocessor to add the contents of the iostream file to the program. It contains declarations for the identifier cout and the operator <. Some old versions of C++ use a header file called iostream.h. this is one of the changes introduced by ANSI C++. ( we should use iostream.h if the compiler does not support ANSI C++ features)

Output operator

The above program has only one output statement i.e is

cout < “c++ is better than c”;

causes the string in quotation mark to be displayed on the screen.

This statement uses two C++ features, cout and <. The identifier cout is a predefined object that represents the standard output stream. In C++ standard output stream represents the screen.

Note: it is also possible to redirect the output to other output devices. That we will discuss in unit 6.

The operator < is called the insertion operator. It inserts the contents of the variable on its right to the object on its left.

Input operator

The Statement

cin > number1;

is an input statement and causes the program to wait for the user to type a number.

The identifier cin is a predefined object in c++ that corresponds to the standard input stream.

The operator > is known as extraction operator. It extracts the value from the keyboard and assigns it to the variable on its right.

Cascading I/O operator:

If we use more than one insertion or extraction operator in one statement then that operator is said to be cascaded.

Example1: cascading of input operator

cin > number1>number2;

Here the values are assigned from left to right . That is , if we key in two values, say 10 and 20 then 10 will be assigned to number1 and 20 to number2.

Example2: cascading of output operator

cout<”sum=”<sum<”\n”;

first sends the string “sum=” to cout and then sends the value of sum. Finally, it sends the newline character so that the next output will be in the new line.

Constants:

A constant is an quantity that does not change .This quantity can be stored at a location in the memory of the computer. A variable can be consider as a name given to the location in memory where this constant is stored. Naturally the contents of the variable can change. For example in the equation

3x+y=20

since 3 and 20 cannot change, they are called constants, whereas the quantities x and y can vary or change hence are called variables.

Constants can be classified as integer, floating point, character, string and enumeration constants.

1) Integer Constants:

C++ allows to represent the integer constants in three forms.

  • Octal number system.
  • Decimal number system.
  • Hexadecimal number system.

Octal numbers are specified with a leading zero. Rest of the digits being between 0 and 7.

e.g: 0175

0123

Decimal number system is represented by using digits 0 - 9

e.g:

129

Hexadecimal numbers are specified with 0x or 0X in the beginning .The digits that follow 0x must be numbers in the range 0 – 9 or one of the letters a – f or A – F.

e.g:

0xa1

0XB4

The size or sign qualifier can be appended at the end of the constant. The suffix u is used for unsigned int constants.l for long int constants, s for signed int constants. It is not case sensitive.

e.g:

567u

567U

2)floating point constants:

Decimal notation

here the number is represented as a whole number, followed by a decimal point and a fractional part.

e.g:

3.444

241.67

Exponential notationis useful in representing nos whose magnitude is very large or very small.

3.4e4

3e8

3) Character constants:

A character constant is enclosed in single quotes.

e.g:

‘a’

‘s’

‘\n’

4)String literals:

A string literal is a sequence of characters enclosed in double quotes.

The characters may be letters, numbers, escape sequences or clank spaces.

Note: A String always ends with a null character or ‘\0’

Variables

A variable is an quantity whose value can be changed during program execution. Variable names are names given to the locations in memory of a computer where different constants are stored.

The general form of variable declaration is

type variable_list;

here type must be a valid data type.

Example:

int a,b;

float f1,f2;

DataTypes in C++

Built-in Data Types/ basic data types /Primary data Types:

are:

1.char

2.int

3.float

4.double

5.void

Type Modifiers:

Different type modifiers are long, short, unsigned and signed. Type modifiers are used to derive another data type from primary data types. But we cannot apply all type modifiers to all data types.

Data Type / Range / Bytes
char / -127 to +128 / 1
signed char / -127 to +128 / 1
unsigned char / 0 to 255 / 1
int / -32767 to +32768 / 2
signed int / -32767 to +32768 / 2
unsigned int / 0 to 65535 / 2
short int / -32767 to +32768 / 2
short signed int / -32767 to +32768 / 2
short unsigned int / 0 to 65535 / 2
long int / -2147483647 to 2147483648 / 4
long signed int / -2147483647 to 2147483648 / 4
long unsigned int / 0 to 4294967295 / 4
Float / -3.4e308 to +3.4e308 / 4
Double / -1.7e308 to +1.7e308 / 8
long double / -1.7e4932 to +1.7e4932 / 10

*Note: these data types are also called as Variable types.

Type conversions:

There is automatic type conversion in C++; you can multiply an int by float etc.

The operands of different types when executed in the same expression, the lower-type variable is converted to the type of higher type variable.

Data Type / order
long double / (highest)

(lowest)
Double
Float
Int
Char

When the automatic data conversion do not takes place the programmer needs to convert a value from one type to another.

C++ permits explicit type conversion of variables or expressions using the type cast operator.

C++ supports following two types of typecast operator:

(type name) expression // C notation

type name (expression) // C++ notation

Examples:

Avg=sum/(float)i;

Avg=sum/float(i);

Arithmetic operators:

Operator / Meaning / Example / Result
+,- / Unary Positive,
Negative / +500
-100 / 500
-100
+ / Addition / 5+10 / 15
- / Subtraction / 5 – 10 / -5
* / Multiplication / 5 * 10 / 15
/ / Division / 22 / 7 / 3.14159
% / Modulus / 5 mod 2 / 1
++ / Increment operator
-- / Decrement operator

The Remainder Operator / modulus operator( %).

This operator finds the remainder when one number is divided by another.

Example:

int main(){

cout < 6%8<endl;

cout < 7%8<endl;

cout < 8%8<endl;

cout < 9%8<endl;

cout < 10%8<endl;

return 0;

}

This program would display the values:

6

7

0

1

2

Increment and Decrement operators( ++ , --):

The operator ++ adds 1 to its operand, and – subtracts one, in otherwords

x=x+1;

is same as ++x;

and

x=x-1;

is same as x--;

Both the increment and decrement operators may either precede (prefix) or follow (postfix) the operand. For example,

x=x+1; can be written

++x or x++

There is , however, a difference between the prefix and postfix forms when you use these operators in an expression. When an increment or decrement operator precedes its operand, the increment and decrement operation is performed before obtaining the value of the operand for use in the expression. If the operator follows its operand, the value of the operand is obtained before incrementing or decrementing it.

For example

x=10;

y= ++x;

sets y to 11. However if you write the code as

x=10;

y=x++;

y is set to 10. Either way, x is set to 11.

Here is the precedence of the arithmetic operators

Highest

Lowest / ++ --
-(unary minus) + (unary minus)
* / %
+ -

Operators on the same level of precedence are evaluated by the compiler from left to right.

Manipulator

Manipulators are operators that are used to format the data display. The most commonly used manipulators are endl and setw.

The endl manipulators, when used in an output statement, causes a linefeed to be inserted. It has the same effect as using the newline character “\n”. For example:

……

……

cout < “m = “ <1000<endl;

cout < “n = “ <20 <endl;

cout < “p = “ <3 <endl;

…….

…….

Would cause three lines of output, one for each variable as follows:

1 / 0 / 0 / 0
2 / 0
3

Note that By default outputs are left-justified. It displays the output from the left hand side.

The manipulator setw(n) specifies the field width n for displaying the value. Here the output is Right-justified. It displays the output from the right hand side.

For example

……

……

cout < “m = “ <setw(5)<1000<endl;

cout < “n = “< setw(5) <20<endl;

cout < “p = “< setw(5)<3 <endl;

…….

…….

Would cause the following output:

1 / 0 / 0 / 0
2 / 0
3

The manipulator setw(6) specifies a field width 5 for displaying the values of the variables.

White Space or escape sequences in C++

The following table shows some of the Escape sequences in C++

Code / Meaning
\b / Backspace
\f / Form feed
\n / New Line
\r / Carriage return
\0 / Null
\a / Alert
\\ / Backslash
\v / Vertical tab
\t / Horizontal tab

typedef statement

typedef statement is used to redefine the name of an existing variable type.

For example, consider the following statement in which the type unsigned long int is redefined to be of type TWOWORDS:

unsigned long int TWOWORDS;

now we can declare variables of the type unsigned long int by writing

TWOWORDS var1,var2

Instead of

unsigned long int var1,var2;

thus, typedef provides a short and meaningful way to call a data type.

Preprocessor Directives

Preprocessor Directives are not the program statements .These are instructions to the compilers.

The preprocessor contains the following directives:

#define #elif #else #endif #error #undef

#if #ifdef # ifndef #include #line #pragma

All preprocessor directives directives begin with # sign.

Preprocessors is the part of the compiler and deals with these directives before it begins the real compilation process.

a)#define Directive

consider the program

#include <iostream>

#define LIMIT 25

int main()

{

for ( int i=0 ;I < LIMIT ; i++)

cout < I;

return 0;

}

#define LIMIT 25

This statement is called “macro definition” (or macro). During the preprocessing, the preprocessor replaces every occurrence of LIMIT in the program with 25.

When we compile the program, before the source code passes to the compiler it is examined by the C++ preprocessor for any macro definitions. When it sees the #define directive, it goes through the entire program in search of the macro templates; whenever it finds one, it replaces the macro template with the appropriate macro expansion.

b) #include Directive

#include tells the compiler to insert another file into your source file.

E.g

#include <iostream> instruct the compiler to read and compile the header for the c++ I/ system library functions.

C) #undef Dirctive

In order to undefined a macro which has been earlier defined, the directive

#undef macrotemplate

can be used.

E.g: #undef LIMIT

Would cause the definition of LIMIT to be removed from the system.

D) #ifdef and #endif

General Form:

#ifdef macroname

stmt 1

stmt 2

stmt 3

#endif

e.g:

#ifdef LIMIT

stmt 1

stmt 2

stmt 3

#endif

If the macroname has been #defined , the block of code (stmt 1,stmt 2, stmt 3) will be processed as usual; otherwise not.

E) #if, #else , #elif, #endif

The general form is

#if constant-expression

statement sequence

#endif

if the constant expression following #if is true, the code that is between it and #endif is compiled. Otherwise, the intervening code is skipped. The #endif directive marks the end of an #IF block.

E.g:

The #elif directive means “else if” and establishes an if-else-if chain for multiple compilation options.

The general form is

#if expression

statement sequence

#elif expression1

statement sequence

#elif expression2

statement sequence

--

#elif expression n

statement sequence

#endif

------

University questions:

1.What is the output of the following program segment.

int *I;

void *p=*I;

a)error b) address of pointer I is stored in pointer p

c)value of i is stored in p d)value of I is stored in the location where

the pointer p points to

2) cout<width(10)<no1;cout<no2 // this statement will

a) displays the nos with a width of 10 b)produces error

c)displays the no1 with width 10 d)result unpredictable.

3) which of the following is a manipulator

a)setw() b)endl c)ios::left d)fill()

(6+4)

Explain the integer variables and character variables along with suitable example programs.

What is the use of const qualifier and #define directive.

(4+6)

Along with suitable example program explain manipulators

Explain—a)Arithmetic assignment operators b) Increment operators.

App/ May 2004

a) Explain escape sequences.

b) Explain—a)Arithmetic assignment operators b) Increment operators.

App/ May 2004

a)Explain the integer variables and character variables along with suitable example programs.

b)What are preprocessor directives?explain

Nov 2003

a)what are the advantages of OOPs?

b)Explain the general structure of C++ program.

Nov 2003

a)Explain the different data types supported by C++ with examples.

b)Write a C++ program to read two integers and compute their bitwise NAD, OR ,EXOR and complement and output the result in a neat format with suitable labels.

UNIT 2 ( Expected No of Questions : 01)

Relational Operators

The Relational operators are used to construct a relational expression.

The complete set of C+ relational operators are given in the following table.

Operator / Comparison / Example / Meaning
== / Equal to / X==Y / Is X equal to Y?
Greater than / X>Y / Is X Greater than Y?
Less tan / X<Y / Is X less than Y?
>= / Greater than OR Equal to / X>=Y / Is X Greater than or equal to Y?
<= / Less than Or Equal to / X<=Y / Is X less than Y?
!= / Not Equals / X != Y / Is X not equal to Y?

Logical Operators

Logical operators are used to combine one or more relational expressions. They compare two relational expressions and return true or false value based on the result of the comparison.

The following table lists the commonly used Logical operators to construct a logical expression.

For Example: ( X < 10) and (Y > 10)

Operator / Example / Result after Evaluation
X & Y / true if both X and Y are true; false Otherwise
|| / X || Y / true X or Y , or both of them, are true; false only if both X and Y are false.
! / !X / true if X is false, false if X is true.

C++ fully supports the zero\non-zero concept of true and false. However, it also defines the bool data type and the boolean constants true and false. In C++ , a 0 value is automatically converted into false, and a non-zero value automatically converted into true. The reverse also applies: true converts to 1 and false converts to 0. In c++ outcome of a logical expression is true or false.

e.g:

cout < (5>2); would display “true”

Precedence of Arithmetic, Relational and Logical operators.

Arithmetic / Relational/comparison operators / Logical Operators
++ --- / > >= < <= / !
- (Unary Minus) / == !=
* / % / ||
+ -

Bitwise Operators

Bitwise operators can be applied only to char and int data types. You cannot use bitwise operators on float, double, long double, void, bool, or other, more complex types.

Operator / Action
AND
| / OR
^ / XOR
~ / NOT (one’s complement)
Shift right
Shift left
Bitwise Operators

Conditional Statements or Selection Statements or Branching Statements :

C/C++ supports three types of selection statements:

1. if

2. switch

3. turnary (?) operator

if:

The if statement may be implemented in different forms depending on the complexity of the conditions to be tested:

  1. Simple if statement
  2. if…..else statement
  3. Nested if…else statement.
  4. else if ladder.

Simple if:

The general form of a simple if statement is

The ‘statement_block’ may be a single statement or a group of statements. If the test expression is true , the statement_block will be executed; otherwise the statement_block will be skipped and the execution will jump to the statement-x’.

E.g:

………………

………………

if( category == SPORTS)

{

marks = marks+bonus_marks;

}

cout<marks;

…………………….

…………………….

The program tests the type of category of the student. If the student belongs to the SPORTS category, then the additional bonus_marks are added to his marks before they are printed. For others bonus_marks are not added.

The if….else statement:

The if…else statement is an extension of the simple if statement. The general form is

If the test expression is true, then the true-block statement(s) immediately following the if statement, are executed, otherwise, the false-block statement(s) are executed. In either case either true-block or false-block will be executed, not both.

Let us consider an example of counting the number of boys and girls in the class.we use code 1 for boy and 2 for girl. The program statement to do this may be written as follows:

……………………

…………………..

if(code==1)

boy=boy+1;

else

girl = girl+1;;

xxx;

if the code is equal to 1, the statement boy=boy+1; is executed and the control is transferred to the statement xxx, after skipping the else part. If the code is not equal to 1, the statement boy = boy+1; is skipped and the statement in the else part girl = girl+1; is executed before the control reaches the statement xxx.