Character Array program 1

C Program to take input for a string and display it in the given format? And display length of string?
N=”hello”
o/p
h
e
l
l
o

Problem In Hand

We have to take input for a sting and display it in given format and also we have to display length of tht string.

Process and Solution Of Problem

  1. Take input for a string
  2. Apply a while loop to read the string till end.
  3. set i=0
  4. while(n[i]!=’\0′)  : read till ‘\0’ is encountered. ‘\0’ (NULL character) is the terminating charcter of the array.
  5. read the character at i th position and display it.
  6. value of i is incremented by 1
  7. steps 5 and 6 is repeated till all the character of the string and read.
  8. further value of i is display which gives the length of the string.

Program/Source Code

 #include <stdio.h>
 int main()
 {
     char n[20];
     int i=0;
     printf("Enter any string ");
     gets(n); /* scanf("%s",n); */
     while(n[i]!='\0')
     {
         printf("%c\n",n[i]);
         i++;
     }
     printf("Length = %d\n",i);
 return 0;
 }

Program Explanation

On execution of the program 

  • user enters the string
  • string is stored in a character array variable “n”
  • i is set to 0
  • while loop is applied to read the string character by character and displayed on the screen.
  • after reading the full string length of the string is displayed.

Output:

Enter any string Hello
H
e
l
l
o
Length = 5