Program to find the product of ASCII values of characters in a string
Last Updated :
08 Feb, 2024
Given a string str. The task is to find the product of ASCII values of characters in the string.
Examples:
Input: str = “IS”
Output: 6059
73 * 83 = 6059
Input: str = “GfG”
Output: 514182
The idea is to start with iterating through characters of the string and multiply their ASCII values to a variable namely, prod. Hence, return prod after the complete iteration of the string.
Note: If the string is large, the program may cause segmentation fault because of the limited size of an int.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
long long productAscii(string str)
{
long long prod = 1;
for ( int i = 0; i < str.length(); i++) {
prod *= ( int )str[i];
}
return prod;
}
int main()
{
string str = "GfG" ;
cout << productAscii(str);
return 0;
}
|
Java
class GFG
{
static long productAscii(String str)
{
long prod = 1 ;
for ( int i = 0 ; i < str.length(); i++)
{
prod *= str.charAt(i);
}
return prod;
}
public static void main(String[] args)
{
String str = "GfG" ;
System.out.println(productAscii(str));
}
}
|
Python3
def productAscii( str ):
prod = 1
for i in range ( 0 , len ( str )):
prod = prod * ord ( str [i])
return prod
if __name__ = = '__main__' :
str = "GfG"
print (productAscii( str ))
|
C#
using System;
class GFG
{
static long productAscii(String str)
{
long prod = 1;
for ( int i = 0; i < str.Length; i++)
{
prod *= str[i];
}
return prod;
}
static public void Main ()
{
String str = "GfG" ;
Console.Write(productAscii(str));
}
}
|
Javascript
<script>
function productAscii(str)
{
var prod = 1;
for (i = 0; i < str.length; i++)
{
prod *= str.charAt(i).charCodeAt(0);
}
return prod;
}
str = "GfG" ;
document.write(productAscii(str));
</script>
|
PHP
<?php
function productAscii( $str )
{
$prod = 1;
for ( $i = 0; $i < strlen ( $str ); $i ++)
{
$prod *= ord( $str [ $i ]);
}
return $prod ;
}
$str = "GfG" ;
echo productAscii( $str );
?>
|
Time Complexity: O(N), where N is the length of string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Share your thoughts in the comments
Please Login to comment...