Using a different library in C - c

I just coded from scratch a program that would count the upper and lowercase letters and blank spaces of whatever the user input. Since then I found out that code for those specific functions have already been prewritten in another library! My question is, how can all the code that I have written below be simplified with the use of
isupper(int c), islower(int c), and isspace(int c) which are defined in ctype.h.
#include <stdio.h>
int main(void){
int iochar, numdigits=0, numlower=0, numupper=0, numwhites=0;
printf("Please enter a phrase:\n\n");
while((iochar=getchar())!=EOF)
{
if ((iochar==' ')||(iochar=='\t')||(iochar=='\n'))
{
numwhites++;
putchar(iochar);
}
else
if((iochar>='0')&&(iochar<='9'))
{
numdigits++;
putchar(iochar);
}
else
if(('a'<=iochar)&&(iochar<='z'))
{
numlower++;
putchar(iochar-32);
}
else
if(('A'<=iochar)&&(iochar<='Z'))
{
numupper++;
putchar(iochar);
}
else
putchar(iochar);
}
printf("%d white characters, %d digits, ",numwhites,numdigits);
printf("%d lowercase have been converted to ",numlower);
printf("uppercase and %d uppercase.\n",numupper);
printf("\n\n");
return 0;}

Here is it written better and cleaned up:
#include <stdio.h>
#include <ctype.h>
int main(int argc, char **argv) {
int iochar, numdigits=0, numlower=0, numupper=0, numwhites=0;
printf("Please enter a phrase:\n\n");
while ((iochar=getchar()) != EOF) {
// increase counts where necessary
if (isspace(iochar)) {
numwhites++;
} else if (isdigit(iochar)) {
numdigits++;
} else if (islower(iochar)) {
numlower++;
iochar = toupper(iochar);
} else if (isupper(iochar)) {
numupper++;
}
// this happens always, don't put it in the if's
putchar(iochar);
}
printf("%d white characters, %d digits, ", numwhites, numdigits);
printf("%d lowercase have been converted to ", numlower);
printf("uppercase and %d uppercase.\n", numupper);
printf("\n\n");
return 0;
}

Just #include <ctype.h> and then change e.g.
if((iochar==' ')||(iochar=='\t')||(iochar=='\n'))
to
if (isspace(iochar))
etc.
For full details see man ctype.

Related

C Program to check if character is a lower case letter and convert to upper case letter and vice versa

C Program to check if character is a lower case letter and convert to upper case letter and vice versa
why this works ?
(it seems to be working if i use if statement twice but not if i use if-else statement)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch , k ;
printf("enter an alphabet : ");
scanf("%c",&ch);
if (ch>=97 && ch<=122)
{
printf(" \n small letter");
k=ch-32;
printf(" \n after conversion %c",k);
}
if (ch>=65 && ch<=90)
{
printf(" \n capital letter");
k=ch+32;
printf(" \n after conversion %c",k);
}
return 0;
}
but this displays a random value.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch , k ;
printf("enter an alphabet : ");
scanf("%c",&ch);
if (ch>=97 && ch<=122)
{
printf(" \n small letter");
k=ch-32;
printf(" \n after conversion %c",k);
}
else (ch>=65 && ch<=90);
{
printf(" \n capital letter");
k=ch+32;
printf(" \n after conversion %c",k);
}
return 0;
}
if (ch>=97 && ch<=122) it will only work with ASCII codes. It is not portable. C has special functions for this task:
#include <ctype.h>
int swapCase(int ch)
{
return isupper((unsigned char)ch) ? tolower((unsigned char)ch) : toupper((unsigned char)ch);
/*
//or
if(isupper((unsigned char)ch))
ch = tolower((unsigned char)ch);
else
ch = toupper((unsigned char)ch);
return ch;
*/
}
and some helper function and the main program to demonstrate how it works:
char *strSwapCase(char *str)
{
char *wrk = str;
if(str)
{
while(*str)
{
*str = swapCase(*str);
str++;
}
}
return wrk;
}
int main (void){
char x[] = "asDrgdfDFGHFDSdfgf3546&&&434fdgffyhfghfdfsdgsfdDFDGdfgdf";
printf("before: %s\n", x);
printf("after : %s", strSwapCase(x));
}
https://godbolt.org/z/E4oe99sGd
Your second code, as written, does not compile. If you meant to use "else if", it should be written:
else if (ch>=65 && ch<=90)
Correcting this line causes your code to both compile and behave as expected. As it stands, I'm not sure how your code is running and giving you a "random value", but you may be using some unusual compiler that's discarding the statement after your else?

C Program about Password Validation not working

I wrote a program which is supposed to check if an entered password has an uppercase letter , a lowercase letter and a number. It won't return anything if the password is valid and if the password is invalid it should say "Not a valid password!". But this program doesn't work and I don't understand why.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int main()
{
char pass[20];
int a, i=0;
printf("Enter your password. It must contain an uppercase and a lowercase letter with a number. Password should be less than 19 characters.\n ");
scanf(" %s", pass);
a = strlen(pass);
/* Checking if an uppercase letter is present*/
for(i=0; i<a ; i++)
{
if(!isupper(pass[i] && i!=(a-1)))
{
continue;
}
else if (!isupper(pass[i]))
{
printf("Not a valid Password!");
}
else
{
break;
}
}
/* Checking if a lowercase letter is present */
for(i=0; i<a ; i++)
{
if(!islower(pass[i] && i!=(a-1)))
{
continue;
}
else if (!islower(pass[i]))
{
printf("Not a valid Password!");
}
else
{
break;
}
}
/* Checking if a number is present*/
for(i=0; i<a ; i++)
{
if(!isdigit(pass[i] && i!=(a-1)))
{
continue;
}
else if (!isdigit(pass[i]))
{
printf("Not a valid Password!");
}
else
{
break;
}
}
}
It looks like you have copied the code of the loop that checks uppercase, and used it in the other loops. The else if part in each loop contains the exact same condition.
A better way to do this would be using three flags:
int lower_flag = 0, upper_flag = 0, digit_flag = 0;
for(i=0 ; i<a ; i++) {
if(isupper(pass[i])) upper_flag=1;
else if(islower(pass[i])) lower_flag=1;
else if(isdigit(pass[i])) digit_flag=1;
}
if(upper_flag && lower_flag && digit_flag)
printf("Valid");
else
printf("Invalid");
You don't need 3 loops to check the valid password in your case.
You can do as below with one loop. All you need is 3 bool variables to mark upper,lower & digits presence in your password.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include<stdbool.h>
int main()
{
char pass[20];
int a, i=0;
bool upperPresent = false,lowerPresent = false,digitPresent = false;
printf("Enter your password. It must contain an uppercase and a lowercase letter with a number. Password should be less than 19 characters.\n ");
scanf(" %s", pass);
a = strlen(pass);
/* Checking if an uppercase letter is present*/
for(i=0; i<a ; i++){
if(isupper(pass[i])){
upperPresent = true;
}
else if (islower(pass[i])){
lowerPresent = true;
}else if (isdigit(pass[i])){
digitPresent = true;
}
}
if (upperPresent && lowerPresent && digitPresent)
printf("Valid password\n");
else
printf("invalid Password\n");
}
Why don't you add a bool that is triggered if you find an upper or a lower or a number and then exit out of the loop, because right now you are just traversing the whole string. Also you are checking for an upper in the third loop again.

How do I break the one dimensional array when condition met?

I am trying to enter an array of numbers (only integers for now) and what I wan't to do is if the user enters all the needed numbers, give him the ability to break the operation of entering numbers and skip to printing the entered numbers. My code is below. So the thing is, I've set 100 array elements, but if only have 5 to enter I don't wan't to enter the other 95.
Commented code is what I've tried and it didn't work. ( I work in CodeBlocks and am a total beginner, so I'm still learning this...)
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Declaring variables
int one_d_array[100],counter=0;
printf("Enter a list of numbers(max. 100)\nTo end, enter two zeros (00)\n");
for (counter=0;counter<5;counter++){
scanf("%d",&one_d_array[counter]);
/*if (one_d_array[counter]==00){
break;
}*/
}
printf("Entered list is:\n");
for (counter=0;counter<5;counter++){
printf("%d\n",one_d_array[counter]);
}
}
return 0;
}
fgets can be used to input a line. If the line is 00 exit the loop. Otherwise sscanf tries to scan a number.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void)
{
int one_d_array[100],each=0,counter=0;
char input[99] = "";
printf("Enter a list of numbers(max. 100)\nTo end, enter two zeros (00)\n");
while ( 1){
if ( fgets ( input, sizeof ( input), stdin)) {//get a line
if ( strcmp ( input, "00\n") == 0) {//exit on 00
break;
}
if ( ( sscanf(input, "%d",&one_d_array[counter])) != 1) {// != 1 means sscanf failed
printf("could not scan a number try again\n");
continue;
}
counter++;
printf("numbers input: %d\n\n", counter);
if ( counter >= 100) {
break;
}
}
else {
fprintf ( stderr, "problem reading input\n");
exit ( 1);
}
}
printf("Entered list is:\n");
for (each=0;each<counter;each++){
printf("%d\n",one_d_array[each]);
}
return 0;
}
Variable names cannot start with a number, so I've edited it accordingly.
#include <stdio.h>
#include <stdlib.h>
int main(){
//Declaring variables
int oneD_array[100],counter=0, num=0;
char c[3];
do{
printf("Enter your %d number, q to quit", counter+1);
scanf("%s",&c);
if(c == "q" || c == "Q"){
break;
}
else{
num = atoi(c);
oneD_array[num];
counter++;
}
}while(c != "q");
printf("Entered list is:\n");
for (int i = 0;i<counter;i++){
printf("%d\n",oneD_array[i]);
}
}
return 0;
}

Recursive way of display alphabet in c

I am quite newbie in c, so I just starting off with some code, experimenting some stuff, right now I am stuck with this problem in C, creating a function that displays the alphabet in lowercase, on a single line, by ascending order, starting from the letter ’a’.
This is where I am stuck:
#include <stdio.h>
int alfabet(unsigned int i) {
if(i <= 122) {
char litera = i;
return litera;
}
return alfabet(i+1);
}
int main() {
int i = 97;
printf(alfabet(i));
return 0;
}
Here, you won't print anything really interesting. In fact, your application will crash because printf() require at least a char * parameter (a string).
Your alfabet() function seems not so bad, but you should print the letter in it :
int alfabet(unsigned int i)
{
if (i > 'z') {
// Here is the stop condition.
// If the value is higher than 122 ('z' character), we stop recursivity)
return;
}
printf("%c ", i);
// Otherwise, let's call this function with another character
return alfabet(i+1);
}
Target simplicity
void alfabet(int c) {
printf("%c", c);
if (c < 'z') alfabet(c+1);
}
called from main as
alfabet('a');
You may add a printf("\n");
the function prints the character given as parameter
you only call recursively the function with the next character to be printed if necessary, i.e. if the current character is below z.
Something like that:
#include <stdio.h>
void alfabet(char i) {
if(i < 'z')
{
alfabet(i+1);
}
printf("%c", i);
}
int main() {
char i = 'a';
alfabet(i);
return 0;
}
to print zyxwvutsrqponmlkjihgfedcba. Or:
#include <stdio.h>
void alfabet(char i) {
printf("%c", i);
if(i < 'z')
{
alfabet(i+1);
}
}
int main() {
char i = 'a';
alfabet(i);
return 0;
}
to print abcdefghijklmnopqrstuvwxyz
As you are new in this language, the basic thing to know is that each and every character on the keyboard has its own ASCII value ranging from 000 to 127 (i.e. total 128).
Now if you want to print a to z in a single line, the ASCII value for 'a' is 97 and that for 'z' is 122.
So, for printing this on screen you need to learn the basic for loop structure.The syntax for basic for loop is as follows :-
for(expr1;expr2;expr3)
{
Body of the loop;
}
Here, expr1 refers to the initial value of the variable, expr2 refers to the exit condition of the loop and expr3 refers to the increment or decrement value.
So, the code to print a to z is as follows :-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
print_alpha();
getch();
}
void print_alpha()
{
int i;
for(i=97;i<+122;i++)
{
printf("%c",i);
}
}
int main() {
int i = 97;
printf("%c",alfabet(i));
return 0;
}
You Have to provide format specifier in printf (i.e. %c for character, %d for integer) Just check man printf in terminal.
And for printing a to z you can use for loop suggested by #Michel Jord, for printing in one line just put space in place of \n
#include <stdio.h>
void print_alphabets(char i) {
if(i>='a' && i<='z')
{
print_alphabets(i+1);
printf("%c ", i);
}
}
int main() {
char i;
scanf("%c",&i);
print_alphabets (i);
return 0;
}

Why is my password checking code not working correctly? It gives same output regardless of whatsoever input

I made a password checking program which checks for the following criteria:-
Should have atleast
1 uppercase
1 lower case
1 special character
1 number
Should be lesser than 100 characters
and thats it. I have not given any lower limit. And no matter what input I give (correct or incorrect), the program gives me the same or similar output as attached in my screenshot.
For eg:- Pratik10, pratik10, pratikten, pr#tiK10, I get the same output "Password is fine and valid".
Why is my program not checking the defined conditions correctly? It is not even printing the counters of the password correctly.
Following is my code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
int main()
{
char x[100];
int i;
int uc=0;
int lc=0;
int num=0;
int misc=0;
printf("enter your password\n");
scanf("%s",x);
for(i=0;i<100;i++) {
if (isalpha(x[i])) {
if (isupper(x[i])) {
uc++;
}
if (islower(x[i])) {
lc++;
}
}
if (isdigit(x[i])) {
num++;
}
else {
misc++;
}
}
printf("checking your password\n");
printf("%d uc\n",uc);
printf("%d lc\n",lc);
printf("%d num\n",num);
printf("%d misc\n",misc);
if ((uc > 0) && (lc > 0) && (num > 0) && (misc > 0)) {
printf("password is fine and valid\n");
}
else {
if(lc<=0) {
printf("lowercase character(s) missing cannot proceed without inclusion\n");
}
if(uc<=0) {
printf("uppercase character(s) missing cannot proceed without inclusion\n");
}
if(num<=0) {
printf("number(s) missing cannot proceed without inclusion\n");
}
if(misc<=0) {
printf("special character(s) missing cannot proceed without inclusion\n");
}
printf("please include all the missing parameters in combination to validate the password and try again\n\n");
}
return 0;
}
How to correct this?
Output:
The problem is that you are checking the whole array, which is mostly uninitialized and contains all kind of characters at random.
Therefore, you have to exit the loop when you encounter a '\0' character.
You should check only the null-terminated string provided as input by the user.
In other words, you should iterate x until you encounter the null-character.
Change this:
for (i = 0; i < 100; i++)
To this:
for (i = 0; x[i] != 0; i++)
A second problem is that you are not using if/else properly.
As a result, every character which is not a digit is counted as misc.
Change this:
if (isdigit(x[i]))
To this:
else if (isdigit(x[i]))
Other answers have mentioned the main problem. There is still one more problem: There is a missing else before if (isdigit(x[i])) {num++;},
for(i=0; x[i]!=0; i++)
{
if (isalpha(x[i]))
{
if (isupper(x[i])) {uc++;}
if (islower(x[i])) {lc++;}
}
else if (isdigit(x[i])) {num++;} // a missing else
else {misc++;}
}

Resources