I'm not sure why this if statement isn't work

94 views Asked by At

Why isn't this working?

I think the logic in this if statement is flawed but I'm sure exactly what's wrong.

edit: i forgot to add the header files as well as int main(void). everything should be there now

int main(void){
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
string word = "APPPLE";
string alphabet[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", 
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};


    if (word[0] == alphabet[0])
    {
        printf("this program works");
    }
}

                  
2

There are 2 answers

1
Vlad from Moscow On BEST ANSWER

The pointer word (string is a typedef for the type char *) points to the first character of the string literal "APPLE".

string word = "APPPLE";

So the expression word[0] has type char.

Elements of the array alphabet point to another string literals.

string alphabet[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", 
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

and have the type string that is char *.

In the if statement you are trying to compare a character words[0] with a pointer alphabet[0]

if (word[0] == alphabet[0])
{
    printf("this program works");
}

that does not make a sense.

What you need is the following

if (word[0] == alphabet[0][0])
{
    printf("this program works");
}

Though it would be better to declare the array alphabet like

string alphabet = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};

In this case the if statement will look like

if (word[0] == alphabet[0])
{
    printf("this program works");
}
2
susritha kakarla On

There is no in-built name called "string" in C. Instead, a character array is used for handling strings. The following code might help you.

#include <stdio.h>

int main() {

     char word[] = "APPPLE";

     char alphabet[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

     if (word[0] == alphabet[0]) 

        printf("this program works");

    return 0;
}