Sunday, 29 June 2025

Create an array of size 10, input values and print the array, and search an element in the array

Create an array of size 10, input values and print the array, and search an element in the array

array_operations.c
#include <stdio.h>

int main() {
    int arr[10];         // Step 1: Declare an array of size 10
    int i, search, found = 0;

    // Step 2: Input 10 elements from the user
    printf("Enter 10 integers:\n");
    for(i = 0; i < 10; i++) {
        printf("Element %d: ", i + 1);
        scanf("%d", &arr[i]);
    }

    // Step 3: Print the array
    printf("\nThe array is:\n");
    for(i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }

    // Step 4: Search for an element
    printf("\n\nEnter the number to search: ");
    scanf("%d", &search);

    for(i = 0; i < 10; i++) {
        if(arr[i] == search) {
            printf("%d found at position %d (index %d)\n", search, i + 1, i);
            found = 1;
            break;
        }
    }

    if(!found) {
        printf("%d not found in the array.\n", search);
    }

    return 0;
}

๐Ÿง  Step-by-Step Explanation

๐Ÿ”น Step 1: Declare an array

int arr[10];
  • This line creates an integer array of size 10
  • It can store 10 elements of type int
  • Array indices range from 0 to 9

๐Ÿ”น Step 2: Take input from the user

for(i = 0; i < 10; i++) {
    scanf("%d", &arr[i]);
}
  • This loop runs from 0 to 9 (10 iterations)
  • We use scanf() to take user input
  • Each input is stored in consecutive array indices
  • &arr[i] gets the memory address of each element

๐Ÿ”น Step 3: Display the array

for(i = 0; i < 10; i++) {
    printf("%d ", arr[i]);
}
  • Prints each element of the array
  • Elements are separated by spaces
  • Output appears on a single line

๐Ÿ”น Step 4: Search for an element

scanf("%d", &search);
for(i = 0; i < 10; i++) {
    if(arr[i] == search) {
        // Print the found message
        break;
    }
}
  • First reads the number to search for
  • Linear search through the array elements
  • Compares each element with search value
  • If found, prints position and breaks the loop
  • If not found, displays appropriate message

๐Ÿ–จ️ Sample Output:

Enter 10 integers:
Element 1: 12
Element 2: 34
Element 3: 56
Element 4: 78
Element 5: 90
Element 6: 11
Element 7: 23
Element 8: 45
Element 9: 66
Element 10: 67

The array is:
12 34 56 78 90 11 23 45 66 67

Enter the number to search: 90
90 found at position 5 (index 4)

๐Ÿ’ก Key Concepts:

  • Array Declaration: Specifies size and type at compile time
  • Zero-based Indexing: First element is at index 0
  • Linear Search: Simple search algorithm checking each element sequentially
  • Loop Control: for loops provide precise iteration control
  • I/O Operations: printf and scanf for console input/output

Python Dictionaries

Python Dictionaries

๐Ÿ“˜ What is a Dictionary?

A dictionary in Python is a collection of key-value pairs. It's like a real-life dictionary where you look up a word (the key) to find its meaning (the value).

  • ๐Ÿ”‘ Keys → The unique identifiers
  • ๐Ÿ“ฆ Values → The data associated with those keys

๐Ÿ” Syntax:

my_dict = {
    "name": "Ansh",
    "age": 7,
    "grade": "1st"
}

Here:

  • "name", "age", and "grade" are the keys
  • "Ansh", 7, and "1st" are the values

๐Ÿงฉ Why Use a Dictionary?

  • To store related information (like name, marks, etc.) together
  • To quickly look up data using keys
  • It's organized and flexible

✍️ Creating a Dictionary

Example:

student = {
    "name": "Aarav",
    "age": 14,
    "class": "8th",
    "marks": 87
}

This creates a student dictionary with four key-value pairs.

๐ŸŽฏ Accessing Values

Use the key inside square brackets or the .get() method.

print(student["name"])   # Output: Aarav
print(student.get("marks"))  # Output: 87

➕ Adding New Items

student["school"] = "Tapasvi School"
print(student)

๐Ÿ” Updating a Value

student["marks"] = 92

❌ Removing Items

del student["class"]  # Removes the "class" key-value pair

Or:

student.pop("age")

๐Ÿ“š Useful Dictionary Methods

Method Description
dict.keys() Returns a list of all keys
dict.values() Returns a list of all values
dict.items() Returns key-value pairs as tuples
dict.update() Adds or updates items from another dict
dict.clear() Empties the dictionary

Example:

print(student.keys())    # dict_keys(['name', 'marks', 'school'])
print(student.values())  # dict_values(['Aarav', 92, 'Tapasvi School'])

๐Ÿ”„ Looping Through a Dictionary

Loop through keys:

for key in student:
    print(key)

Loop through keys and values:

for key, value in student.items():
    print(key, ":", value)

๐Ÿง  Nested Dictionaries

A dictionary can contain another dictionary. This is useful when storing complex data.

Example:

class_data = {
    "student1": {"name": "Riya", "marks": 90},
    "student2": {"name": "Aman", "marks": 85}
}

To access Riya's marks:

print(class_data["student1"]["marks"])  # Output: 90

✅ When to Use a Dictionary

Use a dictionary when:

  • You want to store pairs (like ID–name, product–price, etc.)
  • You need quick access to a value using a key
  • Order doesn't matter (though in Python 3.7+, order is preserved)

๐Ÿ”š Summary

  • A dictionary holds key-value pairs.
  • Keys must be unique and immutable (strings, numbers, etc.)
  • Values can be anything (numbers, strings, lists, even other dictionaries)
  • Great for organized and structured data

Friday, 27 June 2025

Lists in Python

Lists in Python

✅ What is a List?

A list is a collection of items in Python. You can think of it like a basket that holds multiple values—like numbers, words, or both.

A list:

  • Is ordered (items have a specific position)
  • Is changeable (you can add, remove, or update items)
  • Allows duplicate values

๐ŸŸข How to Create a List

Use square brackets [ ] to create a list:

students = ["ansh", "aarav", "mishti"]
numbers = [1, 2, 3, 4]
mixed = [1, "hello", 3.5, True]

You can also create an empty list:

empty_list = []

๐Ÿ”ข Accessing Items in a List

You can use indexing to access items in a list. Python indexes start from 0.

students = ["ansh", "aarav", "mishti"]
print(students[0])  # ansh
print(students[1])  # aarav

You can also use negative indexing:

print(students[-1])  # mishti (last item)

✏️ Changing List Items

Lists are mutable, meaning you can change values.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)  # ['apple', 'mango', 'cherry']

➕ Adding Items to a List

append() – adds at the end:

fruits.append("orange")

insert() – adds at a specific position:

fruits.insert(1, "grape")  # inserts at index 1

❌ Removing Items from a List

remove() – removes by value:

fruits.remove("banana")

pop() – removes by index (default is last item):

fruits.pop()     # removes last
fruits.pop(0)    # removes first

clear() – removes all items:

fruits.clear()

๐Ÿ” Looping Through a List

You can use a for loop:

for fruit in fruits:
    print(fruit)

๐Ÿ“ Getting Length of a List

Use the len() function:

fruits = ["apple", "banana", "cherry"]
print(len(fruits))  # 3

๐Ÿ”„ Joining Two Lists

Use the + operator to combine two lists:

list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2  # [1, 2, 3, 4]

๐Ÿ” Checking for an Item

Use the in keyword:

if "apple" in fruits:
    print("Yes, apple is in the list")

๐Ÿงฉ List with Different Data Types

A list can have different types of data:

my_list = [10, "hello", True, 3.5]

๐Ÿงฑ Nested Lists

A list can contain another list (called a nested list):

nested = [1, 2, [3, 4]]
print(nested[2])      # [3, 4]
print(nested[2][1])   # 4

๐Ÿงช List Methods (Commonly Used)

Method Description
append() Adds item at the end
insert() Adds item at specific index
remove() Removes item by value
pop() Removes item by index
clear() Removes all items
sort() Sorts the list (ascending by default)
reverse() Reverses the list
index() Returns index of first match
count() Returns number of times item appears

๐Ÿ”ƒ Sorting a List

numbers = [3, 1, 4, 2]
numbers.sort()        # [1, 2, 3, 4]
numbers.sort(reverse=True)  # [4, 3, 2, 1]

๐Ÿ” Copying a List

list1 = [1, 2, 3]
list2 = list1.copy()

๐Ÿงฐ Converting List to Other Types

List to Tuple:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)

✅ Summary

  • Lists are used to store multiple items in a single variable
  • Lists are ordered and changeable
  • You can add, remove, and update items
  • Lists support looping, sorting, nesting, and more
  • Lists are one of the most commonly used data structures in Python

Tuples in Python

Tuples in Python

✅ What is a Tuple?

A tuple is a collection in Python that lets you store multiple items in a single variable.

It is:

  • Ordered – items stay in the same order
  • Immutable – you cannot change the items once added
  • Allows duplicates – repeated values are okay

๐ŸŸจ How to Create a Tuple

Use round brackets () to create a tuple.

my_tuple = ("apple", "banana", "cherry")
print(my_tuple)

๐Ÿ“Œ You can also create a tuple without parentheses (Python understands it):

my_tuple = "apple", "banana", "cherry"

๐Ÿงช Tuple Examples

fruits = ("apple", "banana", "cherry")
numbers = (1, 2, 3, 4)
mixed = (1, "hello", 3.5)

✅ Tuples can contain:

  • Strings
  • Integers
  • Floats
  • Booleans
  • Other tuples!

๐Ÿ”ข Accessing Tuple Items

Use index numbers to access values (starting from 0):

colors = ("red", "blue", "green")
print(colors[0])  # red
print(colors[1])  # blue

You can also use negative indexing:

print(colors[-1])  # green (last item)

๐Ÿšซ Tuples are Immutable

Once a tuple is created, you can't change, add, or remove items:

numbers = (1, 2, 3)
# numbers[0] = 10  ❌ This will give an error

๐Ÿ“ Tuple Length

Use the len() function:

my_tuple = ("a", "b", "c")
print(len(my_tuple))  # 3

๐Ÿ” Looping Through a Tuple

Use a for loop to go through items:

colors = ("red", "blue", "green")
for color in colors:
    print(color)

๐Ÿ”„ Tuple Operations

✅ Concatenation:

t1 = (1, 2)
t2 = (3, 4)
result = t1 + t2  # (1, 2, 3, 4)

✅ Repetition:

t = ("hi",)
print(t * 3)  # ('hi', 'hi', 'hi')

๐Ÿ” Checking for an Item

fruits = ("apple", "banana", "cherry")
if "apple" in fruits:
    print("Yes, apple is there!")

๐Ÿงฉ Tuple with One Item?

You must add a comma if the tuple has only one item:

t = ("hello",)  # This is a tuple
x = ("hello")   # This is just a string

๐Ÿงฑ Nesting Tuples

Tuples can contain other tuples:

nested = (1, 2, (3, 4))

๐Ÿ“ฆ Tuple Packing and Unpacking

Packing:

info = ("Ansh", 7, "India")

Unpacking:

name, age, country = info
print(name)     # Ansh
print(age)      # 7
print(country)  # India

๐Ÿ”„ Converting Lists to Tuples

Use the tuple() function:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)  # (1, 2, 3)

๐Ÿ“Œ Tuple Methods

Method Description
count() Counts how many times an item appears
index() Returns the index of the first occurrence of an item

Example:

t = (1, 2, 3, 2, 4)
print(t.count(2))   # 2
print(t.index(3))   # 2

✅ When to Use Tuples?

Use tuples when:

  • You want data to be unchanged (read-only)
  • You are storing a fixed set of items
  • You want faster access than a list

๐ŸŽ“ Summary

  • Tuples use () to store multiple items
  • They are ordered and immutable
  • You can access items with indexing
  • Tuples are faster and safer than lists for fixed data
  • You can loop, count, and unpack tuples

Thursday, 26 June 2025

Python Built-in Datatypes

๐ŸŒŸ Introduction to Built-in Datatypes

Ever wondered how computers understand different types of data like numbers, names, or even true/false questions? That's where datatypes come into play! They're like labels that tell the computer what kind of value you're working with.

๐Ÿ” What Are Datatypes?

In programming, a datatype tells the interpreter what kind of value a variable holds. It could be a number, a piece of text, a list of things, or even something more complex.

๐Ÿ“Œ Why Datatypes Matter in Programming

Imagine trying to add two names together or divide a word by a number—it wouldn't make any sense! That's why programming languages use datatypes to prevent errors and organize your code.

⚖️ Static vs Dynamic Typing

  • Static Typing: You must declare the datatype before using it (like in Java or C++)
  • Dynamic Typing: The interpreter figures it out for you (like in Python)

Python uses dynamic typing, so it automatically understands what kind of data you're using.

๐Ÿงฑ Built-in vs User-defined Datatypes

  • Built-in Datatypes: Already available in the language (no need to define them)
  • User-defined Datatypes: Created by programmers using classes and objects

In this article, we're focusing on the built-in ones.

๐Ÿ”ข Numeric Datatypes

These are used when you want to store numbers.

1. Integer (int)

Used to store whole numbers, like 10, -3, or 0.

age = 25

2. Float (float)

Used to store decimal numbers, like 3.14, -0.5, or 99.99.

pi = 3.14159

3. Complex (complex)

Used in advanced mathematics, includes a real and an imaginary part.

z = 2 + 3j

๐Ÿ“š Sequence Datatypes

A sequence is an ordered collection of items.

1. String (str)

Used to store text, written in quotes.

name = "Alice"

You can use:

  • len(name) → Number of characters
  • name.upper() → Convert to uppercase

2. List (list)

Used to store multiple items in one variable. Lists are mutable (you can change them).

fruits = ["apple", "banana", "mango"]
fruits.append("orange")

3. Tuple (tuple)

Similar to lists but immutable (cannot be changed).

coordinates = (10, 20)

๐Ÿ”˜ Set Datatypes

Sets store unique items and do not maintain order.

1. Set (set)

numbers = {1, 2, 3, 3}
# Output: {1, 2, 3}

Useful for removing duplicates.

2. Frozen Set (frozenset)

An immutable version of a set.

fs = frozenset([1, 2, 3])

๐Ÿ—บ️ Mapping Datatype

Dictionary (dict)

Stores data in key-value pairs.

student = {
  "name": "John",
  "age": 16,
  "grade": "A"
}

Access using keys:

print(student["name"])  # Output: John

✅ Boolean Datatype

Boolean (bool)

Has only two values: True or False.

is_logged_in = True

Commonly used in conditions and loops.

๐Ÿšซ None Type

What is None?

None represents the absence of a value. It's like a blank placeholder.

result = None

You might use it when a variable is declared but not yet given a value.

๐Ÿ”„ Type Conversion and Type Casting

Sometimes you need to change one datatype into another.

Implicit Conversion

Python does it for you.

x = 5     # int
y = 2.5   # float
z = x + y  # float (Python converts int to float automatically)

Explicit Conversion

You do it manually.

x = 10
y = str(x)  # Convert int to string

๐Ÿ› ️ Built-in Functions for Datatypes

These make life easier:

  • type() → Returns the datatype
  • id() → Returns the memory address
  • isinstance() → Checks the type

Example:

num = 100
print(type(num))  # Output: <class 'int'>

๐Ÿ” Memory and Mutability

Mutable vs Immutable Types

  • Mutable: Can be changed (list, set, dict)
  • Immutable: Cannot be changed (int, float, str, tuple, frozenset)

Why does it matter? Because changing a mutable object affects its original reference.

๐Ÿ’ผ Real-Life Examples and Use-Cases

Using Lists to Store Marks

marks = [88, 76, 92, 85]

You can calculate average, highest marks, etc.

Using Dictionary for Employee Info

employee = {
  "name": "Ravi",
  "id": 103,
  "department": "HR"
}

You can easily update, search, and manage data using keys.

๐Ÿ Conclusion

Built-in datatypes are the building blocks of every Python program. Whether you're dealing with numbers, names, lists of groceries, or a record of students, Python has a datatype ready for it. Understanding these core types will help you write efficient and error-free code. So, the next time you're coding, remember—you're not just typing lines; you're instructing the computer using these datatypes!

❓ FAQs

  • What is the difference between list and tuple?
    A list is mutable (you can change it), while a tuple is immutable (you can't change it once created).
  • Can a set have duplicate values?
    No, sets automatically remove duplicates.
  • What is the default datatype of a number like 5?
    It's an integer (int).
  • Why is None used in Python?
    To represent a variable with no value or to initialize a variable for future use.
  • Are Python datatypes case-sensitive?
    Yes, Python is case-sensitive. True is a valid Boolean, but true is not.

Wednesday, 25 June 2025

Variables and Assignments in Python

Variables and Assignments in Python

๐Ÿ’ก What is a Variable?

A variable is like a container or a box in the computer's memory that stores a value.

Think of it like naming a jar to store something inside. The jar (variable) holds the value, and you can use that name anytime to get or change what's inside.

Example:

x = 10

Here:

  • x is the variable name
  • 10 is the value
  • = is the assignment operator

You can now use x in your program, and Python knows it means 10.

✅ Why Use Variables?

Variables:

  • Help you store data
  • Make your code easy to read and update
  • Let you perform calculations
  • Are used in almost every program!

๐Ÿ“ฅ Assignment in Python

In Python, we use the equal sign = to assign a value to a variable.

name = "Ansh"
age = 7
score = 92.5
  • name stores a word (string)
  • age stores a number (integer)
  • score stores a decimal (float)

✅ Summary

  • A variable stores a value using a name
  • The = sign is used to assign values
  • You can change or update variables any time
  • Variable names must follow certain rules
  • Python supports different data types like int, float, str, and bool
  • Use type() to check what kind of value a variable holds

Expressions and Numerical Types in Python

Expressions and Numerical Types in Python

๐Ÿ“Œ What is an Expression?

An expression is a combination of values, variables, and operators that Python can calculate (or evaluate) and give a result.

Example:

5 + 3
  • ๐Ÿ‘‰ This is an expression. It combines two numbers and a plus sign.
  • ๐Ÿ‘‰ The result of this expression is 8.
x = 10
y = x + 5
  • ๐Ÿ‘‰ Here, x + 5 is an expression.
  • ๐Ÿ‘‰ Python will calculate it and store 15 in y.

๐Ÿงฎ What are Numerical Types?

In Python, numbers come in different types based on how they are used.

There are mainly three types of numbers in Python:

1. int – Integer

These are whole numbers. They don't have any decimal point.

a = 5       # integer
b = -100    # negative integer

2. float – Floating Point Number

These are numbers with decimal points.

x = 3.14     # float
y = -0.5     # negative float

3. complex – Complex Numbers

These numbers have a real and an imaginary part.
Used mostly in higher math and science.

z = 2 + 3j   # complex number

You can check the type using type():

print(type(10))       # <class 'int'>
print(type(3.5))      # <class 'float'>
print(type(2 + 3j))   # <class 'complex'>

➕ Arithmetic Operators in Python

Python can do basic math using operators. These are:

Operator Meaning Example Result
+ Addition 5 + 3 8
- Subtraction 7 - 2 5
* Multiplication 4 * 3 12
/ Division 10 / 2 5.0
// Floor Division 10 // 3 3
% Modulus (remainder) 10 % 3 1
** Power 2 ** 3 8

✅ Summary

  • An expression is a combination of numbers, variables, and operators.
  • int, float, and complex are the 3 main number types in Python.
  • Python supports all basic math operations like +, -, *, /, %, etc.
  • Python follows the BODMAS rule for solving expressions.
  • You can use functions like abs(), round(), pow() with numbers.

Tuesday, 24 June 2025

Objects in Python

Objects in Python

What is an Object?

In real life, everything around us is an object — like a phone, a car, a ball, or a book.

Each object has:

  • Properties (like color, size, weight)
  • Actions (like ringing, driving, bouncing, or opening)

In Python, it's the same!
An object is something that stores data (like properties) and can do things (like actions).

Python is Object-Oriented

Python is called an Object-Oriented Programming (OOP) language.
This means Python works with objects in a smart way — we can create, use, and manage them easily.

Example of an Object

Let's take a simple example:

x = 5

Here, x is a variable, and it stores the value 5.

But actually, Python treats 5 as an object of type int (which stands for integer).

So:

  • 5 is an object
  • It has properties and actions

You can try:

print(type(x))

This will show:

<class 'int'>

This means x is an object of the class int.

Real-Life Analogy

Let's imagine a dog:

  • Its properties: name = "Bruno", color = "brown", age = 3
  • Its actions: bark

Key Takeaways

  • Everything in Python is an object
  • Objects have properties (data) and actions (methods)
  • Python is fundamentally object-oriented
  • Even simple variables reference objects with types

Introduction to Python

๐ŸŒŸ Introduction to Python

What is Python?

Python is a popular programming language. A programming language is like a set of instructions we give to the computer so it can do what we want — like solving math problems, showing messages, playing sounds, or making games.

Python is special because:

  • ✅ It is easy to read and write.
  • ✅ It looks simple — almost like English.
  • ✅ It is used by beginners as well as experts.
  • ✅ It can be used for many things — like making websites, apps, games, data analysis, artificial intelligence, and more.

Who made Python?

Python was created by Guido van Rossum in 1991. He named it Python after his favorite TV show called Monty Python's Flying Circus — not because of the snake!

Why do people like Python?

People like Python because:

  • ⭐ The rules (called syntax) are simple.
  • ⭐ It saves time because it needs fewer lines of code to do big tasks.
  • ⭐ It works on Windows, Mac, Linux — almost everywhere!
  • ⭐ It has a large community — so lots of help is available online.

Where is Python used?

Python is used in many fields:

  • ๐Ÿ’ป Web development — to build websites
  • ๐Ÿ“Š Data science — to study and understand data
  • ๐Ÿ•น️ Game development — to create games
  • ๐Ÿค– Artificial intelligence and machine learning — to make smart programs
  • ๐Ÿ“ฑ App development — to make apps for phones

How does Python look?

Here is a small example of Python code:

print("Hello, World!")

๐Ÿ‘‰ This code will make the computer show the message Hello, World!

Another example:

a = 5
b = 3
print(a + b)

๐Ÿ‘‰ This will show 8 on the screen because 5 + 3 = 8.

What do we need to write Python?

To start using Python, we need:

  • ✅ Python installed on your computer (from python.org)
  • ✅ A text editor (like Notepad or an app called IDLE that comes with Python)

Summary

๐Ÿ”น Python is a simple, powerful programming language.
๐Ÿ”น It is used for many purposes — from websites to robots.
๐Ÿ”น It is easy to learn, even if you are new to programming.

Total Pageviews

Search This Blog

Create an array of size 10, input values and print the array, and search an element in the array

Create an array of size 10, input values and print the array, and search an element in the array ...