You are on page 1of 14

1) Explain the arithmetic , Relational and logical operators with suitable

example.

Ans: Arithmetic Operators : All the basic arithmetic operations can be carried out in
C++. All the operators have almost the same meaning as in other languages. Both unary
and binary operations are available in C++ language. Unary operations operate on a
singe operand, therefore the number 5 when operated by unary – will have the value –5.

Examples of arithmetic operators are :

x+y

x-y

-x + y

a*b+c

-a * b

Relational Operators : Often it is required to compare the relationship between


operands and bring out a decision and program accordingly. This is when the relational
operator come into picture. C++ supports the following relational operators.
It is required to compare the marks of 2 students, salary of 2 persons, we can ompare
them using relational operators. A simple relational expression contains only one
relational operator and takes the following form :

exp1 relational operator exp2

Where exp1 and exp2 are expressions, which may be simple constants, variables or
combination of them. Given below is a list of examples of relational expressions and
evaluated values.

6.5 <= 25 TRUE

-65 > 0 FALSE

10 < 7 + 5 TRUE

Relational expressions are used in decision making statements of C++ language such as
if, while and for statements to decide the course of action of a running program

Logical Operators : C++ has the following logical operators, they compare or evaluate
logical and relational expressions.

Logical AND (&&) : This operator is used to evaluate 2 conditions or expressions with
relational operators simultaneously. If both the expressions to the left and to the right of
the logical operator is true then the whole compound expression is true.

Example :

a > b && x = = 10

The expression to the left is a > b and that on the right is x == 10 the whole expression is
true only if both expressions are true i.e., if a is greater than b and x is equal to 10.

Logical OR (||) : The logical OR is used to combine 2 expressions or the condition


evaluates to true if any one of the 2 expressions is true.

Example :

a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It
evaluates to true if a is less than either m or n and when a

is less than both m and n.

Logical NOT (!) : The logical not operator takes single expression and evaluates to
true if the expression is false and evaluates to false if the expression is true. In other
words it just reverses the value of the expression.

For example :

! (x >= y)

The NOT expression evaluates to true only if the value of x is neither greater than or
equal to y.

2) Write a C++ program to read ‘n’ integers from keyboard, store those
numbers in array and perform sum of those numbers and display the
result.

Ans:
#include <iostream.h>
int main()
{
int n, count, sum=0;
cout << "How many numbers? ";
cin >> n;
int array[n];
for (count=0; count<n; count++){
cout << "Enter Number: ";
cin >> array[n];
sum = sum + array[n];
}
cout << "The sum is " << sum << endl;

3) With example C++ program, differentiate between break and continue


statements.

Ans:
The break statement is used in switch or loops and continue statement is used only
in loops. When break statement is encountered it immediately stops the switch or loop
execution. When continue statement is encountered, all the statements next to it are
skipped and the loop control goes to next iteration. Generally we use break and continue
with some condition.

S.No. break
continue

break statement is used in switch


1. continue statement is used in loops
and loops.
only.

When break is encountered the


When continue is encountered, the
2. switch or loop execution is
statements after it are skipped and the
immediately stopped.
loop control jump to next iteration.

Example: Example:

#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
3. int i; int i;
for(i=0;i<5;++i){ for(i=0;i<5;++i){
if(i==3) if(i==3)
break; continue;
printf(“%d “,i); printf(“%d “,i);
} }
return 0; return 0;

} }

Output: Output:

012 0124

4) Write a C++ program to count number of alphabets, digitals and other


characters in a given string.

Ans:

#include <iostream.h>

#define MAX_SIZE 100

void main()
{
char str[MAX_SIZE];
int alphabets, digits, others, i;

alphabets = digits = others = i = 0;

Cout<<"Enter any string : ";


Cin>>str;

while(str[i]!='\0')
{
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
{
alphabets++;
}
else if(str[i]>='0' && str[i]<='9')
{
digits++;
}
else
{
others++;
}
i++;
}

Cout<<"Alphabets = %d\n", alphabets;


Cout<<"Digits = %d\n", digits;
Cout<<"Special characters = %d\n", others;

return 0;
}

5) Write a C++ program to accept integer and reveres the integer.

Ans:

#include<iostream.h>
void main()
{
int n,t,r,rev=0;
cout<<"Enter any number : ";
cin>>n;
t=n;

while(t>0)
{
r=t%10;
t=t/10;
rev=rev*10+r;
}

cout<<"Reverse of number "<<n<<" is "<<rev;

return 0;
}

6) What do you understand by the dangling-else problem? How do you


overcome that? Explain it.

Ans:

The dangling else is a problem in computer programming in which an optional else


clause in an if–then(–else) statement results in nested conditionals being ambiguous
if a then if b then s else s2

In this example, s is unambiguously executed when a is true and b is true, but one may
interpret s2 as being executed when a is false (thus attaching the else to the first if) or
when a is true and b is false (thus attaching the else to the second if). In other words,
one may see the previous statement as either of the following expressions:

if a then (if b then s) else s2


if a then (if b then s else s2)

7) Write a C++ program to find roots of quadratic equation using switch


statements.

Ans:

#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
int a, b, c, d, flag;
float x,x1,x2,rpart,ipart;
cout<<"enter values for a, b, c"<<endl;
cin>>a>>b>>c;
if(a==0)
{
x=-b/c;
cout<<"\n"<<"The only root is x="<<x;

}
d=b*b-4*a*c;
if(d>0)
flag=1;
else if(d==0)
flag=2;
else
flag=3;
switch(flag)
{
case 1:
cout<<"\n Real and Distinct roots are:"<<endl;
x1=(-b+ sqrt(d))/(2*a);
x2=(-b- sqrt(d))/(2*a);
cout<<"\n x1="<< x1 <<" and x2 = "<<x2<<endl;
break;
case 2:
cout<<"\n repeated roots are:"<<endl;
x1=-b/(2*a);
x2=x1;
cout<<"\n x1 = "<<x1<<" x2 = "<<x2<<endl;
break;
case 3:
d=sqrt (abs(d));
rpart=-b/(2*a);
ipart=d/(2*a);
cout<<"\n Roots are imaginary \n";
cout<<"\n complex roots are :\n";
cout<< "x1= "<<rpart<<" + i "<<ipart <<endl;
cout<< "x2= "<<rpart<<" - i "<<ipart <<endl;
break;
}
return 0;
}

8) Define class and object. With an example C++ program, explain how data
members are declared and accessed?

Ans:

Class: A class is a definition of objects of the same kind

A class can be visualized as a three-compartment box, as illustrated:


1. Classname (or identifier): identifies the class.
2. Data Members or Variables (or attributes, states, fields): contains the static
attributes of the class.
3. Member Functions (or methods, behaviors, operations): contains the
dynamic operations of the class.
In other words, a class encapsulates the static attributes (data) and dynamic behaviors
(operations that operate on the data) in a box.
Class Members: The data members and member functions are collectively called class
members.
#include <iostream.h>
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};

void Rectangle::set_values (int x, int y) {


width = x;
height = y;
}

int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}

In this particular case, the class (type of the objects) is Rectangle, of which there are two
instances (i.e., objects): rect and rectb. Each one of them has its own member variables
and member functions.

Notice that the call to rect.area() does not give the same result as the call to rectb.area().
This is because each object of class Rectangle has its own variables width and height, as
they -in some way- have also their own function members set_value and area that
operate on the object's own member variables.

Classes allow programming using object-oriented paradigms: Data and functions are
both members of the object, reducing the need to pass and carry handlers or other state
variables as arguments to functions, because they are part of the object whose member
is called. Notice that no arguments were passed on the calls to rect.area or rectb.area.
Those member functions directly used the data members of their respective objects rect
and rectb.

9) Explain with a C++ program copy constructor and destructors.

Ans:

Types of Constructors
Constructors are of three types :

1. Default Constructor
2. Parametrized Constructor
3. Copy COnstructor
Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no
parameter.
Syntax :
class_name ()
{ Constructor Definition }
Example :
class Cube
{
int side;
public:
Cube()
{
side=10;
}
};

int main()
{
Cube c;
cout << c.side;
}
Output : 10
In this case, as soon as the object is created the constructor is called which initializes its
data members.
A default constructor is so important for initialization of object members, that even if we
do not define a constructor explicitly, the compiler will provide a default constructor
implicitly.
class Cube
{
int side;
};

int main()
{
Cube c;
cout << c.side;
}
Output : 0
In this case, default constructor provided by the compiler will be called which will
initialize the object data members to default value, that will be 0 in this case.

Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide
different values to data members of different objects, by passing the appropriate values
as argument.
Example :
class Cube
{
int side;
public:
Cube(int x)
{
side=x;
}
};

int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
OUTPUT : 10 20 30
By using parameterized construcor in above case, we have initialized 3 objects with user
defined values. We can have any number of parameters in a constructor.

Copy Constructor
These are special type of Constructors which takes an object as argument, and is used to
copy values of data members of one object into other object. We will study copy
constructors in detail later.

Constructor Overloading
Just like other member functions, constructors can also be overloaded. Infact when you
have both default and parameterized constructors defined in your class you are having
Overloaded Constructors, one with no parameter and other with parameter.
You can have any number of Constructors in a class that differ in parameter list.

class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}
};

int main()
{
Student A(10);
Student B(11,"Ram");
}
In above case we have defined two constructors with different parameters, hence
overloading the constructors.
One more important thing, if you define any constructor explicitly, then the compiler
will not provide default constructor and you will have to define it yourself.

10) Create a class called STUDENT with data members: Name, Semester
and Percentage.
Ans :
#include<iostream.h>
class student {
private: char name[20];
int sem;
float percent;
public :
/* declare the member functions */
void inputData();
void displayData();
};

/* inputs data from user */


void student :: inputData() {
cout << "Enter Name. : ";
cin >> name;
cout << "Enter semester : ";
cin >> sem;

cout << "Enter Percentage : ";


cin >> percent;
}

/* displays student data */


void student :: displayData() {
cout << "name. : " << name;
cout<<”semester:”<<sem;
cout << "\tPercentage : " << percent << endl;
}

int main() {
student s1, s2; // declare objects 's1' and 's2' of class 'student'
s1.inputData(); // call the function inputData() to input 1st student's data
s2.inputData(); // input 2nd student's data
cout << "\nYou have entered the following data :- " << endl;
s1.displayData(); // display 1st student's data
s2.displayData(); // display 2nd student's data
return 0;
}

You might also like