Programming Basics: Loops, Data Types,
Arrays & String Functions
1. Introduction
In programming, understanding loops, data types, arrays, and string functions is
fundamental. These concepts help manage data efficiently, control the flow of a program,
and perform various operations on data structures.
2. Loops
Loops are control flow statements that allow a block of code to be executed repeatedly
based on a condition. They reduce the redundancy of writing the same code multiple times.
2.1 Basics, Working Principle, and Uses
The basic principle of loops is to continue execution of a code block until a specified
condition is false. They generally consist of three components:
1. Initialization: Setting a starting value.
2. Condition: The loop will continue running as long as this is true.
3. Update: Changing the loop variable to eventually break the loop.
Uses of loops include:
- Repeating tasks efficiently.
- Traversing arrays or data structures.
- Automating repetitive processes.
2.2 Types of Loops
There are mainly three types of loops:
2.2.1 While Loop
The while loop checks the condition before executing the block of code. If the condition is
true, the loop body runs; otherwise, it exits.
Syntax:
i = 0;
while (i < 5) {
printf("%d", i);
i++;
}
Example Output: 0 1 2 3 4
2.2.2 For Loop
The for loop combines initialization, condition, and update in a single line, making it
compact and commonly used.
Syntax:
for (i = 0; i < 5; i++) {
printf("%d", i);
}
Example Output: 0 1 2 3 4
2.2.3 Do-While Loop
The do-while loop executes the block of code first and then checks the condition. It
guarantees at least one execution.
Syntax:
int n = 3;
do {
printf("%d", n);
n--;
} while (n >= 0);
Example Output: 3 2 1 0
3. Indentation
Proper indentation is essential for code readability. It visually separates different blocks of
code, making it easier to understand the program flow.
4. Data Types
Data Type Description Memory
int Integer values 4 Bytes
double Large integer/decimal 8 Bytes
values
float Decimal numbers 4 Bytes
char Single character 1 Byte
string Sequence of characters Variable
5. Arrays
An array is a collection of elements, all of the same data type, stored in contiguous memory
locations. Each element can be accessed using its index.
Example:
char arr[5] = {'A', 'P', 'P', 'L', 'E'};
6. String Functions
Some commonly used string functions are:
Function Description
lower() Converts string to lowercase
upper() Converts string to uppercase
title() Capitalizes first letter of each word
capitalize() Capitalizes first letter of the string
swapcase() Swaps lowercase to uppercase and vice
versa
Example:
s = "mango"
print(s.title()) # Output: Mango