In: Computer Science
Write a C++ program (using pointers and dynamic memory
allocation only) to
implement the following functions and call it from the main
function. (1)Write a function whose signature looks like (char*,
char) which returns true if the 1st parameter cstring contains the
2nd parameter char, or false otherwise.
(2)Create an array of Planets. Populate the array and print the
contents of the array
using the pointer notation instead of the subscripts.
#include <iostream>
using namespace std;
//This function takes 2 parameters one character array and search character
bool SearchParameter(char *str, char ch)
{
//this for loop checks each of the character
//in the character array 'str' for search character 'ch'
for (int i = 0; i < sizeof(char *); i++)
{
if (ch == str[i])
{
return true;
}
else
{
return false;
}
}
}
//the main method
int main()
{
//size to increase the dynamic array
int size = 30;
//to hold search parameter
char ch;
//dynamically allocating memory size through malloc
char *str = (char *)malloc(sizeof(char) * size);
//takes single search character as input
cout << "\nEnter the single Search parameter/character you want to search : ";
cin >> ch;
//takes the characte string as input
cout << "\nEnter the whole Character String: ";
cin >> str;
//this is the function call which stores the result
//as either 0=false or true=1
bool res = SearchParameter(str, ch);
//validate result and print the result status-RB
if (res == true)
{
cout << "And the result is: true";
}
else
{
cout << "And the result is: false";
}
}
The function working and all the code working is explained in comments .