Advertisement
dimipan80

Exam 2. Odd / Even Sum

Jun 6th, 2014
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. namespace _2.OddAndEvenSum
  2. {
  3.     using System;
  4.  
  5.     public class TheSumsFromOddAndEvenNumbersAreEquals
  6.     {
  7.         public static void Main(string[] args)
  8.         {
  9.             checked
  10.             {                
  11.                 int numN = int.Parse(Console.ReadLine());
  12.                 long sumOdd = 0;
  13.                 long sumEven = 0;
  14.  
  15.                 // Reads all numbers in sequence from input and checks their positions odd or even:
  16.                 for (int i = 0; i < (2 * numN); i++)
  17.                 {                    
  18.                     int number = int.Parse(Console.ReadLine());
  19.                     // If number position is even, adds number to sumEven, else adds number to sumOdd:
  20.                     bool numIsOnEvenPosition = (i + 1) % 2 == 0;
  21.                     if (numIsOnEvenPosition)
  22.                     {
  23.                         sumEven += number;
  24.                     }
  25.                     else
  26.                     {
  27.                         sumOdd += number;
  28.                     }
  29.                 }
  30.  
  31.                 // Comparing two calculated sums:
  32.                 bool sumsAreEquals = sumOdd == sumEven;
  33.  
  34.                 // If two sums are not equals, will calculating their difference:
  35.                 if (!sumsAreEquals)
  36.                 {
  37.                     long diff = Math.Abs(sumOdd - sumEven);
  38.  
  39.                     // Print result:
  40.                     Console.WriteLine("No, diff={0}", diff);
  41.                 }
  42.                 else
  43.                 {
  44.                     // Print result:
  45.                     Console.WriteLine("Yes, sum={0}", sumOdd);
  46.                 }
  47.             }
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement