HTML URL Encode

URL encoding, also known as percent-encoding, is a mechanism for encoding information in a Uniform Resource Identifier (URI) under certain circumstances. It is used to encode special characters in URLs, for example when an URL contains characters that are not allowed in a standard URL or when the URL contains spaces or other characters that need to be encoded.

To encode a URL in HTML, you can use the encodeURIComponent() function in JavaScript. This function takes a string as input and returns the encoded version of the string.

Here is an example of how to use encodeURIComponent():

<a href="https://www.example.com/search?q=<script>">Link</a>

This example creates a link to a search page with a query parameter containing an invalid script element. To fix this, you can use encodeURIComponent() to encode the query parameter:

<a href="https://www.example.com/search?q=%3Cscript%3E">Link</a>

In this example, the script element is encoded as %3Cscript%3E, which is the URL-encoded version of <script>.

You can also use the decodeURIComponent() function to decode a URL-encoded string.

For more information about URL encoding and decoding in JavaScript, you can refer to the following resources:

Java Script Code structure

Statements

The first thing we’ll study is the building blocks of code

Statements are syntax constructs and commands that perform actions.

We’ve already seen a statement, alert('Hello, world!'), which shows the message “Hello, world!”.

We can have as many statements in our code as we want. Statements can be separated with a semicolon.

For example, here we split “Hello World” into two alerts:

alert('Hello'); alert('World');

Usually, statements are written on separate lines to make the code more readable:

alert('Hello');
alert('World');

Semicolons

A semicolon may be omitted in most cases when a line break exists.

This would also work:

alert('Hello')
alert('World')

Here, JavaScript interprets the line break as an “implicit” semicolon. This is called an automatic semicolon insertion.

In most cases, a newline implies a semicolon. But “in most cases” does not mean “always”!

There are cases when a newline does not mean a semicolon. For example:

alert(3 +
1
+ 2);

The code outputs 6 because JavaScript does not insert semicolons here. It is intuitively obvious that if the line ends with a plus "+", then it is an “incomplete expression”, so the semicolon is not required. And in this case that works as intended.

But there are situations where JavaScript “fails” to assume a semicolon where it is really needed.

Errors which occur in such cases are quite hard to find and fix.An example of an error

If you’re curious to see a concrete example of such an error, check this code out:

alert("Hello");

[1, 2].forEach(alert);

No need to think about the meaning of the brackets [] and forEach yet. We’ll study them later. For now, just remember the result of running the code: it shows Hello, then 1, then 2.

Now let’s remove the semicolon after the alert:

alert("Hello")

[1, 2].forEach(alert);

The difference compared to the code above is only one character: the semicolon at the end of the first line is gone.

If we run this code, only the first Hello shows (and there’s an error, you may need to open the console to see it). There are no numbers any more.

That’s because JavaScript does not assume a semicolon before square brackets [...]. So, the code in the last example is treated as a single statement.

Here’s how the engine sees it:

alert("Hello")[1, 2].forEach(alert);

Looks weird, right? Such merging in this case is just wrong. We need to put a semicolon after alert for the code to work correctly.

This can happen in other situations also.

We recommend putting semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community. Let’s note once again – it is possible to leave out semicolons most of the time. But it’s safer – especially for a beginner – to use them.

Comments

As time goes on, programs become more and more complex. It becomes necessary to add comments which describe what the code does and why.

Comments can be put into any place of a script. They don’t affect its execution because the engine simply ignores them.

One-line comments start with two forward slash characters //.

The rest of the line is a comment. It may occupy a full line of its own or follow a statement.

Like here:

// This comment occupies a line of its own
alert('Hello');

alert('World'); // This comment follows the statement

Multiline comments start with a forward slash and an asterisk /* and end with an asterisk and a forward slash */.

Like this:

/* An example with two messages.
This is a multiline comment.
*/
alert('Hello');
alert('World');

The content of comments is ignored, so if we put code inside /* … */, it won’t execute.

Sometimes it can be handy to temporarily disable a part of code:

/* Commenting out the code
alert('Hello');
*/
alert('World');

Use hotkeys!

In most editors, a line of code can be commented out by pressing the Ctrl+/ hotkey for a single-line comment and something like Ctrl+Shift+/ – for multiline comments (select a piece of code and press the hotkey). For Mac, try Cmd instead of Ctrl and Option instead of Shift.Nested comments are not supported!

There may not be /*...*/ inside another /*...*/.

Such code will die with an error:

/*
  /* nested comment ?!? */
*/
alert( 'World' );

Please, don’t hesitate to comment your code.

Comments increase the overall code footprint, but that’s not a problem at all. There are many tools which minify code before publishing to a production server. They remove comments, so they don’t appear in the working scripts. Therefore, comments do not have negative effects on production at all.

Later in the tutorial there will be a chapter Code quality that also explains how to write better comments.

Python Interview Questions

Following are frequently asked Interview Questions for freshers as well as an experienced .net/ Java/Python Software Developers.

1) What is OOPS?

OOPS is abbreviated as Object-Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

2) Write basic concepts of OOPS?

Following are the concepts of OOPS:

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

3) What is a class?

A class is simply a representation of a type of object. It is the blueprint/plan/template that describes the details of an object.

4) What is an Object?

An object is an instance of a class. It has its own state, behavior, and identity.

5) What is Encapsulation?

Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden data can be restricted to the members of that class.

Levels are Public, Protected, Private, Internal, and Protected Internal.

6) What is Polymorphism?

Polymorphism is nothing but assigning behavior or value in a subclass to something that was already declared in the main class. Simply, polymorphism takes more than one form.

7) What is Inheritance?

Inheritance is a concept where one class shares the structure and behavior defined in another class. If Inheritance applied to one class is called Single Inheritance, and if it depends on multiple classes, then it is called multiple Inheritance.

8) What are manipulators?

Manipulators are the functions which can be used in conjunction with the insertion (<<) and extraction (>>) operators on an object. Examples are endl and setw.

9) Explain the term constructor

A constructor is a method used to initialize the state of an object, and it gets invoked at the time of object creation. Rules for constructor are:

  • Constructor Name should be the same as a class name.
  • A constructor must have no return type.

10) Define Destructor?

A destructor is a method which is automatically called when the object is made of scope or destroyed. Destructor name is also same as class name but with the tilde symbol before the name.

11) What is an Inline function?

An inline function is a technique used by the compilers and instructs to insert complete body of the function wherever that function is used in the program source code.

12) What is a virtual function?

A virtual function is a member function of a class, and its functionality can be overridden in its derived class. This function can be implemented by using a keyword called virtual, and it can be given during function declaration.

A virtual function can be declared using a token(virtual) in C++. It can be achieved in C/Python Language by using function pointers or pointers to function.

13) What is a friend function?

A friend function is a friend of a class that is allowed to access to Public, private, or protected data in that same class. If the function is defined outside the class cannot access such information.

A friend can be declared anywhere in the class declaration, and it cannot be affected by access control keywords like private, public, or protected.

14) What is function overloading?

Function overloading is a regular function, but it can perform different tasks. It allows the creation of several methods with the same name which differ from each other by the type of input and output of the function.

Example

12345void add(int&amp; a, int&amp; b); void add(double&amp; a, double&amp; b); void add(struct bob&amp; a, struct bob&amp; b);

15) What is operator overloading?

Operator overloading is a function where different operators are applied and depends on the arguments. Operator,-,* can be used to pass through the function, and it has its own precedence to execute

16) What is an abstract class?

An abstract class is a class which cannot be instantiated. Creation of an object is not possible with an abstract class, but it can be inherited. An abstract class can contain only an Abstract method. Java allows only abstract method in abstract class while other languages allow non-abstract method as well.

17) What is a ternary operator?

The ternary operator is said to be an operator which takes three arguments. Arguments and results are of different data types, and it depends on the function. The ternary operator is also called a conditional operator.

18) What is the use of finalize method?

Finalize method helps to perform cleanup operations on the resources which are not currently used. Finalize method is protected, and it is accessible only through this class or by a derived class.

19) What are the different types of arguments?

A parameter is a variable used during the declaration of the function or subroutine, and arguments are passed to the function body, and it should match with the parameter defined. There are two types of Arguments.

  • Call by Value – Value passed will get modified only inside the function, and it returns the same value whatever it is passed into the function.
  • Call by Reference – Value passed will get modified in both inside and outside the functions and it returns the same or different value.

20) What is the super keyword?

The super keyword is used to invoke the overridden method, which overrides one of its superclass methods. This keyword allows to access overridden methods and also to access hidden members of the superclass.

It also forwards a call from a constructor, to a constructor in the superclass.

21) What is method overriding?

Method overriding is a feature that allows a subclass to provide the implementation of a method that overrides the main class. It will override the implementation in the superclass by providing the same method name, same parameter, and same return type.

22) What is an interface?

An interface is a collection of an abstract method. If the class implements an interface, it thereby inherits all the abstract methods of an interface.

Java uses Interface to implement multiple inheritances.

23) What is exception handling?

An exception is an event that occurs during the execution of a program. Exceptions can be of any type – Runtime exception, Error exceptions. Those exceptions are adequately handled through exception handling mechanisms like try, catch, and throw keywords.

24) What are tokens?

A compiler recognizes a token, and it cannot be broken down into component elements. Keywords, identifiers, constants, string literals, and operators are examples of tokens.

Even punctuation characters are also considered as tokens. Example: Brackets, Commas, Braces, and Parentheses.

25) What is the main difference between overloading and overriding?

Overloading is static Binding, whereas Overriding is dynamic Binding. Overloading is nothing but the same method with different arguments, and it may or may not return the equal value in the same class itself.

Overriding is the same method names with the same arguments and return types associated with the class and its child class.

26) What is the main difference between a class and an object?

An object is an instance of a class. Objects hold multiple pieces of information, but classes don’t have any information. Definition of properties and functions can be done in class and can be used by the object.

A class can have sub-classes, while an object doesn’t have sub-objects.

27) What is an abstraction?

Abstraction is a useful feature of OOPS, and it shows only the necessary details to the client of an object. Meaning, it shows only required details for an object, not the inner constructors, of an object. Example – When you want to switch on the television, it is not necessary to know the inner circuitry/mechanism needed to switch on the TV. Whatever is required to switch on TV will be shown by using an abstract class.

28) What are the access modifiers?

Access modifiers determine the scope of the method or variables that can be accessed from other various objects or classes. There are five types of access modifiers, and they are as follows:

  • Private
  • Protected
  • Public
  • Friend
  • Protected Friend

29) What are sealed modifiers?

Sealed modifiers are the access modifiers where the methods can not inherit it. Sealed modifiers can also be applied to properties, events, and methods. This modifier cannot be used on static members.

30) How can we call the base method without creating an instance?

Yes, it is possible to call the base method without creating an instance. And that method should be the “Static method.”

Doing Inheritance from that class.-Use Base Keyword from a derived class.

31) What is the difference between new and override?

The new modifier instructs the compiler to use the new implementation instead of the base class function. Whereas, Override modifier helps to override the base class function.

32) What are the various types of constructors?

There are three types of constructors:

–  Default Constructor – With no parameters.

–  Parametric Constructor – With Parameters. Create a new instance of a class and also passing arguments simultaneously.

–  Copy Constructor – Which creates a new object as a copy of an existing object.

33) What is early and late Binding?

Early binding refers to the assignment of values to variables during design time, whereas late Binding refers to the assignment of values to variables during run time.

34) What is ‘this’ pointer?

THIS pointer refers to the current object of a class. THIS keyword is used as a pointer that differentiates between the current object with the global object. It refers to the current object.

35) What is the difference between structure and a class?

The default access type of a Structure is public, but the class access type is private. A structure is used for grouping data, whereas a class can be used for grouping data and methods. Structures are exclusively used for data, and it doesn’t require strict validation, but classes are used to encapsulate and inherent data, which requires strict validation.

36) What is the default access modifier in a class?

The default access modifier of a class is Internal and the default access modifier of a class member is Private.

37) What is a pure virtual function?

A pure virtual function is a function that can be overridden in the derived class but cannot be defined. A virtual function can be declared as Pure by using the operator =0.

Example –

123Virtual void function1() // Virtual, Not pure Virtual void function2() = 0 //Pure virtual

38) What are all the operators that cannot be overloaded?

Following are the operators that cannot be overloaded -.

  1. Scope Resolution (::)
  2. Member Selection (.)
  3. Member selection through a pointer to function (.*)

39) What is dynamic or run time polymorphism?

Dynamic or Run time polymorphism is also known as method overriding in which call to an overridden function is resolved during run time, not at the compile time. It means having two or more methods with the same name, same signature but with different implementations.

40) Do we require a parameter for constructors?

No, we do not require a parameter for constructors.

41) What is a copy constructor?

This is a special constructor for creating a new object as a copy of an existing object. There will always be only one copy constructor that can be either defined by the user or the system.

42) What does the keyword virtual represented in the method definition?

It means we can override the method.

43) Whether static method can use nonstatic members?

False.

44) What are a base class, subclass, and superclass?

The base class is the most generalized class, and it is said to be a root class.

A Subclass is a class that inherits from one or more base classes.

The superclass is the parent class from which another class inherits.

45) What is static and dynamic Binding?

Binding is nothing but the association of a name with the class. Static Binding is a binding in which a name can be associated with the class during compilation time, and it is also called early Binding.

Dynamic Binding is a binding in which a name can be associated with the class during execution time, and it is also called as Late Binding.

46) How many instances can be created for an abstract class?

Zero instances will be created for an abstract class. In other words, you cannot create an instance of an Abstract Class.

47) Which keyword can be used for overloading?

Operator keyword is used for overloading.

48) What is the default access specifier in a class definition?

Private access specifier is used in a class definition.

49) Which OOPS concept is used as a reuse mechanism?

Inheritance is the OOPS concept that can be used as a reuse mechanism.

50) Which OOPS concept exposes only the necessary information to the calling functions?

Encapsulation

C++ Interview Questions Part 2

What are the differences between C and C++?
1) C++ is a kind of superset of C, most C programs except few exceptions (See this and this) work in C++ as well.
2) C is a procedural programming language, but C++ supports both procedural and Object-Oriented programming.
3) Since C++ supports object-oriented programming, it supports features like function overloading, templates, inheritance, virtual functions, friend functions. These features are absent in C.
4) C++ supports exception handling at the language level, in C exception handling, is done in the traditional if-else style.
5) C++ supports references, C doesn’t.
6) In C, scanf() and print() are mainly used input/output. C++ mainly uses streams to perform input and output operations. cin is a standard input stream and cut is a standard output stream.

There are many more differences, above is a list of main differences.

What are the differences between references and pointers?
Both references and pointers can be used to change local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain.
Despite the above similarities, there are the following differences between references and pointers.

References are less powerful than pointers
1) Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
2) References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
3) A reference must be initialized when declared. There is no such restriction with pointers

Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have above restrictions, and can be used to implement all data structures. References being more powerful in Java, is the main reason Java doesn’t need pointers.

References are safer and easier to use:
1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise )
2) Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed to access members.

What are virtual functions – Write an example?
Virtual functions are used with inheritance, they are called according to the type of the object pointed or referred to, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. Virtual keyword is used to make a function virtual.

Following things are necessary to write a C++ program with runtime polymorphism (use of virtual functions)
1) A base class and a derived class.
2) A function with same name in base class and derived class.
3) A pointer or reference of base class type pointing or referring to an object of derived class.

For example, in the following program bp is a pointer of type Base, but a call to bp->show() calls show() function of Derived class, because bp points to an object of Derived class.filter_none

edit

play_arrow

brightness_4

#include<iostream> using namespace std;  class Base { public: virtual void show() { cout<<" In Base \n"; } };  class Derived: public Base { public: void show() { cout<<"In Derived \n"; }  };  int main(void) {    Base *bp = new Derived;      bp->show();  // RUN-TIME POLYMORPHISM return 0; }

Output:

In Derived

What is this pointer?
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).

Can we do “delete this”?
See https://www.geeksforgeeks.org/delete-this-in-c/

What are VTABLE and VPTR?
the vtable is a table of function pointers. It is maintained per class.
vptr is a pointer to the vtable. It is maintained per object (See this for an example).
The compiler adds additional code at two places to maintain and use vtable and vptr.
1) Code in every constructor. This code sets vptr of the object being created. This code sets vptr to point to the vtable of the class.
2) Code with polymorphic function call (e.g. bp->show() in above code). Wherever a polymorphic call is made, the compiler inserts code to first look for vptr using a base class pointer or reference (In the above example, since the pointed or referred object is of a derived type, vptr of the derived class is accessed). Once vptr is fetched, the vtable of a derived class can be accessed. Using vtable, the address of the derived class function show() is accessed and called.

You may also like:

We will soon be covering more C++. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.

C++ Interview Questions Part 1

Most Frequently asked basic and advanced C++ Interview Questions with code examples for entry-level candidates as well as experienced professionals:

This detailed article will surely be a bookmark for those who are preparing for a C++ interview.

Almost all the major topics in C++ are covered here along with some basic questions on advanced topics like Standard Template Library (STL), etc.

This set of C++ coding questions will help you to face any C++ interview confidently and clear it successfully at the first attempt. 

What You Will Learn: [show]

C++ Interview Questions With Code Examples

Enlisted below are the most popular C++ programming interview questions that are answered by a C++ expert.

Basic C++

Structure Of C++ Program

Q #1) What is the basic structure of a C++ program?

Answer: The basic structure of a C++ program is shown below:

#include<iostream.h>int main(){cout<<”Hello,World!”;return 0;}

The first line that begins with “#” is a preprocessor directive. In this case, we are using include as a directive which tells the compiler to include a header while “iostream.h” which will be used for basic input/output later in the program.

The next line is the “main” function that returns an integer. The main function is the starting point of execution for any C++ program. Irrespective of its position in the source code file, the contents of the main function are always executed first by the C++ compiler.

In the next line, we can see open curly braces that indicate the start of a block of code. After this, we see the programming instruction or the line of code that uses the count which is the standard output stream (its definition is present in iostream.h).

This output stream takes a string of characters and prints it to a standard output device. In this case, it is, “Hello, World!”. Please note that each C++ instruction ends with a semicolon (;), which is very much necessary and omitting it will result in compilation errors.

Before closing the braces}, we see another line “return 0;”. This is the returning point to the main function.

Every C++ program will have a basic structure as shown above with a preprocessor directive, main function declaration followed by a block of code and then a returning point to the main function which indicates successful execution of the program.

Q #2) What are the Comments in C++?

Answer: Comments in C++ are simply a piece of source code ignored by the compiler. They are only helpful for a programmer to add a description or additional information about their source code.

In C++ there are two ways to add comments:

  • //single-line comment
  • /* block comment */

The first type will discard everything after the compiler encounters “//”. In the second type, the compiler discards everything between “/*” and “*/”.

Variables, Data Types, And Constants

Q #3) Difference between Declaration and Definition of a variable.

Answer: The declaration of a variable is merely specifying the data type of a variable and the variable name. As a result of the declaration, we tell the compiler to reserve the space for a variable in the memory according to the data type specified.

Example:

int Result;char c;int a,b,c;

All the above are valid declarations. Also, note that as a result of the declaration, the value of the variable is undetermined.

Whereas, a definition is an implementation/instantiation of the declared variable where we tie up appropriate value to the declared variable so that the linker will be able to link references to the appropriate entities.

From above Example,

Result = 10;

C = ‘A’;

These are valid definitions.

Q #4) Comment on Local and Global scope of a variable.

Answer: The scope of a variable is defined as the extent of the program code within which the variable remains active i.e. it can be declared, defined or worked with.

There are two types of scope in C++:

  1. Local Scope: A variable is said to have a local scope or is local when it is declared inside a code block. The variable remains active only inside the block and is not accessible outside the code block.
  2. Global Scope: A variable has a global scope when it is accessible throughout the program. A global variable is declared on top of the program before all the function definitions.

Example:

#include <iostream.h>Int globalResult=0; //global variableint main(){Int localVar = 10; //local variable.…..  }

Q #5) What is the precedence when there are a Global variable and a Local variable in the program with the same name?

Answer: Whenever there is a local variable with the same name as that of a global variable, the compiler gives precedence to the local variable.

Example:

#include <iostream.h>int globalVar = 2;int main(){int globalVar = 5;cout<<globalVar<<endl;}

The output of the above code is 5. This is because, although both the variables have the same name, the compiler has given preference to the local scope.

Q #6) When there are a Global variable and Local variable with the same name, how will you access the global variable?

Answer: When there are two variables with the same name but different scope, i.e. one is a local variable and the other is a global variable, the compiler will give preference to a local variable.

In order to access the global variable, we make use of a “scope resolution operator (::)”. Using this operator, we can access the value of the global variable.

Example:

#include<iostream.h>int x= 10;int main(){int x= 2;cout<<”Global Variable x = “<<::x;cout<<”\nlocal Variable x= “<<x;}

Output:

Global Variable x = 10
local Variable x= 2

Q #7) How many ways are there to initialize an int with a Constant?

Answer: There are two ways:

  • The first format uses traditional C notation.
    int result = 10;
  • The second format uses the constructor notation.
    int result (10);

Constants

Q #8) What is a Constant? Explain with an example.

Answer: A constant is an expression that has a fixed value. They can be divided into integer, decimal, floating-point, character or string constants depending on their data type.

Apart from the decimal, C++ also supports two more constants i.e. octal (to the base 8) and hexadecimal (to the base 16) constants.

Examples of Constants:

  • 75 //integer (decimal)
  • 0113 //octal
  • 0x4b //hexadecimal
  • 3.142 //floating point
  • ‘c’ //character constant
  • “Hello, World” //string constant

Note: When we have to represent a single character, we use single quotes and when we want to define a constant with more than one character, we use double-quotes.

Q #9) How do you define/declare constants in C++?

Answer: In C++, we can define our own constants using the #define preprocessor directive.

#define Identifier value

Example:

#include<iostream.h>#define PI 3.142int main (){float radius =5, area;area = PI * r * r;cout<<”Area of a Circle = “<<area;}

Output: Area of a Circle = 78.55

As shown in the above example, once we define a constant using #define directive, we can use it throughout the program and substitute its value.

We can declare constants in C++ using the “const” keyword. This way is similar to that of declaring a variable, but with a const prefix.

Examples of declaring a constant

const int pi = 3.142;
const char c = “sth”;
const zipcode = 411014;

In the above examples, whenever the type of a constant is not specified, the C++ compiler defaults it to an integer type.

Operators

Q #10) Comment on Assignment Operator in C++.

Answer: Assignment operator in C++ is used to assign a value to another variable.

a = 5;

This line of code assigns the integer value to variable a.

The part at the left of the =operator is known as an lvalue (left value) and the right as rvalue (right value). Lvalue must always be a variable whereas the right side can be a constant, a variable, the result of an operation or any combination of them.

The assignment operation always takes place from the right to left and never at the inverse.

One property which C++ has over the other programming languages is that the assignment operator can be used as the rvalue (or part of an rvalue) for another assignment.

Example:

a = 2 + (b = 5);

is equivalent to:

b = 5;
a = 2 + b;

Which means, first assign to variable and then assign to a, the value plus the result of the previous expression of b(that is 5), leaves with a final value of 7.

Thus, the following expression is also valid in C++:

a = b = c = 5;

assign 5 to variables aand c.

Q #11) What is the difference between equal to (==) and Assignment Operator (=)?

Answer: In C++, equal to (==) and assignment operator (=) are two completely different operators.

Equal to (==) is an equality relational operator that evaluates two expressions to see if they are equal and returns true if they are equal and false if they are not.

The assignment operator (=) is used to assign a value to a variable. Hence, we can have a complex assignment operation inside the equality relational operator for evaluation.

Q #12) What are the various Arithmetic Operators in C++?

Answer: C++ supports the following arithmetic operators:

  • + addition
  • – subtraction
  • * multiplication
  • / division
  • % module

Let’s demonstrate the various arithmetic operators with the following piece of code.

Example:

#include <iostream.h>int main (){int a=5, b=3;cout<<”a + b = “<<a+b;cout<”\na – b =”<<a-b;cout<<”\na * b =”<<a*b;cout<<”\na / b =”<<a/b;cout<<”\na % b =“<<a%b; return 0;}

Output:

a + b = 8
a – b =2
a * b =15
a / b =2
a % b=1

As shown above, all the other operations are straightforward and the same as actual arithmetic operations, except the modulo operator which is quite different. Modulo operator divides a and b and the result of the operation is the remainder of the division.

Q #13) What are the various Compound Assignment Operators in C++?

Answer: Following are the Compound assignation operators in C++:

+=, -=, *=, /=, %=, >>=, <<=, &=, ^=,|=

Compound assignation operator is one of the most  important features of C++ language which allow us to change the value of a variable with one of the basic operators:

Example:

value += increase; is equivalent to value = value + increase;if base_salary is a variable of type int.int base_salary = 1000;base_salary += 1000; #base_salary = base_salary + 1000base_salary *= 5; #base_salary = base_salary * 5;

Q #14) State the difference between Pre and Post Increment/Decrement Operations.

Answer: C++ allows two operators i.e ++ (increment) and –(decrement), that allow you to add 1 to the existing value of a variable and subtract 1 from the variable respectively. These operators are in turn, called increment (++) and decrement (–).

Example:

a=5;
a++;

The second statement, a++, will cause 1 to be added to the value of a. Thus a++ is equivalent to

a = a+1; or
a += 1;

A unique feature of these operators is that we can prefix or suffix these operators with the variable. Hence, if a is a variable and we prefix the increment operator it will be

++a;

This is called Pre-increment. Similarly, we have pre-decrement as well.

If we prefix the variable a with an increment operator, we will have,

a++;

This is the post-increment. Likewise, we have post-decrement too.

The difference between the meaning of pre and post depends upon how the expression is evaluated and the result is stored.

In the case of the pre-increment/decrement operator, the increment/decrement operation is carried out first and then the result passed to an lvalue. Whereas for post-increment/decrement operations, the lvalue is evaluated first and then increment/decrement is performed accordingly.

Example:

a = 5; b=6;
++a;       #a=6
b–;         #b=6
–a;         #a=5
b++;      #6

I/O through Console

Q #15) What are the Extraction and Insertion operators in C++? Explain with examples.

Answer: In the iostream.h library of C++, cin, and cout are the two data streams that are used for input and output respectively. Cout is normally directed to the screen and cin is assigned to the keyboard.

“cin” (extraction operator): By using overloaded operator >> with cin stream, C++ handles the standard input.

int age;cin>>age;

As shown in the above example, an integer variable ‘age’ is declared and then it waits for cin (keyboard) to enter the data. “cin” processes the input only when the RETURN key is pressed.

“cout” (insertion operator): This is used in conjunction with the overloaded << operator. It directs the data that followed it into the cout stream.

Example:

cout<<”Hello, World!”;cout<<123;

Control Structures And Functions

Control Structures And Loops

Q #16) What is the difference between while and do while loop? Explain with examples.

Answer: The format of while loop in C++ is:

While (expression)
{statements;}

The statement block under while is executed as long as the condition in the given expression is true.

Example:

#include <iostream.h>int main(){int n;cout<<”Enter the number : “;cin>>n;while(n>0){cout<<” “<<n;--n;}cout<<”While loop complete”;}

In the above code, the loop will directly exit if n is 0. Thus in the while loop, the terminating condition is at the beginning of the loop and if it’s fulfilled, no iterations of the loop are executed.

Next, we consider the do-while loop.

The general format of do-while is:

do {statement;} while(condition);

Example:

#include<iostream.h>int main(){int n;cout<<”Enter the number : “;cin>>n;do {cout<<n<<”,”;--n;}while(n>0);cout<<”do-while complete”;}

In the above code, we can see that the statement inside the loop is executed at least once as the loop condition is at the end. These are the main differences between the while and do-while.

In case of the while loop, we can directly exit the loop at the beginning, if the condition is not met whereas in the do-while loop we execute the loop statements at least once.

Functions

Q #17) What do you mean by ‘void’ return type?

Answer: All functions should return a value as per the general syntax.

However, in case, if we don’t want a function to return any value, we use “void” to indicate that. This means that we use “void” to indicate that the function has no return value or it returns “void”.

Example:

void myfunc(){Cout<<”Hello,This is my function!!”;}int main(){myfunc();return 0;}

Q #18) Explain Pass by Value and Pass by Reference.

Answer: While passing parameters to the function using “Pass by Value”, we pass a copy of the parameters to the function.

Hence, whatever modifications are made to the parameters in the called function are not passed back to the calling function. Thus the variables in the calling function remain unchanged.

Example:

void printFunc(int a,int b,int c){a *=2;b *=2;c *=2;} int main() { int x = 1,y=3,z=4;printFunc(x,y,z);cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;}

Output:

x=1
y=3
z=4

As seen above, although the parameters were changed in the called function, their values were not reflected in the calling function as they were passed by value.

However, if we want to get the changed values from the function back to the calling function, then we use the “Pass by Reference” technique.

To demonstrate this we modify the above program as follows:

void printFunc(int& a,int& b,int& c){a *=2;b *=2;c *=2;}int main(){int x = 1,y=3,z=4;printFunc(x,y,z);cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;}

Output:
x=2
y=6
z=8

As shown above, the modifications done to the parameters in the called functions are passed to the calling function when we use the “Pass by reference” technique. This is because using this technique we do not pass a copy of the parameters but we actually pass the variable’s reference itself.

Q #19) What are Default Parameters? How are they evaluated in the C++ function?

Answer: Default Parameter is a value that is assigned to each parameter while declaring a function.

This value is used if that parameter is left blank while calling to the function. To specify a default value for a particular parameter, we simply assign a value to the parameter in the function declaration.

If the value is not passed for this parameter during the function call, then the compiler uses the default value provided. If a value is specified, then this default value is stepped on and the passed value is used.

Example:

int multiply(int a, int b=2){int r;r = a * b;return r;}  int main(){ Cout<<multiply(6);Cout<<”\n”;Cout<<multiply(2,3);}

Output:

12
6

As shown in the above code, there are two calls to multiply function. In the first call, only one parameter is passed with a value. In this case, the second parameter is the default value provided. But in the second call, as both the parameter values are passed, the default value is overridden and the passed value is used.

Q #20) What is an Inline function in C++?

Answer: Inline function is a function that is compiled by the compiler as the point of calling the function and the code is substituted at that point. This makes compiling faster. This function is defined by prefixing the function prototype with the keyword “inline”.

Such functions are advantageous only when the code of the inline function is small and simple. Although a function is defined as Inline, it is completely compiler dependent to evaluate it as inline or not.

Advanced-Data Structure

Arrays

Q #21) Why are arrays usually processed with for loop?

Answer: Array uses the index to traverse each of its elements.

If A is an array then each of its elements is accessed as A[i]. Programmatically, all that is required for this to work is an iterative block with a loop variable i that serves as an index (counter) incrementing from 0 to A.length-1.

This is exactly what a loop does and this is the reason why we process arrays using for loops.

Q #22) State the difference between delete and delete[].

Answer: “delete[]” is used to release the memory allocated to an array which was allocated using new[]. “delete” is used to release one chunk of memory which was allocated using new.

Q #23) What is wrong with this code?

T *p = new T[10];
delete p;

Answer: The above code is syntactically correct and will compile fine.

The only problem is that it will just delete the first element of the array. Though the entire array is deleted, only the destructor of the first element will be called and the memory for the first element is released.

Q #24) What’s the order in which the objects in an array are destructed?

Answer: Objects in an array are destructed in the reverse order of construction: First constructed, last destructed.

In the following Example, the order for destructors will be a[9], a[8], …, a[1], a[0]:

voiduserCode(){Car a[10];...}

Pointers

Q #25) What is wrong with this code?

T *p = 0;
delete p;

Answer: In the above code, the pointer is a null pointer. Per the C++ 03 standard, it’s perfectly valid to call delete on a NULL pointer. The delete operator would take care of the NULL check internally.

Q #26) What is a Reference Variable in C++?

Answer: A reference variable is an alias name for the existing variable. This means that both the variable name and the reference variable point to the same memory location. Hence, whenever the variable is updated, the reference is updated too.

Example:

int a=10;int& b = a;

Here, b is the reference of a.

Storage Classes

Q #27) What is a Storage Class? Mention the Storage Classes in C++.

Answer: Storage class determines the life or scope of symbols such as variable or functions.

C++ supports the following storage classes:

  • Auto
  • Static
  • Extern
  • Register
  • Mutable

Q #28) Explain Mutable Storage class specifier.

Answer: The variable of a constant class object’s member cannot be changed. However, by declaring the variables as “mutable”, we can change the values of these variables.

Q #29) What is the keyword auto for?

Answer: By default, every local variable of the function is automatic i.e. auto. In the below function both the variables ‘i’ and ‘j’ are automatic variables.

void f(){int i; auto int j;}

NOTE: A global variable is not an automatic variable.

Q #30) What is a Static Variable?

Answer: A static variable is a local variable that retains its value across the function calls. Static variables are declared using the keyword “static”. Numeric variables which are static have the default value as zero.

The following function will print 1 2 3 if called thrice.

void f(){static int i;++i;printf(“%d “,i);}

If a global variable is static, then its visibility is limited to the same source code.

Q #31) What is the purpose of the Extern Storage Specifier?

Answer: “Extern” specifier is used to resolve the scope of a global symbol.

#include <iostream >using nam espace std;main(){extern int i;cout<<i<<endl;}int i=20;

In the above code, “i” can be visible outside the file where it is defined.

Q #32) Explain Register Storage Specifier.

Answer: “Register” variable should be used whenever the variable is used. When a variable is declared with a “register” specifier, then the compiler gives CPU register for its storage to speed up the lookup of the variable.

Q #33) When to use “const” reference arguments in a function?

Answer: Using “const” reference arguments in a function is beneficial in several ways:

  • “const” protects from programming errors that could alter data.
  • As a result of using “const”, the function is able to process both const and non-const actual arguments, which is not possible when “const” is not used.
  • Using a const reference will allow the function to generate and use a temporary variable in an appropriate manner.

Structure & User-Defined Data Types

Q #34) What is a Class?

Answer: Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation, the user is not required to know the details of the working of a class.

In general, class acts as a blueprint of a project and can include in various parameters and functions or actions operating on these parameters. These are called the members of the class.

Q #35) Difference between Class and Structure.

Answer:

Structure: In C language, the structure is used to bundle different types of data types together. The variables inside a structure are called the members of the structure. These members are by default public and can be accessed by using the structure name followed by a dot operator and then the member name.

Class: Class is a successor of the Structure. C++ extends the structure definition to include the functions that operate on its members. By default all the members inside the class are private.

Object-Oriented Programming With C++

Classes, Constructors, Destructors

Q #36) What is Namespace?

Answer: Namespace allows us to group a set of global classes, objects and/or functions under a specific name.

The general form to use namespaces is:

namespace identifier { namespace-body }

Where identifier is any valid identifier and the namespace-body is the set of classes, objects, and functions that are included within the namespace. Namespaces are especially useful in the case where there is a possibility for more than one object to have the same name, resulting in name clashes.

Q #37) What is the use of ‘using’ declaration?

Answer: Using Declaration is used to refer a name from the namespace without the scope resolution operator.

Q #38) What is Name Mangling?

Answer: C++ compiler encodes the parameter types with function/method into a unique name. This process is called name mangling. The inverse process is called as demangling.

Example:

A::b(int, long) const is mangled as ‘b__C3Ail’.

For a constructor, the method name is left out.

That is A:: A(int, long) const is mangled as ‘C3Ail’.

Q #39) What is the difference between an Object and a Class?

Answer: Class is a blueprint of a project or problem to be solved and consists of variables and methods. These are called the members of the class. We cannot access methods or variables of the class on its own unless they are declared static.

In order to access the class members and put them to use, we should create an instance of a class which is called an Object. The class has an unlimited lifetime whereas an object has a limited lifespan only.

Q #40) What are the various Access Specifiers in C++?

Answer: C++ supports the following access specifiers:

  • Public: Data members and functions are accessible outside the class.
  • Private: Data members and functions are not accessible outside the class. The exception is the usage of a friend class.
  • Protected: Data members and functions are accessible only to the derived classes.

Example:

Describe PRIVATE, PROTECTED and PUBLIC along with their differences and give examples.

class A{int x; int y;public int a;protected bool flag;public A() : x(0) , y(0) {} //default (no argument) constructor}; main(){ A MyObj; MyObj.x = 5; // Compiler will issue a ERROR as x is private int x = MyObj.x; // Compiler will issue a compile ERROR MyObj.x is private MyObj.a = 10; // no problem; a is public memberint col = MyObj.a; // no problem MyObj.flag = true; // Compiler will issue a ERROR; protected values are read onlybool isFlag = MyObj.flag; // no problem

Q #41) What is a Constructor and how is it called?

Answer: Constructor is a member function of the class having the same name as the class. It is mainly used for initializing the members of the class. By default constructors are public.

There are two ways in which the constructors are called:

  1. Implicitly: Constructors are implicitly called by the compiler when an object of the class is created. This creates an object on a Stack.
  2. Explicit Calling: When the object of a class is created using new, constructors are called explicitly. This usually creates an object on a Heap.

Example:

class A{int x; int y; public A() : x(0) , y(0) {} //default (no argument) constructor};main(){A Myobj; // Implicit Constructor call. In order to allocate memory on stack,//the default constructor is implicitly called.A * pPoint = new A(); // Explicit Constructor call. In order to allocate//memory on HEAP we call the default constructor.}

Q #42) What is a COPY CONSTRUCTOR and when is it called?

Answer: A copy constructor is a constructor that accepts an object of the same class as its parameter and copies its data members to the object on the left part of the assignment. It is useful when we need to construct a new object of the same class.

Example:

class A{int x; int y;public int color;public A() : x(0) , y(0) {} //default (no argument) constructorpublic A( const A& ) ;};A::A( const A & p ){this->x = p.x;this->y = p.y;this->color = p.color;}main(){A Myobj;Myobj.color = 345;A Anotherobj = A( Myobj ); // now Anotherobj has color = 345}

Q #43) What is a Default Constructor?

Answer: Default constructor is a constructor that either has no arguments or if there are any, then all of them are default arguments.

Example:

class B {public: B (int m = 0) : n (m) {} int n;}; int main(int argc, char *argv[]){B b; return 0;}

Q #44) What is a Conversion Constructor?

Answer: It is a constructor that accepts one argument of a different type. Conversion constructors are mainly used for converting from one type to another.

Q #45) What is an Explicit Constructor?

Answer: A conversion constructor is declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. Its purpose is reserved explicitly for construction.

Q #46) What is the role of the Static keyword for a class member variable?

Answer: The static member variable shares a common memory across all the objects created for the respective class. We need not refer to the static member variable using an object. However, it can be accessed using the class name itself.

Q #47) Explain the Static Member Function.

Answer: A static member function can access only the static member variable of the class. Same as the static member variables, a static member function can also be accessed using the class name.

Q #48) What’s the order in which the local objects are destructed?

Answer: Consider following a piece of code:

Class A{….};int main(){A a;A b;...}

In the main function, we have two objects created one after the other. They are created in order, first a then b. But when these objects are deleted or if they go out of the scope, the destructor for each will be called in the reverse order in which they were constructed.

Hence, the destructor of b will be called first followed by a. Even if we have an array of objects, they will be destructed in the same way in the reverse order of their creation.

Overloading

Q #49) Explain Function Overloading and Operator Overloading.

Answer: C++ supports OOPs concept Polymorphism which means “many forms”.

In C++ we have two types of polymorphism, i.e. Compile-time polymorphism, and Run-time polymorphism. Compile-time polymorphism is achieved by using an Overloading technique. Overloading simply means giving additional meaning to an entity by keeping its base meaning intact.

C++ supports two types of overloading:

Function Overloading:

Function overloading is a technique that allows the programmer to have more than one function with the same name but different parameter list. In other words, we overload the function with different arguments i.e. be it the type of arguments, number of arguments or the order of arguments.

Function overloading is never achieved on its return type.

Operator Overloading:

This is yet another type of compile-time polymorphism that is supported by C++. In operator overloading, an operator is overloaded, so that it can operate on the user-defined types as well with the operands of the standard data type. But while doing this, the standard definition of that operator is kept intact.

For Example, an Addition operator (+) that operates on numerical data types can be overloaded to operate on two objects just like an object of complex number class.

Q #50) What is the difference between Method Overloading and Method Overriding in C++?

Answer: Method overloading is having functions with the same name but different argument lists. This is a form of compile-time polymorphism.

Method overriding comes into picture when we rewrite the method that is derived from a base class. Method overriding is used while dealing with run-time polymorphism or virtual functions.

Q #51) What is the difference between a Copy Constructor and an Overloaded Assignment Operator?

Answer: A copy constructor and an overloaded assignment operator basically serve the same purpose i.e. assigning the content of one object to another. But still, there is a difference between the two.

Example:

complex c1,c2;c1=c2; //this is assignmentcomplex c3=c2; //copy constructor

In the above example, the second statement c1 = c2 is an overloaded assignment statement.

Here, both c1 and c2 are already existing objects and the contents of c2 are assigned to the object c1. Hence, for overloaded assignment statement both the objects need to be created already.

Next statement, complex c3 = c2 is an example of the copy constructor. Here, the contents of c2 are assigned to a new object c3, which means the copy constructor creates a new object every time when it executes.

Q #52) Name the Operators that cannot be Overloaded.

Answer: 

  • sizeof – sizeof operator
  • . – Dot operator
  • .* – dereferencing operator
  • -> – member dereferencing operator
  • :: – scope resolution operator
  • ?: – conditional operator

Q #53) Function can be overloaded based on the parameter which is a value or a reference. Explain if the statement is true.

Answer: False. Both, Passing by value and Passing by reference look identical to the caller.

Q #54) What are the benefits of Operator Overloading?

Answer: By overloading standard operators on a class, we can extend the meaning of these operators, so that they can also operate on the other user-defined objects.

Function overloading allows us to reduce the complexity of the code and make it more clear and readable as we can have the same function names with different argument lists.

Inheritance

Q #55) What is Inheritance?

Answer: Inheritance is a process by which we can acquire the characteristics of an existing entity and form a new entity by adding more features to it.

In terms of C++, inheritance is creating a new class by deriving it from an existing class so that this new class has the properties of its parent class as well as its own.

Q #56) What are the advantages of Inheritance?

Answer: Inheritance allows code re-usability, thereby saving time on code development.

By inheriting, we make use of a bug-free high-quality software that reduces future problems.

Q #57) Does C++ support Multilevel and Multiple Inheritances?

Answer: Yes.

Q #58) What are Multiple Inheritances (virtual inheritance)? What are its advantages and disadvantages?

Answer: In multiple inheritances, we have more than one base classes from which a derived class can inherit. Hence, a derived class takes the features and properties of more than one base class.

For Example, a class driver will have two base classes namely, employee and a person because a driver is an employee as well as a person. This is advantageous because the driver class can inherit the properties of the employee as well as the person class.

But in the case of an employee and a person, the class will have some properties in common. However, an ambiguous situation will arise as the driver class will not know the classes from which the common properties should be inherited. This is the major disadvantage of multiple inheritances.

Q #59) Explain the ISA and HASA class relationships. How would you implement each?

Answer: “ISA” relationship usually exhibits inheritance as it implies that a class “ISA” specialized version of another class. For Example, An employee ISA person. That means an Employee class is inherited from the Person class.

Contrary to “ISA”, “HASA” relationship depicts that an entity may have another entity as its member or a class has another object embedded inside it.

So taking the same example of an Employee class, the way in which we associate the Salary class with the employee is not by inheriting it but by including or containing the Salary object inside the Employee class. “HASA” relationship is best exhibited by containment or aggregation.

Q #60) Does a derived class inherit or doesn’t inherit?

Answer: When a derived class is constructed from a particular base class, it basically inherits all the features and ordinary members of the base class. But there are some exceptions to this rule. For instance, a derived class does not inherit the base class’s constructors and destructors.

Each class has its own constructors and destructors. The derived class also does not inherit the assignment operator of the base class and friends of the class. The reason is that these entities are specific to a particular class and if another class is derived or if it is the friend of that class, then they cannot be passed onto them.

Polymorphism

Q #61) What is Polymorphism?

Answer: The basic idea behind polymorphism is in many forms. In C++, we have two types of Polymorphism:

(i) Compile-time Polymorphism

In compile-time polymorphism, we achieve many forms by overloading. Hence, we have an Operator overloading and function overloading. (We have already covered this above)

(ii) Run-time Polymorphism

This is the polymorphism for classes and objects. General idea is that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.

This means, that an object reacts differently to the same function call. This type of polymorphism can use a virtual function mechanism.

Q #62) What are Virtual Functions?

Answer: A virtual function allows the derived classes to replace the implementation provided by the base class.

Whenever we have functions with the same name in the base as well as derived class, there arises an ambiguity when we try to access the child class object using a base class pointer. As we are using a base class pointer, the function that is called is the base class function with the same name.

To correct this ambiguity we use the keyword “virtual” before the function prototype in the base class. In other words, we make this polymorphic function Virtual. By using a Virtual function, we can remove the ambiguity and we can access all the child class functions correctly using a base class pointer.

Q #63) Give an example of Run-time Polymorphism/Virtual Functions.

Answer:

class SHAPE{public virtual Draw() = 0; //abstract class with a pure virtual method};class CIRCLE: public SHAPE{public int r;public Draw() { this->drawCircle(0,0,r); }};class SQUARE: public SHAPE{public int a;public Draw() { this->drawSquare(0,0,a,a); }}; int main(){SHAPE shape1*;SHAPE shape2*; CIRCLE c1;SQUARE s1; shape1 = &c1;shape2 = &s1;cout<<shape1->Draw(0,0,2);cout<<shape2->Draw(0,0,10,10);}

In the above code, the SHAPE class has a pure virtual function and is an abstract class (cannot be instantiated). Each class is derived from SHAPE implementing Draw () function in its own way.

Further, each Draw function is virtual so that when we use a base class (SHAPE) pointer each time with the object of the derived classes (Circle and SQUARE), then appropriate Draw functions are called.

Q #64) What do you mean by Pure Virtual Functions?

Answer: A Pure Virtual Member Function is a member function in which the base class forces the derived classes to override. Normally this member function has no implementation. Pure virtual functions are equated to zero.

Example:

class Shape { public: virtual void draw() = 0; };

Base class that has a pure virtual function as its member can be termed as an “Abstract class”. This class cannot be instantiated and it usually acts as a blueprint that has several sub-classes with further implementation.

Q #65) What are Virtual Constructors/Destructors?

Answer:

Virtual Destructors: When we use a base class pointer pointing to a derived class object and use it to destroy it, then instead of calling the derived class destructor, the base class destructor is called.

Example:

Class A{….~A();};Class B:publicA{~B();};B b;A a = &b;delete a;

As shown in the above example, when we say delete a, the destructor is called but it’s actually the base class destructor. This gives rise to the ambiguity that all the memory held by b will not be cleared properly.

This problem can be solved by using the “Virtual Destructor” concept.

What we do is, we make the base class constructor “Virtual” so that all the child class destructors also become virtual and when we delete the object of the base class pointing to the object of the derived class, the appropriate destructor is called and all the objects are properly deleted.

This is shown as follows:

Class A{….virtual ~A();};Class B:publicA{~B();};B b;A a = &b;delete a;

Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.

Friend

Q #66) What is a friend function?

Answer: C++ class does not allow its private and protected members to be accessed outside the class. But this rule can be violated by making use of the “Friend” function.

As the name itself suggests, friend function is an external function that is a friend of the class. For friend function to access the private and protected methods of the class, we should have a prototype of the friend function with the keyword “friend” included inside the class.

Q #67) What is a friend class?

Answer: Friend classes are used when we need to override the rule for private and protected access specifiers so that two classes can work closely with each other.

Hence, we can have a friend class to be a friend of another class. This way, friend classes can keep private, inaccessible things in the way they are.

When we have a requirement to access the internal implementation of a class (private member) without exposing the details by making the public, we go for friend functions.

Advanced C++ 

Templates

Q #68) What is a template?

Answer: Templates allow creating functions that are independent of data type (generic) and can take any data type as parameters and return value without having to overload the function with all the possible data types. Templates nearly fulfill the functionality of a macro.

Its prototype is any of the following ones:

template <class identifierfunction_declaration;

template <typename identifierfunction_declaration;

The only difference between both the prototypes is the use of keyword class or typename. Their basic functionality of being generic remains the same.

Exception Handling

Q #69) What is Exception Handling? Does C++ support Exception Handling?

Answer: Yes C++ supports exception handling.

We cannot ensure that code will execute normally at all times. There can be certain situations that might force the code written by us to malfunction, even though it’s error-free. This malfunctioning of code is called Exception.

When an exception has occurred, the compiler has to throw it so that we know an exception has occurred. When an exception has been thrown, the compiler has to ensure that it is handled properly, so that the program flow continues or terminates properly. This is called the handling of an exception.

Thus in C++, we have three keywords i.e. trythrow and catch which are in exception handling.

The general syntax for exception block is:

try{…. # Code that is potentially about to throw exception goes here….throw exception;}catch(exception type) {#code to handle exception goes here}

As shown above, the code that might potentially malfunction is put under the try block. When code malfunctions, an exception is thrown. This exception is then caught under the catch block and is handled i.e. appropriate action is taken.

Q #70) Comment on C++ standard exceptions?

Answer: C++ supports some standard exceptions that can be caught if we put the code inside the try block. These exceptions are a part of the base class “std:: exception”. This class is defined in the C++ header file <exception>.

Few Examples of Exceptions supported by this class include:

bad_alloc – thrown by ‘new’

runtime_error – thrown for runtime errors

bad_typeid – thrown by type id

Introduction to Standard Template Library

Q #71) What is a Standard Template Library (STL)? What are the various types of STL Containers?

Answer: A Standard Template Library (STL) is a library of container templates approved by the ANSI committee for inclusion in the standard C++ specification. We have various types of STL containers depending on how they store the elements.

  1. Queue, Stack – These are the same as traditional queue and stack and are called adaptive containers.
  2. Set, Map – These are basically containers that have key/value pairs and are associative in nature.
  3. Vector, deque – These are sequential in nature and have similarities to arrays.

Q #72) What is an Iterator class?

Answer: In C++ a container class is a collection of different objects.

If we need to traverse through this collection of objects, we cannot do it using simple index variables. Hence, we have a special class in STL called an Iterator class which can be used to step through the contents of the container class.

The various categories of iterators include input iterators, output iterators, forward iterators, bidirectional iterators, random access, etc.

Q #73) What is the difference between an External Iterator and an Internal Iterator? Describe an advantage of the External Iterator.

Answer: An internal iterator is implemented with member functions of the class that has items to step through.

An external iterator is implemented as a separate class that can be bound to the object that has items to step through. The basic advantage of an External iterator is that it’s easy to implement as it is implemented as a separate class.

Secondly, as it’s a different class, many iterator objects can be active simultaneously.

Further reading => C# Interview Questions

Conclusion

Almost all the major coding and programming topics of C++ interview are covered in this article.

We hope that any candidate will feel relaxed after preparing for an interview using this series of interview questions.

Basic c Programming Questions Part 1

What is the difference between declaration and definition of a variable/function
Ans: Declaration of a variable/function simply declares that the variable/function exists somewhere in the program but the memory is not allocated for them. But the declaration of a variable/function serves an important role. And that is the type of the variable/function. Therefore, when a variable is declared, the program knows the data type of that variable. In case of function declaration, the program knows what are the arguments to that functions, their data types, the order of arguments and the return type of the function. So that’s all about declaration. Coming to the definition, when we define a variable/function, apart from the role of declaration, it also allocates memory for that variable/function. Therefore, we can think of definition as a super set of declaration. (or declaration as a subset of definition).

// This is only declaration. y is not allocated memory by this statement
extern int y;

// This is both declaration and definition, memory to x is allocated by this statement.
int x;

What are different storage class specifiers in C?
Ans: auto, register, static, extern

What is scope of a variable? How are variables scoped in C?
Ans: Scope of a variable is the part of the program where the variable may directly be accessible. In C, all identifiers are lexically (or statically) scoped. See this for more details.

How will you print “Hello World” without semicolon?
Ans:filter_none

edit

play_arrow

brightness_4

#include <stdio.h> int main(void) { if (printf("Hello World")) { } }

See print “Geeks for Geeks” without using a semicolon for answer.

When should we use pointers in a C program?
1. To get address of a variable
2. For achieving pass by reference in C: Pointers allow different functions to share and modify their local variables.
3. To pass large structures so that complete copy of the structure can be avoided.
4. To implement “linked” data structures like linked lists and binary trees.

What is NULL pointer?
Ans: NULL is used to indicate that the pointer doesn’t point to a valid location. Ideally, we should initialize pointers as NULL if we don’t know their value at the time of declaration. Also, we should make a pointer NULL when memory pointed by it is deallocated in the middle of a program.

What is Dangling pointer?
Ans: Dangling Pointer is a pointer that doesn’t point to a valid memory location. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. Following are examples.filter_none

edit

play_arrow

brightness_4

// EXAMPLE 1 int* ptr = (int*)malloc(sizeof(int)); ..........................free(ptr);  // ptr is a dangling pointer now and operations like following are invalid *ptr = 10; // or printf("%d", *ptr);

filter_none

edit

play_arrow

brightness_4

// EXAMPLE 2 int* ptr = NULL { int x = 10; ptr = &x; } // x goes out of scope and memory allocated to x is free now. // So ptr is a dangling pointer now.

What is memory leak? Why it should be avoided
Ans: Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.filter_none

edit

play_arrow

brightness_4

/* Function with memory leak */#include <stdlib.h>  void f() { int* ptr = (int*)malloc(sizeof(int));  /* Do some work */ return; /* Return without freeing ptr*/}

What are local static variables? What is their use?
Ans:A local static variable is a variable whose lifetime doesn’t end with a function call where it is declared. It extends for the lifetime of complete program. All calls to the function share the same copy of local static variables. Static variables can be used to count the number of times a function is called. Also, static variables get the default value as 0. For example, the following program prints “0 1”filter_none

edit

play_arrow

brightness_4

#include <stdio.h> void fun() { // static variables get the default value as 0. static int x; printf("%d ", x); x = x + 1; }  int main() { fun(); fun(); return 0; } // Output: 0 1

What are static functions? What is their use?
Ans:In C, functions are global by default. The “static” keyword before a function name makes it static. Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files. See this for examples and more details.

You may also like:

Geeks for Geeks C Coding Questions

For the last 40-45 years, C is one of the most popular and highly recognized programming languages across the world. In fact, it is the first programming language of a huge number of individuals (including Me!). Indeed it is strongly recommended to start your programming journey with C language as it helps to understand a lot of underlying processes on the ground level that enhances your fundamental knowledge & boosts your confidence which further makes it easier for you to learn other high-level programming languages as well. Also, proficiency in C Programming offers you various career opportunities that can prompt you to take it into consideration and start learning the C Language!!

Meanwhile, C was developed by Dennis Ritchie and it is a procedural programming language. The language was principally developed as a system programming language to write an operating system and is used in the development of various major platforms such as Microsoft WindowsLinux, etc. Moreover, C language has a rich library that provides various built-in functions and offers dynamic memory allocation as well. Here in this article, we will discuss the thorough curriculum or pathway that one must follow to learn C Language in just 20 days!

1. Introduction to C Language (Day: 1)

This is the first and foremost thing you need to do – To know and understand the nature of C Language! You’re required to go through the fundamentals of the C Language such as the origin of the language, its features & applications, how to compile and run a C program, etc. Furthermore, you need to create your first C program as well to get a better understanding of C programming. In this initial stage, you’re required to get familiar with the basics of the language as much as you can!

  1. C Language Introduction
  2. Features of C Language
  3. Benefits of C over other languages
  4. Compilation of C program
  5. Hello World Program in C

2. Go Through Variables, Data Types & Operators (Day: 2-3)

While learning a programming language, you must need to know about the variables, how to define and store them (datatypes), how to perform logical and mathematical operations (operators), etc. prior to any other programming concepts. These topics can be considered as the basic necessity to learn C programming skills. Meanwhile, you need to cover here several other related topics as well such as how are variables scoped in C, how to perform typecasting in C, type of operators, etc.

  1. Variables and Keywords in C
  2. Scope rules in C
  3. Data Types in C
  4. Operators & Its Types
  5. Typecasting in C

3. Understand the Control Flow Statements (Day: 4-5)

Now, it’s time to understand the process that controls the flow of a program’s execution. You are required to know what are the control statements & how to implement them. There are various concerning topics such as Conditional Statements, Loops, Jump Statements, and many more. After having a theoretical understanding of these concepts, you can opt for their implementation as well through solving programming questions and creating basic programs. You are also recommended to cover several additional topics like Switch Statements, Continue Statement, Break Statement, etc for more clarification.

  • Loops in C
  • Decision Making Statements
  • Switch Statement in C
  • Continue Statement | Break Statement
  • C Loops & Control Structure Practice Questions

4. Learn Array & String Handling in C (Day: 6-7)

After going through the control flow statements, now you’re required to know about Arrays & String Handling in C. Precisely, an array is a collection of data that holds a fixed number of values of the same type whereas Strings are actually a one-dimensional array of characters terminated by a null character ‘\0’. You need to understand how to declare an Array & access its elements, what are the multidimensional arraysstring library functions, and other relevant topics.

  • Arrays in C
  • Strings in C
  • Multidimensional Arrays in C
  • String functions in C
  • Single-quoted & Double-quoted declaration of the char array

5. Get Familiar with Function in C (Day: 8-10)

Once you’ll get done with the above-mentioned topics, now you need to know about the pillar of the C programming language – Functions in C. A Function is a block of code that performs a specific task or computation. You need to know about user-defined and standard library functions, function prototypes in C, function calling – call by value and call by reference, and various others. Meanwhile, you’re also required to go through several other crucial topics such as storage class, recursion, etc. to understand the Functions in C effectively.

  • Functions in C
  • Function Prototype
  • Parameter Passing Techniques in C
  • Storage Classes in C
  • Recursion Concept

6. Learn about Pointers, Structures, and Unions (Day: 11-13)

Okay, let’s dive deeper into the world of C programming with some more in-depth concepts like Pointers, Structures, Unions, and many more. In short, a Pointer is a variable that stores the address of another variable or a memory location. Moreover, Structures, Union, Enum, etc. are the user-defined data type having their own functionalities and specifications. You need to know about how to declare and Initialize Pointers, about Double Pointer, how to define Structure & Union, and other related concepts.

  • Pointers in C | Double Pointer
  • Structures | Union | Enumeration (or enum) in C
  • Declare a pointer to a function
  • Pointer vs Array in C
  • Operations on struct variables in C

7. Understand Dynamic Memory Allocation & LinkedList (Day: 14-17)

Furthermore, you need to understand the concepts like Dynamic allocation of memoryLinked list, etc. The Dynamic Memory Allocation is the process of allocating memory manually during run-time. You’re required to learn Dynamic Memory Allocation in C using malloc(), malloc(), free() and realloc(). Moreover, a linked list is a linear data structure where each node contains a data field and a reference to the next node in the list. You also need to cover several other appropriate data structures such as StackQueue, etc. as Data Structure is the backbone of each programming language.

  • Dynamic Memory Allocation in C
  • Linked List Data Structure
  • Memory Leak
  • Stack | Queue
  • Difference between malloc and calloc

8. Learn about File Management & Preprocessors in C (Day: 18-20)

Lastly, you’re required to get a thorough understanding of File Management & Preprocessors in the C language. File Handling in C concerns various operations such as creation, opening, reading, writing, moving to a specific location, and closing a file. You are required to learn about the functions used for performing these operations, etc. Moreover, you need to know about C Preprocessor which is used automatically to transform your program before actual compilation. It will also help you to understand the architecture of C programming.

  • File Handling in C
  • Multiline macros in C
  • Merge the content of two files into a third one
  • Preprocessor in C
  • Preprocessor directives

After following the above-given pathway, you’ll be able to implement and showcase your skills in C programming to achieve your career goals. Also, the curriculum is not too complex or time-consuming to follow as you need to go through a few topics each day and you’ll cover the entire syllabus in a mere 20 days. So, without any delay, dive into the C programming world and enhance your programming skills for various career opportunities!

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry-ready.

Pandas interview questions

A list of top frequently asked Python Pandas Interview Questions and answers are given below.

1) Define the Pandas/Python pandas?

Pandas is defined as an open-source library that provides high-performance data manipulation in Python. The name of Pandas is derived from the word Panel Data, which means an Econometrics from Multidimensional data. It can be used for data analysis in Python and developed by Wes McKinney in 2008. It can perform five significant steps that are required for processing and analysis of data irrespective of the origin of the data, i.e., load, manipulate, prepare, model, and analyze.


2) Mention the different types of Data Structures in Pandas?

Pandas provide two data structures, which are supported by the pandas library, Series, and DataFrames. Both of these data structures are built on top of the NumPy.

Series is a one-dimensional data structure in pandas, whereas the DataFrame is the two-dimensional data structure in pandas.


3) Define Series in Pandas?

A Series is defined as a one-dimensional array that is capable of storing various data types. The row labels of series are called the index. By using a ‘series‘ method, we can easily convert the list, tuple, and dictionary into series. A Series cannot contain multiple columns.


4) How can we calculate the standard deviation from the Series?

The Pandas std() is defined as a function for calculating the standard deviation of the given set of numbers, DataFrame, column, and rows.

Series.std(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)


5) Define DataFrame in Pandas?

A DataFrame is a widely used data structure of pandas and works with a two-dimensional array with labeled axes (rows and columns) DataFrame is defined as a standard way to store data and has two different indexes, i.e., row index and column index. It consists of the following properties:

  • The columns can be heterogeneous types like int and bool.
  • It can be seen as a dictionary of Series structure where both the rows and columns are indexed. It is denoted as “columns” in the case of columns and “index” in case of rows.

6) What are the significant features of the pandas Library?

The key features of the panda’s library are as follows:

  • Memory Efficient
  • Data Alignment
  • Reshaping
  • Merge and join
  • Time Series

7) Explain Reindexing in pandas?

Reindexing is used to conform DataFrame to a new index with optional filling logic. It places NA/NaN in that location where the values are not present in the previous index. It returns a new object unless the new index is produced as equivalent to the current one, and the value of copy becomes False. It is used to change the index of the rows and columns of the DataFrame.


8) What is the name of Pandas library tools used to create a scatter plot matrix?

Scatter_matrix


9) Define the different ways a DataFrame can be created in pandas?

We can create a DataFrame using following ways:

  • Lists
  • Dict of ndarrays

Example-1: Create a DataFrame using List:

  1. import pandas as pd    
  2. # a list of strings    
  3. a = [‘Python’, ‘Pandas’]    
  4. # Calling DataFrame constructor on list    
  5. info = pd.DataFrame(a)    
  6. print(info)    

Output:

	0
0   Python
1   Pandas

Example-2: Create a DataFrame from dict of ndarrays:

  1. import pandas as pd    
  2. info = {‘ID’ :[101, 102, 103],’Department’ :[‘B.Sc’,’B.Tech’,’M.Tech’,]}    
  3. info = pd.DataFrame(info)    
  4. print (info)   

Output:

       ID      Department
0      101        B.Sc
1      102        B.Tech
2      103        M.Tech

10) Explain Categorical data in Pandas?

A Categorical data is defined as a Pandas data type that corresponds to a categorical variable in statistics. A categorical variable is generally used to take a limited and usually fixed number of possible values. Examples: gender, country affiliation, blood type, social class, observation time, or rating via Likert scales. All values of categorical data are either in categories or np.nan.

This data type is useful in the following cases:

  • It is useful for a string variable that consists of only a few different values. If we want to save some memory, we can convert a string variable to a categorical variable.
  • It is useful for the lexical order of a variable that is not the same as the logical order (?one?, ?two?, ?three?) By converting into a categorical and specify an order on the categories, sorting and min/max is responsible for using the logical order instead of the lexical order.
  • It is useful as a signal to other Python libraries because this column should be treated as a categorical variable.

11) How will you create a series from dict in Pandas?

A Series is defined as a one-dimensional array that is capable of storing various data types.

We can create a Pandas Series from Dictionary:

Create a Series from dict:

We can also create a Series from dict. If the dictionary object is being passed as an input and the index is not specified, then the dictionary keys are taken in a sorted order to construct the index.

If index is passed, then values correspond to a particular label in the index will be extracted from the dictionary.

  1. import pandas as pd    
  2. import numpy as np    
  3. info = {‘x’ : 0., ‘y’ : 1., ‘z’ : 2.}    
  4. a = pd.Series(info)    
  5. print (a)    

Output:

x     0.0
y     1.0
z     2.0
dtype: float64

12) How can we create a copy of the series in Pandas?

We can create the copy of series by using the following syntax:

pandas.Series.copy
Series.copy(deep=True)

The above statements make a deep copy that includes a copy of the data and the indices. If we set the value of deep to False, it will neither copy the indices nor the data.

Note: If we set deep=True, the data will be copied, and the actual python objects will not be copied recursively, only the reference to the object will be copied.


13) How will you create an empty DataFrame in Pandas?

A DataFrame is a widely used data structure of pandas and works with a two-dimensional array with labeled axes (rows and columns) It is defined as a standard way to store data and has two different indexes, i.e., row index and column index.

Create an empty DataFrame:

The below code shows how to create an empty DataFrame in Pandas:

  1. # importing the pandas library    
  2. import pandas as pd    
  3. info = pd.DataFrame()    
  4. print (info)    

Output:

Empty DataFrame
Columns: []
Index: []

14) How will you add a column to a pandas DataFrame?

We can add any new column to an existing DataFrame. The below code demonstrates how to add any new column to an existing DataFrame:

  1. # importing the pandas library    
  2. import pandas as pd      
  3. info = {‘one’ : pd.Series([1, 2, 3, 4, 5], index=[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]),    
  4.              ‘two’ : pd.Series([1, 2, 3, 4, 5, 6], index=[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’])}    
  5.    
  6. info = pd.DataFrame(info)    
  7.     
  8. # Add a new column to an existing DataFrame object     
  9.     
  10. print (“Add new column by passing series”)    
  11. info[‘three’]=pd.Series([20,40,60],index=[‘a’,’b’,’c’])    
  12. print (info)    
  13. print (“Add new column using existing DataFrame columns”)    
  14. info[‘four’]=info[‘one’]+info[‘three’]    
  15. print (info)    

Output:

Add new column by passing series
      one     two      three
a     1.0      1        20.0
b     2.0      2        40.0
c     3.0      3        60.0
d     4.0      4        NaN
e     5.0      5        NaN
f     NaN      6        NaN

Add new column using existing DataFrame columns
       one      two       three      four
a      1.0       1         20.0      21.0
b      2.0       2         40.0      42.0
c      3.0       3         60.0      63.0
d      4.0       4         NaN      NaN
e      5.0       5         NaN      NaN
f      NaN       6        NaN      NaN

15) How to add an Index, row, or column to a Pandas DataFrame?

Adding an Index to a DataFrame

Pandas allow adding the inputs to the index argument if you create a DataFrame. It will make sure that you have the desired index. If you don?t specify inputs, the DataFrame contains, by default, a numerically valued index that starts with 0 and ends on the last row of the DataFrame.

Adding Rows to a DataFrame

We can use .loc, iloc, and ix to insert the rows in the DataFrame.

  • The loc basically works for the labels of our index. It can be understood as if we insert in loc[4], which means we are looking for that values of DataFrame that have an index labeled 4.
  • The iloc basically works for the positions in the index. It can be understood as if we insert in iloc[4], which means we are looking for the values of DataFrame that are present at index ‘4`.
  • The ix is a complex case because if the index is integer-based, we pass a label to ix. The ix[4] means that we are looking in the DataFrame for those values that have an index labeled 4. However, if the index is not only integer-based, ix will deal with the positions as iloc.

Adding Columns to a DataFrame

If we want to add the column to the DataFrame, we can easily follow the same procedure as adding an index to the DataFrame by using loc or iloc.


16) How to Delete Indices, Rows or Columns From a Pandas Data Frame?

Deleting an Index from Your DataFrame

If you want to remove the index from the DataFrame, you should have to do the following:

Reset the index of DataFrame.

Executing del df.index.name to remove the index name.

Remove duplicate index values by resetting the index and drop the duplicate values from the index column.

Remove an index with a row.

Deleting a Column from Your DataFrame

You can use the drop() method for deleting a column from the DataFrame.

The axis argument that is passed to the drop() method is either 0 if it indicates the rows and 1 if it drops the columns.

You can pass the argument inplace and set it to True to delete the column without reassign the DataFrame.

You can also delete the duplicate values from the column by using the drop_duplicates() method.

Removing a Row from Your DataFrame

By using df.drop_duplicates(), we can remove duplicate rows from the DataFrame.

You can use the drop() method to specify the index of the rows that we want to remove from the DataFrame.


17) How to Rename the Index or Columns of a Pandas DataFrame?

You can use the .rename method to give different values to the columns or the index values of DataFrame.


18) How to iterate over a Pandas DataFrame?

You can iterate over the rows of the DataFrame by using for loop in combination with an iterrows() call on the DataFrame.


19) How to get the items of series A not present in series B?

We can remove items present in p2 from p1 using isin() method.

  1. import pandas as pd  
  2. p1 = pd.Series([2, 4, 6, 8, 10])  
  3. p2 = pd.Series([8, 10, 12, 14, 16])  
  4. p1[~p1.isin(p2)]  

Solution

0    2
1    4
2    6
dtype: int64

20) How to get the items not common to both series A and series B?

We get all the items of p1 and p2 not common to both using below example:

  1. import pandas as pd  
  2. import numpy as np  
  3. p1 = pd.Series([2, 4, 6, 8, 10])  
  4. p2 = pd.Series([8, 10, 12, 14, 16])  
  5. p1[~p1.isin(p2)]  
  6. p_u = pd.Series(np.union1d(p1, p2))  # union  
  7. p_i = pd.Series(np.intersect1d(p1, p2))  # intersect  
  8. p_u[~p_u.isin(p_i)]  

Output:

0     2
1     4
2     6
5    12
6    14
7    16
dtype: int64

21) How to get the minimum, 25th percentile, median, 75th, and max of a numeric series?

We can compute the minimum, 25th percentile, median, 75th, and maximum of p as below example:

  1. import pandas as pd  
  2. import numpy as np  
  3. p = pd.Series(np.random.normal(14, 6, 22))  
  4. state = np.random.RandomState(120)  
  5. p = pd.Series(state.normal(14, 6, 22))  
  6. np.percentile(p, q=[0, 25, 50, 75, 100])  

Output:

array([ 4.61498692, 12.15572753, 14.67780756, 17.58054104, 33.24975515])

22) How to get frequency counts of unique items of a series?

We can calculate the frequency counts of each unique value p as below example:

  1. import pandas as pd  
  2. import numpy as np  
  3. p= pd.Series(np.take(list(‘pqrstu’), np.random.randint(6, size=17)))  
  4. p = pd.Series(np.take(list(‘pqrstu’), np.random.randint(6, size=17)))  
  5. p.value_counts()  

Output:

s    4
r    4
q    3
p    3
u    3

23) How to convert a numpy array to a dataframe of given shape?

We can reshape the series p into a dataframe with 6 rows and 2 columns as below example:

  1. import pandas as pd  
  2. import numpy as np  
  3. p = pd.Series(np.random.randint(1, 7, 35))  
  4. # Input  
  5. p = pd.Series(np.random.randint(1, 7, 35))  
  6. info = pd.DataFrame(p.values.reshape(7,5))  
  7. print(info)  

Output:

0  1  2  3  4
0  3  2  5  5  1
1  3  2  5  5  5
2  1  3  1  2  6
3  1  1  1  2  2
4  3  5  3  3  3
5  2  5  3  6  4
6  3  6  6  6  5

24) How can we convert a Series to DataFrame?

The Pandas Series.to_frame() function is used to convert the series object to the DataFrame.

  1. Series.to_frame(name=None)  

name: Refers to the object. Its Default value is None. If it has one value, the passed name will be substituted for the series name.

  1. s = pd.Series([“a”, “b”, “c”],    
  2. name=”vals”)    
  3. s.to_frame()    

Output:

       vals
0          a
1          b
2          c

25) What is Pandas NumPy array?

Numerical Python (Numpy) is defined as a Python package used for performing the various numerical computations and processing of the multidimensional and single-dimensional array elements. The calculations using Numpy arrays are faster than the normal Python array.


26) How can we convert DataFrame into a NumPy array?

For performing some high-level mathematical functions, we can convert Pandas DataFrame to numpy arrays. It uses the DataFrame.to_numpy() function.

The DataFrame.to_numpy() function is applied to the DataFrame that returns the numpy ndarray.

  1. DataFrame.to_numpy(dtype=None, copy=False)    

27) How can we convert DataFrame into an excel file?

We can export the DataFrame to the excel file by using the to_excel() function.

To write a single object to the excel file, we have to specify the target file name. If we want to write to multiple sheets, we need to create an ExcelWriter object with target filename and also need to specify the sheet in the file in which we have to write.


28) How can we sort the DataFrame?

We can efficiently perform sorting in the DataFrame through different kinds:

  • By label
  • By Actual value

By label

The DataFrame can be sorted by using the sort_index() method. It can be done by passing the axis arguments and the order of sorting. The sorting is done on row labels in ascending order by default.

By Actual Value

It is another kind through which sorting can be performed in the DataFrame. Like index sorting, sort_values() is a method for sorting the values.

It also provides a feature in which we can specify the column name of the DataFrame with which values are to be sorted. It is done by passing the ‘by‘ argument.


29) What is Time Series in Pandas?

The Time series data is defined as an essential source for information that provides a strategy that is used in various businesses. From a conventional finance industry to the education industry, it consists of a lot of details about the time.

Time series forecasting is the machine learning modeling that deals with the Time Series data for predicting future values through Time Series modeling.


30) What is Time Offset?

The offset specifies a set of dates that conform to the DateOffset. We can create the DateOffsets to move the dates forward to valid dates.


31) Define Time Periods?

The Time Periods represent the time span, e.g., days, years, quarter or month, etc. It is defined as a class that allows us to convert the frequency to the periods.


32) How to convert String to date?

The below code demonstrates how to convert the string to date:

  1. fromdatetime import datetime    
  2.     
  3. # Define dates as the strings       
  4. dmy_str1 = ‘Wednesday, July 14, 2018’    
  5. dmy_str2 = ’14/7/17′    
  6. dmy_str3 = ’14-07-2017′    
  7.     
  8. # Define dates as the datetime objects    
  9. dmy_dt1 = datetime.strptime(date_str1, ‘%A, %B %d, %Y’)    
  10. dmy_dt2 = datetime.strptime(date_str2, ‘%m/%d/%y’)    
  11. dmy_dt3 = datetime.strptime(date_str3, ‘%m-%d-%Y’)    
  12.     
  13. #Print the converted dates    
  14. print(dmy_dt1)    
  15. print(dmy_dt2)    
  16. print(dmy_dt3)    

Output:

2017-07-14 00:00:00
2017-07-14 00:00:00
2018-07-14 00:00:00

33) What is Data Aggregation?

The main task of Data Aggregation is to apply some aggregation to one or more columns. It uses the following:

  • sum: It is used to return the sum of the values for the requested axis.
  • min: It is used to return a minimum of the values for the requested axis.
  • max: It is used to return a maximum values for the requested axis.

34) What is Pandas Index?

Pandas Index is defined as a vital tool that selects particular rows and columns of data from a DataFrame. Its task is to organize the data and to provide fast accessing of data. It can also be called a Subset Selection.


35) Define Multiple Indexing?

Multiple indexing is defined as essential indexing because it deals with data analysis and manipulation, especially for working with higher dimensional data. It also enables us to store and manipulate data with the arbitrary number of dimensions in lower-dimensional data structures like Series and DataFrame.


36) Define ReIndexing?

Reindexing is used to change the index of the rows and columns of the DataFrame. We can reindex the single or multiple rows by using the reindex() method. Default values in the new index are assigned NaN if it is not present in the DataFrame.

DataFrame.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None)


37) How to Set the index?

We can set the index column while making a data frame. But sometimes, a data frame is made from two or more data frames, and then the index can be changed using this method.


38) How to Reset the index?

The Reset index of the DataFrame is used to reset the index by using the ‘reset_index‘ command. If the DataFrame has a MultiIndex, this method can remove one or more levels.


39) Describe Data Operations in Pandas?

In Pandas, there are different useful data operations for DataFrame, which are as follows:

  • Row and column selection

We can select any row and column of the DataFrame by passing the name of the rows and columns. When you select it from the DataFrame, it becomes one-dimensional and considered as Series.

  • Filter Data

We can filter the data by providing some of the boolean expressions in DataFrame.

  • Null values

A Null value occurs when no data is provided to the items. The various columns may contain no values, which are usually represented as NaN.


40) Define GroupBy in Pandas?

In Pandas, groupby() function allows us to rearrange the data by utilizing them on real-world data sets. Its primary task is to split the data into various groups. These groups are categorized based on some criteria. The objects can be divided from any of their axes.

DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)

Selenium with Python Interview Questions

Frequently asked Interview Question and Answer in Selenium with Python suites for both Freshers and Experienced Candidates.

1) What Is Python? What Are The Benefits Of Using Python?

Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.

2) How Python Can Be Used In Software Testing?

  • To generate test data; parse test results; generate reports; testing API calls etc.
  • Python to extract requirements from a Word document.
  • For testing tasks automation, setting up environments for tests, extracting performance data, etc…
  • Testers use Python extensively in many companies with Selenium for test automation.
  • For writing desktop applications used by testers.
  • Test data manipulation.
  • To build test environment
  • Testing with IronPython on .NET

3) What Python Frameworks Do You Know?

Framework called Web2py, PAMIE (Python automation Module for I. E.), The py.test framework

4) What Tools That Helps Python Development Do You Know?

There are good tools for helping Python development such as Notepad++ with the PyNPP plugin and Eclipse with PyDev and PyUnit

5) What Is A “unittest” In Python?

The unit testing framework of Python is known as “unittest”.  It supports the sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections, among others.

6) How Python Is Interpreted?

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

7) What Is The Difference Between “xrange” And “range”?

“Xrange” returns the “Xrange” object while range returns the “list” irrespective of the size of the “range”.

8) Define “module” And “package”?

  • Each Python program file is a “module”, which imports other modules like “objects” and “attributes”.
  • A Python program folder is a “package” of “modules”.  A package can have “modules” or “subfolders”.

9) Why my pip is not working when my python is not installed properly?

The executable path is not set properly.

10) What is the commands for downloading selenium?

  • pip install –U selenium
  • sudo pip install python

11) How can we know that our python is properly installed or not?

pip –version

12) How can we implement unittest framework in our scripts?

By using:- import unittest

13) What are the different locators used?

  1. Tag name
  2. Class name
  3. id
  4. link text
  5. Partial link text
  6. CSS Selector
  7. XPath
  8. Name

14) Which is the slowest locator?

Xpath.

15) Which is the best locator?

The selection of the best locator depends on the web elements or the ui page we are automating.

16) What is the library to be imported to add keyboard actions to our scripts?

from selenium.webdriver.common.keys import Keys

17) What is the library to be imported to add mouse actions to our scripts?

from selenium.webdriver.common.actionchains import ActionChains

18) What is Selenium?

It’s a Automation toolkit

19) What is python?

Iit’s a scripting language, it works as an interpreter and not a compiler

20) What is a locator?

It’s an element in web page with which the python script would interact through the selenium driver

21) What is a Webdriver?

Selenium provides a tool to interact with the different web browsers. And they control the operation of the script. Ex: chromedriver, Iedriver, gecko for firefox.

22) Whats XPATH?

It is the extensible markup language’s path finder where the data is stored in XML format like Key value pair

23) Whats the difference between / and // in xpath?

/ : absolute path // relative path

24) Whats explicit and implicit wait?

Explicit wait makes the browser wait for a given duration or the condition is true else, it will throw a time exceeded exception

Implicit wait- will make the browser wait for a defined time and the execution continues

25) What are window handles?

During the script execution if there is a new window that pops up then they have an address and they have a handle, each handle is listed in the variable handles[]

Ex: To reference those windows driver.switch_window(browser.wondow(handle[0]))

26) What are alerts and how do you handle?

Alerts are the popup windows that you get when there is notification to the user,

Handling them: alert_var = browser.switch_to_alert()

To dismiss: alert_var.dismiss()

To accept: alert_var.accept() etc

Get Selenium with Python 100% Practical Training

27) How to find element by hyperlink?

Find_element_by_link_text(“text of that hyperlink”).click()

28) How do you write the text in the login form?

Find_element_by_id(“username_field”).send_keys(“USERNAME”)

29) What is the difference between close() and quit() func of the browser?

Browser.close() will close the current executing window and you can always switch to other window handles even after closing currently active one.Browser.quit() – will close the complete browser with all the open windows, this func handle and makes sure the processes are closed and terminated correctly without any memory leaks.

30) When webpage is dynamic which element locater do we use to locate an element?

driver.findElementByXpath()

31) How do we define a function in Python ?

def functionName: Function body

32) What is an indentation in python?

Python does not use braces to indicate the start & stop of function. It uses indentation (Whitespaces) to make compiler understand start & stop of function.

33) What is the syntax for “for” loop if we have to run for loop for 3 times?

for 1 in 5:Print(“)

34) What is WebDriver in selenium?

WebDriver is a plugin that helps to run selenium test scripts on a web browser.

35)What is the WebDriver used to run selenium script on chrome browser?

chrome driver

36) What type of languages can we use to write selenium scripts?

We can use any scripting language.

Get Selenium with Python Online Training

37) Can I use selenium for automation scripting without selenium IDE?

Yes, selenium can be imported as a module in any other programming platform & write selenium test scripts.

38) What is the use of automation testing?

It will reduce manpower & it also reduces the time that we spend on doing manual testing every time.

39) Can we do data-driven testing using selenium?

Yes, bypassing values as parameters during run time.

40) Is selenium helpful for standalone application testing?

No, Selenium is only used as a test automation tool for web driver applications.

41) Why you prefer to use Python for Selenium?

Python is not very large or complicated and one of the easy-to-use programming languages. Python APIs permit us to connect to the browser through Selenium. Selenium can convey normal Python commands to various browsers, in spite of the disparities in browser design.

42) What versions are there of Selenium?

Selenium WebDriver – Used for the automation of tests in web applications.

Selenium IDE – Firefox plugin to record and run tests.

Selenium Grid – Allows you to run Selenium tests in parallel through multiple machines.

43) What programming languages does Selenium Webdriver support?

Languages supported are: Java, C #, PHP, Ruby, Python.

44) What kind of tests can we perform with Selenium Webdriver?

We can perform functional and regression tests on web applications.

45) What are the limitations of Selenium?

The main limitations of selenium are:

You can only perform tests in web applications, not for desktop or mobile. (But other tools are available to automate desktop application GUI tests.)

Captcha and barcode reading cannot be automated with Selenium. Manual testing is needed for them.

The user who is going to perform automatic tests with Selenium Python must have previous knowledge of Python.

46) What are the different types of locators that we can use to search for an element with Selenium?

The locators that we can use with Selenium are ID, Name, ClassName, TagName, LinkText, and Partial LinkText, XPath, CSS Selector.

47) What is an XPath?

Xpath (XML Path Language) is a language that allows you to retrieve information from an XML document by defining a syntax to set parts in an XML document, allowing you to navigate through its elements and attributes, as well as allowing basic manipulation of Booleans, numbers, and strings.

48) What is the difference between / and // in an XPath expression?

We will use / to start the selection from a node in the document. It allows us to create absolute Xpath expressions. We will use // to start the selection from anywhere in the document. It allows us to create relative Xpath expressions.

49) What are the different types of drivers currently supported by Selenium Webdriver?

The supported drivers are Gecko driver (new from Selenium 3 to create an instance of FirefoxDriver), ChromeDriver, InternetExplorerDriver, SafariDriver, OperaDriver, AndroidDriver, IPhoneDriver, and HtmlUnitDriver.

50) How can we select an option of a dropdown using Selenium Webdriver?

To be able to select the value of a dropdown using Selenium Webdriver we have to use the Select class, of Webdriver. Through this class we can select a value of a dropdown by its value, its visible text or its index number (position).

51) What is Selenium WebDriver

Selenium Web driver is set of class which used automate the web application.

52) Is Selenium Web Driver Automation Tool?

No Selenium web Driver is not an Automation tool, it’s a framework or set of class which is used to automate a web based application.

53) What kind of application best suited for Selenium and why it should be selected.

It is used to automate web based application and have browser and Platform compatiblity. It supports mulitple language such as java, C# and Python

54) Can Selenium Web Services tested using Selenium?

No it is used to automate only web based application.

56) How Can we launch Different browser using python.

For Chrome
driver=Webdriver.Chrome(“PathofChromedriver”)
For Firefox
driver=webdriver.Firefox(“Path of Firefox Driver”)
for IE
driver=webdriver.Ie(“Path of IE Driver”)

57) How Synchronization works in Selenium.

Synchronization is achieved using Implict Wait and Explicit Wait.

58) What is Implicit Wait.

Implicit Wait is used to default waiting time.

59) What is explicity Wait.

Explicit Wait is used to halt the execution untill condition is met or when time is elasped.

60) How can enter the values in text box using python.

driver.find_element(By.ID,”Value”).send_keys(“Value”)

61) How can we check if control enabled or not?

driver.find_element(By.ID,”Value”).is_enabled(), this specific method will return if true or false.

62) How can we get text of a web element.

driver.find_element(By.ID,”Value”).text, this specific method will return innertext of the control.

63) Is there any other way of reteriving text of web element.

driver.find_element(By.ID,”Value”).get_attribute(“InnerText”)

64) What are the different ways of selecting the values in dropdown.

  • SelectByValue: select the option based on option value.
  • selectByVisibleText: selects the option based on visible text.
  • selectByIndex: selects the option base on Index

65) what are the different Navigation command in selenium

it is used to refresh
driver.refresh()
it is used to navigate back
driver.back()
it is used to move forward
driver.forward()

66) What is the difference b/w findelement and findelements

  • FindElement returns first matching element.
  • FindElements returns more than one elements.

67) what is the difference b/w Driver.Close and Diver.quit

  • close is used to close the entire browser
  • quit is used to close the working tab.

68) Can selenium handle the windows pop up?

No Selenium can’t handle windows pop Up

69) Can selenium handle WebBased Pop Up.

Yes it can handle webbased pop up using “driver.switch_to_alert()”

70) How can capture screenshot in selenium.

driver.get_screenshot_as_file(“filename”) with this method we can take screen shot.

71) What are switch Class in selenium.

Switch class are used to switch between the different browser,frames and alert pop up.

72) What Action class in selenium

ACtion class is user facing API to achieve complex user action events.

73) How can we perform drag drop in selenium

act=ActionChains(driver)

act.drag_and_drop(sourcelement,targetelement), with this method we can perform drag and drop

74) How can mouse hover on a control in selenium.

act=ActionChains(driver)
act.move_to_element(element)
with the above method we mouse hover on element, element argument is web element where we need to mouse hover.

75) Can we move the mouse control to specific cooridinate in selenium

yes we can, selenium provides Action class in which we can make use of the act.move_by_offset() method to move the mouse control to specific cooridinates.

76) Write a method to read data from webtable for specific row and column index using selenium.

def GetData(rowIndex,colIndex):
tablerows=driver.find_element_by_id(“IdValue”).find_elements_by_tag_name(“tr”)
tableDefinitons=tablerows[rowIndex+1].find_elements_by_tag_name(“td”)
return tableDefinitons[colIndex].get_attribute(“innerText”)

77) What are Python unitTest default methods

#Will execute before the execution of each test method
def setUp(self):
pass

# will execute once before it executes any test methods
def setUpClass(cls):
pass
#will execute after the execution of each test method
def tearDown(self):
pass
# will execute after it executes all the test methods.
def tearDownClass(cls):
pass

78) How will install selenium in python

We will use PIP command to install selenium
Pip install selenium Version_Nos

79) What is pass in python.

pass means no operation to be done

80) How can we convert string to int in python.

using int(“23″) to convert to int.
str(23) to convert to string

81) How will you handle exception in python

try,except and finally key word is used to handle the exception

try:
#code
except: #catches the exception
finally: #executes the block whether any exception is raised or not.

82) What are the different data types supported in python

integer,string,float and complex are the supported data types in python

83) What is MRO in python

Method Resolution order is used in inheritance concepts
where class is inheriting multiple class and in all the parent class, same method is defined. Child class is confused which method to call during run time. So the MRO helps to resolve the issue.

84) How will identify when web element doesn’t have any of the unique locater.

we can make use of the get_attribute method to get web element from list of web elements.

for control in controls:
if control.get_attribute(“attributename”)==”attributeValue”:
#found the matching control

85) How to execute java script in selnium with python

driver.execute_script(script)
above method will execute the java script.

86) What are the differnt way entering value TextBox

  • find_element_by_id(“val”).send_keys(“valuetoebeentered”)
  • other is using Action Class
    act=ActionChains(driver)
    send_keys_to_element(control,”Valuetobeenterd”)

87) What is the use of Xpath

xpath is used to find the web element in webpage.

88) What are the different exception in selenium

  • webdriver exception
  • noalertPresent Exception
  • nosuchwindow Exception
  • nosuchelement exception
  • timeoutexception

89) How will perform double click on web element

act=ActionChains(driver)
act.double_click(control)
Above method will be used to double click on the control.

90) How will you handle multiple windows in selenium

we can use “switch_to_window” method to switch between the multiple windows. where in argument we would be sending the address of the window in the form of string.

91) What is framework?

Framework defines a set of rules or best practices which we can follow in systematic way to achieve the desired results.

92) What are the different automation Frameworks

  • Data Driven Framework
  • Key Driven Framework
  • Hybrid Framework

93) write a program for the below pattern with only one while loop

*
**
***
****
*****
****
***
**
*
> a = 0
bool = True
While(a<=5):
if(a<0): break; if(a==5): bool = False if(bool): a = a + 1 else: a = a – 1 print(“*”*a)

94) What is the difference between Assert and Verify?

Assert it is used to verify the result. If the test case fails then it will stop the execution of the test case there itself and move the control to another test case.

Verify it is also used to verify the result. If the test case fails then it will not stop the execution of that test case.

95) Why should Selenium be selected as a test tool?

Selenium is free and open source have a large user base and helping communities have cross Browser compatibility (Firefox, chrome, Internet Explorer, Safari etc.) have great platform compatibility (Windows, Mac OS, Linux etc.)supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.) has fresh and regular repository developments supports distributed testing

96) What are the testing types that can be supported by Selenium?

Selenium supports the following types of testing:
• Functional Testing
• Regression Testing

97) When should I use Selenium IDE?

Selenium IDE is the simplest and easiest of all the tools within the Selenium Package. Its record and playback feature makes it exceptionally easy to learn with minimal acquaintances to any programming language. Selenium IDE is an ideal tool for a naïve user.

98) What is Java implementation of Python popularly know?

Jython.

99) What is used to create unicode strings in Python?

Add u before the string u ‘mystring’

100) Explain how python is interpreted.

Python program runs directly from the source code. Each type of Python program is executed code is required. Python converts source code written by the programmer into an intermediate language which is again translated into the native language machine language that is executed. So Python is an Interpreted language.

Identifiers in Groovy

Identifiers are used to define variables, functions or other user-defined variables. Identifiers start with a letter, a dollar or an underscore. They cannot start with a number. Here are some examples of valid identifiers −

def employeename 
def student1 
def student_name

where def is a keyword used in Groovy to define an identifier.

Here is a code example of how an identifier can be used in our Hello World program.

class Example {
   static void main(String[] args) {
      // One can see the use of a semi-colon after each statement
      def x = 5;
      println('Hello World'); 
   }
}

In the above example, the variable x is used as an identifier.