Good Morning:
I am new to programming and I have been working on an assignment for two days now. I have written the code for a loop, but when it runs, it does not increment. Here are the instructions for this function:
Write a function named getCharacterFrequency. This function is passed a null terminated string as its first parameter. The second parameter is an uninitialized array of size 26 that will hold the function result.
The declaration looks like this:
void getCharacterFrequency (char inputString [], unsigned int frequency[]);
The function should first set all values in the frequency array to 0. The function should then use a loop to examine each character in the null terminated string. For each alphabetical character a through z or A through Z, the function should increment the corresponding location in the array. For example, if the input string is Hello, the frequency array will be as follows:
0 0 0 0 1 0 0 1 0 0 0 2 0 0 1 0 0 0 0 0 0 0 0 0 0 0
The first parameter is used to pass data in to the function so the first parameter is an IN parameter. The second parameter is used to return the function results so it is an OUT parameter. The result should be returned. Do not display the result. ///
I fixed the runaway problem but now the function increments the array elements incorrectly.
Here is my new code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
void getCharacterFrequency (char inputString[], unsigned int frequency[])
{
char ch;
int index1 = 0;
int index2 = 0;
const int SIZE = 26;
while (index1 < SIZE)
{
frequency[index1] = 0; // This is to initilize the frequency array values to zero
index1++;
}
ch = inputString[index2];
while (ch != '\0')
{
if (ch >= 65 && ch <= 90)
{
frequency[ch - 65]++;
}
else if (ch >= 95 && ch <= 122)
{
frequency[ch - 95]++;
}
ch = inputString[++index2];
}
}
|
This is what I started with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
//This program will test the getCharacterFrequency function
#include <iostream>
using namespace std;
void getCharacterFrequency (char inputString[], unsigned int frequency[]);
void main()
{
char inputString[] = {"Larry had A biG Dog"};
unsigned int frequency[26];
getCharacterFrequency (inputString, frequency);
cout << frequency << endl;
}
//This function will determine how many times a letter appears in a string
#include <iostream>
using namespace std;
void getCharacterFrequency (char inputString[], unsigned int frequency[])
{
char ch;
int index = 0;
const int SIZE = 26;
if (index < SIZE)
{
frequency[index] = 0;
cout <<"In frequency" << endl;
}index++;
ch = inputString[0];
while (ch != '\0')
{
if (ch >= 65 && ch <= 90)
{
cout <<"In loop1" << endl;
frequency[ch - 65]++;
cout <<frequency[0]<< endl;
index++;
}
if (ch <= 95 && ch <= 122)
{
cout <<"In loop 2" << endl;
frequency[ch - 95]++;
index++;
}
}
}
|
Can anyone tell me what I did wrong? Please.