How many times a digit is appeared in a number - c

Well, I wrote the code and everything is fine except one thing.
When I enter that digit number, which has to be upto 10 digits, I recieve in arr[0] various values, for example, if I enter "12345" I get 20, 1 , 1 , 1 , 1 , 1 , 0 ,0 ,0 ,0.
Which is fine from arr[1] to arr[9], but pretty odd in arr[0].
Any ideas?
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
int i,j,p=0, temp,indexNum, arr[10] = { 0 }, num, level = 10, level2 = 1,maxIndex;
printf("Please enter a digit number (upto 10 digits) \n");
scanf("%d", &num);
temp = num;
while (temp > 0)
{
p++;
temp /= 10;
}
for (i = 0;i < p;i++)
{
temp = num;
while (temp > 0)
{
indexNum = num % level / level2;
arr[indexNum]++;
level *= 10;
level2 *= 10;
temp /= 10;
}
}
for (j = 0; j < 10; j++)
{
printf("%d\n", arr[j]);
}
getch();
}

Here is simplified version of your program:
#include <stdio.h>
#include <math.h>
int main()
{
int i = 0, j = 0, temp = 0, indexNum = 0, num = 0, level = 10;
int arr[10] = {0};
num = 7766123;
temp = num;
if(0 == temp) arr[0] = 1; // Handle 0 input this way
while (temp > 0)
{
indexNum = temp % level;
arr[indexNum]++;
temp /= 10;
}
for (j = 0; j < 10; j++)
{
printf("%d\n", arr[j]);
}
return 0;
}

A few hints to help you:
What does arr[10] = { 0 } actually do?
When you calculate indexNum, you are dividing integers. What happens when the modulus is a one-digit number, and level2 is greater than 1?

It's probably easier to read the input into a string and count digit characters. Something like this (not tested):
std::map<char, int> count;
std::string input;
std::cin >> input;
for (auto iter = input.begin(); iter != input.end(); ++iter) {
if (*iter < 0 || *iter > 9)
break;
else
++count[*iter];
}
for (auto iter = count.begin(); iter != count.end(); ++iter) {
std::cout << *iter << '\n';
}

You need to get rid of your first for loop. Something more like:
#include <stdio.h>
#include <math.h>
using namespace std;
int main()
{
int j;
int temp;
int indexNum;
int arr[10] = { 0 };
int num;
int level = 10;
int level2 = 1;
printf("Please enter a digit number (upto 10 digits) \n");
scanf("%d", &num);
temp = num;
while (temp > 0)
{
indexNum = num % level / level2;
arr[indexNum]++;
level *= 10;
level2 *= 10;
temp /= 10;
}
for (j = 0; j < 10; j++)
{
printf("%d\n", arr[j]);
}
return 0;
}

Check the program below.
void count_digits(unsigned int a, int count[])
{
unsigned int last_digit = 0;
if (a == 0) {
count[0] = 1;
}
while (a != 0)
{
last_digit = a%10;
count[last_digit]++;
a = a/10;
}
}
int main()
{
int count[10]= {0};
unsigned int num = 1122345; /* This is the input, Change it as per your need */
int i = 0;
count_digits(num, count);
for (i = 0; i < 10; i++)
{
printf ("%d: -- %d\n", i, count[i]);
}
return 0;
}

Related

Remove all digits from array

Write a function remove_digits that receives two arrays of type int. The first array contains a number of integers, and the second array is an array of digits. It is necessary to remove all digits from second array which are present in first array.
The function returns 1 if the ejection was successful.The function returns 1 if the eject was successful, and 0 if the array of digits is incorrect for some reason, if the array contains a value less than 0 or greater than 9, or if one of the members is repeated.
EXAMPLE 1:
int first[2]={12345, -12345},second[2]={3,5};
OUTPUT: 124 -124
EXAMPLE 2:
int first[5]={25, 235, 1235, 252, 22552255},second[3]={2,3,5};
OUTPUT: 0 0 1 0 0
My algorithm:
check if digit in second array is less than 0 or grater than 9 or digit is repeated, and in that case return 0 (finish program)
for negative numbers make them positive and in the end of first (for) loop make them negative
in the second (while) loop break number into digits, and for every number check if it's present in second array
if it is present, remove last digit
continue to the rest of elements
Code:
#include <stdio.h>
#include <stdlib.h>
int sum_of_digits(int n) {
int i, sum = 0;
while (n > 0) {
sum++;
n /= 10;
}
return sum;
}
int divide(int n) {
int num_of_digits = sum_of_digits(n);
switch (num_of_digits) {
case 1:
break;
case 2:
break;
case 3:
n /= 10;
break;
case 4:
n /= 100;
break;
case 5:
n /= 1000;
break;
case 6:
n /= 1000;
break;
case 7:
n /= 10000;
break;
case 8:
n /= 100000;
break;
case 9:
n /= 1000000;
default:
break;
}
return n;
}
int remove_digits(int *first, int n, int *second, int vel) {
// first - removing digits from second
// second - searching for digits
int i, j, num, digit, neg = 0;
for (i = 0; i < vel; i++) {
// invalid digit
if (second[i] < 0 || second[i] > 9)
return 0;
for (j = i + 1; j < vel; j++)
// repeated digit
if (second[j] == second[i])
return 0;
}
for (i = 0; i < n; i++) {
// negative case
if (first[i] < 0) {
first[i] = abs(first[i]);
neg = 1;
}
num = first[i];
while (num > 0) {
digit = num % 10;
for (j = 0; j < vel; j++)
if (second[j] == digit)
// remove last digit
first[i] = divide(first[i]) - digit;
num /= 10;
}
if (first[i] <= 0)
first[i] = 0;
if (neg == 1)
first[i] *= -1;
}
return 1;
}
int main() {
int first[2] = {12345, 12345}, second[2] = {3, 5}, i;
remove_digits(first, 2, second, 2);
for (i = 0; i < 2; i++)
printf("%d ", first[i]);
return 0;
}
MY OUTPUT: 4 4
Could you help me to modify my algorithm to work correctly?
simplified approach for your problem would be as follows,
#include <stdio.h>
#include <stdlib.h>
int removeDigit(int src, int digit){
int neg = (src < 0)?-1:1;
int num = abs(src);
src = 0;
//remove digit
while(num){
int num_digit = num%10;
if(num_digit != digit){
src = src * 10 + num_digit;
}
num /= 10;
}
//reverse number
while(src){
num = num * 10 + src%10;
src /=10;
}
return num*neg;
}
int remove_digits(int *first, int n, int *second, int m) {
// first - removing digits from second
// second - searching for digits
int i, j;
for (i = 0; i < m; i++) {
// invalid digit
if (second[i] < 0 || second[i] > 9)
return 0;
for (j = i + 1; j < m; j++)
// repeated digit
if (second[j] == second[i])
return 0;
}
for (i = 0; i < n; ++i) {
for(j =0; j<m; ++j){
first[i]= removeDigit(first[i],second[j]);
}
}
return 1;
}
int main() {
{
printf("Test 1\n");
int first[] = {12345, 12345}, second[] = {3, 5}, i;
remove_digits(first, sizeof(first)/sizeof(first[0]), second, sizeof(second)/sizeof(second[0]));
for (i = 0; i < sizeof(first)/sizeof(first[0]); i++)
printf("%d ", first[i]);
}
{
printf("\n\nTest 2\n");
int first[] = {25, 235, 1235, 252, 22552255}, second[] = {2,3,5}, i;
remove_digits(first, sizeof(first)/sizeof(first[0]), second, sizeof(second)/sizeof(second[0]));
for (i = 0; i < sizeof(first)/sizeof(first[0]); i++)
printf("%d ", first[i]);
}
return 0;
}

I want to print the following pyramid of number pattern

1
2 4
3 5 7
6 8 10 12
9 11 13 15 17
Following is the code in which I am not able to print the pyramid:-
int main()
{
int i,j;
for(i=1;i<=5;i++){
for(j=1;j<=i;j++){
printf("%d ",i*j);
}
printf("\n");
}
return 0;
}
You need to track both even and odd numbers .
#include <stdio.h>
int main()
{
int even=1,odd=2;
int n=10;
for (int i = 1; i <= n; i++)
{
int a= (i % 2 == 0);
for (int j = 1; j < i; j++)
{
if(a)
{
printf("%d ",even);
}
else
{
printf("%d ",odd);
}
even += a ? 2 : 0;
odd += a ? 0 : 2;
}
printf("\n");
}
return 0;
}
Not very clean and compact algorithm but sth like this would work:
#include <stdio.h>
#include <stdlib.h>
int main() {
char tmp[10];
int n = 0, row = 1, odd = 1, even = 2, c = 0, selectOdd, fin = 0;
printf("maximum number: ");
scanf("%s", tmp);
n = atoi(tmp);
if (n != 0) {
while (fin < 2) {
selectOdd = row % 2;
c = row;
if (selectOdd) {
while (c != 0) {
printf("%3d", odd);
odd += 2;
if (odd > n) {
fin++;
break;
}
c--;
}
}
else {
while (c != 0) {
printf("%3d", even);
even += 2;
if (even > n) {
fin++;
break;
}
c--;
}
}
printf("\n");
row++;
}
}
return 0;
}
it's simple
your algorithm is odd, even, odd,... and so on
so you start with odd number until reach line number
for next line is even and you can find start number with this
you just need find number at start of line and continue print number number
in each step you just need
num += 2;
remember 'lineIndex' start from 1
num = (lineIndex - 1) * 2 + lineIndex % 2;
this is a full code
#include <stdio.h>
int main(){
int numIndex;
int lineIndex;
int num;
for (lineIndex = 1; lineIndex <= 5; lineIndex++) {
num = (lineIndex - 1) * 2 + lineIndex % 2;
for (numIndex = 0; numIndex < lineIndex; numIndex++) {
printf("%2d ", num);
num += 2;
}
printf("\n");
}
}

How to find the nth number?

For an assignment, I have to write code which accepts as input an integer n and outputs the nth 'superunusual' number.
The first few su-numbers are: 22, 23, 26, 33, ... So when the input is 1, the output should be 22. 2 gives 23 and 3 gives 26.
I already have a code that checks if the input number is a su-number, but I can't find a way to calculate the nth number.
So when I now input 22, it says that 22 is a superunusual number.
The code:
/* calculates largest prime factor */
int lprime(int n) {
int max = -1;
while (n % 2 == 0) {
max = 2;
n /= 2;
}
for (int i = 3; i*i <= n; i += 2) {
while (n % i == 0) {
max = i;
n = n / i;
}
}
if (n > 2) {
max = n;
}
return max;
}
/* check unusual number */
int unus(int n) {
/* find largest prime of number */
int factor = lprime(n);
/* Check if largest prime > sqrt(n) */
if ((factor*factor) > n) {
return 1; /* true */
}
else {
return 0; /* false */
}
}
/* delete digit from number */
int del(int num, int n) {
int d = log10(num)+1; /* checks amount of digits */
int revnew = 0;
int new = 0;
for (int i = 0; num != 0; i++) {
int dig = num % 10;
num = num / 10;
if(i == (d - n)) {
continue;
} else {
revnew = (revnew * 10) + dig;
}
}
for (int i = 0; revnew != 0; i++) {
new = (new*10) + (revnew % 10);
revnew = revnew / 10;
}
return new;
}
/* driver code */
int main(int argc, char* v[]) {
int m=22, n;
int x = 0;
int i = 1;
int counter = 0;
scanf("%d", &n);
int d = log10(m)+1;
while (counter < n) {
if (unus(m++)) {
counter++;
}
}
for(unus(m); i < d; i++) {
int nmin = del(m, i);
if (unus(nmin)) {
continue;
} else {
printf("%d is not supurunusual\n", (m-1));
x++;
}
}
if(x==0) {
printf("%d is superunusual!\n", (m-1));
}
return 0;
}
I hope you can understand my code. Otherwise I will explain it better.
Also, I'm quite new to coding, so please don't be to harsh...
You have a function to determine whether a number is unusual, but you do the check whether a number is super-unusual in the body of the main routine. If you extract that code into a proper function:
int is_superunusual(int m)
{
int d = log10(m) + 1;
if (unus(m) == 0) return 0;
for(int i = 0; i < d; i++) { // see footnote
int nmin = del(m, i);
if (unus(nmin) == 0) return 0;
}
return 1;
}
then you can use Eugene's code:
while (counter < n) {
if (is_superunusual(m++)) {
counter++;
}
}
printf("The su number #%d is %d\n", n, m - 1);
Your code tested for unusual numbers, not super-unusual numbers.
Footnote: If you take del(num, n) to mean "remove the nth digit from the end", you can do away with the log10 call in del. You must check all deletions anyway, so the order doesn't really matter here.

A simple program for splitting numbers does not display zeroes

I wrote a simple program in c that accepts two numbers and then splits the first number considering the digits of the second number like this:
Input:
362903157 2313
Output:
36
290
3
157
Everything works just fine, except when there are zeroes in the first number, my program skips them. For instance the upper example gives me this output:
36 293 1 570
And that is mycode:
#include <stdio.h>
int nDigits(unsigned i) {
int n = 1;
while (i > 9) {
n++;
i /= 10;
}
return n;
}
// find the highest multiple of 10
int multipleOfTen(int num){
int multiple = 1;
while(multiple <= num){
multiple *= 10;
if(multiple > num){
multiple /= 10;
break;
}
}
return multiple;
}
int main(){
int n, m, digit;
scanf("%d %d", &n, &m);
int lengthOfM = nDigits(m);
for (int i = 0; i < lengthOfM; i++){
digit = m / multipleOfTen(m); //2
for(int j = 1; j <= digit; j++){
printf("%d", n/multipleOfTen(n));
n = n% multipleOfTen(n);
}
printf("\n");
m = m % multipleOfTen(m);
}
return 0;
}
What should I change in my program so that the zeroes won't be ignored?
Instead of calling multipleOfTen() in each loop, call it once and save the result for both n and m. Then in each loop divide those results by 10
#include <stdio.h>
int nDigits(unsigned i) {
int n = 1;
while (i > 9) {
n++;
i /= 10;
}
return n;
}
// find the highest multiple of 10
int multipleOfTen(int num){
int multiple = 1;
while(multiple <= num){
multiple *= 10;
if(multiple > num){
multiple /= 10;
break;
}
}
return multiple;
}
int main(){
int n, m, digit;
int i, j;
int n10, m10;
scanf("%d %d", &n, &m);
int lengthOfM = nDigits(m);
n10 = multipleOfTen(n); //get the multiple of ten once
m10 = multipleOfTen(m);
for ( i = 0; i < lengthOfM; i++){
digit = m / m10;
m10 /= 10;
for( j = 0; j < digit; j++){
printf("%d", n/n10);
n = n% n10;
n10 /= 10;// divide by 10
}
printf("\n");
m = m % multipleOfTen(m);
}
return 0;
}
I suppose an approach like this is inadmissible?
#include <stdio.h>
#include <string.h>
int main ( void ) {
char n[64];
char m[64];
char * p = n;
int i = 0;
int c;
scanf("%63[0-9] %63[0-9]", n, m);
while ((c = m[i++]) != '\0') {
int j = c - '0';
while (j-- > 0) if (*p) putchar(*p++);
putchar(' ');
}
putchar('\n');
return 0;
}
when n=903157 and after n = n% multipleOfTen(n); n becomes 3157 not 03157 so when u dividing again in line printf("%d", n/multipleOfTen(n)); it prints 3 not 0 what you want!!
Fix your code to produce right output.

Largest palindrome made from the product of two 3-digit numbers with C

The code is trying to find the largest palindrome made from the product of two 2-digit numbers. The answer is 91*99 = 9009 but I keep getting 990, which is not even a palindrome. I really appreciate the help!
#include <stdio.h>
int main()
{
int i = 10;
int j = 10;
int a = 0;
int b = 0;
int array[100] = {0};
int divider = 10;
int num;
int great;
int product;
int n;
int flag;
/*Loop through first 2 digit number and second 2 digit number*/
while (i<100)
{
while (j < 100)
{
product = i*j;
array [a] = product % 10;
n = product / divider;
while (n != 0)
{
a++;
num = n%10;
divider *=10;
array[a]=num;
n = product/divider;
}
flag = 0;
while (b<a)
{
if (array[b] != array[a])
{
flag = 1;
}
b++;
a--;
}
if (flag == 0)
{
great = product;
}
j++;
a = 0;
b = 0;
}
i++;
}
printf("The largest palindrome is %d \n", great);
return 0;
}
Here is a code snippet you can try.
#include <stdio.h>
void main()
{
int a = 1; // first integer
int b = 1; // second integer
int currentNumber;
int currentPalin; if a palindrome is found, its stored here
while (a<100){ //loop through the first number
while (b<100){ // loop through the second number
currentNumber = a*b;
if (currentNumber == reverse(currentNumber) ){ //check for palindrome
currentPalin = currentNumber;
}
b = b+1; //increment the second number
}
b = a; // you could have set b=1 but it would not be an efficient algorithm because
//some of the multiplication would occur twice. eg- (54*60) and (60*54)
a = a +1; //increment the first number
}
printf ("Largest palindrom is %d \n", currentPalin);
getchar();
}
// method for finding out reverse
int reverse(int n){
int reverse = 0;
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
// when you divide a number by 10, the
//remainder gives you the last digit. so you are reconstructing the
//digit from the last
n = n/10;
}
return reverse;
}
Update:- As suggested by M Oehm, I have modified the code to make it more general.
#include <stdio.h>
void main()
{
int a = 1;
int b = 1;
int currentNumber;
int currentPalin=0;
while (a<100){
while (b<100){
currentNumber = a*b;
if (currentNumber == reverse(currentNumber) ){
if (currentNumber>currentPalin){
currentPalin = currentNumber;
}
}
b = b+1;
}
b = 1;
a = a +1;
}
if (currentPalin==0){
printf("No Palindrome exits in this range");
}
else {
printf ("Largest palindrome is %d \n", currentPalin);
}
getchar();
}
int reverse(int n){
int reverse = 0;
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
return reverse;
}
An alternative approach to solve the problem.
#include<stdio.h>
int reverse(int num)
{
int result = 0;
while( num > 0)
{
result = result * 10 + (num%10);
num/=10;
}
return result;
}
int main()
{
int last_best = 1;
int best_i=1;
int best_j = 1;
const int max_value = 99;
for( int i = max_value ; i > 0 ; --i)
{
for(int j = i ; j > 0 ; --j){
int a = i * j;
if( last_best > a )
break;
else if ( a == reverse(a) )
{
last_best = a;
best_i = i;
best_j = j;
}
}
}
printf("%d and %d = %d\n", best_i,best_j,last_best);
}
And it is quite simple to follow.
It seems that you do not reinitialize variables at the beginning of loop. They keeps values from previous iterations. For example, j and divider. Put
j = 10;
before starting "j" loop, i.e.:
j = 10;
while (j < 100) ...
The same for divider:
...
j = 10;
while (j < 100) {
divider = 10;
...
If you were using for loops you would avoid this problem naturally:
for(i=10; i<100; i++) {
for(j=10; j<100; j++) {
...
}
}

Resources