Name: Section:-CC-a__ Given a character array A. Write a C++ program that comput
ID: 3599131 • Letter: N
Question
Name: Section:-CC-a__ Given a character array A. Write a C++ program that computes and outputs the n umber of letters in A and frequency (number of occurrence) of the letters in the array. Sample Format A character string "My string is not very very long" Sample Output Number of letters: 31 Frequency a: o b: o C: o d: o e: 2 f: o : 2 : o : 0 k: o n: 3 o: 2 p: o q: O r: 3 s: 2 t: 2 u: o V: 2 W: O x: o y: 3 Z: o Instructions Write and run a C++ program to solve the problem using the sample data given. Prou back of this sheet: (1) the C++ program, and (2) the output obtained. DemonstraExplanation / Answer
#include<iostream>
#include<cstring>
using namespace std;
int main(){
//initial strign
char A[] = "My string is not very very long";
//Frequency counter array with initial values of zero
int freq[27]={0};
cout << "Number of letters:" << strlen(A) << endl;
//for each char in string
for(int i=0;i<strlen(A);i++){
//convert char to lower case
char l = tolower(A[i]);
//get ascii value of character and reduce it by 97 as 'a' value is 97
// which make the starting index of array as zero.
int ind = int(l) - 97;
//update Frequency only if it is valid character.
if(ind>-1 && ind<27){
freq[ind]++;
}
}
cout << "Frequency:" << endl;
for(int i=0;i<26;i++){
//get the character by adding 97 to i index. i.e. 0+97 gives alpha 'a'.
cout<< char(i+97) << ":" << freq[i] << endl;
}
}
/*
sample output
Number of letters:31
Frequency:
a:0
b:0
c:0
d:0
e:2
f:0
g:2
h:0
i:2
j:0
k:0
l:1
m:1
n:3
o:2
p:0
q:0
r:3
s:2
t:2
u:0
v:2
w:0
x:0
y:3
z:0
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.