C# C# Adding Program - Learn Syntax & More

  • Thread starter Thread starter TheDemx27
  • Start date Start date
  • Tags Tags
    Program
AI Thread Summary
The discussion revolves around improving a basic C# program designed to add two numbers and loop for repeated calculations. Key suggestions for enhancing efficiency include creating a custom input function to reduce code repetition, using more concise loop conditions, and declaring variables at their point of use. The importance of error handling is emphasized, particularly when parsing user input to ensure it is an integer, with recommendations to implement try/catch blocks to manage exceptions. Additionally, alternatives such as using a forms application instead of a console app are mentioned for improved efficiency. Overall, the focus is on code optimization, readability, and robust error management in C#.
TheDemx27
Gold Member
Messages
169
Reaction score
13
Just starting to learn C#. I just wrote this program to add two numbers and loops by looking up syntax etc. There HAS to be a more efficient way to do this.

Code:
using System;

    public class Program
    {
        static void Main()
        {
            bool repeat = true;
            while (repeat == true)
                {
                    string x;
                    string y;
                    int xint;
                    int yint;
                    string useranswer;


                    Console.WriteLine("Enter 'X':");
                    x = Console.ReadLine();
                    xint = int.Parse(x);
                    Console.Clear();

                    Console.WriteLine("Enter 'Y':");
                    y = Console.ReadLine();
                    yint = int.Parse(y);
                    Console.Clear();

                    int answer = xint + yint;

                    Console.WriteLine("{0} + {1} = {2}", x, y, answer);
                    Console.ReadLine();
                    
                    Console.WriteLine("Run again?: Y/N");
                    useranswer = Console.ReadLine();
                    Console.Clear();

                    if (useranswer == "y" || useranswer == "Y")
                    {
                        repeat = true;
                    }
                    else
                    {
                        repeat = false;
                    }
                }

            }

    }
 
Technology news on Phys.org
You could pass X and Y from the command line.
 
That's about as good as it gets, for reading input. C# doesn't have "easy to use" functions like scanf() in C or the << operator in C++. But those easy to use functions are not much use except for toy programs, because it's very hard to catch errors in the input.

You could make the code a neater by "factoring out" the repeated code and writing your own input function, something like
Code:
int getvalue(string prompt)
{
  Console.WriteLine(prompt);
  string x = Console.ReadLine();
  Console.Clear();
  return int.Parse(x);
}
...
xint = getvalue("Enter X:");
yint = getvalue("Enter Y:");
(Note, I haven't actually tested that code!)

Your test for repeating the loop is a bit longwinded. You could write
Code:
repeat = (useranswer == "y" || useranswer == "Y");
or even
Code:
repeat = (useranswer.ToLower() == "y");

You can also make your code shorter by declaring variables when you first use them, instead of by separate statements at the top of a function, as I did in
Code:
string x = Console.ReadLine();
or even
Code:
var x = Console.ReadLine();
where "var" means "the compiler can figure out what type of variable this is, so I don't really care".
 
Last edited:
  • Like
Likes 1 person
you could just use a forms app instead of a console app which is much more efficient or
Console.WriteLine("{0} + {1} = {2}", x, y, xint+yint);
maybe that will work its been awhile since I've done a console app. get visual studio it's so superior.
 
It's advisable to error check all inputs. You can do it like this. Once you get an input, check to see if it really is an integer:


try
{
Int.Parse(myinputstring);
}
catch (Exception ex)
{
Console.WriteLine("That was not an integer.");
}

And yes, it will probably be needful to use a goto statement, or else, use a flag to create a rather obscure loop, until you get all legal inputs.
 
And never, ever use Int.Parse without enclosing it in a try/catch, because otherwise your program can throw an obscure error message to the user upon bad input. When I was teaching, that would earn you an instant failing grade.
 
  • Like
Likes TheDemx27
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...

Similar threads

Replies
18
Views
2K
Replies
10
Views
2K
Replies
5
Views
3K
Replies
13
Views
5K
Replies
3
Views
3K
Replies
2
Views
2K
Replies
0
Views
323
Back
Top