I want to make a program to count the sum of digits in a string but only using stdio.h
but the program needs to count until its less than 10
so the example you input 56 it would be 5+6=11 then 1+1=2 and so on
here's my code. For now I'm just confused how to check if its whether more than 9 or not
#include<stdio.h>
int plus(int n);
int main(void)
{
int n, digit, test;
scanf("%d", &n);
test = plus(n);
while(test != 0)
{
if(test > 9)
plus(test);
else
break;
}
printf("%d", test);
}
int plus(int n)
{
int digit=0,test=0;
while(n != 0)
{
digit = n%10;
test = test + digit;
n = n/10;
}
return test;
}
You are not storing the value returned by plus function in the while body.
You can change the condition in while to check whether it is greater than 9 or not, and assign test as test = plus(test);
So, your while will look like this.
while(test > 9)
{
test=plus(test);
}
You need to recursively call the function plus() until the value returned by it becomes less than 10. Like shown below:
int main(void)
{
int n=56;
while(n> 10)
{
n = plus(n);
}
printf("%d", n);
}
Related
this is my code, I want to make a function that when it is called will generate a number between 1111 to 9999, I don't know how to continue or if I've written this right. Could someone please help me figure this function out. It suppose to be simple.
I had to edit the question in order to clarify some things. This function is needed to get 4 random digits that is understandable from the code. And the other part is that i have to make another function which is a bool. The bool needs to first of get the numbers from the function get_random_4digits and check if there contains a 0 in the number. If that is the case then the other function, lets call it unique_4digit, should disregard of that number that contained a 0 in it and check for a new one to use. I need not help with the function get_random_4digitsbecause it is correct. I need helt constructing a bool that takes get_random_4digits as an argument to check if it contains a 0. My brain can't comprehend how I first do the get_random_4digit then pass the answer to unique_4digits in order to check if the random 4 digits contains a 0 and only make it print the results that doesn't contain a 0.
So I need help with understanding how to check the random 4 digits for the integer 0 and not let it print if it has a 0, and only let the 4 random numbers print when it does not contain a 0.
the code is not suppose to get more complicated than this.
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
bool unique_4digits(answer){
if(answer == 0)
return true;
if(answer < 0)
answer = -answer;
while(answer > 0) {
if(answer % 10 == 0)
return true;
answer /= 10;
}
return false;
}
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
Instead of testing each generated code for a disqualifying zero just generate a code without zero in it:
int generate_zero_free_code()
{
int n;
int result = 0;
for (n = 0; n < 4; n ++)
result = 10 * result + rand() % 9; // add a digit 0..8
result += 1111; // shift each digit from range 0..8 to 1..9
return result;
}
You can run the number, dividing it by 10 and checking the rest of it by 10:
int a = n // save the original value
while(a%10 != 0){
a = a / 10;
}
And then check the result:
if (a%10 != 0) printf("%d\n", n);
Edit: making it a stand alone function:
bool unique_4digits(int n)
{
while(n%10 != 0){
n = n / 10;
}
return n != 0;
}
Usage: if (unique_4digits(n)) printf("%d\n", n);
To test if the number doesn't contain any zero you can use a function that returns zero if it fails and the number if it passes the test :
bool FourDigitsWithoutZero() {
int n = get_random_4digit();
if (n % 1000 < 100 || n % 100 < 10 || n % 10 == 0) return 0;
else return n;
}
"I need not help with the function get_random_4digits because it is correct."
Actually the following does not compile,
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
The following includes modifications that do compile, but still does not match your stated objectives::
int get_random_4digit(){
srand(clock());
int lower = 1000, upper = 9999,answer;
int range = upper-lower;
answer = lower + rand()%range;
return answer;
}
" I want to make a function that when it is called will generate a number between 1111 to 9999,"
This will do it using a helper function to test for zero:
int main(void)
{
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
return 0;
}
Function that does work follows:
int random_range(int min, int max)
{
bool zero = true;
char buf[10] = {0};
int res = 0;
srand(clock());
while(zero)
{
res = min + rand() % (max+1 - min);
sprintf(buf, "%d", res);
zero = if_zero(buf);
}
return res;
}
bool if_zero(const char *num)
{
while(*num)
{
if(*num == '0') return true;
num++;
}
return false;
}
I'm writing an recursion method to calculate collatz conjecture for a sequence of positive integers. However, instead of stopping the calculation when the value reaches 1, I need it to stop when the value become smaller than or equal to the original value. I can't figure out what condition I should put in the if statement.
int collatz (int n) {
printf("%d%s", n, " ");
if(n > collatz(n)) { // here I would get an error saying all path leads to the method itself
return n;
}
else {
if(n % 2 == 0) {
return collatz(n / 2);
}
else {
return collatz((3 * n) + 1);
}
}
}
I used two more parameters:
startValue, to pass through the recursive calls the initial value and
notFirstTime, to check if it is the first call (and not a recursive call). In this case a value n <= startValue is allowed.
Here the code:
int collatz (int startValue, int n, int notFirstTime){
printf("%d%s ", n, " ");
if(n <= startValue && !notFirstTime)
{ // here I would get an error saying all path
//leads to the method itself
return n;
}
else
{
if ( n%2==0 )
{
collatz(startValue, n/2, 0);
}
else
{
collatz(startValue, (3*n)+1, 0);
}
}
}
int main() {
int x = 27;
int firstTime = 1;
int test = collatz(x,x, firstTime);
printf("\nLast value: %d\n", test);
return 0;
}
Please note that I removed two return statements from the recursive calls.
I'm trying to solve Problem 4 -Project Euler and I am stucked. So I need a little help with my code. Here is the problem I am trying to solve:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int is_palindrom(int number, int revrse) {
char str1[6];
char str2[6];
sprintf(str1, "%d", number);
sprintf(str2, "%d", revrse);
return strcmp(str1, str2);
}
int main(void) {
int number, revrse;
int i, j, temp;
int maks;
for(i=999;i>99;i--)
for(j=999;j>99;j--) {
temp = number = i*j;
while (temp != 0) {
revrse = revrse * 10;
revrse = revrse + temp%10;
temp = temp/10;
}
if(is_palindrom(number, revrse)==0 && number > maks)
maks = number;
}
printf("%d",maks);
return 0;
}
The revrse var isn't initialized so there are rubbish in it. Remember to always init a variable!
Complementing the answer from #kleszcz, revrse must always be initialized before the while loop begins, otherwise, it will hold the previous value (and rubbish in the first iteration, as he intelligently pointed out).
Another issue is that you do not need the is_palindrome function. You can check directly if the numbers are equal.
To get the reversed form of your number properly, you need to first set an initial value for revrse of 0 for each iteration of your loop, otherwise the behavior is undefined. It also helps to set an initial value for maks to compare against. Finally, why use a function to check for palindromes when you can just check for equality between your number and its reverse?
int main()
{
int number;
int i,j,temp;
int maks = -1;
int revrse;
for(i=999;i>99;i--) {
for(j=999;j>99;j--) {
number = i*j;
revrse = 0;
temp=number;
while (temp != 0){
revrse = revrse * 10;
revrse = revrse + temp%10;
temp = temp/10;
}
if(number == revrse) {
if(number > maks) {
maks = number;
}
}
}
}
printf("%d",maks);
return 0;
}
#include<stdio.h>
int main(void)
{
int rev=0,temp=0,frwd,n,ans=0;
int i,j;
for(i=100;i<=999;i++)
{
for(j=i;j<=999;j++)
{
n = i*j;
frwd = n;
while(n!=0)
{
temp = n%10;
n = n/10;
rev = temp+rev*10;
}
printf("%d",rev);
if((rev == frwd)&&(ans<frwd))
{
ans=frwd;
printf("%d",ans);
}
}
}
return(0);
}
I have tried working out everything but this code doesn't seem to give the correct output.
The desired output is largest palindrome number of 6 digits.
If I am running the individual parts i.e. the reversing of number , checking of number whether or not it is a palindrome or the for loops, they are working fine but in the program they are giving garbage as output.
Any help would be appreciated.
ya the problem is that you are not reinitializing rev to 0 as said by cowanother.anon.ard. Try putting rev=0 in inner for loop.
But you cant get 999999 as the highest palindrome number of 6 digit by your method as u r not checking all the 6 digit numbers.
#include<stdio.h>
int main(void)
{
int rev=0,temp=0,frwd,n,ans=0;
int i,j;
for(i=100000;i<=999999;i++)
{
frwd = n = i;
rev = 0;
while(n!=0)
{
temp = n%10;
n = n/10;
rev = temp+rev*10;
}
if((rev == frwd)&&(ans<frwd))
{
ans=frwd;
}
}
printf("%d\n",ans);
return(0);
}
4 problems with your Code:-
Like another.anon.coward said- you need to put rev=0 inside inner loop
You need to separate each number printed either by a space or a newline ('\n')
printf("\n %d");. Otherwise they will look like one big number (garbage).
Your algorithm is also wrong. According to your program, the largest 6-digit number is 906609 (The correct answer is 999999). For this you should change your inner loop to j=0;j<999;j++ and change n=i*j to n=i*1000+j.
Also move the printf("\n%d",ans); outside the loop.
The corrected program is:
#include <stdio.h>
int main(void)
{
int rev=0,temp=0,frwd,n,ans=0;
int i,j;
for(i=100;i<=999;i++)
{
for(j=0;j<=999;j++) /*CORRECTED THIS LINE,*/
{ rev=0;/*ADDED THIS LINE;*/
n = (i*1000) + j; /*CORRECTED THIS LINE*/
frwd = n;
while(n!=0)
{
temp = n%10;
n = n/10;
rev = temp+rev*10;
}
printf("\n%d",rev); /*THIS LINE,*/
if((rev == frwd)&&(ans<frwd))
{
ans=frwd;
}
}
}
printf("\n%d",ans); /* AND THIS LINE*/
return(0);
}
#include <stdio.h>
int main(void)
{
int rev=0,temp=0,frwd,n,ans=0;
int i,j;
for(i=100;i<=999;i++)
{
for(j=0;j<=999;j++) /*CORRECTED THIS LINE,*/
{ rev=0;/*ADDED THIS LINE;*/
n = (i*1000) + j; /*CORRECTED THIS LINE*/
frwd = n;
while(n!=0)
{
temp = n%10;
n = n/10;
rev = temp+rev*10;
}
printf("\n%d",rev); /*THIS LINE,*/
if((rev == frwd)&&(ans<frwd))
{
ans=frwd;
}
}
}
printf("\n%d",ans); /* AND THIS LINE*/
return(0);
}
UVA problem 100 - The 3n + 1 problem
I have tried all the test cases and no problems are found.
The test cases I checked:
1 10 20
100 200 125
201 210 89
900 1000 174
1000 900 174
999999 999990 259
But why I get wrong answer all the time?
here is my code:
#include "stdio.h"
unsigned long int cycle = 0, final = 0;
unsigned long int calculate(unsigned long int n)
{
if (n == 1)
{
return cycle + 1;
}
else
{
if (n % 2 == 0)
{
n = n / 2;
cycle = cycle + 1;
calculate(n);
}
else
{
n = 3 * n;
n = n + 1;
cycle = cycle+1;
calculate(n);
}
}
}
int main()
{
unsigned long int i = 0, j = 0, loop = 0;
while(scanf("%ld %ld", &i, &j) != EOF)
{
if (i > j)
{
unsigned long int t = i;
i = j;
j = t;
}
for (loop = i; loop <= j; loop++)
{
cycle = 0;
cycle = calculate(loop);
if(cycle > final)
{
final = cycle;
}
}
printf("%ld %ld %ld\n", i, j, final);
final = 0;
}
return 0;
}
The clue is that you receive i, j but it does not say that i < j for all the cases, check for that condition in your code and remember to always print in order:
<i>[space]<j>[space]<count>
If the input is "out of order" you swap the numbers even in the output, when it is clearly stated you should keep the input order.
Don't see how you're test cases actually ever worked; your recursive cases never return anything.
Here's a one liner just for reference
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
Not quite sure how your code would work as you toast "cycle" right after calculating it because 'calculate' doesn't have explicit return values for many of its cases ( you should of had compiler warnings to that effect). if you didn't do cycle= of the cycle=calculate( then it might work?
and tying it all together :-
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
int max_int(int a, int b) { return (a > b) ? a : b; }
int min_int(int a, int b) { return (a < b) ? a : b; }
int main(int argc, char* argv[])
{
int i,j;
while(scanf("%d %d",&i, &j) == 2)
{
int value, largest_cycle = 0, last = max_int(i,j);
for(value = min_int(i,j); value <= last; value++) largest_cycle = max_int(largest_cycle, three_n_plus_1(value));
printf("%d %d %d\r\n",i, j, largest_cycle);
}
}
Part 1
This is the hailstone sequence, right? You're trying to determine the length of the hailstone sequence starting from a given N. You know, you really should take out that ugly global variable. It's trivial to calculate it recursively:
long int hailstone_sequence_length(long int n)
{
if (n == 1) {
return 1;
} else if (n % 2 == 0) {
return hailstone_sequence_length(n / 2) + 1;
} else {
return hailstone_sequence_length(3*n + 1) + 1;
}
}
Notice how the cycle variable is gone. It is unnecessary, because each call just has to add 1 to the value computed by the recursive call. The recursion bottoms out at 1, and so we count that as 1. All other recursive steps add 1 to that, and so at the end we are left with the sequence length.
Careful: this approach requires a stack depth proportional to the input n.
I dropped the use of unsigned because it's an inappropriate type for doing most math. When you subtract 1 from (unsigned long) 0, you get a large positive number that is one less than a power of two. This is not a sane behavior in most situations (but exactly the right one in a few).
Now let's discuss where you went wrong. Your original code attempts to measure the hailstone sequence length by modifying a global counter called cycle. However, the main function expects calculate to return a value: you have cycle = calculate(...).
The problem is that two of your cases do not return anything! It is undefined behavior to extract a return value from a function that didn't return anything.
The (n == 1) case does return something but it also has a bug: it fails to increment cycle; it just returns cycle + 1, leaving cycle with the original value.
Part 2
Looking at the main. Let's reformat it a little bit.
int main()
{
unsigned long int i=0,j=0,loop=0;
Change these to long. By the way %ld in scanf expects long anyway, not unsigned long.
while (scanf("%ld %ld",&i,&j) != EOF)
Be careful with scanf: it has more return values than just EOF. Scanf will return EOF if it is not able to make a conversion. If it is able to scan one number, but not the second one, it will return 1. Basically a better test here is != 2. If scanf does not return two, something went wrong with the input.
{
if(i > j)
{
unsigned long int t=i;i=j;j=t;
}
for(loop=i;loop<=j;loop++)
{
cycle=0;
cycle=calculate(loop );
if(cycle>final)
{
final=cycle;
}
}
calculate is called hailstone_sequence_length now, and so this block can just have a local variable: { long len = hailstone_sequence_length(loop); if (len > final) final = len; }
Maybe final should be called max_length?
printf("%ld %ld %ld\n",i,j,final);
final=0;
final should be a local variable in this loop since it is separately used for each test case. Then you don't have to remember to set it to 0.
}
return 0;
}