Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
    }
}

                  

>Solution :

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");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading