Vous êtes sur la page 1sur 10

1. What are pre- processor directives? Explain each with an example.

Preprocessor directives are lines included in the code of programs preceded by a hash
sign (#). Pre-Processor directives are special symbols which are evaluated before
compilation. The preprocessors are the directives, which give instruction to the compiler
to preprocess the information before actual compilation starts. All preprocessor
directives begin with #, and only white-space characters may appear before a
preprocessor directive on a line. Preprocessor directives are not C++ statements, so they
do not end in a semicolon (;).

There are number of preprocessor directives supported by C++ like

#include, #define, #if, #else, #line, etc.

Source file inclusion (#include): When the preprocessor finds an #include directive it
replaces it by the entire content of the specified header or file. There are two ways to use
#include:

#include <header>
#include "file"

In the first case, a header is specified between angle-brackets <>. This is used to include
headers provided by the implementation, such as the headers that compose the standard
library (iostream, string,...). Whether the headers are actually files or exist in some other
form is implementation-defined, but in any case they shall be properly included with this
directive.

The syntax used in the second #include uses quotes, and includes a file. The file is
searched for in an implementation-defined manner, which generally includes the current
path. In the case that the file is not found, the compiler interprets the directive as a header
inclusion, just as if the quotes ("") were replaced by angle-brackets (<>).

The #define Preprocessor: The #define preprocessor directive creates symbolic constants. The
symbolic constant is called a macro and the general form of the directive is #define macro-
name replacement-text
Eg. #define PI 3.14159

Conditional inclusions (#ifdef, #ifndef, #if, #endif, #else and #elif): These directives
allow to include or discard part of the code of a program if a certain condition is met.
#ifdef allows a section of a program to be compiled only if the macro that is specified as
the parameter has been defined, no matter which its value is. For example:

#ifdef TABLE_SIZE

2. Write the syntax for new and delete operator, with a suitable program.

new and delete operators are used for allocating and de allocating the memory
dynamically.

Syntax for new operator :- new data-type;


Example:- double* pvalue= NULL;
pvalue = new int; // memory is dynamically allocated for integer data type.
Syntax for delete operator:- delete variable-name;
Example:- delete pvalue;// release memory pointed to pvalue
Program using new and delete expressions

#include <iostream>
using namespace std;

int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable

*pvalue = 29494.99; // Store value at allocated address


cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // free up the memory.

return 0;
}

3. What is an object oriented programming? Write its advantages and applications.


i. Object oriented programming (OOPS) was introduced to overcome the drawbacks
of procedure oriented programming.
ii. The primary function of OOPS is to focus on data rather than procedure.
iii. In OOPS the programs are divided into a number of entities called objects.
iv. The data and functions are designed to characterize these objects.
v. Data is hidden and cannot be shared by outside functions.

Advantages of OOPs
Code Reuse and Recycling
Encapsulation
Design Benefits
Software Maintenance

Applications of OOPs

Real time systems.


User interface designs
Neural networking and programming
Simulation and modeling etc...

4. Mention and explain tokens in C++.


A token is a group of characters that logically belong together. The programmer can write
a program by using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.

i. Keywords:- These are some reserved words in C++ which have predefined meaning
to compiler called keywords.
Ex:- void, char, new, delete etc...

ii. Identifiers:- Symbolic names can be used in C++ for various data items used by a
programmer in his program. A symbolic name is generally known as an identifier.
The identifier is a sequence of characters taken from C++ character set.

iii. Literals:- Literals (often referred to as constants) are data items that never change
their value during the execution of the program. The following types of literals are
available in C++.
Integer constants
Character constants.
Floating constants
String constants

iv. Punctuators:- The following punctuators are used in c++

Opening and closing brackets indicate single and


Brackets [ ]
multidimensional array subscript.

Parentheses Opening and closing brackets indicate functions calls,;


( ) function parameters for grouping expressions etc.
Opening and closing braces indicate the start and end of a
Braces { }
compound statement.

Comma , It is used as a separator in a function argument list.

Semicolon ; It is used as a statement terminator.

It indicates a labeled statement or conditional operator


Colon :
symbol.

It is used in pointer declaration or as multiplication


Asterisk *
operator.

Equal sign = It is used as an assignment operator.

Pound sign # It is used as pre-processor directive.

5. Explain the string types and associated operations with string class, with
program.
Two types of string declarations are supported by C++.
i. The C-style Character string.
The C-style character string originated within the C language and continues to be
supported within C++. This string is actually a one-dimensional array of
characters which is terminated by a null character '\0'. Thus a null-terminated
string contains the characters that comprise the string followed by a null.

ii. The standard C++ library:


The standard C++ library provides a string class type that supports all the
operations mentioned above, additionally much more functionality.

Program using C++ standard library

#include <iostream>
#include <string>
using namespace std;
int main () {
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
// copy str1 into str3
str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total lenghth of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;

return 0;
}

6. Explain enumeration types with an example.


An enumerated type declares an optional type name and a set of zero or more identifiers
that can be used as values of the type. Each enumerator is a constant whose type is the
enumeration.

To create an enumeration requires the use of the keyword enum. The general form of an
enumeration type is:

enum<identifier> {member1, member2, ---------- membern};

where, enum->Keyword

identifier-> Name that identifies enum data types.

member1, member2-------- member-> integer constants.

Program:-

int main()
{
enum Fruits{orange, guava, apple};
Fruits myFruit;
int i;
cout << "Please enter the fruit of your choice(0 to 2)::";
cin >> i;
switch(i)
{
case orange:
cout << "Your fruit is orange";
break;
case guava:
cout << "Your fruit is guava";
break;
case apple:
cout << "Your fruit is apple";
break;
}
return 0;
}

7. What is pointer? Explain the differences between a pointer and reference types
with a suitable example.

A pointer is a variable whose value is the address of another variable. Like any variable
or constant, you must declare a pointer before you can work with it.
Syntax:- type *var-name;

Differences between pointers and reference types

a. A pointer can be re-assigned any number of times while a reference cannot be re-
seated after binding.
b. Pointers can point nowhere (NULL), whereas reference always refer to an object.
c. You can't take the address of a reference like you can with pointers.
d. Use references in function parameters and return types to define useful and self-
documenting interfaces and use pointers to implement algorithms and data structures.
e. Pointers are just another type of object, and like any object in C++, they can be a
variable. References on the other hand are never objects, only variables.
8. Define an array and write a C++ program to find the largest element of an array.

An array is defined as collection of elements of same data types.


Syntax:- data-type <name> [size];
Program to find the largest element in an array.
#include<iostream.h>
int main()
{
clrscr();
int large, arr[50], size, i;
cout<<"Enter Array Size : ";
cin>>size;
cout<<"Enter array elements : ";
for(i=0; i<size; i++)
{
cin>>arr[i];
}
cout<<"Searching for largest number ...\n\n";
large=arr[0];
for(i=0; i<size; i++)
{
if(large<arr[i])
{
large=arr[i];
}
}
cout<<"Largest Number = "<<large;
return 0;
}

9. Give the differences between the four objects defined.

i. int ival=1024// instructs the compiler to allocate sufficient storage to hold any
value of type int, associate the name ival with that storage, and then place an
initial value of 1024 in that storage.
ii. int *pi = &ival// assign pi address of ival.
iii. int *pi2 = new int(1024)// allocates an unnamed object of type int, initializes that
object to a first value of 1024, and then returns the address of the object in
memory.
iv. int *pi3 = new int[1024]// allocates an array of elements of integer type with
1024 as size.

10. Explain the difference between following sets of literal constants


i) ‘a’, L ‘a’, ”a”, L”a” ii) 10, 10u, 10L, 10uL, 012, OxC
ii) 3.14, 3.14f 3.14L
i. ‘a’=>represents single character, L ‘a’=>wide character literal,
”a”=>represents string followed by null character,
L”a”=> wide string literal followed by null character,
ii. 10=>integer value ten, 10u=>unsigned integer number ,
10L=> long integer number, 10uL=>unsigned long integer
number ,
012=> octal number, OxC=> hexadecimal number
iii. 3.14=> floating number, 3.14f=>single precision floating
number
3.14L =>long floating number

11. Which of the following is illegal definition? Correct any that are identified as illegal.
a) int car=1024. Auto=2048; b) int ival=ival; c) int ival(int());
d) double salary=wage=9999.99; e) cin>>int input_value;

a. int car=1024. Auto=2048; // illegal


int car=1024, Auto=2048; // legal
b.int ival=ival; //illegal
can’t be initialised without assigning value to ival=10;
c. int ival(int()); //illegal
int ival=int(); //legal
d.double salary=wage=9999.99; //illegal
double salary=999999,wage=9999.99; //legal
e. cin>>int input_value; //illegal
int input_value;
cin>>input_value; //legal

12. Write a C++ program that accepts lengths of 3 sides of a triangle and find its
area. Display the area along with the values of its sides. In this context explain
cin, cout and #include.

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
float a,b,c,s,Area;
cout<<"Enter three sides of triangle : ";
cin>>a>>b>>c;
s=(a+b+c)/2;
Area=sqrt(s*(s-a)*(s-b)*(s-c));
cout<< “sides of triangle are”<<a<<b<<c<<endl
cout<<"Area of triangle is : "<<Area;
return 0;
}

cout is a predefined keyword in C++ that represents standard output string.


It is always followed by <<(insertion/ put to) operator.

cin is a predefined keyword in C++ that corresponds to standard input string


It is always followed by >> (extraction/get from) operator.

#include<header> used for Source files inclusion. The header file is declared within the
angle brackets.

15. What is an exception? What are the primary components of exception


handling? Explain with an example.

An exception is a problem that arises during the execution of a program. A C++


exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.

 throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.

 catch: A program catches an exception with an exception handler at the place in a


program where you want to handle the problem. The catch keyword indicates the
catching of an exception.

 try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.

Syntax:-

try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}
Program that throws divide by zero exception

#include <iostream>
using namespace std;

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

int main () {
int x = 50;
int y = 0;
double z = 0;

try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}

return 0;
}

Vous aimerez peut-être aussi