how to print an uppercase,lowercase and number in c - c

I'm in the middle of homework and I need some help here.
So this is the code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
int upper=0,lower=0,number = 0;
char ch[500];
printf("Enter the String:\n");
gets(ch);
i=0;
while(ch[i]!=0)
{
if(ch[i]>='A' && ch[i]<='Z')
{
upper++;
}
else if(ch[i]>='a' && ch[i]<='z')
{
lower++;
}
else if(ch[i]>='0' && ch[i]<='9')
{
number++;
}
i++;
}
printf("lowercase letters: %d",lower);
printf("\nuppercase letters: %d",upper);
printf("\nnumber letters: %d",number);
getch();
return 0;
}
As you can see here. When you give a string input. The code will give a total number of uppercase,lowercase and number
for example: If I'm giving "Hello World 123" To the code. The result will be 2 Uppercases 8 Lowercases and 3 Numbers
The problem is the task want me to print all 3 types of letter seperately
for example: from "Hello World 123" Should print "HW" , "elloorld" and "123"
I know that I have to create another 3 arrays for seperate the letter. I tried to create like upperc[i],lowerc[i] and num[i] to input the letter in each of if command but It doesn't work.
So how can I do that?

Here's one way of going about it. It doesn't require 3 separate arrays like you thought because it prints the characters directly:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
printf("Enter a string: ");
char str[1024] = {0};
fgets(str, sizeof str, stdin);
// Use different functions in each iteration
int (*ctype_fns[])(int) = {isupper, islower, isdigit};
for (unsigned i = 0; i < sizeof ctype_fns / sizeof *ctype_fns; ++i)
{
for (const char *it = str; *it; ++it)
{
// If char matches requirements, print it
if (ctype_fns[i]((unsigned char)*it))
putchar(*it);
}
putchar('\n');
}
}
Example of running:
Enter a string: Hello World 123
HW
elloorld
123

For your simple homework project you must assume some decent values. We assume the input is no longer than 128 characters and each of the three types is no more than 64. In real life projects we must check on these values.
Adapting your main, the following would work:
#include <stdio.h>
#include <stdlib.h>
#define MAX_IN 128
#define MAX_X 64
int main()
{
int i;
int upper=0,lower=0,number = 0;
char ch[MAX_IN], chUpper[MAX_X], chLower[MAX_X], chNumber[MAX_X];
printf("Enter the String:\n");
gets(ch);
i=0;
while(ch[i]!=0)
{
if(ch[i]>='A' && ch[i]<='Z')
{
chUpper[upper++]= ch[i];
}
else if(ch[i]>='a' && ch[i]<='z')
{
chLower[lower++]= ch[i];
}
else if(ch[i]>='0' && ch[i]<='9')
{
chNumber[number++]= i;
}
i++;
}
chLower[lower]= '\0';
chUpper[upper]= '\0';
chNumer[number]= '\0';
printf("lowercase letters: %d: %s\n",lower, chLower);
printf("uppercase letters: %d: %s\n",upper, chUpper);
printf("number letters: %d: %s\n",number, chNumber);
getch();
return 0;
}

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_IN 128
#define MAX_X 64
int main()
{
int i;
int upper=0,lower=0,number = 0;
char ch[MAX_IN], chUpper[MAX_X], chLower[MAX_X], chNumber[MAX_X];
printf("Enter the String:\n");
gets(ch);
printf("input given is : %s\n",ch);
for (i=0;ch[i]!='\0';i++)
{
if(ch[i]>='A' && ch[i]<='Z')
{
chUpper[upper++]= ch[i];
}
else if(ch[i]>='a' && ch[i]<='z')
{
chLower[lower++]= ch[i];
}
else if(ch[i]>='0' && ch[i]<='9')
{
chNumber[number++]= ch[i];
}
if ((ch[i+1]) == ' '){
i += 1;
}
}
printf("lowercase letters: %d: %s\n",lower, chLower);
printf("uppercase letters: %d: %s\n",upper, chUpper);
printf("number letters: %d: %s\n",number, chNumber);
return 0;
}

Related

Palindrome program in C

My program in C which is Palindrome has an error in its function. My function is not comparing the 2 characters in my string. When I type a single character it answers palindrome but if it is two or more always not palindrome.
Code:
int IntStrlength=strlen(StrWord);
int IntCtr2=0;
int IntCtr=1, IntAnswer;
while(IntCtr<=(IntStrlength/2)){
printf(" %d %d\n", IntCtr2,IntStrlength);
if(StrWord[IntStrlength] != StrWord[IntCtr2]){
IntAnswer=0;
printf(" %d=Not Palindrome", IntAnswer);
exit (0);
}//if(StrWord[IntCtr2]!=StrWord[IntStrlength]) <---------
else{
IntCtr2++;
IntStrlength--;
}// else <--------
IntCtr++;
}//while(IntCtr<IntStrlength/2) <-----------
IntAnswer=1;
printf(" %d=Palindrome", IntAnswer);
return ;
}
Single character:
Two or more characters:
Why not write it like this
int wordLength = strlen(StrWord);
for (int i=0;i<(wordLength/2);i++) {
if (StrWord[i] != StrWord[wordLength-i-1]) {
return 0;
}
}
return 1;
For words with an even length (say 8) the counter will go from 0 to 3, accessing all letters. For uneven words (say 7) the c ounter will go from 0 to 2, leaving the middle element unchecked. This is not necessary since its a palindrome and it always matches itself
#include<stdio.h>
int check_palindrom(char *);
int main()
{
char s1[20];
printf("Enter the string...\n");
gets(s1);
int x;
x=check_palindrom(s1);
x?printf("Palindrom\n"):printf("Not Palindrom\n");
}
int check_palindrom(char *s)
{
int i,j;
for(i=0;s[i];i++);
for(i=i-1,j=0;i>j;i--,j++)
if(s[i]!=s[j])
return 0;
if(s[i]==s[j])
return 1;
}
Enter the string...
radar
Palindrom
I've seen this algorithm before in a interview book called "Cracking the Coding Interview".
In it the author shows a very simple and easy implementation of the code. The code is below: Also here is a video explaining the code.
#include<stdio.h>
#include<string.h> // strlen()
void isPalindrome(char str[]);
int main(){
isPalindrome("MOM");
isPalindrome("M");
return 0;
}
void isPalindrome(char str[]){
int lm = 0;//left most index
int rm = strlen(str) - 1;//right most index
while(rm > lm){
if(str[lm++] != str[rm--]){
printf("No, %s is NOT a palindrome \n", str);
return;
}
}
printf("Yes, %s is a palindrome because the word reversed is the same \n", str);
}
You can do this like this:
#include <stdio.h>
#include <string.h>
int check_palindrome(char string []);
int main()
{
char string[20];
printf("Enter the string...\n");
scanf ("%s", &string);
int check;
check = check_palindrome (string);
if (check == 0)
printf ("Not Palindrome\n");
else
printf ("Palindrome\n");
return 0;
}
int check_palindrome (char string [])
{
char duplicate [];
strcpy (string, duplicate);
strrev (string);
if (strcmp (string, duplicate) == 0)
return 1;
else
return 0;
}
This uses the strcmp and strrev function.
Take a look at this code, that's how I have implemented it (remember to #include <stdbool.h> or it will not work):
for(i = 0; i < string_length; i++)
{
if(sentence[i] == sentence[string_lenght-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
Doing that it will check if your sentence is palindrome and, at the first occurence this is not true it will break the for loop. You can use something like
if(palindrome)
printf(..);
else
printf(..);
for a simple prompt for the user.
Example :
radar is palindrome
abba is palindrome
abcabc is not palindrome
Please , pay attention to the fact that
Abba
is not recognized as a palindrome due to the fact that ' A ' and 'a' have different ASCII codes :
'A' has the value of 65
'a' has the value of 97
according to the ASCII table. You can find out more here.
You can avoid this issue trasforming all the characters of the string to lower case characters.
You can do this including the <ctype.h> library and calling the function int tolower(int c); like that :
for ( ; *p; ++p) *p = tolower(*p);
or
for(int i = 0; str[i]; i++){
str[i] = tolower(str[i]);
}
Code by Earlz, take a look at this Q&A to look deeper into that.
EDIT : I made a simple program to do this, see if it can help you
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
void LowerCharacters(char *word, int word_lenth);
int main(void){
char *word = (char *) malloc(10);
bool palindrome = false;
if(word == 0)
{
printf("\nERROR : Out of memory.\n\n");
return 1;
}
printf("\nEnter a word to check if it is palindrome or not : ");
scanf("%s", word);
int word_length = strlen(word);
LowerCharacters(word,word_length);
for(int i = 0; i < word_length; i++)
{
if(word[i] == word[word_length-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
palindrome ? printf("\nThe word %s is palindrome.\n\n", word) : printf("\nThe word %s is not palindrome.\n\n", word);
free(word);
return 0;
}
void LowerCharacters(char *word, int word_length){
for(int i = 0; i < word_length; i++)
word[i] = tolower(word[i]);
}
Input :
Enter a word to check if it is palindrome or not : RadaR
Output :
The word radar is palindrome.
This code may help you to understand the concept:
#include<stdio.h>
int main()
{
char str[50];
int i,j,flag=1;
printf("Enter the string");
gets(str);
for(i=0;str[i]!='\0';i++);
for(i=i-1,j=0;j<i;j++,i--)
{
str[i]=str[i]+str[j];
str[j]=str[i]-str[j];
str[i]=str[i]-str[j];
}
for(i=0;str[i]!='\0';i++);
for(i=i-1,j=0;j<i;j++,i--)
{
if(str[i]==str[j]){
flag=0;
break;
}
}if(flag==0)
{
printf("Palindrome");
}else
{
printf("Not Palindrome");
}
}
I have solution for this
char a[]="abbba";
int i,j,b=strlen(a),flag=0;
for(i=0,j=0; i<b; i++,j++)
{
if(a[i]!=a[b-j-1])
{
flag=1;
break;
}
}
if(flag)
{
printf("the string is not palindrum");
}
else
{
printf("the string is palindrum");
}
This may works for you
#include <stdio.h>
#include <stdlib.h>
int main(void) {
setbuf(stdout,NULL);
int i,limit;
char string1[10];
int flag=0;
printf("enter a string");
scanf("%s",string1);
limit=strlen(string1);
for(i=0;i<limit;i++){
if(string1[i]!=string1[limit-i-1]){
flag=1;
break;
}
} if(flag==1){
printf("entered string is not palindrome");
}else{
printf("entered string is palindrome");
}
return EXIT_SUCCESS;
}

How to remove multiple trailing newlines after fgets()?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
int upper=0;
int digit=0;
int i=0;
char s[30];
char c;
printf("Enter sentence: ");
fgets(s, 30, stdin);
//s[strlen(s) - 1] = '\0';
while(c=getchar() && c!='\n')
{
c = s[i];
if(isupper(c))
{
upper++;
}
if(isdigit(c))
{
digit++;
}
i++;
}
printf("Number of upper case letters............... %d", upper);
printf("\n");
printf("Number of digits........................... %d", digit);
printf("\n");
printf("Program done. ");
return 0;
system("PAUSE");
}
How can I remove the multiple newlines after the fgets() ?
I have tried implementing the following line after fgets()
s[strlen(s) - 1] = '\0';
but this does not work and my program does not run through all the code.
Without the code -----> s[strlen(s) - 1] = '\0';
Here is the Output:
Enter sentence: Whats UP 1234
Number of upper case letters............... 3
Number of digits........................... 4
Program done.
Process returned 0 (0x0) execution time : 9.340 s
Press any key to continue.
As you can see my program is able to run however I have to press enter multiple times and there is a lot of newlines
and then at the very end the program runs the last bit of code.
The program is suppose to count the number of upper case letters and digits in the string
entered. Can someone please explain why this is happening ?
Thanks to Jongware:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
int upper=0;
int digit=0;
int i=0;
char s[30];
char c;
printf("Enter sentence: ");
fgets(s, 30, stdin);
//correction: getchar() has been removed from the while condition.
while( c!='\n')
{
c = s[i];
if(isupper(c))
{
upper++;
}
if(isdigit(c))
{
digit++;
}
i++;
}
printf("Number of upper case letters............... %d", upper);
printf("\n");
printf("Number of digits........................... %d", digit);
printf("\n");
return 0;
system("PAUSE");
}

C programming Hex to Char

What I'm trying to do is have the user input a hex number this number will then be converted to a char and displayed to the monitor this will continue until an EOF is encountered.I have the opposite of this code done which converts a char to a hex number. The problem I'm running into is how do i get a hex number from the user I used getchar() for the char2hex program. Is there any similar function for hex numbers?
this is the code for the char2hex program
#include <stdio.h>
int main(void) {
char myChar;
int counter = 0;
while (EOF != (myChar = getchar())) {
/* don't convert newline into hex */
if (myChar == '\n')
continue;
printf("%02x ", myChar);
if (counter > 18) {
printf("\n");
counter = -1;
}
counter++;
}
system("pause");
return 0;
}
this is what i want to the program to do except it would do this continuously
#include <stdio.h>
int main() {
char myChar;
printf("Enter any hex number: ");
scanf("%x", &myChar);
printf("Equivalent Char is: %c\n", myChar);
system("pause");
return 0;
}
any help would be appreciated
thank you
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void) {
int myChar;
int counter = 0;
char buff[3] = {0};
while (EOF != (myChar = getchar())) {
if(isxdigit(myChar)){
buff[counter++] = myChar;
if(counter == 2){
counter = 0;
myChar = strtol(buff, NULL, 16);
putchar(myChar);
}
}
}
printf("\n");
system("pause");
return 0;
}
Because chars and ints can be used interchangably in C, you can use the following code:
int main(void) {
int myChar;
printf("Enter any hex number: ");
scanf("%x", &myChar);
printf("Equivalent Char is: %c\n", myChar);
system("pause");
return 0;
}
If you want it to loop then just enclose it in the while loop as in your example code.
Edit: You can try out the working code here http://ideone.com/yyvz85

Arrays in a Palindrome program

So I made a program where I have to input a word and it displays if it is a palindrome (a word that is the same both ways) or not.
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[]){
char word;
int length, counter;
printf("Please enter a word: ");
scanf("%c", &word);
int flag = 1;
for (counter = 0; counter < length && flag; counter++) {
printf("%c\t %c", word[counter], word[length - counter])
if (word[counter] == word[length - counter - 1]){
flag = 0;
}
}
if (flag) {
printf("%c is a palindrome!", word);
}
else {
printf("%c is NOT a palindrome!", word);
}
}
I set it up so that it displays each letter side by side. If a letter isn't the same then the flag is "thrown"(set to 0) and this will end the program saying: "word is NOT a palindrome!"
I get an error at the part where it says word[counter] saying it isn't a subscripted value. What can I do to make this work? Is there anything else I am doing wrong?
This char word; is not an array. This char word[100]; is an Array. Also you read a single character using scanf("%c", &word); not a word (as in a string or series of characters). Use:
fgets (word , 100 , stdin)
Also length is not initialized, so it will lead to UB.
Make this modifications in your program.It will run fine.
#include <stdio.h>
#include <string.h>
int main()
{
char word[100];
int length, counter;
printf("Please enter a word: ");
scanf("%s",word);
length=strlen(word);
int flag = 1;
for(counter = 0; counter < length/2 && flag; counter++)
{
if (word[counter] != word[length-counter-1])
{
flag = 0;
break;
}
}
if (flag)
{
printf("%s is a palindrome!\n", word);
}
else {
printf("%s is NOT a palindrome\n!", word);
}
}
****************************************************************
* Simple Array Palindrome Program *
****************************************************************/
#include <iostream>
using namespace std;
int main (){
int arr_size;
int flag=0;
/*****************************************
* Array Size *
*****************************************/
cout<<"Enter The Array Size: \n->arr[";
cin>>arr_size;cout<<" ]";
int arr[arr_size];
/*****************************************
* User_Input *
*****************************************/
for(int i=0;i<arr_size;i++){
cout<<"Enter Value For Arr[ "<<i<<" ] -> ";
cin>>arr[i];
}
/*****************************************
* Palindrome_Check *
*****************************************/
for(int k=0,j=arr_size-1;k<arr_size && j>-1;k++)
{
if(arr[i]==arr[j];
{
flag++;
}
}
/*****************************************
* Flag Check *
*****************************************/
if(flag==arr_size) {
cout<<"Array Is Palindrome: ";
}
else
{
cout<<"Array Is Not Palindrome: ";
}
}

Program which count chars of selected word

Its a homework, sorry for that.
I can't make working program for counting chars in word, for an example:
I enter the String : My name is peter
The program asks which word to process..
I enter the number : 3
Program says : Count of the Third word is 2.
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char text[200],vards[20];
int i, length,lengthv, count=0,x;
printf("insert txt\n");
gets(text);
length=strlen(text);
for(i=0; i<length; i++)
{
if(text[i]!=' ' && text[i]!='.' && text[i]!=',')
{
printf("%c", text[i]);
if (text[i+1]=='\0')
count++;
}
else
{
if(text[i-1]!=' ' && text[i-1]!='.' && text[i-1]!=',')
{
count++;
printf("\n");
}
}
}
printf("detect lenght of wich name\n");
for(i=0;i<x;i++);
scanf("%s", &text);
lengthv=strlen(vards);
printf("\n The lenght of name is %d", lengthv);
getch();
return 0;
}
I can't really understand your code, but here is how I would do it:
#include <stdlib.h>
#include <stdio.h>
int main() {
char text[200], whichText[200];
int i=0, length, countWord=0, currWord=1, wordChars=0;
// Get text input:
printf("insert txt\n");
gets(text);
length=strlen(text);
// Get word to count:
while(countWord == 0) {
printf("Count which word?\n");
gets(whichText);
sscanf(whichText, "%i", &countWord);
}
// Iterate through each character of the text input:
for( i=0; i < length; i++ ) {
// Keep track of which word we are on, by counting spaces:
if( text[i] == ' ' ) {
currWord ++;
continue;
}
// While we are on the desired word, count the characters:
if( currWord == countWord )
wordChars ++;
}
printf("Count of word %i is %i.\n", countWord, wordChars);
return 0;
}

Resources