IT, Programming, & Web Development › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 2: [Arrays] – Functions, Variable and Scope, Debugging, Arrays, and Command Line Arguments › Caesar: Uppercase not converting to cipher text possibly due to wrong if, else usage
Tagged: if else in c
- This topic is empty.
-
AuthorPosts
-
January 27, 2022 at 8:07 am #170
[dm_code_snippet background=”yes” background-mobile=”no” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
#include<stdio.h> #include<cs50.h> #include<string.h> #include<ctype.h> int main(void) { string name = get_string("Enter: "); printf("Entered text by user: %s\n", name); int n = strlen(name); printf("length of entered text: %i\n", n); int key = get_int("enter key: "); char newuppercase_array[n]; for (int i = 0; i < n; i++) { if (isupper(name[i])) { newuppercase_array[i] = ((((name[i] - 65) + key)%26) + 65); } if (islower(name[i])) { newuppercase_array[i] = ((((name[i] - 97) + key)%26) + 97); } else { newuppercase_array[i] = name[i]; } printf("%c",newuppercase_array[i]); } printf("\n"); }
[/dm_code_snippet]
Reply
https://edstem.org/us/courses/176/discussion/1049000
Yes. It is because of how you’ve done your if else statements. In your code, you have two independent if statements. The first if statement checks if the character is an upper case alphabet. However, there is no else statement for this logic test. What happens then, is that regardless of whether or not the char has passed this first if statement, it will always run your second if statement.
The problem is that your second if statement has an else after it. Thus, when the character fails the second if statement, it will always run the else statement.
If we take the char ‘A’ for example, it is clearly an uppercase letter. Your code will run the first if statement to check if it is upper case, which it will pass therefore it will execute the rest of the code that is in the if statement. Since the next code block after the first if statement is also an if statement, it will also run this check. ‘A’ will fail the second if statement because it is obviously not a lower case letter. However, because the second if statement has an else, it will then run the else code (since it did not pass the if statement). Your code is actually setting the correct value for the capital letters in the string, and then failing the 2nd if statement and then setting it right back to the original.
Side note: you don’t need to create the newuppercase_array because you can access and change the characters in a string individually by accessing their index (name[0] = ‘A’ in your code will turn the first character in the string called name into an ‘A’.)
[learn_press_profile]
-
AuthorPosts
- You must be logged in to reply to this topic.