Factorial of number -
#include<iostream>
using namespace std;
int factorial(int n){
if(n==0 || n==1){
return 1;
}
return n*factorial(n-1);
}
int main(){
int num =5;
cout<< "factorial of "<<num<<" is "<<factorial(num)<<endl;
return 0;
}
Prime or not – O(n)
#include <iostream>
using namespace std;
bool isPrimeBruteForce(int n) {
if (n <= 1) return false;
for (int i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
if (isPrimeBruteForce(n))
cout << n << " is a prime number.\n";
else
cout << n << " is not a prime number.\n";
return 0;
}
Optimized – O(root n)
#include <iostream>
#include <cmath>
using namespace std;
bool isPrimeOptimized(int n) {
if (n <= 1) return false;
if (n == 2 || n == 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
Second Largest array –
#include <iostream>
#include <climits> // For INT_MIN
#include<bits/stdc++.h>
using namespace std;
int findSecondLargest(int arr[], int n) {
if (n < 2) {
cout << "Array must have at least two elements." << endl;
return -1; // Return a sentinel value indicating an error
}
int largest = INT_MIN;
int secondLargest = INT_MIN;
for (int i = 0; i < n; i++) {
if (arr[i] > largest) {
secondLargest = largest; // Update second largest
largest = arr[i]; // Update largest
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i]; // Update second largest only
}
}
return secondLargest;
}
int main() {
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int secondLargest = findSecondLargest(arr, n);
if (secondLargest != -1)
cout << "The second largest element is: " << secondLargest << endl;
return 0;
}
Fibonacci Series
#include <iostream>
using namespace std;
void printFibonacci(int n) {
int t1 = 0, t2 = 1, nextTerm;
for (int i = 1; i <= n; ++i) {
cout << t1 << " ";
nextTerm = t1 + t2; // Calculate the next term
t1 = t2; // Update t1 to the next term
t2 = nextTerm; // Update t2 to the next term
}
cout << endl;
}
int main() {
int n;
cout << "Enter the number of terms: ";
cin >> n;
cout << "Fibonacci Series: ";
printFibonacci(n);
return 0;
}
Amstrong number –
#include <iostream>
using namespace std;
bool isArmstrong(int n) {
int originalNum = n;
int sum = 0;
int numDigits = 0;
// Calculate the number of digits
while (n != 0) {
n /= 10;
++numDigits;
}
n = originalNum; // Reset n to the original value
// Calculate the sum of the digits each raised to the power of the number of digits
while (n != 0) {
int digit = n % 10;
// Manually compute digit^numDigits
int power = 1;
for (int i = 0; i < numDigits; ++i) {
power *= digit;
}
sum += power;
n /= 10;
}
// Check if the sum is equal to the original number
return (sum == originalNum);
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
if (isArmstrong(n))
cout << n << " is an Armstrong number.\n";
else
cout << n << " is not an Armstrong number.\n";
return 0;
}
Reverse string –
#include <iostream>
using namespace std;
void reverseString(string &str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
// Swap characters at start and end
char temp = str[start];
str[start] = str[end];
str[end] = temp;
// Move pointers towards the center
start++;
end--;
}
}
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
// Reverse the string
reverseString(str);
cout << "Reversed string: " << str << endl;
return 0;
}
Leap year –
#include <iostream>
using namespace std;
bool isLeapYear(int year) {
// A year is a leap year if:
// 1. It is divisible by 4 but not divisible by 100, OR
// 2. It is divisible by 400
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return true;
} else {
return false;
}
}
int main() {
int year;
cout << "Enter a year: ";
cin >> year;
if (isLeapYear(year)) {
cout << year << " is a leap year." << endl;
} else {
cout << year << " is not a leap year." << endl;
}
return 0;
}
Member of febonacci -
#include <iostream>
using namespace std;
bool isFibonacci(int n) {
if (n < 0) {
return false; // Negative numbers are not in the Fibonacci sequence
}
// Initializing the first two Fibonacci numbers
int a = 0, b = 1;
// Generate Fibonacci numbers until we reach or exceed n
while (a <= n) {
if (a == n) {
return true;
}
int temp = a;
a = b;
b = temp + b;
}
return false;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
if (isFibonacci(n)) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}
Palindrome –
#include <iostream>
#include <string>
using namespace std;
// Function to check if a string is a palindrome
bool isPalindromeString(const string &str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
if (str[start] != str[end]) {
return false;
}
start++;
end--;
}
return true;
}
// Function to check if a number is a palindrome
bool isPalindromeNumber(int n) {
if (n < 0) return false; // Negative numbers are not palindromes
int original = n;
int reversed = 0;
while (n > 0) {
int digit = n % 10;
reversed = reversed * 10 + digit;
n /= 10;
}
return original == reversed;
}
int main() {
string str;
int num;
// Check if a string is a palindrome
cout << "Enter a string: ";
getline(cin, str);
if (isPalindromeString(str)) {
cout << "\"" << str << "\" is a palindrome." << endl;
} else {
cout << "\"" << str << "\" is not a palindrome." << endl;
}
return 0;
}
Frequency Occurrence -
#include <iostream>
using namespace std;
int findFrequency(const int arr[], int size, int element) {
int count = 0;
// Iterate through the array to count occurrences of the element
for (int i = 0; i < size; ++i) {
if (arr[i] == element) {
count++;
}
}
return count;
}
int main() {
int size, element;
cout << "Enter the number of elements in the array: ";
cin >> size;
int* arr = new int[size];
// Input elements into the array
cout << "Enter " << size << " elements:" << endl;
for (int i = 0; i < size; ++i) {
cin >> arr[i];
}
// Input the element to find its frequency
cout << "Enter the element to find its frequency: ";
cin >> element;
// Find and display the frequency of the element
int frequency = findFrequency(arr, size, element);
cout << "The element " << element << " occurs " << frequency << " times in the array." <<
endl;
delete[] arr; // Free the allocated memory
return 0;
}
Anagrams -
#include <iostream>
#include <algorithm> // For sort() function
#include <cctype> // For tolower() function
using namespace std;
// Function to check if two strings are anagrams
bool areAnagrams(const string &str1, const string &str2) {
// If lengths are different, they can't be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Create copies of the strings to avoid modifying the originals
string s1 = str1;
string s2 = str2;
// Convert both strings to lowercase for case-insensitive comparison
transform(s1.begin(), s1.end(), s1.begin(), ::tolower);
transform(s2.begin(), s2.end(), s2.begin(), ::tolower);
// Sort both strings
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
// Compare sorted versions of the strings
return s1 == s2;
}
int main() {
string str1, str2;
cout << "Enter the first string: ";
getline(cin, str1);
cout << "Enter the second string: ";
getline(cin, str2);
if (areAnagrams(str1, str2)) {
cout << "\"" << str1 << "\" and \"" << str2 << "\" are anagrams." << endl;
} else {
cout << "\"" << str1 << "\" and \"" << str2 << "\" are not anagrams." << endl;
}
return 0;
}
frequency of characters in a string
#include<bits/stdc++.h>
using namespace std;
int main()
{
//Initializing variables.
char str[100];
int i;
int freq[256] = {0};
//Accepting inputs.
cout<<"Enter the string: ";
gets(str);
//Calculating frequency of each character.
for(i = 0; str[i] != '\0'; i++)
{
freq[str[i]]++;
}
//Printing frequency of each character.
for(i = 0; i < 256; i++)
{
if(freq[i] != 0)
{
cout<<"The frequency of "<<char(i)<<" is "<<freq[i]<<endl;
}
}
return 0;
}
Bubble sort -
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; ++i)
for (int j = 0; j < n - i - 1; ++j)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; ++i) cin >> arr[i];
bubbleSort(arr, n);
for (int i = 0; i < n; ++i) cout << arr[i] << " ";
cout << endl;
return 0;
}
Merge sort –
#include <iostream>
using namespace std;
// Function to merge two sorted subarrays into a single sorted array
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1; // Size of the left subarray
int n2 = r - m; // Size of the right subarray
int L[n1], R[n2]; // Temporary arrays to hold the subarrays
// Copy data to temporary arrays L[] and R[]
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l; // Initial indexes for L[], R[], and merged array
// Merge the temporary arrays back into arr[l..r]
while (i < n1 && j < n2) {
if (L[i] <= R[j]) // If the current element of L[] is smaller or equal
arr[k++] = L[i++]; // Add it to the merged array
else // Otherwise, add the current element of R[]
arr[k++] = R[j++];
}
// Copy any remaining elements of L[], if any
while (i < n1)
arr[k++] = L[i++];
// Copy any remaining elements of R[], if any
while (j < n2)
arr[k++] = R[j++];
}
// Function to perform merge sort
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2; // Find the middle point to divide the array
mergeSort(arr, l, m); // Recursively sort the first half
mergeSort(arr, m + 1, r); // Recursively sort the second half
merge(arr, l, m, r); // Merge the sorted halves
}
}
int main() {
int n;
cin >> n; // Input the number of elements
int arr[n];
// Input the array elements
for (int i = 0; i < n; ++i)
cin >> arr[i];
mergeSort(arr, 0, n - 1); // Perform merge sort on the entire array
// Output the sorted array
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
return 0;
}
Sum of natural numbers -
#include<bits/stdc++.h>
using namespace std;
int getSum(int n)
{
if(n==0)
return n;
return n + getSum(n-1);
}
int main()
{
int n;
cout << "Enter a number : ";
cin >> n;
int sum = getSum(n);
cout << sum;
return 0;
}
Binary to decimal -
#include <iostream>
#include <string>
using namespace std;
int binaryToDecimal(string binary) {
int decimal = 0;
int base = 1; // 2^0
// Start from the last digit and move to the first digit
for (int i = binary.length() - 1; i >= 0; --i) {
if (binary[i] == '1') {
decimal += base;
}
base *= 2; // Move to the next power of 2
}
return decimal;
}
int main() {
string binary;
cout << "Enter a binary number: ";
cin >> binary;
int decimal = binaryToDecimal(binary);
cout << "Decimal equivalent: " << decimal << endl;
return 0;
}
Vowel –
//C++ Program to check whether alphabet is vowel or consonant
#include <iostream>
using namespace std;
//main function
int main()
{
char c;
cout<<"Enter an alphabet: ";
cin>>c;
//checking for vowels
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
{
cout<<c<<" is a vowel"; //condition true input is vowel
}
else
{
cout<<c<<" is a consonant"; //condition false input is consonant
}
return 0;
}
Ascii –
#include<iostream>
using namespace std;
//main program
int main()
{
char val;
cout<<"Enter a character: ";
cin>>val;
//printing the ASCII value of input
//through typecasting
cout<<"The ASCII value of "<<val<<" is "<<(int)val;
return 0;
}
Remove all characters from string except alphabets
#include <iostream>
using namespace std;
int main()
{
//Initializing variable.
char str[100];
int i, j;
//Accepting input.
cout<<"Enter a string : ";
gets(str);
//Iterating each character and removing non alphabetical characters.
for(i = 0; str[i] != '\0'; ++i)
{
while (!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\0') )
{
for(j = i; str[j] != '\0'; ++j)
{
str[j] = str[j+1];
}
str[j] = '\0';
}
}
//Printing output.
cout<<"After removing non alphabetical characters the string is :";
puts(str);
return 0;
}
Sum of Digits of a Number
//C++ Program
//Sum of digits in a number
#include
using namespace std;
int main ()
{
int num, sum = 0;
cout <<"Enter any num:"; cin >> num;
//loop to find sum of digits
while(num!=0){
sum += num % 10;
num = num / 10;
}
//output
cout <<"\nSum of digits : " << sum;
return 0;
}
Power of number -
// This method handles all cases,
// when exponent/bases are integers/decimals or positive/negative
// pow function is contained in math.h library
#include
#include
using namespace std;
int main()
{
double base = 1.5;
double expo1 = 2.5;
double expo2 = -2.5;
double res1, res2;
// calculates the power
res1 = pow(base, expo1);
res2 = pow(base, expo2);
cout << base << " ^ " << expo1 << " = " << res1 << endl;
cout << base << " ^ " << expo2 << " = " << res2 << endl;
return 0;
}