Program to Count the sum of numbers in a string

Program to Count the sum of numbers in a string

10 May 2023

10 May 2023

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 about Program to Count the sum of numbers in a string

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

 

Input

Hello56

Output

11

 

C Program to Count the sum of numbers in a string

#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 to Count the sum of numbers in a string

#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 Program to Count the sum of numbers in a string

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 Program to Count the sum of numbers in a string

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 !