Tuesday 10 February 2015

Strings in c language-1

In c & cpp language there is no separate data type for string. But we can use string as array of characters.A string constant is a one dimensional array of characters terminated by null (‘\0’) .

For example

Char a[]={‘w’,’e’,’l’,’c’,’o’,’m’,’e’,’\0’};

We know that character data type take only one byte of memory .In string each character take one byte of memory and last character is always null. The terminating null is important because only by null character a string knows that it is the end of the string.

What is the difference between character array and numerical array?. Can elements character array can be accessed as numerical array. The following sample programs will explain it

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
Char name[]=”muthu”;
int i=0;
clrscr();
while(i<=4)
{
printf(“%c”,name[i]);
i++;
}
getch();
}

Output:
Muthu.

In the above program we have initialized a character array and have printed out the elements of this array in while loop.

 The other way of using while loop to print the character array is using the end character null(‘\0’).

Example

#include<stdio.h>
#include<conio.h>
void main()
{
char name[]=”karthikeyan”;
Int i=0;
clrscr();
while (name[i]!=’\0’)
{
printf(“%c”,name[i])
i++;
}
getch();
}

Output:

Karthikeyan.

Another simple way of printing a string.

#include<stdio.h>
#include<conio.h>
void main()
{
char name[]=”karthikeyan”;
clrscr();
printf(“%s”, name);
getch();
}

Output:
karthikeyan

Note that in the previous programs we used ‘ %c’ as format specifier. But in the above program we used ‘%s’ as format specifier.we also use %s in scanf statement.

#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
clrscr();
printf(“enter your name”);
scanf(“%s”,name);
printf(“hai %s”,name)
getch();
}

Output:
Enter your name :
Muthu karthikeyan
hai Muthu

Note in the above program we give the input as a multi worded string “Muthu karthikeyan”.but the output is only muthu. Because scanf() is not capable getting input of multi worded string.The way of getting aroung this limitation is using gets() for getting input puts for getting output.

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
clrscr();
printf(“enter name”);
gets(name)
puts(“hai”);
puts(name);
getch();
}

Output

Enter name

Muthu karthikeyan

Hai Muthu karthikeyan.



The  other thing to note in gets() and puts() is we don’t have to use format specifier. But gets() and puts() can be only used to getting input and printing output of only strings.
to read my blogs in tamil visit:


No comments:

Post a Comment