I need to write a function that subtracts from right to left digits of array elements and prints absolute value of them.
For array a[4]={101, 3002, 70008, 900001}, program would print:
OUTPUT: 11 302 7008 90001
Explanation: abs(1-0)=1, abs(0-1)=1, so first printed number is 11
#include <stdio.h>
#include <stdlib.h>
int subtract(int a[], int y, int k) {
int count[100] = {0}, n[100], b[100][100], number[100], x;
n[k] = a[k];
while (n[k] != 0)
{
n[k] /= 10;
count[k] ;
}
number[k] = count[k];
if (count[k] != 0) {
count[k] = 0;
n[k] = a[k];
while (n[k] != 0) {
b[k][count[k]] = n[k] % 10;
n[k] /= 10;
count[k] ;
}
}
int i;
for (i = number[k] - 2; i >= 0; i--) {
return abs(b[k][i] - b[k][i 1]);
}
}
int main() {
int a[4] = {101, 3002, 70008, 900001}, n = 4, i;
for (i = 0; i < n; i ) {
printf("%d ", subtract(a, n, i));
}
return 0;
}
My code prints (1 3 7 9) only first digits of numbers that should be printed. How to make it print all digits like in output?
CodePudding user response:
This works for every entered array, with one mistake that it always has one digit 1 surplus at the end.
#include <stdio.h>
#include <stdlib.h>
int subtract(int a[], int y, int k) {
int count[100] = {0}, n[100], b[100][100], number[100], x;
n[k] = a[k];
while (n[k] != 0) {
n[k] /= 10;
count[k] ;
}
number[k] = count[k];
if (count[k] != 0) {
count[k] = 0;
n[k] = a[k];
while (n[k] != 0) {
b[k][count[k]] = n[k] % 10;
n[k] /= 10;
count[k] ;
}
}
int i;
for (i = number[k] - 2; i >= 0; i--) {
printf("%d", abs(b[k][i] - b[k][i 1]));
}
}
int main() {
int a[4] = {101, 3002, 70008, 900001}, n = 4, i;
for (i = 0; i < n; i ) {
printf("%d ", subtract(a, n, i));
}
return 0;
}
