Pascal To C# Translator - C# Programming Exercise

This C# exercise involves creating a basic Pascal to C# translator. The program should accept code written in Pascal and convert it to an equivalent C# code. The exercise starts by reading a text file containing Pascal code, with the file name provided by the user either via the command line or interactively. The contents of the file are then dumped into another text file with the same structure, but with a ".cs" extension instead of ".pas".

Next, the translator must perform several key transformations to convert the Pascal code to C#. Specific words and structures need to be replaced, such as "WriteLn" with "Console.WriteLine", the operator " = " with "==", and " := " with "=", among others. Additionally, "begin" should be replaced with "{", and "end;" and "end." should be replaced with "}", to follow the correct C# syntax.

In this exercise, other Pascal structures like "program x;" should be replaced with "class x {" followed by "Main", and "readLn(x)" with "x = Convert.ToInt32(Console.ReadLine())". Also, the "var" keyword must be eliminated, and type declarations like "x: integer" should be converted to "int x". Finally, the "for" loop must be properly formatted. The main challenge of this exercise is to create a translator that can generate compilable C# code from Pascal code.

 Category

File Management

 Exercise

Pascal To C# Translator

 Objective

Create a basic Pascal to C# translator. It will accept program such as:

example program;

var
i: integer;
max: integer;

begin
writeLn("How many times?");
readLn(max);
for i := 1 to max do
writeLn("Hola");
end.

The steps you must follow are:
Read from beginning to end a text file, whose name will be entered by the user in command line or in an interactive way: up to 2 points.

Dump the contents to another text file, whose name will be the same, but with ".cs" extension instead of ".pas": up to 4 points.

Replace "WriteLn" with "Console.WriteLine", " = "with "==", " := " with "=", simple quotes with double quotes, "begin" with "{" and "end;", "end.", "end" (in that order) with "}", : up to 6 points.

Replace "program x;" with "class x {" followed with "Main", Replace "readln(x)" with "x=Convert.ToInt32(Console.RadLine())" ("x" must be any other identifier): up to 8 points.

Eliminate "var" and replace "x: integer" with "int x" (but "x" must be any other identifier): up to 9 points. Give a proper format to "for": up to 10 points.

Create a compilable C# source from the previous Pascal source and similar ones: up to 11 points.

 Write Your C# Exercise

// Importing necessary namespaces for basic operations
using System; // For basic Console operations
using System.IO; // For file handling
using System.Text.RegularExpressions; // For using regular expressions

public class PascalToCSharpTranslator
{
    // Method to translate Pascal code to C# code
    public static string TranslatePascalToCSharp(string pascalCode)
    {
        // Replacing "WriteLn" with "Console.WriteLine"
        pascalCode = pascalCode.Replace("WriteLn", "Console.WriteLine");

        // Replacing " = " with "=="
        pascalCode = pascalCode.Replace(" = ", "==");

        // Replacing " := " with "="
        pascalCode = pascalCode.Replace(" := ", "=");

        // Replacing single quotes with double quotes
        pascalCode = pascalCode.Replace("'", "\"");

        // Replacing "begin" with "{"
        pascalCode = pascalCode.Replace("begin", "{");

        // Replacing "end;" and "end." with "}"
        pascalCode = pascalCode.Replace("end;", "}");
        pascalCode = pascalCode.Replace("end.", "}");

        // Replacing "program x;" with "class x {"
        pascalCode = Regex.Replace(pascalCode, @"program\s+(\w+);", "class $1 {");

        // Replacing "readln(x)" with "x = Convert.ToInt32(Console.ReadLine())"
        pascalCode = Regex.Replace(pascalCode, @"readln\((\w+)\)", "$1 = Convert.ToInt32(Console.ReadLine())");

        // Replacing "var" and "x: integer" with "int x"
        pascalCode = Regex.Replace(pascalCode, @"var", "");
        pascalCode = Regex.Replace(pascalCode, @"(\w+):\s*integer", "int $1");

        // Formatting "for" loops to C# style
        pascalCode = Regex.Replace(pascalCode, @"for\s+(\w+)\s*:=\s*(\d+)\s+to\s*(\d+)\s*do", "for(int $1 = $2; $1 <= $3; $1++)");

        return pascalCode;
    }

    // Method to process the Pascal code file and generate the C# code file
    public static void ProcessFile(string inputFileName)
    {
        // Reading the Pascal code from the input file
        string pascalCode = File.ReadAllText(inputFileName);

        // Translating Pascal code to C#
        string cSharpCode = TranslatePascalToCSharp(pascalCode);

        // Creating the output file name by changing the extension from .pas to .cs
        string outputFileName = Path.ChangeExtension(inputFileName, ".cs");

        // Writing the translated C# code to the output file
        File.WriteAllText(outputFileName, cSharpCode);

        Console.WriteLine($"Translation complete. The C# code has been saved to {outputFileName}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Asking user for the Pascal file name
        Console.Write("Enter the Pascal file name (with .pas extension): ");
        string inputFileName = Console.ReadLine();

        // Calling the ProcessFile method to handle the translation
        PascalToCSharpTranslator.ProcessFile(inputFileName);
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Convert a text file to uppercase

    This C# exercise involves creating a program that reads a text file and dumps its content into another file, making a transformation in the process. The transformatio...

  •  Convert any file to uppercase

    This C# exercise involves creating a program that reads a file of any kind and dumps its content into another file, applying a transformation in the process. The tran...

  •  File inverter

    This C# exercise involves creating a program to "invert" a file. The program must take an original file and create a new one with the same name but with the ".inv" ex...

  •  File encrypter

    This C# exercise involves creating a program to encrypt a text file into another text file. The program should be able to read the content of a text file, apply an en...

  •  Count words

    This C# exercise involves creating a program to count the number of words stored in a text file. The program should read the content of a text file, process it, and c...

  •  BMP width and height, BinaryReader

    This C# exercise involves creating a program to display the width and height of a BMP file using a BinaryReader. The program should read the BMP file header an...