Home > Back-end >  C program that reads five strings and only prints strings that begin with the letter 'a'
C program that reads five strings and only prints strings that begin with the letter 'a'

Time:12-04

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

#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')

CodePudding user response:

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

  •  Tags:  
  • c
  • Related