Identify the errors in the following C# program. Write the
correct program. Explain the
errors.
class Program
{
static Main(string[] args)
{
int x = 10
Console.WriteLine("{0}" + x);
Console.ReadLine();
}
The funcrions used in the code have no issues but there are so many syntactical errors in the code provided in question.
Error 1: Main() method and class Program must have modifiers.
I have added access modifier public to main() and class Program.
Error 2: Main() method must have a return type. If it doesn't return anything then void data type should be mentioned.
I have added void return type to main() function.
Error 3: There should be semi colon after declaration of variable x.
I have added semi colon to int x=10;
Error 4:Main() method is ended properly but class has not closed in given code. A '}' (Closing curly brace) is missing at the end of class Program.
I have added a closing curly brace for class Program at the end of code.
The correct C# code is:
using System;
// making Program class available through out the code
public class Program
{
// Main method with no return type
public static void Main(string[] args)
{
//Declaring a variable x of type integer
int x = 10;
//Console.WriteLine() function is used to display output to console
Console.WriteLine("{0}" + x);
//Console.ReadLine() function is used to take user input from console
Console.ReadLine();
}
}
In the code provided in questiontwo functions Console.WriteLine() and Console.ReadLine() are used. The functions syntax and usage is correct but Console.ReadLine() has no application in the program. The read line not assigned to any variable nor the read input is used for any operation. So there is no need of Console.ReadLine() in the program. I haven't removed it in the above code because it is given in question. However if you feel the same, you can remove it.
The output of the above code is:
Hope this answer helps you.
Thank you :)
Get Answers For Free
Most questions answered within 1 hours.