Strings in c language with examples | Reading and displaying a string variable in C | Initialization of a string variable in C

You must first complete Display output in C – printf() function before viewing this Lesson

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 data type is known as a string variable.

Syntax 

char var[size];

char is the data type to declare a string variable .

var is the name of string variable.  It must follow all the rules of valid identifier of C language.

[ ] Square brackets are necessary to declare a string variable.

size is the maximum number of characters that can be stored in the 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 variable:

a. The first way to initialize a string variable is

char var[Size]={Sequence of characters};

char is the data type to declare a string variable .

var is the name of string variable.

[ ] Square brackets are necessary to declare a string variable.

size is the maximum number of characters that can be stored in the string variable. It is optional during initialization.

Sequence of characters are the characters to be stored in string variable.

Example:

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);
}

Spread the love
Lesson tags: display string in c, initialicze a string variable in, read string value in c, string in c
Back to: C Programming Language
Spread the love