Count times digits appear in a number C - c

I am trying to make a code in C that takes a number as an input, counts how many times 0-9 appears in the given number.
The code as nooby as it might is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,dig,dat[9],mod;
printf("Give a number: ");
scanf("%d",&num);
mod = num % 10;
while(mod != 0)
{
if(mod > 1)
{
dig = mod / 10;
while(dig >= 0 )
{
++dat[dig];
}
}
else if(mod =1)
{
dig = mod/1;
while(dig >= 0 )
{
++dat[dig];
}
}
--mod;
}
printf("%d appears %d\n",dig,dat[dig]);
return 0;
}
Thanks in advance
Nothing really works, i dont even get any response from printf.

#include <stdio.h>
int main(void) {
int n = 12334268;
int digits[10] = {0};
while(n)
{
++digits[n%10];
n/=10;
}
for(int i=0; i<10; ++i)
{
if (digits[i])
{
printf("Digit %d appears %d times\n", i, digits[i]);
}
}
return 0;
}
Output
Success #stdin #stdout 0s 5512KB
Digit 1 appears 1 times
Digit 2 appears 2 times
Digit 3 appears 2 times
Digit 4 appears 1 times
Digit 6 appears 1 times
Digit 8 appears 1 times

For starters the array dat shall have 10 elements because there are 10 digits 0-9.
dat[10],
And moreover you are using the uninitialized array
++dat[dig];
If the entered number is divisible by 10 then the while loop is skipped
mod = num % 10;
while(mod != 0)
{
//...
So the code does not make sense.
Pay attention to that you should deal with unsigned integers. Otherwise the program shall take into account the sign of the entered number.
Also the user can enter 0 that is a valid number containing one digit 0.
The program can look the following way.
#include <stdio.h>
int main( void )
{
enum { N = 10 };
unsigned int digits[N] = { 0 };
unsigned int num;
printf( "Give a number: " );
if ( scanf( "%u",&num ) == 1 )
{
const unsigned int Base = 10;
do
{
++digits[num % Base];
} while ( num /= Base );
puts( "The number contains the following digits:" );
for ( unsigned int i = 0, j = 0; i < N; i++ )
{
if ( digits[i] != 0 )
{
if ( j != 0 ) printf( ", " );
printf( "%u: %u", i, digits[i] );
j = 1;
}
}
}
}

Related

How to get sequence of numbers and then print the last 5?

Im trying to make a program that will get sequence from the user that end with 0, and then i want to print the last 5 numbers (not including the 0).
I can assume that the user will input all the numbers in one line and will end it with 0.
I wrote that code but something is wrong with it, I think its something about the scanf line.
Input:
1 6 9 5 2 1 4 3 0
Output: no output
#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;
printf("please enter more than %d number and than enter 0: \n", N);
last_input = 0;
while (last_input<N) {
scanf(" %d", &j);
if (j == '0') {
last_input = N;
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}
printf("The last %d numbers u entered are:\n", N);
for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);
}
for (j=0; j<last_input; ++j) {
printf(" %d", arr[j]);
}
return 0;
}
This comparison
if (j == '0') {
does not make a sense because the user will try to enter the integer value 0 instead of the value (for example ASCII 30h or EBCDIC F0h) for the character '0'.
You need to write at least
if (j == 0) {
Due to these sub-statements of the if statement
last_input = N;
break;
this for loop
for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);
}
is never executed and does not make a sense.
This statement
last_input=-1;
results in breaking the order of the N last elements in its output. And moreover the result value of the variable last_input will be incorrect.
You need to move elements of the array one position left. For this purpose you can use a loop of standard C function memmove.
The program can look the following way.
#include <stdio.h>
#include <string.h>
int main( void )
{
enum { N = 5 };
int arr[N];
printf( "Please enter at least not less than %d numbers (0 - stop): ", N );
size_t count = 0;
for (int num; scanf( "%d", &num ) == 1 && num != 0; )
{
if (count != N)
{
arr[count++] = num;
}
else
{
memmove( arr, arr + 1, ( N - 1 ) * sizeof( int ) );
arr[N - 1] = num;
}
}
if (count != 0)
{
printf( "The last %zu numbers u entered are: ", count );
for (size_t i = 0; i < count; i++)
{
printf( "%d ", arr[i] );
}
putchar( '\n' );
}
else
{
puts( "There are no entered numbers." );
}
}
The program output might look like
Please enter at least not less than 5 numbers (0 - stop): 1 2 3 4 5 6 7 8 9 0
The last 5 numbers u entered are: 5 6 7 8 9
I made some changes based on ur comments and now its work fine!
#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;
printf("please enter more than %d number and than enter 0: \n", N);
last_input = 0;
while (last_input<N) {
scanf("%d", &j);
if (j == 0) {
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}
printf("The last %d numbers u entered are:\n", N);
for (j=(last_input); j<N; ++j) {
printf("%d ", arr[j]);
}
for (j=0; j<last_input; ++j) {
printf("%d ", arr[j]);
}
return 0;
}
thank u guys <3.

counting consecutive value and printing in c programming

how to count consecutive two heads and tails in this program please help me, I am really stuck, I tried hard but failed please, write the code for consecutive please, I am very hopeful that StackOverflow can help me
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int flip();
int main()
{
int loop;
int headCount = 0;
int tailCount = 0;
srand( time( NULL ) );
for ( loop = 1; loop <= 100; loop++ ) {
if ( flip() == 0 )
{
tailCount++;
}
else
{
headCount++;
}
if ( loop % 10 == 0 )
{
printf( "\n" );
}
}
printf( "\nThe total number of consecutive Heads was %d\n", headCount );
printf( "The total number ofconsecutive Tails was %d\n", tailCount );
return 0;
}
int flip() {
int HorT = rand() %2;
if ( HorT == 0) {
printf( "Tails " );
}
else
{
printf( "Heads " ); }
return HorT;
}
I don't know how you want to count 4 consecutive runs of a tail (is that 3, or 4 or 2?), and I'm not going to worry too much about it. Mostly posting this to point out some stylistic issues with your code. You can greatly simplify what you're doing with something like:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int flip(void);
int
main(int argc, char **argv)
{
int loop;
int max = argc > 1 ? strtol(argv[1], NULL, 10) : 100;
int count[2] = {0, 0};
int prev = -1;
srand(time(NULL));
for( loop = 0; loop < max; loop++ ) {
int t = flip();
if( t == prev ) {
count[t] += 1;
}
if( loop % 10 == 9 || loop == max - 1 ) {
putchar('\n');
}
prev = t;
}
printf( "\nThe total number of consecutive Heads was %d\n", count[0]);
printf( "The total number of consecutive Tails was %d\n", count[1]);
return EXIT_SUCCESS;
}
int
flip(void)
{
int HorT = rand() % 2;
fputs(HorT ? "Heads " : "Tails ", stdout);
return HorT;
}

C code is giving zero value every time. What can I correct?

I am starter in the C.I wrote a simple code which are calculating how many digits are the entered Number and sum of entered number’s digits.Code calculating digit count right but sum of digits being given as ‘0’ every time.Could you say where is my error?thanks.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
int ndigit(int val) {
if (val == 0)
return 0;
int digit_count = 1;
while ((val = getchar() != '\n')) {
digit_count++;
val /= 10;
}
return digit_count;
}
int sumdigit(int number) {
int result = 0;
while ((number = getchar()) != '\n'){
result += number - '0';
}
return result;
}
int main()
{
int a;
printf("Bir tam sayi giriniz: \n");
a = getchar();
printf("Bu sayinin basamak sayisi =%d", ndigit(a));
printf("Bu sayinin basamak degeri toplami= %d", sumdigit(a));
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
The program does not make sense. To enter a number you should use one function. That is the number of digits and the sum of digits must be calculated for the same number.
This condition in the while statement
while ((val = getchar() != '\n')) {
is equivalent to
while ( ( val = ( getchar() != '\n' ) ) ) {
and as a result the integer val gets either 1 or 0.
As the variable val stores an internal representation of a character (for example its ASCII value) then this statement
val /= 10;
also does not make sense. Also the user can enter a non-digit character.
You should either use a character array for the entered number by means of calls of the function getchar or use the function scanf to enter a value of an integer object.
If to use a character array then the program can look the following way
#include <stdio.h>
char * get_number( char *number, size_t n )
{
size_t i = 0;
int c;
while( i + 1 < n && ( c = getchar() ) != EOF && c != '\n' && '0' <= c && c <= '9' )
{
number[i++] = c;
}
number[i] = '\0';
return number;
}
size_t ndigit( const char *number )
{
size_t n = 0;
while ( number[n] != '\0' ) ++n;
return n;
}
unsigned int sumdigit( const char *number )
{
unsigned int sum = 0;
while ( *number != '\0' )
{
sum += *number++ - '0';
}
return sum;
}
int main(void)
{
enum { N = 50 };
char number[N];
printf( "Bir tam sayi giriniz: " );
get_number( number, N );
printf( "Bu sayinin basamak sayisi = %zu\n", ndigit( number ) );
printf( "Bu sayinin basamak degeri toplami = %u\n", sumdigit( number ) );
return 0;
}
The program output might look like
Bir tam sayi giriniz: 123456789987654321
Bu sayinin basamak sayisi = 18
Bu sayinin basamak degeri toplami = 90
If to use an integer number then the program can look the following way
#include <stdio.h>
size_t ndigit( unsigned long long number )
{
const unsigned long long Base = 10;
size_t n = 0;
do
{
++n;
} while ( number /= Base );
return n;
}
unsigned int sumdigit( unsigned long long number )
{
const unsigned long long Base = 10;
unsigned int sum = 0;
do
{
sum += number % Base;
} while ( number /= Base );
return sum;
}
int main(void)
{
unsigned long long number = 0;
printf( "Bir tam sayi giriniz: " );
scanf( "%llu", &number );
printf( "Bu sayinin basamak sayisi = %zu\n", ndigit( number ) );
printf( "Bu sayinin basamak degeri toplami = %u\n", sumdigit( number ) );
return 0;
}
The program output might look as it is shown above.
Bir tam sayi giriniz: 123456789987654321
Bu sayinin basamak sayisi = 18
Bu sayinin basamak degeri toplami = 90
You code has 3 getchar() that are independent. Just use one getchar, either in main, or ndigit or sumdigit.
I propose, you should get the number in main function using scanf instead of getchar(), then pass the number as the argument to the other functions (ndigit and sumdigit). Because getchar reads character by character, and it does not guarantee the character is a digit or not.
The main function becomes:
int main () {
int num;
printf("enter the number: ");
scanf("%d", &num);
// calling the ndigit and sumdigit function:
printf("sum of digits = %d\n number of digits = %d\n", sumdigit(num), ndigit(num));
return 0;
}
For two function ndigit and sumdigit, you can change to:
ndigit function:
int ndigit(int number) {
number = abs(number); // calculate abs if the number is negative
if(number == 0)
return 1;
int count = 0;
do {
count++;
num /= 10;
} while(num != 0);
return count;
}
sumdigit function:
int sumdigit(int number) {
number = abs(number); // calculate abs if the number is negative
int sum = 0, temp = 0;
while (number != 0) {
temp = number % 10;
sum += temp;
number /= 10;
}
return sum;
}
The complete code:
#include <stdio.h>
#include <stdlib.h>
int ndigit(int number) {
number = abs(number); // calculate abs if the number is negative
if(number == 0)
return 1;
int count = 0;
do {
count++;
number /= 10;
} while(number != 0);
return count;
}
int sumdigit(int number) {
number = abs(number); // calculate abs if the number is negative
int sum = 0, temp = 0;
while (number != 0) {
temp = number % 10;
sum += temp;
number /= 10;
}
return sum;
}
int main () {
int num;
printf("enter the number: ");
scanf("%d", &num);
// calling the ndigit and sumdigit function:
printf("sum of digits = %d\nnumber of digits = %d\n", sumdigit(num), ndigit(num));
return 0;
}
The output of test:
enter the number: 222333
sum of digits = 15
number of digits = 6
After using scanf, change your sumdigit while loop to:
while (number > 0) {
result += number % 10;
number /= 10;
}

Need 10 outputs per line

I am having trouble refining some code. My code takes a number "n" and calculates that many prime numbers. I need to display 10 primes per line of output data. Any tips would be appreciated.
#include <stdio.h>
int main()
{
int n, i = 3, count, c;
printf("How many primes would you like?");
scanf("%d",&n);
if ( n >= 1 )
{
printf("2");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf(" %d",i);
count++;
}
i++;
}
return 0;
}
Just try
printf(" %5d", i);
/* ^ to help align the numbers
and
if ((count + 1) % 10 == 0)
fputc(stdout, '\n');
fix for the first time when you already print 2.
bool is_prime(int anyNum) //takes an integer array returns, is_prime
{
bool is_prime = true;
for (int c = 2; c <= anyNum - 1; c++)
{
if (anyNum % c == 0)
{
//printf("%d is not prime\r\n" , anyNum);
is_prime = false;
}
}
return is_prime;
}
int main()
{
int num_primes;
printf("How many primes would you like: ");
std::cin >> num_primes;
printf("\r\nScanned Primes Are---\r\n");
int foundPrimes = 0;
int x = 0;
for (; x <= num_primes; x++)
{
bool gotLuckyFindingPrime = is_prime( x );
if (gotLuckyFindingPrime)
{
if (foundPrimes % 10 == 0)
{
printf("\r\n");
}
printf(" %d", x);
foundPrimes = (foundPrimes + 1) % 10;
}
}
}
Does handle ten digit showing on cmd too, you can experiment with formatting

C Programming While Loop Assignment

Question: Take n as input. Then take n numbers as input and print the summation of those n numbers. But this time output as the format below.
Example:
Input:
4
1 5 3 -4
output 1 + 5 + 3 – 4 = 5
I got the output value correctly, but I do not know how am I going to show the actual summation sequence, especially in one line....
My Code:
main ()
{
int n,m,cnt=0,sum=0;
printf("Input: ");
scanf("%d", &n);
while(cnt<n)
{
scanf("%d\b", &m);
sum=sum+m;
cnt=cnt+1;
if(m>0 && m!=n)
{
printf("\b+",m);
}
else if (m<0)
{
printf("%d",m);
}
}
printf("=%d\n\n",sum);
}
Here's a sample solution that I came up with:
#include <stdio.h>
int main() {
int n = 0,
count = 0,
sum = 0;
int first = 1;
printf("How many numbers do you wish to sum? " );
scanf("%d", &n);
while (count < n) {
int m;
scanf("%d\b", &m);
if (!first) {
if (m < 0) {
printf("- %d ", -m);
} else {
printf("+ %d ", m);
}
} else {
first = !first;
printf("%d ", m);
}
sum += m;
count++;
}
printf("= %d\n\n", sum);
return 0;
}
Here's a sample execution:
$ gcc stackoverflow.c -o stackoverflow
$ ./stackoverflow
How many numbers do you wish to sum? 5
1 -2 -3 4 10 -40
1 - 2 - 3 + 4 + 10 = 10
If the summation sequence is to be printed after the input, the problem could be solved by using a dynamically allocated array int[] of length n in which the input is read. After the input is read, the actual summation can be done and the summands can be printed, as they have been stored in the array. The dynamic allocation can be done with the malloc function; you would also have to use the free function after the summation.
Catch!:)
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
unsigned int n = 0;
printf( "Enter number of items (0-exit): " );
scanf( "%u", &n );
if ( n != 0 )
{
int items[n];
printf( "Enter %u numbers: ", n );
unsigned int i = 0;
while ( i < n && scanf( "%d", &items[i] ) == 1 ) ++i;
int sum = 0;
_Bool first = 1;
n = i;
for ( i = 0; i < n; i++ )
{
sum += items[i];
if ( !first || items[i] < 0 )
{
printf( "%c ", items[i] < 0 ? '-' : '+' );
}
if ( first ) first = 0;
printf( "%u ", ( unsigned int )abs( items[i] ) );
}
printf( "= %d\n", sum );
}
return 0;
}
The output might look like
Enter number of items (0-exit): 4
Enter 4 numbers: 1 5 3 -4
1 + 5 + 3 - 4 = 5
#include <stdio.h>
int main()
{
int num;
int answer=0;
do
{
printf("\nEnter the number(s) to be added: (enter 0 to quit) ");
scanf("%d", &num);
answer=answer + num;
}
while (num!=0);
printf("Answer is %d", answer);
return 0;
}
Advantage of above approach is that you don't require an array and don't have to declare the no. of values that you are adding. Sort of like adding using a calculator where you simply press the "=" button when you are done.

Resources