Question #21814

explain logical and syntax error with simple example program
1

Expert's answer

2013-01-11T04:28:33-0500

Logic errors

Logic errors do not allow the program to carry out the proposed action. Your code can be compiled and executed without error, but the result is unexpected and may be incorrect.

For example, the variable FirstName can be initially set to the empty string. Furthermore, the FirstName can be combined with the other variable LastName to display the full name. If you forget to set the value of FirstName, only the last name will be displayed instead of the full name, as expected.

Here's an example. I want to compare two strings a and b. If these strings are equal, program should display the value a. But there is one logical error in the program. There is semicolon after the IF operator. In this case, the program will start, but will not work correctly because the operator IF is empty. And it does not matter the condition is true or not output statement Console.WriteLine(a); will always be displayed.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Errors
{
    class Program
    {
        static void Main(string[] args)
        {
            string a, b;
            Console.WriteLine("Enter a");
            a = Console.ReadLine();
            Console.WriteLine("Enter b");
            b = Console.ReadLine();
            if (a == b) ; //Logic error
            Console.WriteLine(a);
        }
    }
}
Output
Enter a
Base
Enter b
bbbb
Base

Syntax errors

Syntax errors occur due to incorrect entry operators of the programming language. These errors are detected at compile time. Program will not work with syntax errors. Most compiler errors are caused by mistakes that you make when typing code. For example, you might misspell a keyword, leave out some necessary punctuation, or try to use an End If statement without first using an If statement. In the example there is missing a semicolon after the creation of variables a and b (string a, b). But when trying to run the program the compiler gave error information.


namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            string a, b;//Syntax error
            Console.WriteLine("Enter a");
            a = Console.ReadLine();
            Console.WriteLine("Enter b");
            b = Console.ReadLine();
            if (a == b) {
                Console.WriteLine(a);
                Console.ReadLine();
            }
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS