Logic error with an encode/decode program (C) - c

I am a beginner in a C programming class, and our assignment for the third chapter of our textbook was to create an encode/decode program that takes in four digits from user input and rearranges them depending on whether or not the user wants them to be either encoded or decoded. I am also having trouble with getting the program to do both decoding and encoding in one file. However, when I fire up the program, whenever I select encode and type in my four digits, the program not only gives me a massive number that should only be four digits as the encoded result. It also gives me the "press any key to continue" prompt, signifying the end of the program, instead of starting over completely and going back to where it asks the user to either decode or encode.
The output is also attached.
I've tried looking around and changing some of the variables from int to double, as well as checking my math... I'm not 100% sure why the encryption and decryption aren't limited to anything besides four digits.
As for getting the program to start over, I've tried using a do-while loop, but it still didn't seem to work, so I deleted it.. I also tried using another if statement and then using break, but it was marked as an error.
The assignment says that, "each digit should be encrypted by adding 7 and taking the remainder after division by 10; after encrypting each digit, swap the first and third digits, and then swap the second and fourth digits. Decryption should reverse the process. Program must do encode and decode in one file.
Here is the example that my instructor posted for this, this is what the output should look like.
Enter a four digit number: 1234
Encoded Digits: 0189
Continue (1) Exit (0): 1
Encode (1) Decode (2): 2
Enter a four digit number: 0189
Decoded Digits: 1234
Continue (1) Exit (0): 0
Here is my code:
///Compiler used: Microsoft Visual Studio
///Language: C
#include <string>
#pragma warning(disable: 4996)
#include <math.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int Encodechoice = 1;
int inputdigit1 = 0;
int Decodechoice = 2;
int UserChoice = 0;
int ContinueChoice = 0;
int UserDigit1 = 0;
int UserDigit2 = 0;
int UserDigit3 = 0;
int UserDigit4 = 0;
{
printf("(1) Encode, (2) Decode\n");
printf("Make your selection.\n");//Asks user to make selection
scanf_s("%d", &UserChoice);
if (UserChoice == 1)//begin encryption
{
UserDigit1 = 0;
UserDigit2 = 0;
UserDigit3 = 0;
UserDigit4 = 0;
printf("Encode: Enter FOUR integers.\n");
scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
int EncodedIntegers1 = (UserDigit1 + 7) % 10;
int EncodedIntegers2 = (UserDigit2 + 7) % 10;
int EncodedIntegers3 = (UserDigit3 + 7) % 10;
int EncodedIntegers4 = (UserDigit4 + 7) % 10;
printf("Encoded result:\n");
printf("%d", "%d", "%d", "%d\n", EncodedIntegers3, &EncodedIntegers4, &EncodedIntegers1, &EncodedIntegers2); /// swap order of integers
}///end if
if (UserChoice == 2)///begin decryption
{
UserDigit1 = 0;
UserDigit2 = 0;
UserDigit3 = 0;
UserDigit4 = 0;
printf("Decode: Enter FOUR integers.\n");
scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
int DecodedIntegers1 = (UserDigit1 - 7) * 10;
int DecodedIntegers2 = (UserDigit2 - 7) * 10;
int DecodedIntegers3 = (UserDigit3 - 7) * 10;
int DecodedIntegers4 = (UserDigit4 - 7) * 10;
printf("Decoded result:\n");
printf("%d", "%d", "%d", "%d\n", DecodedIntegers1, &DecodedIntegers2, &DecodedIntegers3, &DecodedIntegers4); /// keep order the same to decrypt
}///end if
system("pause");
return 0;
}
}
Output:
Make your selection.
1
Encode: Enter FOUR integers.
1234
Encoded result:
11893608 Continue? (1) Yes, (0) No
Make your selection.
1
Press any key to continue . . .```

You scanf is wrong. I would rather do this
char UserInputNumber[5];
printf("Encode: Enter FOUR integers.\n");
scanf("%s", UserInputNumber);
// optional error checking the input: length is 4? All char is a number?
UserDigit1 = (UserInputNumber[0] - '0');
UserDigit2 = (UserInputNumber[1] - '0');
UserDigit3 = (UserInputNumber[2] - '0');
UserDigit4 = (UserInputNumber[3] - '0');
Also your printf should look like this:
printf("%d%d%d%d\n", EncodedIntegers3, EncodedIntegers4, EncodedIntegers1, EncodedIntegers2);
With the & you tried to print their memory address not their value, but also your format string was wrong too.

The easiest way is probably work directly on a string consisting of the four digits:
char d[5], e[5] = { 0 };
scanf("%4s", d)
This is for encoding:
for (int i = 0; i < 4; i++) e[(i+2)%4]=(d[i]-41)%10+'0';
For decoding, you have to change the magic 41 to 45. The result is in e.

Related

Different algorithm for reversing a number using expanded form of numbers

Below is the code for reversing a number (in the standard way)
#include <stdio.h>
int main()
{
int result=0;
int q,n,rem;
printf("enter number: ");
scanf("%d",&n);
q=n;
while(q!=0){
rem=q%10;
result=result*10+rem;
q=q/10;
}
printf("reversed number is: %d",result);
return 0;
}
But I was thinking whether there is a way to find the reversed program using the expanded form of numbers?
For example: If the input to the program is 123, then the required output would be 321 which can be written as 3 * 100+2 * 10+1 * 1
I'm not quite sure what you mean by a "different algorithm for reversing a number using expanded form of numbers."
Perhaps this is a solution to what you are asking:
Take each digit, one at a time, moving from right to left across the number and multiply that digit by the multiple of 10 associated with the current left-most digit. Accumulate these values in the variable reverse.
e.g. number = 123, digitCount = 3, power = 100, reverse = 0
for loop executed digitCount times (3 times)
get current right-most digit (3)
multiply current right-most digit (3) times current left-most multiple of 10 (100) = 300
reverse = 300
drop right-most digit from number (number changes from 123 to 12)
adjust multiple of 10 (power changes from 100 to 10)
continue with second pass through loop, etc.
Also your version of the program will not properly handle trailing zeroes. The printf statement at the end of this program will fill in any formerly trailing zeroes which now should be leading zeroes.
/* reverse.c
reverse the digits of a non-negative integer and display it on the terminal
uses an advanced formatting option of printf() to handle any trailing zeroes
e.g. 500 produces 005
*/
#include <stdio.h>
int main (void)
{
printf("\n"
"program to reverse a number\n"
"\n"
"enter a number: ");
int number;
scanf ("%d", &number);
printf("\n");
int digitCount = 1;
int power = 1;
while (number / power > 9) {
++digitCount;
power *= 10;
}
// power = multiple of 10 matching left-most digit in number
// e.g. if number = 123 then power = 100
int reverse = 0;
for (int i = 1; i <= digitCount; ++i) {
reverse += number % 10 * power; // number % 10 = right-most digit
number /= 10; // drop right-most digit
power /= 10; // adjust multiple of 10
}
// .* represents a variable that specifies the field width (the minimum number of
// digits to display for an integer and with unused digits filled by leading zeroes)
printf("reversed number: %.*d\n", digitCount, reverse);
return 0;
}
There is no particular logic like that,if you are interested to acheive that kind of output, you can just come up with something like this
#include <stdio.h>
#include <math.h>
int main()
{
int result=0;
int q,n,rem;
printf("enter number: ");
scanf("%d",&n);
q=n;
int number[100];
for (int i = 0; i < 100 ; i++){
number[i] = -1;
}
int i=0;
while(q!=0){
rem=q%10;
number[i++]= rem;
q=q/10;
}
int size=0;
for (i = 0; i < 100 ; i++){
if(number[i]== -1) break;
else{
size++;
}
}
int tenPowers= size;
for(int i=0; i<=size-1 && tenPowers>=0 ;i++){
printf("%dx%d", number[i],(int)pow(10,tenPowers-1));
tenPowers=tenPowers-1;
if(tenPowers>=0) printf("+");
}
return 0;
}
You can have this. It's not reversing, but it's formatting the output for you. Reversing a binary number or a string is not difficult.
int main() {
int n = 123456;
char in[16], obuf[] = " + x*10000000";
sprintf( in, "%d", n );
int rev = strlen( in ) + 2;
for( int o=3, i=0; (obuf[3] = in[i]) != '\0'; o=0, i++ )
printf( "%.*s", rev+3-o-i-(in[i+1]?0:2), obuf+o );
return 0;
}
Output
1*100000 + 2*10000 + 3*1000 + 4*100 + 5*10 + 6
You can expand the sizes to suit your needs.

How do I make the numbers in this C program print in the correct order and not in reverse?

I am new to C so I am having a little difficulty!
I want to take an integer input from the user and add 7 to each of the digit in the input. All of that works, but the digits are printing in the reverse order.
How do i make the digits print in the correct order? I checked other similar questions on Stack overflow but it does not seem to work. Thanks in advance!
int main(void)
{
int numToEncrypt;
printf("Please input a 4-digit number you wish to encrypt: ");
scanf("%d", &numToEncrypt);
while (numToEncrypt > 0)
{
int digit = numToEncrypt % 10;
// do something with digit
digit = (digit + 7)%10;
numToEncrypt /= 10;
printf("number is: %d \n",digit);
}
}
)
Converting the string input to an integer and back is pointless. Just work with the data as a string. eg:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
int c;
if( getenv("V") ) {
printf("Please input the number you wish to encrypt: ");
fflush(stdout);
}
while( (c = getchar()) != EOF ) {
if( isspace(c) ) {
fflush(stdout);
} else if( isdigit(c) ) {
c = '0' + (c - '0' + 7) % 10;
} else {
fprintf(stderr, "Invalid input: %c", c);
return EXIT_FAILURE;
}
putchar(c);
}
}
Note that a huge advantage of doing this is that it is easy to work with ten million digit integers. You will not be able to do that using scanf to convert the string into an integer.
One way is using a variable to specify which digit to process.
#include <stdio.h>
int main(void)
{
int numToEncrypt;
int delta = 1000; // for 4-digit number
printf("Please input a 4-digit number you wish to encrypt: ");
scanf("%d", &numToEncrypt);
while (delta > 0)
{
int digit = (numToEncrypt / delta) % 10;
// do something with digit
digit = (digit + 7)%10;
delta /= 10;
printf("number is: %d \n",digit);
}
}
As this is homework, you could use recursion:
#include <stdio.h>
void print_recursive(int num)
{
// print leading digits
if (num>9)
{
print_recursive(num/10);
}
// print last digits
printf("number is: %d\n", (num+7)%10);
}
int main(void)
{
int number;
printf("Please input a 4-digit number you wish to encrypt: ");
scanf(" %d", &number); // note: You should check the return value!
print_recursive(number);
}
It is not limited to 4 digits.
For a simple program like this, one usually does not bother with a lot of design. However, it is also beneficial to practice software design on simple problems like this, since the knowledge extends to more complicated programs. This is an application of divide and conquer (as a problem solving strategy, not the computer algorithm). The idea being that smaller problems are simpler than larger ones.
In this case, you consider encapsulating the work of "encrypting" to a function, and have the function return the encrypted value. We'll just implement a stub for now, and fill it in later.
int encryptBy7(int input) {
int output = 0;
return output;
}
In addition, we can encapsulate the work of "printing" to a function. And, this is your actual question, if we think about it critically.
void printDigitByDigit(int num, const char *msg) {
printf("stub\n");
}
So your main program would look like:
int main(void) {
int numToEncrypt;
int numEncrypted;
printf("Please input a 4-digit number you wish to encrypt: ");
scanf("%d", &numToEncrypt);
numEncrypted = encryptBy7(numToEncrypt);
printDigitByDigit(numEncrypted, "number is");
return 0;
}
So, your algorithm to encrypt seems to work, so let's just code that up in a way that it stores it as a number.
int encryptBy7(int input) {
int output = 0;
int pow10 = 1;
/* Original program didn't deal with 0 */
if (input == 0) return 0;
while (input > 0) {
int digit = input % 10;
// do something with digit
digit = (digit + 7)%10;
input /= 10;
// build output
output += digit * pow10;
pow10 *= 10;
}
return output;
}
So, now we get to the meat of your question, which is about how to print out the digits starting with the most significant digit. If we see how we built up the output in the previous function, we can reverse the same process of looking at the powers of 10 to find the most significant digit, and then work backwards from there.
void printDigitByDigit(int input, const char *msg) {
int pow10 = 1;
int x = input;
// Find the position of the most significant digit
while (x > 10) {
pow10 *= 10;
x /= 10;
}
// Divide by the input appropriate power of 10 to
// find and print the corresponding digit
while (pow10 > 0) {
int digit = (input / pow10) % 10;
printf("%s: %d\n", msg, digit);
pow10 /= 10;
}
}
Of course, you are free to choose to try to do this as a single program inside of main as you had originally attempted, and the result would probably be a shorter program. I'll leave that as an exercise. However, I would argue that breaking up the program into tasks will provide you more benefit in the long run, and itself is a problem solving tool. Each function becomes easier to think about, and thus an easier problem to solve.

How can I store a digit of an Integer I'm trying to separating?

The issue I'm having is, I want to take an integer and separate it. For example: The user enters: 23432. The console should print" 2 3 4 3 2. The issue I'm having is storing that digits. For example,
User Input : 2020
assign input to num.
digit = 2020 % 10 = 0 <--- 1st Digit
num = num / 10 = 202
digit2 = num % 10 = 2 <--- 2nd Digit
num = num / 100 = 20.2
temp = round(num) = 20
digit3 = num % 10 = 0 <--- 3rd Digit
digit4 = num / 10 = 2 <---- 4th Digit
The problem with this approach is that its dependent on the user input, I'm working with the range 1-32767, so I wont know how many digit variables to create. Using the structure I've created can someone assist in making it run in a way the no matter what the number is, the digit is saved and printed in the way I've described?
int Rem(int num);
int Div(int num);
int main() {
int num;
printf("Enter an integer between 1 and 32767: ");
scanf("%d", &num);
Rem(num);
Div(num);
printf("%d","The digits in the number are: ");
}
int Rem(int num) {
int rem = num % 10;
return rem;
}
int Div(int num){
int div = num / 10;
return div;
}
The problem with this approach is that its dependent on the user input, I'm working with the range 1-32767, so I wont know how many digit variables to create.
So calculate it. You can do this by increasing a variable by a factor of 10 each time until increasing it one more time would make it larger than your input number:
int num;
printf("Enter an integer between 1 and 32767: ");
scanf("%d", &num);
int div = 1;
while(div * 10 <= num)
div *= 10;
Then you can repeatedly divide your number by this divisor to get each of the digits, dividing the divisor by 10 each time to shift one place at a time:
printf("The digits in the number are: ");
while(div > 0)
{
printf("%d ", (num / div) % 10);
div /= 10;
}
That's a really complicated approach. Why not read the string, and parse the string out like this:
int main(void) {
char buf[256]; // should be big enough, right? 10^256-1
memset(buf, 0, 256];
puts("enter something : ");
if( NULL == fgets(STDIN, 255, buf)) {
perror("Egad! Something went wrong!");
exit(1);
}
// at this point, you already have all the input in the buf variable
for(int i=0; buf[i]; i++) {
putchar( buf[i] ); // put out the number
putchar( ' ' ); // put out a space
}
putchar( '\n' ); // make a nice newline
}
As written above, it allows any character, not just numbers. If you want to restrict to numbers, you could filter the input, or put a check in the for loop ... depending on what you were trying to accomplish.
One way that C allows you do deal with problems this extremely elegantly is via recursion.
Consider a routine that only knows how to print the very last digit of a number, with a preceding space if needed.
void printWithSpaces(int neblod)
{
// Take everything except the last digit.
int mene = neblod / 10;
// Now extract the last digit
int fhtagn = neblod % 10;
// Check if there are leading digits
if (mene != 0)
{
// There are, so do some magic to deal with the leading digits
// And print the intervening space.
putchar(' ');
}
putchar(fhtagn + '0');
}
OK. So that's well and good, except what can we use to "Do some magic to deal with the leading digits"?
Don't we want to just print them as a sequence of digits, with suitable intervening spaces?
Isn't that exactly what void printWithSpaces(int neblod) does?
So we make one change:
void printWithSpaces(int neblod)
{
// Take everything except the last digit.
int mene = neblod / 10;
// Now extract the last digit
int fhtagn = neblod % 10;
// Check if there are leading digits
if (mene != 0)
{
// There are, so print them out
printWithSpaces(mene);
// And print the intervening space.
putchar(' ');
}
putchar(fhtagn + '0');
}
And you're done.
For the curious, the following article on C recursion may provide both an amusing read, and a little insight into my slightly unusual choice of variable names. ;) http://www.bobhobbs.com/files/kr_lovecraft.html

Convert String to Integer without library function in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to write a program that converts an user input (which is a string) to an Integer. In the same time it should check, if the user input really is a number.
And also everything in one method.
and NO LIBRARY FUNCTIONS allowed.
I can't figure any idea how to do it. All I got for the beginning is just this pathetic structure
#include <stdio.h>
void main()
{
char input[100];
int i;
int sum = 0;
printf("Type a String which will be converted to an Integer: ");
scanf("%c, &input");
for (i = 0; i < 100; i++)
{
}
}
I appreciate any help, thanks
The conversion is the easy part...
But if you must not use library functions,
there is only one way to take a string, and that is argv;
there is only one way to give an integer, and that is the exit code of the program.
So, without much ado:
int main( int argc, char * argv[] )
{
int rc = 0;
if ( argc == 2 ) // one, and only one parameter given
{
unsigned i = 0;
// C guarantees that '0'-'9' have consecutive values
while ( argv[1][i] >= '0' && argv[1][i] <= '9' )
{
rc *= 10;
rc += argv[1][i] - '0';
++i;
}
}
return rc;
}
I did not implement checking for '+' or '-', and did not come up with a way to signal "input is not a number". I also just stop parsing at the first non-digit. All this could probably be improved upon, but this should give you an idea of how to work around the "no library functions" restriction.
(Since this sounds like a homework, you should have to write some code of your own. I already gave you three big spoons of helping regarding argv, the '0'-'9', and the conversion itself.)
Call as:
<program name> <value>
(E.g. ./myprogram 28)
Check return code with (for Linux shell):
echo $?
On Windows it's something about echo %ERRORLEVEL% or somesuch... perhaps a helpful Windows user will drop a comment about this.
Source for the "'0'-'9' consecutive" claim: ISO/IEC 9899:1999 5.2.1 Character sets, paragraph 3:
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
I'm sure this is preserved in C11, but I only have the older C99 paper available.
Take hightes digit and add it to number, multiply the number by 10 and add the next digit. And so on:
#include <stdio.h> // scanf, printf
void main()
{
char input[100];
printf("Type a String which will be converted to an Integer: ");
scanf("%s", input);
int number = 0;
int neg = input[0] == '-';
int i = neg ? 1 : 0;
while ( input[i] >= '0' && input[i] <= '9' )
{
number *= 10; // multiply number by 10
number += input[i] - '0'; // convet ASCII '0'..'9' to digit 0..9 and add it to number
i ++; // step one digit forward
}
if ( neg )
number *= -1;
printf( "string %s -> number %d", input, number );
}
input[i] - '0' works, because ASCII characters '0'..'9' have ascending ASCII codes from 48 to 57.
So basically you want to know how something like the standard library atoi works. In order to do this, you need to consider how strings represent numbers.
Basically, a string (that represents a number) is a list o digits from 0 to 9. The string abcd (where a, b, c, d are placeholders for any digit) represents the number a*10 ^ 3 + b*10^2 + c * 10 + d (considering base 10 here, similar for other bases). So basically you need to decompose the string as shown above and perform the required arhitmetic operations:
// s - the string to convert
int result = 0;
for (int index = 0; index < strlen(s); index++) {
result = result * 10 + s[index] - '0';
}
The operation s[index] - '0' converts the character that represent a digit to its value.
// the function returns true for success , and false for failure
// the result is stored in result parameter
// nb: overflow not handled
int charToInt(char *buff,int *result){
*result=0;
char c;
while(c=*buff++){
if((c < '0') || (c >'9')) // accept only digits;
return 0;
*result *= 10;
*result += c-'0';
}
return 1;
}
Lot of things which are missed. Firstly taking a string in is done by scanf("%s",input); By the way in which you are receiving it, it only stores a character, secondly run the loop till the length of the string recieved. Check the below code.
#include <stdio.h>
#include<string.h>
void main()
{
char input[100];
int i;
int sum = 0;
printf("Type a String which will be converted to an Integer: ");
scanf("%s", input);
for (i = 0; i < strlen(input); i++)
{
if(input[i]>=48 && input[i]<=57)
{
//do something, it is a digit
printf("%d",input[i]-48);
//48 is ascii value of 0
}
}
Try it:
#include <stdio.h>
void main()
{
char input[100];
int i,j;
int val = 0;
printf("Type a String which will be converted to an Integer: ");
scanf("%s",input);
for(j=0; input[j] != '\0'; j++); // find string size
for (i = 0; i < j; i++)
{
val = val * 10 + input[i] - 48;
}
}
If you want your code to be portable to systems that don't use ASCII, you'll have to loop over your char array and compare each individual character in the source against each possible number character, like so:
int digit;
switch(arr[i]) {
case '0':
digit=0; break;
case '1':
digit=1; break;
// etc
default:
// error handling
}
Then, add the digit to your result variable (after multiplying it by 10).
If you can assume ASCII, you can replace the whole switch statement by this:
if(isdigit(arr[i])) {
digit=arr[i] - '0';
} else {
// error handling
}
This works because in the ASCII table, all digits are found in a single range, in ascending order. By subtracting the ordinal value of the zero character, you get the value of that digit. By adding the isdigit() macro, you additionally ensure that only digit characters are converted in this manner.

C program: Checking digits entered are 1s and 0s only using arrays

So I am trying to make a smaller simple program to solve a problem. For this, I am trying to check to make sure the user inputs a number containing ONLY 1s and 0s and then I will use this number to perform a division. For example the number 11010 or 10111. Now my problem is, if I declare an integer to store this number (as follows) there wouldn't be a way to check all the digits are 1s or 0s right?
int userInput;
Now, I can use an array for this. (I know how to do this BUT this leads to my second problem.). Like so:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main (int argc, char *argv[]){
int myArray[20];
int i, input, length;
printf("Please enter how long your number is: \n");
scanf("%d", &length);
for (i = 0; i < length; i++){
printf("Please enter digit %d of your array\n", i+1);
scanf("%d", &input);
assert ((input == 1) || (input ==0));
}
For example, for the first digit the user enters a '1', the second digit the user enters a '0', then the third digit the user enters '0'. I need to "grab" this number though. How would I grab this number "100" and perform arithmetic operations on it. I hope this makes sense, if not moderators please give me a chance to clear it up.
EDIT: Many have suggested the modulo approach. BUT I still want to know if I can do this with an array. That is creating a integer variable and set that equal to each element the user has entered in the array.
I think this could be more simple:
bool is_zeros_and_ones(int n) {
for (; n != 0; n /= 10) {
int mod = n % 10;
if (0 != mod && 1 != mod) {
return false;
}
return true;
}
So you can input whole number and test it without arrays.
You don't really need to get the number one digit at a time.
It is easy to extract the digits of an int. Notice that a number such as 12345 is actually
5 * 10^0 + 4 * 10^1 + 3 * 10^2 + 2 * 10^3 + 1 * 10^4.
To get the lowest digit you can just take the remainder of the number when divided by 10 (i.e. mod it by 10 using the % operator). So, 12345 % 10 is 5. To get the next digit, you can divide the number by 10 (getting 1234) and then mod by ten again - giving you 4. Keep doing this as long as you have digits left in the number (i.e. the number is > 0).
#include <stdio.h>
int is_valid(int number) {
if (number == 0) return 1; // its a 0.
while (number != 0) {
int digit = number % 10;
if (digit != 1 && digit != 0) return 0;
number = number / 10;
}
return 1; // no other digits were found.
}
int main() {
int n;
scanf("%d", &n);
if (is_valid(n)) printf("valid\n");
else printf("not valid\n");
return 0;
}
Here's another idea:
Just write the number again into a string. Then iterate over the string checking each character. This is somewhat less efficient, but simpler to understand/code.
#include <stdio.h>
int is_valid(int n) {
char buffer[20];
char *c;
sprintf(buffer, "%d", n);
for(c = buffer; *c != '\0'; c++) {
if (*c != '0' && *c != '1') return 0;
}
return 1;
}
int main() {
int n;
scanf("%d", &n);
if (is_valid(n)) printf("valid\n");
else printf("not valid\n");
return 0;
}
EDIT:
Since you mentioned in your edit that you are not interested in alternate approaches and just need a way to "grab" the digits as they are fed in, I'm adding this to my answer.
Keep a variable initially set to 0. Now as each digit comes in, (I am assuming the user enters higher digits before lower ones), we multiply our variable by 10 and add the new digit to it. Thus, if the user enters 1, 0, 0, our variable is initially 0, the its 1 (0 * 10 + 1), then its 10 (1*10 + 0) and finally 100 (10 * 10 + 0), which is what we needed.
Maybe something like this would be enough
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main (int argc, char *argv[]){
int myArray[21];
printf("Please enter your number (max 20 digits)\n");
scanf("%s", myArray);
for (i = 0; i < strlen(myArray); i++){
assert ((myArray[i] == 1) || (myArray[i] == 0));
}
You don't need an array to store all the digits.
Keep dividing by 10 & taking modulo to get each digit & keep a single flag to mark if all digits are 1 or 0.
Of course works only for max word size of the integer...
Something like:
char isBinary = 1;
int copyInput = +input;
while(copyInput && (isBinary=copyInput%10<=1)) copyInput/=10;
You could cheat your way by making sure the program always deals with ints. Your array basically holds the binary representation of a base 10 number. Why not use it convert to an int. Then you can apply all operations to that number just as you would operate on ints.
Here is what i mean
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main (int argc, char *argv[]){
int i, input, length;
int num = 0; /* holds the actual number */
printf("Please enter how long your number is <= %d: \n", 8 * sizeof(num) - 1);
scanf("%d", &length);
for (i = 0; i < length; i++){
printf("Please enter digit %d of your array\n", i+1);
scanf("%d", &input);
assert ((input == 1) || (input ==0));
/* humans enter numbers L TO R */
/* set that bit if it is one */
num |= (input << (length - i - 1)) ;
}
printf("Your number in base 10 is %d\n",num);
/* Now you do normal multiplications, additions, divisions */
/* The only thing remaining now is to convert from base 10 to base 2. */
}
Sample run
Please enter how long your number is <= 31:
5
Please enter digit 1 of your array
1
Please enter digit 2 of your array
1
Please enter digit 3 of your array
1
Please enter digit 4 of your array
1
Please enter digit 5 of your array
0
Your number in base 10 is 30
This solution is only for the second part of the problem. You can take the input as characters and use atoi to convert them to integer.
char arrayOfNumbers[MAX_LENGTH];
char tmpChar;
int number;
for (i = 0; i < length; i++){
printf("Please enter digit %d of your array\n", i+1);
scanf("%c", &tmpChar);
assert ((tmpChar == '1') || (tmpChar == '0'));
arrayOfNumbers[i] = tmpChar;
}
/*make sure it is NULL terminated*/
arrayOfNumbers[length] = '\0';
number = atoi(arrayOfNumbers);

Resources