Advertisement
kyamaliev

SumOf5Numbers

Nov 25th, 2015
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.25 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace SumOfFiveNumbers
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.  
  14.     //write a program to add a sequence of numbers, inputted on one line, separated by space.
  15.             string input = Console.ReadLine();
  16.             double sum = 0.0; // this will keep our sum
  17.  
  18.             //loop over the input string, a string is an array of chars, and as an array we can iterate over it
  19.             for (int i = 0; i < input.Length; i++)
  20.             {
  21.                 //string to parse is declared in the for loop, so at every iteration it is empty again.
  22.                 string stringToParse = string.Empty;
  23.                 //if we are currently at a digit, we start going forward and collect all the digits
  24.                 if (char.IsDigit(input[i]) || input[i] == '-')
  25.                 {
  26.                     //if the char is not whitespace, it is part of a number (digit or decimal point)
  27.                     while (!char.IsWhiteSpace(input[i]))
  28.                     {
  29.                         //append the current char to the string
  30.                         stringToParse += input[i];
  31.                         //increment i, so after we exit from the while loop, the for loop continues at the same position
  32.                         //the idea is that we don't collect the same digits again and again
  33.                         //we have to test if we are at the end of the string! (indices are zero based)
  34.                         if (i == input.Length - 1)
  35.                         {
  36.                             break;
  37.                         }
  38.  
  39.                         i++;
  40.                     }
  41.  
  42.                     //if the code enters the while loop and reaches this line, we now have to parse the string to a number and add it to a sum
  43.                     // we can make sure by testing if stringToParse is not empty
  44.                     if (stringToParse != string.Empty)
  45.                     {
  46.                         double number = double.Parse(stringToParse);
  47.                         sum += number;
  48.                     }
  49.                 }
  50.             }
  51.  
  52.             Console.WriteLine(sum);
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement