tags:

views:

4032

answers:

13

I have a lot of java background and am new to C. If the input integer is 11031, I want to count the number of 1's digits, how would I do this?

I know in java I can take the input as a String and use charAt, but I understand there is no implicit String function in C...

+4  A: 

Division and modulus are your friends.

#include "stdio.h"

int main(){
    int digits[] = {0,0,0,0,0,0,0,0,0,0};
    int i = 11031;

    while(i > 0){
     digits[i % 10]++;
     i = i / 10;
    }

    printf("There are %d ones.\n", digits[1]);
}
Aaron Maenpaa
+1  A: 

Homework?

You'd read it into a char* using the fread() function, and then store how many bytes were read in a separate variable. Then use a for loop to iterate through the buffer and count how many of each byte are present.

John Millikin
+1  A: 

If you have just the number, then you can do this:

 int val; //Input
 ...
 int ones = 0;
 while(val != 0) {
   ones += ((val % 10) == 1) ? 1 : 0;
   val /= 10;
 }

If you have a string (char*), the you'd do something like this:

while(*str != '\0') {
  if(*str++ == '1') {
    ones++;
  }
}

It's also worth noting that c does have a charAt function, in a way:

"java".charAt(i) == "c the language"[i];

By indexing into the char*, you can get the value you want, but you need to be careful, because there is no indexOutOfBounds exception. The program will crash if you go over the end of a string, or worse it may continue running, but have a fucked up internal state.

Patrick
A: 

Something along the lines of:

int val=11031;
int count=0;
int i=0;
char buf[100];
sprint(buf, "%d", val);
for(i=0; (i < sizeof(buf)) && (buf[i]); i++) {
  if(buf[i] == '1')
    count++;
}
kfh
A: 

Try something like...

int digit = 0;
int value = 11031;

while(value > 0)
{
    digit = value % 10;
    /* Do something with digit... */
    value = value / 10;
}
Jarrett Meyer
A: 
int count_digit(int nr, int digit) {
    int count=0;
    while(nr>0) {
      if(nr%10==digit)
        count++;
      nr=nr/10;
    }
    return count;
}
A: 

While this somewhat looks like homework to me, it provides the opportunity to correct a misunderstanding about strings in C. C strings are just an array of characters terminated by a nul character ('\0'). You can explicitly convert between a character and an integer in C.

int count_digits(int digit, const char *in)
{
   int ii, count = 0;
   if (digit < 0 || digit > 9) return -0;
   digit = digit + (int)'0'; /* make the digit the correct ascii value */

   for (ii = 0; in[ii] != '\0'; ++ii)
   {
      if (in[ii] == (char)digit) count++;
   }

   return count;
}

Of course, you could always change that method to be "smarter":

int count_chars(char ch, const char *in)
{
   int ii, count = 0;
   for (ii = 0; in != NULL && in[ii] != '\0'; ++ii)
   {
      if (in[ii] == ch) count++;
   }

   return count;
}

Now you could just make count_digits call count_chars.

sixlettervariables
This of course assumes your input is a string. If you input is an integer, you'll have to use something like modulo arithmetic.
sixlettervariables
A: 

This sounds like a homework problem to me. Oh well, it's your life.

You failed to specify the type of the variable that contains the "input integer". If the input integer is an integral type (say, an "int") try this:

int countOnes(int input)
{
    int result = 0;
    while(input) {
        result += ((input%10)==1);
        result /= 10;
    }
    return result;
}

If the "input integer" is in a string, try this:

int countOnes(char *input)
{
    int result = 0;
    while(input && *input) {
        result += (*input++ == '1');
    }
    return result;
}

Hope this helps. Next time, do your own homework. And get off of my lawn! Kids, these days, ...

Rob Adams
A: 
int countDigit(int Number, int Digit)
{
   int counter = 0;

   do
   {
      if( (Number%10) == Digit)
      {
         counter++;
      }
   }while(Digit>0)

   return counter;
}
Robert
A: 

Something along the lines of this:

#include <stdio.h>

main() {
        char buf[100];
        char *p = buf;
        int n = 0;
        scanf("%s", buf);
        while (*p) {
                if (*p == '1') {
                        n++;
                }
                p++;
        }
        printf ("'%s' contains %i ones\n", buf, n);
}
Mr Shark
A: 

This will do it. :-)

int count_digits(int n, int d) {
  int count = 0;
  while(n*10/=10) if (n%10==d) count++
  return count;
}
hoyhoy
A: 

For all those who refer to the question as the homework question: I have to say, most of you provided a homework answer.

You don't do division/modulus to get the digits in production code, firstly because it's suboptimal (your CPU is designed for binary arithmetics not decimal) and secondly because it's unintuitive. Even if it's not originally a string, it's more optimal to convert it to one and then count the characters (std::count is the way to go in C++).

melfar
The only way to convert an integer to string, is using division/modulus. Even if you use the simplest method possible (itoa from C), it is done this way... In conclusion, the @hoyhoy answer is more optimized than yours, as you need to first convert the integer and then count characters
rossoft
+1  A: 

I see this as a basic understanding problem, which inevitably everyone goes through switching from one language to the next.

A good reference to go through to understand how string's work in C when you've started familiarity with java is look at how string.h works. Where as in java string's are an Object and built in, strings in C are just integer arrays.

There are a lot of tutorials out there, one that helped me when I was starting earlier in the year was http://www.physics.drexel.edu/students/courses/Comp_Phys/General/C_basics/ look at the string section.

Sometimes asking a question speeds up learning a lot faster than pouring through the text book for hours on end.

Ren