Please tell me how to print num in the same form as 122333 when num = 123 is entered in c.
I can make a repetition of a number separately, but I can't print it out by adding it to num.
you can get the number of digits first in your desired number, then you can get digit by digit from the left using the equation digit = num / (10^(numOfDigits)) % 10 where numOfDigits is just a variable used to indicate which digit to extract right now.
so when you get digit by digit you can use for-loop to loop digit times on that digit to be printed.
so you can do something like:
#include <stdio.h>
#include <math.h>
int main() {
int num = 123;
int numOfDigits = 0;
int dummy = num;
// finding number of digits
while (dummy != 0)
{
// increment number of digits
numOfDigits++;
// go to next digit
dummy /= 10;
}
printf("output = ");
while (numOfDigits != 0){
// get the current digit
int digit = (num / (int)pow(10,(numOfDigits-1))) % 10;
for (int i = 0; i < digit; ++i) {
// print the number
printf("%d", digit);
}
// go to next digit
numOfDigits--;
}
printf("\n");
return 0;
}
and this is the output:
output = 122333
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.
The problem says that the user will input numbers till he inserts 0 (exit) then if there are any prime digits in that given number, the program shall multiply them.
For example:
input : 4657
output : 35 ( 5 * 7 )
Here is what I have tried so far but I cannot pull it off with the multiplication... my code might look a little bit clumsy, I am a beginner :)
int main() {
int number;
int digit, prime;
int i, aux;
int multiplier;
input:
printf("Give Number :");
scanf("%d", &number);
do {
multiplier = 1;
digit = number % 10;
number = number / 10;
printf("%d \n", digit);
prime = 1;
for (i = 2; i <= sqrt(digit); i++) {
if (digit % 1 == 0) {
prime = 0;
}
}
if (prime != 0) {
multiplier = multiplier * digit;
}
} while (number != 0);
printf("The result : %d\n", multiplier);
goto input;
return 0;
}
There are multiple problems in your code:
missing #include <stdio.h>
use of label and goto statement to be avoided at this stage.
testing for prime digits can be done explicitly instead of a broken loop.
digit % 1 == 0 is always true, you should write digit % i == 0 (maybe a typo from copying someone else's code?
i <= sqrt(digit) will not work unless you include <math.h> and still a bad idea. Use i * i < 10 instead.
0 and 1 should not be considered primes.
it is unclear what the output should be if none of the digits are prime, let's assume 1 is OK.
Here is a modified version:
#include <stdio.h>
int main() {
for (;;) {
int number, multiplier;
printf("Give Number :");
if (scanf("%d", &number) != 1 || number <= 0)
break;
multiplier = 1;
while (number != 0) {
int digit = number % 10;
number = number / 10;
if (digit == 2 || digit == 3 || digit == 5 || digit == 7)
multiplier *= digit;
}
printf("The result: %d\n", multiplier);
}
return 0;
}
Expected Input:
123456
Expected output:
12
34
56
I have tried in this way
#include <stdio.h>
int main()
{
// Put variables for further proceed
int number, remainder, quotient = 1, numberUpdate, count = 0;
int value = 10000;
/*This for input validation. User can give exactly 6 digit as an input If
user breaks this condition then It
will redirect back to take input again */
while (1)
{
int countUpdate = 0;
int quotientUpdate = 1;
printf("Enter a number: ");
scanf("%d", &number);
numberUpdate = number;
while (quotientUpdate != 0)
{
quotientUpdate = numberUpdate / 10;
numberUpdate = quotientUpdate;
countUpdate++;
}
if (countUpdate > 6 || countUpdate < 6)
{
printf("It allows exactly 6 digits\n");
}
else
{
break;
}
}
//This for finding the pair of two consecutive digits.
while (quotient != 0)
{
count++;
if (count == 4)
{
break;
}
quotient = number / value;
remainder = number % value;
if (count != 2)
printf("%d\n", quotient);
if (count == 1)
{
number = remainder;
}
else
{
number = quotient;
}
if (count == 1)
{
value = value / 1000;
}
if (count == 3)
{
remainder = remainder * 10 + 6;
printf("%d\n", remainder);
}
}
return 0;
}
My problem is: I have made this for the exact input 6 digits. From my code, I did not get the expected output. Output comes from my code like:
If a user gives an input 987654
Output shows:
98
76
56
But my expectation is:
98
76
54
Here is another problem: this code does not work for less than 6 or greater than 6 digits. But I want to solve this problem for any number of digit.
Can you help me identifying and solving my problem?
Your solution is a bit overcomplicated.
If you want to use integers, you could do it like this (untested).
Depending on range for your number, you might change to long long.
#include <stdio.h>
int main(void)
{
int number;
int digits = 1;
while (digits & 1)
{ // loop until we get an even number
printf("Enter a number: ");
int ret = scanf("%d", &number);
if (ret != 1)
continue;
// count number of digits
digits = 0;
while (number != 0)
{
number /= 10;
digits++;
}
if (digits & 1)
printf("Please enter even number of digits.\n");
}
// If we are here, we have 2, 4, 6, ... digits
// Calculate divider to chop first 2 digits
int divider = 1;
while (digits > 2)
{
divider *= 100;
digits -= 2;
}
// chop remaining digits and print 2 of them
while (divider)
{
pair = (number / divider) % 100;
printf("%d\n", pair);
divider /= 100;
}
return 0;
}
Another option would be to use strings instead of numbers and then simply print 2 characters per line.
I've updated your code a bit, it should be working and handle the "0" digit within the code. For the "0" digit at the beginning of the code, you should input a string and not a number.
#include <stdio.h>
int main()
{
// Put variables for further proceed
int number, remainder, quotient = 1, numberUpdate, count = 0;
int countUpdate = 0;
int value = 10000;
/*This for input validation. User can give exactly 6 digit as an input If
user breaks this condition then It
will redirect back to take input again */
while (1)
{
int quotientUpdate = 1;
printf("Enter a number: ");
scanf("%d", &number);
numberUpdate = number;
while (quotientUpdate != 0)
{
quotientUpdate = numberUpdate / 10;
numberUpdate = quotientUpdate;
countUpdate++;
}
if (countUpdate < 2 || countUpdate % 2 != 0)
{
printf("Even number of digits only\n");
}
else
{
break;
}
}
count = countUpdate / 2;
numberUpdate = number;
int d[count];
for (int i = 0; i < count; i++)
{
d[i] = numberUpdate % 100;
numberUpdate /= 100;
}
for (int i = count - 1; i >= 0; i--)
{
if (d[i] < 10) printf("0");
printf("%d\n", d[i]);
}
return 0;
}
Before proposing my solution, I'll try to explain what's wrong in your code.
Analysis of the original code
First of all, since you have currently the fixed length limitation, your loop that checks if the number has exactly 6 digits can be omitted; the same check can be performed just checking the range:
if (number < 1000000 || number > 999999)
{
printf("It allows exactly 6 digits\n");
}
else
{
break;
}
The core of your logic is in the loop while (quotient != 0). It contains a lot of strange attempts you perform in order to compensate the previous mistake. It leads to the final reminder with a single digit instead of two, so you try to compensate it with this line
remainder = remainder * 10 + 6;
this obviously works only if the last digit is 6.
The root of the problem is in this row:
if (count == 1)
{
value = value / 1000;
}
But why 1000? value represents the divider in the next loop, so you want it to obtain a reminder with two digit less (instead of 3), so the correct division is value = value / 100;.
All the subsequent correction come after this one. The other answers widely cover the correct solution storing the input within an integer.
A solution involving strings
Since you need a solution with any number of digits, you must be aware that using an int you'll be able to manage at most 10 digits (because the maximum value of an integer is INT_MAX (2147483647).
Using an integer you'll only be limited by the size of the string buffer you choose.
That's the code. Our only limitation is forcing the user to insert only an even number of digits:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
// Put variables for further proceed
char number[101] = { 0 };
int isValid = 0, count = 0;
/*Input validation */
while(!isValid)
{
count = 0;
isValid = 1;
char *p = number;
printf("Enter a number: ");
scanf("%100s", number);
/* Check the validity of the string */
while(*p != '\0')
{
count++;
if(!isdigit(*p))
{
isValid = 0;
break;
}
p++;
}
if( !(isValid = isValid && ( count % 2 == 0 ) ) )
printf("Please insert an even number of digits (numbers only)\n");
}
/* Print the digits*/
for(int i=0; i<count; i+=2)
printf("%c%c\n", number[i], number[i+1] );
return 0;
}
I defined an array of 101 characters (100 + one for the string terminator) and I say scanf to store up to 100 characters (%100s)
I complicated a bit the input validator just to avoid to loop twice through the string (the first using strlen(), needed to check the even digits requirement,and the second to check the digits-only requirement)
In the end I just print two characters at a time using %c format specifier reading them from the string number
The output:
Enter a number: 1234567 // Test the check on an input with an odd number of digits
Please insert an even number of digits (numbers only)
Enter a number: 1234567A // Test the check on an input containing a non-digit char
Please insert an even number of digits (numbers only)
Enter a number: 1234567890123456 // Well formed input
12
34
56
78
90
12
34
56
Here is my solution to this problem. Hope it satisfy your requirement.
#include <stdio.h>
int main()
{
// Put variables for further proceed
int number, remainder, quotient = 1, numberUpdate, temp,count = 0;
int value = 1;
printf("Enter a number: ");
scanf("%d", &number);
numberUpdate = number;
temp = number;
if(number < 100) {
printf("%d",number);
} else {
while(numberUpdate > 100) {
value = value*100;
numberUpdate = numberUpdate/100;
}
while (temp > 0)
{
temp = number/value;
number = number%value;
value = value/100;
printf("%d\n",temp);
}
}
return 0;
}
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
I am writing a C program to ask the user to enter in a pin code and checks if each digit in the number is divisible by 2. For instance, if they enter 123452 it tells the user that it is wrong because 1,2,3,5 isn't divisible by 2. If I enter 642642 it says it is fine but if I enter in 622248 it displays invalid number, which is wrong because every digit in 622248 is divisible by 2. How can I fix this error?
#include <stdio.h>
#define N 6
int main(void)
{
int num, digits[N], i, invalid, count = 1, sum = 0;
TOP:
printf("Enter pin code (attempt %d): ", count++);
scanf("%d", &num);
invalid = num;
// stores each digit of the number entered into the the array
for (i = 6; i >= 0; i--) {
digits[i] = num % 10;
num = num / 10;
}
// if the user enters more than 6 digits than it will give you an error.
if (digits[N] > 6) {
printf("Code %d is invalid!\n", invalid);
goto TOP;
}
// loops through the array elements and see if each digit is divisble by 2, if not then print an error.
for (i = 0; i < 6; i++) {
if (digits[i] % 2 != 0) {
printf("Code %d is invalid!\n", invalid);
goto TOP;
}
else {
printf("Congratulation, code %d is valid!\n", invalid);
break;
}
}
return 0;
}
If you are permitted to process the input as a string, rather than an integer, all that is needed is strspn to determine the validity of the digits in the pin and strlen to determine the validity of the length:
#include <string.h>
size_t len = strlen(str_pin);
if (len <= 6 && strspn(str_pin, "24680") == len)
{
puts("Valid pin");
}
else
{
puts("Invalid pin");
}
There's a problem with how you're storing the digits:
for (i = 6; i >= 0; i--) {
digits[i] = num % 10;
num = num / 10;
}
The length of the array digits is 6, meaning that valid indexes go from 0 to 5, but you start reading into index 6. This writes past the bounds of the array invoking undefined behavior.
Change the loop to start at 5.
for (i = 5; i >= 0; i--) {
digits[i] = num % 10;
num = num / 10;
}
This check is also invalid:
if (digits[N] > 6) {
Because it again reads past the end of the array. Even if it did not read past the end, you're checking if an element of the array is greater than 6, not if there are more than 6 digits.
You divide num by 10 in a loop to get the digits, so if this value is non zero then you know there are too many digits.
if (num > 0) {