taji01
taji01

Reputation: 2615

Get the total of a number in a loop in C#

My program generates 2 random numbers from 1 - 14.
The program loops ten times to check if numb1 matches numb2, and if it does, the program displays the number matched.

How can I get the total of numb1, for example if the out put was:

Output:

i value: 2 numb1 value: 1

i value: 3 numb1 value: 2

i value: 10 numb1 value: 5

"The total of numb1 is: 8" <-- how can i get the total?

static void Main(string[] args)
    {


        for (int i = 1; i < 11; i++)
        {
            int numb1 = anyNumber();
            int numb2 = anyNumber();

            if (numb1 == numb2)
            {
                Console.WriteLine("i value:      " + i);
                Console.WriteLine("numb1 value:  " + numb1);
                Console.WriteLine();
            }

        }
    }


    static Random randNumb = new Random();
    static int anyNumber()
    {
        return randNumb.Next(1, 15);
    }

Upvotes: 0

Views: 1119

Answers (1)

Slashy
Slashy

Reputation: 1881

You might want to add a variable which will summ numb1 values.

static void Main(string[] args)
{

     int sum=0;
    for (int i = 1; i < 11; i++)
    {
        int numb1 = anyNumber();
        int numb2 = anyNumber();


        if (numb1 == numb2)
        {
            sum+=numb1;
            Console.WriteLine("i value:      " + i);
            Console.WriteLine("numb1 value:  " + numb1);
            Console.WriteLine();
        }
         Console.WriteLine("total is "+sum);
    }
}

Upvotes: 3

Related Questions