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

about printing a single character in an array without using for loop in c language

Recived blank screen output in c compiler when i used this simple code

what i need is to print a single specified character in array (without any type loop)

#include <stdio.h>
int main(void)
{
  int str[10] = {'h','e','l','l','o'};


  printf("\n%s", str[1]); //hoping to print e
  
  return 0;
}

sharing an article or something about it very appreciated

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

>Solution :

According to the documentation for the function printf, the %s format specifier is for printing a string. If you want to print a single character, you should use the %c format specifier instead:

#include <stdio.h>

int main(void)
{
    int str[10] = {'h','e','l','l','o'};

    printf( "%c\n", str[1] ); //hoping to print e
  
    return 0;
}

This program has the following output:

e

It is also worth nothing that it is normal to use the data type char instead of int, when dealing with integers representing characters:

char str[10] = {'h','e','l','l','o'};

Since we are now using char instead of int, we can also initialize the array from a string literal, which is simpler to type:

char str[10] = "hello";

Both declarations define an array of exactly 10 char elements, with the last 5 elements initialized to 0, i.e. a null character.

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