Write a program in Java to accept a set of any 10 characters. Calculate
and print the sum of ASCII codes of the characters.
Answers
Answer:
We are given a sentence of english language(can also contain digits), we need to compute and print the sum of ASCII values of characters of each word in that sentence.
Examples:
Input : GeeksforGeeks, a computer science portal for geeks
Output : Sentence representation as sum of ASCII each character in a word:
1361 97 879 730 658 327 527
Total sum -> 4579
Here, [GeeksforGeeks, ] -> 1361, [a] -> 97, [computer] -> 879, [science] -> 730
[portal] -> 658, [for] -> 327, [geeks] -> 527
Input : I am a geek
Output : Sum of ASCII values:
73 206 97 412
Total sum -> 788
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Approach:
Iterate over the length of the string and keep converting the characters to their ASCII
Keep adding up the values till the end of sentence.
When we come across a space character, we store the sum calculated for that word and set the sum equal to zero again.
Later, we print elements
// C++ implementation for representing
// each word in a sentence as sum of
// ASCII values of each word
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Function to compute the sum of ASCII values of each
// word separated by a space and return the total sum
// of the ASCII values, excluding the space.
long long int ASCIIWordSum(string str,
vector<long long int>& sumArr)
{
int l = str.length();
int sum = 0;
long long int bigSum = 0L;
for (int i = 0; i < l; i++) {
// Separate