Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

c++ - count number of times a character appears in an array?

i've been thinking for a long time and havent got anywhere with the program. i dont know where to begin. The assignment requires use of single function main and only iostream library to be used. the task is to Declare a char array of 10 elements. Take input from user. Determine if array contains any values more than 1 times . do not show the characters that appears 1 time only.

Sample output:
a 2
b 4
..

a an b are characters. and 2 and 4 represents number of times they appear in the array B.

i tried to use nested loop to compare a character with all the character in array and incrementing a counter each time similer character id sound but unexpected results are occuring.

Here is the code

#include <iostream>
using namespace std;
void main()
{

    char ara[10];
    int counter=0;
    cout<<"Enter 10 characters in an array
";
    for ( int a=0; a<10; a++)
        cin>>ara[a];

    for(int i=0;  i<10;  i++)
    {
       for(int j=i+1; j<10;  j++)
     {
         if(ara[i] == ara[j])
               {
                  counter++;
                  cout<<ara[i]<<"	"<<counter<<endl;
               }
     }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Algorithm 2: std::map
Declare / define the container:

std::map<char, unsigned int> frequency;
  1. Open the file
  2. read a letter.
  3. find the letter: frequency.find(letter)
  4. If letter exists, increment the frequency: frequency[letter]++;
  5. If letter no exists, insert into frequency: frequency[letter] = 1;
  6. After all letters processed, iterate through the map displaying the letter and its frequency.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...