0% found this document useful (0 votes)
30 views3 pages

Day 35 Coding Solutions

The document provides code snippets in C, C++, Java, and Python to count the sum of all numeric digits in a given string. It explains that the program takes a string as input from the user, iterates through each character, checks if it is a number, and adds it to the running sum. It then prints out the final sum. Sample input and output is given to demonstrate the expected behavior.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views3 pages

Day 35 Coding Solutions

The document provides code snippets in C, C++, Java, and Python to count the sum of all numeric digits in a given string. It explains that the program takes a string as input from the user, iterates through each character, checks if it is a number, and adds it to the running sum. It then prints out the final sum. Sample input and output is given to demonstrate the expected behavior.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Talent Battle 100 Days Coding Series

Write a Program to Count the sum of numbers in a string


Description

Get a string from the user and find the sum of numbers in the string.

Input

Hello56

Output

11

C Program

#include<stdio.h>

#include<string.h>

int main()

char str[100];

int i,sum = 0;

printf("Enter a string: ");

scanf("%s",str);

for (i= 0; str[i] != '\0'; i++)

if ((str[i] >= '0') && (str[i] <= '9'))

sum += (str[i] - '0');

printf("Sum is: %d", sum);

return 0;

}
Talent Battle 100 Days Coding Series

C++ Program

#include<iostream>

#include<string.h>

using namespace std;

int main()

char str[100];

int i,sum = 0;

cout<<"Enter a string: ";

cin>>str;

for (i= 0; str[i] != '\0'; i++)

if ((str[i] >= '0') && (str[i] <= '9'))

sum += (str[i] - '0');

cout<<"Sum is: "<<sum;

return 0;

Java

import java.util.Scanner;

public class Main

public static void main(String[] args) {

Scanner sc =new Scanner(System.in);

System.out.print("Enter a string: ");

String str1 = sc.nextLine();


Talent Battle 100 Days Coding Series

int sum=0;

for (int i = 0; i < str1.length(); i++) {

if(Character.isDigit(str1.charAt(i)))

sum=sum+Character.getNumericValue(str1.charAt(i));

System.out.println("Sum is: "+sum);

Python

Str1 = input('Enter a string:')

Sum = 0

for i in Str1:

if ord(i) >= 48 and ord(i) <= 57:

Sum = Sum + int(i)

print('Sum is: ' + str(Sum))

You might also like