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);
Related
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.
I have a number, 321197186 which the user inputs. How can I store this number into an array one element at a time. Basically, I am trying to store the 1st digit into 0th element and so on. And then I have to do some computation on that number.
Represent your number as a string, where every character of that string will be the corresponding digit of your number.
There are a plethora of method to read a string, but I suggest you use fgets() like this:
#include <stdio.h>
#include <string.h>
#define MAX_LEN 10
int main (int argc, char *argv[])
{
char number[MAX_LEN];
printf("Enter a number: \n");
fgets(number, MAX_LEN , stdin);
printf("%s\n", number);
return 0;
}
With a for loop, you access the characters (digits) of the string (number) one by one, if you like.
I suggest you also eat the trailing newline that fgets() leaves in the input array, as already explained in Removing trailing newline character from fgets() input.
Alternative solution proposed by bruno#:
scanf("%9s", number);
Read more in C - scanf() vs gets() vs fgets().
Assume you have
int num;
if (scanf("%d", &num) != 1)
{
// Input error
exit(1);
}
// Now the user input is available in num
then you do
#define MAX_DIGITS 32
int digits[MAX_DIGITS] = { 0 };
int index = 0;
while(num != 0 && index < MAX_DIGITS)
{
digits[index] = num % 10;
++index;
num = num / 10;
}
// Now the array digits holds the individual digits
// and index holds the number of valid digits
You can consider this logic in C -
number = 321197186
while(number> 0) - leave if number becomes 0
{
int last_digit = number % 10; - Last digit from the number
printf("%d",last_digit);
number = number / 10; - to get the remaining number.
}
This can be also done in Python as -
number = 321197186
list1 = []
for i in str(number):
list1.append(i)
print(list1)
store this number into an array one element at a time.
Let us take advantage of the input process to have a convenient way to determine the length of input including leading zeros (but not input with a sign, leading spaces) by using "%n" to record the offset of the scan.
Use % 10 to exact the least significant decimal digit of the number.
int number;
int offset;
if (scanf("%d%n", &number, &offset) == 1) {
int a[offset]; // VLA
while (offset > 0) {
a[--offset] = number % 10;
number /= 10;
}
for (int i = 0; i < sizeof a/sizeof a[0]; i++) {
printf("a[%d] = %d\n", i, a[i]);
}
}
Output
a[0] = 3
a[1] = 2
a[2] = 1
a[3] = 1
a[4] = 9
a[5] = 7
a[6] = 1
a[7] = 8
a[8] = 6
But as bruno points out, you just have to check it as a string as an user input with fgets is an array of characters (even if we are talking about numbers).
For more detail:
for(i=0;i<sizeof(array_input);i++){
//Store the char into another array
}
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.
I am currently trying to finish a code where a user inputs two 5 digit long numbers. The code then checks to see if there are any identical numbers in the same spot for the two numbers and displays how many identical numbers there are in the same spot of the two inputs. (ex. comparing 56789 and 94712 there would be one similar digit, the 7 in the 3rd digit place.) As of now I have been able to break down the inputs into the digits in each spot, I just need help comparing them. Originally I thought I could just create an int that would serve as a counter and use modulus or division to output a 1 whenever the digits were the same, but I have been unable to put together a formula that outputs a 1 or 0 depending on if the digits are alike or not.
suppose you know the length of strings n (as a condition you would need them to be equal, if they differ in length other validation is needed)
//n is the length of string
for(int i=0;i<n;i++)
{
if(string1[i]==string2[i])
{
//do something, make a counter that increments here...
//also save index i, so you can tell the position when a match occured
}else
{
//do something else if you need to do something when chars didnt match
}
}
Here you when i=0, you are comparing string1[0] with string2[0], when i=1, you compare string1[1] with string2[1] and so on.....
I'd recommend reading the two in as strings or converting to strings if you have the ability to. From there it's a simple string compare with a counter. Something like this:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int is_numeric(char *str)
{
while (*str)
if (!isdigit(*str++))
return (0);
return (1);
}
int main(void)
{
char num1[32];
char num2[32];
int count = 0;
printf("Digit 1\n>> ");
if (scanf("%5s", num1) != 1 || !is_numeric(num1))
return (0);
printf("Digit 2\n>> ");
if (scanf("%5s", num2) != 1 || !is_numeric(num2))
return (0);
if (strlen(num1) != 5 || strlen(num2) != 5)
return (0);
for (int i=0; i<5; ++i)
if (num1[i] == num2[i])
++count;
printf("%d\n", count);
return (0);
}
You can do it very easy using modulo (%) and divide (/). First you do % 10 to get the least significant digit and do the compare. Then you do / 10 to remove the least significant digit. Like:
#include <stdio.h>
#include <string.h>
int main(void) {
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1 || i1 < 10000 || i1 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1 || i2 < 10000 || i2 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
for (i=0; i<5; ++i)
{
if ((i1 % 10) == (i2 % 10)) ++cnt; // Compare the digits
i1 = i1 / 10;
i2 = i2 / 10;
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
It can also be done using strings. Read the input as unsigned int and then convert the value to a string using snprintf and finally compare the two strings character by character.
Something like:
#include <stdio.h>
#include <string.h>
int main(void) {
char str1[32];
char str2[32];
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str1, 32, "%u", i1);
if (strlen(str1) != 5) // Convert to string
{
printf("input error - not 5 digits\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str2, 32, "%u", i2); // Convert to string
if (strlen(str2) != 5)
{
printf("input error - not 5 digits\n");
return 0;
}
for (i=0; i<5; ++i)
{
if (str1[i] == str2[i]) ++cnt; // Compare the characters
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
The reason for taking the input into a unsigned int instead of directly to a string is that by doing that I don't have to check that the string are actually valid numbers (e.g. the user type 12W34). scanf did that for me.
I am new to C programming as you can already guess by my question. I am trying to enter a valid pin of 4 digits e.g. 9999. However, if the first digit is a zero i.e. 0111 the logic in my program doesn't increment counter. In a nutshell I am stuck on how I can account for a pin that begins with a zero. I could add a piece of error checking stating to the user that the pin must not begin with a zero but I don't want to resort to that if its possible.
Here is what I have so far:
/*
Program name: Count num of digits
*/
#include <stdio.h>
#define PIN_LENGTH 4
int main()
{
int pin = 0;
int counter = 0;
printf("Enter your PIN: ");
scanf("%d", &pin);
while(pin != 0)
{
pin = pin / 10;
counter++;
}
if(counter == PIN_LENGTH)
{
printf("Valid pin of %d digits\n", counter);
}
else
{
printf("Invalid pin of %d digits\n", counter);
}
return(0);
}
As you can see I divide the pin number by 10 and assign the new value into pin.
9999 divided by 10 = 999 (int truncates decimal part) and counter = 1
999 divided by 10 = 99 (int truncates decimal part) and counter = 2
99 divided by 10 = 9 (int truncates decimal part) and counter = 3
9 divided by 10 = 0 (int truncates decimal part) and counter = 4
Then I compare it to the symbolic name value which is 4 and if they are the same length I say its valid, and if not, its not valid.
But how do I account for a pin beginning with zero...
As #Olaf said, read the pin as a string. Define your pin as follows: char pin[PIN_LENGTH + 1], with the '+1' for the '\0' character. Then in scanf, you can say scanf("%4s", pin) to read the 4 characters. Finally, when you want to drag the values down, you can simply subtract a '0' from the character read at any position and treat them as integers from there on.
You cannot actually if you read it as an integer. One thing you can do is to read it as a string, count its length and find out if its right input or not. Afterwards you can use the ASCII table to convert the chars into integers in order to get each pin number.
You can change the type of pin to char * and do this
#include <stdio.h>
int size(char *, int);
int main() {
char pin[5];
printf("Enter your pin: ");
fgets(pin, sizeof(pin), stdin);
if(size(pin, sizeof(pin)/sizeof(char)) == 5) {
printf("Valid pin of 4 digits\n");
} else {
printf("Invalid pin of %d digits\n", size(pin) - 1);
}
return 0;
}
int size(char * a, int size) {
int i;
for (i = 0; a[i] != '\0' && i < size; i++);
return i;
}
fgets() is a better approach, but to do this task with scanf()...
Use "%n" to record the number of characters scanned.
printf("Enter your PIN: ");
int n1, n2;
if (scanf(" %n%d%n", &n1, &pin, &n2) == 1 && (n2 - n1) == 4)) {
// Success, 4 character `int` has been read.
}
Note: This will accept "+123".