Check whether a character is a Vowel or Consonant - c

I need to make Check whether a character is a Vowel or Consonant as function and it returns 1 if it's a vowel and returns 0 if it's consonant
That's what I've come up with
#include <stdio.h>
#include <stdlib.h>
int vowel(char c) {
int lowercase, uppercase;
lowercase = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
uppercase = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
if (lowercase || uppercase)
return 1;
else
return 0;
}
int main() {
char c;
printf("Enter an alphabet: ");
scanf("%c", &c);
vowel(c);
}
Input: a
Output: Process returned 0

Your function int vowel(char c) looks OK, though for readability and better compiler optimization opportunities I'd use a switch statement, like this:
int vowel(char c) {
switch(tolower(c)){
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return 1;
default:
return 0;
}
}
The second observation is that you seem to ignore the result of the function's execution altogether. I could only assume you were supposed to do something with it, like printing out the result. Something along these lines (instead of the v̶o̶w̶e̶l̶(̶c̶)̶;̶ code):
printf("\nThe character '%c' is %sa vowel\n", c, vowel(c) ? "" : "not ");

return type of vowel function is "int". But the function call is not storing the value. Change the function call as below.
int main() {
char c;
printf("Enter an alphabet: ");
scanf("%c", &c);
int flag = vowel(c);
printf("%d",flag); }

#include <stdio.h>
#include <stdlib.h>
int vowel(char c) {
int lowercase, uppercase;
lowercase = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
uppercase = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
if (lowercase || uppercase)
return 1;
else
return 0;
}
int main() {
char c;
printf("Enter an alphabet: ");
scanf("%c", &c);
int a=vowel(c);
if(a==1)
printf("vowel");
if(a==0)
printf("consonant");
}

Answering your questions one by one
Firstly,
what you have is a void function called vowel that takes in a char parameter.
When you declare a type of the function, what you are basically doing is telling the system what sort of return type you are expecting from this function. Since you are declaring the function void, you are expecting no return type from it hence, it does not matter what you return there.
Secondly,
when you declare the vowel function int, in your main function you have to store the value of the vowel function in a variable.
Thirdly,
the process returned 0 that you see is mainly the execution of your program saying no errors occurred.
What you probably are looking for is something like this I think,
if (lowercase || uppercase)
printf("1");
else
printf("0");
It's awesome to come up with own solutions, I would also suggest following the solutions given above as they are good coding practice.

Related

how to put if..else statement in do..while loop c program

so I have been working on my assignment and I can't figure out how to put if...else statement in my do..while loop because want I run the program it doesn't loop. the output is like this.
[this the output that I got][1]
#include <stdio.h>
#include <ctype.h>
int main(void){
char alphabet;
char confirm;
int lowercase_vowel, uppercase_vowel;
int a =1;
do{
printf("Enter an alphabet: ");
scanf("%c", &alphabet);
// evaluates to 1 if variable c is a lowercase vowel
lowercase_vowel = (alphabet == 'a' || alphabet == 'e' || alphabet == 'i' || alphabet == 'o' || alphabet == 'u');
// evaluates to 1 if variable c is a uppercase vowel
uppercase_vowel = (alphabet == 'A' || alphabet == 'E' || alphabet == 'I' || alphabet == 'O' || alphabet == 'U');
if(!isalpha(alphabet))
{
printf("Error! Non-alphabetic character.\n");
}
else if(lowercase_vowel || uppercase_vowel)
{
printf("%c is a vowel.\n", alphabet);
}
else
{
printf("%c is a consonant.\n", alphabet);
}
printf("\nif u want to proceed enter 1, if not enter 0\n");
scanf("%d", &a);
}while( a == 1);
}
``
[1]: https://i.stack.imgur.com/oRK1G.png
do
{
// code
}while (a = 1);
This will create an infinite loop, because it will assign 1 to a, and because a is now a nonzero value, the condition is true, and it will loop again:
Maybe what you want is:
do
{
// code
}while (a == 1); // comparison, not assignment
Also:
scanf("%d", a);
should be:
scanf("%d", &a);

Number of occurences of any two specific letters in a line or text( string)

Q : Write a program to count the number of occurrences of any two vowels in succession in a line of text. For example the following sentence :
"Please read the application and give me gratuity"
Such occurrences in the sentence are :- "ea" , "ea" , "io" , "ui". Ultimately the question is to count the number of such occerrences in the line which is a user input string.
Problem : My program is just recieve a line but did not give any output.
It's my first question in stackoverflow. I am a beginner in programming.
My code:
# include <stdio.h>
int main () {
char line[100];
printf("\nEnter a line\n");
gets(line);
//printf("You entered : %s\n", line);
char A,E,I,O,U,a,e,J,o,u;
A = 'A';
E = 'E';
I = 'I';
O = 'O';
U = 'U';
a = 'a';
e = 'e';
J = 'i';
o = 'o';
u = 'u';
int occurence =0,i =0 ;
while (line[i] =! '\0'){
if((line[i] == A || E || I || O || U || a || e || J || o || u) && (line[i+1] == a || e || J || o || u)){
occurence++;
}
i++;
}
printf("Number of occurence of any two vowels in succession in the line is : %d\n", occurence);
return 0;
}
Your code has multiple issues, some of which are:
You use gets to read the string. This function is now at least deprecated (I think it was even removed from recent versions of the standard library) because it is unsafe. Use fgets instead!
You use the || operator wrong - this was already pointed out in mediocrevegetable1's comment.
You could use a code similar to this one to solve your problem. The code contains comments, so it should be easy to understand. However, if this is a homework or project for school, do NOT use this exact code, as this would most likely be considered plagiarism!
#include <stdio.h>
#include <ctype.h>
#define STRLEN 100
int main () {
char line[STRLEN];
char* ch;
char incrementIfVowel;
int occurences;
/* Read line */
printf("\nEnter a line\n");
fgets(line, STRLEN, stdin);
/* Init variables */
incrementIfVowel = 0;
occurences = 0;
/* Iterate through characters */
for (ch = line; *ch != '\0'; ch++) {
/* Test if the current character is a vowel. Three cases can occur: */
if (toupper(*ch) == 'A' || toupper(*ch) == 'E' || toupper(*ch) == 'I' || toupper(*ch) == 'O' || toupper(*ch) == 'U') {
if (incrementIfVowel == 1) {
/* Case 1: The current character is a vowel, and its predecessor was also a vowel */
incrementIfVowel = 0;
occurences++;
}
else {
/* Case 2: The current character is a vowel, but its predecessor was not a vowel or it was the second vowel in a row */
incrementIfVowel = 1;
}
}
else {
/* Case 3: The current character is not a vowel */
incrementIfVowel = 0;
}
}
/* Print result */
printf("Number of occurence of any two vowels in succession in the line is : %d\n", occurences);
return 0;
}
There are 3 main issues with your code:
gets(line);
gets doesn't check the length of the buffer and for this reason, is susceptible to buffer overflows. gets had been deprecated since C99 and was removed in C11. You're probably compiling with an older version of the standard; I'd suggest you switch to newer versions. As for an alternative, see fgets.
while (line[i] =! '\0'){
=! is a typo. Replace it with !=
if((line[i] == A || E || I || O || U || a || e || J || o || u) && (line[i+1] == a || e || J || o || u))
This will always evaluate to true because || doesn't chain like that. Ideally, you should put this in a function:
_Bool is_vowel(char ch)
{
return toupper(ch) == 'A' || toupper(ch) == 'E' || toupper(ch) == 'I' || toupper(ch) == 'O' || toupper(ch) == 'U';
}
toupper is defined in <ctype.h> so be sure to include that. You could also shorten this behemoth of a line with return strchr("AEIOUaeiou", ch), but if you haven't used strchr and are not comfortable with using it yet, that's okay.
Modifying only the incorrect parts, your final code will can look something like this:
#include <stdio.h>
#include <ctype.h>
_Bool is_vowel(char ch)
{
return toupper(ch) == 'A' || toupper(ch) == 'E' || toupper(ch) == 'I' || toupper(ch) == 'O' || toupper(ch) == 'U';
}
int main () {
char line[100];
printf("\nEnter a line\n");
fgets(line, sizeof line, stdin);
int occurence = 0, i = 0;
while (line[i] != '\0') {
if(is_vowel(line[i]) && is_vowel(line[i + 1]))
occurence++;
i++;
}
printf("Number of occurence of any two vowels in succession in the line is : %d\n", occurence);
return 0;
}
An example of running this:
Enter a line
Please do something about the bee hive and then eat some meat
Number of occurence of any two vowels in succession in the line is : 5
(5 because Pl<ea>se do something ab<ou>t the b<ee> hive and then <ea>t some m<ea>t)

C: scanf input single character and validation

I've encountered a problem when validating a single-char scanf input in C and I cannot find an existing solution that works...
The scenario is: a method is taking a single letter 'char' type input and then validating this input, if the criteria is not met, then pops an error message and re-enter, otherwise return this character value.
my code is:
char GetStuff(void)
{
char c;
scanf("%c", &c);
while(c != 'A' || c != 'P')
{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &dtChar);
}
return c;
}
however, i got the infinite loop of error message no matter what input I type in. I read some other posts and guess it's the problem that %c specifier does no automatically get rid of the newline when I hit enter, and so far I have tried:
putting a white space before/after %c like:
scanf(" %c", &c);
write a separate method or include in this GetStuff method to clean the newline like:
void cleanBuffer(){
int n;
while((n = getchar()) != EOF && n != '\n' );
}
Can anyone help me with this problem please? Thank you in advance.
Please consider the following snippet:
#include <stdio.h>
#include <ctype.h>
char GetStuff(void)
{
char c;
do {
printf("Please enter A for AM or P for PM: ");
scanf ("%c", &c);
// clean input buffer (till the end of line)
while(getchar()!='\n');
} while(toupper(c) != 'A' && toupper(c) != 'P');
return c;
}
int main(void)
{
printf("Your input is'%c'\n", GetStuff());
return 0;
}
Note the points:
condition while(c != 'A' || c != 'P') will be always true (just because one character cannot be 'A' and 'P' at the same time), so use while(c != 'A' && c != 'P') instead
No need for two scanf if you use do..while loop
After entering a char with scanf it is recommended to clean all characters from buffer, e.g. with while(getchar()!='\n'); (this will clean all input including incorrect and redundant characters)
use toupper to avoid making 4 comparison (actually single c=toupper(c) inside loop can minimize your while as while(c != 'A' && c != 'P') )
UPDATE:
To add message "Invalid input" and adding some other useful improvement subjected befor... new code is as:
#include <stdio.h>
#include <ctype.h>
void CleanBuffer(){
int n;
while((n = getchar()) != EOF && n != '\n' );
}
char GetStuff(void)
{
char c;
do {
printf("Please enter A for AM or P for PM: ");
scanf (" %c", &c);
c = toupper(c); // here letter become uppercase
CleanBuffer();
} while( (c != 'A' && c != 'P')?printf("Invalid input! "):0 );
return c;
}
int main(void)
{
printf("You have entered: %c\n", GetStuff());
return 0;
}
Note: function will return 'A' or 'P' in uppercase, so if this is not needed change the code as in example before update (use two toupper and do not change c after scanf). Also you can use tolower as an option (of course with comparing to 'a' and 'p').
#include <stdio.h>
char GetStuff(void) {
char c;
scanf("%c", &c);
getchar();
while ((c != 'A') && (c != 'a') && (c != 'P') && (c != 'p')) {
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &c);
getchar();
}
return c;
}
int main(void) {
printf("Calling GetStuff()...\n");
char x = GetStuff();
printf("User entered %c\n", x);
return 0;
}
You are using while (c != 'A' || c != 'P') as your loop conditional, but this will always return true. What you meant to use is the && "and" operator, instead of the || "or" operator.
Also, call getchar() after your scanf statements, to capture the newline. This should work the way you want it to.
Inside loop you are taking input in dtChar but your loop condition checks variable c which is not updated in the loop, that is causing infinite loop
Also you would change your condition
while(c != 'A' || c != 'P')
to
while(c != 'A' && c != 'P')
If you want user to enter either 'A' or 'P'
Another possible solution. As others mentioned the condition was to be done with &&. Anyway the big problem is how to remove what's left on the console input line. Since the console works by lines, we remove everything up to the next '\n'. If the user already left something on the input line before calling GetStuff(), it would be useful to add a call to SkipRestOfTheLine() before the while loop.
In general I suggest to start with a while(1) loop, before making it nicer (such as in the cleanBuffer() you posted).
#include <stdlib.h>
#include <stdio.h>
void SkipRestOfTheLine(void)
{
while (1) {
int c = fgetc(stdin);
if (c == EOF || c == '\n')
break;
}
}
char GetStuff(void)
{
while (1) {
int c = fgetc(stdin);
if (c == EOF)
exit(EXIT_FAILURE); // Deal with this case in an appropriate way
if (c == 'A' || c == 'P')
return c;
printf("invalid input, enter again (A for AM or P for PM): ");
SkipRestOfTheLine();
}
}
int main(void)
{
char c = GetStuff();
return 0;
}
try this,
char GetStuff(void)
{
char c;
scanf("%c", &c);
while (((c != 'A') || (c != 'a')) && ((c != 'P') || (c != 'p'))==1)
{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &dtChar);
}
return c;
}
I hope this works, some time because of not given proper bracket it is stuck in the loop.
#include <stdio.h>
int main(){
char c;
do{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%s", &c);
}while ((c != 'A') && (c != 'P'));
return 0;
}

How to use loops in terms of input (in C language)?

I've been trying to get this code to work but the loop does not seem to work? I am very new to C and I sort of get confused with the syntax of this language. However my loop is not functioning like how I want it to be. I want the if and else statement to work but no matter what input (right or wrong) it always outputs "thank you".
#include <stdio.h>
#include <stdlib.h>
int confirm()
{
char c;
printf("Confirm (y/n): ");
scanf("%c", &c);
while (scanf("%c", &c))
{
if (c = 'Y' && 'y' && 'N' && 'n')
{
printf("\nthank you");
break;
}
else
{
printf("\nInput not recognised, try again. \n");
printf("\nConfirm (y/n): ");
scanf("%c", &c);
}
}
}
int main(int argc, char* agrv[])
{
confirm();
return 0;
}
it won't ask to enter another output when the output is incorrect. It just keeps ending from the if statement, thus the loop is not running?
Please help.
There's nothing wrong with your loop - it's the if statement that's wrong.
This code compiles, but it does not do what you want it to do:
if (c = 'Y' && 'y' && 'N' && 'n')
= is an assignment; you need == to do a comparison
&& means "AND"; you need ||, which means an "OR"
You combine logical expressions, not constants with && or ||
The condition should be
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')
Also note that when you read single characters with %c, your program "sees" all characters, including whitespace. This is a problem, because the '\n' left over in the buffer will be passed to your program before Y or N. To fix this, add a space before %c to your format string:
scanf(" %c", &c)
// ^
// |
// Here
Your code also ignores the first character that it reads. I think this is not intentional, so remove the call of scanf before the loop. You should also remove the second scanf from the loop, leaving the only call to scanf in the loop header.
int confirm()
{
char c;
printf("Confirm (y/n): ");
//scanf("%c", &c);// <---------- needless
while (scanf("%c", &c)) //<----while loop will do `scanf("%c",&c)`, so previous line should be remove.
{
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')// <- &&(AND); ||(OR). Also, be careful that don't be lazy, [c == 'Y' || 'y' || 'N' || 'n'] can't to communicate with computer
{
printf("\nthank you");
break;
}
else
{
printf("\nInput not recognised, try again. \n");
printf("\nConfirm (y/n): ");
scanf("%c", &c);
}
}
}

Letter options in menu stated as undeclared in C program

I think my problem is something simple, but I'm not seeing it. I'm new to programming in C and this is an effort to see what I've absorbed, bit by bit. I think I must have not properly defined my char variable "dopt". Hope you can help. Here's the code:
#include <stdio.h>
int dbref();
int aart();
int wgame();
int calc();
int txtoc();
int amin()
{
char dopt;
printf("What should this program have the options of doing?\n");
printf("A) Reference a database?\n");
printf("B) Print ascii art?\n");
printf("C) Make a noun, pronoun, object, verb word game?\n");
printf("D) Being a calculator?\n");
printf("E) creating a text file and save it as a .c file?\n");
printf("F) or should it just terminate?\n");
scanf("%c", &dopt);
if (dopt == a || A)
{ dbref();}
if (dopt== b || B)
{ aart();}
if ( dopt==c || C)
{ wgame();}
if ( dopt==d || D)
{ calc();}
if ( dopt==e || E)
{ txtoc();}
if ( dopt==f || F)
{ return 0;}
return 1;
}
dbref()
{
printf("reference A correct");
return 2;
}
aart()
{
printf("reference B correct");
return 3;
}
wgame()
{
printf("reference C correct");
return 4;
}
calc()
{
printf("reference D correct");
return 5;
}
txtoc()
{
printf("reference E correct");
return 6;
}
As a sidenote, the printf routines in the functions are just to verify that the menu is flowing correctly.
Code like this:
if (dopt == a || A)
should be written something like this:
if (dopt == 'a' || dopt == 'A')
because a would be the name of a variable or function (which doesn't exist), and 'a' is a character literal.
Alternatively, you could consider a switch block:
switch (dopt)
{
case 'a':
case 'A':
dbref();
break;
case 'b':
case 'B':
aart();
break;
/* etc. */
default:
fprintf(stderr, "Unrecognised option!\n");
return 1;
}
a is not the same as 'a'
a is an identifier
'a' is a character
You want to match that if the contents of the char variable dopt is any of the characters. So you need to compare the ASCII values of the characters, which can be found by placing the character within a single quotes.
Therefore
if (dopt == a || A)
{ dbref();}
a and A are treated as two separate variables (names), which are not declared (at least locally) .
Thus it should be
if (dopt == 'a' || 'A')
{ dbref();}
Here 'a' and 'A' are character constants and not variable names.
BUT 'a' || 'A' is always 1 because || is logical OR operator. Therefore dopt will always be false (almost). But if you want to make the effect that if dopt is either 'a' or 'A' then call dbref () then you need to do the following:
if ((dopt == 'a') || (dopt == 'A'))
{ dbref();}
or also
if (toupper (dopt) == 'A') // similar with tolower ()
{ dbref();}
Writing dopt == a || A does not work in C. What you want is
dopt == 'a' || dopt == 'A'
In C, you have to enclose character literals with ' (otherwise they are interpreted as variables). You also can't combine the logical or, but have to type in the dopt == each time.
You want to quote your letters in the option check, otherwise they're treated as variables, and will fail to compile because they don't exist.

Resources