C# Program to Read a String and Find the Sum of all Digits


C# is a popular object-oriented programming language used to develop Windows applications, web applications, and games. In this article, we will discuss how to write a C# program to read a string and find the sum of all digits present in the string.

Step 1: Reading the Input String

The first step in this program is to read the input string from the user. We can use the Console.ReadLine() method to read the string from the console. Here is an example −

Console.WriteLine("Enter a string:");
string inputString = Console.ReadLine();

Step 2: Finding the Sum of Digits

The next step is to find the sum of all digits present in the input string. We can use the char.IsDigit() method to check if a character is a digit or not. We can then convert the digit character to an integer using the int.Parse() method and add it to the sum.

int sum = 0;
foreach (char c in inputString) {
   if (char.IsDigit(c)) {
      sum += int.Parse(c.ToString());
   }
}

Step 3: Displaying the Result

Finally, we need to display the sum of digits to the user. We can use the Console.WriteLine() method to display the result on the console.

Console.WriteLine("The sum of digits in the string is: " + sum);

Example

Here is the complete C# program −

using System;

namespace SumOfDigits {
   class Program {
      static void Main(string[] args) {
         string inputString = ("11603529");
         int sum = 0;
         foreach (char c in inputString) {
            if (char.IsDigit(c)) {
               sum += int.Parse(c.ToString());
            }
         }
         Console.WriteLine("The sum of digits in the string is: " + sum);
      }
   }
}

Output

The sum of digits in the string is: 27

Conclusion

In this article, we learned how to write a C# program to read a string and find the sum of all digits present in the string. We used the char.IsDigit() method to check if a character is a digit, the int.Parse() method to convert the digit character to an integer, and the Console.WriteLine() method to display the result on the console. This program can be useful in various applications where we need to find the sum of digits in a given string.

Updated on: 04-May-2023

696 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements