Arithmetic Operation on Two Arrays in C# 4.5

Introduction

In this article, I describe how to perform arithmetic operations on two arrays in C# .Net. In this article however I have declared both arrays with the same length to perform the arithmetic operations on an array, like addition, subtraction, multiplication and division. I have performed all these operations in a simple and easy way. So let us understand the procedure.

  • Open Visual Studio
  • "File" -> "New" -> "Project..."
  • Choose "Template" -> "Visual C#" -> "Console application"

Perform Addition

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        public static void Main(string[] args)
        {
            const int n = 5;
            int[] a = new int[n] { 10, 20, 30, 40, 50 };
            int[] b = new int[n] { 5, 4, 3, 2, 1 };
            int[] arr = new int[n];
            for (int i = 0, j = 0; i < a.Length; i++, j++)
            {
                arr[i] = a[i] + b[j];
            }
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + " ");
            }
            Console.Read();
        }
    }
}

Output

sum-of-array.jpg

Note: In the code shown above the sum of two single-dimension arrays is produced.  Which is done simply  by the "+" operator.

Perform Subtraction

public static void Main(string[] args)
{
    const int n = 5;
    int[] a = new int[n] { 10, 20, 30, 40, 50 };
    int[] b = new int[n] { 5, 4, 3, 2, 1 };
    int[] arr = new int[n];
    for (int i = 0, j = 0; i < a.Length; i++, j++)
    {
        arr[i] = a[i] - b[j];
    }
    for (int i = 0; i < arr.Length; i++)
    {
        Console.Write(arr[i] + " ");
    }
    Console.Read();
}

Output

subtraction-of-array.jpg

Perform Multiplication

public static void Main(string[] args)
{
    const int n = 5;
    int[] a = new int[n] { 10, 20, 30, 40, 50 };
    int[] b = new int[n] { 5, 4, 3, 2, 1 };
    int[] arr = new int[n];
    for (int i = 0, j = 0; i < a.Length; i++, j++)
    {
        arr[i] = a[i] * b[j];
    }
    for (int i = 0; i < arr.Length; i++)
    {
        Console.Write(arr[i] + " ");
    }
    Console.Read();
}

Output

multiplication-of-array.jpg

Perform Division

public static void Main(string[] args)
{
    const int n = 5;
    int[] a = new int[n] { 10, 20, 30, 40, 50 };
    int[] b = new int[n] { 5, 4, 3, 2, 1 };
    int[] arr = new int[n];
    for (int i = 0, j = 0; i < a.Length; i++, j++)
    {
        arr[i] = a[i] / b[j];
    }
    for (int i = 0; i < arr.Length; i++)
    {
        Console.Write(arr[i] + " ");
    }
    Console.Read();
}

Output

division-of-array.jpg

Summary

In this article, I have described all the arithmetic operations on a single-dimension array using the same methods in a simple way. 


Similar Articles