Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace SumOfFiveNumbers
- {
- class Program
- {
- static void Main(string[] args)
- {
- //write a program to add a sequence of numbers, inputted on one line, separated by space.
- string input = Console.ReadLine();
- double sum = 0.0; // this will keep our sum
- //loop over the input string, a string is an array of chars, and as an array we can iterate over it
- for (int i = 0; i < input.Length; i++)
- {
- //string to parse is declared in the for loop, so at every iteration it is empty again.
- string stringToParse = string.Empty;
- //if we are currently at a digit, we start going forward and collect all the digits
- if (char.IsDigit(input[i]) || input[i] == '-')
- {
- //if the char is not whitespace, it is part of a number (digit or decimal point)
- while (!char.IsWhiteSpace(input[i]))
- {
- //append the current char to the string
- stringToParse += input[i];
- //increment i, so after we exit from the while loop, the for loop continues at the same position
- //the idea is that we don't collect the same digits again and again
- //we have to test if we are at the end of the string! (indices are zero based)
- if (i == input.Length - 1)
- {
- break;
- }
- i++;
- }
- //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
- // we can make sure by testing if stringToParse is not empty
- if (stringToParse != string.Empty)
- {
- double number = double.Parse(stringToParse);
- sum += number;
- }
- }
- }
- Console.WriteLine(sum);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement