Forms often allow a user to enter an integer. Write a program that takes in a string representing an integer as input, and outputs yes if every character is a digit 0-9. You may assume that the string does not contain spaces and will always contain less than 50 characters.Ex: If the input is:1995the output is:yesEx: If the input is:42,000 or1995!the output is:noHint: Use a loop and the isdigit() function (don't forget to include the ctype library).

Respuesta :

Answer:

#include <stdio.h>

#include <ctype.h>

int main(void) {

char data[50];

int i;

   printf("Enter data: ");

   scanf("%s", data);

 

for (i = 0; data[i] != '\0'; ++i){

 if(isdigit(data[i]) == 0){

  printf("\nno");

  return 0;

 }

}

printf("\nyes");

return 0;

}

Explanation:

Step 1 : Define variables and libraries

  • Variables:

           char data[50];

     int i;

  • Libraries:

           #include <stdio.h>

           #include <ctype.h>

Step 2:  Read the data and asign to variable:

       printf("Enter data: ");

       scanf("%s", data);

Step 3: Loop over the data :

       for (i = 0; data[i] != '\0'; ++i)

Step 4: Validate if the element is digit:

       if(isdigit(data[i]) == 0)

Step 5: If the element is not digit print no and finish the program:

               if(isdigit(data[i]) == 0){

  printf("\nno");

  return 0;

 }

Step 6: If all elements are digits print yes and finish the program:

       printf("\nyes");

return 0;