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

27 June 2022

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


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

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;

}

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();

                             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))


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023
Related Articles

Ask Us Anything !