Wednesday 29 January 2014

Explain string with different formats.

String
Group of characters,digits,symbols enclosed within quotation marks are called strings.The C compiler inserts NULL(\0) character automatically at end of the string.
Different formats of initialization of string
char name[]="INDIA";
or
char name[]={'I','N','D','I,'A','\0'};
or
char name[]={{I},{N},{D},{I},{A}};

Write a program to print "INDIA" by using different formats of initialization of array.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
   {
    char a1[]={'I','N','D','I''A','\0'};
    char a2[]="INDIA";
    char a3[6]={{I},{N},{D},{I},{A}};
    clrscr();
    printf("\n Array1=%s",a1);
    printf("\n Array2=%s",a2);
    printf("\n Array3=%s",a3);
   }
Output
Array1=INDIA
Array2=INDIA
Array3=INDIA

Write a program to display string 'PRABHAKAR 'using different formats.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char a[]="PRABHAKAR";
clrscr();
printf("  %s  \n ",a);
printf(" %.5s \n ",a);
printf(" %.8s \n ",a");
printf(" %.15s \n ",a);
printf(" %-10.4s  \n",a);
printf(" %11s \n ",a);
}
Output
PRABHAKAR
PRABH
PRABHAKA
PRABHAKAR
PRAB
PRABHAKAR

Print elements of character array given with while loop (help of Null character).

#include<stdio.h>
#include<conio.h>
main()
{
    char a[]="Have a nice day";
    int i=0;
    clrscr();
    printf("Elements of the array:");
    printf("\n");
    while(a[i]!='\0')
        {
        printf("  %c ",a[i]);
        i++;   
        }

}
Output
Elements of the array:
Have a nice day

No comments:

Post a Comment