Entering a letter then minus to the alphabet - c

i am making a program that discard a letter from a list if you enter a letter, can anyone help me. thanks.
in example:
(BEFORE)
ABCDEFGHIJKLMNOPQRSTUVWXYZ
enter a letter: A
(AFTER ENTERING A LETTER 'A')
_BCDEFGHIJKLMNOPQRSTUVWXYZ
enter a letter:
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <windows.h>
int main()
{
int alphabet[26];
char letter;
int i;
int j;
alphabet[0] = 'A';
for(i = 0;i < 26; i++)
{
alphabet[i] = alphabet[0];
printf ("%c", alphabet[i], alphabet[i]);
alphabet[0]++;
}
printf("\n\nenter the letter you want to remove in the alphabet: ");
scanf("%c", letter);
while(j<alphabet[i])
{
if(letter==alphabet[i])
{
j--;
}
}
}
The problem is its not removing the letter in the alphabet when i entered the letter i want to remove. please help. thanks.
EDIT: one last thing, how can i make it only one input?, i mean if i input the same letter in 2nd time it will said "you already input that letter".

You are assuming that the letters are contiguos, as in ASCII, but you cannot assume that in C.
The next line has a duplicated argument:
printf ("%c", alphabet[i], alphabet[i]);
Drop the last alphabet[i].
Your last if() sentence is wrong: the comparisson must be done with ==.
It is not clear at all what do you want to do.
EDIT:
I would do the program in this way:
#include <stdio.h>
int main()
{
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char letter;
printf("Choose a letter: ");
letter = getchar();
printf("\n\n");
for(int i = 0; i < 26; i++)
if (letter == alphabet[i])
{
alphabet[i] = '_';
break; /* This terminates the for() loop */
}
printf("Result: %s \n", alphabet);
}
EDIT2: I have changed the declaration of alphabet, because the string constant has to be modified later...

you are assigning a value to letter with the the statement
letter=alphabet[i]
this statement will always be true, unless alphabet[i] is 0.
use comparision instead
letter==alphabet[i]
also your while loop is a bit weird, as the value of j will be undefined in the beginning , so your comparision will be undefined.
while(j<alphabet[i])
{
if(letter=alphabet[i])
{
j--;
}
probably you simply want to do something like:
for(i = 0;i < 26; i++) {
if(alphabeth[i]==letter) {
alphabeth[i]='_';
}
}
if you only want to replace the first occurence of the letter, insert a break; after alphabeth[i]='_';
and you probably don't want to have magic values like "26" occuring multiple times in your sourcecode.
instead use something like
#define ALPHABETSIZE 26
and replace all occurences of 26 by ALPHABETSIZE

There are a few things here that you are doing to make it hard for yourself.
You need to use "==" not "=" to compare two variables
Your value for "j" is not initialised so "j--" would be undefined
Its probably better to keep all your types the same and make the array a "char" array not an "int" array.
To remove an element from your array "int alphabet[26];" would be very difficult, it would probably be easier to make this a "string" exercise. All you can really do is to make a "blank" letter by
alphabet[j] = ' ';
I think its possible to make a better design though if you explain your requirements more clearly :)

If I got you right you want to go through your array and check if the entered char matches any in the array.
Is there any reason, why you dont use a for-loop like this and set the array position to 0 instead of the while statement?
for(i=0;i<26;i++)
{
if(letter == alphabet[i])
alphabet[i] = "_"; // or setting it to 0 if you use and int-array
}
Or do I get something wrong here?

Related

Why are there random characters outputting in my code?

I have been writing a program to input a phrase and turn it into an acronym. For some reason when I output my acronym at the moment it comes out with a bunch of random characters. How do I fix it?
#include <stdio.h>
#include <string.h>
#define MAXLEN 50
int main() {
int num;
printf("Enter number of acronyms to add to the database:");
scanf("%d", &num);
getchar();
char strings[num][MAXLEN];
char acronym[num][MAXLEN];
for(int i = 0; i < num; i++){
printf("Enter the string to convert into an acronym:");
fgets(strings[i],MAXLEN,stdin);
printf("%s\n", strings[i]);
for(int j = 0; j < 11; j++){
if((strings[i][j]) >= 'A' && (strings[i][j]) <= 'Z'){
char buffer[][20] = {strings[i][j]};
strcat(acronym[i], buffer[i]);
}
}
puts(acronym[i]);
}
return 0;
}
I have tried changing the MAXLEN value to see if it was a memory issue or like a buffer overload. I've also just tried changing around how the strings switch and work together but nothing has worked.
char buffer[][20] = {strings[i][j]};
Here you let the compiler count how many elements the array has from the initialization.
It has 1 element, A string with single a single character strings[i][j] and rest of the 20 byte array filled with 0.
strcat(acronym[i], buffer[i]);
Here you access buffer[i], but there is only one string there (as explained above), so this is invalid if i is anything but 0.
I'm not sure what you are trying to do, but this would be valid implementation of what this code tries to do:
// extract single character as a string
char buffer[2] = {strings[i][j], 0}; // only one of 2 and 0 is mandatory
// append it to acronym
strncat(acronym[i], 20, buffer);
Probably lots of other stuff there is wrong, but here is one definite issue and a possible solution.

Output not showing in C

I'm writing a code that must identify the letter 't' or 'T' in a word, before or after the middle of it.
If the first half of the word does contain a 't' or a 'T', the program should output a 1. If the first half does not contain the letter 't' or 'T', but the second half does, then the program should output a 2. Otherwise, if there is no 't' or 'T' in the word at all, the program's output should be -1. The word entered will not have more than 50 letters.
#include <stdio.h>
#include <string.h>
int main() {
char word[50];
int i = 0, length, t = 0, T = 0;
scanf("%s", word);
length = strlen(word);
t = word[i] == 't';
T = word[i] == 'T';
while(!t || !T) {
if((t || T) && i <= length / 2) {
printf("%d", '1');
} else if((t || T) && i > length / 2) {
printf("%d", '2');
//}else{
// printf("%d", '-1');
}
i++;
}
return 0;
}
If I enter any word and press enter, nothing is printed. Another thing is that when I remove the comment slashes from the two lines at the bottom, the program goes through an infinite loop.
Could someone please help?
This sounds like a school assignment, so I'll focus on advising/critiquing your code rather than giving a solution.
The first recommendation I have is to use a for loop instead of a while loop. A Rule of thumb in C is to only use a while loop when you actually don't have any idea how many things you need your program to look at.
You already have the length of the string, so set up your for loop to loop exactly once for each character.
Next you need to change how you are using printf. The %d format specifier is for printing integers, but you are passing it '1'. This is not an integer, it is the ascii representation of the symbol 1 (which is actually has the value 49, see the ascii table for more info)
You can either pass printf the value 1, or use the %c specifier, which expects ascii characters.
Better yet, just say printf("1");
That doesn't get you all the way there, but I think it lays the ground work so you can find the solution!
Condition !t || !T has no sense to be used as loop condition ...ask yourself how the loop will end ? you need just to check i is less than length
Second, the assignments t = word[i] == 't'; T = word[i] == 'T'; outside the loop have no sense ...you will be just pointing to the zero index of the string ...you should check all characters
third , the printf lines need to use %d
fourth , you appear not getting the purpose of the program printing inside loop will lead to printing many numbers and you just want to know if there is t or T you need to print single line.you may use variable int result=0; to hold the value you want and print it in the end ...of course you will need using break statement in the if((t || T) && i <= length / 2) and if((t || T) && i > length / 2) because no need for more searching
fifth, you should re-read , re-think , re-code the assignment before going bored and asking about it
sixth, there is a working version by modifying your code but you should try writing a good solution before looking at a solution as it better to solve your problems by yourself
#include <stdio.h>
#include <string.h>
int main() {
char word[50];
int i = 0, length, t = 0, T = 0;
scanf("%s", word);
length = strlen(word);
int result=0;
while( i<length) {
t = word[i] == 't';
T = word[i] == 'T';
if((t || T) && i <= length / 2) {
result=1;
break;
} else if((t || T) && i > length / 2) {
result=2;
break;
}else{
result=-1;
}
i++;
}
printf("%d",result);
return 0;
}
# include <stdio.h>
int main()
{
char name[20];
int age;
int siblings;
int childrens;
printf ("Hello my name is A.I, what is your name? \n");
scanf("%s", &name);
printf("how old are you : \n");
scanf("%d",&age);
printf("how many siblings you have: \n");
scanf("%d", &siblings);
printf("how many children you have: \n");
scanf("%d", &childrens);
printf("so your name is : %s \n", name);
printf("and your age is : %d \n", age);
printf("you have siblings : %d\n", siblings);
printf("so you have childrens : %d\n", childrens);
return 0;
}

Can anyone tell me what's wrong with my Caesar algorithm?

The output is wonky when I use numbers 4-22, and I can't figure out why. Help would be greatly appreciated, and I would also like to know why this does not work.
#include<cs50.h>
#include<stdio.h>
#include<string.h>
int main(void)
{
int shifts;
int enc;
printf("What is your message ");
string message = get_string();
printf("By how many letters do you want to shift?");
scanf("%d",&shifts);
for(int i=0;i<strlen(message);i++)
{
enc=((message[i] - 89)+shifts)%26;
printf("%c",enc + 89);
}
printf("\n");
}
Inside the for loop you should check whether the character is uppercase, lowercase or neither. The number 89 is also wrong, that is 'Y', what you probably want is 65 or 97, 'a' and 'A' respectively. The for loop should be changed to be something like:
#include <ctype.h> // For isupper()/islower()
for(int i = 0; i < strlen(message); i++)
{
if(isupper(message[i])) { // Check if current char is uppercase
enc=((message[i] - 'A')+shifts)%26; // Apply cipher
printf("%c",enc + 'A');
} else if(islower(message[i])) { // Check if current char is lowercase
enc=((message[i] - 'a')+shifts)%26; // Apply cipher
printf("%c",enc + 'a');
} else { // Print char without change
printf("%c", message[i]);
}
}
Note the use of 'A' and 'a' instead of 65 and 97, these will translate to the corresponding integer literals at compile time. There are other ways to write this, this probably isn't even the most clean way to do it (multiple printf()s for example), but it should illustrate how this works and should be done.

How to remove an element in a character array or create a copy of a new array without specific elements?

The objective of my assignment is to take in user input string and then print out the English alphabetic characters (both lower case and upper case) that the user has entered.
For example if the user inputs:D_!an!_ i12el the output would be Daniel.
My approach was to loop through the input and just remove all the non alpha characters but I dont know how to.Please help with any ideas! This is what I have so far:
#include <stdio.h>
#include <string.h>
int main()
{
char my_array[100];
printf("Enter a message: ");;
while(strlen(gets (my_array)) == 0);
printf(" Your message is: %s\n", my_array);
for(int i = 0; i< strlen(my_array);i++)
{
if(my_array[i] < 'A' || my_array[i] > 'z')
{
my_array[i] = ' ';
}
}
printf(" Your new message is: %s\n", my_array);
}
EDIT:I got my loop working to print out only the alpha characters but it keeps adding extra characters when i print the elements. For example D_!a_*&Ni#32el becomes DaNielASCIIV. I dont know why this is happening.
for(int i = 0; i< 100;i++)
{
if (isalpha(message[i]))
{
putchar(message[i]);
}
}
Rather than trying to update the string you have, just print out a character if it's a letter.
Also, upper case and lower case characters don't immediately follow one another, so you need to check for them separately:
printf(" Your new message is: ");
for(int i = 0; i< strlen(my_array);i++)
{
if((my_array[i] >= 'A' && my_array[i] <= 'Z') ||
(my_array[i] >= 'z' && my_array[i] <= 'z'))
{
putchar(my_array[i]);
}
}
printf("\n");
Alternetely, you could replace the above if condition with a function that checks for this:
if (isalpha(my_array[i]))
EDIT:
The reason you're now seeing extra characters is because you changed the loop to loop over the entire array instead of the length of the string. Go back to using strlen(my_array) instead of 100 and you'll be fine.
Use this pattern for removing elements from an array
int i, j;
j = 0;
for (i=0;i<N;i++)
if (good(array[i]) )
array[j++] = array[i];
N = j;
We go through, adding everything that matches. It's efficient and in-place.
It might be better to loop through the input string and use strchr() to see if the characters are in the string "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz". This has the advantages of not relying on a specific ordering for of the letters of the alphabet (see here and here), and being flexible so that you can easily change the characters that you want to pick out. You could then collect the results in a string, or print the filtered characters out directly.
char my_array[100];
char filtered_array[100];
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
char *pchar;
int j = 0;
...
for (int i = 0; i < strlen(my_array); i++)
if ((pchar = strchr(alphabet, my_array[i])) != NULL) {
filtered_array[j] = *pchar;
++j;
}
filtered_array[j] = '\0';
...
The above code collects the results in a string. Note that a null-terminator is added to the end of filtered_array[], since this character would not be copied to the new array. If you want to include spaces or hyphens in the filtered string, just add these characters to the alphabet[] string.

How to approach this exercise? (C)

"Have a program request the user to enter an uppercase letter. Use nested loops to produce a pyramid pattern like this:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
The pattern should extend to the character entered. For example, the preceding pattern would result from an input value of E."
So far I've been doing this for a good few hours and I'm getting the 'pyramid' to format properly for the letters when iterating forwards through the alphabet with:
#include <stdio.h>
int main(void)
{
char ch = 0;
char ch2 = 0;
int rows = 0;
printf("Enter a character: ");
scanf("%c", &ch);
rows = ch - 64;
while(rows > 0)
{
int spaces;
for(spaces = rows-1; spaces > 0; spaces--)
{
printf(" ");
}
ch2 = 65;
while(ch2 < (ch-(rows-2)))
{
printf("%c", ch2);
ch2++;
}
printf("\n");
rows--;
}
}
However, I feel as though I've hit a brick wall with trying to get it to iterate backwards properly. I know it should only be a few basic loops but I'm well and truly stuck. I'm sure it's easy... I think I've just been looking at it too long. Ideas?
You are so close, you only need to take a breath and you'll see it.
When you print out your character, it has to be done after this part
while(ch2 < (ch-(rows-2)))
{
printf("%c", ch2);
ch2++;
}
or it won't fall at the end of the string. What you need is another loop that starts at the character that's one below the last character printed. It should print a character and decrement that character until it has printed the 'A' character.
Since this is homework, I'll give you a chance to write that loop before telling you the exact details.
There are ways this code could probably be rewritten to make it clearer, but basing on what you have, something like this would probably work right after your current while loop.
while (ch2 > 'A')
{
ch2--;
printf("%c", ch2);
}
I do recommend attempting to refactor your code a bit to make it clearer, though. As I suggested in a comment, start off by using character literals rather than raw integers.
You can iterate down as well as up:
while(ch2 >= 'A')
{
printf("%c", ch2);
ch2--;
}
Try this:
#include <stdio.h>
int main (int argc, const char * argv[])
{
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if(ch<'A' || ch>'Z'){
printf("Character must be between 'A' and 'Z'\n");
return 1;
}
for(int rows = ch - 'A'; rows >= 0; rows--)
{
char ch2;
for(int spaces = rows; spaces > 0; spaces--)
printf(" ");
for(ch2='A'; ch2 < (ch-(rows-1)); ch2++)
printf("%c", ch2);
for(ch2=ch2-2;ch2>='A';ch2--)
printf("%c", ch2);
printf("\n");
}
return 0;
}

Resources