The Wayback Machine - https://web.archive.org/web/20240804080107/https://www.geeksforgeeks.org/morse-code-implementation/
Open In App

Morse Code Implementation

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph.

The algorithm is very simple. Every character in the English language is substituted by a series of ‘dots’ and ‘dashes’ or sometimes just singular ‘dot’ or ‘dash’ and vice versa.

Every text string is converted into the series of dots and dashes. For this every character is converted into its Morse code and appended in encoded message. Here we have copied space as it is. We have considered both numbers and alphabets.

Examples: 

Input :  geeksforgeeks
Output : --...-.-.....-.---.-.--...-.-...

Input :  program
Output : .--..-.-----..-..---

Implementation:

C++




// CPP program to demonstrate Morse code
#include <iostream>
using namespace std;
 
// function to encode a alphabet as
// Morse code
string morseEncode(char x)
{
 
    // refer to the Morse table
    // image attached in the article
    switch (x) {
    case 'a':
        return ".-";
    case 'b':
        return "-...";
    case 'c':
        return "-.-.";
    case 'd':
        return "-..";
    case 'e':
        return ".";
    case 'f':
        return "..-.";
    case 'g':
        return "--.";
    case 'h':
        return "....";
    case 'i':
        return "..";
    case 'j':
        return ".---";
    case 'k':
        return "-.-";
    case 'l':
        return ".-..";
    case 'm':
        return "--";
    case 'n':
        return "-.";
    case 'o':
        return "---";
    case 'p':
        return ".--.";
    case 'q':
        return "--.-";
    case 'r':
        return ".-.";
    case 's':
        return "...";
    case 't':
        return "-";
    case 'u':
        return "..-";
    case 'v':
        return "...-";
    case 'w':
        return ".--";
    case 'x':
        return "-..-";
    case 'y':
        return "-.--";
    case 'z':
        return "--..";
    case '1':
        return ".----";
    case '2':
        return "..---";
    case '3':
        return "...--";
    case '4':
        return "....-";
    case '5':
        return ".....";
    case '6':
        return "-....";
    case '7':
        return "--...";
    case '8':
        return "---..";
    case '9':
        return "----.";
    case '0':
        return "-----";
    default:
        cerr << "Found invalid character: " << x << ' '
             << std::endl;
        exit(0);
    }
}
 
void morseCode(string s)
{
 
    // character by character print
    // Morse code
    for (int i = 0; s[i]; i++)
        cout << morseEncode(s[i]);
    cout << endl;
}
 
// Driver's code
int main()
{
    string s = "geeksforgeeks";
    morseCode(s);
    return 0;
}


Java




// Java program to demonstrate Morse code
class GFG
{
    // function to encode a alphabet as
    // Morse code
    static String morseEncode(char x)
    {
     
        // refer to the Morse table
        // image attached in the article
        switch (x)
        {
            case 'a':
                return ".-";
            case 'b':
                return "-...";
            case 'c':
                return "-.-.";
            case 'd':
                return "-..";
            case 'e':
                return ".";
            case 'f':
                return "..-.";
            case 'g':
                return "--.";
            case 'h':
                return "....";
            case 'i':
                return "..";
            case 'j':
                return ".---";
            case 'k':
                return "-.-";
            case 'l':
                return ".-..";
            case 'm':
                return "--";
            case 'n':
                return "-.";
            case 'o':
                return "---";
            case 'p':
                return ".--.";
            case 'q':
                return "--.-";
            case 'r':
                return ".-.";
            case 's':
                return "...";
            case 't':
                return "-";
            case 'u':
                return "..-";
            case 'v':
                return "...-";
            case 'w':
                return ".--";
            case 'x':
                return "-..-";
            case 'y':
                return "-.--";
            // for space
            case 'z':
                return "--..";
            case '1':
                return ".----";
            case '2':
                return "..---";
            case '3':
                return "...--";
            case '4':
                return "....-";
            case '5':
                return ".....";
            case '6':
                return "-....";
            case '7':
                return "--...";
            case '8':
                return "---..";
            case '9':
                return "----.";
           case '0':
                return "-----";
        }
        return "";
    }
     
    static void morseCode(String s)
    {
        // character by character print
        // Morse code
        for (int i = 0;i<s.length(); i++)
            System.out.print(morseEncode(s.charAt(i)));
            System.out.println();
    }
     
    // Driver code
    public static void main (String[] args)
    {
        String s = "geeksforgeeks";
        morseCode(s);
    }
}
 
// This code is contributed by Anant Agarwal.


Python 3




# Python3 program to demonstrate Morse code
 
# function to encode a alphabet as
# Morse code
def morseEncode(x):
     
    # refer to the Morse table
    # image attached in the article
    if x is 'a':
        return ".-"
    elif x is 'b':
        return "-..."
    elif x is 'c':
        return "-.-."
    elif x is 'd':
        return "-.."
    elif x is 'e':
        return "."
    elif x is 'f':
        return "..-."
    elif x is 'g':
        return "--."
    elif x is 'h':
        return "...."
    elif x is 'i':
        return ".."
    elif x is 'j':
        return ".---"
    elif x is 'k':
        return "-.-"
    elif x is 'l':
        return ".-.."
    elif x is 'm':
        return "--"
    elif x is 'n':
        return "-."
    elif x is 'o':
        return "---"
    elif x is 'p':
        return ".--."
    elif x is 'q':
        return "--.-"
    elif x is 'r':
        return ".-."
    elif x is 's':
        return "..."
    elif x is 't':
        return "-"
    elif x is 'u':
        return "..-"
    elif x is 'v':
        return "...-"
    elif x is 'w':
        return ".--"
    elif x is 'x':
        return "-..-"
    elif x is 'y':
        return "-.--"
    elif x is 'z':
        return "--.."
    elif x is '1':
        return ".----";
    elif x is '2':
        return "..---";
    elif x is '3':
        return "...--";
    elif x is '4':
        return "....-";
    elif x is '5':
        return ".....";
    elif x is '6':
        return "-....";
    elif x is '7':
        return "--...";
    elif x is '8':
        return "---..";
    elif x is '9':
        return "----.";
    elif x is '0':
        return "-----";
 
# character by character print
# Morse code
def morseCode(s):
    for character in s:
        print(morseEncode(character), end = "")
 
# Driver Code
if __name__ == "__main__":
    s = "geeksforgeeks"
    morseCode(s)
 
# This code is contributed
# by Vivek Kumar Singh


C#




// C# program to demonstrate Morse code
using System;
 
class GFG
{
    // function to encode a alphabet as
    // Morse code
    static string morseEncode(char x)
    {
     
        // refer to the Morse table
        // image attached in the article
        switch (x)
        {
            case 'a':
                return ".-";
            case 'b':
                return "-...";
            case 'c':
                return "-.-.";
            case 'd':
                return "-..";
            case 'e':
                return ".";
            case 'f':
                return "..-.";
            case 'g':
                return "--.";
            case 'h':
                return "....";
            case 'i':
                return "..";
            case 'j':
                return ".---";
            case 'k':
                return "-.-";
            case 'l':
                return ".-..";
            case 'm':
                return "--";
            case 'n':
                return "-.";
            case 'o':
                return "---";
            case 'p':
                return ".--.";
            case 'q':
                return "--.-";
            case 'r':
                return ".-.";
            case 's':
                return "...";
            case 't':
                return "-";
            case 'u':
                return "..-";
            case 'v':
                return "...-";
            case 'w':
                return ".--";
            case 'x':
                return "-..-";
            case 'y':
                return "-.--";
            // for space
            case 'z':
                return "--..";
             
            case '1':
                return ".----";
            case '2':
                return "..---";
            case '3':
                return "...--";
            case '4':
                return "....-";
            case '5':
                return ".....";
            case '6':
                return "-....";
            case '7':
                return "--...";
            case '8':
                return "---..";
            case '9':
                return "----.";
           case '0':
                return "-----";
        }
        return "";
    }
     
    static void morseCode(string s)
    {
        // character by character print
        // Morse code
        for (int i = 0;i<s.Length; i++)
            Console.Write(morseEncode(s[i]));
            Console.WriteLine();
    }
     
    // Driver code
    public static void Main ()
    {
        string s = "geeksforgeeks";
        morseCode(s);
    }
}
 
// This code is contributed by vt_m.


PHP




<?php
// php program to demonstrate
// Morse code
 
// function to encode a 
// alphabet as Morse code
function morseEncode($x)
{
 
  // refer to the Morse table
  // image attached in the article
  switch ($x) {
    case 'a':
        return ".-";
    case 'b':
        return "-...";
    case 'c':
        return "-.-.";
    case 'd':
        return "-..";
    case 'e':
        return ".";
    case 'f':
        return "..-.";
    case 'g':
        return "--.";
    case 'h':
        return "....";
    case 'i':
        return "..";
    case 'j':
        return ".---";
    case 'k':
        return "-.-";
    case 'l':
        return ".-..";
    case 'm':
        return "--";
    case 'n':
        return "-.";
    case 'o':
        return "---";
    case 'p':
        return ".--.";
    case 'q':
        return "--.-";
    case 'r':
        return ".-.";
    case 's':
        return "...";
    case 't':
        return "-";
    case 'u':
        return "..-";
    case 'v':
        return "...-";
    case 'w':
        return ".--";
    case 'x':
        return "-..-";
    case 'y':
        return "-.--";
    case '1':
     return ".----";
    case '2':
     return "..---";
    case '3':
     return "...--";
    case '4':
     return "....-";
    case '5':
     return ".....";
    case '6':
     return "-....";
    case '7':
      return "--...";
    case '8':
      return "---..";
    case '9':
     return "----.";
    case '0':
     return "-----";
 
    // for space
    case 'z':
        return "--..";
  }
}
 
function morseCode($s)
{
 
  // Character by character
  // print  Morse code
  for ($i = 0; $i<strlen($s); $i++)
      echo morseEncode($s[$i]);
  echo "\n";
}
 
// Driver code
$s = "geeksforgeeks";
morseCode($s);
 
// This code is contributed by mits
?>


Javascript




// JavaScript program to demonstrate Morse code
 
// function to encode a character as Morse code
function morseEncode(x) {
 
  // refer to the Morse table
  switch (x) {
    case 'a':
      return ".-";
    case 'b':
      return "-...";
    case 'c':
      return "-.-.";
    case 'd':
      return "-..";
    case 'e':
      return ".";
    case 'f':
      return "..-.";
    case 'g':
      return "--.";
    case 'h':
      return "....";
    case 'i':
      return "..";
    case 'j':
      return ".---";
    case 'k':
      return "-.-";
    case 'l':
      return ".-..";
    case 'm':
      return "--";
    case 'n':
      return "-.";
    case 'o':
      return "---";
    case 'p':
      return ".--.";
    case 'q':
      return "--.-";
    case 'r':
      return ".-.";
    case 's':
      return "...";
    case 't':
      return "-";
    case 'u':
      return "..-";
    case 'v':
      return "...-";
    case 'w':
      return ".--";
    case 'x':
      return "-..-";
    case 'y':
      return "-.--";
    case 'z':
      return "--..";
    case '1':
      return ".----";
    case '2':
      return "..---";
    case '3':
      return "...--";
    case '4':
      return "....-";
    case '5':
      return ".....";
    case '6':
      return "-....";
    case '7':
      return "--...";
    case '8':
      return "---..";
    case '9':
      return "----.";
    case '0':
      return "-----";
    default:
      console.error("Found invalid character: " + x);
      process.exit(0);
  }
}
 
// function to print Morse code
function morseCode(s) {
 
  // character by character print Morse code
  let result = "";
  for (let i = 0; i < s.length; i++) {
    result += morseEncode(s[i]);
  }
  console.log(result);
}
 
// Driver's code
let s = "geeksforgeeks";
morseCode(s);
// This code is contributed by rudra1807raj


Output

--...-.-.....-.---.-.--...-.-...

Time Complexity: O(n)
Auxiliary Space: O(1)



Similar Reads

Count distinct strings possible by replacing each character by its Morse code
Given an array of strings arr[], the task is to count the number of distinct strings that can be generated from the given array by replacing each character of the strings by its Morse code. Below is the Morse code of all the lowercase alphabets: Examples: Input: arr[] = {"gig", "zeg", "gin", "msn"}Output: 2Explanation: Replacing each character of t
10 min read
Check if given Morse Code is valid
Given a string S representing a Morse Code, the task is to check is the code is valid or not. A Morse code is valid if that meets all the below requirements: Any message must begin with a dot. [ '.' ]Any message must end with a dash. [ '-' ]Every dot must have a corresponding dash after it to close it. Examples: Input: S = ".--"Output: Valid Input:
4 min read
Thue-Morse sequence
Thue–Morse sequence, or Prouhet–Thue–Morse sequence, is an infinite binary sequence of 0s and 1s. The sequence is obtained by starting with 0 and successively appending the Boolean complement of the sequence obtained so far. First few steps : Start with 0 Append complement of 0, we get 01 Append complement of 01, we get 0110 Append complement of 01
6 min read
Find first K characters in Nth term of the Thue-Morse sequence
Given two integers N and K, the task is to print the first K bits of the Nth term of the Thue-Morse sequence. The Thue-Morse sequence is a binary sequence. It starts with a "0" as its first term. And then after the next term is generated by replacing "0" with "01" and "1" with "10". Examples: Input: N = 3, K = 2Output: 01Explanation: The 1st term i
6 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Convert the given RGB color code to Hex color code
Given three colors, such as R, G, and B, convert these RGB color to a hex color code. If the conversion is not possible, print -1. Examples: Input: R = 0, G = 0, B = 0 Output: #000000 Input: R = 255, G = 255, B = 256 Output: -1 Explanation: A 256 color code is not possible as only the 0-255 range is available for a color. Approach: First, check if
9 min read
Longest Monotonically Increasing Subsequence Size (N log N): Simple implementation
Given an array of random numbers, find the longest monotonically increasing subsequence (LIS) in the array. If you want to understand the O(NlogN) approach, it's explained very clearly here. In this post, a simple and time-saving implementation of O(NlogN) approach using stl is discussed. Below is the code for LIS O(NlogN): Implementation: C/C++ Co
5 min read
Binary Tree (Array implementation)
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation
6 min read
Implementation of K Nearest Neighbors
Prerequisite: K nearest neighbors Introduction Say we are given a data set of items, each having numerically valued features (like Height, Weight, Age, etc). If the count of features is n, we can represent the items as points in an n-dimensional grid. Given a new item, we can calculate the distance from the item to every other item in the set. We p
10 min read
Linked List Implementation in C#
A LinkedList is a linear data structure which stores element in the non-contiguous location. The elements in a linked list are linked with each other using pointers. Or in other words, LinkedList consists of nodes where each node contains a data field and a reference(link) to the next node in the list. In C#, LinkedList is the generic type of colle
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg