0% found this document useful (0 votes)
15 views30 pages

Code Practical

coes

Uploaded by

pramitkanzariya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views30 pages

Code Practical

coes

Uploaded by

pramitkanzariya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Great!

Below is a detailed explanation of each topic in C language, tailored for placement


preparation:

1. Basics of C

What is C?

C is a general-purpose, procedural programming language developed in the 1970s. It is the


foundation for many modern languages like C++, Java, etc.

Features:

• Fast execution

• Low-level memory access

• Portable and efficient

• Supports structured programming

Structure of a C Program:

#include<stdio.h>

int main() {

printf("Hello, World!");

return 0;

Key Concepts:

• Keywords: int, float, return, etc.

• Identifiers: Names for variables, functions, etc.

• Data Types: int, float, char, double

2. Operators and Expressions

Used to perform operations.

Type Examples

Arithmetic +, -, *, /, %

Relational ==, !=, <, >

Logical &&, `
Type Examples

Bitwise &, `

Assignment =, +=, -=

Example:

int a = 10, b = 5;

int result = a + b;

3. Control Structures

If-Else:

if (x > 0) {

printf("Positive");

} else {

printf("Negative");

Switch Case:

switch(choice) {

case 1: printf("One"); break;

default: printf("Other");

Loops:

• For Loop: Fixed iterations

for (int i = 0; i < 5; i++) {

printf("%d", i);

• While Loop: Entry-controlled

• Do-While Loop: Exit-controlled

4. Functions

Syntax:

returnType functionName(parameters) {
// code

return value;

Recursion:

A function calling itself.

int factorial(int n) {

if(n <= 1) return 1;

return n * factorial(n-1);

5. Arrays

One-Dimensional:

int arr[5] = {1, 2, 3, 4, 5};

Two-Dimensional (Matrix):

int matrix[2][2] = {{1,2},{3,4}};

6. Strings

Character arrays.

char name[20] = "Alice";

String Functions:

• strlen(str) – Length

• strcpy(dest, src) – Copy

• strcmp(str1, str2) – Compare

• strcat(str1, str2) – Concatenate

7. Pointers

Stores memory address of another variable.

int x = 5;

int *ptr = &x;

Pointer & Arrays:

int arr[3] = {1,2,3};


int *p = arr; // Points to arr[0]

8. Structures & Unions

Structure:

struct Student {

int id;

char name[20];

};

Union:

union Data {

int i;

float f;

};

9. Dynamic Memory Allocation

Allocating memory at runtime using:

• malloc()

• calloc()

• realloc()

• free()

Example:

int *ptr = (int*) malloc(5 * sizeof(int));

10. File Handling

Used to store and retrieve data from files.

Basic Functions:

FILE *fp = fopen("file.txt", "r");

fscanf(fp, "%d", &num);

fclose(fp);

11. Preprocessor Directives


Examples:

• #include<stdio.h> – Include header

• #define PI 3.14 – Macro definition

• Conditional compilation:

#ifdef DEBUG

printf("Debug mode");

#endif

12. Command Line Arguments

Used to pass input to the main() function from the command line.

int main(int argc, char *argv[]) {

printf("First arg: %s", argv[1]);

13. Storage Classes

Controls scope, visibility, and lifetime.

Storage Class Description

auto Default for local vars

static Retains value

extern Access global var

register Fast access register

14. Common C Mistakes (Placement Focused)

• Missing break in switch

• Confusing = and ==

• Array out of bounds

• Using uninitialized pointers

• Not freeing dynamic memory

Want this as a PDF with examples and interview questions for each topic?
Here are complete Python notes covering all important topics for placement preparation, technical
interviews, and coding rounds.

Python Notes for Placements (Topic-Wise)

1. Python Basics

• High-level, interpreted, dynamically typed language

• Indentation-based syntax

Key Elements:

# Hello World

print("Hello, World!")

• Keywords: if, else, for, def, class, etc.

• Identifiers: Variable/function/class names

2. Data Types

Type Example

int x=5

float y = 3.14

str name = "Alice"

bool True, False

NoneType None

Type Casting:

int("5") # 5

str(10) # "10"

float(3) # 3.0

3. Operators

• Arithmetic: + - * / % // **

• Comparison: == != > < >= <=

• Logical: and or not


• Bitwise: & | ^ << >>

• Membership: in, not in

4. Control Flow

# if-elif-else

if x > 0:

print("Positive")

elif x == 0:

print("Zero")

else:

print("Negative")

Loops:

# for loop

for i in range(5):

print(i)

# while loop

while x < 5:

x += 1

5. Functions

def greet(name):

return "Hello " + name

print(greet("Alice"))

• Default Args: def f(x=0):

• Variable Args: *args, **kwargs

• Lambda: square = lambda x: x*x

6. Data Structures

List
l = [1, 2, 3]

l.append(4)

l[1] = 10

Tuple

Immutable sequence.

t = (1, 2, 3)

Set

Unordered, unique items.

s = {1, 2, 3}

s.add(4)

Dictionary

Key-value pairs.

d = {'a': 1, 'b': 2}

d['c'] = 3

7. String Handling

s = "hello"

s.upper(), s.lower(), s[1:4], len(s)

"e" in s # True

Formatting:

name = "Alice"

print(f"Hello, {name}")

8. Modules and Packages

import math

print(math.sqrt(16))

from datetime import date

• Custom Module: Save .py file and import

9. File Handling
with open("file.txt", "r") as f:

content = f.read()

Modes: "r", "w", "a", "r+"

10. Exception Handling

try:

x=5/0

except ZeroDivisionError:

print("Cannot divide by zero")

finally:

print("Done")

11. OOP in Python

class Person:

def __init__(self, name):

self.name = name

def greet(self):

print("Hi", self.name)

• Inheritance, Polymorphism, Encapsulation, etc.

12. Important Built-in Functions

• len(), type(), range(), enumerate()

• map(), filter(), zip(), sorted()

13. Useful Libraries for Placements

Area Library

DSA collections, heapq

Math math, random

Data Handling pandas, numpy


Area Library

Plotting matplotlib

14. Practice Topics for Interviews

• String/Array problems

• Recursion & Backtracking

• HashMap, Stack, Queue, LinkedList

• Sorting & Searching

• Binary Tree and Graphs

• Dynamic Programming

Sample Problem (Python DSA)

# Reverse a string

def reverse_string(s):

return s[::-1]

print(reverse_string("hello"))

Would you like a PDF version with code examples and MCQs, or want detailed explanations for
specific Python topics next (like OOP or recursion)?

Sure! Here's a complete explanation of Object-Oriented Programming (OOP) in Python – an


important topic for placements, interviews, and real-world development.

What is OOP?

OOP (Object-Oriented Programming) is a programming paradigm based on the concept of “objects”,


which contain data (attributes) and behavior (methods).

Python supports both procedural and object-oriented programming.

Four Pillars of OOP

Pillar Meaning

1. Encapsulation Binding data and methods into a single unit


Pillar Meaning

2. Abstraction Hiding internal implementation and showing essentials

3. Inheritance Reusing code from existing classes

4. Polymorphism Performing one action in different ways

1. Classes and Objects

• Class: A blueprint for creating objects.

• Object: Instance of a class.

Example:

class Student:

def __init__(self, name, age): # Constructor

self.name = name # Attributes

self.age = age

def display(self): # Method

print(f"{self.name} is {self.age} years old")

# Creating object

s1 = Student("Alice", 20)

s1.display()

2. Encapsulation

• Wrapping data (variables) and methods into a class

• Access Specifiers:

o public: accessible anywhere (default)

o _protected: for internal use

o __private: name mangled, hidden from outside access

class BankAccount:

def __init__(self):

self.balance = 1000 # Public


self._type = "Savings" # Protected

self.__pin = 1234 # Private

def get_pin(self):

return self.__pin

obj = BankAccount()

print(obj.balance) #

print(obj._type) # (but not recommended)

# print(obj.__pin) Error

print(obj.get_pin()) # Access via method

3. Abstraction

• Hiding implementation details from users.

• Achieved via abstract base classes using abc module.

from abc import ABC, abstractmethod

class Shape(ABC):

@abstractmethod

def area(self):

pass

class Circle(Shape):

def __init__(self, r):

self.r = r

def area(self):

return 3.14 * self.r * self.r

c = Circle(5)

print(c.area())
4. Inheritance

• Child class inherits attributes/methods from parent class.

Example:

class Animal:

def speak(self):

print("Animal speaks")

class Dog(Animal): # Single Inheritance

def bark(self):

print("Dog barks")

d = Dog()

d.speak()

d.bark()

Types of Inheritance:

• Single: One parent → One child

• Multiple: Multiple parents

• Multilevel: Parent → Child → Sub-child

• Hierarchical: One parent → Multiple children

• Hybrid: Combination of above

5. Polymorphism

Types:

1. Method Overriding (runtime polymorphism)

2. Duck Typing

Example – Method Overriding:

class Bird:

def sound(self):

print("Chirp")
class Parrot(Bird):

def sound(self):

print("Squawk")

b = Parrot()

b.sound() # Squawk

Duck Typing:

class Cat:

def speak(self): print("Meow")

class Dog:

def speak(self): print("Woof")

def animal_sound(animal):

animal.speak()

animal_sound(Cat())

animal_sound(Dog())

6. Constructor & Destructor

• Constructor: __init__() – initializes object

• Destructor: __del__() – called when object is deleted

class A:

def __init__(self):

print("Constructor")

def __del__(self):

print("Destructor")

obj = A()

del obj
7. Operator Overloading

Python allows customizing the behavior of operators using magic methods (__add__, __eq__, etc.)

class Point:

def __init__(self, x):

self.x = x

def __add__(self, other):

return Point(self.x + other.x)

p1 = Point(3)

p2 = Point(4)

p3 = p1 + p2

print(p3.x) # 7

Summary Table of Important OOP Terms in Python:

Concept Keyword/Example

Class class ClassName:

Object obj = ClassName()

Constructor __init__()

Destructor __del__()

Inheritance class B(A):

Abstraction ABC, @abstractmethod

Polymorphism Overriding, Duck Typing

Encapsulation __private, _protected

Operator Overloading __add__, __eq__, etc.

Would you like:

• Code examples for each OOP type?

• A PDF of Python OOP Notes?

• Interview Questions on Python OOP?


Let me know how you'd like to continue.

Here's a complete guide to all important sorting algorithms for placements and coding interviews,
including concepts, time complexities, and Python code examples:

Sorting Algorithms for Placements

1. Bubble Sort

• Compares adjacent elements and swaps if in wrong order.

• Repeats until array is sorted.

Time Complexity:

• Worst: O(n²)

• Best: O(n) (already sorted)

Python Code:

def bubble_sort(arr):

n = len(arr)

for i in range(n):

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

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

arr[j], arr[j+1] = arr[j+1], arr[j]

2. Selection Sort

• Finds the minimum and places it at the beginning.

• Repeats for each index.

Time Complexity:

• Worst: O(n²)

Python Code:

def selection_sort(arr):

for i in range(len(arr)):

min_idx = i

for j in range(i+1, len(arr)):

if arr[j] < arr[min_idx]:


min_idx = j

arr[i], arr[min_idx] = arr[min_idx], arr[i]

3. Insertion Sort

• Builds the final sorted array one element at a time.

• Inserts current element in correct position.

Time Complexity:

• Worst: O(n²)

• Best: O(n) (if already sorted)

Python Code:

def insertion_sort(arr):

for i in range(1, len(arr)):

key = arr[i]

j=i-1

while j >= 0 and arr[j] > key:

arr[j+1] = arr[j]

j -= 1

arr[j+1] = key

4. Merge Sort ( Divide & Conquer)

• Divides array into halves, sorts each, then merges.

Time Complexity:

• All cases: O(n log n)

Python Code:

def merge_sort(arr):

if len(arr) > 1:

mid = len(arr)//2

L = arr[:mid]

R = arr[mid:]

merge_sort(L)
merge_sort(R)

i=j=k=0

while i < len(L) and j < len(R):

if L[i] < R[j]:

arr[k] = L[i]

i += 1

else:

arr[k] = R[j]

j += 1

k += 1

while i < len(L):

arr[k] = L[i]

i += 1

k += 1

while j < len(R):

arr[k] = R[j]

j += 1

k += 1

5. Quick Sort ( Divide & Conquer)

• Picks a pivot, partitions array into left (less than pivot) and right, then recursively sorts.

Time Complexity:

• Best: O(n log n)

• Worst: O(n²) (when array is already sorted)

Python Code:

def quick_sort(arr):

if len(arr) <= 1:

return arr

pivot = arr[-1]

left = [x for x in arr[:-1] if x <= pivot]


right = [x for x in arr[:-1] if x > pivot]

return quick_sort(left) + [pivot] + quick_sort(right)

6. Heap Sort

• Uses a binary heap to sort.

Time Complexity:

• All cases: O(n log n)

Python Code:

def heapify(arr, n, i):

largest = i

l, r = 2*i + 1, 2*i + 2

if l < n and arr[l] > arr[largest]: largest = l

if r < n and arr[r] > arr[largest]: largest = r

if largest != i:

arr[i], arr[largest] = arr[largest], arr[i]

heapify(arr, n, largest)

def heap_sort(arr):

n = len(arr)

for i in range(n//2 - 1, -1, -1):

heapify(arr, n, i)

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

arr[0], arr[i] = arr[i], arr[0]

heapify(arr, i, 0)

7. Counting Sort (Only for integers)

• Counts number of occurrences of each value.

Time Complexity:

• O(n + k) where k = max element


Python Code:

def counting_sort(arr):

max_val = max(arr)

count = [0] * (max_val + 1)

for num in arr:

count[num] += 1

idx = 0

for i, c in enumerate(count):

for _ in range(c):

arr[idx] = i

idx += 1

8. Radix Sort (Non-comparison sort for integers)

• Sorts digit by digit (starting from LSD to MSD)

Time Complexity:

• O(n * k) (k = number of digits)

Python Code:

def counting_sort_exp(arr, exp):

n = len(arr)

output = [0] * n

count = [0] * 10

for i in arr:

index = (i // exp) % 10

count[index] += 1

for i in range(1, 10):

count[i] += count[i - 1]

for i in reversed(arr):

index = (i // exp) % 10

output[count[index] - 1] = i

count[index] -= 1
for i in range(n):

arr[i] = output[i]

def radix_sort(arr):

max1 = max(arr)

exp = 1

while max1 // exp > 0:

counting_sort_exp(arr, exp)

exp *= 10

Comparison Table

Algorithm Time (Best) Time (Worst) Space Stable

Bubble Sort O(n) O(n²) O(1) Yes

Selection Sort O(n²) O(n²) O(1) No

Insertion Sort O(n) O(n²) O(1) Yes

Merge Sort O(n log n) O(n log n) O(n) Yes

Quick Sort O(n log n) O(n²) O(log n) No

Heap Sort O(n log n) O(n log n) O(1) No

Counting Sort O(n + k) O(n + k) O(k) Yes

Radix Sort O(nk) O(nk) O(n+k) Yes

Would you like:

• A PDF version of all sorting algorithms with code?

• Sorting visualization or animations?

• DSA problem sets related to sorting?

Let me know how you want to continue.

Great question!

The sort() method and the sorted() function in Python both use the same algorithm under the
hood, called:
Timsort

What is Timsort?

Timsort is a hybrid sorting algorithm derived from:

• Merge Sort (for worst-case efficiency)

• Insertion Sort (for small chunks)

It is designed to be:

• Stable (preserves the order of equal elements)

• Efficient on real-world data (partially sorted)

Key Facts about Timsort:

Feature Detail

Time Complexity (Best) O(n) (if already sorted)

Time Complexity (Average/Worst) O(n log n)

Space Complexity O(n) (extra space needed)

Stable Yes

Used in list.sort(), sorted(), Java's Arrays.sort() for objects

How It Works (Simplified):

1. Divides the list into runs (small chunks).

2. Sorts each run using insertion sort.

3. Merges runs using merge sort rules.

Example:

nums = [3, 1, 4, 1, 5]

nums.sort() # Uses Timsort internally

print(nums) # [1, 1, 3, 4, 5]

Timsort is great when:

• The data is partially sorted.

• You want fast performance and stable sorting.


Would you like a visual explanation of how Timsort works step-by-step, or want to compare it with
Quick Sort or Merge Sort?

Here is a complete list of all important searching algorithms, commonly asked in placement
interviews and used in competitive programming or real-world applications.

Searching Algorithms

1. Linear Search

• How it works: Check each element one by one.

• Best case: Element found at the start → O(1)

• Worst case: Element at the end or not found → O(n)

def linear_search(arr, target):

for i in range(len(arr)):

if arr[i] == target:

return i

return -1

2. Binary Search (Only for sorted arrays)

• Divide and conquer technique.

• Time complexity:

o Best: O(1)

o Average/Worst: O(log n)

def binary_search(arr, target):

low, high = 0, len(arr)-1

while low <= high:

mid = (low + high)//2

if arr[mid] == target:

return mid

elif arr[mid] < target:

low = mid + 1
else:

high = mid - 1

return -1

3. Jump Search (For sorted arrays)

• Jump ahead in blocks and then do linear search.

• Block size ≈ √n

• Time complexity: O(√n)

import math

def jump_search(arr, target):

n = len(arr)

step = int(math.sqrt(n))

prev = 0

while arr[min(step, n)-1] < target:

prev = step

step += int(math.sqrt(n))

if prev >= n:

return -1

for i in range(prev, min(step, n)):

if arr[i] == target:

return i

return -1

4. Interpolation Search (Better than binary if values are uniformly distributed)

• Formula-based search based on the value.

• Time complexity:

o Best: O(log log n)

o Worst: O(n)

def interpolation_search(arr, target):


low = 0

high = len(arr) - 1

while low <= high and arr[low] <= target <= arr[high]:

pos = low + ((target - arr[low]) * (high - low) //

(arr[high] - arr[low]))

if arr[pos] == target:

return pos

elif arr[pos] < target:

low = pos + 1

else:

high = pos - 1

return -1

5. Exponential Search

• Use binary search after finding a range where the element lies.

• Best for unbounded sorted arrays

• Time complexity: O(log n)

def binary_search(arr, target, start, end):

while start <= end:

mid = (start + end) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

start = mid + 1

else:

end = mid - 1

return -1

def exponential_search(arr, target):


if arr[0] == target:

return 0

i=1

while i < len(arr) and arr[i] <= target:

i *= 2

return binary_search(arr, target, i//2, min(i, len(arr)-1))

6. Fibonacci Search

• Uses Fibonacci numbers to divide the array.

• Similar to binary search.

• Time complexity: O(log n)

7. Ternary Search (Mostly used for optimization in mathematical problems)

• Divide array into 3 parts.

• Time complexity: O(log₃ n)

8. Hashing Search (Using hash maps)

• Used when we want O(1) average-case search.

• Good for unordered data.

def hash_search(arr, target):

hash_set = set(arr)

return target in hash_set

Comparison Table

Algorithm Best Case Worst Case Data Must Be Sorted?

Linear Search O(1) O(n) No

Binary Search O(1) O(log n) Yes

Jump Search O(√n) O(√n) Yes

Interpolation Search O(log log n) O(n) Yes (Uniform)


Algorithm Best Case Worst Case Data Must Be Sorted?

Exponential Search O(log n) O(log n) Yes

Hashing O(1) O(n) No

Would you like a PDF version, MCQs, or a cheat sheet of all searching algorithms for revision?

Here’s a complete breakdown of the major Data Structures topics — especially important for
placements — explained in detail:

1. Arrays

• Definition: Collection of elements stored at contiguous memory locations.

• Operations: Traversal, Insertion, Deletion, Searching.

• Time Complexities:

o Access: O(1)

o Search: O(n)

o Insert/Delete: O(n)

• Python Example:

• arr = [1, 2, 3]

• arr.append(4) # Insertion

• arr.pop(2) # Deletion

2. Linked List

• Types:

o Singly Linked List

o Doubly Linked List

o Circular Linked List

• Operations: Insert at beginning/end, delete node, search, reverse list.

• Advantages: Dynamic size, efficient insert/delete.

• Drawbacks: No direct access to elements.

• Python (Node Example):

• class Node:

• def __init__(self, data):


• self.data = data

• self.next = None

3. Stack

• Definition: Follows LIFO (Last In First Out).

• Operations: push(), pop(), peek(), isEmpty().

• Use Cases: Undo, Recursion, Expression Evaluation.

• Python Example:

• stack = []

• stack.append(1)

• stack.pop()

4. Queue

• Definition: Follows FIFO (First In First Out).

• Types:

o Simple Queue

o Circular Queue

o Deque (Double Ended)

o Priority Queue

• Python (Queue Example):

• from collections import deque

• queue = deque()

• queue.append(1)

• queue.popleft()

5. Trees

• Binary Tree: Each node has ≤ 2 children.

• Binary Search Tree (BST): Left < Root < Right

• AVL Tree: Balanced BST

• Heap:

o Min-Heap: Parent < Child


o Max-Heap: Parent > Child

• Operations: Traversal (Inorder, Preorder, Postorder, Level-order), Insert, Delete.

• Use Cases: Hierarchical data, fast search.

6. Graphs

• Components: Vertices (nodes), Edges (connections).

• Types:

o Directed / Undirected

o Weighted / Unweighted

• Representations:

o Adjacency Matrix

o Adjacency List

• Traversals:

o DFS (Depth First Search)

o BFS (Breadth First Search)

• Use Cases: Networks, Maps, Social Graphs.

7. Hashing

• Concept: Map keys to indices using a hash function.

• Use Cases: Fast lookup, Dictionary/Set in Python.

• Collision Handling: Chaining, Open Addressing.

8. Recursion

• Definition: Function calling itself.

• Use Cases: Tree traversals, Divide & Conquer, Factorial, Fibonacci.

9. Searching Algorithms

• Linear Search – O(n)

• Binary Search – O(log n) (Sorted array only)

• Ternary Search, Jump Search, Exponential Search – advanced techniques.


10. Sorting Algorithms

• Bubble Sort, Insertion Sort, Selection Sort – O(n²)

• Merge Sort, Quick Sort, Heap Sort – O(n log n)

• Timsort – Used in Python’s sorted()

11. Backtracking

• Concept: Try all possibilities and backtrack if a choice leads to failure.

• Use Cases: N-Queens, Sudoku Solver, Rat in Maze.

12. Dynamic Programming (DP)

• Definition: Solving subproblems once and storing their solutions.

• Top-down (Memoization) or Bottom-up (Tabulation).

• Problems: Knapsack, LIS, LCS, Fibonacci.

13. Greedy Algorithms

• Idea: Pick the best option at every step.

• Problems: Activity Selection, Huffman Coding, Kruskal’s Algorithm.

Would you like:

1. Python code examples for each data structure?

2. A PDF or table with complexity of each operation?

3. Topic-wise questions for practice?

Let me know how you'd like to study this further.

You might also like