153k views
2 votes
Develop an algorithm and write a C++ program that finds the number of occurrences of a specified character in the string; make sure you take CString as input and return number of occurrences using call by reference. For example, Write a test program that reads a string and a character and displays the number of occurrences of the character in the string. Here is a sample run of the program:______.

User Harun Ugur
by
6.1k points

1 Answer

6 votes

Answer:

The algorithm is as follows:

1. Input sentence

2. Input character

3. Length = len(sentence)

4. count = 0

5. For i = 0 to Length-1

5.1 If sentence[i] == character

5.1.1 count++

6. Print count

7. Stop

The program in C++ is as follows:

#include <iostream>

#include <string.h>

using namespace std;

int main(){

char str[100]; char chr;

cin.getline(str, 100);

cin>>chr;

int count = 0;

for (int i=0;i<strlen(str);i++){

if (str[i] == chr){

count++;} }

cout << count;

return 0;}

Step-by-step explanation:

I will provide explanation for the c++ program. The explanation can also be extended to the algorithm

This declares the string and the character

char str[100]; char chr;

This gets input for the string variable

cin.getline(str, 100);

This gets input for the character variable

cin>>chr;

This initializes count to 0

int count = 0;

This iterates through the characters of the string

for (int i=0;i<strlen(str);i++){

If the current character equals the search character, count is incremented by 1

if (str[i] == chr){ count++;} }

This prints the count

cout << count;

User Hectorsvill
by
6.4k points