Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Cognizant is a leading technology company that conducts interviews to hire skilled professionals. The interview process covers many topics to assess a candidate's technical knowledge, problem-solving abilities, & communication skills.
In this article, we'll talk about some commonly asked Cognizant interview questions, which includes the concepts like malloc, mark & sweep algorithm, multitasking vs multithreading, dangling pointers, agile methodology, pointers in C, recursion, virtual memory, IP addresses, & memory leaks and many more.
Beginner level Cognizant Interview Question
1. Explain malloc?
Malloc is a function in C used to dynamically allocate memory at runtime. It takes the number of bytes to allocate as an argument & returns a pointer to the allocated memory block. The allocated memory persists until it is explicitly freed using the free() function or until the program terminates.
2. Explain the mark & sweep algorithm
The mark & sweep algorithm is a garbage collection technique used to automatically manage memory in programming languages like Java. It consists of two phases:
Mark phase: The garbage collector traverses the object graph starting from the root objects & marks all reachable objects as alive.
Sweep phase: The garbage collector scans the heap & frees the memory occupied by unmarked (dead) objects.
The mark & sweep algorithm helps prevent memory leaks by reclaiming memory that is no longer in use by the program.
3. Explain the difference between multitasking & multithreading
Parameters
Multitasking
Multithreading
Definition
Running multiple processes simultaneously
Running multiple threads within a single process
Resource Sharing
Processes have separate memory spaces
Threads share the same memory space
Context Switching
Occurs between processes, more overhead
Occurs between threads, less overhead
Communication
Inter-process communication mechanisms
Shared memory & synchronization primitives
4. What is a dangling pointer?
A dangling pointer is a pointer that points to a memory location that has been freed or deallocated. Dereferencing or using a dangling pointer can lead to undefined behavior, crashes, or security vulnerabilities.
5. What is agile methodology?
Agile methodology is an iterative & incremental approach to software development. It emphasizes flexibility, collaboration, & rapid delivery of working software.
Important principles of agile are :
Iterative development in short sprints
Frequent communication & collaboration with stakeholders
Embracing change & adapting to feedback
Delivering working software incrementally
Continuous integration & testing
6. Explain the concept of pointers in C along with example.
Pointers in C are variables that store the memory address of another variable. They allow direct access to memory locations & enable efficient memory manipulation. Key points about pointers:
Declaring a pointer: int* ptr;
Assigning an address to a pointer: ptr = &variable;
Dereferencing a pointer to access the value: *ptr
Pointers can be used for dynamic memory allocation, passing function arguments by reference, & implementing data structures like linked lists.
Here's an example of using pointers:
#include <stdio.h>
int main() {
int num = 10;
int* ptr = #
printf("Value: %d\n", *ptr); // Output: 10
printf("Address: %p\n", (void*)ptr); // Output: Address of num
return 0;
}
7. What is virtual memory?
Virtual memory is a memory management technique used by operating systems to provide the illusion of a larger memory space than the actual physical memory. It allows programs to run even when their memory requirements exceed the available physical memory.
8. What is an IP address & its types?
An IP address is a unique identifier assigned to each device connected to a network. It allows devices to communicate & route data packets. There are two main types of IP addresses:
IPv4: 32-bit addresses represented in dotted-decimal notation (e.g., 192.168.0.1). It provides about 4.3 billion unique addresses.
IPv6: 128-bit addresses represented in hexadecimal notation (e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334). It provides a vastly larger address space to accommodate the growing number of devices.
9. What is a bootloader?
A bootloader is a small program that loads the operating system into memory when a computer starts up. It is the first piece of software that runs when a computer is turned on. The bootloader is responsible for initializing hardware, loading the kernel into memory, & transferring control to the operating system. It resides in a specific sector of the boot device, such as a hard drive or a bootable CD/DVD.
10. Can you explain memory leaks?
Memory leaks occur when a program fails to free allocated memory that is no longer needed, leading to a gradual depletion of available memory. They can cause performance degradation, crashes, or even system instability. Memory leaks can happen due to:
Forgetting to free dynamically allocated memory
Losing track of pointers to allocated memory
Circular references preventing objects from being garbage collected
Intermediate Cognizant Interview Question
11. Explain the concept of recursion
Recursion is a programming technique where a function calls itself to solve a problem by breaking it down into smaller subproblems. It consists of two parts:
Base case: The condition where the recursion stops & returns a value without further recursive calls.
Recursive case: The condition where the function calls itself with modified arguments to solve smaller subproblems.
Here's an example of a recursive function to calculate the factorial of a number:
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}
int main() {
int num = 5;
int result = factorial(num);
printf("Factorial of %d is %d\n", num, result); // Output: Factorial of 5 is 120
return 0;
}
Output
Factorial of 5 is 120
12. What are DML statements?
DML stands for Data Manipulation Language. It is a subset of SQL (Structured Query Language) used to manipulate data stored in a database. DML statements are used to insert, update, delete, & retrieve data from database tables.
The common DML statements are:
INSERT: Adds new rows of data into a table
UPDATE: Modifies existing data in a table
DELETE: Removes rows of data from a table
SELECT: Retrieves data from one or more tables
13. What is an IP address & its types?
An IP address is a unique identifier assigned to each device connected to a network. It allows devices to communicate & route data packets.
There are two main types of IP addresses:
IPv4: 32-bit addresses represented in dotted-decimal notation (e.g., 192.168.0.1). It provides about 4.3 billion unique addresses.
IPv6: 128-bit addresses represented in hexadecimal notation (e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334). It provides a vastly larger address space to accommodate the growing number of devices.
14. What is a constructor?
A constructor is a special method in object-oriented programming that is automatically invoked when an object of a class is created. It has the same name as the class & is used to initialize the object's state (i.e., its properties or attributes). Constructors can accept parameters to set initial values for the object's properties. If no explicit constructor is defined, a default constructor with no parameters is provided by the compiler.
15. Describe OSI model layers
The OSI (Open Systems Interconnection) model is a conceptual framework that standardizes communication functions in a network.
It consists of seven layers:
Layer
Name
Description
7
Application
Provides services to applications (e.g., HTTP, FTP)
6
Presentation
Handles data formatting, encryption, & compression
5
Session
Establishes, manages, & terminates sessions between applications
4
Transport
Provides end-to-end data delivery & error recovery (e.g., TCP, UDP)
3
Network
Routes data packets between network devices (e.g., IP)
2
Data Link
Provides reliable data transfer between adjacent network nodes
1
Physical
Defines physical characteristics of the network (e.g., cables, connectors)
16. Write a program to find power of a number
public class PowerOfNumber {
public static int power(int base, int exponent) {
if (exponent == 0) {
return 1;
} else {
return base * power(base, exponent - 1);
}
}
public static void main(String[] args) {
int base = 2;
int exponent = 5;
int result = power(base, exponent);
System.out.println(base + "^" + exponent + " = " + result);
}
}
17. Write a program to reverse a linked list
public class ReverseLinkedList {
private static class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode nextNode = current.next;
current.next = prev;
prev = current;
current = nextNode;
}
return prev;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
System.out.println("Original Linked List:");
printList(head);
head = reverseList(head);
System.out.println("Reversed Linked List:");
printList(head);
}
private static void printList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
System.out.println();
}
}
18. What is DNS & how does it work?
DNS stands for Domain Name System. It is a hierarchical decentralized naming system that translates human-readable domain names (e.g., www.example.com) into IP addresses (e.g., 192.0.2.1). DNS acts as the phone book of the internet, allowing users to access websites using easy-to-remember domain names instead of numerical IP addresses.
How DNS works:
A user enters a domain name in their web browser.
The browser sends a DNS query to the local DNS resolver (usually provided by the ISP).
The resolver checks its cache for the corresponding IP address. If found, it returns the IP address to the browser.
If not found, the resolver sends a query to the root DNS servers.
The root servers respond with the IP address of the relevant Top-Level Domain (TLD) server (e.g., .com, .org).
The resolver then queries the TLD server, which responds with the IP address of the authoritative name server for the domain.
The resolver queries the authoritative name server, which returns the IP address associated with the domain name.
The resolver caches the IP address & returns it to the browser.
The browser uses the IP address to establish a connection with the web server & retrieve the requested website.
19. Write a code to reverse a number in Java
public class ReverseNumber {
public static int reverse(int number) {
int reversed = 0;
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
return reversed;
}
public static void main(String[] args) {
int number = 12345;
int reversedNumber = reverse(number);
System.out.println("Original number: " + number);
System.out.println("Reversed number: " + reversedNumber);
}
}
20. Explain process synchronization & its methods
Process synchronization is the coordination of simultaneous processes or threads to ensure correct execution & avoid race conditions. It involves mechanisms to control the access of shared resources & maintain data consistency. Process synchronization is necessary when multiple processes or threads access shared data concurrently to prevent data corruption or inconsistent results.
Methods of process synchronization:
Locks: A lock is a synchronization primitive that allows only one process or thread to enter a critical section at a time. It provides mutual exclusion & ensures that only the process holding the lock can access the shared resource.
Semaphores: Semaphores are integer variables used to control access to shared resources. They have two main operations: wait (decrement) & signal (increment). Semaphores can be used for both mutual exclusion & condition synchronization.
Monitors: Monitors are high-level synchronization constructs that encapsulate shared data & provide a set of methods to access & manipulate the data. They ensure that only one process or thread can execute a method on the monitor object at a time.
Message Passing: Message passing is a synchronization mechanism where processes or threads communicate by sending & receiving messages. It allows synchronization through the exchange of messages, which can include data & control information.
Barriers: Barriers are synchronization points where multiple processes or threads must wait until all of them reach the barrier. Once all processes have reached the barrier, they can proceed further, allowing for synchronization & coordination.
Advanced Cognizant Interview Questions
21. What is subnetting & why is it used?
Subnetting is the process of dividing a larger network into smaller subnetworks (subnets). It involves partitioning the IP address space into smaller addressable units.
Subnetting is used for several reasons. Some of them are:
Efficient utilization of IP address space
Improved network performance by reducing broadcast traffic
Enhanced security by isolating network segments
Simplified network management & troubleshooting
22. What is the difference between NAT & PAT?
Parameters
NAT (Network Address Translation)
PAT (Port Address Translation)
Mapping
Maps private IP addresses to public IP addresses
Maps private IP addresses & ports to a single public IP address
IP Address
Uses a pool of public IP addresses
Uses a single public IP address
Port Numbers
Does not change port numbers
Changes port numbers to uniquely identify connections
Simultaneous Connections
Limited by the number of available public IP addresses
Allows thousan
23. What are the different types of file systems?
There are several types of file systems used in operating systems:
FAT (File Allocation Table): Simple & widely supported, used in DOS & early versions of Windows.
NTFS (New Technology File System): Default file system in modern Windows versions, provides security, reliability, & large file support.
ext (Extended File System): Common in Linux systems, includes ext2, ext3, & ext4 versions.
HFS+ (Hierarchical File System Plus): Used in macOS, optimized for performance & supports long filenames.
APFS (Apple File System): Newer file system used in macOS, iOS, & other Apple operating systems, designed for flash storage & encryption.
exFAT (Extended File Allocation Table): Optimized for flash drives & supports large files, compatible with multiple operating systems.
24. Explain the difference between abstraction & encapsulation
Parameters
Abstraction
Encapsulation
Definition
Hiding unnecessary details & providing a simplified view
Bundling data & methods into a single unit & restricting access
Focus
What an object does
How an object does it
Access
Defines a public interface for interaction
Controls access to internal details using access modifiers
Purpose
Reduces complexity & improves understanding
Ensures data integrity & provid
25. What is the advantage of using a Trie over a Binary Search Tree?
Tries are quicker to lookup keys. Looking up a key of length m takes O(m) time in the worst-case scenario. Lookups depend on the depth of the tree, which is logarithmic to the number of keys if it is balanced. A BST does O(log n) key comparisons and takes O(m log n) time in the worst-case scenario.
Nodes are shared between keys with common sub-sequences. Tries with a large number of short keys are more efficient.
Tries facilitate longest-prefix matching and assist in discovering the key with the longest possible prefix of unique characters.
The length of the key is equal to the number of internal nodes from root to leaf. As a result, balancing the tree isn't an issue.
26. What is the difference between stack & queue?
Parameters
Stack
Queue
Order
LIFO (Last In, First Out)
FIFO (First In, First Out)
Access
Elements are inserted & removed from the top
Elements are inserted at the rear & removed from the front
Operations
push (insert), pop (remove), peek (view top element)
enqueue (insert), dequeue (remove), front (view first element)
Usage
Function call stack, undo/redo operations
Task scheduling, print spooling, b
27. Discuss the principles of functional programming
Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions & avoids changing state & mutable data.
The main principles of functional programming are:
Immutability: Data is immutable, meaning it cannot be changed once created. Instead of modifying data, new data structures are created.
Pure functions: Functions have no side effects & always produce the same output for the same input. They rely only on their input parameters.
Recursion: Recursive functions are used for iteration instead of loops. Functions call themselves with smaller subproblems until a base case is reached.
Higher-order functions: Functions can take other functions as parameters & return functions as results, enabling powerful abstractions.
Lazy evaluation: Expressions are evaluated only when their results are needed, allowing for efficient handling of large or infinite data structures.
Functional programming promotes code reusability, modularity, & easier testing & debugging due to the absence of side effects & mutable state.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
# Example usage
# Create a linked list: 1 -> 2 -> 3 -> 4 -> 5
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
# Reverse the linked list
reversed_head = reverseList(head)
# Print the reversed linked list
while reversed_head:
print(reversed_head.val, end=" ")
reversed_head = reversed_head.next
Implement a function to check if a string is a palindrome
def isPalindrome(s):
# Remove non-alphanumeric characters & convert to lowercase
s = ''.join(c.lower() for c in s if c.isalnum())
# Check if the string is equal to its reverse
return s == s[::-1]
30. Explain the concept of VLANs & its advantages
VLANs (Virtual Local Area Networks) are logical subnetworks created within a physical network. They allow for the segmentation of a network into separate broadcast domains, regardless of the physical location of devices.
Increased flexibility in network design & device placement
Support for logical grouping of devices based on functions or departments
VLANs are configured on network switches & use VLAN tagging (IEEE 802.1Q) to identify & segregate traffic between different VLANs.
Conclusion
We hope you have gained some insights on Cognizant Interview Questions through this article. We understand that preparing for interviews can be nerve-wracking and hope these Cognizant Interview Questions will help you during your interviews and you learn and grow in your role!
You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360.