28.4k views
5 votes
Your program must define and call the following function that returns the number of times the input character appears in the input string. int CountCharacters(char userChar, string userString)

1 Answer

2 votes

Answer:

The program to this question can be given as:

Program:

#include <iostream> //header file

using namespace std; //using name space.

int CountCharacters(char userChar,string userString) //define function.

{

int count = 0; //define variable

for (int i=0;i<userString.length();i++) //loop

if (userString[i]==userChar) //if block

count++; //increment the value.

return count; //return value.

}

int main() //main method.

{

string userString= "Clanguage"; //define variable and assign value.

char userChar = 'a'; //define variable and assign value.

cout << CountCharacters(userChar,userString); //calling function and print value.

return 0;

}

Output:

2

Step-by-step explanation:

  • In the above C++ programming language program we define a function that is "CountCharacters". Inside function parameters, we pass two parameters that are "userChar and userString". The userChar is a char variable that holds single character value and userString is a string variable that holds a string value.
  • In the function, we define an integer variable that is "count". This variable counts the match value and returns its value.
  • To counts values, we define a loop in a loop we use if statement that counts the value that how many time it occurs in a string value and return its value.
  • In the main method, we define these variables ("userChar and userString") and assign values that are "a and Clanguage " and call the function and print function return value.
User Edelwater
by
8.1k points