In: Computer Science
Rewrite the following program so
that the counting of the a's and
total count are done be
separate functions
The code you turn in should have 2 functions
*/
#include<stdio.h>
int main(void){
char input[81];
// Input string
int a=0, total=0;
// counter variables
// Ask for an input string
puts(" Input a string of up to 80 characters
and\n"
" I will tell you how many a\'s it contains \n"
" as well as a total character count.\n\n");
fputs(" ",stdout);
// just make things line
up
// read the input string
fgets(input,80,stdin);
while(input[total] != '\0'){ // go through the string
if(input[total] == 'a' ||
input[total] == 'A') // count the number of a's
a++;
total++;
// total character
count
}
total--;
// fgets reads the newline -
we don't want to count that
// output the results
printf(" %d a\'s and %d total
characters.\n",a,total);
return 0;
}
We have to rewrite given program so that counting of a's and total count are done in different functions.
So we will create a function named count_a() which will take input string as parameter and return number of a's .
We will create another function named count_total() which will also take input string as parameter and return total number of characters present in string.
Modified program-
#include<stdio.h>
//function to find number of a in string
int count_a(char input[]){
int i=0;
int a=0;
while(input[i] != '\0'){ //traverse whole string till we reach the end
if(input[i]=='a' || input[i]=='A'){
a++; // if character is 'a' then we will increase the count of a
}
i++; //increment i to reach to next element of string
}
return a; //return taotal number of a's in the string
}
//function to find total number of characters in string
int count_total(char input[]){
int total=0;
while(input[total] != '\0'){ //traverse whole string till we reach end of string
total++; //total characters count
}
total--; //fgets reads the newline - we don't want to count that
return total; //return total number of characters
}
int main(void){
char input[81]; // Input string
int a, total; // counter variables
// Ask for an input string
puts(" Input a string of up to 80 characters and\n"
" I will tell you how many a\'s it contains \n"
" as well as a total character count.\n\n");
fputs(" ",stdout); // just make things line up
// read the input string
fgets(input,80,stdin);
a=count_a(input); //calling the function to count a's
total=count_total(input); // calling the function to count total characters
// output the results
printf(" %d a\'s and %d total characters.\n",a,total);
return 0;
}
Comments are added in the program for better understanding.