Cihan Toker
Cihan Toker

Reputation: 5

How can i make a addition with the numbers from for loop in c#?

I am a newbie on c# and I am trying to make a calculator. In these codes, I am trying to take the values from input in a for loop and make an addition with them. But I couldn't do it. How can I do this?

using System;
using System.Text;

namespace cihantoker
{
    class Program1
    {
        public static void Main()
        {
            Console.WriteLine("Please enter your operation:");
            Console.WriteLine("[1]Addition");
            Console.WriteLine("[2]Subtraction");
            Console.WriteLine("[1]Multiplacition");
            Console.WriteLine("[1]Division");
            String operation = Console.ReadLine();
            //Addition Begins
            if (operation == "1")
            {

                Console.WriteLine("Please enter the count of the numbers that you want to make addition:");
                String NumberCount = Console.ReadLine();
                int Numbercount = int.Parse(NumberCount);
                for (int i = 0; i < Numbercount; i++)
                {
                    String NumberToMakeAddition = Console.ReadLine();
                    int NumberToMakeAddition2 = int.Parse(NumberToMakeAddition);

                }
            }
        }
    }
}

Upvotes: -1

Views: 914

Answers (6)

John Alexiou
John Alexiou

Reputation: 29244

This being C# and highly object-oriented you are doing yourself a disservice by treating it as script and having all your code under Main().

In C# think about a data model. How do I define objects that hold the information I want. In this example I want to make a calculator, and so I design a class that holds the calculator result, and can perform the basic operations to this result.

Data Model

public class Calculator
{
    public Calculator()
    {
        Result = 0;
    }
    /// <summary>
    /// Hold the result of the calculations
    /// </summary>
    public int Result { get; set; }
    /// <summary>
    /// Adds a number to the result
    /// </summary>
    /// <param name="x">The number.</param>
    public void Add(int x)
    {
        Result += x;
    }
    /// <summary>
    /// Subtracts a number from the result
    /// </summary>
    /// <param name="x">The number.</param>
    public void Subtract(int x)
    {
        Result -= x;
    }
    /// <summary>
    /// Multiplies the result with a number
    /// </summary>
    /// <param name="x">The number.</param>
    public void Multiply(int x)
    {
        Result *= x;
    }
    /// <summary>
    /// Divides the result with a number
    /// </summary>
    /// <param name="x">The number.</param>
    public void Divide(int x)
    {
        Result /= x;
    }
}

The above is pretty straightforward. There are four methods that modify the result, and one constructor to initialize the data.

Program

The actual program should then define and act on the data model. I chose to have an infinite loop when the user can select the next action, and can exit the loop by just pressing enter

class Program
{
    static void Main(string[] args)
    {
        // calculator object iniialized
        Calculator calculator = new Calculator();
        // Inifinte loop
        while (true)
        {
            // Report the caclulator result
            Console.WriteLine($"Result = {calculator.Result}");
            Console.WriteLine();
            Console.WriteLine("Select Operation:");
            Console.WriteLine(" [1] Addition");
            Console.WriteLine(" [2] Subtraction");
            Console.WriteLine(" [3] Multiplication");
            Console.WriteLine(" [4] Division");
            Console.WriteLine(" [ENTER] Exit");
            string input = Console.ReadLine();
            // Check if user entered a number
            if (int.TryParse(input, out int operation))
            {
                Console.WriteLine("Enter value:");
                input = Console.ReadLine();    
                // Check if user enter a value
                if (int.TryParse(input, out int x))
                {
                    // Perform the operation
                    switch (operation)
                    {
                        case 1:
                            calculator.Add(x);
                            break;
                        case 2:
                            calculator.Subtract(x);
                            break;
                        case 3:
                            calculator.Multiply(x);
                            break;
                        case 4:
                            calculator.Divide(x);
                            break;
                        default:
                            Console.WriteLine("Unknown Operation");
                            break;
                    }
                }
            }
            else // user did not enter a number
            {                    
                break;  // end the while loop
            }
        }
    }
}

Inside the loop, the last result is displayed and the user selects the operation 1-4 and types a number to use. Then use the calculator methods to do the math. For example calculator.Add(x); adds the number stored in x to the result.

Upvotes: 0

Pradeep Kumar
Pradeep Kumar

Reputation: 1491

I have made some correction in the code. you are using = operator which every time assign/store number(which need to add) to variable NumberToMakeAddition2. So output is last entered number.

For Desired output or Proper implementation of addition, Need to do three things :-

  1. Declare NumberToMakeAddition2 outside the for loop and set zero.
  2. Use += operator which add each entered/input number in NumberToMakeAddition2 if it is valid int. in background it is like this :-

NumberToMakeAddition2 += entered number;

is same as the below

NumberToMakeAddition2 = NumberToMakeAddition2 + entered number;

  1. Exception Handling :- input can be entered as string also or invalid number like special character or any string so system/code will throw exception and crash but in this requirement system/code should give proper message and ignore invalid. For this , use either int.TryParse() or Convert.ToInt32().

      1. int.TryParse() :- Do not need to use try catch but it does not handle null value and in this case(console) input cannot be null so **int.TryParse() is more appropriate**.
      2. Convert.ToInt32() :- Can handle null but need try catch to give proper message in catch and code looks clumsy.
    

using System; using System.Text;

namespace cihantoker
{
    class Program1
    {
        public static void Main()
        {
            Console.WriteLine("Please enter your operation:");
            Console.WriteLine("[1]Addition");
            Console.WriteLine("[2]Subtraction");
            Console.WriteLine("[1]Multiplacition");
            Console.WriteLine("[1]Division");
            String operation = Console.ReadLine();
            //Addition Begins
            if (operation == "1")
            {

                Console.WriteLine("Please enter the count of the numbers that you want to make addition:");
                                    
                if (int.TryParse(Console.ReadLine(), out int Numbercount))
                {
                   int NumberToMakeAddition2 = 0;
                   for (int i = 0; i < Numbercount; i++)
                   {
                     if (int.TryParse(Console.ReadLine(), out int number))
                     {
                        NumberToMakeAddition2 += number;
                     }
                     else
                     {
                        Console.WriteLine("You entered invalid number, Ignoring this and please enter valid number");
                     }
                   }
                }
                else
               {
                 Console.WriteLine("Please enter valid number");
               }
                
            }
        }
    }
}

Upvotes: 0

Chris Phillips
Chris Phillips

Reputation: 2124

Create a List like this: List<int> myList = new List<int>(), to push all your users numbers into. In your loop, when you parse the users entry, use myList.Add(NumberToMakeAddition). Then, after your loop, you can do MyList.Sum(), or you can loop through your list and add them one at a time

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29006

I will suggest you use int.TryParse() instead of int.Parse since we cannot trust the input from the console. And the only thing you need to do here is to declare one variable outside the loop and keep the sum in that variable while looping. A sample code will be like the following:

if (operation == "1")
{
    Console.WriteLine("Please enter the count of the numbers that you want to make addition:");
    int.TryParse(Console.ReadLine(), out int numberCount);
    int sumOfNumbers = 0;
    for (int i = 0; i < numberCount; i++)
    {
        if (int.TryParse(Console.ReadLine(), out int numberInput))
        {
            sumOfNumbers += numberInput;
        }
        else
        {
            Console.WriteLine("Wrong input from console, skipping the number");
        }
    }
    Console.WriteLine($"Sum of numbers :{sumOfNumbers}");
}

Upvotes: 0

Cetin Basoz
Cetin Basoz

Reputation: 23797

Cihan, First, you are assuming people would make inputs that are parseable to int. That may not be the case. Check and study int.TryParse() for that matter. Second, in your loop, you are redeclaring a NEW variable NumberToMakeAdition2 and assigning the parsed value to it. There is no addition there. What you should do is to initialize it before the loop, say:

int sum = 0;

and then in loop add to it:

sum += int.Parse(...) // remember TryParse, just keeping it simple here

Upvotes: 0

d_w_
d_w_

Reputation: 84

You aren't adding any numbers in your for loop. You are overwriting the value of NumberToMakeAddition2 with each number you parse.

Define NumberToMakeAddition2 outside the for loop and initialize it to 0. Add each number that you parse to the sum.

You have no error handling so be careful if the text entered is not an integer.

Upvotes: 2

Related Questions