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

C program that reads five strings and only prints strings that begin with the letter 'a'

I’m new to programming and cant figure out what I’m doing wrong.

From the 5 given strings I’m trying to print only strings that begin with the character ‘a’.

This is what i have done so far

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

#include <stdio.h>


int main()
{
char str[5][100];
int i;

//For loop asks user to input 5 strings
for(i=0;i<5;i++)
{
   printf("\nEnter line > ");
   scanf("%s", str[i]);
    
}
for(i=0;i<5;i++)
{
 //To check if the first character in a string is 'a'
    if(!str[0]=='a')
    {
        printf("\n%s", str[i]);
    }
    
}

return 0;
}

This part is not working. In my mind its supposed to check the first letter of every string but its not doing that. Instead the program doesn’t print out anything when this if statement is there.

   if(!str[0]=='a')

>Solution :

In your if statement, you need to remove the ! character and access the first element of the string i like this:

   if(str[i][0]=='a')

Your are accessing the pointer to the first string which will be a random memory address. If you access the first value, you will need to access two array elements: First the correct character array (string) by using [i] and then the character you want to test [0]

The ! in front of the first value will turn any non-zero value to zero and a zero into a one (logical negation). Therefore you are always testing

if(0 == 'a')

which is always false

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