I'm taking a course in C (it's my first week) and I need to write a program that prints out sequences of hailstone numbers.
I'm expected to build a function to do that.
The next number gets printed out but that's it. For example when I enter 58, I get 29. But I'd like to print out a whole sequence of 9 next numbers.
Please, if you could guide in the right direction, I'd be eternally grateful.
#include <stdio.h>
#include <stdlib.h>
int Hailstone (int n)
{
if (n % 2 == 0) {
return n /= 2;
}
else {
return n = 3 * n + 1;
}
return n;
}
int main (void)
{
int start, result;
printf("Input a number: ");
scanf("%d", &start);
result = Hailstone(start);
printf("%d\n", result);
return 0;
}
What you want is to iterate. You don't need the result variable; you just plug in the new value:
while (start > 1) {
start = Hailstone(start);
printf ("%d\n", start);
}
There's a bit more that could be improved, e.g. the return n; is unreachable and the assignments to n are useless:
int Hailstone (int n)
{
if (n % 2 == 0) {
return n / 2;
}
else {
return 3 * n + 1;
}
}
If you want to hand in a pro C version of Hailstone() you could even write it as
int Hailstone (int n)
{
return n % 2 ? 3 * n + 1 : n / 2;
}
see, in your program, you are trying to return only a single value to the main..Hence to print all the numbers just write a loop as below..
#include <stdio.h>
#include <string.h>
int Hailstone(int n)
{
if(n % 2 == 0) {
return n /=2;
}
else {
return n = (3 * n) + 1;
}
}
int main (void)
{
int start;
printf("Input a number: ");
scanf("%d", &start);
while(start!=1)
{
start = Hailstone(start);
printf("%d\n", start);
}
}
Related
#include <stdio.h>
int FAC(int a)
{
if (a >= 1, a--)
{
return a + 1 * a;
FAC(a);
}
}
int main()
{
int a = 0;
int ret = 0;
scanf("%d", &a);
ret = FAC(a);
printf("%d\n", ret);
}
if I input 5 the outcome is 8
But in the first function should't it be
5>=1 5-1 return 5*4 4>=1...
First of all, you're returning a value before you're using recursion. The return keyword takes effect immediately, so all statements following this won't be executed.
Also, your factorial function does not actually calculate the factorial of a.
Examples for factorial functions:
Recursive
int factorial(int n) {
if(n > 0) {
return n * factorial(n - 1); // n! = n * (n-1) * (n-2) * ... * 1
} else {
return 1;
}
}
Iterative
// Does exactly the same, just an iterative function
int factorial(int n) {
int fac = 1;
for(; n > 0; n--) {
fac *= n;
}
return fac;
}
Your factorial function (FAC) should ideally be something like:
unsigned int FAC(unsigned int a)
{
// base condition - break out of recursion
if (a <= 1)
return 1;
return a * FAC(a - 1);
}
unsigned int restricts range of argument to be in [0, UINT_MAX].
Do note that FAC returns a unsigned int, so you may be able to provide argument value up to 12, else there will be an overflow and you can see weird output.
BTW, UINT_MAX is defined in limits.h
#include <stdio.h>
int FAC(int a)
{
if (a < 0) {
return -1;
} else {
if (a == 0) {
return 1;
} else {
return (a * FAC(a-1));
}
}
}
int main()
{
int a = 0;
int ret = 0;
scanf("%d", &a);
ret = FAC(a);
if (ret == -1) {
printf("%s\n", "Input was a negative integer.");
} else {
printf("%d\n", ret);
}
}
(Purpose of the code is write in the title) my code work only if i put the same number once and in the end like - 123455 but if i write 12345566 is dosent work or 11234 it dosent wort to someone know why? i have been trying for a few days and i faild agine and agine.
while(num)
{
dig = num % 10 // dig is the digit in the number
num /= 10 // num is the number the user enter
while(num2) // num2 = num
{
num2 /= 10
dig2 = num2 % 10 // dig2 is is the one digit next to dig
num2 /= 10
if(dig2 == dig) // here I check if I got the same digit twice to
// not include him
{
dig2 = 0
dig = 0
}
}
sum = sum + dig + hold
}
printf("%d", sum)
Well your code's almost correct but there's are somethings wrong ,
When you declared num2 to be equal to num1 it was out of the loop so as soon as one full loop execution is done , num2 still remains to be less than zero or to be zero if it was a unsigned int, so according to the condition the second loop wont execute after its first run.
So mind adding ,
num2 = num1
inside your first loop .
Also your updating num2 twice which i think you wont need to do after the first change .
Full code which i tried
#include<stdio.h>
int main(void)
{
int num;
int num2;
int sum = 0;
int dig, dig2;
scanf_s("%d", &num);
while (num>0)
{
dig = num % 10; //dig is the digit in the number
num /= 10;
num2 = num;// num is the number the user enter
while (num2>0) // num2 = num
{
dig2 = num2 % 10; // dig2 is is the one digit next to dig
if(dig2 == dig) // here i check if i got the same digit twice to //not include him
{
dig = 0;
}
num2 /= 10;
}
sum = sum + dig ;
}
printf("%d", sum);
return 0;
}
O(n)
#include <stdio.h>
int main () {
unsigned int input = 0;
printf("Enter data : ");
scanf("%u", &input);
int sum = 0;
int dig = 0;
int check[10] = {0};
printf("Data input: %u\n", input);
while(input) {
dig = 0;
dig = input%10;
input = input/10;
if (check[dig] == 0) {
check[dig]++;
sum += dig;
}
}
printf("Sum of digits : %d\n", sum);
return 0;
}
My program uses a character array (string) for storing an integer. We convert its every character into an integer and I remove all integers repeated and I calculate the sume of integers without repetition
My code :
#include <stdio.h>
#include <stdlib.h>
int remove_occurences(int size,int arr[size])
{int s=0;
for (int i = 0; i < size; i++)
{
for(int p=i+1;p<size;p++)
{
if (arr[i]==arr[p])
{
for (int j = i+1; j < size ;j++)
{
arr[j-1] = arr[j];
}
size--;
p--;
}
}
}
for(int i=0;i<size;i++)
{
s=s+arr[i];
}
return s;
}
int main()
{
int i=0, sum=0,p=0;
char n[1000];
printf("Input an integer\n");
scanf("%s", n);
int T[strlen(n)];
while (n[i] != '\0')
{
T[p]=n[i] - '0'; // Converting character to integer and make it into the array
p++;i++;
}
printf("\nThe sum of digits of this number :%d\n",remove_occurences(strlen(n),T));
return 0;
}
Example :
Input : 1111111111 Output : 1
Input : 12345566 Output : 21
Or ,you can use this solution :
#include <stdio.h>
#include <stdbool.h>
bool Exist(int *,int,int);
int main ()
{
unsigned int n = 0;
int m=0,s=0;
printf("Add a number please :");
scanf("%u", &n);
int T[(int)floor(log10(abs(n)))+1];
// to calculate the number of digits use : (int)floor(log10(abs(n)))+1
printf("\nThe length of this number is : %d\n",(int)floor(log10(abs(n)))+1);
int p=0;
while(n!=0)
{
m=n%10;
if(Exist(T,p,m)==true)
{
T[p]=m;
p++;
}
n=n/10;
}
for(int i=0;i<p;i++)
{
s=s+T[i];
}
printf("\nSum of digits : %d\n", s);
return 0;
}
bool Exist(int *T,int k,int c)
{
for(int i=0;i<k;i++)
{
if(T[i]==c)
{
return false;
}
}
return true;
}
test case:
input: 1234
output: 24
input: 2468
output: 2468
input: 6
output: 6
I have this code:
#include <stdio.h>
#include <math.h>
int main() {
int num;
printf("Enter a number: \n");
scanf("%d", &num);
int numberLength = floor(log10(abs(num))) + 1;
int inputNumberArray[numberLength];
int evenNumberCount = 0;
int even[10];//new even no. array
int i = 0;
do {
inputNumberArray[i] = num % 10;
num = num / 10;
i++;
} while (num != 0);
i = 0;
while (i < numberLength) {
if (inputNumberArray[i] % 2 == 0) {
evenNumberCount ++;
even[i] = inputNumberArray[i];
}
i++;
}
printf("array count %d\n", evenNumberCount);
i = 0;
for (i = 0; i < 8; i++) {
printf(" %d", even[i]);//print even array
}
i = 0;
int result = 0;
for (i = 0; i < 10; i++) {
if (evenNumberCount == 1) {
if (even[i] != 0) {
result = even[i];
} else {
break;
}
} else {
if (even[i] != 0) {
result = result + even[i] * pow(10, i);
} else
break;
}
}
printf("\nresult is %d", result);
/*
int a = 0;
a = pow(10, 2);
printf("\na is %d", a);
*/
}
when I enter number 1234, the result/outcome is 4, instead of 24.
but when I test the rest of test case, it is fine.
the wrong code I think is this: result = result + even[i] * pow(10, i);
Can you help on this?
Thanks in advance.
why do you have to read as number?
Simplest algorithm would be
Read as text
Validate
loop through and confirm if divisible by 2 and print live
next thing, have you try to debug?
debug would let you know what are doing wrong. Finally the issue is with indexing.
evenNumberCount ++; /// this is technically in the wrong place.
even[i]=inputNumberArray[i]; /// This is incorrect.
As the user Popeye suggested, an easier approach to accomplish this would be to just read in the entire input from the user as a string. With this approach, you can iterate through each letter in the char array and use the isdigit() method to see if the character is a digit or not. You can then easily check if that number is even or not.
Here is a quick source code I wrote up to show this approach in action:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char input[100] = { '\0' };
char outputNum[100] = { '\0' };
// Get input from user
printf("Enter a number: ");
scanf_s("%s", input, sizeof(input));
// Find the prime numbers
int outputNumIndex = 0;
for (int i = 0; i < strlen(input); i++)
{
if (isdigit(input[i]))
{
if (input[i] % 2 == 0)
{
outputNum[outputNumIndex++] = input[i];
}
}
}
if (outputNum[0] == '\0')
{
outputNum[0] = '0';
}
// Print the result
printf("Result is %s", outputNum);
return 0;
}
I figured out the solution, which is easier to understand.
#include <stdio.h>
#include <math.h>
#define INIT_VALUE 999
int extEvenDigits1(int num);
void extEvenDigits2(int num, int *result);
int main()
{
int number, result = INIT_VALUE;
printf("Enter a number: \n");
scanf("%d", &number);
printf("extEvenDigits1(): %d\n", extEvenDigits1(number));
extEvenDigits2(number, &result);
printf("extEvenDigits2(): %d\n", result);
return 0;
}
int extEvenDigits1(int num)
{
int result = -1;
int count = 0;
while (num > 1) {
int digit = num % 10;
if (digit % 2 == 0) {
result = result == -1 ? digit : result + digit * pow(10, count);
count++;
}
num = num / 10;
}
return result;
}
}
You are overcomplicating things, I'm afraid.
You could read the number as a string and easily process every character producing another string to be printed.
If you are required to deal with a numeric type, there is a simpler solution:
#include <stdio.h>
int main(void)
{
// Keep asking for numbers until scanf fails.
for (;;)
{
printf("Enter a number:\n");
// Using a bigger type, we can store numbers with more digits.
long long int number;
// Always check the value returned by scanf.
int ret = scanf("%lld", &number);
if (ret != 1)
break;
long long int result = 0;
// Use a multiple of ten as the "position" of the resulting digit.
long long int power = 1;
// The number is "consumed" while the result is formed.
while (number)
{
// Check the last digit of what remains of the original number
if (number % 2 == 0)
{
// Put that digit in the correct position of the result
result += (number % 10) * power;
// No need to call pow()
power *= 10;
}
// Remove the last digit.
number /= 10;
}
printf("result is %lld\n\n", result);
}
}
I recently made code in C that reads a set of numbers until zero (zero ends the number set) and prints its prefix sum:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, sum;
sum = 0;
while(x)
{
scanf("%d", &x);
sum += x;
if(x != 0)
{
printf("%d,", sum);
}
else{
break;
}
}
return 0;
}
If I were to type 2 3 5 7 11 0: It would print the following:
2,5,10,17,28,
I was wondering how to remove the comma by the number 28 or to add commas to numbers until the last number?
My preferred solution, adapted to the code in the question, is:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int sum = 0;
int x;
const char *pad = ""; /* Or put a prefix here */
while (scanf("%d", &x) == 1 && x != 0)
{
sum += x;
printf("%s%d", pad, sum);
pad = ","; /* Or use ", " if you prefer */
}
putchar('\n');
return 0;
}
Note that this code does not test the uninitialized variable x on the first iteration (unlike the code in the question), and it checks that the scanf() succeeds before using the value (unlike the code in the question). These are routine precautions you should be taking. It would be possible to adapt the code to keep track of how many bytes have been printed on the line (what's the return value from printf()?) and arrange for pad to contain "\n" (instead of a comma, or ",\n" if you want a comma at the end of all lines except the last) when the line gets 'too long'.
Note too that if you type the numbers at the program, the output gets messy. If the program is reading from a built-in list of numbers, or reading from a file, then you get good outputs.
You could use the following approach:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 0;
int sum = 0;
int i = -1;
int ret;
while(1)
{
i++;
ret = scanf("%d", &x);
if(ret != 1)
break;
sum += x;
if(x != 0)
{
if(i == 0)
printf("%d", sum);
else
printf(",%d", sum);
}
else
{
break;
}
}
printf("\n");
return 0;
}
Output:
1
2
3
0
1,3,6
Print the comma before all but the first value. It's not elegant but it works.
if(x != 0)
{
if(sum == x) // On the first pass, sum == x
printf("%d", sum);
else
printf(",%d", sum);
}
Of course, this could break if you have negative values. In that case, keeping a counter or bool would be better.
print comma only after the first iteration (use a custom flag) , print result no matter what:
int first_iteration = 1;
...
if (!first_iteration)
{
printf(",");
}
sum += x;
first_iteration = 0;
printf("%d", sum);
There is always a clumsy but tried-and-true method:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, sum;
sum = 0;
comma = 0;
while(x)
{
scanf("%d", &x);
sum += x;
if(x != 0)
{
if (comma != 0)
{
printf(",");
}
printf("%d", sum);
comma = 1;
}
else{
break;
}
}
return 0;
}
int main()
{
int i,n;
printf("Enter the number");
scanf("%d",&n);
i=pali(n);
if(n==i)
printf("Number is pall");
else
printf("Not Pall");
}
int pali(int n)
{
int r;
static sum=0;
if(n!=0)
{
r=n%10;
sum=sum*10+r;
pali(n/10);
}
return sum;
}
I used a static variable to add up the sum. Is there any way where no static variable will be used?
Yes, the typical ("functional") approach is to carry the state in the form of a function argument. This often makes it necessary/nice to have a second function that does the actual recursion, which you can start by calling with the proper initial values for the state:
int do_pali(int sum, int n)
{
if(n != 0)
{
const int r = n % 10;
return do_pali(10 * sum + r, n / 10);
}
return sum;
}
the public function then just becomes:
int pali(int n)
{
return do_pali(0, n);
}
In languages with inner functions this can be more neatly expressed (GCC supports this as an extension).
Sure, you can do it this way :
#include <stdio.h>
int pali(int n)
{
int sum = 0;
int keeper = 0;
for (int i = n; i > 0; i /= 10) {
if (keeper != 0) {
sum *= 10;
sum += (keeper - i * 10);
}
keeper = i;
}
sum *= 10;
sum += keeper;
return sum;
}
int main(int argc, char** argv)
{
int i, n;
printf("Enter the number : ");
scanf("%d",&n);
i = pali(n);
if(n == i)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
Using recursion is even easier :
#include <stdio.h>
int pali(int n, int sum)
{
sum += n - ((n / 10) * 10);
n /= 10;
if (n > 0)
pali(n, sum * 10);
else
return sum;
}
int main(int argc, char** argv)
{
int i, n;
printf("Enter the number : ");
scanf("%d",&n);
i = pali(n, 0);
if(n == i)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
And a recursive version with only one parameter :
#include <stdio.h>
int pali(int n)
{
int fUnit, lUnit;
fUnit = n;
int mul = 1;
while (fUnit > 10) {
fUnit /= 10;
mul *= 10;
}
lUnit = n - ((n / 10) * 10);
n -= (fUnit * mul);
n /= 10;
if (mul == 1) return 1;
else if (fUnit == lUnit) return pali(n);
else return 0;
}
int main(int argc, char** argv)
{
int n;
printf("Enter the number : ");
scanf("%d",&n);
if(pali(n) == 1)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
Since your function returns sum you could replace this line:
pali(n/10);
with
sum=pali(n/10);
You'd also have to move it up a line too.
Here is an optimized version that
Doesn't use local static.
Only includes stdio.h
Uses recursion.
#include <stdio.h>
static void perform_useless_recursion (int n)
{
if(n--)
{
perform_useless_recursion(n);
}
}
_Bool is_pali (int n)
{
perform_useless_recursion(1);
int sum = 0;
for(int i=n; i!=0; i/=10)
{
sum = sum*10 + i%10;
}
return n == sum;
}
int main (void)
{
int n=5005;
if(is_pali(n))
printf("Number is pall");
else
printf("Not Pall");
return 0;
}
The code could be improved even further by removing the perform_useless_recursion() function.
The advantage of this code is that the actual calculation is performed by a fast loop, instead of slow, dangerous recursion. In the real world outside artificial school assignments, there is no reason to write inefficient and dangerous code when you could write efficient and safe code. As a bonus, removing recursion also gives far more readable code.
If you benchmark this code you'll notice that it will be faster than all other versions posted and consumes less memory.
You can make a function that check only the first and the last digits of the number and pass the rest of the number onward.
To explain better, think about the following cases:
pali(1220) would check for the first (1) and last (0) digits. Since 1 != 0 pali would return false.
pali(17891) would check first (1) and last (1). Since they're equal then the function would recursively return pali(789) (which itself would return false since 7 != 9).
pali(878) would check that 8=8 and recursively return pali(7)
pali(3) would check that first (3) and last (3) numbers are equal and return 0.
The challenge here is to develop an algorithm that:
Check if first and last numbers are the same (even if it's only one digit!)
Strip the number from first and last digits and call itself on the remainder
Then all you need to do is apply recursion. Here's a sample implementation:
int pali(int number)
{
int smallDigit, bigDigit;
/* When recursion ends suceffuly*/
if (number == 0)
return 1;
/* Check for first and last digit of a number */
smallDigit = number % 10;
bigDigit = number;
while(bigDigit/10!=0)
{
bigDigit = bigDigit/10;
smallDigit = smallDigit*10;
}
/* Check to see if both digits are equal (Note: you can't use smallDigit here because it's been multiplied by 10 a few times) */
if (bigDigit != number%10)
return 0;
else
{
number = (number - smallDigit)/10; /* This is why smallDigit was multiplied by 10 a few times */
return pali(number); /* Recursion time */
}
}