Josh Engelsma
Josh Engelsma

Reputation: 2646

Meaning of a C statement involving char arrays

I am working on an algorithm for a project and I ran across some code that I think may be helpful. However, as I try to read the code, I am having some difficulty understanding a statement in the code. Here is the code.

int firstWord[MAX_WORD_SIZE] = {0}, c = 0;

while (word1[c] != '\0') //word1 is char[] sent as a parameter
{
  firstWord[word1[c]-'a']++;
  c++;
}

I understand (I hope correctly) that the first line is setting up an integer array of my max size, and initializing elements to zero along with making the initial counter value "c" zero.

I understand that the while loop is looping through all of the characters of the word1[] array until it hits the final char '\0'

I am confused on the line firstWord[word1[c]-'a']++; word1[c] should give a char, so what does doing the -'a' do? Does this cast the char to an integer which would allow you to access an element of the firstWord[] array and increment using ++? If so, which element or integer is given by word1[c]-'a'

Upvotes: 1

Views: 125

Answers (3)

Soumen
Soumen

Reputation: 1078

word1[c]-'a' means the difference between the character in cth position of word1 and the integer value of 'a'. Basically it calculates the number of occurences of letters in a word.

So if word1[c] is 'b', then value of word1[c]-'a' will be ('b' - 'a') = 1. So the number of occurences of 'b' in the word will be incremented by 1.

Upvotes: 2

michaeltang
michaeltang

Reputation: 2898

it seems this code is doing a letter count

1 so what does doing the -'a' do?

if word1[c] is 'a' then word1[c]-'a' is 0

2 . Does this cast the char to an integer which would allow you to access an element of the firstWord[] array and increment using ++?

yes, it is integer promotion

3 .If so, which element or integer is given by word1[c]-'a'

if word1[c] is 'a' then word1[c]-'a' is 0

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122423

This is a program that counts the number of letters a to z from a word. The key point here is, 'a' - 'a' has a value of 0, and 'b' - 'a' has a value of 1, etc.

For instance, if word1[c] is the letter 'd', then 'd' - 'a' is 3, so it would increment firstWord[3]. When the word has been iterated character by character, firstWord[3] contains the number of letter 'd' in the word.

Upvotes: 1

Related Questions