Strings in c language with examples | Reading and displaying a string variable in C | Initialization of a string variable in C
String is group of one or more characters within double quotes (“).
Example: “Lovejot” , “2019” , “Rs4000”, “[email protected]”
1. What is a String variable in C ?
An array of char type is known as a string variable.
Example: char name[20];
In this example, sname is a string variable which can contain maximum 19 characters.
2. Initialization of a string variable in C
There are two ways to initialize a string varible:
a. The first way to initialize a string variable is
char name[]={‘S’,’u’,’m’,’i’,’t’};
Above examples contains string variable name having value “Sumit”.
b. The second way to initialize a string variable is
char name[]=”Sumit”;
Program to initialize a string variable in C |
#include<stdio.h> int main() { char name[]="Sumit"; //char studentname1[]={'S','u','m','i','t'}; printf("\nname=%s",name); return(0); } |
Output |
name=Amita |
3. Reading and displaying a string variable in C
We can read and display a string variable just as we read a normal variable of C Language.
Program to read and display a string variable in C. |
#include<stdio.h> int main() { char sname[30]; printf(“Enter name=”); gets(sname); printf("\nsname=%s",sname); return(0); } |