Counting occurance of a specific number in an integer in C - c

I'm having some troubles... I'm trying to input a number, followed by an integer of multiple numbers. I am trying to count how many times the first number occurs in the integer.
Now, I made this really easy code to show you what I actually am trying to do. The thing is, this code only compares two integers and tells me if they are the same or not. Mind you, I am very unexperienced in C programming, hence this question...
int main(){
int numberOne;
int numberTwo;
int count = 0;
scanf("%d", &numberOne);
scanf("%d", &numberTwo);
if(numberOne == numberTwo){
count++;
}
printf("Amount of equals found: %d", count);
return 0;
}
Now, if I'd have the following input: '1 1021023234', the output would be: 'Amount of equals found:0'
The output should be (in this case) 'The output would be Amount of equals found:2'
I hope you guys can give me some tips.

If I have understood correctly then you need the following
#include <stdio.h>
int main(void)
{
unsigned int numberOne;
unsigned int numberTwo;
unsigned int x;
unsigned int base;
size_t n;
printf( "Enter first number: " );
scanf( "%u", &numberOne );
printf( "Enter second number: " );
scanf( "%u", &numberTwo );
x = numberOne;
base = 1;
do { base *= 10; } while ( x /= 10 );
n = 0;
do { n += numberOne == numberTwo % base; } while ( numberTwo /= 10 );
printf( "Amount of equals found: %u", n );
return 0;
}
For numbers 12 and 76512612 the output is
Amount of equals found: 2

you can read them as integer but you cannot compare them the way you are doing. to compare them you need to extract each digit from the number and compare.
temp = numbertwo % 10; //this gives the digit in the unit place
if(temp == numberone)
count++;
numbertwo = numbertwo / 10; //this now removes the last digit that has already been compared
keep the above code in a loop until numbertwo becomes zero. and it will work as you wanted
another way to do this would be to read the integer as a String.
char* numbertwo;
char = malloc(20);
fgets(numbertwo, 20, stdin);
and then compare the integer in a for loop

Write the code yourself. Here are the hints:
Since you need only one input,eliminate numbertwo from your program and implement the following:
numberone%10 would give the first digit of the user input. Assign it to a variable one.
If user input(numberone)<10 , print first digit is found 1 time in input and exit the program.
Use a while loop and put numberone>=10 in its condition.check if(numberone%10==one) in the loop if true,increment variable count. Add
numberone/10 after it.
Print your last printf and end the program

You can try it using strings as below..
#include<stdio.h>
#include<string.h>
main()
{
char int1[100];
char int2[100];
int cnt=0;
scanf("%s",int1);
scanf("%s",int2);
char *p;
while(p=strstr(s1,s2)) //searches for the string s2 in s1 and if found, returns the address to the pointer p//
{
cnt++
s1=p+strlen(s2); //now s1 points to the next location from the end of string s2 in s1//
}
printf("Amout of equals found:%d\n",cnt");
}

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.

Frequency digit counting

I'm trying to find the frequency of digit into given string,which contain digit and letters. When i run the same program i get different result, look like random output. where is the problem ?
int main() {
char num[1001];
int digit[10];
int j,i;
int count;
scanf("%s",num);
for(i=48;i<=57;i++)
{
count = 0;
for(j=0; num[j] != EOF;j++)
{
if(num[j] == i)
{
count++;
}
}
printf("%d ",count);
}
return 0;
}
You have missed an & in the line with scanf before num. Correct code should be:
scanf("%s", &num);
When you are scanning for the value, you need to provide the address of the variable. That is you let your program know where to put the value. &num points to the address of the variable num. But if you just write scanf("%s",num) you are providing value of the num variable, which you don't care at all. You'll be overwriting that value anyway.
At the end of the string, computer puts a null character \0 whose ASCII value is 0, to denote that this is the end of the string. Kind of like a '.' but for a computer. So you check until you find the null character in the for loop like: num[j] != '\0' [Not EOF]
I don't see any issue here, it seems output is not readable properly
so try printing correctly like
printf("%c=>%d ",i, count);
so that you can read what number how many times. if you find wrong frequency,
post the input for which you are getting wrong output.
It seems like you're trying to compare a char element with an integer type.
for example:
char num[7] = {"ABC123");
if (num[3] == 1)
{
printf("True\n");
}
else
{
printf("False\n");
}
return 0;
// This will return False, even though the element at index 3 is "1".
I've ran your code, and it seems like the output is the same given the same input.
Edit:
We wanted to compare a two digit number to a char data type - which is essentially a character - a one digit number/case.
When we take a number N and modulo by 10, we get the last digit, example:
48 % 10 = 8
To get the first digit we simply divide by 10, and take the quotient, example:
48 / 10 = 4 (remainder 8).
With this knowledge, we can compare the n-th char with first digit, and the n+1-th char with the last one (given that we only compare two digits, we'll stop at n+1-th).
Tip: a number char can be turned into a int using char = char - '0'
char num[1001];
int digit[10];
int j,i;
int count;
scanf("%s",num);
for(i=48;i<=57;i++)
{
count = 0;
for(j=0; num[j] != EOF;j++)
{
if(num[j] - '0' == i / 10 && num[j+1] - '0' == i % 10)
{
printf("%c", num[j] - '0');
count++;
}
}
printf("%d: %d \n",i, count);
}
printf("\n");
return 0;
// This code will print the digits and the frequency in a new line:
48: n times
49: n times
.
.
.
57: n times

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

Addition of numbers from string delimited by ' . '

I want to write a C program which will take an IP address from the user like "112.234.456.789" in a string and give formatted output in addition of each block in string, e.g., "04.09.15.24" for the above IP address. Here's what I have so far:
#include<stdio.h>
#include<string.h>
#include<conio.h>
main()
{
char s[15],d[11];
int i=0,c = 0, sum[4] = {0};
d[i]=sum[c]/10;
printf("Enter ip address:");
gets(s);
printf("\n \n %s",s);
i=0;
for(c=0;c<15;c++)
{
if(s[c]!='.'||s[c]!='\0')
sum[i]=(s[c]-48)+sum[i];
else
i++;
}
for(i=0,c=0;c<4;c++,i+=3)
{
d[i]=(sum[c]/10)+48;
d[i+1]=sum[c]%10+48;
d[i+2]='.';
}
printf("\n \n %s",d);
getch();
}
The input should be an IP address like "112.234.546.234", and the output should be the result of adding the digits in each block, "04.09.15.06". The input and output should be in strings.
The problem with your code is that s[c]!='.'||s[c]!='\0' is going to evaluate true for any character in the input -- even '.'. This means i is never incremented, and ot only is every digit is summed to sum[0], but so is '.' - 48.
What you meant was s[c] != '.' && s[c] != '\0'.
I wrote the function you desire here.
#include <stdio.h>
#include <ctype.h>
void convert(const char *in, char *out) {
unsigned int sum = 0;
char ch;
do {
ch = *in++;
if (isdigit(ch)) {
sum += ch - '0';
} else {
*out++ = sum / 10 + '0';
*out++ = sum % 10 + '0';
if (ch == '.') {
*out++ = '.';
sum = 0;
}
}
} while (ch);
}
By the way, each "block" of the IPv4 address is an octet, and what you are doing is replacing each with its digit sum.
I just code you a simple example of how to "discard" unwanted characters.
#include <studio.h>
main ()
{
int add1, add2, add3, add4;
printf("enter an ip in the form xxx.xxx.xxx.xxx: )";
scanf("%d%*c%d%*c%d%*c%d", &add1, &add2, &add3, &add4);
printf("add1 = %d add2 = %d add3 = %d add4 = %d\n\n", add1, add2, add3, add4);
return 0;
}
console output:
enter a ip in the form xxx.xxx.xxx.xxx: 123.321.456.654
add1 = 123 add2 = 321 add3 = 456 add4 = 654
EDIT: you just have to play along with the "add#" variables to do your math thing.
It looks like homework (if this is the case, please tag it as homework), so I am going to give a few pointers:
Use fgets to read the input from the user. Read the input into a string.
Use sscanf to parse the string. Since you know there will be four positive integers, use "%u.%u.%u.%u" as the format string.
For each one of the four integers, compute the sum of the digits (using division by 10 and remainder by 10, as you just did).
Print the formatted output using printf (or snprintf to print to a string). If you want each sum to be formatted as a two-digits integer, with leading 0, use "%02u" as format specifier.
P.S. Be careful with snprintf, it might bite.
Other tips
Focus on one step at a time. Divide and conquer. Write a digit_sum function, taking an integer as argument, which computes the sum of its digits:
unsigned int digit_sum(unsigned int n)
{
unsigned int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
Once your digit_sum function is working well, proceed with the main task.

Help on string handling in C

In a program to find whether the given number is an Armstrong number, I stored the input no (3 digit) as string as follows.
char input[10];
scanf("%s",&input);
Now I have to calculate cube of each digit by using pow method of math.h as follows.
int a;
a = pow(input[0],3);
By coding like this, I could not get correct result. If I print the value of "a", it shows some irrelevant answer. My doubt is, how to convert from string value to integer value?
You are performing your calculation on the ASCII value of the digit. You'll need to convert it to a numeric value like so:
int digit = input[0] - '0';
int a; a = pow(digit, 3);
There are two problems, both already detailed. The first is that your scanf needs a char*, not a char**. Fix this with what Jeremy said:
scanf("%s", input);
Next, calculate the power correctly, like Adam said:
a = pow(input[0]-'0',3);
You do not need to get the address of the input array using &input. Simply passing input will pass the pointer to your string to scanf(). Your call to scanf() should look like this:
scanf("%s", input);
Another way of doing it, with the address of operator:
scanf("%s", &input[0]);
armstrong numbers are numbers that exhibit the armstron property in any given base, not just base 10.
int isArmstrong(int n, int b)
{
int sum = 0;
int n2 = n;
int nDigits = 0;
while(n2 != 0)
{
nDigits++;
n2 /= b;
}
n2 = n;
for(int i = 0; i < nDigits; i+++)
{
sum += pow(n2 % b, nDigits);
n2 /= b;
}
return sum == n;
}
On the other hand, you may need to replace the power with a more generic one like power = strlen(input)
so the code should look like this.
char input[10];
int power, sum = 0;
scanf("%s", input);
power = strlen(input);
sum += pow(input[0] - '0', power);
/* you need to compare in here */
Doh, I might have spend too much time far of C, because I think most of the answers here miss the final goal... The advice on dropping the & is fine, of course, but there are several other issues with the scanf.
First, it should be OK for throw away code/homework, but it is dangerous: type 11 chars and get a buffer overflow.
Second, IIRC, since you need a number, you should use an int variable and get that. Untested code from a rusty mind:
int inputNumber;
scanf("%d", &inputNumber);
Here you need the & because you no longer have a pointer.
C should do the conversion for you, and you have a safer input.
Other problematic code:
int a = pow(input[0], 3);
You are not making math with the first digit, but with the Ascii value of the first digit! Ie. 49 for 1, 50 for 2...
Since you got a number from my previous correction, divide it by the correct power of 10 to get the digit.
If you prefer to go the string route, use input[0] - '0' at least.
Freehand coding, building on #PhiLho's idea to use an actual integer input:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a, sum, i;
printf("Enter an Armstrong number, an integer in the range 100..999:\n");
if(scanf("%d", &a) != 1)
return EXIT_FAILURE;
if(a < 100 || a > 999)
return EXIT_FAILURE;
/* Now extract digits, and compute sum of cubes. */
for(sum = i = 0; i < 3; i++)
{
sum += pow(a % 10, 3);
a /= 10;
}
printf("sum is: %d\n", sum);
return EXIT_SUCCESS;
}

Resources