C Language Please add comments Write and test a function hyd

C Language

Please add comments

Write and test a function hydroxide that returns a 1 for true if its string argument ends in the substring OH.

Try the function hydroxide on the following data:

KOH H202 NaOH C9H8O4 MgOH

Solution

#include<stdio.h>

int hydroxide(char *str)
{
int len = 0;
int i;
  
//Initialize result with 0
int res = 0;
  
//Get the length of the string.
while(str[i])
i++;
len = i;
  
//If string has atleast 2 characters and last 2 characters are OH then result is 1.
if(len>=2)
{
if(str[len-1]==\'H\' && str[len-2]==\'O\')
res = 1;
}
  
return res;
}

int main()
{
char *str = \"KOH\";
int result;
  
result = hydroxide(str);
if(result==1)
printf(\"%s ends with OH.\ \",str);
else
printf(\"%s does not ends with OH.\ \",str);
  
str = \"H202\";
result = hydroxide(str);
if(result==1)
printf(\"%s ends with OH.\ \",str);
else
printf(\"%s does not ends with OH.\ \",str);
  
str = \"NaOH\";
result = hydroxide(str);
if(result==1)
printf(\"%s ends with OH.\ \",str);
else
printf(\"%s does not ends with OH.\ \",str);
  
str = \"C9H8O4\";
result = hydroxide(str);
if(result==1)
printf(\"%s ends with OH.\ \",str);
else
printf(\"%s does not ends with OH.\ \",str);
  
str = \"MgOH\";
result = hydroxide(str);
if(result==1)
printf(\"%s ends with OH.\ \",str);
else
printf(\"%s does not ends with OH.\ \",str);
  

return 0;
}

OUTPUT:

KOH ends with OH.
H202 does not ends with OH.
NaOH ends with OH.
C9H8O4 does not ends with OH.
MgOH ends with OH.

C Language Please add comments Write and test a function hydroxide that returns a 1 for true if its string argument ends in the substring OH. Try the function h
C Language Please add comments Write and test a function hydroxide that returns a 1 for true if its string argument ends in the substring OH. Try the function h

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site