- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.