function that splits digits then sums them - c

I am trying to solve a problem that requires me to take a number. Use the % and / to take the rightmost number and sum the digits that are separated. Then tell see if the number is divisible by 9.
I have created a function that will separate the rightmost number and then I have tried to take that number and run it through a while loop. The problem that exist is, when I run the while loop. It creates an infinite loop or the output will not be printed.
#include <stdio.h>
int loopnum(int n);
int main(void)
{
int num;
int sum = 0;
int d = loopnum(num);
printf("Enter a number:\n");
scanf("%d", &num);
while (loopnum(num) > 0) {
printf("d = %d", d);
printf(",sum = %d\n", sum);
}
if (num % 9 == 0) {
printf("n = %d is divisible by 9\n", num);
}
else {
printf("n = %d is not divisible by 9\n", num);
}
return 0;
}
int loopnum(int n)
{
n = n % 10;
n = n / 10;
return n;
}
Enter a number:
9
n = 9 is divisible by 9
The result of this code is suppose to output d = "the digit" ,sum =
"digit + sum" and n = "digit" is divisible by 9. for example if I
input 9. The output would be d = 9, sum = 9.

The function does not make sense.
int loopnum(int n)
{
n = n % 10;
n = n / 10;
return n;
}
For example for n equal to 27 you will get
n = n % 10;
now n is equal to 7 and then
n = n / 10;
now n is equal to 0.
So for the number 27 the function returns 0.
And moreover inside the loop
while (loopnum(num) > 0) {
printf("d = %d", d);
printf(",sum = %d\n", sum);
}
neither num, nor d, nor sum is changed.
There is no great sense to define such a function except that it could itself to output intemediate sums and digits.
Without the function the program can look the following way.
#include <stdio.h>
int main(void)
{
while ( 1 )
{
const unsigned int Base = 10;
const unsigned int DIVISOR = 9;
printf( "Enter a non-negative number (0 - exit): " );
unsigned int n;
if ( scanf( "%u", &n ) != 1 || n == 0 ) break;
unsigned int sum = 0;
unsigned int tmp = n;
do
{
unsigned int digit = tmp % Base;
sum += digit;
printf( "d = %u, sum = %u\n", digit, sum );
} while ( tmp /= Base );
printf( "\nn = %u is %sdivisble by %u.\n\n",
n,
sum % DIVISOR == 0 ? "" : "not ", DIVISOR );
}
return 0;
}
Its ouutput might look like
Enter a non-negative number (0 - exit): 9
d = 9, sum = 9
n = 9 is divisble by 9.
Enter a non-negative number (0 - exit): 123456
d = 6, sum = 6
d = 5, sum = 11
d = 4, sum = 15
d = 3, sum = 18
d = 2, sum = 20
d = 1, sum = 21
n = 123456 is not divisble by 9.
Enter a non-negative number (0 - exit): 0

The loopnum code is wrong. It will always return zero and therefor the while will not loop.
int loopnum(int n)
{
n = n % 10; // After this n is a number between 0 and 9
n = n / 10; // Consequently, when you divide by 10 you'll end up with zero
return n;
}
Your design requires two things:
1) Return the remainder
2) Change n
To do that you need to pass a pointer to n.
Something like:
int loopnum(int *n)
{
int res = *n % 10;
*n = *n / 10;
return res;
}
int main(void)
{
int x = 123;
int sum = 0;
while(x) sum += loopnum(&x);
printf("%d\n", sum);
return 0;
}

Related

Extract a number from a position in C

In this exercise he asks me to create a function
Number_pos (N, pos, m) which allows to extract a number composed of m digits
from position pos using functions.
Example:
N = 12345, pos = 2, m = 3
Number_pos (N, pos, m) = 234
I use an Extraxt_from_position function which extracts a number from a given position, then I use a function which calculates the number of digits of the number to extract, then I have a mirror function which inverts the number and I do the successive division until the number of digits are equal to the number of digits of the number we want to extract.
The problem is: forbidden to use mirror function, can you help me
int Extract_from_position(int n, int r)
{
int m = 0, s = 0;
while (n != 0)
{
m = n % 10;
s++;
if (s == r)
{
return n;
}
n = n / 10;
}
}
int Number_of_digits(int n)
{
int m = 0, s = 0;
while (n != 0)
{
m = n % 10;
s++;
n = n / 10;
}
return s;
}
int Mirror(int n)
{
int m = 0, s = 0;
while (n != 0)
{
m = n % 10;
s = s * 10 + m;
n = n / 10;
}
return s;
}
int Number_Pos(int N, int pos, int m)
{
int x = Extract_from_position(N, pos);
int y = 0;
int R = Mirror(x);
int T = Number_of_digits(R);
while (T >= m + 1)
{
y = R % 10;
R = R / 10;
T--;
}
return Mirror(R);
}
int main()
{
int n, pos, nbcx;
printf("Give n :");
scanf("%d", &n);
printf("Give the position :");
scanf("%d", &pos);
printf("give the number of digits of the number to extract :");
scanf("%d", &nbcx);
printf("\nThe result after the amber extract from position %d on the right and the number of digits %d is : %d \n", pos, nbcx, Number_Pos(n, pos, nbcx));
}
UPDATE: Count from right
If you want count the digits from right, the NumberPos function will be just:
#include <stdio.h>
#include <math.h>
int NumberPos(int N, int pos, int m)
{
int trc = (int)(N / (int)pow(10, pos - 1));
trc = trc % (int)pow(10, m);
return trc;
}
int main()
{
int n, pos, nbcx;
printf("Give n :");
scanf("%d", &n);
printf("Give the position :");
scanf("%d", &pos);
printf("give the number of digits of the number to extract :");
scanf("%d", &nbcx);
printf("\nThe result after the amber extract from position %d on the right and the number of digits %d is : %d \n", pos, nbcx, NumberPos(n, pos, nbcx));
}
And the output will be, for example:
Give n :1234567
Give the position :3
give the number of digits of the number to extract :2
The result after the amber extract from position 3 on the right and the number of digits 2 is : 45
OLD: This could be a solution (in basically 4 line):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int NumberPos(int N, int pos, int m)
{
int digit = floor(log10(abs(N))) + 1;
int trc = N % (int)pow(10, digit - pos + 1);
digit = floor(log10(abs(trc))) + 1;
trc = (int)(trc / (int)pow(10, digit - m));
return trc;
}
int main()
{
int n, pos, nbcx;
printf("Give n :");
scanf("%d", &n);
printf("Give the position :");
scanf("%d", &pos);
printf("give the number of digits of the number to extract :");
scanf("%d", &nbcx);
printf("\nThe result after the amber extract from position %d on the right and the number of digits %d is : %d \n", pos, nbcx, NumberPos(n, pos, nbcx));
}
The output will be:
Give n :12345
Give the position :2
give the number of digits of the number to extract :2
The result after the amber extract from position 2 on the right and the number of digits 2 is : 23
UPDATE: Library restriction
If for whatever reason you are not allowed to use math.h or stdlib.h you can:
Re-implement pow reading: Write Pow Function Without math.h in C
Re-implement abs reading: this
Re-implement the digit counter: C program to count number of digits in an integer
Something like this might work. I trim the digits you don't want on the right then mod to mask off the digits on the left you don't want.
Based on your sample I assume that pos is 1-based. If not there's a comment on the code you would need to remove.
You'd probably want to add error checking to make sure that pos and num_digits are valid for the given N, but that's an exercise for you.
#include <stdio.h>
int Number_of_digits(int n)
{
int count = 0;
while (n != 0)
{
n = n / 10;
++count;
}
return count;
}
int Number_Pos(int N, int pos, int num_digits)
{
int len = Number_of_digits(N);
pos -= 1; //pos is 1 based.
//trim right side
for (int i = 0; i < len - num_digits - pos; ++i)
{
N /= 10;
}
//calculate mod to keep num_digits.
int m = 10;
for (int i = 0; i < num_digits - 1; ++i)
{
m *= 10;
}
return N % m;
}
int main()
{
int n = 1234567;
int pos = 2;
int num_digits = 3;
int result = Number_Pos(n, pos, num_digits);
printf("Num: %d, Pos: %d, Digits: %d - Result: %d\n", n, pos, num_digits, result);
pos = 3;
num_digits = 4;
result = Number_Pos(n, pos, num_digits);
printf("Num: %d, Pos: %d, Digits: %d - Result: %d\n", n, pos, num_digits, result);
pos = 1;
num_digits = 4;
result = Number_Pos(n, pos, num_digits);
printf("Num: %d, Pos: %d, Digits: %d - Result: %d\n", n, pos, num_digits, result);
pos = 6;
num_digits = 2;
result = Number_Pos(n, pos, num_digits);
printf("Num: %d, Pos: %d, Digits: %d - Result: %d\n", n, pos, num_digits, result);
return 0;
}
Output:
Num: 1234567, Pos: 2, Digits: 3 - Result: 234
Num: 1234567, Pos: 3, Digits: 4 - Result: 3456
Num: 1234567, Pos: 1, Digits: 4 - Result: 1234
Num: 1234567, Pos: 6, Digits: 2 - Result: 67

How many prime numbers C program

I wrote this program to find prime numbers between 1 and 50000, and I still need to find how many prime numbers there is (I tried a lot of tricks but I did not succeed)
#include <stdio.h>
//int getValueFromUser();
void PrintListOfPrime(int value);
int main() {
int value = 23;
PrintListOfPrime(value);
return 0;
}
void PrintListOfPrime(int value) {
int ValueIsPrime; //ValueIsPrime is used as flag variable
printf("The list of primes: ");
for (int i = 2; i <= value; i++) {
ValueIsPrime = 1;
/* Check if the current number i is prime or not */
for (int j = 2; j <= i / 2; j++) {
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
if (i % j == 0) {
ValueIsPrime = 0;
break;
}
}
/* If the number is prime then print */
if (ValueIsPrime == 1)
printf("%d, ", i);
}
printf("\n");
}
I tried a lot of tricks but I did not succeed
If OP's code takes too long to ran, iterate to the square root of i, not up to i/2.
j <= i / 2 is very slow. Use j <= i / j instead.
Form a count and increment with every prime. #gspr
if (ValueIsPrime == 1) {
printf("%d, ", i);
prime_count++;
}
Bigger change yet even faster to "find prime numbers between 1 and 50000", research Sieve of Eratosthenes
Hello fast answer is to create a variable in main, int totaleOfPrimes = 0; for example.
then send it by reference to the fucntion :
Function declaration : void PrintListOfPrime(int value,int* counter);
Function call : void PrintListOfPrime(value,&totaleOfPrimes);
then Increment counter befor printing :
if (ValueIsPrime == 1){
(*counter)++;
printf("%d, ", i);
}
There is no need to iterate the loops for all numbers between 2 and value. You should consider only 2 and odd numbers.
The function can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
static inline size_t PrintListOfPrime( unsigned int n )
{
size_t count = 0;
printf( "The list of primes:\n" );
for ( unsigned int i = 2; i <= n; i = i != 2 ? i + 2 : i + 1 )
{
int isPrime = 1;
/* Check if the current number i is prime or not */
for ( unsigned int j = 3; isPrime && j <= i / j; j += 2 )
{
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
isPrime = i % j != 0;
}
/* If the number is prime then print */
if ( isPrime )
{
if ( ++count % 14 == 0 ) putchar( '\n' );
printf( "%u ", i );
}
}
return count;
}
int main(void)
{
unsigned int n = 50000;
size_t count = PrintListOfPrime( n );
printf( "\n\nThere are %zu prime numbers up to %u\n", count, n );
return 0;
}
Run this code in C. It will return the value of a pi(x) function. It is basically the Prime counting function:
#include <stdio.h>
#define LEAST_PRIME 2
#include <math.h>
int main() //works for first 10000 primes.
{
int lower_limit = 2, no_of_sets;
// printf("NUMBER OF SETS: ");
// scanf("%d", &no_of_sets);
int remainder, divisor = 2, remainder_dump, upper_limit; //upper limit to be specified
//by user.
int i = 1;
// printf("SPECIFY LOWER LIMIT: ");
// scanf("%d", &lower_limit);
int number_to_be_checked = lower_limit;
printf("SPECIFY UPPER LIMIT: ");
scanf("%d", &upper_limit);
printf("2\t\t\t\t", number_to_be_checked);
//PRINTS 2.*/
do
{
remainder_dump = 1;
divisor = 2;
do
{
remainder = number_to_be_checked % divisor;
if (remainder == 0)
{
remainder_dump = remainder_dump * remainder; // dumping 0 for rejection.
break;
}
++divisor;
} while (divisor <= number_to_be_checked / divisor); // upto here we know number
is prime or not.
if (remainder_dump != 0)
{
++i;
printf("%d.\t\t\t\t", number_to_be_checked); //print if prime.
};
number_to_be_checked = number_to_be_checked + 1;
} while (number_to_be_checked <= upper_limit);
printf("\n pi(x) = %d \n", i);
//printf("pi function value is %f.", (i - 1) / (log(i - 1)));
float app;
app = upper_limit / (log(upper_limit));
float plot_value;
plot_value = (i) / app;
printf(" BETA FUNCTION VALUE ~ %f", plot_value);
return 0;
}

is this program correct to calculate the sum of 5 digits

Program to calculate the sum of five digits
This program is showing error in the compiler even though I think its factually correct
#include<stdio.h>
int main()
{
int i,a,num=32765,n;
int sum=0;
a=num%10;
n=num/10;
sum=sum+a;
for(i=0;i>4;i++)
{
a=n%10;
n=n/10;
sum=sum+a;
}
printf("the sum of five digits is %d", sum);
}
The loop in your code is never entered because i=0 and then you check if i>=3 which is never true.
You could use something like this:
int digit_sum(int num){
int sum=0;
while (num !=0){
sum += num%10;
num = num/10;
}
return sum;
}
int main()
{
int num = 12346;
/*
if (num <0) // add this block if negative number is posible
num = -num; // and its ok to change num or use some temp instead
*/
int sum = digit_sum(num);
printf("the sum of five digits is %d",sum);
return 0;
}
Or use recursion:
int digit_sum(int num){
if (num)
return num%10 + digit_sum(num/10);
}
Your loop is never entered because i=0 and cant be greater then 3!!! so the solution is:
int number=12345;
int total=0;
int remainder=0;
while(number>0){
remainder=number%10;
total=total+remainder;
number=number/10;
}
Your code is almost correct, just needed correct loop condition. Added comments so that you can see what is going on:
#include <stdio.h>
int main()
{
int i, a, num = 32765, n;
int sum = 0;
// extract 1st digit
a = num % 10; // a is 5 (% returns the remainder of the division)
n = num / 10; // n is 3276 (should be 3276.5, but int eats 0.5)
sum = sum + a; // sum is 5 which is (0 + 5)
// extract the remaining 4 digits
for (i = 0; i < 4; i++) // i is 0, 1, 2, 3
{
a = n % 10; // a is 6, 7, 2, 3
n = n / 10; // n is 327, 32, 3, 0
sum = sum + a; // sum is 11, 18, 20, 23
}
printf("the sum of five digits is %d", sum);
return 0;
}
https://ideone.com/EI9tgM

Sum of Digits Program not giving correct answer for negative number in c

printf("Sum Digit Program\n");
int n,re, sum = 0;
printf("Enter an integer n="); scanf("%d", &n);
while(n){
re = n % 10;
sum = sum + re;
n = n / 10;
}
printf("Sum digit = %d", sum);
return 0;
}
I try this and it works well with positive integer but when I enter a negative integer like: -323 => -8
It's supposed to be -3+2+3 =2 not -3-2-3=-8
I try using abs function but it still doesn't work right
OP almost had it. Simply treat MSDigit as signed. All other digits, use abs(rem). Works for INT_MIN
printf("Sum Digit Program\n");
int sum = 0;
printf("Enter an integer n=");
scanf("%d", &n);
while (n) {
int re = n % 10;
n = n / 10;
sum += n ? abs(re) : re; // At MSDigit when n==0
}
printf("Sum digit = %d", sum);
Well, you may use conditional operator to store the sign value like int sign = (n >= 0 ? 1 : -1); as shown below -
#include <stdio.h>
#include <stdlib.h>
/*
* #brief Logic for returning sum of digits
*/
int digi_sum(int n)
{
int sign = (n >= 0 ? 1 : -1);
int sum = 0;
n *= sign;
while (n)
{
if (n < 10)
sum += (sign * (n % 10));
else
sum += n % 10;
n /= 10;
printf("Sum: %d, n: %d\n", sum, n);
}
printf("sum: %d, n: %d\n", sum, n);
return sum;
}
/*
* #brief Driver function
*/
int main(int argc, char *argv[])
{
int num = -323;
printf("Sum: %d\n", digi_sum(num));
return 0;
}
The idea is to store the sign of the number into a separate variable and use it when n < 10.
Use n=abs(n/10) instead of n=n/10
#include <stdio.h>
#include <math.h>
main()
{
printf("Sum Digit Program\n");
int n,re, sum = 0;
printf("Enter an integer n="); scanf("%d", &n);
while(n)
{
re = n % 10;
sum = sum + re;
n =abs(n/10);
}
printf("Sum digit = %d", sum);
return 0;
}
You can add a condition to the first line of your loop to make sure that the sum so far is positive when n < 10, after that it will make the subtraction for the least digit if it has too. Then your loop should look like this:
while(n){
if (abs(n) < 10) {
sum = abs(sum);
}
re = n % 10;
sum = sum + re;
n = n / 10;
}
I think that you need a precondition for the first number.
with an if then else.
Solved
I changed the output to see the values
include<stdio.h>
int main(void)
{
int re,n;
int sum =0 ;
printf("Sum Digit Program \n");
printf("Enter an integer n= ");
scanf("%d", &n);
while(n)
{
if (abs(n) < 10) {
sum = abs(sum);
}
re= (n % 10);
sum = sum + re;
n= n / 10;
printf ("\n re = %d , n= %d \n", re, n);
}
printf ("\n sum= %d \n",sum);
return 0;
}

Sum of digits at Even and Odd Places in C

I need to add the digits on the even and odd places in an integer. Say, Let number = 1234567. Sum of even place digits = 2+4+6 = 12 Sum of odd place digits = 1+3+5+7 = 16
The code I currently have is:
int returnsum(int num) {
while (num) {
rem = num % 10;
sum = sum + rem;
num = num / 10;
}
while (sum) {
a = sum % 10;
arr[i] = a:
sum = sum / 10;
i++;
}
for (i = 0; a[i]; i += 2) {
summ = summ + a[i];
}
return summ;
}
void main() {
int n, m, oddSum = 0, evenSum = 0;
printf("Please insert the number for the program:");
scanf("%d", & n);
while (n != 0) {
oddSum += n % 10;
n /= 10;
evenSum += n % 10;
n /= 10;
}
printf("Sum of digits in even places:%d\n", evenSum);
printf("Sum of digits in odd places:%d\n", oddSum);
}
Here is a solution for your problem:
void main()
{
int n,m,oddSum=0,evenSum=0;
printf("Please insert the number for the program:");
scanf("%d",&n);
int flag=0;
int counter=1;
while (n!=0) {
if(counter%2==0)
{
evenSum += n % 10;
n /= 10;
}
else
{
oddSum += n % 10;
n /= 10;
}
counter++;
}
if(counter%2==0)
{
int temp=oddSum;
oddSum=evenSum;
evenSum=temp;
}
printf("Sum of digits in even places:%d\n",evenSum);
printf("Sum of digits in odd places:%d\n",oddSum);
}
Okay, let's first assume the number has an even number of digits, so that the second-last and last are at odd and even positions respectively.
Then, the last digit can be retrieved with number % 10 and the second last with (number / 10) % 10.
So, knowing that, you can simply loop over the number, adding those values and dividing by a hundred until you get a number less than ten.
If that number is zero, then your assumption about the original having an even number of digits was correct and you can exit.
If it's a non-zero (1..9), then your assumption was wrong, you should swap the even and odd sums to date then add the final digit to the odd sum.
The pseudo-code goes something like this:
def getEvenOdd (num):
even = 0
odd = 0
while num > 9:
even = even + (num % 10)
odd = odd + ((num / 10) % 10)
num = num / 100
if num > 0:
temp = even
even = odd
odd = temp
odd = odd + num
return (even,odd)
print getEvenOdd(1234567)
And the output of that would be something like (12,16).
And it's no accident that pseudo-code looks like beginner's Python, since that language is the perfect pseudo-code language, provided you don't mess about with the more complex corners of it.
Check the below code:
#include <stdio.h>
int main(void){
char p[20];
int i=0,even=0,odd=0,n;
scanf("%d",&n);
sprintf(p,"%d",n);
while(p[i] != '\0')
{
if(i%2 == 0)
odd+= (p[i] - '0');
else
even+= (p[i] - '0');
i++;
}
printf("%d\n",even);
printf("%d\n",odd);
return 0;
}
To sum every other digit, simply divide by 100 in each iteration:
int sumodd(int num) {
int sum = 0, rem;
while(num) {
rem=num%10;
sum=sum+rem;
num=num/100);
}
return sum;
}
Since we already have a function that can sum every other digit, we can re-use it:
int sumeven(int num) {
return sumodd(num/10);
}
My five cents.:)
#include <stdio.h>
typedef struct pair
{
unsigned int odd;
unsigned int even;
} pair_t;
pair_t GetSums( unsigned int x )
{
const unsigned int Base = 10;
pair_t sums = { 0u, 0u };
size_t n = 0;
do
{
if ( ++n & 1 ) sums.odd += x % Base;
else sums.even += x % Base;
} while ( x /= Base );
if ( ( n & 1 ) == 0 )
{
unsigned int tmp = sums.odd;
sums.odd = sums.even;
sums.even = tmp;
}
return sums;
}
int main(void)
{
while ( 1 )
{
unsigned int x;
pair_t sums;
printf( "\nEnter a non-negative number (0 - exit): " );
if ( scanf( "%u", &x ) != 1 || x == 0 ) break;
sums = GetSums( x );
printf( "\nSum of digits in odd positions is %u\n", sums.odd );
printf( "Sum of digits in even positions is %u\n", sums.even );
}
return 0;
}
The output might look like
Enter a non-negative number (0 - exit): 1234567
Sum of digits in odd positions is 16
Sum of digits in even positions is 12
Enter a non-negative number (0 - exit): 123456
Sum of digits in odd positions is 9
Sum of digits in even positions is 12
Enter a non-negative number (0 - exit): 0

Resources