-->

How to Initialize String Variables

How to Initialize String Variables in C Programming
Initializing String Variables 
#include <stdio.h>
int main()
{
int i;
char strl[] = "Hello world";
char str3[12] = "Hello world";
char str2[5];
str2[0]='M';
str2[1]='E';
str2[2]='3';
str2[3]='0';
str2[4]='\0';
printf("str1==%s\n",str1);  ------------->
for(i=0; i<5; i++)
{
printf("str2[%d]==%c\n", i, str2[i]); ----->
}
return 0;
}


OUTPUT
str1==Hello world
str2[0]==M
str2[1]==E
str2[2]==3
str2[3]==0
str2[4]==

Declare as an array of type char

Can initialize implicitly or explicitly (using a string constant or using individual characters and a terminating NULL character)

Can print an entire string using printf and %s format specification

Can print individual elements of a suing by indexing and using %c format specification

Strings - Practice 1 
Declare: 
A string variable named me30 and and initialize it to hold the string, “ME 30 rocks!”
Determine: 
The minimum number of characters of array elements needed to store the string: 
length of the string 
What is stored in me30[2]? 
What is stored in me30[12]?
Solution 
Declare: 
char me30[]="ME 30 rocks!" //
The minimum number of character array elements need to store is given here. 
13 
Try sizeof(me30)/sizeof(char) (Or) 
strlen(me30)+ 1 
me30[2]== space // Space is stored in me30[2]
What is stored in me30[12]=='\0'  //Null character is stored in me30[12].



Related Posts

Subscribe Our Newsletter