Using for loop to find minimal sum of digits in given number interval - c

So, I am doing a task that asks to find the amount of positive integers from interval [m, n] with minimum sum of digits.
I declared a function that computes the sum of digits, however I am having problems finding the amount of numbers. Below is the code I wrote for finding the minimum sum of digits and counting. I hope I made myself clear. I would appreciate if you could help me fix this code.
Input: 1 100
Output: 3
int minSum(int m, int n){
for (int i=m; i<=n; i++){
int sm=sum(i);
if (sm<min) min=sm;
if (min==sm) cnt++;
}
return cnt;
}

Problems:
cnt and min not initialized in the function (nor defined)
cnt is not reset when a new minimum value is found.
Your code is easy to fix. Like:
int minSum(int m, int n){
int cnt = 0; // Initialize cnt
int min = INT_MAX; // Initialize min to a high value
for (int i=m; i<=n; i++){
int sm=sum(i);
if (sm<min)
{
cnt = 0; // Reset cnt
min=sm;
}
if (min==sm) cnt++;
}
return cnt;
}

For starters the variables min and cnt are not declared within the function. If they are a file scope variables then using file scope variables in the function is a bad idea.
The function can look the following way. I assume that sum of digits can not be a negative number.
unsigned int minSum( int m, int n )
{
unsigned int cnt = 0;
int min = 0;
if ( !( n < m ) )
{
do
{
int sm = sum( m );
if ( sm < min )
{
min = sm;
cnt = 1;
}
else if ( !( min < sm ) )
{
++cnt;
}
} while ( m++ != n );
}
return cnt;
}
Pay attention to that the for loop in your original code
for (int i=m; i<=n; i++){
can invoke undefined behavior for example when n is equal to INT_MAX.

int sum(int x)
{
int result = 0;
while(x)
{
result += abs(x % 10);
x /= 10;
}
return result;
}
size_t minSum(int m, int n){
int min = sum(m);
int sm;
size_t cnt = 0;
for (int i = m + 1; i <= n; i++)
if ((sm = sum(i)) < min) min = sm;
for (int i = m; i <= n; i++)
if (sum(i) == min) cnt++;
return cnt;
}
Or less brute force:
size_t minsum(int m, int n){
int min = sum(m);
int sm;
size_t cnt = 1;
for (int i = m + 1; i <= n; i++)
{
sm = sum(i);
if (sm < min)
{
min = sm;
cnt = 1;
}
else if(sm == min) cnt++;
}
return cnt;
}

Related

Hiding even numbers from display in array in C

Any suggestion on how to hide even numbers from user input and only printing odd numbers in ascending order? Like this output describes:
5
3
2
8
7
OUTPUT:
3
5
7
Press any key to continue . . .
I've been trying to figure it out in few hours but was unable to figure the solution :( .
#include <stdio.h>
#include <time.h>
void sort(int number[], int count)
{
int temp, i, j, k;
for (j = 0; j < count; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (number[j] > number[k])
{
temp = number[j];
number[j] = number[k];
number[k] = temp;
}
}
}
printf("OUTPUT:\n");
for (i = 0; i < count; ++i)
printf("%d\n", number[i]);
}
void main()
{
int i, number[1000];
int count = 5;
printf("\nType your number:");
for (i = 0; i < count; ++i)
scanf("%d", &number[i]);
sort(number, count);
}
Just add 'if(number[i]%2==0)' in your program.
#include <stdio.h>
#include <time.h>
void sort(int number[], int count)
{
int temp, i, j, k;
for (j = 0; j < count; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (number[j] > number[k])
{
temp = number[j];
number[j] = number[k];
number[k] = temp;
}
}
}
printf("OUTPUT:\n");
for (i = 0; i < count; ++i)
if(number[i]%2!=0)
printf("%d\n", number[i]);
}
void main()
{
int i, number[1000];
int count = 5;
printf("\nType your number:");
for (i = 0; i < count; ++i)
scanf("%d", &number[i]);
sort(number, count);
}
try to use the following code will solve your problem :
#include <stdio.h>
#include <time.h>
void sort(int number[], int count)
{
int temp, i, j, k;
int numbs[100];
int counter = 0;
for(int h=0; h<count; ++h){
if(number[h] % 2 != 0){
numbs[counter] = number[h];
counter++;
}
}
for (j = 0; j < counter; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (numbs[j] > numbs[k])
{
temp = numbs[j];
numbs[j] = numbs[k];
numbs[k] = temp;
}
}
}
printf("OUTPUT:\n");
for (i = 0; i < counter; ++i)
printf("%d\n", numbs[I]);
}
void main()
{
int i, number[1000];
int count = 5;
printf("\nType your number:");
for (i = 0; i < count; ++i)
scanf("%d", &number[i]);
sort(number, count);
}
There are many ways to accomplish the task, the following might be an overkill.
Consider the interface and usage of qsort to sort an array of int in ascending order.
#include <stdlib.h>
// It needs a function that compares the values
int cmp_int(void const *lhs, void const *rhs)
{
int const a = *(int *)lhs;
int const b = *(int *)rhs;
return (b < a) - (a < b);
}
int main(void)
{
int a[] = {42, 17, -3, 0, 8, -2, 33};
size_t const a_size = (sizeof a) / (sizeof a[0]);
qsort(a, a_size, // The source array and the number of its elements.
sizeof(a[0]), // The size of each element.
cmp_int); // The pointer to the comparator function.
// ...
}
You can adapt the same concepts and write a function that prints only the odd elements.
#include <stdbool.h>
#include <stdio.h>
bool is_odd(int x)
{
return (x % 2) != 0;
}
void print_if(char const *fmt,
size_t n, int const *a,
bool (*predicate)(int))
{
for (size_t i = 0; i < n; ++i)
{
if ( predicate(a[i]) )
printf(fmt, a[i]);
}
putchar('\n');
}
int main(void)
{
int a[] = //...
size_t const a_size = //...
// ...
// Sort 'a', hopefully using qsort.
print_if("%d ", a_size, a, is_odd);
// ...
}
As an alternative, you could copy only the odd elements into another (suitably sized) array, sort it and print it all.
size_t copy_if(size_t n, int const *src,
int *dst,
bool (*predicate)(int))
{
size_t j = 0;
for ( size_t i = 0; i < n; ++i )
{
if ( predicate( src[i] ) )
{
dst[j] = src[i];
++j;
}
}
return j; // Note that the number of elements copied is returned. Use it!
}
Live example #Compiler Explorer.
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
As the declared array has 1000 elements then it means that the user may enter any number of values no greater than 1000. Otherwise there is no sense to declare an array with 1000 elements to enter only 5 numbers. That is you should ask the user how many integers he is going to enter.
Your sort function does not distinguish odd and even numbers. It tries to sort all elements of the array though it seems you need to sort only elements with odd values.
To sort only elements with odd values of an array you could use for example the bubble sort algorithm.
Also you should split sorting and outputting elements with odd values in two separate functions.
Here is a demonstration program that shows how the task can be performed.
#include <stdio.h>
void sort_odds( int a[], size_t n )
{
size_t i = 0;
while ( i != n && a[i] % 2 == 0 ) i++;
if ( i != n )
{
a += i;
n -= i;
for ( size_t last = 0; !( n < 2 ); n = last )
{
last = 0;
size_t previous = 0;
for ( size_t j = 0; j < n; j++ )
{
if ( a[j] % 2 == 1 )
{
if ( a[j] < a[previous] )
{
int tmp = a[j];
a[j] = a[previous];
a[previous] = tmp;
last = j;
}
previous = j;
}
}
}
}
}
void display_odds( const int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
if ( a[i] % 2 == 1 ) printf( "%d ", a[i] );
}
putchar( '\n' );
}
int main(void)
{
enum { N = 1000 };
int number[N];
size_t count = 0;
printf( "Enter the number of integers you want to input (no more than %d): ", N );
scanf( "%zu", &count );
if ( count != 0 )
{
if ( N < count ) count = N;
printf( "Enter your integers: " );
int num;
size_t i = 0;
for ( ; scanf( "%d", &num ) == 1 && i < count; i++ )
{
number[i] = num;
}
sort_odds( number, i );
display_odds( number, i );
}
}
The program output might look like
Enter the number of integers you want to input (no more than 1000): 10
Enter your integers: 9 8 7 6 5 4 3 2 1 0
1 3 5 7 9

A number formed by every k-th digit of another number in c

Given some natural numbers n and k, my goal is to write a C program that outputs a number formed by every k-th digit of n. I wrote a program as follows:
#include <stdio.h>
#include <math.h>
#define MAX 100
void printDigit(int n, int k)
{
int arr[MAX];
int i = 0;
int j, r;
while (n != 0) {
r = n % (int)pow(10,k);
arr[i] = r;
i++;
n = n / pow(10,k);
}
for (j = i - 1; j > -1; j--) {
printf("%d ", arr[j]);
}
}
int main()
{
int n = 12345678;
int k = 2;
printDigit(n,k);
return 0;
}
My code outputs the same number but partitioned into substrings of length k. Why is that and how can I fix it so that I get the number I wanted?
Your logic is too complicated, but if you want to stick to it:
int intpow(int x, int y)
{
int result = 1;
while(y--) result *= x;
return result;
}
void printDigit(int n, int k)
{
int arr[MAX];
int i = 0;
int j, r, powv;
while (n != 0) {
powv = intpow(10,k -1);
n /= powv;
if(!n) break;
r = n % 10;
arr[i] = r;
i++;
n = n / 10;
}
for (j = i - 1; j > -1; j--) {
printf("%d ", arr[j]);
}
}
n % (int)pow(10,k) is the low-order k digits of n. If you just want one digit, use n % 10.
Since pow(10, k) returns a double, it might not be an exact integer. You should round it to the nearest integer to do proper division.
void printDigit(int n, int k)
{
int arr[MAX];
int i = 0;
int j, r;
int divisor = lround(pow(10, k));
while (n != 0) {
r = n % 10;
arr[i] = r;
i++;
n = n / divisor;
}
for (j = i - 1; j > -1; j--) {
printf("%d ", arr[j]);
}
}

how can i replace scanf with for loop counter?

I am writing a program in order to count all achilles numbers without the math.h library. In this programm first I calculate powerful numbers after that I calculate GCD of powerful number. If GCD is 1 then the current number is achilles.
My problem is that my program works with scanf() but not with for loop counter! What i am doing wrong?
Thank you very much!
#include <stdio.h>
#define MAX 1000
int main(void)
{
int n;
int i, j, a;
int counter2 = 0;
int large;
int small;
int rem, gcd, max = 1, min = 1;
int achilles;
for (a = 1; a <= MAX; a++) //for loop for counter
{
n=a;
for (i = 1; i <= n; i++)
{
int count = 0;
for (j = 1; j <= i; j++)
{
if (i % j == 0)
{
count++;
}
}
int l = 0;
if (count == 2)
{
while (n % i == 0) // calculate factor and his exponent
{
l++;
n = n / i;
}
if (l > max) // calculates min and max in order to find GCD
{
max = l;
}
if (l < min)
{
min = l;
}
}
large = max;
small = min;
while (small) { // While small is not 0
// Calculates GCD
rem = large % small;
large = small;
small = rem;
}
gcd = large;
// printf("GCD(%d,%d)= %d", large, small, gcd);
}
if (gcd == 1) {
achilles = n;
// printf("%d\n", achilles);
}
// printf("GCD(%d,%d)= %d", max, min, gcd);
printf("%d\n", achilles);
}
}
The programm before editing with the for loop is the following!
#include <stdio.h>
#define MAX 1000
int main(void)
{
int n;
int i, j, a;
int counter2 = 0;
int large;
int small;
int rem, gcd, max = 1, min = 1;
int achilles;
scanf("%d", &n);
printf("%d = ",n);
for (i = 1; i <= n; i++)
{
int count = 0;
for (j = 1; j <= i; j++)
{
if (i % j == 0)
{
count++;
}
}
int l = 0;
if (count == 2)
{
while (n % i == 0) // calculate factor and his exponent
{
l++;
n = n / i;
}
if (l > max) // calculates min and max in order to find GCD
{
max = l;
}
if (l < min)
{
min = l;
}
}
large = max;
small = min;
while (small) { // While small is not 0
// Calculates GCD
rem = large % small;
large = small;
small = rem;
}
gcd = large;
// printf("GCD(%d,%d)= %d", large, small, gcd);
}
/*if (gcd == 1) {
achilles = n;
// printf("%d\n", achilles);
}*/
printf("GCD(%d,%d)= %d", max, min, gcd);
//printf("%d\n", achilles);
}

Copying elements from an array to another one and counting the number of a character in C

I'm new to C, so I apologize for asking silly questions.
I need to copy certain elements from an array to another one, but I can't make it work and get random numbers instead. In this case I need all the elements after the smallest one from the first array to be copied to the second one.
The other thing I can't figure out is a function that counts how many times a certain symbol is used. I need to find the number of times I've used the biggest odd digit in an array.
Here's the code, I've made so far. I hope you understand most of it:
#include <stdio.h>
#define DIM 100
int enter (int x[]);
int min (int x[], int y[], int n);
int sort (int x[], int n);
void print (int x[], int n);
//=============================================
int main () {
int a[DIM], b[DIM], n, i;
n = enter (a);
printf("The smallest element in the first array: %d.\n The smallest element in the second array: %d.\n", min (a, b, n));
printf("%d\n", sort (b, n));
for (i = 0; i < n; i++)
printf ("%d ", b[i]);
printf ("\n");
system("pause");
return 0;
}
//===========================================================
int enter (int x[]) {
int i, n;
do {
printf ("Enter number of elements in array: ");
scanf ("%d", &n);
}
while (n < 1 || n > DIM);
printf ("Enter %d elements:\n", n);
for (i = 0; i < n; i++)
scanf ("%d", &x[i]);
return x[i], n;
}
int min (int x[], int y[], int n) {
int minimum, i, j=0, p;
minimum = x[0];
for ( i = 1 ; i < n ; i++ ) {
if ( x[i] < minimum ) {
minimum = x[i];
p = i+1;
}
}
for (i = p+1; i<n; i++ && j++) {
x[i] = y[j];
}
return minimum;
}
int sort (int x[], int n) {
int i, j, a;
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j) {
if (x[i] > x[j]){
a = x[i];
x[i] = x[j];
x[j] = a;
}
}
}
printf("Elements from array in ascending order: \n");
for (i = 0; i < n; ++i)
printf("%d\n", x[i]);
return x[i];
}
I need to find the number of times I've used the biggest odd digit in
an array.
Fist sort your array start at the end and find the biggest odd number. You can find a odd number by number%2==1. Finally count equal numbers:
// sort the array
sort(b, n); // sort function from your questions code
// find the biggest odd number
int i = n-1;
while ( i >= 0 && b[i]%2 == 0 )
{
i --;
}
// count the biggest odd number
count = 0;
int j = i;
while ( j >= 0 && b[i]==b[j] ) // note first time i==j !
{
count ++;
j --;
}
If you don't want to sort your array use this:
// find the biggest odd number
int oddInx = -1;
for ( int i = 0; i < n; i++ )
{
if ( b[i]%2 == 1 && ( oddInx < 0 || b[i] > b[oddInx] ) )
oddInx = i;
}
// count the biggest odd number
count = 0;
if ( oddInx >= 0 )
{
for ( int i = 0; i < n; i++ )
{
if ( b[i] == b[oddInx] )
count ++;
}
}

finding index of max value in an array in C

I want to find index of max value in array in C.
I write this code example:
maks=0;
for(i=0;i< N * N;i++) {
if(array[i]>maks) {
maks=(int) array[i];
k=i;
}
}
But this isn't work properly.Could you advise me another example please?
Best Regards...
k = 0;
max = array[k];
for (i = 0; i < N * N; ++i)
{
if (array[i] > max)
{
max = (int)array[i];
k = i;
}
}
Should work !
Below function accepts pointer to array with size of the array as arguments and returns the max index.
int max_index(float *a, int n)
{
if(n <= 0) return -1;
int i, max_i = 0;
float max = a[0];
for(i = 1; i < n; ++i){
if(a[i] > max){
max = a[i];
max_i = i;
}
}
return max_i;
}
Usage example,
float a[3] ={1.2,3.2,4.0};
cout<<max_index(a,3)<<endl; //will output 2, because a[2] element is the max

Resources