C# Adding Program - Learn Syntax & More

  • Context: C# 
  • Thread starter Thread starter TheDemx27
  • Start date Start date
  • Tags Tags
    Program
Click For Summary

Discussion Overview

The discussion revolves around a C# program designed to add two numbers, focusing on syntax, efficiency, and best practices in coding. Participants explore various approaches to improve the program's structure, error handling, and user input methods.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested
  • Homework-related

Main Points Raised

  • One participant suggests passing inputs X and Y from the command line as a more efficient method.
  • Another participant notes that C# lacks user-friendly input functions like those in C or C++, but proposes creating a custom input function to streamline the code.
  • There are suggestions to simplify the loop control logic by using more concise expressions for checking user input.
  • A participant recommends using a forms application instead of a console application for improved efficiency.
  • One participant emphasizes the importance of error checking for user inputs and provides a method to validate integer inputs using try/catch blocks.
  • Another participant warns against using Int.Parse without error handling, citing potential issues with obscure error messages for users.

Areas of Agreement / Disagreement

Participants express various viewpoints on improving the program, with no consensus on a single best approach. There are differing opinions on the necessity and method of error handling, as well as the choice between console and forms applications.

Contextual Notes

Participants highlight limitations in the current program's error handling and input methods, but do not resolve these issues. The discussion reflects a range of coding practices and preferences without settling on definitive solutions.

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   Reactions: 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   Reactions: TheDemx27

Similar threads

  • · Replies 18 ·
Replies
18
Views
2K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 13 ·
Replies
13
Views
5K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K