Use of Parentheses
An important bit of code in C# are Parentheses. Knowing when to use them, when not use them, and using them correctly in code is an important skill that young coders must understand. So in the exerciser below we are going to try and the correct desired out put by making sure that we place parentheses where they should and leaving them out when they are not needed. Your mission to to correct the code below so that we get the results that we need. Try to fix the code before running the program.
Pre-Assignment Videos
The Code
using System;
namespace Parenthesis
{
class Program
{
static void Main(string[] args)
{
{
int v = 2;
int result = v + 1 * 2;
Console.WriteLine("result: " + result + " expected result : 6");
result = v + 1 * v + 2 * 2;
Console.WriteLine("result: " + result + " expected result : 24");
result = v - 1 * 2 + 2 * 2;
Console.WriteLine("result: " + result + " expected result : 6");
result = v + v * v + v * 2;
Console.WriteLine("result: " + result + " expected result : 32");
result = v / 2 * v + 2 * 2;
Console.WriteLine("result: " + result + " expected result : 4");
}
}
}
}
namespace Parenthesis
{
class Program
{
static void Main(string[] args)
{
{
int v = 2;
int result = v + 1 * 2;
Console.WriteLine("result: " + result + " expected result : 6");
result = v + 1 * v + 2 * 2;
Console.WriteLine("result: " + result + " expected result : 24");
result = v - 1 * 2 + 2 * 2;
Console.WriteLine("result: " + result + " expected result : 6");
result = v + v * v + v * 2;
Console.WriteLine("result: " + result + " expected result : 32");
result = v / 2 * v + 2 * 2;
Console.WriteLine("result: " + result + " expected result : 4");
}
}
}
}
The results that we are after
result: 6 expected result : 6
result: 24 expected result : 24
result: 6 expected result : 6
result: 32 expected result : 32
result: 4 expected result : 4
result: 24 expected result : 24
result: 6 expected result : 6
result: 32 expected result : 32
result: 4 expected result : 4