I have written a program in C where the user gives an input string and the program separates the vowels and consonants into different strings and prints the output but the counter variable does not start from zero and increase in an sequential order.
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void append(char string[] , char letter)
{
char arr[] = {letter , ''};
strcat(string,arr);
}
void checkcon(char letter,char string[] , int counter)
{
char consonants[] = "bcdfghjklmnpqrstvwxyz";
for (int i=0;i<=20;i++)
{
if (letter == consonants[i])
{
append(string,letter);
counter = counter + 1;
printf("Con : %dn",counter);
}
}
}
void checkvow(char letter,char string[],int counter)
{
char vowels[] = "aeiou";
for (int i=0;i<=4;i++)
{
if (letter == vowels[i])
{
append(string,letter);
counter = counter + 1;
printf("Vow : %dn",counter);
}
}
}
int main(void)
{
char inp[5000] = {0};
char vow[5000] = {0};
char con[5000] = {0};
int vowno,conno = 0;
int length;
printf("Enter a string: ");
scanf("%s",&inp);
for (length = 0; inp[length] != ''; ++length)
{
inp[length] = tolower(inp[length]);
}
for (int i=0;i<=length;i++)
{
checkcon(inp[i],con,conno);
checkvow(inp[i],vow,vowno);
}
printf("Consonants: %sn",con);
printf("Number of consonants: %dn",conno);
printf("Vowels: %sn",vow);
printf("Number of vowels: %d",vowno);
return 0;
}
Output :
Enter a string: String
Con : 1
Con : 1
Con : 1
Vow : 15081
Con : 1
Con : 1
Consonants: strng
Number of consonants: 0
Vowels: i
Number of vowels: 15080
I do not understand why my counter does not start from zero and increase sequentially.
I tried it with all the alphabets and this is the output:
Enter a string: abcdefghijklmnopqrstuvwxyz
Vow : 15081
Con : 1
Con : 1
Con : 1
Vow : 15081
Con : 1
Con : 1
Con : 1
Vow : 15081
Con : 1
Con : 1
Con : 1
Con : 1
Con : 1
Vow : 15081
Con : 1
Con : 1
Con : 1
Con : 1
Con : 1
Vow : 15081
Con : 1
Con : 1
Con : 1
Con : 1
Con : 1
Consonants: bcdfghjklmnpqrstvwxyz
Number of consonants: 0
Vowels: aeiou
Number of vowels: 15080
I had referred to this since I was using a for loop to check for consonants and vowels instead of a function but I still did not get anything right. My question is quite different from this and from this because neither of the questions use a separate function to check for consonants and vowels and neither question have more details on how their counter is not working.
The problem focuses on why the counter was not working, this has been fixed by initialising the variables and assigning the return value of the function to the respective variables(change return type to int and return ‘counter’ after the loop).
10
The syntax of variable definition is not as you think it is.
int vowno,conno = 0;
Means:
int vowno; // define, but not initialize
int conno = 0; // define and initialize
If you want to define and initialize both variables in one line:
int vowno = 0, conno = 0;
2