INTERVIEW QUESTIONS
INTERVIEW QUESTIONS
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
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.
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.
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 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
printf(): The printf() function is used to print the integer, character, float and string values on to the screen.
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?
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.
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.
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
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.
When a function calls itself, and this process is known as recursion. The function that calls itself is known as a
recursive function.
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.
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.
One-dimensional array: One-dimensional array is an array that stores the elements one after the another.
Multidimensional array: Multidimensional array is an array that contains more than one array.
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.
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
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.
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.
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
o Dangling pointer arises when an object is deleted without modifying the value of the pointer. The pointer points to
o The problem of a dangling pointer can be overcome by assigning a NULL value to the dangling pointer
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.
o In case of static memory allocation, memory is allocated at compile time, and memory can't be increased while
o In case of dynamic memory allocation, memory is allocated at runtime and memory can be increased while
o The malloc() or calloc() function is required to allocate the memory at the runtime.
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.
2. calloc()
o The calloc() is same as malloc() function, but the difference only is that it initializes the memory with
zero value.
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.
4. free():
The free() function releases the memory allocated by either calloc() or malloc() function.
Syntax = free(ptr);
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.
Return value It returns a pointer pointing to the allocated memory. It returns a pointer pointing to the allocated memory.
o The structure is a user-defined data type that allows storing multiple types of data in a single unit. It occupies the
o Structure variables accessing the same structure but the memory allocated for each variable will be different.
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.
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.
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.
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.
5. Special characters: All the characters except alphabets and digits are treated as special characters.
The argument passed to the main() function while executing the program is known as command line argument.
For example:
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]);
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.
#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;
}
#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();
}
#include<stdio.h>
#include<conio.h>
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.
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.
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().
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.
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.
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;
}
#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.
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.
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
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
int main()
{
int n = 8;
return 0;
}
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.
mergedTail->next = temp;
mergedTail = temp;
}
if (head1 != nullptr) {
mergedTail->next = head1;
} else if (head2 != nullptr) {
mergedTail->next = head2;
}
return mergedHead;
}
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.
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.
The main difference between C and C++ are provided in the table below:
C C++
Function and operator overloading are not supported Function and operator overloading is supported
in C in C++
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.
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
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.
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.
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;
}
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.
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
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;
}
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.
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.
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.
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?
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.
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 ::
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.
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 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 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(){
}
};
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.
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;
}
}
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;
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;
}
The new operator is used for memory allocation and deletes operator is used for memory
deallocation in C++.
For example-
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;
}
int main() {
std::string input = "racecar";
bool isPal = isPalindrome(input);
std::cout << "Is Palindrome: " << std::boolalpha << isPal << std::endl;
return 0;
}
```
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;
}
```
int main() {
int num = 12345;
int reversed = reverseInteger(num);
std::cout << "Reversed integer: " << reversed << std::endl;
return 0;
}
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
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.
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.
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.
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.
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.
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.
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.
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)
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.
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.
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:
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.
input_array = [1, 2, 3, 4, 5]
array_sum = sum_array(input_array)
print("Sum:", array_sum)
```
input_string = "racecar"
is_pal = is_palindrome(input_string)
print("Is Palindrome:", is_pal)
```
num = 50
fibonacci_series(num)
```
num = 12345
reversed_num = reverse_integer(num)
print("Reversed integer:", reversed_num)
```
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
print(array_1)
print(list_1)
Code
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)
Code
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.
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.
29) In Python, how would you randomise the elements of a list while it's
running?
Code
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
string = 'JAVATPOINT'
print(string.lower())
Code
"""
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:
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.
Code
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
Code
class My_Class:
def f(self):
print("f()")
import monk
def monkey_f(self):
print ("we are calling monkey_f()")
object_.func()
Code
class my_class:
pass
object_ = my_class()
object_.name = "Javatpoint"
print("Name = ", object_.name)
def bubble_Sort(array):
n = len(array)
for i in range(n-1):
print(array)
#example array
arr = [23, 14, 64, 13, 64, 23, 86]
bubble_Sort(arr)
for i in range(0,n-2):
series.append(num)
print(series)
# 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
# Creating a string
sequence = 'abjucujba'
# Reversing the string
reverse = sequence[::-1]
import numpy
array = numpy.array([4, 8, 4, 9, 2])
print(array.argsort()[-2:][::-1])
import numpy
array = numpy.array([3, 6, 1, 6, 5, 2])
percentile = numpy.percentile(array, 45) #Returns 45th percentile
print(percentile)
num = 1101001
while(num > 0):
l = num % 10
if l!=0 and l!=1:
break
num = num // 10
if num == 0:
num = 12
fact = 1
if num < 0:
print("Factorial of 0 is 1")
else:
fact = fact * i
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):
lcm = greater_num
break
greater_num += 1
print("LCM of", num_1, "and", num_2, "=", greater_num)
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)
array = [23, 12, 5, 24, 23, 76, 86, 24, 86, 24, 75]
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:
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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".
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?
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.
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.
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.
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.
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.
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.
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.
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.
Bandwidth
Load
Delay
Reliability
MTU
Maximum Transmission Unit
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.
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.
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.
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
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.
34. What are types of passwords that can be used in CISCO routers?
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.
Public IP Private IP
It is routable and therefore, communication It is not routable and therefore, communication among different
among different users is possible. users is not possible.
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:
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.
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.
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.