Question

In: Computer Science

Please assist with getting my code to correctly check to validate input. Everything else works fine,...

Please assist with getting my code to correctly check to validate input. Everything else works fine, but when I enter a character, it should say Invalid entry.

Everything else should also work. It should not allow more or less than 9 digits, and it should ask again for input if it doesn't like the input. Please help my code and explain how it is working. I also need to keep the recursive function.

#include <stdio.h>
#include <ctype.h >
int SecNumSum(long long int num) {

   //If num is single digit
   if (num < 10) {
       return num;
   }
   else {
       //return unit place digit + sum of rest of the number
       return (long long int) num % 10 + SecNumSum(num / 10);
   }

}

//Return square of number
int square(int num) {
   return num * num;
}

int main() {
   //Input social security number and store it in num variable
   //Type of num is long long int to take large value in input
   long long int num;
   int   count = 0;
  
  
   printf("Please enter social security number\n");
  

   scanf_s("%lld", &num);

  
  

       int digits = num;
       // run loop until digits is greater than 0

       do
       {
           count++;
           digits /= 10;
       } while (digits != 0);

       while (count != 9 || count > 9)
       {

           printf("Invalid number. Please enter social security number \n");
           scanf_s("%d", &num);

           digits = num;
           count = 0;
           do
           {

               count++;
               digits /= 10;
           } while (digits != 0);

       }

       int ssnSum = SecNumSum(num);
       printf("Sum of all digits: %d\n", ssnSum);

       printf("Your security code will be: %d\n", square(ssnSum));

  
  
   return 0;
}

Solutions

Expert Solution

An easier approach to solve this would to read the security number as a string (array of characters) instead of reading it as a number. Here we can easily check the length using the strlen function. Also, we can use the isdigit() function, to check if each character is a digit. If every character is a digit, and it is of length 9, then it is a valid security number and we can simply convert it into integer data type using atoi (ascii to integer) function. We then proceed to compute the sum and the square as in the code above.

Code has been shared below.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

int SecNumSum(long long int num) {
   //If num is single digit
   if (num < 10) {
   return num;
   }
   else {
   //return unit place digit + sum of rest of the number
   return (long long int) num % 10 + SecNumSum(num / 10);
   }
}

//Return square of number
int square(int num) {
   return num * num;
}

// if the security number is invalid returns -1 else returns 0
int isValidSecNum(char digits[])
{
   // checks the length
   int length = strlen(digits);
   if (length != 9)
   {
       printf("Invalid length.\n");
       return -1;
   }
   // checks if each character is a digit
   for (int i = 0; i < length; i++)
   {
       if (!isdigit(digits[i]))
       {
           printf("Not a valid security number.\n");
           return -1;
       }
   }
   return 0;
}

// reads the security number as an array of characters
long long int readSecNum()
{
   char num[10];
   while (1)
   {
       printf("Please enter social security number\n");
       scanf_s("%s", num);
       // breaks out of loop is the security number is valid
       if (isValidSecNum(num) == 0) break;
   }
   return atoi(num);
}

int main() {
   //Input social security number and store it in num variable
   //Type of num is long long int to take large value in input
   long long int num;
   num = readSecNum();
   int ssnSum = SecNumSum(num);
   printf("Sum of all digits: %d\n", ssnSum);
   printf("Your security code will be: %d\n", square(ssnSum));
return 0;
}

Screenshot (included for readability)

Output


Related Solutions

Prompt the user to input their lucky number. Upon getting the users input, validate that the...
Prompt the user to input their lucky number. Upon getting the users input, validate that the input is a valid number using Int32.TryParse (more info can be found at https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-a-string-to-a-number (Links to an external site.)). If the input is not a valid number, output a message to the user stating that you are sorry but you are unable to run the FizzBuzz process due to the input not being a valid number. If the input is valid, you are clear...
My code works in eclipse, but not in Zybooks. I keep getting this error. Exception in...
My code works in eclipse, but not in Zybooks. I keep getting this error. Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFor(Scanner.java:937) at java.base/java.util.Scanner.next(Scanner.java:1478) at Main.main(Main.java:34) Your output Welcome to the food festival! Would you like to place an order? Expected output This test case should produce no output in java import java.util.Scanner; public class Main {    public static void display(String menu[])    {        for(int i=0; i<menu.length; i++)        {            System.out.println (i + " - " + menu[i]);...
Validating Input file, So for my C++ assignment, my professor says we need to validate the...
Validating Input file, So for my C++ assignment, my professor says we need to validate the Input File, Which means, if the line is missing a comma, one of the 3 information, or the string is a white line, it will ignore it. If the line has a white line, the program will correct it and will read in the line. I will store these into an Array, and display them in First name, Last name, and Number of Votes...
Python programming: can someone please fix my code to get it to work correctly? The program...
Python programming: can someone please fix my code to get it to work correctly? The program should print "car already started" if you try to start the car twice. And, should print "Car is already stopped" if you try to stop the car twice. Please add comments to explain why my code isn't working. Thanks! # Program goals: # To simulate a car game. Focus is to build the engine for this game. # When we run the program, it...
I have a problem with my code. It does not run. Please can someone check the...
I have a problem with my code. It does not run. Please can someone check the code and tell me where I went wrong? This is the question: Program Specification: Write a C program that takes the length and width of a rectangular yard, and the length and width of a rectangular house (that must be completely contained in the yard specified) as input values. Assuming that the yard has grass growing every where that the house is not covering,...
Thank you all. my other code is working fine. It was my IDE issue. This is...
Thank you all. my other code is working fine. It was my IDE issue. This is the new code i am writing for the below question. please help as you always do: a=int(input('Input a: ')); b=int(input('Input b: ')); c=int(input('Input c: ')); r=int(input('Input r: ')); s=int(input('Input s: ')); t=int(input('Input t: ')); x=2; min_rst = min(r,s,t); while(1): if((x-a)%r==0): if((x-b)%s==0): if((x-c)%t==0): break; x=x+1; print('The required number is: ',x); Questions: Write a Python program called crt.py that finds the value of x that satisfies...
Please see if you can correct my code. I am getting an ReferenceError in Windows Powershell...
Please see if you can correct my code. I am getting an ReferenceError in Windows Powershell that says payment is undefined. I am trying to create a main.js file that imports the function from the hr.js file; call the function passing the necessary arguments and log the result to the console. main.js var Dev = require("./hr.js") const { add } = require("./hr.js") var dev_type = 1; var hr = 40; console.log("your weekly payment is " + payment(dev_type, hr)) dev_type =...
this is my matlab code for class, my professor commented "why is the eps an input...
this is my matlab code for class, my professor commented "why is the eps an input when it is set inside the function and not specified as a variable? how do i fix? function[] = () %Declare Global Variables global KS; global KC; KC = 0; KS = 0; End = 0; while (End == 0) choice = questdlg('Choose a function', ... 'Fuction Menu', ... 'A','B','B'); switch choice; case 'A' Program = 'Start'; while strcmp(Program,'Start'); Choice = menu('Enter the Trigonometric...
I'm getting an error with my code on my EvenDemo class. I am supposed to have...
I'm getting an error with my code on my EvenDemo class. I am supposed to have two classes, Event and Event Demo. Below is my code.  What is a better way for me to write this? //******************************************************** // Event Class code //******************************************************** package java1; import java.util.Scanner; public class Event {    public final static double lowerPricePerGuest = 32.00;    public final static double higherPricePerGuest = 35.00;    public final static int cutOffValue = 50;    public boolean largeEvent;    private String...
I would like to compare my current code with that of someone else to be sure...
I would like to compare my current code with that of someone else to be sure I did this assignment correctly. My main concern is with Problems 2 and 4. I sometimes struggle with testing the methods I have created. If you can, please answer all of the questions so that I may reference them if I am still lost on Problems 2 and 4. Each problem requires the one before it and so seeing the entire assignment as opposed...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT