Data Structures and Algorithm
Data Structures and Algorithm
● Integer:
An integer is a whole number without any fractional or decimal part. It can be
positive, negative, or zero. Integers are commonly used for counting,
indexing, and basic arithmetic operations.
Example: -10, 0, 45
● Float:
A float, or floating-point number, is a number that has a fractional or decimal
component. Floats are used to represent real numbers with precision and are
commonly employed in calculations that require fractions or large ranges of
values.
● Character:
A character represents a single alphanumeric symbol or punctuation mark. It
is usually enclosed in single quotes (') in many programming languages.
Characters are used to represent text or symbols.
● Boolean:
A Boolean data type represents one of two values: true or false. It is used to
represent logical states and is commonly employed in decision-making,
comparisons, and control flow.
2. Float (float)
float pi = 3.14159;
float temperature = -20.5;
3. Character (char)
● Size: Typically, 1 byte (8 bits), which can represent 256 different characters
(ASCII set).
● Examples:
1. Fixed Size: The size of an array must be defined at the time of its
declaration and cannot be changed during runtime.
2. Homogeneous Data: All elements in an array must be of the same type
(e.g., all integers, floats, or characters).
3. Indexed Access: Elements in an array are accessed using zero-based
indexing (i.e., the first element is at index 0, the second at index 1, and so
on).
4. Efficient Memory Layout: Arrays use contiguous memory locations, which
allows for fast element access using indices.
Syntax
dataType arrayName[arraySize];
● dataType: The type of elements the array will store (e.g., int, float, char).
● arrayName: The name of the array.
● arraySize: The number of elements the array can hold (a positive integer).
Examples
Declaration and Initialization
int numbers[5]; // Declaration of an integer array of size 5
numbers[0] = 10; // Assigning a value to the first element
numbers[1] = 20; // Assigning a value to the second element
int main() {
int scores[3] = {95, 87, 92};
cout << "First score: " << scores[0] << endl; // Access first element
cout << "Second score: " << scores[1] << endl; // Access second element
return 0;
}
Iterating Over an Array
#include <iostream>
using namespace std;
int main() {
int scores[5] = {10, 20, 30, 40, 50};
return 0;
}
Characteristics
● Arrays can store any data type: int, float, char, or even custom types.
● If not explicitly initialized, an array's elements may contain garbage values.
● Multidimensional arrays (e.g., 2D arrays) can also be declared for more
complex data structures.
Advantages
Limitations