Home > Enterprise >  Sum of the first 100 even and odd number?
Sum of the first 100 even and odd number?

Time:10-18

I need some help getting this code to work. I need the code to calculate the first 100 even and odd numbers. The code below shows the even portion, but I assume they both will work the same way, just with different numbers. I know that the first 100 even numbers are 2 to 200 or 0 to 200?, and the first 100 odd numbers are 1 to 199. (I also need to use while loops, would I use a separate while loop to determine how the code calculate the sum?)

here is the code.

    Dim sum, count As Integer 'the sum and count are changing and they must be a whole number. 
    Const num As Integer = 2
    'now we must deveolp a while loop/equation that adds every number lower or equal to 100 together.


    While count Mod 2 <= 200 'while the count is smaller or equal to 100,
        count =
        sum  = count 'The sum will be add or equaled to the count
        count  = 1 'The count will be added to equaled to 1 

    End While

    Console.WriteLine("The Sum of the first 100 even numbers is: {0}!", sum) 'This is the text the user sees, which tells them that the sum of the first 100 numbers will be 5050.

    Console.ReadLine()
End Sub

As usual the math portion is giving me trouble. I feel like I have the right idea, but I cant execute it properly.

CodePudding user response:

You can calculate both values at the same time in a single loop:

Dim maxCount = 100
Dim sumEven, sumOdd, countEven, countOdd As Integer
Dim number = 0  

While countEven < maxCount OrElse countOdd < maxCount
    If number Mod 2 = 0 Then
        countEven  = 1
        sumEven  = number
    Else
        countOdd  = 1
        sumOdd  = number
    End If
    number  = 1
End While

So the While loops collects even and odds until it has found 100. The If checks if the number can be divided through 2. The = number calculates the sum of all even and odd and the = 1 simply counts them.

CodePudding user response:

    Dim sumEven, sumOdd As Integer
    Dim even = 2
    Dim odd = 1

    While even <= 200 AndAlso odd <= 200

        sumEven  = even
        sumOdd  = odd

        even  = 2
        odd  = 2

    End While

    Console.WriteLine("The Sum of the first 100 even numbers is: {0}!", sumEven)
    Console.WriteLine("The Sum of the first 100 odd numbers is: {0}!", sumOdd)
  • Related