The Wayback Machine - https://web.archive.org/web/20240927175329/https://www.geeksforgeeks.org/strong-password-suggester-program/
Open In App

Strong Password Suggester Program

Last Updated : 17 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a password entered by the user, check its strength and suggest some password if it is not strong.

Criteria for strong password is as follows : 
A password is strong if it has : 

  1. At least 8 characters 
  2. At least one special char 
  3. At least one number 
  4. At least one upper and one lower case char. 

Examples : 

Input : keshav123
Output : Suggested Password
        k(eshav12G3
        keshav1@A23
        kesh!Aav123
        ke(shav12V3
        keGshav1$23
        kesXhav@123
        keAshav12$3
        kesKhav@123
        kes$hav12N3
        $kesRhav123

Input :rakesh@1995kumar
Output : Your Password is Strong

Approach : Check the input password for its strength if it fulfills all the criteria, then it is strong password else check for the absent characters in it, and return the randomly generated password to the user.  

Implementation:

C++




// CPP code to suggest strong password
#include <bits/stdc++.h>
 
using namespace std;
 
// adding more characters to suggest strong password
string add_more_char(string str, int need)
{
    int pos = 0;
 
    // all 26 letters
    string low_case = "abcdefghijklmnopqrstuvwxyz";
 
    for (int i = 0; i < need; i++) {
        pos = rand() % str.length();
        str.insert(pos, 1, low_case[rand() % 26]);
    }
    return str;
}
 
// make powerful string
string suggester(int l, int u, int d, int s, string str)
{
 
    // all digits
    string num = "0123456789";
 
    // all lower case, uppercase and special characters
    string low_case = "abcdefghijklmnopqrstuvwxyz";
    string up_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string spl_char = "@#$_()!";
 
    // position at which place a character
    int pos = 0;
 
    // if there is no lowercase char in input string, add it
    if (l == 0) {
        // generate random integer under string length
        pos = rand() % str.length();
 
        // generate random integer under 26 for indexing of a to z
        str.insert(pos, 1, low_case[rand() % 26]);
    }
 
    // if there is no upper case char in input string, add it
    if (u == 0) {
        pos = rand() % str.length();
        str.insert(pos, 1, up_case[rand() % 26]);
    }
 
    // if there is no digit in input string, add it
    if (d == 0) {
        pos = rand() % str.length();
        str.insert(pos, 1, num[rand() % 10]);
    }
 
    // if there is no special character in input string, add it
    if (s == 0) {
        pos = rand() % str.length();
        str.insert(pos, 1, spl_char[rand() % 7]);
    }
 
    return str;
}
 
/* make_password function :This function is used to check
strongness and if input string is not strong, it will suggest*/
void generate_password(int n, string p)
{
    // flag for lower case, upper case, special
    // characters and need of more characters
    int l = 0, u = 0, d = 0, s = 0, need = 0;
 
    // password suggestions.
    string suggest;
 
    for (int i = 0; i < n; i++) {
        // password suggestions.
        if (p[i] >= 97 && p[i] <= 122)
            l = 1;
        else if (p[i] >= 65 && p[i] <= 90)
            u = 1;
        else if (p[i] >= 48 && p[i] <= 57)
            d = 1;
        else
            s = 1;
    }
 
    // Check if input string is strong that
    // means all flag are active.
    if ((l + u + d + s) == 4) {
        cout << "Your Password is Strong" << endl;
        return;
    }
    else
        cout << "Suggested password " << endl;
 
    /*suggest 10 strong strings */
    for (int i = 0; i < 10; i++) {
        suggest = suggester(l, u, d, s, p);
        need = 8 - suggest.length();
        if (need > 0)
            suggest = add_more_char(suggest, need);
        cout << suggest << endl;
    }
}
 
// Driver code
int main()
{
    string input_string = "geek@2018";
    srand(time(NULL));
 
    // srand function set Seed for rand().
    generate_password(input_string.length(), input_string);
    return 0;
}


Java




// Java code to suggest strong password
import java.io.*;
import java.util.*;
import java.util.Random;
 
public class GFG {
 
    // adding more characters to suggest
    // strong password
    static StringBuilder add_more_char(
                        StringBuilder str, int need)
    {
        int pos = 0;
        Random randm = new Random();
         
        // all 26 letters
        String low_case = "abcdefghijklmnopqrstuvwxyz";
 
        for (int i = 0; i < need; i++) {
            pos = randm.nextInt(1000) % str.length();
            str.setCharAt(pos,low_case.charAt(
                            randm.nextInt(1000) % 26));
        }
        return str;
    }
 
    // make powerful String
    static StringBuilder suggester(int l, int u, int d,
                              int s, StringBuilder str)
    {
        Random randm = new Random();
         
        // all digits
        String num = "0123456789";
 
        // all lower case, uppercase and special
        // characters
        String low_case = "abcdefghijklmnopqrstuvwxyz";
        String up_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String spl_char = "@#$_()!";
 
        // position at which place a character
        int pos = 0;
 
        // if there is no lowercase char in input
        // String, add it
        if (l == 0) {
             
            // generate random integer under
            // String length()
            pos = randm.nextInt(1000) % str.length();
 
            // generate random integer under 26 for
            // indexing of a to z
            str.setCharAt(pos,low_case.charAt(randm.nextInt(1000)
                                        % 26));
        }
 
        // if there is no upper case char in input
        // String, add it
        if (u == 0) {
            pos = randm.nextInt(1000) % str.length();
            str.setCharAt(pos,low_case.charAt(randm.nextInt(1000)
                                        % 26));
        }
 
        // if there is no digit in input String, add it
        if (d == 0) {
            pos = randm.nextInt(1000) % str.length();
            str.setCharAt(pos,low_case.charAt(randm.nextInt(1000)
                                        % 10));
        }
 
        // if there is no special character in input
        // String, add it
        if (s == 0) {
            pos = randm.nextInt(1000) % str.length();
            str.setCharAt(pos,low_case.charAt(randm.nextInt(1000)
                                        % 7));
        }
 
        return str;
    }
 
    /* make_password function :This function is used
    to check strongness and if input String is not
    strong, it will suggest*/
    static void generate_password(int n, StringBuilder p)
    {
         
        // flag for lower case, upper case, special
        // characters and need of more characters
        int l = 0, u = 0, d = 0, s = 0, need = 0;
 
        // password suggestions.
        StringBuilder suggest;
 
        for (int i = 0; i < n; i++) {
             
            // password suggestions.
            if (p.charAt(i) >= 97 && p.charAt(i) <= 122)
                l = 1;
            else if (p.charAt(i) >= 65 && p.charAt(i) <= 90)
                u = 1;
            else if (p.charAt(i) >= 48 && p.charAt(i) <= 57)
                d = 1;
            else
                s = 1;
        }
 
        // Check if input String is strong that
        // means all flag are active.
        if ((l + u + d + s) == 4) {
            System.out.println("Your Password is Strong");
            return;
        }
        else
            System.out.println("Suggested password ");
 
        /*suggest 10 strong Strings */
        for (int i = 0; i < 10; i++) {
            suggest = suggester(l, u, d, s, p);
            need = 8 - suggest.length();
            if (need > 0)
                suggest = add_more_char(suggest, need);
            System.out.println(suggest);;
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        StringBuilder input_String = new StringBuilder("geek@2018");
        generate_password(input_String.length(), input_String);
    }
}
 
// This code is contributed by Manish Shaw (manishshaw1)


Python3




# Python code to suggest strong password
 
import random
 
# Function to insert character in a string
# Because string is immutable in python
def insert(s, pos, ch):
        return(s[:pos] + ch + s[pos:])
         
# adding more characters to
# suggest strong password
def add_more_char(s, need):
        pos = 0
 
        # add 26 letters
        low_case = "abcdefghijklmnopqrstuvwxyz"
 
        for i in range(need):
                pos = random.randint(0, len(s)-1)
                s = insert(s, pos, low_case[random.randint(0,25)])
 
        return(s)
 
# Make powerful string
def suggester(l, u, d, s, st):
 
        # all digits
        num = '0123456789'
 
        # all lower case, upper case and special characters
        low_case = "abcdefghijklmnopqrstuvwxyz"
        up_case = low_case.upper()
        spl_char = '@#$_()!'
 
        # Position at which place a character
        pos = 0
 
        # If there is no lowercase char
        # in input string, add it
        if( l == 0 ):
           
                # Generate random integer under string length
                pos = random.randint(0,len(st)-1)
 
                # Generate random integer under 26 for indexing of a to z
                st = insert(st, pos, low_case[random.randint(0,25)])
 
        # If there is no upper case char in input string, add it
        if( u == 0 ):
           
                # Generate random integer under string length
                pos = random.randint(0,len(st)-1)
 
                # Generate random integer under 26 for indexing of A to Z
                st = insert(st, pos, up_case[random.randint(0,25)])
 
        # If there is no digit in input string, add it
        if( d == 0 ):
           
                # Generate random integer under string length
                pos = random.randint(0,len(st)-1)
 
                # Generate random integer under 10 for indexing of 0 to 9
                st = insert(st, pos, num[random.randint(0,9)])
 
        # If there is no special character
        # in input string, add it
        if( s == 0 ):
           
                # Generate random integer under string length
                pos = random.randint(0,len(st)-1)
 
                # Generate random integer under 7 for
                # indexing of special characters
                st = insert(st, pos, low_case[random.randint(0,6)])
 
        return st
 
# generate_password function : This function is used to check
# strength and if input string is not strong, It will suggest
def generate_password(n, p):
   
        # flag for lower case, upper case, special
        # characters and need of more characters
        l = 0; u = 0; d = 0; s = 0; need = 0
 
        # Password suggestions
        suggest = ''
 
        for i in range(n):
           
                # Password suggestion
                if( p[i].islower() ):
                        l = 1
                elif( p[i].isupper() ):
                        u = 1
                elif( p[i].isdigit() ):
                        d = 1
                else:
                        s = 1
 
        # Check if input string is strong that
        # means all flags are active
        if( (l + u + d + s) == 4):
                print("Your Password is Strong")
                return
        else:
                print("Suggested Passwords")
 
        # Suggest 10 strong strings
        for i in range(10):
                suggest = suggester(l, u, d, s, p)
                need = 8 - len(suggest)
 
                if(need > 0):
                        suggest = add_more_char(suggest, need)
                print(suggest)
 
 
# Driver Code
input_string = 'geek@2018'
 
generate_password( len(input_string), input_string)
 
 
# This code is contributed by Arjun Saini


C#




// C# code to suggest strong password
using System;
using System.Collections.Generic;
 
class GFG {
 
    // adding more characters to suggest
    // strong password
    static string add_more_char(string str, int need)
    {
        int pos = 0;
        Random randm = new Random();
         
        // all 26 letters
        string low_case = "abcdefghijklmnopqrstuvwxyz";
 
        for (int i = 0; i < need; i++) {
            pos = randm.Next(1,1000) % str.Length;
            str = str.Insert(pos,low_case[randm.Next(1000)
                                        % 26].ToString());
        }
        return str;
    }
 
    // make powerful string
    static string suggester(int l, int u, int d, int s,
                                             string str)
    {
        Random randm = new Random();
         
        // all digits
        string num = "0123456789";
 
        // all lower case, uppercase and special
        // characters
        string low_case = "abcdefghijklmnopqrstuvwxyz";
        string up_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string spl_char = "@#$_()!";
 
        // position at which place a character
        int pos = 0;
 
        // if there is no lowercase char in input
        // string, add it
        if (l == 0) {
             
            // generate random integer under
            // string length
            pos = randm.Next(1,1000) % str.Length;
 
            // generate random integer under 26 for
            // indexing of a to z
            str = str.Insert(pos,low_case[randm.Next(1,
                                 1000) % 26].ToString());
        }
 
        // if there is no upper case char in input
        // string, add it
        if (u == 0) {
            pos = randm.Next(1,1000) % str.Length;
            str = str.Insert(pos,up_case[randm.Next(
                              1,1000) % 26].ToString());
        }
 
        // if there is no digit in input string, add it
        if (d == 0) {
            pos = randm.Next(1,1000) % str.Length;
            str = str.Insert(pos,num[randm.Next(1,1000)
                                      % 10].ToString());
        }
 
        // if there is no special character in input
        // string, add it
        if (s == 0) {
            pos = randm.Next(1,1000) % str.Length;
            str = str.Insert(pos,spl_char[randm.Next(
                              1,1000) % 7].ToString());
        }
 
        return str;
    }
 
    /* make_password function :This function is used
    to check strongness and if input string is not
    strong, it will suggest*/
    static void generate_password(int n, string p)
    {
         
        // flag for lower case, upper case, special
        // characters and need of more characters
        int l = 0, u = 0, d = 0, s = 0, need = 0;
 
        // password suggestions.
        string suggest;
 
        for (int i = 0; i < n; i++) {
             
            // password suggestions.
            if (p[i] >= 97 && p[i] <= 122)
                l = 1;
            else if (p[i] >= 65 && p[i] <= 90)
                u = 1;
            else if (p[i] >= 48 && p[i] <= 57)
                d = 1;
            else
                s = 1;
        }
 
        // Check if input string is strong that
        // means all flag are active.
        if ((l + u + d + s) == 4) {
            Console.WriteLine("Your Password is Strong\n");
            return;
        }
        else
            Console.WriteLine("Suggested password\n ");
 
        /*suggest 10 strong strings */
        for (int i = 0; i < 10; i++) {
            suggest = suggester(l, u, d, s, p);
            need = 8 - suggest.Length;
            if (need > 0)
                suggest = add_more_char(suggest, need);
            Console.WriteLine(suggest + "\n");;
        }
    }
 
    // Driver code
    public static void Main()
    {
        string input_string = "geek@2018";
        generate_password(input_string.Length, input_string);
    }
}
 
// This code is contributed by Manish Shaw (manishshaw1)


PHP




<?php
// php code to suggest
// strong password
 
// adding more characters to
// suggest strong password
function add_more_char( $str, $need)
{
    $pos = 0;
 
    // all 26 letters
    $low_case = "abcdefghijklmnopqrstuvwxyz";
 
    for ($i = 0; $i < $need; $i++)
    {
        $pos = rand() % strlen($str);
        $str[$pos]=$low_case[rand() % 26];
    }
    return $str;
}
 
// make powerful string
function suggester($l, $u, $d, $s, $str)
{
     
    // all digits
    $num = "0123456789";
 
    // all lower case, uppercase and
    // special characters
    $low_case = "abcdefghijklmnopqrstuvwxyz";
    $up_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     
    // $spl_char1 = "@#$_()!";
    // position at which place
    // a character
    $pos = 0;
 
    // if there is no lowercase char
    // in input string, add it
    if ($l == 0)
    {
         
        // generate random integer
        // under string length
        $pos = rand() % strlen($str);
 
        // generate random integer under
        // 26 for indexing of a to z
        $str[$pos]=$low_case[rand() % 26];
    }
 
    // if there is no upper case
    // char in input string, add it
    if ($u == 0)
    {
        $pos = rand() % strlen($str);
        $str[$pos]=$up_case[rand() % 26];
    }
 
    // if there is no digit
    // in input string, add it
    if ($d == 0) {
        $pos = rand() % strlen($str);
        $str[$pos]=$num[rand() % 10];
    }
 
    // if there is no special character
    // in input string, add it
    if ($s == 0)
    {
        $pos = rand() % strlen($str);
        $str[$pos]=$spl_char1[rand() % 7];
    }
 
    return $str;
}
 
// Make_password function : This
// function is used to check
// strongness and if input string
// is not strong, it will suggest
function generate_password($n, $p)
{
     
    // flag for lower case, upper case,
    // special characters and need
    // of more characters
    $l = 0;
    $u = 0;
    $d = 0;
    $s = 0;
    $need = 0;
 
    // password suggestions.
    $suggest;
 
    for ($i = 0; $i < $n; $i++)
    {
        // password suggestions.
        if ($p[$i] >= 97 && $p[$i] <= 122)
            $l = 1;
        else if ($p[$i] >= 65 && $p[$i] <= 90)
            $u = 1;
        else if ($p[$i] >= 48 && $p[$i] <= 57)
            $d = 1;
        else
            $s = 1;
    }
 
    // Check if input string is strong
    // that means all flag are active.
    if (($l + $u + $d + $s) == 4)
    {
        echo "Your Password is Strong.\n";
        return;
    }
    else
        echo "Suggested password";
 
    // suggest 10 strong strings
    for ($i = 0; $i < 10; $i++)
    {
        $suggest = suggester($l, $u, $d, $s, $p);
        $need = 8 - strlen($suggest);
        if ($need > 0)
            $suggest = add_more_char($suggest, $need);
        echo "\n".$suggest;
    }
}
 
    // Driver code
    $input_string = "geek@2018";
    srand(mktime(NULL));
 
    // srand function set Seed for rand().
    generate_password(strlen($input_string),
                      $input_string);
 
// This code is contributed by mits
?>


Javascript




// adding more characters to suggest
// strong password
function add_more_char(str, need) {
    let pos = 0;
    // all 26 characters
    const low_case = "abcdefghijklmnopqrstuvwxyz";
    for (let i = 0; i < need; i++) {
        pos = Math.floor(Math.random() * 1000) % str.length;
        str = str.substring(0, pos) + low_case.charAt(
            Math.floor(Math.random() * 1000) % 26
        ) + str.substring(pos + 1);
    }
    return str;
}
 
function suggester(l, u, d, s, str) {
   // all numbers, upper case letters,lower case letters
    const num = "0123456789";
    const low_case = "abcdefghijklmnopqrstuvwxyz";
    const up_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const spl_char = "@#$_()!";
 
    let pos = 0;
 
    if (l === 0) {
       // generate random integer under
       // String length()
        pos = Math.floor(Math.random() * 1000) % str.length;
        // generate random integer under 26 for
        // indexing of a to z
        str = str.substring(0, pos) + low_case.charAt(
            Math.floor(Math.random() * 1000) % 26
        ) + str.substring(pos + 1);
    }
    // if there is no upper case char in input
    // String, add it
    if (u === 0) {
        pos = Math.floor(Math.random() * 1000) % str.length;
        str = str.substring(0, pos) + up_case.charAt(
            Math.floor(Math.random() * 1000) % 26
        ) + str.substring(pos + 1);
    }
    // if there is no digit in input String, add it
    if (d === 0) {
        pos = Math.floor(Math.random() * 1000) % str.length;
        str = str.substring(0, pos) + num.charAt(
            Math.floor(Math.random() * 1000) % 10
        ) + str.substring(pos + 1);
    }
     // if there is no special character in input
     // String, add it
    if (s === 0) {
        pos = Math.floor(Math.random() * 1000) % str.length;
        str = str.substring(0, pos) + spl_char.charAt(
            Math.floor(Math.random() * 1000) % 7
        ) + str.substring(pos + 1);
    }
 
    return str;
}
/* make_password function :This function is used
to check strongness and if input String is not
strong, it will suggest*/
function generate_password(n, p) {
    // flag for lower case, upper case, special
    // characters and need of more characters
    let l = 0, u = 0, d = 0, s = 0, need = 0;
    let suggest;
 
    for (let i = 0; i < n; i++) {
        if (p.charCodeAt(i) >= 97 && p.charCodeAt(i) <= 122) {
            l = 1;
        } else if (p.charCodeAt(i) >= 65 && p.charCodeAt(i) <= 90) {
            u = 1;
        } else if (p.charCodeAt(i) >= 48 && p.charCodeAt(i) <= 57) {
            d = 1;
        } else {
            s = 1;
        }
    }
     // Check if input String is strong that
     // means all flag are active.
    if ((l + u + d + s) === 4) {
        console.log("Your Password is Strong");
        return;
    } else {
        console.log("Suggested password");
    }
    // Generate some 10 random suggestions which are strong
    for (let i = 0; i < 10; i++) {
        suggest = suggester(l, u, d, s, p);
        need = 8 - suggest.length;
        if (need > 0) {
            suggest = add_more_char(suggest, need);
        }
        console.log(suggest);
    }
}
 
const input_String = "geek@2018";
generate_password(input_String.length, input_String);


Output: 

Suggested password 
geek@201K8
geek@201S8
gOeek@2018
geek@201N8
geek@2P018
geek@D2018
geUek@2018
geek@2Q018
geek@2F018
geekZ@2018

 

Time complexity : O(n). 



Previous Article
Next Article

Similar Reads

Minimum characters required to make a password strong
Given string str denoting a password, the task is to count the minimum characters that need to be added to make the password strong. A password is said to be strong if it satisfies the following criteria: It contains at least 8 characters.It contains at least one digit.It contains at least one lower case alphabet.It contains at least one upper case
6 min read
Program to check Strong Number
Strong Numbers are the numbers whose sum of factorial of digits is equal to the original number. Given a number, check if it is a Strong Number or not.Examples: Input : n = 145Output : YesSum of digit factorials = 1! + 4! + 5! = 1 + 24 + 120 = 145Input : n = 534Output : NoRecommended PracticeStrong NumbersTry It!1) Initialize sum of factorials as 0
9 min read
Check if N is Strong Prime
Given a positive integer N, the task is to check if N is a strong prime or not. In number theory, a strong prime is a prime number that is greater than the arithmetic mean of nearest prime numbers i.e next and previous prime numbers. First few strong prime numbers are 11, 17, 29, 37, 41, 59, 67, 71, ... A strong prime Pn can be represented as- wher
9 min read
Print all Strong numbers less than or equal to N
Given a number N, print all the Strong Numbers less than or equal to N. Strong number is a special number whose sum of the factorial of digits is equal to the original number. For Example: 145 is strong number. Since, 1! + 4! + 5! = 145. Examples: Input: N = 100 Output: 1 2 Explanation: Only 1 and 2 are the strong numbers from 1 to 100 because 1! =
6 min read
Count Strong Pairs
Given array A[] of size N, each element represents 2A[i] for all i from 1 to N. The Task for this problem is to find the number of Strong pairs. A Strong pair is defined as a pair (i, j) such that 2A[i] ^ 2A[j] = 2A[j] ^ 2A[i] for i < j. Note: operator ^ denotes the exponent. Examples: Input: A[] = {3, 1, 3, 2} Output: 2Explanation: We have two
7 min read
Program to check the validity of password without using regex.
Password checker program basically checks if a password is valid or not based on the password policies mention below: Password should not contain any space. Password should contain at least one digit(0-9). Password length should be between 8 to 15 characters. Password should contain at least one lowercase letter(a-z). Password should contain at lea
9 min read
Program to check Strength of Password
A password is said to be strong if it satisfies the following criteria: It contains at least one lowercase English character.It contains at least one uppercase English character.It contains at least one special character. The special characters are: !@#$%^&*()-+Its length is at least 8.It contains at least one digit.Given a string, find its str
5 min read
Random password generator in C
In this article, we will discuss how to generate a random password of a given length consists of any characters. Approach: The below-given program involves basic concepts like variables, data types, array, loop, etc.Follow the below steps to solve this problem:Take the length of the password and declare a character array of that length to store tha
2 min read
How to store a password in database?
Most of the web applications require their users to authenticate themselves by asking them username and password. They compare the user supplied credentials with the data stored in their database and if the credentials match, the user is granted access. Sounds good! But what will happen if the database in which the website is storing your passwords
7 min read
To Generate a One Time Password or Unique Identification URL
A one-time password (OTP) is a password that is valid for only one login session or transaction, on a computer system or other digital device. For more details refer this. Algorithm Randomly pick characters from our all possibilities and generate a string of the desired length from it. OTPs are generally 6-7 characters long and randomness in 6-7 ch
5 min read
Javascript Program for Program to cyclically rotate an array by one
Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4}Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Following are steps. 1) Store last element in a variable say x. 2) Shift all elements one position ahead. 3) Replace first element o
2 min read
Write a program to Delete a Tree
To delete a tree, we must traverse all the nodes of the tree and delete them one by one. So, which traversal we should use - inorder traversal, preorder traversal, or the postorder traversal? The answer is simple. We should use the postorder traversal because before deleting the parent node, we should delete its child nodes first.We can delete the
11 min read
Write a program to add two numbers in base 14
Asked by Anshya. Base 14: Decimal numbersBase 14 numbers0011223344556677889910A11B12C13D14D1 Below are the different ways to add base 14 numbers.Method 1 Thanks to Raj for suggesting this method. 1. Convert both i/p base 14 numbers to base 10. 2. Add numbers. 3. Convert the result back to base 14. Method 2 Just add the numbers in base 14 in the sam
15 min read
C Program to Sort an array of names or strings
Given an array of strings in which all characters are of the same case, write a C function to sort them alphabetically. The idea is to use qsort() in C and write a comparison function that uses strcmp() to compare two strings. C/C++ Code #include <stdio.h> #include <stdlib.h> #include <string.h> // Defining comparator function as
2 min read
Program for subtraction of matrices
The below program subtracts of two square matrices of size 4*4, we can change N for a different dimension. Implementation: C/C++ Code // C++ program for subtraction of matrices #include <bits/stdc++.h> using namespace std; #define N 4 // This function subtracts B[][] from A[][], and stores // the result in C[][] void subtract(int A[][N], int
7 min read
Program to find sum of series 1 + 1/2 + 1/3 + 1/4 + .. + 1/n
If inverse of a sequence follows rule of an A.P i.e, Arithmetic progression, then it is said to be in Harmonic Progression.In general, the terms in a harmonic progression can be denoted as : 1/a, 1/(a + d), 1/(a + 2d), 1/(a + 3d) .... 1/(a + nd). As Nth term of AP is given as ( a + (n – 1)d) .Hence, Nth term of harmonic progression is reciprocal of
4 min read
C++ Program to remove spaces from a string
Given a string, remove all spaces from it. For example "g e e k" should be converted to "geek" and " g e " should be converted to "ge". The idea is to traverse the string from left to right and ignore spaces while traversing. We need to keep track of two indexes, one for the current character being red and the other for the current index in the out
2 min read
C Program for Red Black Tree Insertion
Following article is extension of article discussed here.In AVL tree insertion, we used rotation as a tool to do balancing after insertion caused imbalance. In Red-Black tree, we use two tools to do balancing. Recoloring Rotation We try recoloring first, if recoloring doesn't work, then we go for rotation. Following is detailed algorithm. The algor
6 min read
Remove comments from a given C/C++ program
Given a C/C++ program, remove comments from it. We strongly recommend to minimize your browser and try this yourself first. The idea is to maintain two flag variables, one to indicate that a single line comment is started, another to indicate that a multiline comment is started. When a flag is set, we look for the end of comment and ignore all char
3 min read
Program to add two binary strings
Given two binary strings, return their sum (also a binary string). Example: Input: a = "11", b = "1" Output: "100" We strongly recommend you to minimize your browser and try this yourself first The idea is to start from the last characters of two strings and compute the digit sum one by one. If the sum becomes more than 1, then store carry for the
7 min read
Program to print factors of a number in pairs
Given a number n, the task of the programmer is to print the factors of the number in such a way that they occur in pairs. A pair signifies that the product of the pair should result in the number itself. Examples: Input : 24Output : 1*24 2*12 3*8 4*6Input : 50Output : 1*50 2*25 5*10Recommended: Please try your approach on {IDE} first, before movin
7 min read
Program to calculate the number of odd days in given number of years
Given an integer N, the task is to find the number of odd days in the years from 1 to N. Odd Days: Number of odd days refer to those days that are left in a certain year(s) when it's days gets converted into weeks. Say, an ordinary year has 365 days, that is 52 weeks and one odd day. This means, out of the 365 days in an ordinary year, 364 days wil
7 min read
C++ Program to implement Symbol Table
Prerequisite: Symbol Table A Symbol table is a data structure used by the compiler, where each identifier in program's source code is stored along with information associated with it relating to its declaration. It stores identifier as well as it's associated attributes like scope, type, line-number of occurrence, etc. Symbol table can be implement
4 min read
Recursive program to print formula for GCD of n integers
Given a function gcd(a, b) to find GCD (Greatest Common Divisor) of two number. It is also known that GCD of three elements can be found by gcd(a, gcd(b, c)), similarly for four element it can find the GCD by gcd(a, gcd(b, gcd(c, d))). Given a positive integer n. The task is to print the formula to find the GCD of n integer using given gcd() functi
4 min read
Program to find sum of first n natural numbers
Given a number n, find the sum of the first natural numbers. Examples : Input: n = 3 Output: 6 Explanation: Note that 1 + 2 + 3 = 6 Input : 5 Output : 15 Explanation : Note that 1 + 2 + 3 + 4 + 5 = 15Program to Find the Sum of First N Natural Numbers A simple solution is to do the following. 1) Initialize : sum = 0 2) Run a loop from x = 1 to n and
10 min read
Program for diamond pattern with different layers
Given a number n and using 0-n numbers you have to print such a pattern.Examples: Input : n = 5 Output : 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 4 5 4 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 Input : n = 3 Output : 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 The idea here is to count the space in beginning o
10 min read
Program to find gravitational force between two objects
Introduction to Gravitational Force We know that gravity is universal. According to Newton's Law of Universal Gravitation, all objects attract each other with a force of gravitational attraction. According to this law, the force of gravitational attraction is directly dependent upon the masses of both objects and inversely proportional to the squar
4 min read
Program to check if N is an Icosikaioctagonal Number
Given an integer N, the task is to check if it is a icosikaioctagonal number or not. An icosikaioctagonal number is class of figurate number. It has 28 – sided polygon called icosikaioctagon. The N-th icosikaioctagonal number count’s the 28 number of dots and all other dots are surrounding with a common sharing corner and make a pattern. The first
4 min read
Program to find correlation coefficient
Given two array elements and we have to find the correlation coefficient between two arrays. The correlation coefficient is an equation that is used to determine the strength of the relation between two variables. The correlation coefficient is sometimes called as cross-correlation coefficient. The correlation coefficient always lies between -1 to
8 min read
Program to find slope of a line
Given two coordinates, find the slope of a straight line. Examples: Input : x1 = 4, y1 = 2, x2 = 2, y2 = 5 Output : Slope is -1.5 Approach: To calculate the slope of a line you need only two points from that line, (x1, y1) and (x2, y2). The equation used to calculate the slope from two points is: Below is the implementation of the above approach: C
3 min read
Article Tags :
Practice Tags :