Table of contents
1.
Introduction
2.
Beginner level Cognizant Interview Question
2.1.
1. Explain malloc?
2.2.
2. Explain the mark & sweep algorithm
2.3.
3. Explain the difference between multitasking & multithreading
2.4.
4. What is a dangling pointer?
2.5.
5. What is agile methodology?
2.6.
6. Explain the concept of pointers in C along with example.
2.7.
7. What is virtual memory?
2.8.
8. What is an IP address & its types?
2.9.
9. What is a bootloader?
2.10.
10. Can you explain memory leaks?
3.
Intermediate Cognizant Interview Question
3.1.
11. Explain the concept of recursion
3.2.
12. What are DML statements?
3.3.
13. What is an IP address & its types?
3.4.
14. What is a constructor?
3.5.
15. Describe OSI model layers
3.6.
16. Write a program to find power of a number
3.7.
17. Write a program to reverse a linked list
3.8.
18. What is DNS & how does it work?
3.9.
19. Write a code to reverse a number in Java
3.10.
20. Explain process synchronization & its methods
4.
Advanced Cognizant Interview Questions
4.1.
21. What is subnetting & why is it used?
4.2.
22. What is the difference between NAT & PAT?
4.3.
23. What are the different types of file systems?
4.4.
24. Explain the difference between abstraction & encapsulation
4.5.
25. What is the advantage of using a Trie over a Binary Search Tree?
4.6.
26. What is the difference between stack & queue?
4.7.
27. Discuss the principles of functional programming 
4.8.
28. Discuss the differences between IPv4 & IPv6
4.9.
29. Write a program to reverse a linked list
4.10.
30. Explain the concept of VLANs & its advantages
5.
Conclusion
Last Updated: Jul 1, 2024
Easy

Cognizant Interview Question

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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.

Cognizant Interview Question

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

DefinitionRunning multiple processes simultaneouslyRunning multiple threads within a single process
Resource SharingProcesses have separate memory spacesThreads share the same memory space
Context SwitchingOccurs between processes, more overheadOccurs between threads, less overhead
CommunicationInter-process communication mechanismsShared 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 : 

  1. Iterative development in short sprints
     
  2. Frequent communication & collaboration with stakeholders
     
  3. Embracing change & adapting to feedback
     
  4. Delivering working software incrementally
     
  5. 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:

  1. Declaring a pointer: int* ptr;
     
  2. Assigning an address to a pointer: ptr = &variable;
     
  3. Dereferencing a pointer to access the value: *ptr
     
  4. 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 = &num;
    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:

 

  1. IPv4: 32-bit addresses represented in dotted-decimal notation (e.g., 192.168.0.1). It provides about 4.3 billion unique addresses.
  2. 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:

  1. Base case: The condition where the recursion stops & returns a value without further recursive calls.
     
  2. 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:

  1. INSERT: Adds new rows of data into a table
     
  2. UPDATE: Modifies existing data in a table
     
  3. DELETE: Removes rows of data from a table
     
  4. 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:

  1. IPv4: 32-bit addresses represented in dotted-decimal notation (e.g., 192.168.0.1). It provides about 4.3 billion unique addresses.
     
  2. 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

7ApplicationProvides services to applications (e.g., HTTP, FTP)
6PresentationHandles data formatting, encryption, & compression
5SessionEstablishes, manages, & terminates sessions between applications
4TransportProvides end-to-end data delivery & error recovery (e.g., TCP, UDP)
3NetworkRoutes data packets between network devices (e.g., IP)
2Data LinkProvides reliable data transfer between adjacent network nodes
1PhysicalDefines 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:

  1. A user enters a domain name in their web browser.
     
  2. The browser sends a DNS query to the local DNS resolver (usually provided by the ISP).
     
  3. The resolver checks its cache for the corresponding IP address. If found, it returns the IP address to the browser.
     
  4. If not found, the resolver sends a query to the root DNS servers.
     
  5. The root servers respond with the IP address of the relevant Top-Level Domain (TLD) server (e.g., .com, .org).
     
  6. The resolver then queries the TLD server, which responds with the IP address of the authoritative name server for the domain.
     
  7. The resolver queries the authoritative name server, which returns the IP address associated with the domain name.
     
  8. The resolver caches the IP address & returns it to the browser.
     
  9. 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:

  1. 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.
     
  2. 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.
     
  3. 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.
     
  4. 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.
     
  5. 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:

  1. Efficient utilization of IP address space
     
  2. Improved network performance by reducing broadcast traffic
     
  3. Enhanced security by isolating network segments
     
  4. Simplified network management & troubleshooting

22. What is the difference between NAT & PAT?

Parameters

NAT (Network Address Translation)

PAT (Port Address Translation)

MappingMaps private IP addresses to public IP addressesMaps private IP addresses & ports to a single public IP address
IP AddressUses a pool of public IP addressesUses a single public IP address
Port NumbersDoes not change port numbersChanges port numbers to uniquely identify connections
Simultaneous ConnectionsLimited by the number of available public IP addressesAllows thousan

 

23. What are the different types of file systems?

There are several types of file systems used in operating systems:

  1. FAT (File Allocation Table): Simple & widely supported, used in DOS & early versions of Windows.
     
  2. NTFS (New Technology File System): Default file system in modern Windows versions, provides security, reliability, & large file support.
     
  3. ext (Extended File System): Common in Linux systems, includes ext2, ext3, & ext4 versions.
     
  4. HFS+ (Hierarchical File System Plus): Used in macOS, optimized for performance & supports long filenames.
     
  5. APFS (Apple File System): Newer file system used in macOS, iOS, & other Apple operating systems, designed for flash storage & encryption.
     
  6. 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

DefinitionHiding unnecessary details & providing a simplified viewBundling data & methods into a single unit & restricting access
FocusWhat an object doesHow an object does it
AccessDefines a public interface for interactionControls access to internal details using access modifiers
PurposeReduces complexity & improves understandingEnsures data integrity & provid

 

25. What is the advantage of using a Trie over a Binary Search Tree?

  1. Tries are quicker to lookup keys. Looking up a key of length m takes O(m) time in the worst-case scenarioLookups 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.
     
  2. Nodes are shared between keys with common sub-sequences. Tries with a large number of short keys are more efficient.
     
  3. Tries facilitate longest-prefix matching and assist in discovering the key with the longest possible prefix of unique characters.
     
  4. 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

OrderLIFO (Last In, First Out)FIFO (First In, First Out)
AccessElements are inserted & removed from the topElements are inserted at the rear & removed from the front
Operationspush (insert), pop (remove), peek (view top element)enqueue (insert), dequeue (remove), front (view first element)
UsageFunction call stack, undo/redo operationsTask 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.

28. Discuss the differences between IPv4 & IPv6

Parameters

IPv4

IPv6
Address Size32 bits128 bits
Address FormatDotted decimal notation (e.g., 192.168.0.1)Hexadecimal notation (e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334)
Address SpaceApproximately 4.3 billion unique addressesApproximately 340 undecillion unique addresses
Header FormatSimpler header with 12 fieldsStreamlined header with 8 fields
SecurityOptional support for IPsecMandatory support for IPsec
Quality of ServiceRelies on Type of Service (ToS) fieldIncludes Flow Label field for better QoS handling
FragmentationAllowed by routers & hostsOnly allowed by hosts, not routers

29. Write a program to reverse a linked list

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. 

Some advantages of VLANs are:

  1. Improved security by isolating network traffic
     
  2. Reduced broadcast traffic & improved network performance
     
  3. Simplified network management & configuration
     
  4. Increased flexibility in network design & device placement
     
  5. 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

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass