Here's a clear comparison between Python's built-in list and NumPy array:
Feature | Python List | NumPy Array |
---|---|---|
Data Type | Can store elements of different types | Stores elements of the same data type |
Performance | Slower for numerical operations | Faster due to optimized C backend |
Memory Efficiency | Less efficient (stores type info per item) | More memory-efficient |
Functionality | General-purpose container | Best for mathematical & matrix operations |
Operations | Element-wise ops need loops | Supports vectorized operations |
Libraries Needed | Built-in, no import needed | Requires import numpy as np |
Multidimensional Support | Limited (nested lists) | Powerful multidimensional support (ndarray ) |
a = [1, 2, 3]
b = [4, 5, 6]
print(a + b) # Output: [1, 2, 3, 4, 5, 6] (concatenation)
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # Output: [5 7 9] (element-wise addition)
#include<stdio.h>
int main()
{
int num1 = 36, num2 = 60, lcm;
// finding the larger number here
int max = (num1 > num2)? num1 : num2;
// LCM will atleast be >= max(num1, num2)
// Largest possibility of LCM will be num1*num2
for(int i = max ; i <= num1*num2 ; i++)
{
if(i % num1 == 0 && i % num2 == 0){
lcm = i;
break;
}
}
printf("The LCM: %d", lcm);
return 0;
}
// Time Complexity : O(N)
// Space Complexity : O(1)
In C++, the line:
using namespace std;
is used to tell the compiler to use the standard namespace (std
), which includes all the classes, functions, and objects of the C++ Standard Library.
Most standard C++ library features (like cout
, cin
, string
, vector
, etc.) are defined inside the std
namespace.
Without using namespace std;
, you would have to write:
std::cout << "Hello, world!" << std::endl;
With it, you can just write:
cout << "Hello, world!" << endl;
While using namespace std;
is convenient for small programs or beginners, it's discouraged in large projects or header files because:
It can cause naming conflicts if other libraries have functions or classes with the same names.
It pollutes the global namespace, making code less maintainable.
C |
C++ |
1. It is a structured programming language. |
1. It is an object-oriented programming language. |
2. There are no objects, classes, constructors, and so on in this language. |
2. There are objects, classes, constructors, and so on in this language. |
3. C is a subset of C++ |
3. C++ is a superset of C. |
4. It doesn't support polymorphism, inheritance, and other OOPS properties. |
4. It supports polymorphism, inheritance, and other OOPS properties. |
5. It doesn’t contain namespaces. |
5. It contains namespaces. |
A recursion function is a function that calls itself within its own definition. It's a powerful programming technique where a problem is solved by breaking it down into smaller, self-similar subproblems until a simple base case is reached.
Think of it like a set of Russian nesting dolls (Matryoshka dolls). Each doll contains a smaller version of itself until you reach the smallest doll, which doesn't contain any other.
Key Components of a Recursive Function:
Base Case: This is the crucial part of a recursive function. It's the condition under which the function stops calling itself. Without a proper base case, the function would call itself infinitely, leading to a stack overflow error (running out of memory to store the function calls). The base case represents the simplest form of the problem that can be solved directly.
Recursive Step (or Recursive Call): This is where the function calls itself with a smaller or simpler version of the original problem. The goal is to reduce the problem towards the base case with each recursive call.
How it Works (Conceptual Example: Calculating Factorial):
Let's say you want to calculate the factorial of a non-negative integer n
(denoted as n!
), which is the product of all positive integers less than or equal to n
(e.g., 5! = 5 * 4 * 3 * 2 * 1 = 120).
You can define the factorial recursively:
n
is 0, then n!
is 1 (0! = 1).n
is greater than 0, then n!
is n
multiplied by the factorial of n-1
(n! = n * (n-1)!).Here's how a recursive function for factorial might look in Python:
def factorial_recursive(n):
if n == 0: # Base case
return 1
else: # Recursive step
return n * factorial_recursive(n - 1)
# Example usage
result = factorial_recursive(5)
print(f"The factorial of 5 is: {result}") # Output: The factorial of 5 is: 120
Tracing the Execution for factorial_recursive(5)
:
factorial_recursive(5)
calls 5 * factorial_recursive(4)
factorial_recursive(4)
calls 4 * factorial_recursive(3)
factorial_recursive(3)
calls 3 * factorial_recursive(2)
factorial_recursive(2)
calls 2 * factorial_recursive(1)
factorial_recursive(1)
calls 1 * factorial_recursive(0)
factorial_recursive(0)
reaches the base case and returns 1
.factorial_recursive(1)
receives 1
and returns 1 * 1 = 1
.factorial_recursive(2)
receives 1
and returns 2 * 1 = 2
.factorial_recursive(3)
receives 2
and returns 3 * 2 = 6
.factorial_recursive(4)
receives 6
and returns 4 * 6 = 24
.factorial_recursive(5)
receives 24
and returns 5 * 24 = 120
.
Advantages of Recursion:
Disadvantages of Recursion:
When to Use Recursion:
Recursion is often a good choice when:
No, this()
and super()
method calls cannot be used within the same constructor in Java (and in languages with similar constructor chaining mechanisms).
Here's why:
They must be the first statement: Both this()
and super()
must be the very first statement in a constructor. This is because they are responsible for invoking another constructor (either in the same class using this()
or in the superclass using super()
) to initialize the object's state.
Constructor Chaining: The process of calling one constructor from another is known as constructor chaining. This ensures that the initialization logic of the current class and its superclass(es) is executed correctly in a specific order (superclass constructors are called before subclass constructors).
Mutual Exclusivity: Allowing both this()
and super()
in the same constructor would create ambiguity about which constructor should be invoked first. The language designers enforce the rule that only one of them can be the initial call to maintain a clear and predictable object initialization sequence.
Analogy:
Think of building a house. Before you can start working on the specific features of your house, you need to lay the foundation.
super()
is like saying, "First, let's build the foundation according to the blueprint of the parent house design."this()
is like saying, "First, let's use another blueprint we have for a slightly different foundation design within our own overall house plan."You can't decide to build two different foundations at the very beginning. You have to choose one to start with.
Example demonstrating the error:
//Java
class Parent {
Parent() {
System.out.println("Parent constructor");
}
}
class Child extends Parent {
Child() {
super(); // Calls the Parent's constructor (must be first)
// this(); // Error: Constructor call must be the first statement in a constructor
System.out.println("Child constructor");
}
Child(int value) {
// super(); // Can be here as the first statement
this(); // Calls the no-arg constructor of Child (must be first)
// super(); // Error: Constructor call must be the first statement in a constructor
System.out.println("Child constructor with value: " + value);
}
public static void main(String[] args) {
Child c1 = new Child();
Child c2 = new Child(10);
}
}
In the Child()
(no-argument) constructor, super()
is the first statement. If you tried to add this()
as well, it would result in a compile-time error.
Similarly, in the Child(int value)
constructor, this()
is the first statement, calling the Child()
constructor. You cannot have super()
as the first statement in this constructor as well.
//Java program to reverse a string
public class Main
{
public static void main(String[] args) {
String stringExample = "FreeTimeLearn";
System.out.println("Original string: "+stringExample);
//Declaring a StringBuilder
//and converting string to StringBuilder
StringBuilder reverseString = new StringBuilder(stringExample);
//Reversing the StringBuilder
reverseString.reverse();
//Converting StringBuilder to String
String result = reverseString.toString();
// Printing the reversed String
System.out.println("Reversed string: "+result);
}
}
Original string: FreeTimeLearn
Reversed string: nraeLemiTeerF
//Java program to Reverse a number
public class Main
{
public static void main(String[] args)
{
int n= 123456789, reversed = 0;
System.out.println("Original Number: " + n);
//Run the loop until n is equal to 0
while(n != 0)
{
//get last digit from n
int digit = n % 10;
reversed = reversed * 10 + digit;
//remove the last digit from num
n /= 10;
}
System.out.println("Reversed Number: " + reversed);
}
}
Original Number: 123456789
Reversed Number: 987654321
WYSIWYG stands for "What You See Is What You Get."
WYSIWYG refers to a system or interface where the content displayed during editing appears very similar—or exactly the same—as the final output (like a printed document or a published webpage).
Word processors (e.g., Microsoft Word, Google Docs)
Web editors (e.g., Wix, WordPress editors, Adobe Dreamweaver)
Email editors
Presentation software (e.g., PowerPoint)
When you type in Microsoft Word:
You apply bold, italic, or change fonts.
What you see on screen is almost exactly what gets printed.
* That’s WYSIWYG in action.
Here's a simple leap year program written in C++, Java, and Python — choose the one you'd like, or use all three as reference:
#include <iostream>
using namespace std;
int main() {
int year;
cout << "Enter a year: ";
cin >> year;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
cout << year << " is a leap year." << endl;
else
cout << year << " is not a leap year." << endl;
return 0;
}
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = sc.nextInt();
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Sure! Here's a simple implementation of a Doubly Linked List in C++, including operations to:
Insert at the end
Delete a node
Display the list
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* prev;
Node* next;
Node(int value) {
data = value;
prev = nullptr;
next = nullptr;
}
};
class DoublyLinkedList {
private:
Node* head;
public:
DoublyLinkedList() {
head = nullptr;
}
// Insert at the end
void insert(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next != nullptr)
temp = temp->next;
temp->next = newNode;
newNode->prev = temp;
}
// Delete a node with given value
void remove(int value) {
Node* temp = head;
while (temp != nullptr && temp->data != value)
temp = temp->next;
if (temp == nullptr) {
cout << "Value not found!" << endl;
return;
}
if (temp->prev != nullptr)
temp->prev->next = temp->next;
else
head = temp->next;
if (temp->next != nullptr)
temp->next->prev = temp->prev;
delete temp;
}
// Display list
void display() {
Node* temp = head;
cout << "Doubly Linked List: ";
while (temp != nullptr) {
cout << temp->data << " <-> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
};
int main() {
DoublyLinkedList dll;
dll.insert(10);
dll.insert(20);
dll.insert(30);
dll.display(); // 10 <-> 20 <-> 30 <-> NULL
dll.remove(20);
dll.display(); // 10 <-> 30 <-> NULL
return 0;
}
A Zombie Process in operating systems (especially Unix/Linux) is a process that has completed execution but still has an entry in the process table.
When a child process finishes execution, it sends a termination status to its parent. Until the parent process reads (or "reaps") this status using functions like wait()
or waitpid()
, the child stays in a "zombie" state.
Feature | Description |
---|---|
Process is dead | It has finished running |
Still in process table | Yes, with a status of Z (zombie) |
Consumes resources? | Minimal (just a slot in the process table) |
PID still exists | Yes, until the parent reads its exit status |
One or two zombies are harmless. But if many zombie processes accumulate, the process table can fill up, preventing new processes from being created — which can lead to system issues.
Make sure the parent process calls wait()
to clean up child processes.
Use a signal handler to catch the SIGCHLD
signal (child terminated).
If a parent dies before reaping, the init process (PID 1) adopts and reaps the zombie.
Run this in a terminal to simulate:
ps aux | grep Z
def function_fibo(value):
a,b = 0,1
print('The Fibonacci series is :',end= " ")
for i in range(2, value):
c = a + b
a = b
b = c
print(c, end=" ")
value = 15
function_fibo(value)
1 2 3 5 8 13 21 34 55 89 144 233 377
public class Main
{
public static void main(String[] args) {
double base = 1.5;
double expo1 = 2.5;
double expo2 = -2.5;
double res1, res2;
// calculates the power
res1 = Math.pow(base, expo1);
res2 = Math.pow(base, expo2);
System.out.println(base + " ^ " + expo1 + " = " + res1 );
System.out.println(base + " ^ " + expo2 + " = " + res2 );
}
}
#include<bits/stdc++.h>
using namespace std;
bool isPrime(int n){
int count = 0;
// 0, 1 negative numbers are not prime
if(n < 2)
return false;
// checking the number of divisors b/w 1 and the number n-1
for(int i = 2;i < n; i++)
{
if(n % i == 0)
return false;
}
// if reached here then must be true
return true;
}
int main()
{
int lower, upper;
lower=1,upper=100;
for(int i = lower; i <= upper; i++)
if(isPrime(i))
cout << i << " ";
}
// Time Complexity : O(N^2)
// Space Complexity : O(1)
Sure! An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
For example:
153
is an Armstrong number because:
1^3 + 5^3 + 3^3 = 153
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int num, originalNum, remainder, result = 0, n = 0;
cout << "Enter a number: ";
cin >> num;
originalNum = num;
// Count the number of digits
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
// Calculate the sum of nth powers of its digits
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}
if (result == num)
cout << num << " is an Armstrong number." << endl;
else
cout << num << " is not an Armstrong number." << endl;
return 0;
}