C Program to take input for a string and display it and also print total digits in the string?
Problem In Hand
We have to take input for a sting and display it and also we have to count and print total number of digits ( 0 to 9 ) in the string.
Process and Solution Of Problem
- Take input for a string
- set i=0, d=0
- Apply a while loop to read the string till end.
- 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.
- if the read character is between “0” and “9” then we increment the count d by 1
- value of i is incremented by 1 to move to the next character
- steps 5, 6 and 7 are repeated till all the character of the string and read.
- further value of “d” is display which gives total number of digits in the string.
Program/Source Code
#include <stdio.h> int main() { char n[20]; int i=0,d=0; printf("Enter any string "); gets(n); /* scanf("%s",n); */ while(n[i]!='\0') { printf("%c\n",n[i]); if(n[i]>='0' && n[i]<='9') d++; i++; } printf("Total digits in string = %d\n",d); return 0; }
Output:
Enter any string abc123 a b c 1 2 3 Total digits is string = 3