Reputation: 27
In this piece of code if i run a for loop to know elements stored inside the array c
I get output as 1 1 1 0 0 0 0 1 0 0
.
The input is abc
. Why it does it give 1 1 1
instead of 0 1 2 0 0 0 0 0 0
?
int c[26]={};
cin >> s;
len = s.length();
for(int i = 0 ; i < len ; i++ ){
c[s[i] - 'a'] ++ ;
}
Upvotes: 0
Views: 70
Reputation: 589
s[i] - 'a'
That is returning 0, 1 and 2. But
c[s[i] - 'a'] ++ ;
Is always increasing 1 each occurrence of C[] which at the beginning was initializing with all zeros. For that reason you get all 1s in your output.
Try
c[s[i] - 'a'] = s[i] - 'a'
Upvotes: 0
Reputation: 3779
Your c
array is a histogram of the characters read. Your output is saying you read 1 'a', 1 'b' and 1 'c'. Try c[s[i] - 'a'] = s[i] - 'a';
Upvotes: 1
Reputation: 76240
Your code is basically counting the number of letters in a string. The count is stored in the array c
where the index represents the letter index in the alphabet. So a
is 0
, b
is 1
, c
is 2
and so on.
So for abc
the correct input is indeed 1 1 1
, due to the fact that there's 1 a
, 1 b
and 1 c
. Your 0 1 2
would represent a string with 1 b
and 2 c
s.
Upvotes: 0