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

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...
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...
My code is working fine but after selecting an option and at the end I want...
My code is working fine but after selecting an option and at the end I want user could enter another option again without going back to menu. However, in my code when I enter another option, it prints the whole menu again then I can select option.Could anyone help me on that? #include "stdafx.h" #include #include #include using namespace std; const double pi = 3.14159265358979323846; const double deg_to_rad = (pi / 180); int main() { int option; do { cout...
This code works fine. In java, can you: change the variable and method names to make...
This code works fine. In java, can you: change the variable and method names to make logical sense add method header comments to describe what the method does and what the params/returns are add a class header comment to describe what the code does import java.util.Arrays; import java.util.Scanner; public class MethodLibrary { public static void main(String args[]) { System.out.println("MethodLibrary"); System.out.println("Example use of methods"); int[] smallNums1 = {2, 1, 7, 4, 3}; display("display:", smallNums1); char [] characters = {'a','b','c','d','e','f'}; first( characters,...
Need to check if File is successfully opened? C++ It works when I input the right...
Need to check if File is successfully opened? C++ It works when I input the right txt file. But, it keeps stating, File successfully open." even I put in a non-existing file. Here are the specifications: Develop a functional flowchart and then write a C++ program to solve the following problem. Create a text file named first.txt and write your first name in the file. You will be reading the name of the file from the keyboard as a string,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT