In: Computer Science
In objective-C
Task: Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. The output should include the input character and use the plural form, n's, if the number of times the characters appears is not exactly 1.You may assume that the string does not contain spaces and will always contain less than 50 characters. Ex: If the input is: n Monday the output is: 1 n Ex: If the input is: z TodayisMonday the output is: 0 z's Ex: If the input is: n It'ssunnytoday the output is: 2 n's Case matters. Ex: If the input is: n Nobody the output is: 0 n's n is different from N.
#include <stdio.h>
#include <string.h>
int main(void) {
char letter;
char word[50];
printf("Enter the letter to be checked: ");
scanf("%c", &letter);
scanf("%s", word);
int numChars = 0;
for (int i = 0; i <= strlen(word); i++)
if (word[i] == letter)
{
numChars++;
printf("%d %c's", numChars, letter);
}
else
{
printf("%c is different from %c\n", letter, word[i]);
}
return 0;
}
Enter the letter to be checked: n
Monday
n is different from M
n is different from o
1 n'sn is different from d
n is different from a
n is different from y
n is different from
I created this program, but cannot get the right output. Can someone suggest how to improve it?
Source Code:
Output:
Code in text format (See above images of code for indentation):
/*include library files*/
#include <stdio.h>
/*main function*/
int main()
{
/*variables*/
char c,word[50];
int i,count=0;
/*read a character from user*/
printf("Enter the letter to be checked: ");
scanf("%c",&c);
/*read a string from user*/
printf("Enter a string: ");
scanf("%s",word);
/*using a loop count number of times character appears
in string*/
for(i=0;word[i]!='\0';i++)
{
/*check and count*/
if(word[i]==c)
count++;
}
/*print count*/
printf("Number of %c's in word %s is : %d
n",c,word,count);
/*for plural*/
if(count!=1)
printf("'s");
}