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
- Take input for a string
- Apply a while loop to read the string till end.
- set i=0
- while(n[i]!=’\0′) : read till ‘\0’ is encountered. ‘\0’ (NULL character) is the terminating charcter of the array.
- read the character at i th position and display it.
- value of i is incremented by 1
- steps 5 and 6 is repeated till all the character of the string and read.
- 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