Open In App

Types of Issues and Errors in Programming/Coding

Last Updated : 21 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Where there is code, there will be errors

If you have ever been into programming/coding, you must have definitely come across some errors. It is very important for every programmer to be aware of such errors that occur while coding.

In this post, we have curated the most common types of programming errors and how you can avoid them.

1. Syntax errors: 

These are the type of errors that occur when code violates the rules of the programming language such as missing semicolons, brackets, or wrong indentation of the code,

Example:

Write a function int fib(int n) that returns Fn. For example, if n = 0, then fib() should return 0. If n = 1, then it should return 1. For n > 1, it should return Fn-1 + Fn-2.

For n = 9
Output: 34

Wrong Implementation of Code for the above Problem Statement:

C++
// Fibonacci Series using Recursion
#include <bits/stdc++.h>
using namespace std;

int fib(int n)
{
    if (n <= 1)
        return n
    return fib(n - 1) + fib(n - 2);


int main()
{
    int n = 9;
    cout << fib(n);
    getchar();
    return 0;
}
Java
import java.util.*;

public class Main {
    static int fib(int n) {
        if (n <= 1)
            return n  // Intentional error: missing semicolon
        return fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] args) {
        int n = 9;
        System.out.println(fib(n));
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
    }
}
//this code is contributed by Monu.
Python
# Fibonacci Series using Recursion
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

# Driver program
if __name__ == "__main__":
    n = 9
    print(fib(n))
JavaScript
// Function to calculate Fibonacci sequence using memoization
function fib(n, memo = {}) {
    // If the Fibonacci number is already calculated, return it from memo
    if (n in memo) {
        return memo[n];
    }
    // Base cases: if n is 0 or 1, return n
    if (n <= 1) {
        return n;
    }
    // Calculate Fibonacci number for n recursively and store it in memo
    memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
    return memo[n];
}

// Main function
function main() {
    var n = 9; // Input value for Fibonacci sequence
    console.log(fib(n)); // Output the result of Fibonacci sequence
}

// Call the main function
main();

If we review the above code, we can see that a semicolon (;) is missing after the return statement in the ,fib() function and the closing bracket is also missing for the fib() function. 

Below is the screenshot of the error.

2. Logical errors:

These are the type of errors that occurs when incorrect logic is implemented in the code and the code produces unexpected output.

Example:

Find GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers that is the largest number that divides both of them.

For finding the GCD of two numbers we will first find the minimum of the two numbers and then find the highest common factor of that minimum which is also the factor of the other number.

Wrong Implementation of Code for the above Problem Statement:

C++
// C++ program to find GCD of two numbers
#include <iostream>
using namespace std;
// Function to return gcd of a and b
int gcd(int a, int b)
{
    int result = min(a, b); // Find Minimum of a and b
    while (result > 0) {
        if (a % result != 0 && b % result != 0) {
            break;
        }
        result--;
    }
    return result; // return gcd of a and b
}

// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    cout << "GCD of " << a << " and " << b << " is "
        << gcd(a, b);
    return 0;
}
Java
public class Main {
    // Function to return gcd of a and b
    static int gcd(int a, int b) {
        int result = Math.min(a, b); // Find Minimum of a and b
        while (result > 0) {
            if (a % result != 0 || b % result != 0) { // Use || (logical OR) instead of && (logical AND)
                break;
            }
            result--;
        }
        return result; // return gcd of a and b
    }

    // Driver program to test above function
    public static void main(String[] args) {
        int a = 98, b = 56;
        System.out.println("GCD of " + a + " and " + b + " is " + gcd(a, b));
    }
}
Python3
def gcd(a, b):
    result = min(a, b)  # Find Minimum of a and b
    while result > 0:
        if a % result != 0 or b % result != 0:
            break
        result -= 1
    return result  # return gcd of a and b

# Driver program to test above function
if __name__ == "__main__":
    a, b = 98, 56
    print(f"GCD of {a} and {b} is {gcd(a, b)}")
C#
using System;

public class Program
{
    // Function to return gcd of a and b
    public static int Gcd(int a, int b)
    {
        int result = Math.Min(a, b); // Find Minimum of a and b
        while (result > 0)
        {
            if (a % result != 0 && b % result != 0)
            {
                break;
            }
            result--;
        }
        return result; // return gcd of a and b
    }

    // Driver program to test above function
    public static void Main(string[] args)
    {
        int a = 98, b = 56;
        Console.WriteLine($"GCD of {a} and {b} is {Gcd(a, b)}");
    }
}
Javascript
// Function to return gcd of a and b
function gcd(a, b) {
    let result = Math.min(a, b); // Find Minimum of a and b
    while (result > 0) {
        if (a % result !== 0 || b % result !== 0) {
            break;
        }
        result--;
    }
    return result; // return gcd of a and b
}

// Driver program to test above function
function main() {
    let a = 98, b = 56;
    console.log(`GCD of ${a} and ${b} is ${gcd(a, b)}`);
}

// Calling the main function
main();
//This code is contributed by Utkarsh.

Output
GCD of 98 and 56 is 55


Expected Output: GCD of 98 and 56 is 14

In the above code, the Output produced by the code and the expected output are different. Hence, we can say that there is a logical error in the above code. If we review the above code, we can see the condition, if (a % result != 0 && b % result != 0) is not correct. It should be if (a % result == 0 && b % result == 0).

3. Runtime errors:

These are the errors caused by unexpected condition encountered while executing the code that prevents the code to compile. These can be null pointer references, array out-of-bound errors, etc.

Example:

C++
// C++ program to illustrate
// runtime error

#include <iostream>
using namespace std;

// Driver Code
int main()
{

    int a = 5;

    // Division by Zero
    cout << a / 0;
    return 0;
}
Java
// Java program to illustrate
// runtime error

public class Main {
    // Driver Code
    public static void main(String[] args) {

        int a = 5;

        // Division by Zero
        System.out.println(a / 0);
    }
}
Python3
# code
print("GFG")
# Python program to illustrate
# runtime error

# Driver Code
def main():
    a = 5

    # Division by Zero
    print(a / 0)

if __name__ == "__main__":
    main()
JavaScript
// JavaScript code to illustrate
// division by zero

// Driver Code
function main() {
    let a = 5;

    // Division by Zero
    console.log(a / 0);
}

main();

Below is the error produced by the above code:

4. Time Limit exceeded error:

Time Limit Exceeded error is caused when a code takes too long to execute and execution time exceeds the given time in any coding contest. TLE comes because the online judge has some restrictions that the code for the given problem must be executed within the given time limit.

How to Overcome Time Limit Exceed(TLE)?

Example:

Given two arrays, arr1 and arr2 of equal length N, the task is to find if the given arrays are equal or not. Two arrays are said to be equal if: both of them contain the same set of elements, arrangements (or permutations) of elements might/might not be the same. If there are repetitions, then counts of repeated elements must also be the same for two arrays to be equal.

Expected Time Complexity: O(N)

One possible approach can be to Sort both arrays, then linearly compare the elements of both arrays. If all are equal then return true, else return false. The time complexity for this approach will be O(N*log(N)). But the expected time complexity is O(N), so this code will give Time Limit Exceeded error. In online judges, we need to write code that executes within a given time limit. Hence, we need to optimize the approach.

Another possible approach can be to store the count of all elements of arr1[] in a hash table. Then traverse arr2[] and check if the count of every element in arr2[] matches with the count of elements of arr1[]. The time complexity for this approach will be O(N). Hence code for this approach will not give a time limit error and will get submitted successfully.

Below is the code for the above approach:

C++
// C++ program for the above approach

#include <bits/stdc++.h>
using namespace std;

// Returns true if arr1[0..N-1] and arr2[0..M-1]
// contain same elements.
bool areEqual(int arr1[], int arr2[], int N, int M)
{
    // If lengths of arrays are not equal
    if (N != M)
        return false;

    // Store arr1[] elements and their counts in
    // hash map
    unordered_map<int, int> mp;
    for (int i = 0; i < N; i++)
        mp[arr1[i]]++;

    // Traverse arr2[] elements and check if all
    // elements of arr2[] are present same number
    // of times or not.
    for (int i = 0; i < N; i++) {
        // If there is an element in arr2[], but
        // not in arr1[]
        if (mp.find(arr2[i]) == mp.end())
            return false;

        // If an element of arr2[] appears more
        // times than it appears in arr1[]
        if (mp[arr2[i]] == 0)
            return false;
        // decrease the count of arr2 elements in the
        // unordered map
        mp[arr2[i]]--;
    }

    return true;
}

// Driver's Code
int main()
{
    int arr1[] = { 3, 5, 2, 5, 2 };
    int arr2[] = { 2, 3, 5, 5, 2 };
    int N = sizeof(arr1) / sizeof(int);
    int M = sizeof(arr2) / sizeof(int);

    // Function call
    if (areEqual(arr1, arr2, N, M))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}
Java
import java.util.HashMap;

public class Main {
    // Returns true if arr1[0..N-1] and arr2[0..M-1]
    // contain the same elements.
    static boolean areEqual(int arr1[], int arr2[], int N, int M) {
        // If lengths of arrays are not equal
        if (N != M)
            return false;

        // Store arr1[] elements and their counts in a HashMap
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < N; i++)
            map.put(arr1[i], map.getOrDefault(arr1[i], 0) + 1);

        // Traverse arr2[] elements and check if all
        // elements of arr2[] are present the same number
        // of times or not.
        for (int i = 0; i < N; i++) {
            // If there is an element in arr2[], but
            // not in arr1[]
            if (!map.containsKey(arr2[i]))
                return false;

            // If an element of arr2[] appears more
            // times than it appears in arr1[]
            if (map.get(arr2[i]) == 0)
                return false;

            // Decrease the count of arr2 elements in the HashMap
            map.put(arr2[i], map.get(arr2[i]) - 1);
        }

        return true;
    }

    // Driver's Code
    public static void main(String[] args) {
        int arr1[] = { 3, 5, 2, 5, 2 };
        int arr2[] = { 2, 3, 5, 5, 2 };
        int N = arr1.length;
        int M = arr2.length;

        // Function call
        if (areEqual(arr1, arr2, N, M))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python3
# Function to check if arr1 and arr2 contain the same elements
def areEqual(arr1, arr2):
    # If lengths of arrays are not equal
    if len(arr1) != len(arr2):
        return False

    # Dictionary to store arr1 elements and their counts
    mp = {}
    for num in arr1:
        mp[num] = mp.get(num, 0) + 1

    # Traverse arr2 and check if all elements are present in arr1
    # with the same counts
    for num in arr2:
        # If an element in arr2 is not in arr1
        if num not in mp:
            return False
        # If an element appears more times in arr2 than in arr1
        if mp[num] == 0:
            return False
        # Decrease the count of arr2 elements in the dictionary
        mp[num] -= 1

    return True

# Driver code
if __name__ == "__main__":
    arr1 = [3, 5, 2, 5, 2]
    arr2 = [2, 3, 5, 5, 2]

    # Function call
    if areEqual(arr1, arr2):
        print("Yes")
    else:
        print("No")
C#
using System;
using System.Collections.Generic;

public class Program
{
    // Function to check if arr1 and arr2 contain the same elements
    static bool AreEqual(int[] arr1, int[] arr2)
    {
        // If lengths of arrays are not equal
        if (arr1.Length != arr2.Length)
            return false;

        // Dictionary to store arr1 elements and their counts
        Dictionary<int, int> mp = new Dictionary<int, int>();
        foreach (int num in arr1)
        {
            if (mp.ContainsKey(num))
                mp[num]++;
            else
                mp[num] = 1;
        }

        // Traverse arr2 and check if all elements are present in arr1
        // with the same counts
        foreach (int num in arr2)
        {
            // If an element in arr2 is not in arr1
            if (!mp.ContainsKey(num))
                return false;
            // If an element appears more times in arr2 than in arr1
            if (mp[num] == 0)
                return false;
            // Decrease the count of arr2 elements in the dictionary
            mp[num]--;
        }

        return true;
    }

    // Entry point of the program
    public static void Main(string[] args)
    {
        int[] arr1 = { 3, 5, 2, 5, 2 };
        int[] arr2 = { 2, 3, 5, 5, 2 };

        // Function call
        if (AreEqual(arr1, arr2))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
Javascript
function areEqual(arr1, arr2) {
    // If lengths of arrays are not equal
    if (arr1.length !== arr2.length)
        return false;

    // Store arr1 elements and their counts in a Map
    let map = new Map();
    for (let i = 0; i < arr1.length; i++)
        map.set(arr1[i], (map.get(arr1[i]) || 0) + 1);

    // Traverse arr2 elements and check if all
    // elements of arr2 are present the same number
    // of times or not.
    for (let i = 0; i < arr2.length; i++) {
        // If there is an element in arr2, but
        // not in arr1
        if (!map.has(arr2[i]))
            return false;

        // If an element of arr2 appears more
        // times than it appears in arr1
        if (map.get(arr2[i]) === 0)
            return false;

        // Decrease the count of arr2 elements in the Map
        map.set(arr2[i], map.get(arr2[i]) - 1);
    }

    return true;
}

// Driver's Code
let arr1 = [3, 5, 2, 5, 2];
let arr2 = [2, 3, 5, 5, 2];

// Function call
if (areEqual(arr1, arr2))
    console.log("Yes");
else
    console.log("No");

Output
Yes


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads