Algorithm for Problem Solving
Overview
This document contains fundamental algorithms for problem solving in programming. Each algorithm is explained with clear steps and example code.
Swapping Two Values
Use another variable to store the value of variable1 then replace the value of variable1 with value of variable2, then replace the value of variable2 with value of the temporary variable.
- Create a temporary variable (temp)
- Store value of variable1 in temp
- Assign value of variable2 to variable1
- Assign value of temp to variable2
Finding Biggest Number Between Two Numbers
Use a variable 'big' to store the larger value. Compare the two numbers and assign the larger one to 'big'.
if (variable1 > variable2) {
big = variable1;
} else {
big = variable2;
}
Fahrenheit (°F) to Celsius (°C) Conversion
Use the formula: cel = 5/9 * (fahrenheit - 32)
float fahrenheit = 98.6;
float celsius = (5.0 / 9.0) * (fahrenheit - 32);
Sum of First n Natural Numbers
Initialize sum to 0 and use a loop to accumulate the sum of numbers from 1 to n.
int n = 10;
int sum = 0;
int i = 1;
while (i <= n) {
sum += i;
i++;
}
Factorial of n (Product of First n Natural Numbers)
Initialize product to 1 and use a loop to multiply numbers from 1 to n.
int n = 5;
int product = 1;
int i = 1;
while (i <= n) {
product *= i;
i++;
}
Reverse Digits of a Number
Use modulo operation to get last digit and build the reversed number.
int n = 123;
int reversed = 0;
while (n > 0) {
int lastDigit = n % 10;
reversed = reversed * 10 + lastDigit;
n = n / 10;
}
Swapping Numbers Without Temporary Variable
a = a + b;
b = a - b;
a = a - b;
Advanced Algorithms
Finding Element in an Array
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
int searchElement = 6;
for(int i = 0; i <= 9; i++) {
if(arr[i] == searchElement) {
printf("Found %d at index %d\n", searchElement, i);
}
}
Note: Array indexing starts at 0.
Bubble Sort Algorithm
int arr[10] = {9,10,3,2,1,7,5,8,4,6};
int size = 10;
int temp;
for(int i = 0; i < size - 1; i++) {
for(int j = 0; j < size - i - 1; j++) {
if(arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for(int k = 0; k < size; k++) {
printf("%d ", arr[k]);
}
Common and Important Algorithms
number1 = 1, number2 = 2
number3 = number1
number1 = number2
number2 = number3
After: number1 = 2, number2 = 1
Fahrenheit = 5°F
cel = 5/9 (5 - 32) = -15°C (approx)
number1 = 10, number2 = 15
if number1 > number2 then big = number1 else big = number2
Result: big = 15
n = 7
while i != n
sum = sum + i
i = i + 1
n = 5
while i != n
product = product * i
i = i + 1
n = 123
lastdigit = n % 10
while n > 0:
reverse = reverse * 10 + lastdigit
n = n / 10