'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
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
