Académique Documents
Professionnel Documents
Culture Documents
Ans –
datatype variablename
Or
int data;
data=0;
Example of Constants
Constant
Example Constraints
Numeric 23000 Can be negative or positive,
Constant cannot contain blanks or
450.6 (Floatingcommas, or $
point)
Character ‘A’ Any character enclosed within
Constant single quotes, represented by
unique ASCII number in the
memory
String “Hello” Set of characters enclosed in
Constant double quotes, last character
in the string is null character
‘\0’
Operators supported in C++ are listed below. Unary operators are used
with one operand and binary operator is used with two operands.
Operators in C++
// sum.cpp
#include<iostream.h>
void main()
{
int a,b,sum;
cout<<”Please enter any two numbers”<<endl;
cin>>a>>b;
sum=a+b;
cout<<”Sum of two numbers is ”<<sum;
}
When you execute the program, the compiler displays the output
of the program and comes back to the program editor. To view the
output and wait for user to press any key to return to the editor, type
getch() as the last statement in the program. Getch() is an inbuilt
predefined library function which inputs a character from the user
through standard input. However you should include another header file
named conio.h to use this function. Conio.h contains the necessary
declarations for using this function. The include statement will be similar
to iostream.h.
During compilation, if there are any errors that will be listing by the
compiler. The errors may be any one of the following
1. Syntax error
This error occurs due to the flaw in the logic. This will not be
identified by the compiler. However it can be traced using the debug tool
in the editor. First identify the variable which you suspect creating the
error and add them to watch list by selecting Debug ->Watches->Add
watch. Write the variable name in the watch expression. After adding all
the variables required to the watch list, go to the statement from where
you want to observe. If you are not sure, you can go to the first
statement of the program. Then select Debug ->Toggle Breakpoint (or
press ctrl + f8). A red line will appear on the statement. Then Run the
program by selecting Ctrl + f9 or Run option from run menu. The
execution will halt at the statement where you had added the
breakpoint. The watch variables and their values at that point of time will
be displayed in the bottom in the watch window. Press F8 to execute the
next statement till you reach the end of the program. In this way you can
watch closely the values in the watch variables after execution of each
and every statement in the program. If you want to exit before execution
of the last statement press Ctrl + Break. To remove the breakpoint in the
program go to the statement where you have added breakpoint select
Debug ->Toggle Breakpoint (or press ctrl + f8). Select Debug -> watch
->remove watches to remove the variables in the watch list. This tool
helps in knowing the values taken by the variable at each and every
step. You can compare the expected value with the actual value to
identify the error.
3. Linker error
This error occur when the files during linking are missing or mispelt
4. Runtime error
Ans –
If statement
// evenodd.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
int num;
cout<<”Please enter a number”<<endl;
cin>>num;
if ((num%2) == 0)
cout<<num <<” is a even number”;
else
cout<<num <<” is a odd number”;
getch();
}
The above program accepts a number from the user and divides it
by 2 and if the remainder (remainder is obtained by modulus operator) is
zero, it displays the number is even, otherwise as odd. We make use of
the relational operator == to compare whether remainder is equal to
zero or not.
Nested If statement
If (condition1)
{ if (condition 2)
{ statement1;
Statement2;
}
else if (condition3)
{statement3;
}
}
else statement4;
If ((condition1 || (condition2))
statement1;
else
statement2;
//Large.cpp
# include <iostream.h>
void main()
{ int a,b,c;
cout<<”Please enter three numbers”;
cin>>a>>b>>c;
if ((a>b) && (b>c))
cout<<a<< “ is the largest number”;
else if ((b>a) && (b>c))
cout<<b<< “ is the largest number”;
else if ((c>a) && (c>b))
cout<<c<< “ is the largest number”;
}
The above program accepts three numbers from the user and
displays which is the largest number among the three.( assumption is
that all the numbers are unique, the program has to be modified if you
would like to allow same number twice)
B) switch statements
Ans –
Switch statement
Syntax :
Switch (variablename)
{ case value1: statement1;
break;
case value2: statement2;
break;
case value3: statement3;
break;
default: statement4;
}
position.cpp
# include<iostream.h>
void main()
{ char pos;
int x=15, y=15;
cout << “ you are currently located at” <<x<<” “<<y<<endl;
cout>>”please choose the letter to move l for left, r for right, u for up
and d for down” <<endl;
cin>>pos;
switch (pos)
{ case ‘l’: x–;
break;
case ‘r’: x++;
break;
case ‘u’: y++;
break;
case ‘d’: y–;
break;
default: cout<<”You selected a wrong option”;
}
cout<<“ you are now located at” <<x<<” “<<y;
}
The above program asks the user to enter l,r,u,d for allowing him
to move left,right,up and down respectively. The position is initialised to
15 and 15 which are x and y coordinates of his position. Depending upon
the what user has selected the the x and y co-ordinates are incremented
or decremented by one(x++ is same as x=x+1). If the user types a letter
other than l,r,u,d, he gets an error message. Since the switch variable is
a character, l,u,r,d and enclosed within single quote.
++ and — operator can be used as postfix or as prefix operator
which has no effect if used as an independent statement. However if it
used as part of an expression, the prefix operator will be operated and
then the expression will be evaluated whereas the postfix operated will
be evaluated later.
Ans –
Conditional Operator
if (a>b)
large=a;
else
large=b;
The above can be done using conditional operator in the following way:
large= (a>b) ? a : b ;
Ans –
#include<iostream.h>
#include<conio.h>
#include<process.h>
void main()
{ clrscr();
int a[10][10],b[10][10],p[10][10],r,c,m,n,i,j,s;
cout<<"Enter number of rows of first matrix: "; cin>>r;
cout<<"Enter number of columns of first matrix: "; cin>>c;
cout<<"Enter number of rows of second matrix: "; cin>>m;
cout<<"Enter number of columns of second matrix: "; cin>>n;
if (c!=m) cout<<"\nMatrices cannot be multiplied", getch(), exit(0);
clrscr();
cout<<"Enter elements of first matrix...\n\n";
for (i=0;i<r;i++)
for (j=0;j<c;j++) cin>>a[i][j];
cout<<"Enter elements of first matrix...\n\n";
for (i=0;i<m;i++)
for (j=0;j<n;j++) cin>>b[i][j];
clrscr();
cout<<"1st matrix...\n";
for (i=0;i<r;i++)
{ for (j=0;j<c;j++) cout<<" "<<a[i][j]; cout<<"\n"; }
cout<<"2nd matrix...\n";
for (i=0;i<m;i++)
{ for (j=0;j<n;j++) cout<<" "<<b[i][j]; cout<<"\n"; }
cout<<"\nProduct...\n";
for (i=0;i<r;i++)
{ for (j=0;j<n;j++)
{ p[i][j]=0; for (s=0;s<c;s++) p[i][j]+=a[i][s]*b[s][j]; cout<<" "<<p[i][j]; }
cout<<"\n"; }
getch();
}
Ans –
//passingbyreference.cpp
# include <iostream.h>
int swap(int& m, int& n); // function declaration
void main()
{
int a,b ;
cout<< “enter two numbers”;
cin>>a>>b;
swap(a,b);
cout<<”The value of a is”<<a<<endl;
cout<<”The value of b is”<<b<<endl;
}
void swap(int& m, int& n)
{ int temp;
temp=m;
m=n;
n=temp;
}
Ans –
You can derive a class from any number of base classes. Deriving a
class from more than one direct base class is called multiple inheritance.
In the following example, classes A, B, and C are direct base classes for
the derived class X:
class A { /* … */ };
class B { /* … */ };
class C { /* … */ };
A direct base class cannot appear in the base list of a derived class more
than once:
However, a derived class can inherit an indirect base class more than
once, as shown in the following example:
class B2 : public L { /* … */ };
class B3 : public L { /* … */ };
In the above example, class D inherits the indirect base class L once
through class B2 and once through class B3. However, this may lead to
ambiguities because two sub objects of class L exist, and both are
accessible through class D. You can avoid this ambiguity by referring to
class L using a qualified class name. For example:
B2::L
or
B3::L.
Ans –
// objectptr.cpp
# include <iostream.h>
class base
{ public:
void show()
{cout<<“base”<<endl;}};
class derv1:public base
{ public:
void show()
{cout<<“derv1”<<endl;}};
class derv2: public base
{ public:
void show()
{cout<<“derv2”<<endl;}};
void main()
{
derv1 dv1;
derv2 dv2;
base *ptr;
ptr=&dv1;
ptr->show();
ptr=&dv2;
ptr->show();
}
base
base
//virtual.cpp
# include <iostream.h>
class base
{ public:
virtual void show() // virtual function
{cout<<“base”<<endl;}};
class derv1:public base
{ public:
void show()
{cout<<“derv1”<<endl;}};
class derv2: public base
{ public:
void show()
{cout<<“derv2”<<endl;}};
void main()
{
derv1 dv1;
derv2 dv2;
base *ptr;
ptr=&dv1;
ptr->show();
ptr=&dv2;
ptr->show();
}
By declaring the base class function as virtual, we now get the output as:
derv1
derv2
Virtual functions are for just name sake and will not be executed
many a times. If the virtual function has no specific role in the base but
just declared for enabling the derived class objects access through
pointers, the function can be declared as a pure virtual function. A pure
virtual function is one which does not have any body. Virtual functions
declared by equating it to zero as shown below:
Ans –
So far we have seen just one way to open a file, either for reading,
either for writing. But it can be opened another way too. So far, you
should be aware of this method:
ifstream OpenFile(“cpp-home.txt”);
Well, this is not the only way. As mentioned before, the above code
creates an object from class ifstream, and passes the name of the file to
be opened to its constructor. But in fact, there are several overloaded
constructors, which can take more than one parameter. Also, there is
function open() that can do the same job. Here is an example of the
above code, but using the open() function:
ifstream OpenFile;
OpenFile.open(“cpp-home.txt”);
Other use of open() is for example if you open a file, then close it,
and using the same file handle open another file. This way, you will need
the open() function.
#include <fstream.h>
void read(ifstream &T) { //pass the file stream to the function
//the method to read a file
char ch;
while(!T.eof()) {
T.get(ch);
cout << ch;
}
cout << endl << "——–" << endl;
}
void main() {
ifstream T("file1.txt");
read(T);
T.close();
T.open("file2.txt");
read(T);
T.close();
}
So, as long as file1.txt and file2.txt exists and has some text into, you
will see it.
You should know that filename is the name of the file (a string).
What is new here is the open_mode. The value of open_mode defines
how to a file can be opened. Here is a table of the open modes:
#include <fstream.h>
void main() {
ofstream SaveFile("file1.txt", ios::ate);
SaveFile << "That’s new!n";
SaveFile.close();
}
As you see in the table, using ios::ate will write at the end of the
file. If it wasn’t used, the file would have been overwritten. So, if file1.txt
has this text:
Running the above code, will add “That’s new!” to it, so it will look this
way:
If you want to set more than one open mode, just use the OR operator
(|). This way:
ios::ate | ios::binary
Using different open modes helps make file handling an easy job. Having
In fact, that is only the declaration. The code line above creates a
file stream handle, named File. As you know, this is an object from class
fstream. When using fstream, you should specify ios::in and ios::out as
open modes. This way, you can read from the file, and write in it, in the
same time, without creating new file handles. Well, of course, you can
only read or write. Here is the code example:
#include <fstream.h>
void main() {
fstream File("test.txt", ios::in | ios::out);
File << "Hi!"; //put “Hi!” in the file
static char str[10]; //when using static, the array is automatically
//initialized, and very cell NULLed
File.seekg(ios::beg); //get back to the beginning of the file
//this function is explained a bit later
File >> str;
cout << str << endl;
File.close();
}
This line, creates an object from class fstream. At the time of execution,
the program opens the file test.txt in read/write mode. This means, that
you can read from the file, and put data into it, at the same time.
I am sure the reader is aware of this and hence the explanation for this
statement is redundant.
This makes a char array with 10 cells. The word static initializes the array
when at the time of creation.
File.seekg(ios::beg);
while(!OpenFile.eof()) {
OpenFile.get(ch);
cout << ch;
}
This is a while loop, that will loop until you reach the end of the file.
But how does the loop know if the end of the file is reached? The answer
is; when you read the file, there is something like an inside-pointer
(current reading/writing position) that shows where you are up to, with
the reading (and writing, too). Every time you call OpenFile.get(ch) it
returns the current character to the ch variable, and moves the inside-
pointer one character after that, so that the next time this function is
called, it will return the next character. And this repeats, until you reach
the end of the file.
Going back to the code line; the function seekg() will put the inside-
pointer to a specific place (specified by you). One can use:
Or you can also set the number of characters to go back or after. For
example, if you want to go 5 characters back, you should write:
File.seekg(-5);
File.seekg(40);
It is imperative to mention that the seekg() function is overloaded, and it
can take two parameters, too. The other version is this one:
File.seekg(-5, ios::end);
In this example, you will be able to read the last 4 characters of the text,
because:
Why you will read 4 but not 5 characters? One character is lost, because
the last thing in the file is neither a character nor white space. It is just
position (i.e., end of file).
Why this function was used the program above. After putting “Hi!” in the
file, the inside-pointer was set after it, i.e., at the end of the file. And as
we want to read the file, there is nothing that can be read at the end.
Hence, we have to put the inside-pointer at the beginning. And that is
exactly what this function does.
I believe this line reminds us of cin >>. In fact, it has much to do with it.
This line reads one word from the file, and puts it into the specified array.
For example, if the file has this text:
Using File >> str, will put just “Hi!” to the str array. And, as what we put
in the file was “Hi!” we don’t need to do a while loop, that takes more
time to code. That’s why this technique was used. By the way, in the
while loop for reading, that was used so far, the program reads the file,
char by char. But you can read it word by word, this way:
Ans –
When compiling B.cpp, the compiler has both the declarations and
the definitions available. At this point the compiler does not need to
generate any definitions for template classes, since there are no
instantiations. When the compiler compiles main.cpp, there are two
instantiations: template class B<int> and B<float>. At this point the
compiler has the declarations but no definitions.
//stack.h
#pragma once
template <class T>
class Stack {
public:
Stack(int = 10);
~Stack() { delete [] stackPtr; }
int push(const T&);
int pop(T&); // pop an element off the stack
int isEmpty()const { return top == -1; }
int isFull() const { return top == size – 1; }
private:
int size; // Number of elements on Stack
int top;
T* stackPtr;
};
//constructor with the default size 10
template <class T>
Stack<T>::Stack(int s) {
size = s > 0 && s < 1000 ? s : 10;
top = -1; // initialize stack
stackPtr = new T[size];
}
// push an element onto the Stack
template <class T>
int Stack<T>::push(const T& item) {
if (!isFull())
{
stackPtr[++top] = item;
return 1; // push successful
}
return 0; // push unsuccessful
}
// pop an element off the Stack
template <class T>
int Stack<T>::pop(T& popValue) {
if (!isEmpty())
{
popValue = stackPtr[top--];
return 1; // pop successful
}
return 0; // pop unsuccessful
}
#include <iostream>
#include "stack.h"
using namespace std;
void main() {
typedef Stack<float> FloatStack;
typedef Stack<int> IntStack;
FloatStack fs(5);
float f = 1.1;
cout << "Pushing elements onto fs" << endl;
while (fs.push(f))
{
cout << f << ‘ ‘;
f += 1.1;
}
cout << endl << "Stack Full." << endl
<< endl << "Popping elements from fs" << endl;
while (fs.pop(f))
cout << f << ‘ ‘;
cout << endl << "Stack Empty" << endl;
cout << endl;
IntStack is;
int i = 1.1;
cout << "Pushing elements onto is" << endl;
while (is.push(i))
{
cout << i << ‘ ‘;
i += 1;
}
cout << endl << "Stack Full" << endl
<< endl << "Popping elements from is" << endl;
while (is.pop(i))
cout << i << ‘ ‘;
cout << endl << "Stack Empty" << endl;
}
Output:
Stack Empty