Tagged: 

  • This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #170
    admin
    Keymaster
      
      
      #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))
              {
              newuppercase_array = ((((name - 65) + key)%26) + 65);
              }
              if (islower(name))
              {
              newuppercase_array = ((((name - 97) + key)%26) + 97);
              }
              else
              {
              newuppercase_array = name;
              }
              printf("%c",newuppercase_array);
          }
          printf("\n");
      }


      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]

    Viewing 1 post (of 1 total)
    • You must be logged in to reply to this topic.
    Scroll to Top