0% found this document useful (0 votes)
2 views

INTERVIEW QUESTIONS

This document contains a comprehensive set of C programming interview questions and answers, covering topics such as memory allocation, pointers, arrays, functions, and the differences between various C constructs. It also includes example codes for practical understanding, such as removing duplicates from an array. Additionally, it explains key concepts like recursion, storage classes, and the use of specific functions like printf() and scanf().
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

INTERVIEW QUESTIONS

This document contains a comprehensive set of C programming interview questions and answers, covering topics such as memory allocation, pointers, arrays, functions, and the differences between various C constructs. It also includes example codes for practical understanding, such as removing duplicates from an array. Additionally, it explains key concepts like recursion, storage classes, and the use of specific functions like printf() and scanf().
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

C INTERVIEW QUESTIONS

1. What is the difference between `malloc()` and `calloc()`?


- `malloc()` is used to allocate a block of memory of a specified size, while `calloc()` is used
to allocate a block of memory and initializes it to zero.
2. What is a pointer in C?
- A pointer is a variable that stores the memory address of another variable. It allows
indirect access to the memory location and enables dynamic memory allocation.
3. Explain the difference between `++i` and `i++` in C.
- `++i` is the pre-increment operator, which increments the value of `i` and returns the
incremented value.
- `i++` is the post-increment operator, which increments the value of `i` but returns the
original value before incrementing.
4. What is the `sizeof` operator used for?
- The `sizeof` operator is used to determine the size (in bytes) of a data type or variable in C
5. What is the difference between an array and a pointer?
- An array is a collection of elements of the same data type, whereas a pointer is a variable
that stores the memory address of another variable. However, in certain cases, an array name
can be treated as a pointer to its first element.
6. What is the purpose of the `const` keyword in C?
- The `const` keyword is used to declare constants in C. It specifies that the value of a
variable cannot be changed once it is assigned.
7. What is the difference between `strcpy()` and `strncpy()`?
- `strcpy()` is used to copy a string from one location to another until it reaches the null
terminator, while `strncpy()` allows you to specify the maximum number of characters to be
copied.
8. What is the purpose of the `static` keyword in C?
- The `static` keyword is used to define variables and functions with a local scope that
persist throughout the program's lifetime. It also restricts the visibility of variables and
functions to the file they are declared in.
9. What are the storage classes in C?
- C has four storage classes: `auto`, `register`, `static`, and `extern`. Each storage class
determines the scope, lifetime, and visibility of variables and functions.
10. How do you dynamically allocate memory in C?
- Dynamic memory allocation in C is done using functions like `malloc()`, `calloc()`, and
`realloc()`. These functions allow you to allocate memory during runtime and deallocate it
when it is no longer needed.

1) What is C language?

C is a mid-level and procedural programming language. The Procedural programming language is also known
as the structured programming language is a technique in which large programs are broken down into smaller
modules, and each module uses structured code. This technique minimizes error and misinterpretation

2) Why is C known as a mother language?

C is known as a mother language because most of the compilers and JVMs are written in C language. Most of
the languages which are developed after C language has borrowed heavily from it like C++, Python, Rust,
javascript, etc. It introduces new core concepts like arrays, functions, file handling which are used in these
languages.

3) Why is C called a mid-level programming language?

C is called a mid-level programming language because it binds the low level and high -level programming
language. We can use C language as a System programming to develop the operating system as well as an
Application programming to generate menu driven customer driven billing system.

6) What are the features of the C language?

o Simple: C is a simple language because it follows the structured approach, i.e., a program is broken into parts

o Portable: C is highly portable means that once the program is written can be run on any machine with little or no

modifications.

o Mid Level: C is a mid-level programming language as it combines the low- level language with the features of the

high-level language.

o Structured: C is a structured language as the C program is broken into parts.

o Fast Speed: C language is very fast as it uses a powerful set of data types and operators.

o Memory Management: C provides an inbuilt memory function that saves the memory and improves the

efficiency of our program.

o Extensible: C is an extensible language as it can adopt new features in the future.

7) What is the use of printf() and scanf() functions?

printf(): The printf() function is used to print the integer, character, float and string values on to the screen.

Following are the format specifier:

o %d: It is a format specifier used to print an integer value.


o %s: It is a format specifier used to print a string.

o %c: It is a format specifier used to display a character value.

o %f: It is a format specifier used to display a floating point value.

scanf(): The scanf() function is used to take input from the user.

8) What is the difference between the local variable and global variable in C?

Basis for Local variable Global variable


comparison

Declaration A variable which is declared inside function or block A variable which is declared outside function or block is
is known as a local variable. known as a global variable.

Scope The scope of a variable is available within a function The scope of a variable is available throughout the
in which they are declared. program.

Access Variables can be accessed only by those statements Any statement in the entire program can access variables.
inside a function in which they are declared.

Life Life of a variable is created when the function block Life of a variable exists until the program is executing.
is entered and destroyed on its exit.

Storage Variables are stored in a stack unless specified. The compiler decides the storage location of a variable.

9) What is the use of a static variable in C?

A variable which is declared as static is known as a static variable. The static variable retains its value between multiple
function calls. The static variable is initially initialized to zero. If we update the value of a variable, then the updated value is
assigned.

10) What is the use of the function in C?

o C functions are used to avoid the rewriting the same code again and again in our program.

o C functions can be called any number of times from any place of our program.

o When a program is divided into functions, then any part of our program can easily be tracked.

o C functions provide the reusability concept, i.e., it breaks the big task into smaller tasks so that it makes the C

program more understandable.

11) What is the difference between call by value and call by reference in C?
Call by value Call by reference

Description When a copy of the value is passed to the function, then When a copy of the value is passed to the function,
the original value is not modified. then the original value is modified.

Memory Actual arguments and formal arguments are created in Actual arguments and formal arguments are created
location separate memory locations. in the same memory location.

Safety In this case, actual arguments remain safe as they cannot In this case, actual arguments are not reliable, as they
be modified. are modified.

Arguments The copies of the actual arguments are passed to the The addresses of actual arguments are passed to their
formal arguments. respective formal arguments.

12) What is recursion in C?

When a function calls itself, and this process is known as recursion. The function that calls itself is known as a
recursive function.

Recursive function comes in two phases:

Winding phase: When the recursive function calls itself, and this phase ends when the condition is reached.

Unwinding phase: Unwinding phase starts when the condition is reached, and the control returns to the original
call.

13) What is an array in C?

An Array is a group of similar types of elements. It has a contiguous memory location. It makes the code
optimized, easy to traverse and easy to sort. The size and type of arrays cannot be changed after its declaration.

Arrays are of two types:

One-dimensional array: One-dimensional array is an array that stores the elements one after the another.

Syntax: data_type array_name[size];

Multidimensional array: Multidimensional array is an array that contains more than one array.

Syntax: data_type array_name[size];

14) What is a pointer in C?

A pointer is a variable that refers to the address of a value. It makes the code optimized and makes the
performance fast. Whenever a variable is declared inside a program, then the system allocates some memory to
a variable. The memory contains some address number. The variables that hold this address number is known as
the pointer variable.

15) What is the usage of the pointer in C?


o Accessing array elements: Pointers are used in traversing through an array of integers and strings. The string is an

array of characters which is terminated by a null character '\0'.

o Dynamic memory allocation: Pointers are used in allocation and deallocation of memory during the execution of

a program.

o Call by Reference: The pointers are used to pass a reference of a variable to other function.

o Data Structures like a tree, graph, linked list, etc.: The pointers are used to construct different data structures

like tree, graph, linked list, etc.

16) What is a NULL pointer in C?

A pointer that doesn't refer to any address of value but NULL is known as a NULL pointer. When we assign a
'0' value to a pointer of any type, then it becomes a Null pointer.

17) What is a far pointer in C?

A pointer which can access all the 16 segments (whole residence memory) of RAM is known as far pointer. A
far pointer is a 32-bit pointer that obtains information outside the memory in a given section.

18) What is dangling pointer in C?

o If a pointer is pointing any memory location, but meanwhile another pointer deletes the memory occupied by the

first pointer while the first pointer still points to that memory location, the first pointer will be known as a dangling

pointer. This problem is known as a dangling pointer problem.

o Dangling pointer arises when an object is deleted without modifying the value of the pointer. The pointer points to

the deallocated memory.

o How to overcome the problem of a dangling pointer

o The problem of a dangling pointer can be overcome by assigning a NULL value to the dangling pointer

19) What is pointer to pointer in C?

In case of a pointer to pointer concept, one pointer refers to the address of another pointer. The pointer to pointer
is a chain of pointers. Generally, the pointer contains the address of a variable. The pointer to pointer contains
the address of a first pointer.

20) What is static memory allocation?

o In case of static memory allocation, memory is allocated at compile time, and memory can't be increased while

executing the program. It is used in the array.

o The static memory is allocated using static keyword.

o The static memory is implemented using stacks or heap.


o The static memory is faster than dynamic memory.

21) What is dynamic memory allocation?

o In case of dynamic memory allocation, memory is allocated at runtime and memory can be increased while

executing the program. It is used in the linked list.

o The malloc() or calloc() function is required to allocate the memory at the runtime.

o An allocation or deallocation of memory is done at the execution time of a program.

int *p= malloc(sizeof(int)*10);

22) What functions are used for dynamic memory allocation in C language?

1. malloc()
o The malloc() function is used to allocate the memory during the execution of the program.

o It does not initialize the memory but carries the garbage value.

o It returns a null pointer if it could not be able to allocate the requested space.

Syntax = ptr = (cast-type*) malloc(byte-size)

2. calloc()

o The calloc() is same as malloc() function, but the difference only is that it initializes the memory with

zero value.

Syntax = ptr = (cast-type*)calloc(n, element-size);

3. realloc()

o The realloc() function is used to reallocate the memory to the new size.If sufficient space is not available

in the memory, then the new block is allocated to accommodate the existing data.

Syntax =ptr = realloc(ptr, newsize.

4. free():

 The free() function releases the memory allocated by either calloc() or malloc() function.

Syntax = free(ptr);

23) What is the difference between malloc() and calloc()?


calloc() malloc()

Description The malloc() function allocates a single block of The calloc() function allocates multiple blocks of
requested memory. requested memory.

Initialization It initializes the content of the memory to zero. It does not initialize the content of memory, so it
carries the garbage value.

Number of It consists of two arguments. It consists of only one argument.


arguments

Return value It returns a pointer pointing to the allocated memory. It returns a pointer pointing to the allocated memory.

24) What is the structure?

o The structure is a user-defined data type that allows storing multiple types of data in a single unit. It occupies the

sum of the memory of all members.

o The structure members can be accessed only through structure variables.

o Structure variables accessing the same structure but the memory allocated for each variable will be different.

25) What is a union?

o The union is a user-defined data type that allows storing multiple types of data in a single unit. However, it doesn't

occupy the sum of the memory of all members. It holds the memory of the largest member only.

o In union, we can access only one variable at a time as it allocates one common space for all the members of a

union.

26) What is an auto keyword in C?

In C, every local variable of a function is known as an automatic (auto) variable. Variables which are declared
inside the function block are known as a local variable. The local variables are also known as an auto variable. It
is optional to use an auto keyword before the data type of a variable. If no value is stored in the local variable,
then it consists of a garbage value.

27) What is the purpose of sprintf() function?

The sprintf() stands for "string print." The sprintf() function does not print the output on the console screen. It
transfers the data to the buffer. It returns the total number of characters present in the string.

Syntax = int sprintf ( char * str, const char * format, ... );

29) What is a token?


The Token is an identifier. It can be constant, keyword, string literal, etc. A token is the smallest individual unit
in a program. C has the following tokens:

1. Identifiers: Identifiers refer to the name of the variables.

2. Keywords: Keywords are the predefined words that are explained by the compiler.

3. Constants: Constants are the fixed values that cannot be changed during the execution of a program.

4. Operators: An operator is a symbol that performs the particular operation.

5. Special characters: All the characters except alphabets and digits are treated as special characters.

30) What is command line argument?

The argument passed to the main() function while executing the program is known as command line argument.
For example:

32) What is the difference between getch() and getche()?

The getch() = function reads a single character from the keyboard. It doesn't use any buffer, so entered data will
not be displayed on the output screen.

The getche() = function reads a single character from the keyword, but data is displayed on the output screen.
Press Alt+f5 to see the entered character.

C INTERVIEW CODES
39. How can you remove duplicates in an array?

#include <stdio.h>

int main() {
int n, a[100], b[100], calc = 0, i, j,count;
printf("Enter no. of elements in array: ");
scanf("%d", &n);
printf("Enter %d integers: ", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);

for (i = 0; i<n; i++) {


for (j = 0; j<calc; j++) {
if(a[i] == b[j])
break;
}
if (j== calc) {
b[calc] = a[i];
calc++;
}
}

printf("Array obtained after removing duplicate elements: ");


for (i = 0; i<calc; i++) {
printf("%d ", b[i]);
}
return 0;
}

42. How do you override a defined macro?

To override a defined macro we can use #ifdef and #undef preprocessors as follows:

 #ifdef A
 #undef A
 #endif
 #define A 10

If macro A is defined, it will be undefined using undef and then defined again using define.

43. Write a C program to check if it is a palindrome number or not using a recursive


method.

#include <stdio.h>
#include <conio.h>
int reverse(int num);
int isPalindrome(int num);
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(isPalindrome(num) == 1)
{
printf("the given number is a palindrome");
}
else
{
printf("the given number is not a palindrome number");
}
return 0;
}

int isPalindrome(int num)


{
if(num == reverse(num))
{
return 1;
}
return 0;
}
int reverse(int num)
{
int rem;
static int sum=0;
if(num!=0){
rem=num%10;
sum=sum*10+rem;
reverse(num/10);
}
else
return sum;
return sum;
}

44. C program to check the given number format is in binary or not.

#include<stdio.h>
#include<conio.h>
int main() {
int j,num;
printf("Please enter a number :");
scanf("%d",&num);
while(num>0)
{
j=num%10;
if( j!=0 && j!=1 )
{
printf("num is not binary");
break;
}
num=num/10;
if(num==0)
{
printf("num is binary");
}
}
getch();
}

45. C Program to find a sum of digits of a number using recursion.

#include<stdio.h>
#include<conio.h>

int sumOfDigits(int num)


{
static int sum = 0;
int rem;
sum = sum + (num%10);
rem = num/10;
if(rem > 0)
{
sumOfDigits(rem);
}
return sum;
}
int main() {
int j,num;
printf("Please enter a number :");
scanf("%d",&num);
printf("sum of digits of the number = %d ",sumOfDigits(num));
getch();
}

47. What is the use of a semicolon (;) at the end of every program statement?
It is majorly related to how the compiler reads( or parses) the entire code and breaks it into a set of
instructions(or statements), to which semicolon in C acts as a boundary between two sets of
instructions.

49. Differentiate between the macros and the functions.

The differences between macros and functions can be explained as follows:

Macros Functions
It is preprocessed rather than compiled. It is compiled not preprocessed.
It is preprocessed rather than compiled. Function checks for compilation errors.
Code length is increased. Code length remains the same.
Macros are faster in execution. Functions are a bit slower in execution.
Macros are useful when a small piece of code is Functions are helpful when a large piece of code
used multiple times in a program. is repeated a number of times.

50. Differentiate Source Codes from Object Codes

Source Code = is a collection of computer instructions written using a human-readable programming


language and Source Code is modified, each time the Source Code needs to be compiled to reflect the
changes in the Object Code.

Object Code = is a sequence of statements in machine language, and is the output after the compiler
or an assembler converts the Source Code and Object Code is the way the changes are reflected.

51. What are header files and what are its uses in C programming?

In C header files must have the extension as .h, which contains function definitions, data type
definitions, macro, etc. The header is useful to import the above definitions to the source code using
the #include directive. For example, if your source code needs to take input from the user do some
manipulation and print the output on the terminal, it should have stdio.h file included as #include
<stdio.h>, with which we can take input using scanf() do some manipulation and print using printf().

52. When is the "void" keyword used in a function

The keyword “void” is a data type that literally represents no data at all. The most obvious use of this
is a function that returns nothing:

void PrintHello()
{
printf("Hello\n");
return; // the function does "return", but no value is returned
}

Here we’ve declared a function, and all functions have a return type. In this case, we’ve said the
return type is “void”, and that means, “no data at all” is returned.
The other use for the void keyword is a void pointer. A void pointer points to the memory location
where the data type is undefined at the time of variable definition. Even you can define a function of
return type void* or void pointer meaning “at compile time we don’t know what it will return” Let’s
see an example of that.

void MyMemCopy(void* dst, const void* src, int numBytes)


{
char* dst_c = reinterpret_cast<char*>(dst);
const char* src_c = reinterpret_cast<const char*>(src);
for (int i = 0; i < numBytes; ++i)
dst_c[i] = src_c[i];
}

53. What is dynamic data structure?

A dynamic data structure (DDS) refers to an organization or collection of data in memory that has the
flexibility to grow or shrink in size, enabling a programmer to control exactly how much memory is
utilized. Dynamic data structures change in size by having unused memory allocated or de-allocated
from the heap as needed.

Dynamic data structures play a key role in programming languages like C, C++, and Java because
they provide the programmer with the flexibility to adjust the memory consumption of software
programs.

54. Add Two Numbers Without Using the Addition Operator

For the sum of two numbers, we use the addition (+) operator. In these tricky C programs, we will
write a C program to add two numbers without using the addition operator.

#include<stdio.h>
#include<stdlib.h>
int main()
{
int x, y;
printf("Enter two number: ");
scanf("%d %d",&x,&y);

// method 1
printf("%d\n", x-(-y));

// method 2
printf("%d\n", -(-x-y));

// method 3
printf("%d\n", abs(-x-y));

// method 4
printf("%d", x-(~y)-1);

return 0;
}

55. Subtract Two Number Without Using Subtraction Operator

#include<stdio.h>
#include<stdlib.h>
int main()
{
int x, y;
printf("Enter two number: ");
scanf("%d %d",&x,&y);
printf("%d", x+(~y)+1);
return 0;
}

The bitwise complement operator is used in this program. The bitwise complement of number ~y=-
(y+1). So, expression will become x+(-(y+1))+1=x-y-1+1=x-y
56. Multiply an Integer Number by 2 Without Using Multiplication Operator

#include<stdio.h>
int main()
{
int x;
printf("Enter a number: ");
scanf("%d",&x);
printf("%d", x<<1);
return 0;
}

The left shift operator shifts all bits towards the left by a certain number of specified bits. The
expression x<<1 always returns x*2. Note that the shift operator doesn’t work on floating-point
values.

For multiple of x by 4, use x<<2. Similarly x<<3 multiply x by 8. For multiple of the number x by
2^n, use x<<n.

57. Check whether the number is EVEN or ODD, without using any arithmetic or
relational operators

#include<stdio.h>
int main()
{
int x;
printf("Enter a number: ");
scanf("%d", &x);
(x&1)?printf("Odd"):printf("Even");
return 0;
}

The bitwise and(&) operator can be used to quickly check the number is odd or even.

58. Reverse the Linked List. Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1-


>NULL

Assume that we have linked list 1 → 2 → 3 → Ø, we would like to change it to Ø ← 1 ← 2 ← 3.

While you travel the linked list, change the current node's next pointer to point to its previous
element. reference to the previous nodes should be stored into a temp variable as shown so that we
don’t lose track of the swapped node. You also need another pointer to store the next node before
changing the reference. Also when we are done return the new head of the reversed list.

/* Function to reverse the linked list */


static void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next;
while (current != NULL)
{
// store next
next = current->next;

// reverse curr node pointer


current->next = prev;
// move pointer one position ahead
prev = current;
current = next;
}
*head_ref = prev;
}

60. Program to find n’th Fibonacci number

Fibonacci sequence is characterized by the fact that every number after the first two is the sum of the
two preceding ones. For example, consider below sequence

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . .. and so on

Where in F{n} = F{n-1} + F{n-2} with base values F(0) = 0 and <code>F(1) = 1

Below is naive implementation for finding the nth member of the Fibonacci sequence

// Function to find the nth Fibonacci number


int fib(int n)
{
if (n <= 1) {
return n;
}

return fib(n - 1) + fib(n - 2);


}

int main()
{
int n = 8;

printf("nth Fibonacci number is %d", fib(8));

return 0;
}

62. Merge Two sorted Linked List

Merge two sorted linked lists and return them as a sorted list. The list should be made by splicing
together the nodes of the first two lists.

Merging Two Sorted Linked List


NodePtr merge_sorted(NodePtr head1, NodePtr head2) {

// if both lists are empty then merged list is also empty


// if one of the lists is empty then other is the merged list
if (head1 == nullptr) {
return head2;
} else if (head2 == nullptr) {
return head1;
}

NodePtr mergedHead = nullptr;


if (head1->data <= head2->data) {
mergedHead = head1;
head1 = head1->next;
} else {
mergedHead = head2;
head2 = head2->next;
}

NodePtr mergedTail = mergedHead;

while (head1 != nullptr && head2 != nullptr) {


NodePtr temp = nullptr;
if (head1->data <= head2->data) {
temp = head1;
head1 = head1->next;
} else {
temp = head2;
head2 = head2->next;
}

mergedTail->next = temp;
mergedTail = temp;
}

if (head1 != nullptr) {
mergedTail->next = head1;
} else if (head2 != nullptr) {
mergedTail->next = head2;
}

return mergedHead;
}

C++ INTERVIEW QUESTIONS

1. What is C++?
C++ is a general-purpose, high-level programming language that was developed as an
extension of the C programming language. It provides additional features such as object-
oriented programming, templates, and standard libraries.
2. What are the differences between C and C++?
C++ is an extension of the C language and includes additional features like classes and
objects, inheritance, polymorphism, and exception handling. C++ also supports function
overloading, namespaces, and the Standard Template Library (STL), which are not present in
C.
3. What are the basic principles of object-oriented programming (OOP)?
The basic principles of OOP are encapsulation, inheritance, and polymorphism.
Encapsulation refers to the bundling of data and methods into a single unit (class), inheritance
allows the creation of new classes based on existing classes, and polymorphism enables
objects of different types to be treated as objects of a common base class.
4. What is the difference between a class and an object?
A class is a blueprint or template that defines the properties and behaviors of objects. It
describes the structure, data members, member functions, and accessibility of the objects. An
object is an instance of a class that can be created using the class blueprint. Multiple objects
can be created from a single class.
5. What is function overloading?
Function overloading allows multiple functions with the same name but different parameters
to exist in the same scope. The compiler differentiates between the functions based on the
number, type, and order of the parameters. This enables programmers to use the same
function name for different behaviors.
6. What is a constructor? How is it different from a regular member function?
A constructor is a special member function of a class that is automatically called when an
object of that class is created. It is used to initialize the object's data members. Unlike regular
member functions, constructors have the same name as the class and do not have a return
type.
7. What is dynamic memory allocation in C++?
Dynamic memory allocation refers to the allocation and deallocation of memory at runtime
using operators like `new` and `delete`. It allows you to allocate memory for variables and
objects when their sizes are not known at compile time. The dynamically allocated memory
must be manually deallocated to avoid memory leaks.
8. What are the storage classes in C++?
C++ provides four storage classes: `auto`, `static`, `register`, and `extern`.
- `auto`: It is the default storage class for local variables. The variables are automatically
created and destroyed within their scope.
- `static`: It creates variables that persist throughout the program's execution. Static variables
are initialized only once and retain their values between function calls.
- `register`: It suggests that a variable be stored in a register for faster access. However, the
compiler ultimately decides whether to honor the request.
- `extern`: It is used to declare a variable that is defined in another file or scope.
9. What are virtual functions?
Virtual functions are functions that are declared in a base class and can be overridden by
derived classes. They enable polymorphism, allowing a derived class object to be treated as
an object of its base class. The actual function call is determined at runtime based on the type
of the object being referred to.
10. What is the difference between pass-by-value and pass-by-reference?
In pass-by-value, a copy of the argument is passed to the function, so any changes made to
the parameter inside the function do not affect the original argument. In pass-by-reference, a
reference to the argument is passed, allowing changes made to the parameter inside the
function to modify the original argument.

1. What are the different data types present in C++?

 Primitive Datatype(basic datatype). Example- char, short, int, float, long, double, bool, etc.
 Derived datatype. Example- array, pointer, etc.
 Enumeration. Example- enum
 User-defined data types. Example- structure, class, etc.

2. What is the difference between C and C++?

The main difference between C and C++ are provided in the table below:

C C++

C++ is an object-oriented programming


C is a procedure-oriented programming language.
language.

Data is hidden by encapsulation to ensure that


C does not support data hiding. data structures and operators are used as
intended.

C is a subset of C++ C++ is a superset of C.

Function and operator overloading are not supported Function and operator overloading is supported
in C in C++

Namespace is used by C++, which avoids


Namespace features are not present in C
name collisions.

Functions can not be defined inside structures. Functions can be defined inside structures.

calloc() and malloc() functions are used for memory new operator is used for memory allocation
allocation and free() function is used for memory and deletes operator is used for memory
deallocation. deallocation.
3. What are class and object in C++?

A class is a user-defined data type that has data members and member functions. Data
members are the data variables and member functions are the functions that are used to
perform operations on these variables. An object is an instance of a class. Since a class is a
user-defined data type so an object can also be called a variable of that data type.

4. What is the difference between struct and class?

In C++ a structure is the same as a class except for a few differences like security. The
difference between struct and class are given below:

Structure Class

Members of the class are private by


Members of the structure are public by default.
default.

When deriving a struct from a class/struct, default access When deriving a class, default access
specifiers for base class/struct are public. specifiers are private.

5. What is operator overloading?

Operator Overloading is a very essential element to perform the operations on user-defined


data types. By operator overloading we can modify the default meaning to the operators
like +, -, *, /, <=, etc.

For example -

The following code is for adding two complex number using operator overloading-

class complex{
private:
float r, i;
public:
complex(float r, float i){
this->r=r;
this->i=i;
}
complex(){}
void displaydata(){
cout<<”real part = “<<r<<endl;
cout<<”imaginary part = “<<i<<endl;
}
complex operator+(complex c){
return complex(r+c.r, i+c.i);
}
};
int main(){
complex a(2,3);
complex b(3,4);
complex c=a+b;
c.displaydata();
return 0;
}
6. What is polymorphism in C++?

Polymorphism in simple means having many forms. Its behavior is different in different
situations. And this occurs when we have multiple classes that are related to each other by
inheritance.

The two types of polymorphism in c++ are:

 Compile Time Polymorphism


 Runtime Polymorphism

7. Explain constructor in C++

The constructor is a member function that is executed automatically whenever an object is


created. Constructors have the same name as the class of which they are members so that
compiler knows that the member function is a constructor. And no return type is used for
constructors.

Example:

class A{
private:
int val;
public:
A(int x){ //one argument constructor
val=x;
}
A(){ //zero argument constructor
}
}
int main(){
A a(3);

return 0;
}

8. Tell me about virtual function

Virtual function is a member function in the base class that you redefine in a derived class.
A virtual function is declared using the virtual keyword. When the function is made virtual,
C++ determines which function is to be invoked at the runtime based on the type of the
object pointed by the base class pointer.

9. Compare compile time polymorphism and Runtime polymorphism

Compile-time polymorphism Run time polymorphism

In this method, we would come to know at compile In this method, we come to know at run time
time which method will be called. And the call is which method will be called. The call is not
resolved by the compiler. resolved by the compiler.

It provides fast execution because it is known at the It provides slow execution compared to
compile time. compile-time polymorphism because it is
Compile-time polymorphism Run time polymorphism

known at the run time.

It is achieved by function overloading and operator It can be achieved by virtual functions and
overloading. pointers.

Example -
Example -
class A{
int add(int a, int b){ public:
return a+b; virtual void fun(){
} cout<<"base ";
int add(int a, int b, int c){ }
return a+b+c; };
} class B: public A{
public:
int main(){ void fun(){
cout<<add(2,3)<<endl; cout<<"derived ";
cout<<add(2,3,4)<<endl; }
};
int main(){
return 0; A *a=new B;
} a->fun();

return 0;
}

10. What do you know about friend class and friend function?

A friend class can access private, protected, and public members of other classes in which it
is declared as friends.Like friend class, friend function can also access private, protected,
and public members. But, Friend functions are not member functions.

For example -

class A{
private:
int data_a;
public:
A(int x){
data_a=x;
}
friend int fun(A, B);
}
class B{
private:
int data_b;
public:
A(int x){
data_b=x;
}
friend int fun(A, B);
}
int fun(A a, B b){
return a.data_a+b.data_b;
}
int main(){
A a(10);
B b(20);
cout<<fun(a,b)<<endl;
return 0;
}

11. What are the C++ access specifiers?

Public: All data members and member functions are accessible outside the class.

Protected: All data members and member functions are accessible inside the class and to
the derived class.

Private: All data members and member functions are not accessible outside the class.

12. Define inline function

If a function is inline, the compiler places a copy of the code of that function at each point
where the function is called at compile time. One of the important advantages of using an
inline function is that it eliminates the function calling overhead of a traditional function.

13. What is a reference in C++?

A reference is like a pointer. It is another name of an already existing variable. Once a


reference name is initialized with a variable, that variable can be accessed by the variable
name or reference name both.

For example-

int x=10;
int &ref=x; //reference variable

If we change the value of ref it will be reflected in x. Once a reference variable is initialized
it cannot refer to any other variable. We can declare an array of pointers but an array of
references is not possible.

14. What do you mean by abstraction in C++?

Abstraction is the process of showing the essential details to the user and hiding the details
which we don’t want to show to the user or hiding the details which are irrelevant to a
particular user.

15. Is deconstructor overloading possible? If yes then explain and if no then why?

No destructor overloading is not possible. Destructors take no arguments, so there’s only


one way to destroy an object. That’s the reason destructor overloading is not possible.

16. What do you mean by call by value and call by reference?


In call by value method, we pass a copy of the parameter is passed to the functions. For
these copied values a new memory is assigned and changes made to these values do not
reflect the variable in the main function.In call by reference method, we pass the address of
the variable and the address is used to access the actual argument used in the function call.
So changes made in the parameter alter the passing argument.

17. What is an abstract class and when do you use it?

A class is called an abstract class whose objects can never be created. Such a class exists as
a parent for the derived classes. We can make a class abstract by placing a pure virtual
function in the class.

18. What are destructors in C++?

A constructor is automatically called when an object is first created. Similarly when an


object is destroyed a function called destructor automatically gets called. A destructor has
the same name as the constructor (which is the same as the class name) but is preceded by a
tilde.

Example:

class A{
private:
int val;
public:
A(int x){
val=x;
}
A(){
}
~A(){ //destructor
}
}
int main(){
A a(3);
return 0;
}

19. What are the static members and static member functions?

When a variable in a class is declared static, space for it is allocated for the lifetime of the
program. No matter how many objects of that class have been created, there is only one
copy of the static member. So same static member can be accessed by all the objects of that
class. A static member function can be called even if no objects of the class exist and the
static function are accessed using only the class name and the scope resolution operator ::

20. Explain inheritance

Inheritance is the process of creating new classes, called derived classes, from existing
classes. These existing classes are called base classes. The derived classes inherit all the
capabilities of the base class but can add new features and refinements of their own.

Class Bus, Class Car, and Class Truck inherit the properties of Class Vehicle.
The most important thing about inheritance is that it permits code reusability.

C++ Interview Questions For Experienced

21. What is a copy constructor?

A copy constructor is a member function that initializes an object using another object of
the same class.

Example-

class A{
int x,y;
A(int x, int y){
this->x=x;
this->y=y;
}

};
int main(){
A a1(2,3);
A a2=a1; //default copy constructor is called
return 0;
}

We can define our copy constructor. If we don’t define a copy constructor then the default
copy constructor is called.

Shallow Copy Deep Copy

Shallow copy stores the references of objects to Deep copy makes a new and separate copy of an
the original memory address. entire object with its unique memory address.

Shallow copy is faster. Deep copy is comparatively slower.

Shallow copy reflects changes made to the Deep copy doesn’t reflect changes made to the
new/copied object in the original object. new/copied object in the original object

22. What is the difference between shallow copy and deep copy?

23. What is the difference between virtual functions and pure virtual functions?

A virtual function is a member function in the base class that you redefine in a derived
class. It is declared using the virtual keyword.

Example-

class base{
public:
virtual void fun(){
}
};

A pure virtual function is a function that has no implementation and is declared by


assigning 0. It has no body.

Example-

class base{
public:
virtual void fun()=0;
};

Here, = sign has got nothing to do with the assignment, and value 0 is not assigned to
anything. It is used to simply tell the compiler that a function will be pure and it will not
have anybody.

24. If class D is derived from a base class B. When creating an object of type D in what
order would the constructors of these classes get called?

The derived class has two parts, a base part, and a derived part. When C++ constructs
derived objects, it does so in phases. First, the most-base class(at the top of the inheritance
tree) is constructed. Then each child class is constructed in order until the most-child class
is constructed last. So the first Constructor of class B will be called and then the constructor
of class D will be called.During the destruction exactly reverse order is followed. That is
destructor starts at the most-derived class and works its way down to base class.
So the first destructor of class D will be called and then the destructor of class B will be
called.

25. Can we call a virtual function from a constructor?

Yes, we can call a virtual function from a constructor. But the behavior is a little different
in this case. When a virtual function is called, the virtual call is resolved at runtime. It is
always the member function of the current class that gets called. That is the virtual machine
doesn’t work within the constructor.

For example-

class base{
private:
int value;
public:
base(int x){
value=x;
}
virtual void fun(){

}
}

class derived{
private:
int a;
public:
derived(int x, int y):base(x){
base *b;
b=this;
b->fun(); //calls derived::fun()
}
void fun(){
cout<<”fun inside derived class”<<endl;
}
}

26. What are void pointers?

A void pointer is a pointer which is having no datatype associated with it. It can hold
addresses of any type.

For example-

void *ptr;
char *str;
p=str; // no error
str=p; // error because of type mismatch

We can assign a pointer of any type to a void pointer but the reverse is not true unless you
typecast it as

str=(char*) ptr;

27. What is this pointer in C++?

The member functions of every object have a pointer named this, which points to the object
itself. The value of this is set to the address of the object for which it is called. It can be
used to access the data in the object it points to.

Example

class A{
private:
int value;
public:
void setvalue(int x){
this->value=x;
}
};

int main(){
A a;
a.setvalue(5);
return 0;
}

28. How do you allocate and deallocate memory in C++?

The new operator is used for memory allocation and deletes operator is used for memory
deallocation in C++.
For example-

int value=new int; //allocates memory for storing 1 integer


delete value; // deallocates memory taken by value

int *arr=new int[10]; //allocates memory for storing 10 int


delete []arr; // deallocates memory occupied by arr

C++ INTERVIEW CODES

Question 1: Reverse a String


Write a function that takes a string as input and returns the reversed string.
#include <iostream>
#include <string>
std::string reverseString(const std::string& str) {
std::string reversedStr;
for (int i = str.length() - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
}

int main() {
std::string input = "Hello, World!";
std::string reversed = reverseString(input);
std::cout << "Reversed string: " << reversed << std::endl;
return 0;
}
```

#include <iostream>
int sumArray(const int* arr, int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int sum = sumArray(arr, size);
std::cout << "Sum: " << sum << std::endl;
return 0;
}

Question 3: Check if a String is Palindrome


#include <iostream>
#include <string>
#include <algorithm>

bool isPalindrome(const std::string& str) {


std::string reversedStr = str;
std::reverse(reversedStr.begin(), reversedStr.end());
return str == reversedStr;
}

int main() {
std::string input = "racecar";
bool isPal = isPalindrome(input);
std::cout << "Is Palindrome: " << std::boolalpha << isPal << std::endl;
return 0;
}
```

Question 4: Find the Fibonacci Series


#include <iostream>

void printFibonacci(int n) {
int first = 0, second = 1;
std::cout << "Fibonacci Series: ";
while (first <= n) {
std::cout << first << " ";
int next = first + second;
first = second;
second = next;
}
std::cout << std::endl;
}

int main() {
int num = 50;
printFibonacci(num);
return 0;
}
```

Question 5: Reverse an Integer


#include <iostream>

int reverseInteger(int num) {


int reversedNum = 0;
while (num != 0) {
reversedNum = reversedNum * 10 + num % 10;
num /= 10;
}
return reversedNum;
}

int main() {
int num = 12345;
int reversed = reverseInteger(num);
std::cout << "Reversed integer: " << reversed << std::endl;
return 0;
}

PYTHON INTERVIEW QUESTIONS


1. What is Python?
Python is a high-level, interpreted programming language known for its simplicity and
readability. It emphasizes code readability and a clean syntax, making it easy to learn and
use. Python supports multiple programming paradigms, including object-oriented, imperative,
and functional programming.
2. What are the key features of Python?
Key features of Python include:
- Easy-to-read syntax and high code readability
- Dynamic typing and automatic memory management (garbage collection)
- Support for multiple programming paradigms
- Extensive standard library and third-party module ecosystem
- Cross-platform compatibility
3. What is PEP 8?
PEP 8 is the official style guide for Python code. It provides guidelines on how to format
Python code to enhance its readability and maintainability. It covers aspects such as
indentation, line length, naming conventions, and more. Adhering to PEP 8 makes your code
more consistent and easier to understand by other Python developers.
4. What is the difference between a list and a tuple in Python?
In Python, both lists and tuples are used to store multiple items, but they have some
differences:
- Lists are mutable, meaning their elements can be modified. Tuples, on the other hand, are
immutable and their elements cannot be changed once defined.
- Lists are created using square brackets ([]), while tuples are created using parentheses ().
- Lists are typically used for collections of homogeneous items, whereas tuples are used for
heterogeneous data.
5. What is the difference between a shallow copy and a deep copy in Python?
In Python, a shallow copy creates a new object that references the original elements. If the
elements are mutable objects, changes made to the original object will be reflected in the
copied object. A deep copy, on the other hand, creates a completely independent copy of the
original object and its contents, recursively copying all nested objects. Changes made to the
original object do not affect the deep copy.

6. Explain the concept of a decorator in Python.


A decorator is a design pattern in Python that allows you to modify the behavior of a function
or a class without changing its source code. Decorators are implemented using the "@"
symbol followed by the decorator name placed above the function or class definition. They
provide a way to add functionality to existing functions or classes dynamically.
7. What are Python generators?
Generators are a type of iterable, similar to lists or tuples. However, unlike lists that store all
their values in memory, generators generate values on-the-fly and only hold one value at a
time. They are implemented using the yield keyword and are useful when dealing with large
datasets or when memory efficiency is a concern.
8. How are exceptions handled in Python?
In Python, exceptions are handled using try-except blocks. The code that might raise an
exception is enclosed within the try block, and if an exception occurs, it is caught by the
except block. Multiple except blocks can be used to catch different types of exceptions.
Additionally, the finally block can be used to specify code that should always be executed,
regardless of whether an exception occurred or not.
9. What is the Global Interpreter Lock (GIL) in Python?
The Global Interpreter Lock (GIL) is a mechanism used by the C Python interpreter (the
default Python implementation) to synchronize access to Python objects. It ensures that only
one thread executes Python bytecode at a time, even on multi-core systems. This means that,
in C Python, multi-threaded programs cannot achieve true parallelism for CPU-bound tasks.
However, the GIL does not affect performance significantly for I/O-bound tasks.
10. How does memory management work in Python?
Python uses automatic memory management, also known as garbage collection, to reclaim

What is Python?
Python is one of the most widely-used and popular programming languages, was developed
by Guido van Rossum and released first on February 20, 1991. Python is a free and open-
source language with a very simple and clean syntax which makes it easy for developers to
learn Python. It supports object-oriented programming and is most commonly used to
perform general-purpose programming. Python is used in several domains like Data
Science, Machine Learning, Deep Learning, Artificial Intelligence, Scientific Computing
Scripting, Networking, Game Development Web Development, Web Scraping, and various
other domains.
Python grows exponentially due to its simplistic nature and the ability to perform several
functions in just a few lines of code. Due to its ability to support powerful computations
using powerful libraries, it is used in various domains and it become the reason for the huge
demand for Python developers across the world. Companies are willing to offer amazing
Packages and benefits to these developers.
1. What is Python? List some popular applications of Python in the world of
technology.
Python is a widely-used general-purpose, high-level programming language. It was created
by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It
was designed with an emphasis on code readability, and its syntax allows programmers to
express their concepts in fewer lines of code.
It is used for:
System Scripting
Web Development
Game Development
Software Development
Complex Mathematics

2. What are the benefits of using Python language as a tool in the present scenario?
Object-Oriented Language
High-Level Language
Dynamically Typed language
Extensive support Libraries
Presence of third-party modules
Open source and community development
Portable and Interactive
Portable across Operating systems

3. Is Python a compiled language or an interpreted language?


Actually, Python is a partially compiled language and partially interpreted language. The
compilation part is done first when we execute our code and this will generate byte code
internally this byte code gets converted by the Python virtual machine(p.v.m) according to
the underlying platform(machine+operating system).
4. What does the ‘#’ symbol do in Python?
‘#’ is used to comment on everything that comes after on the line.
5. What is the difference between a Mutable datatype and an Immutable data type?
Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at runtime. Eg – String,
Tuple, etc.
6. How are arguments passed by value or by reference in Python?
Everything in Python is an object and all variables hold references to the objects. The
reference values are according to the functions; as a result, you cannot change the value of
the references. However, you can change the objects if it is mutable.
7. What is the difference between a Set and Dictionary?
The set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements.
A dictionary in Python is an unordered collection of data values, used to store data values
like a map.
8. What is List Comprehension? Give an Example.
List comprehension is a syntax construction to ease the creation of a list based on existing
iterable.
For Example:
my_list = [i for i in range(1, 10)]
9. What is a lambda function?
A lambda function is an anonymous function. This function can have any number of
parameters but, can have just one statement. For Example:
a = lambda x, y : x*y
10. What is a pass in Python?
Pass means performing no operation or in other words, it is a placeholder in the compound
statement, where there should be a blank left and nothing has to be written there.
11. What is the difference between / and // in Python?
// represents floor division whereas / represents precise division. For Example:
5//2 = 2
5/2 = 2.5
12. How is Exceptional handling done in Python?
There are 3 main keywords i.e. try, except, and finally which are used to catch exceptions
and handle the recovering mechanism accordingly. Try is the block of a code that is
monitored for errors. Except block gets executed when an error occurs.
The beauty of the final block is to execute the code after trying for an error. This block gets
executed irrespective of whether an error occurred or not. Finally, block is used to do the
required cleanup activities of objects/variables.
13. What is swapcase function in Python?
It is a string’s function that converts all uppercase characters into lowercase and vice versa.
It is used to alter the existing case of the string. This method creates a copy of the string
which contains all the characters in the swap case.
14. Difference between for loop and while loop in Python
The “for” Loop is generally used to iterate through the elements of various collection types
such as List, Tuple, Set, and Dictionary. Developers use a “for” loop where they have both
the conditions start and the end. Whereas, the “while” loop is the actual looping feature that
is used in any other programming language. Programmers use a Python while loop where
they just have the end conditions.

15. Can we Pass a function as an argument in Python?

Yes, Several arguments can be passed to a function, including objects, variables (of the
same or distinct data types), and functions. Functions can be passed as parameters to other
functions because they are objects. Higher-order functions are functions that can take other
functions as arguments.

16. What are *args and *kwargs?

To pass a variable number of arguments to a function in Python, use the special


syntax *args and **kwargs in the function specification. It is used to pass a variable-length,
keyword-free argument list. By using the *, the variable we associate with the * becomes
iterable, allowing you to do operations on it such as iterating over it and using higher-order
operations like map and filter.

17. Is Indentation Required in Python?

Yes, indentation is required in Python. A Python interpreter can be informed that a group of
statements belongs to a specific block of code by using Python indentation. Indentations
make the code easy to read for developers in all programming languages but in Python, it is
very important to indent the code in a specific order.

18. What is Scope in Python?

The location where we can find a variable and also access it if required is called the scope
of a variable.
 Python Local variable: Local variables are those that are initialized within a function
and are unique to that function. It cannot be accessed outside of the function.
 Python Global variables: Global variables are the ones that are defined and declared
outside any function and are not specified to any function.
 Module-level scope: It refers to the global objects of the current module accessible in
the program.
 Outermost scope: It refers to any built-in names that the program can call. The name
referenced is located last among the objects in this scope.

19. What is docstring in Python?

Python documentation strings (or docstrings) provide a convenient way of associating


documentation with Python modules, functions, classes, and methods.
 Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or
“””triple double quotes””” just below the class, method, or function declaration. All
functions should have a docstring.
 Accessing Docstrings: The docstrings can be accessed using the __doc__ method of
the object or using the help function.

20. What is a dynamically typed language?

Typed languages are the languages in which we define the type of data type and it will be
known by the machine at the compile-time or at runtime. Typed languages can be classified
into two categories:
 Statically typed languages: In this type of language, the data type of a variable is
known at the compile time which means the programmer has to specify the data type of
a variable at the time of its declaration.
 Dynamically typed languages: These are the languages that do not require any pre-
defined data type for any variable as it is interpreted at runtime by the machine itself. In
these languages, interpreters assign the data type to a variable at runtime depending on
its value.

21. What is a break, continue, and pass in Python?

The break statement is used to terminate the loop or statement in which it is present. After
that, the control will pass to the statements that are present after the break statement, if
available.
Continue is also a loop control statement just like the break statement. continue statement is
opposite to that of the break statement, instead of terminating the loop, it forces to execute
the next iteration of the loop.
Pass means performing no operation or in other words, it is a placeholder in the compound
statement, where there should be a blank left and nothing has to be written there.

22. What are Built-in data types in Python?

The following are the standard or built-in data types in Python:


 Numeric: The numeric data type in Python represents the data that has a numeric value.
A numeric value can be an integer, a floating number, a Boolean , or even a complex
number.
 Sequence Type: The sequence Data Type in Python is the ordered collection of similar
or different data types. There are several sequence types in Python:
 Python String
 Python List
 Python Tuple
 Python range
 Mapping Types: In Python, hashable data can be mapped to random objects using a
mapping object. There is currently only one common mapping type, the dictionary, and
mapping objects are mutable.
 Python Dictionary
 Set Types: In Python, a Set is an unordered collection of data types that is iterable,
mutable, and has no duplicate elements. The order of elements in a set is undefined
though it may consist of various elements.

23. How do you floor a number in Python?

The Python math module includes a method that can be used to calculate the floor of a
number.
 floor() method in Python returns the floor of x i.e., the largest integer not greater than
x.
 Also, The method ceil(x) in Python returns a ceiling value of x i.e., the smallest integer
greater than or equal to x.

Intermediate Python Interview Question


24. What is the difference between xrange and range functions?
range() and xrange() are two functions that could be used to iterate a certain number of
times in for loops in Python. In Python 3, there is no xrange, but the range function behaves
like xrange in Python 2.
 range() – This returns a list of numbers created using the range() function.
 xrange() – This function returns the generator object that can be used to display
numbers only by looping. The only particular range is displayed on demand and hence
called lazy evaluation.
25. What is Dictionary Comprehension? Give an Example
Dictionary Comprehension is a syntax construction to ease the creation of a dictionary
based on the existing iterable.
For Example: my_dict = {i:1+7 for i in range(1, 10)}
26. Is Tuple Comprehension? If yes, how, and if not why?
(i for i in (1, 2, 3))
Tuple comprehension is not possible in Python because it will end up in a generator, not a
tuple comprehension.
27. Differentiate between List and Tuple?
Let’s analyze the differences between List and Tuple:
List
 Lists are Mutable datatype.
 Lists consume more memory
 The list is better for performing operations, such as insertion and deletion.
 The implication of iterations is Time-consuming
Tuple
 Tuples are Immutable datatype.
 Tuple consumes less memory as compared to the list
 A Tuple data type is appropriate for accessing the elements
 The implication of iterations is comparatively Faster
28. What is the difference between a shallow copy and a deep copy?
Shallow copy is used when a new instance type gets created and it keeps values that are
copied whereas deep copy stores values that are already copied.
A shallow copy has faster program execution whereas a deep coy makes it slow.
29. Which sorting technique is used by sort() and sorted() functions of python?
Python uses the Tim Sort algorithm for sorting. It’s a stable sorting whose worst case is
O(N log N). It’s a hybrid sorting algorithm, derived from merge sort and insertion sort,
designed to perform well on many kinds of real-world data.
30. What are Decorators?
Decorators are a very powerful and useful tool in Python as they are the specific change
that we make in Python syntax to alter functions easily.
31. How do you debug a Python program?
By using this command we can debug a Python program:
$ python -m pdb python-script.py
32. What are Iterators in Python?
In Python, iterators are used to iterate a group of elements, containers like a list. Iterators
are collections of items, and they can be a list, tuples, or a dictionary. Python iterator
implements __itr__ and the next() method to iterate the stored elements. We generally use
loops to iterate over the collections (list, tuple) in Python.
33. What are Generators in Python?
In Python, the generator is a way that specifies how to implement iterators. It is a normal
function except that it yields expression in the function. It does not implement __itr__ and
next() method and reduces other overheads as well.
If a function contains at least a yield statement, it becomes a generator. The yield keyword
pauses the current execution by saving its states and then resumes from the same when
required.
34. Does Python supports multiple Inheritance?
Python does support multiple inheritances, unlike Java. Multiple inheritances mean that a
class can be derived from more than one parent class.
35. What is Polymorphism in Python?
Polymorphism means the ability to take multiple forms. So, for instance, if the parent class
has a method named ABC then the child class also can have a method with the same name
ABC having its own parameters and variables. Python allows polymorphism.
36. Define encapsulation in Python?
Encapsulation means binding the code and the data together. A Python class is an example
of encapsulation.
37. How do you do data abstraction in Python?
Data Abstraction is providing only the required details and hides the implementation from
the world. It can be achieved in Python by using interfaces and abstract classes.
38. How is memory management done in Python?
Python uses its private heap space to manage the memory. Basically, all the objects and
data structures are stored in the private heap space. Even the programmer can not access
this private space as the interpreter takes care of this space. Python also has an inbuilt
garbage collector, which recycles all the unused memory and frees the memory and makes
it available to the heap space.
39. How to delete a file using Python?
We can delete a file using Python by following approaches:
 os.remove()
 os.unlink()

40. What is slicing in Python?

Python Slicing is a string operation for extracting a part of the string, or some part of a list.
With this operator, one can specify where to start the slicing, where to end, and specify the
step. List slicing returns a new list from the existing list.
Syntax: Lst[ Initial : End : IndexJump ]
41. What is a namespace in Python?
A namespace is a naming system used to make sure that names are unique to avoid naming
conflicts.

Advanced Python Interview Questions & Answers


42. What is PIP?
PIP is an acronym for Python Installer Package which provides a seamless interface to
install various Python modules. It is a command-line tool that can search for packages over
the internet and install them without any user interaction.
43. What is a zip function?
Python zip() function returns a zip object, which maps a similar index of multiple
containers. It takes an iterable, converts it into an iterator and aggregates the elements based
on iterables passed. It returns an iterator of tuples.
44. What are Pickling and Unpickling?
The Pickle module accepts any Python object and converts it into a string representation
and dumps it into a file by using the dump function, this process is called pickling. While
the process of retrieving original Python objects from the stored string representation is
called unpickling.
45. What is monkey patching in Python?
In Python, the term monkey patch only refers to dynamic modifications of a class or
module at run-time.
# g.py
class GeeksClass:
def function(self):
print "function()"

import m
def monkey_function(self):
print "monkey_function()"

m.GeeksClass.function = monkey_function
obj = m.GeeksClass()
obj.function()
46. What is __init__() in Python?
Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python
classes. The __init__ method is called automatically whenever a new object is initiated.
This method allocates memory to the new object as soon as it is created. This method can
also be used to initialize variables.
47. Write a code to display the current time?
currenttime= time.localtime(time.time())
print (“Current time is”, currenttime)

48. What are Access Specifiers in Python?

Python uses the ‘_’ symbol to determine the access control for a specific data member or a
member function of a class. A Class in Python has three types of Python access modifiers :
 Public Access Modifier: The members of a class that are declared public are easily
accessible from any part of the program. All data members and member functions of a
class are public by default.
 Protected Access Modifier: The members of a class that are declared protected are
only accessible to a class derived from it. All data members of a class are declared
protected by adding a single underscore ‘_’ symbol before the data members of that
class.
 Private Access Modifier: The members of a class that are declared private are
accessible within the class only, the private access modifier is the most secure access
modifier. Data members of a class are declared private by adding a double underscore
‘__’ symbol before the data member of that class.

49. What are unit tests in Python?

Unit Testing is the first level of software testing where the smallest testable parts of the
software are tested. This is used to validate that each unit of the software performs as
designed. The unit test framework is Python’s xUnit style framework. The White Box
Testing method is used for Unit testing.

50. Python Global Interpreter Lock (GIL)?


Python Global Interpreter Lock (GIL) is a type of process lock that is used by Python
whenever it deals with processes. Generally, Python only uses only one thread to execute
the set of written statements. The performance of the single-threaded process and the multi-
threaded process will be the same in Python and this is because of GIL in Python. We can
not achieve multithreading in Python because we have a global interpreter lock that restricts
the threads and works as a single thread.

51. What are Function Annotations in Python?

Function Annotation is a feature that allows you to add metadata to function parameters and
return values. This way you can specify the input type of the function parameters and the
return type of the value the function returns.
Function annotations are arbitrary Python expressions that are associated with various parts
of functions. These expressions are evaluated at compile time and have no life in Python’s
runtime environment. Python does not attach any meaning to these annotations. They take
life when interpreted by third-party libraries, for example, mypy.
Python 3.10 above Feature:

52. What are Exception Groups in Python?

The latest feature of Python 3.11, Exception Groups. The ExceptionGroup can be handled
using a new except* syntax. The * symbol indicates that multiple exceptions can be
handled by each except* clause.
ExceptionGroup is a collection/group of different kinds of Exception. Without creating
Multiple Exceptions we can group together different Exceptions which we can later fetch
one by one whenever necessary, the order in which the Exceptions are stored in the
Exception Group doesn’t matter while calling them.

PYTHON INTERVIEW CODES

Question 1: Reverse a String


def reverse_string(string):
return string[::-1]
input_string = "Hello, World!"
reversed_string = reverse_string(input_string)
print("Reversed string:", reversed_string)
```

Question 2: Find the Sum of an Array


def sum_array(arr):
return sum(arr)

input_array = [1, 2, 3, 4, 5]
array_sum = sum_array(input_array)
print("Sum:", array_sum)
```

Question 3: Check if a String is Palindrome


def is_palindrome(string):
return string == string[::-1]

input_string = "racecar"
is_pal = is_palindrome(input_string)
print("Is Palindrome:", is_pal)
```

Question 4: Find the Fibonacci Series


def fibonacci_series(n):
first, second = 0, 1
print("Fibonacci Series:", end=" ")
while first <= n:
print(first, end=" ")
next_num = first + second
first = second
second = next_num

num = 50
fibonacci_series(num)
```

Question 5: Reverse an Integer


def reverse_integer(num):
reversed_num = int(str(num)[::-1])
return reversed_num

num = 12345
reversed_num = reverse_integer(num)
print("Reversed integer:", reversed_num)
```

23) How is a local variable different from a global variable?

Global Variables: Global variables are those that have been declared outside of a function. The scope
outside of the function is known as global space. Any program function has access to these variables.

Local Variables: Any variable declared inside a function is referred to as a local variable. This
variable does not exist in the global domain; it only exists locally.

Code

# Python program to show how global variables and local variables are different
var = 56
# Creating a function
def addition():
var1 = 7
c = var + var1
print("In local scope: ", var1)
print("Adding a global scope and a local scope variable: ", c)
addition()
print("In global scope: ", var)

24) What is the distinction between Python Arrays and Python Lists?
In Python, arrays and lists both store data similarly. On the other hand, arrays can only have a single
data type element, while lists can contain any data type component.

Code

# Python program to show the difference between a list and an array

# Importing array module


import array as arr

# Creating an array and a list


array_1 = arr.array("i", [3, 6, 2, 7, 9, 5])
list_1 = [4, 'Interview', 7.20]

print(array_1)
print(list_1)

# Trying to create an array with multiple data types


try:
array_2 = arr.array("i", [3, 7, 3, "Interview"])
except Exception as e:
print(e)

25) What exactly is __init__?


In Python, __init__ is a function or function Object() { [native code] }. When a new object/instance of
a class is created, this function is automatically called to reserve memory. The __init__ method is
available in all classes.

Here's an instance of how to put it to good use.

Code

# Python program to explain __init__

class Student:
def __init__(self, st_name, st_class, st_marks):
self.st_name = st_name
self.st_class = st_class
self.st_marks = 67
S1 = Student("Itika", 10, 67)
print(S1.st_name)
print(S1.st_class)

26) What is a lambda function, and how does it work?


A lambda function is a type of nameless function. This method can take as many parameters as you
want but a single statement.

Code

# Python program to show how to use lambda functions

# Creating a lambda function for addition


sum_ = lambda x, y, z : x + y + z
print("Sum using lambda function is: ", sum_(4, 6, 8))

27) In Python, what is the self?


A self is a class instance or object. This is explicitly supplied as the initial argument in Python.
However, in Java, in which it is optional, that's not the case. Local variables make it easy to
differentiate between a class's methods and attributes.

In the init method of a class, the self variable corresponds to the freshly generated objects, whereas it
relates to the entity whose method can be called in the class's other methods.

28) How do these commands work: break, pass and continue?

Break The loop is terminated when a criterion is


fulfilled, and control is passed to the
subsequent statement.

Pass You can use this when you need a code block
syntactically correct but don't want to run it.
This is a null action in essence. When it is run,
nothing takes place.

Continu When a specified criteria is fulfilled, the


e control is moved to the start of the loop,
allowing some parts of the loop currently in
execution to be skipped.

29) In Python, how would you randomise the elements of a list while it's
running?

Consider the following scenario:

Code

# Python program to show to randomise elements of a list

# Importing the random module


import random
list_ = ["Python", "Interview", "Questions", "Randomise", "List"]
print("Original list: ", list_)
random.shuffle(list_)
print("After randomising the list: ", list_)

30) What is the difference between pickling and unpickling?


The Pickle module takes any Python object and then transforms it into the representation of a string,
which it then dumps into a file using the dump method. Unpickling is the procedure of recovering
authentic Python items from a saved string representation.

31) What method will you use to turn the string's all characters into lowercase
letters?
The lower() function could be used to reduce a string to lowercase.

Code

# Python program to show how to convert a string to lower case

string = 'JAVATPOINT'
print(string.lower())

32) How do you comment on multiple lines at once in Python?


Multi-line comments span many lines. A # must precede all lines that we will comment on. You could
also use a convenient alternative to comment on several lines. All you have to do is press down the
ctrl key, hold it, and click the left mouse key in every area where you need a # symbol to appear, then
write a # once. This will add a comment to the lines wherever you insert your cursor.
33) In Python, what are docstrings?
Docstrings stands for documentation strings, which are not just comments. We enclose the docstrings
in triple quotation marks. They are not allocated to any variable, and, as a result, they can also be used
as comments.

Code

# Python program to show how to write a docstring

"""
This is a docstring.
We write docstrings to explain a program.
This program will multiply two numbers and then display the output.
"""
a = 39
b = 45
c=a*b
print("Result of multiplication: ", c)

34) Explain the split(), sub(), and subn() methods of the Python "re" module.
Python's "re" module provides three ways for modifying strings. They are as follows:

split() "splits" a string into a list using a regex pattern.

sub() finds all substrings that match the regex pattern given by us. Then it replaces that substring with
the string provided.

subn() is analogous to sub() in that it gives the new string and the number of replacements.

35) What is the best way to add items to a Python array?


We can use the append(), extend(), as well as insert (i,x) methods to add items to an array.

Code

# Python program to show how to add elements to an array

array = arr.array('d', [1 , 2 ,3] )


array.append(8) # appending will add an element to the end of the array
print(array)
array.extend([4,6,9]) # extending will add elements by looping through the given iterable
print(array)
array.insert(2, 9) # inserting will add the element at the specified index
print(array)

36) What is the best way to remove values from a Python array?
The pop() or remove() methods can be used to remove array elements. The distinction between these
2 methods is that the first returns the removed value, while the second does not.

Code

# Python program to show how to remove elements from a Python array

array = arr.array('d', [1, 3, 8, 1, 4, 8, 2, 4])


print(array.pop()) # By default it will remove and return the last element of the array
print(array.pop(5)) # It will return and remove the element present at 5th index
array.remove(1) # It will remove only the first occurrence of the element - 1 from the array
print(array)

37) In Python, what is monkey patching?


The phrase "monkey patch" in Python exclusively references run-time dynamic alterations to a
module.

Code

class My_Class:
def f(self):
print("f()")

The monkey-patch testing will then be done as follows:

import monk
def monkey_f(self):
print ("we are calling monkey_f()")

# changing address of func


monk.My_Class.func = monkey_f
object_ = monk.My_Class()

object_.func()

38) In Python, how do you make an empty class?


An empty class has no statements contained within its blocks. It can be produced by using the pass
keyword. But you can make an object outside the class. The PASS statement doesn't do anything in
Python.

Code

# Python program to show how to make an empty class

class my_class:
pass
object_ = my_class()
object_.name = "Javatpoint"
print("Name = ", object_.name)

39) Write a Python script to implement the Bubble sort algorithm.


Code

# Python program to show how to implement bubble sort

def bubble_Sort(array):
n = len(array)

for i in range(n-1):

for j in range(0, n-i-1):

if array[j] > array[j + 1] :


array[j], array[j + 1] = array[j + 1], array[j]

print(array)

#example array
arr = [23, 14, 64, 13, 64, 23, 86]

bubble_Sort(arr)

40) In Python, create a program that generates a Fibonacci sequence.


Code
#taking number of terms to print the series
n=9
first = 0 #first value of series
second = 1 #second value of series
series = [first, second]
if n == 0:

print("The required fibonacci series is",first)


else:

for i in range(0,n-2):

num = series[i] + series[i+1]

series.append(num)
print(series)

41) Make a Python script that checks if a given number is prime.


Code

# Python program to check if a number is prime or not

# Declaring a variable
n = 37
if n == 2:
print("2 is a prime number")

if n != 1:
for i in range(2, n):
if n % i == 0:
print("The given number is a composite number")
break
if i == n-1:
print("The given number is a prime number")
else:
print("1 is not a prime number")
42) Create a Python program that checks if a given sequence is a Palindrome.
Code

# Python program to check if the given string is a palindrome

# Creating a string
sequence = 'abjucujba'
# Reversing the string
reverse = sequence[::-1]

# Checking if the string is a palindrome


if reverse == sequence:
print("The sequence is a palindrome")
else:
print("The sequence is not a palindrome")

43) In a NumPy array, how do I extract the indices of N maximum values?


Code

import numpy
array = numpy.array([4, 8, 4, 9, 2])
print(array.argsort()[-2:][::-1])

44) Using Python/ NumPy, write code to compute percentiles?


Code

import numpy
array = numpy.array([3, 6, 1, 6, 5, 2])
percentile = numpy.percentile(array, 45) #Returns 45th percentile
print(percentile)

45) Write a Python program to determine whether a number is binary.


Code

num = 1101001
while(num > 0):
l = num % 10
if l!=0 and l!=1:

print("given number is not binary")

break

num = num // 10

if num == 0:

print("given number is binary")

46) Using the Iterative technique, calculate factorial in Python.


Code

num = 12
fact = 1
if num < 0:

print("Since number is negative factorial cannot be calculated")


elif num == 0:

print("Factorial of 0 is 1")
else:

for f in range(1, num + 1):

fact = fact * i

print("Factorial of",num ,"is",fact)

47) Compute the LCM of two given numbers using Python code.
Code

num_1 = 24
num_2 = 92
if num_1 > num_2:

greater_num = num_1
else:

greater_num = num_2
while(True):

if((greater_num % num_1 == 0) and (greater_num % num_2 == 0)):

lcm = greater_num

break

greater_num += 1
print("LCM of", num_1, "and", num_2, "=", greater_num)

48) Write a Python program that removes vowels from a string.


Code

string = 'Javatpoint'
result=''
for s in string:
if s in ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'):
s = ''
result += s
print("Required string without vowels is:", result)

50) Write a Python code to reverse a given list.

array = [23, 12, 5, 24, 23, 76, 86, 24, 86, 24, 75]

print("Reverse order of array is")


# Reversing the given array
for i in range(len(array)-1, -1, -1):

print(array[i], end=' ')


51) Write a Python program that rotates an array by two positions to the right.
Code

listt = [23, 12, 5, 24, 23, 76, 86, 24, 86, 24, 75]

for _ in range(0,2):
temp = listt[len(listt)-1]
for i in range(len(listt)-1,-1,-1):
listt[i]=listt[i-1]
listt[0]=temp
print("After implementing right rotation the list is :")
print(listt)
CCNA INTERVIEW QUESTIONS

1. Explain Routing.

Routing is basically a process of establishing the routes that data packets take on their way to the
destination. It is a process of selecting a path across one or more networks to move a data packet
from source to destination. Routing is generally performed in many types of networks such as
circuit-switched networks, computer networks, etc. It is considered as one of the most essential
features in a network and is done by a device called routers.

In the above diagram, the data packet moves from Computer A to Computer B. There are two paths
available:

1st- Network 1, 3, and 5


2nd- Network 2 and 4

It depends upon network routers to make a choice whether to pass through 1st or 2nd. The 1st one is
a long path but might be faster at forwarding packets whereas the 2nd one is a shorter path. These
are the kinds of choices that routers have to make constantly.

2. What do you mean by data packets?

Data packet is a unit of data that is made into a single package for transmission over a network.
They are also referred to as a network layer package and are also used by IP protocol as they
contain the IP information which is attached to each packet. They contain much essential
information like email messages, website data, and VoIP (Voice-over-IP) calls. Each data packet
has a unique numeric identification number that defines the packet number and order.

3. What do you mean by routers? Write its major functions.

Router is a networking device that is used to forward data packets along with a network from source
to destination. The devices are specially designed to receive, analyze, and forward data packets
between computer networks. It examines a destination IP address of a data packet and uses its
headers and routing table to determine the best way or route for transferring the packets. There are
some popular companies that develop routers like HP, Juniper, Nortel, Cisco, etc.

Functions of Routers:

 Send and receive data on computer networks.


 Used to create local networks of devices
 Helps to connect multiple devices to the Internet.
 Allows users to configure the port as per their requirements in the network.
 Filter unwanted interference, and carry out the process of data encapsulation and decapsulation.
 Used to segment network traffic.
 Prevent network bottlenecks simply by isolating portions of a network.
 Reduce excessive traffic.

4. Name types of routes that are available in routers.

Types of routes available in routers include:

Static Route: This route is also known as a non-adaptive route. It is either directly configured on an
active interface of the router or manually added to the routing table by an administrator.

Default Route: In this, the router is configured to send all packets towards a single router, and it
does not matter whether or not it belongs to a specific network. It is especially used when networks
deal with a single exit point.

Dynamic Route: This route is also known as the adaptive route. It makes automatic adjustments of
the routes as per the current state of the route in the routing table and also uses routing protocols to
find network destinations.

5. What do you mean by Switching?

Switching is a process in computer networks that enable us to interconnect links to form a larger
network. It works at the DLL frame and uses hardware address or mac address of devices on LAN
(Local Area Network) to segment a network.

6. Name two ports of Switches.

The two ports of switches include:

Access Port: It connects network hosts to a single VLAN and only carries the traffic of one VLAN.
In this, traffic is sent and received in native format without any VLAN tagging. Access ports are
basically used to connect switch ports with computers with a minimum of 10 Mbps speed.

Trunk Port: It generally connects to another switch and is able to interact with several other
VLANs. By default, it is a member of all VLANs in the VLAN database. The trunk port is basically
used for multiple connections between the switch to switch and switch to routers.

7. Name different IPX access list.

Standard: Used to filter the source or destination IP address.

Extended: Uses source and destination IP addresses, protocol, socket, and port when fileting a
network.

8. What is the main objective of Data Link Layer and Transport Layer?

Data Link Layer: It is the 2nd layer of the OSI model which is generally responsible for
transferring the datagram across an individual link. It is considered one of the most complicated
layers and also has complex functionalities and liabilities. It also ensures that the appropriate
physical protocol is assigned to the data.

Transport Layer: It is the 4th layer of the OSI model which is responsible for providing
transparent transfer of data among end-users, thus providing reliable data transfer services to the top
layers. Its main objective is to deliver the entire message from source to destination.

9. What do you mean by 100BaseFX?

100BaseFX is basically an Ethernet media standard for Ethernet over fiber optic cables, rather than
twisted-pair cables. It is a version of Fast Ethernet that makes use of fiber optic cables as the main
transmission medium. Here, 100 refers to 100Mbps data speed that means it carries data traffic at
100 Mbps in LAN.

10. Name the LAN Switching method that is mostly used in CISCO Catalyst 5000?

Store and forward switching method is mostly used by CISCO Catalyst 5000 because it stores the
entire frame to its buffers and executes a CRC check before deciding whether to forward that data
frame or not.
11. Name different memories that are used in CISCO routers.

Different memories that are used in CISCO router include:

 NVRAM (Non-volatile RAM): It is used to store startup configuration files. It also retains its content even
after a device is restarted or powered down.
 DRAM (Dynamic Random-Access Memory): It is used to store configuration files that are being executed.
It loses its content when a device is restarted.
 ROM (Read Only Memory): It is used to store a bootstrap program that initializes a boot process. It also
runs and maintains instructions for POST diagnostics.
 Flash Memory: It is used to store CISCO IOS. It can also be used to store other files such as backup
configuration files.

12. Write difference between tracert and traceroute.

Tracert: It is a Command Prompt command that is used to show various details about the path that
a packet takes from the source computer to the specified destination computer. It only uses ICMP
(Internet Control Message Protocol) echo requests. It can be used on a PC. This command is
generally used in Windows NT-based OS.

Traceroute: As the name suggests, it is a command that is used to trace the records of the path that
a packet takes from the source computer to the specified destination computer. It uses UDP (User
Datagram Protocol) echo requests. Traceroute command can be used on a router or switch. This
command is generally used in UNIX OS.

13. Explain HDLC.

HDLC (High-Level Data Link Control) is a group of communication protocols that usually
provides reliable delivery of data frames over communication or network link. It is a proprietary
protocol for CISCO and is the default encapsulation operated within CISCO routers. It also ensures
the error-free transmission of data and can provide both connection-oriented and connectionless
services.

14. What do you mean by DLCI?

DLCI (Data Link Connection Identifier) is basically a frame relay 10-bit-wide link-local virtual
circuit normally assigned by frame relay service to uniquely identify each virtual circuit that is
present on the network. It simply identifies which logical circuit the data travels over.

15. Name router command that is used to display RAM content and NVRAM Content.

The router command that is used to display RAM content is “Show run/show running-config", and
the router command that is used to display NVRAM content is “Show start/show start-config".

16. What do you mean by Frame relay?

Frame relay is basically a packet switching technology typically used to transfer data between
geographically separated LANs or across WANs. It simply provides connection-oriented
communication by developing and maintaining virtual circuits. It is cost-effective technology and is
generally used to join two or more routers with a single interface. It works on the data link layer
and physical layer of the OSI model.
17. What are three possible ways of data transmission in CCNA?

Three possible ways of data transmission in CCNA include:

Simplex: The Communication is unidirectional in Simplex mode, as on a single-direction road. Just


one of the two devices on a connection can communicate, the other can just get. The simplex mode
can utilize the whole limit of the channel to send information one way.

Half Duplex: Each station can transmit and receive in Half-duplex mode, however not
simultaneously. At the point when one device is sending, the other can just receive, and the other
way around. The half-duplex mode is utilized in situations where there is no requirement for
communication both ways simultaneously. The whole limit of the channel can be used for every
direction.

Full Duplex: Both stations can send and receive all the while in full-duplex mode. Signals that are
going in one direction share the capacity of the connection with signals going another way IN this
type of mode. This sharing can happen in two ways:
 Either the connection should contain two truly separate transmission ways, one for sending and the other for
receiving.
 The capacity is split between signals going in two ways.

Full-duplex mode is utilized when communication both ways are required constantly. The limit or
capacity of the channel, anyway, should be split between the two directions.

18. What do you mean by MTU?

MTU (Maximum Transmission Unit) is considered the largest size frame or packet that a
network-connected device will accept. Its default size is 1500 bytes which is the largest Ethernet
standard unit. TCP (Transmission Control Protocol) generally uses MTU to determine the
maximum size of each packet in any transmission.

19. What are different types of cables used in routing?

There are basically three different types of cables used in routing:

Straight Cable: These cables are used to connect different group devices. It is especially used in
LAN to connect different devices such as computers to a network hub like a router, PC and switch,
router and switch, etc. Its ultimate goal is to connect a host to the client.

Cross Cable: These cables are used to connect the same group of devices. It is considered one of
the most commonly used cable formats for network cables. It is especially used when two similar
devices need to be connected. Cross cables are also known as cross-wired cables.

Rollover Cable: These cables are used to connect the console port of the computer. This cable is
specially designed flat to help distinguish it from other types of cables. It generally allows
programmers to connect to network devices and can also manipulate the programming whenever
needed. Rollover cables are also known as Yost cable, Cisco cable, or a Console cable.

20. Explain network latency.

Network latency basically represents the delay in communication over a network. It simply refers to
the performance of one device when it communicates with another. It is the time taken for some
data to go from the source to its destination across the network. Network latency can be affected by
bandwidth speed, cabling, network card performance, and congestion.

21. What do you mean by User mode and Privileged mode?

User Mode: User mode is generally used to view the configurations of the routers. It allows us to
view basic system information, check router status, connect to remote devices, etc. User mode is
mostly used to perform regular tasks on the router when we are using a Cisco router.

Privileged Mode: Privileged mode is generally used to view all the configurations on the router. It
allows you to change configurations that are less important. Privileged mode is mostly used to
perform high-level tasks on the routers such as making configurations and debugging.

22. What do you mean by Windows in terms of networking?

In terms of networking, the window is the number of segments that are allowed to be transferred
from the source to the destination before any acknowledgment is sent.

23. What is the function of an LLC sublayer?

LLC (Logical Link Control) is basically the upper sublayer of the data link layer and acts as an
interface between the network layer and MAC sublayer of the data link layer of the OSI model.
This sublayer provides the logic for data link as it controls the synchronization, flow control,
multiplexing, and also error checking functions of the data link layer. It simply provides optional
services to an application developer.

CCNA Interview Questions for Experienced

24. What do you mean by EIGRP? Mention some metrics of EIGRP Protocol.

EIGRP (Enhanced Interior Gateway Routing Protocol) is referred to as Cisco's IGP (Interior
Gateway Protocol) that is used on a computer network especially for automating routing decisions
and configurations. This protocol is suited for different topologies and media. It is mostly used on a
router to share routes with other routers within the same autonomous system.

EIGRP Protocol generally includes the following metrics:

 Bandwidth
 Load
 Delay
 Reliability
 MTU
 Maximum Transmission Unit

25. What is CDP? Write its functions.

CDP (Cisco Discovery Protocol) is a Layer 2, media-independent, and network-independent


protocol that runs on all the Cisco devices that helps us to discover Cisco devices on the network.
This protocol works on the basis of MAC address. It also facilitates the management of Cisco
devices by discovering these devices, identifying how to configure them, and allowing systems to
learn about each other using different network-layer protocols. Some of its functions include:

 Collects information about directly connected neighboring devices.


 Find adjacent Cisco devices.
 Find out port numbers, IP addresses, router models, switch models, interface details, iOS details, device ID-
hostname.
 Simplifies the process of keeping an up-to-date inventory of Cisco network devices.
 Share information about other directly connected Cisco equipment like OS version, IP addresses.

26. What do you mean by VLAN? Write its main objective.


VLAN (Virtual Local Area Network) is basically a logical group of workstations, services, or
network devices that communicate with one another on a separate physical LAN. It improves the
network performance or applies some additional security features. It also allows several networks to
work virtually as if they were a LAN sharing a single broadcast domain.

27. What are the benefits of using VLAN?

There are several advantages of using VLAN:

 Removes latency and traffic load on the network


 Saves network resources and increases network efficiency
 Reduces IT cost and the incidence of collisions
 Improve network security and performance
 Ensure network flexibility and provide easier management
 Make it easier to relocate a network or a network device
 Increase the number of broadcast domains while decreasing the size of broadcast domains.
 Establish broadcast domains in switched networks.

28. What do you mean by a broadcast domain and a collision domain?

Broadcast Domain: As the name suggests, a Broadcast domain is a logical set of reachable
computer systems without having a router. In this type of domain, traffic flows all over the network.
In this scenario, when a device sends a broadcast message, then all the other devices present in its
broadcast domain have to pay attention to it.

Collision Domain: As the name suggests, a Collision domain is a part of a network where packet
collisions can take place when being sent on a shared medium or through repeaters. In this scenario,
when a device sends a message to a network, then all other devices present in its collision domain
have to pay attention to it, whether or not it was destined for them.
29. Explain BootP.

BootP (Bootstrap Protocol or Boot Program) is defined as a computer networking protocol that is
being used by a client for obtaining an IP address of a server PC. In a network, BootP is generally
used for booting diskless workstations. These diskless workstations use BootP to get their own IP
address as well as the server’s IP address. It was originally designed to replace RARP (Reverse
Address Resolution Protocol), also known as RFC 903.

30. What do you mean by route poisoning?

Route poisoning refers to a method that prevents certain networks from sending data packets to path
destinations that have already become invalid. This method is being employed by distance vector
routing protocols like RIPv2 whenever they see any invalid route to prevent routing loops. It is
generally used to overcome large routing loops and informs all the connected routers in a network
about the path that is invalid by saying that it has a hop count that exceeds the maximum allowable.

31. Write difference between static and dynamic IP addressing.

Static vs Dynamic IP address:

Static IP address Dynamic IP address

This IP address is generally provided by ISP (Internet This IP address is generally provided by DHCP
Service Provider). (Dynamic Host Configuration Protocol).

The address does not change whenever a device is assigned The address changes over time whenever a device is
a static IP address by the network administrator. assigned a dynamic IP address.

It is less secure and more difficult to designate as It is more secure and easy to designate as compared
compared to dynamic IP addresses. to static IP addresses.

It is more appropriate for a business. It is more appropriate for a home network.

These are costlier to deploy and more difficult to manage These are cheaper to deploy and easier to manage as
as compared to dynamic IP addresses. compared to static IP addresses.

It is more suitable for dedicated services like mail, VPN It is more suitable for a large network that requires
and FTP servers, etc. internet access to all devices.

It is mostly used where computational data is less It is mostly used where data is more confidential
Static IP address Dynamic IP address

confidential. and requires higher security.

32. What is network congestion? When network congestion happens?

Network congestion is a situation that occurs when a network node is overloaded with data or
traffic and can cause a common problem for admins. It usually occurs when the network is carrying
or exchanging more data than the network devices like routers and switches can accommodate. It is
a result of an internet route becoming too full when many users try using the same bandwidth. This
condition is true in big networks that do not resort to network segmentation.

33. What are two types of networks in CCNA?

Two types of networks in CCNA includes:

Server-based network: Client-Server networks can also be referred to as Server-Based networks.


A server is a node that provides services to clients. In this, a Centralized server is used to store the
data because its management is centralized.

Peer-to-Peer network: A peer-to-peer network is also known as a computer-to-computer network


or P2P. Peers are nodes or computer systems that are connected to one another. Every node in this
kind of network is connected to another node.

34. What are types of passwords that can be used in CISCO routers?

Different types of passwords that can be used in CISCO routers include:

 Enabled: This is a global command that disables privileged execution mode. The password is not encrypted.
To change it, one can use "enable password password"
 Enable Secret: In place of an enable password, this secret password is used. To change it, one can use
"enable secret password".
 AUX (Auxiliary): Passwords for auxiliary ports can be set using an auxiliary password. Through a modem, a
router can be accessed via this port.
 Console: Console port passwords are set using the console password.
 VTY (Virtual Terminal): For Telnet sessions into the router, you will need the virtual terminal password.
Passwords can be changed at any time. You can set it up when you configure the router from the console.

35. Write difference between public IP and private IP.

Public IP Private IP

It is mostly used within a private network or LAN to connect


It is used on public networks.
securely with other devices within the same network.

It is usually assigned by a Service provider or


It is usually assigned by a LAN administrator.
IANA.

It is generally used to communicate outside


It is generally used to communicate within the same network.
the network.

It can be known by searching “what is my IP”


It can be known by typing “ipconfig” on the command prompt.
on google.

Its scope is global. Its scope is local to the present network.


Public IP Private IP

These come with a cost and are controlled by


These are free of cost and are used to load network OS.
ISP.

It is routable and therefore, communication It is not routable and therefore, communication among different
among different users is possible. users is not possible.

Address ranges to be used by private networks are:


It can be any number not included in the Class A: 10.0.0.0 - 10.255.255.255
reserved private IP address range. Class B: 172.16.0.0 - 172.31.255.255
Example: 202.60.23.1 Class C: 192.168.0.0 - 192.168.255.255
Example: 192.168.0.3

36. Write the main function of the application layer in networking?

The application layer is the topmost layer in the OSI model that is used by end-user software such
as web browsers and email clients. It is considered as the layer through which users interact. It
usually consists of some protocols that are more focused on process-to-process communication
across an IP Network. Some of its functions include:

 Manage data exchange in a peer-to-peer or a client-server networking model.


 Provide firm communication interface and end-user services.
 Enables users to access the network.
 Provide the basis for email forwarding and storage facilities.
 Allows access to global information about different services.

37. Explain PoE.

PoE (Power on Ethernet) generally refers to a technology that allows electric power to be carried
over the Ethernet cable that carries data. It passes the electric power supply to the network through
the cable rather than the power cords and minimizes the number of wires required to install the
network.

38. What do you mean by OSPF?

OSPF (Open Shortest Path First) is basically a popular link-state routing protocol for IP networks
that are used to connect to a large number of networks without any limitation on the number of
hops. It determines the best route for delivering the data packets within an IP network. It has been
implemented by a wide range of network vendors such as Cisco. It works on Dijkstra Algorithm.

 Firstly, a shortest-path tree is constructed.


 Secondly, the routing table is populated with the resulting best paths.

39. Write difference between RIP and IGRP.

RIP (Routing Information Protocol) IGRP (Interior Gateway Routing Protocol)

It is a distance vector-based routing protocol. It is a distance vector-based interior gateway routing protocol.

It is used to calculate the metric in terms of Hop It is used to calculate the metric in terms of bandwidth, load,
count. and delay.
RIP (Routing Information Protocol) IGRP (Interior Gateway Routing Protocol)

It is an industry-standard dynamic protocol and It is a Cisco standard dynamic protocol and is mainly used for
is mainly used for smaller-sized organizations. medium to large-sized organizations.

It is denoted by ‘R’ in the routing table and It is denoted by ‘I’ in the routing tables and supports 255
supports 15 routers max. routers max.

We cannot create a separate administrative Using autonomous System numbers, we can create a separate
boundary in the network in the RIP routing administrative boundary in the network in the IGRP routing
protocol. protocol.

You might also like