Creating a function to check if a number is Palindrome - c

i am trying to make a function to return true if the number is palindrome and return false if the number is not , so first i created a function that reverse the number then another function to tell if the reversed number is equal to the original number , but it not returning for me the correct output , any help ?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
//Reversing a number
int DigitsReversing(int num)
{
int resultofR = 0;
while (num > 0)
{
resultofR = resultofR * 10 + num % 10;
num = num / 10;
}
return resultofR;
}
//telling if the original number equal to the reversed number if yes return if not return false
int isPali(int num)
{
DigitsReversing(num);
int resultofR;
if (num == resultofR)
return true;
else
return false;
return 0;
}
//calling the function
int main()
{
int num;
scanf("%d", &num);
printf("%d", isPali(num));
return 0;
}
edited **** :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
int DigitsReversing(int num)
{
int resultofR = 0;
while (num > 0)
{
resultofR = resultofR * 10 + num % 10;
num = num / 10;
}
return resultofR;
}
bool isPali(int num , int resultofR)
{
resultofR = DigitsReversing(num);
if (num == resultofR)
return true;
else
return false;
}
int main()
{
int num, resultofR;
scanf("%d", &num);
resultofR = DigitsReversing(num);
isPali(num, resultofR);

C does have a boolean datatype. Usually, 0 is false and 1 is true. They return value 1 for true and 0 for false.
As #exnihilo and #bob__ suggested C does have boolean datatypes.
#include<stdio.h>
#include<math.h>
//Reversing a number
int DigitsReversing(int num)
{
int resultofR = 0;
while (num > 0)
{
resultofR = resultofR * 10 + num % 10;
num = num / 10;
}
return resultofR;
}
//telling if the original number equal to the reversed number if yes return if not return false
void isPali(int num)
{
int resultofR= DigitsReversing(num);
if (num == resultofR)
printf("True");
else
printf("False");
}
//calling the function
int main()
{
int num;
scanf("%d",&num);
isPali(num);
return 0;
}
OUTPUT
For non-palindrome numbers.
9998
False
--------------------------------
Process exited after 10.35 seconds with return value 0
Press any key to continue . . .
For palindrome numbers.
9999
True
--------------------------------
Process exited after 10.35 seconds with return value 0
Press any key to continue . . .

The posted snippets show some confusion about fundamental topics like the correct way to pass arguments to a function and collect the returned value or just the differnece between an "output" and a "returned" value.
Consider this, for example:
bool isPali(int num , int resultofR)
{ // ^^^^^^^^^ It's passed to the function...
resultofR = DigitsReversing(num); // <- and immediately overwritten by another value
if (num == resultofR)
return true;
else
return false;
}
int main()
{
int resultofR;
// ...
resultofR = DigitsReversing(num); // <-- This is effectually called twice
isPali(num, resultofR); // <-- The returned value is ignored
}
You just need to write one function
#include <stdbool.h>
bool is_palindrome(long num)
{
long reversed = 0;
for (long i = num; i > 0; i /= 10)
{
reversed = reversed * 10 + i % 10;
}
return reversed == num;
}
Then, call it and interpret its return value properly, to generate the wanted output
int number;
scanf("%d", &number);
printf("%s\n", is_palindrome(number) ? "True" : "False");

Related

why this c program can't compile factorial

#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);
}
}

Program to check if an number contained in another number

i did a program that can check if a number contained in another number , for example :
1234
234
does 1234 contain 234 ? yes . print true
1234
943
does 1234 contain 943 ? no . print false
my problem that i don't know how should i print false , i have an problematic if , so how i can print false only if the number not contained ? if the program prints true its also print false anyway , so how i can make it print false only if the number not contained ?
my code :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int main() {
int firstnumb, tobechecked, numberofdigits = 0, hezka;
scanf("%d %d", &firstnumb, &tobechecked);
numberofdigits = log10(tobechecked) + 1;
hezka = pow(10, numberofdigits);
while (firstnumb > 0) {
if (firstnumb % hezka == tobechecked) {
printf("true");
}
firstnumb = (firstnumb / 10);
}
printf("false");
}
edited :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int main() {
int firstnumb, tobechecked, numberofdigits = 0, hezka , result = 0;
scanf("%d %d", &firstnumb, &tobechecked);
numberofdigits = log10(tobechecked) + 1;
hezka = pow(10, numberofdigits);
while (firstnumb > 0) {
if (firstnumb % hezka == tobechecked) {
result = 1;
}
firstnumb = (firstnumb / 10);
}
if (result) {
printf("true");
}
else {
printf("false");
}
}
You can count the number of time the number to be checked was found. Then, after the while loop, use that count to determine if you print true or false.
int count = 0;
while (firstnumb > 0) {
if (firstnumb % hezka == tobechecked) {
count++;
}
firstnumb = (firstnumb / 10);
}
if (count == 0)
{
printf("false");
}
else
{
printf("true");
}

how do I add up the sum of the digits of a number except for digits that repeat themselves in c?

I have an assignment and I need to add up the digits of it and ignore the once that repeat themselves
for example 234111 -> 2 + 3 + 4 + 1 -> 10
I tried doing this:
#include
int main(void)
{
int i = 0;
int num = 0;
int sum = 0;
printf("Please enter a number\n");
scanf("%d", &num);
while(num > 0){
sum += num%10;
num /= 10;
}
printf("%d", sum);
return 0;
}
what I did just adds up the digits, it doesn't ignore that ones that get repeated
What do i need to add to the code?
You can keep an array of 'flags' for which digits have been used already:
#include <stdio.h>
int main(void)
{
// int i = 0; // You don't actually use this in the code!
int num = 0;
int sum = 0;
int used[10] = { 0, }; // Set all "used" flags to zero
printf("Please enter a number\n");
scanf("%d", &num);
while (num > 0)
{
int digit = num % 10; // Get the digit
if (!used[digit]) sum += digit; // Only add if not used already
used[digit] = 1; // Now we have used it!
num /= 10;
}
printf("%d", sum);
return 0;
}
Feel free to ask for further clarification and/or explanation.
Just read each character and record if you've already seen it:
#include <stdio.h>
#include <ctype.h>
int
main(void)
{
int seen[10] = {0};
int sum = 0;
int c;
while( ( c = getchar()) != EOF ) {
int v = c - '0';
if( isspace(c)) {
continue;
}
if( v < 0 || v > 9 ) {
fprintf(stderr, "Invalid input\n");
return 1;
}
if( ! seen[v]++ )
sum += v;
}
printf("%d\n", sum);
return 0;
}

A recursive function that determines whether the digits of a number are in ascending order

I'm practicing recursion and my solution to the problem doesn't seem to work.
I'm trying to write a recursive code that will determine if the digits of a number are in ascending order or not. here's my code:
#include <stdio.h>
int isAscending(int num);
int main(){
int result;
result = isAscending(123);//Should print "The number is in ascending order!"
if (result == 0) {
printf("The number is in ascending order!\n");
}
else {
printf("The number is not in ascending order!\n");
}
}
int isAscending(int num) {
int new = num / 10;
int result = 0;
if ((num % 10) == 0) {
return 0;
}
else if ((num % 10) > (new % 10)) {
result += isAscending(num / 10);
return result;
}
else {
return 1;
}
}
Here's another (bare-bones) way to go about it. The basic idea is that if we have a single digit, we return affirmative, else we check if the rightmost number is greater than the one just to it's left. And we do this for the remaining digits.
#include <stdio.h>
int isAsc(int i)
{
int rem = i % 10; // remainder
int quo = i / 10; // quotient
if (rem == i)
return 1;
else if (rem <= (quo % 10))
return 0;
else
return 1 && isAsc(quo);
}
int main(void)
{
int i = 123123;
if (isAsc(i))
printf("%s\n", "Ascending");
else
printf("%s\n", "Not ascending");
return 0;
}
Can you please try below recurrsive code:
`
boolean isascending(int num){
if(num == 0) return true;
if(num%10>num%100) return isascending(num/10);
else return false;
}`
or you can use while loop:
while(num>0){
if(num%10 > num%100){
num = num/10;
continue;
} return false;
} return true;
It would be better to use another parameter to store the last digit, which is going to be "dropped" in the current iteration.
So I came up with the following recursive logic:
use a parameter which stores the last digit dropped
base case: if the number is 0, return 0 (true)
calculate the current last digit of the number (number%10)
if the current last digit is greater than the last digit dropped: is this case, return 1 (false)
if not, return isAscendingRecursive() on the new number dropping the current last digit and pass it as the next iteration last digit.
Code:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char** args){
int num=0;
printf("Insert a number:\n");
scanf("%d",&num);
if(isAscending(num)==0)
printf("Ascending\n");
else
printf("Not ascending\n");
}
int isAscending(int num){
return isAscendingRecursive(num,9);
}
int isAscendingRecursive(int num, int lastDigit){
if(num == 0)
return 0;
int temp = num%10;
if(temp > lastDigit)
return 1;
else
return isAscendingRecursive(num/10, temp);
}
This solution returns 0 on failure otherwise some other integer on success. It seems that isDescending() is easier to write when returning 0 as a failure value but I contorted this accordingly:
#include <stdio.h>
#include <stdlib.h>
int isAscending(int num) {
int quotient = num / 10;
int remainder = num % 10;
if (quotient != 0) {
int result = isAscending(quotient);
if (result == 0 || result >= remainder) {
return 0;
}
}
return remainder;
}
int main(int argc, char **argv) {
if (isAscending(atoi(argv[1]))) {
printf("The number is in ascending order!\n");
} else {
printf("The number is not in ascending order!\n");
}
return 0;
}
TESTS
% ./a.out 123
The number is in ascending order!
% ./a.out 321
The number is not in ascending order!
% ./a.out 101
The number is not in ascending order!
%
No, it doesn't handle negative numbers! It also doesn't handle '0' correctly as an input -- other single digit numbers are fine.
Again, isDescending() is easier to write but unfortunately, !isDescending() != isAscending()
Your tests are incorrect. You should return true for numbers with a single digit, false if the last digit is less or equal to the previous one and recurse for the rest:
int isAscending(int num) {
int new = num / 10;
if (new == 0) {
return 1;
} else
if (num % 10 <= new % 10) {
return 0;
} else {
return isAscending(new);
}
}
This kind of recursion is called tail recursion as you return the result of the recursive call. Good compilers will generate iterative code equivalent to this:
int isAscending(int num) {
for (;;) {
int new = num / 10;
if (new == 0) {
return 1;
}
if (num % 10 <= new % 10) {
return 0;
}
num = new;
}
}
I fixed my code and it works, thanks for the help!:
#include <stdio.h>
int isAscending(int num);
int main(){
int result;
result = isAscending(2589);//Should print "The number is in ascending order!"
if (result == 0) {
printf("The number is in ascending order!\n");
}
else {
printf("The number is not in ascending order!\n");
}
}
int isAscending(int num) {
int new = num / 10;
int result = 0;
if ((num % 10) == 0) {
return 0;
}
else if ((num % 10) > (new % 10)) {
return isAscending(num / 10);
}
else {
return 1 + isAscending(num / 10);
}
}

C program with a function which checks if integer A contains integer B

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int funkcija(int num, int num2)
{
int doesContain;
if (doesContain == 1)
return 1;
else
return 0;
}
int main(void)
{
int num, num2;
scanf("%d", num);
scanf("%d", num2);
printf("%d", funkcija(num, num2));
return 0;
}
So basically, I need to make a function which takes number 1 and number 2, checks if number2 is in number1, then returns 0 or 1.
So for example, if number 1 is let's say '2452325678', and number 2 is '7', number 1 DOES contain number 2 and the statement is true. But if num1 is '2134' and num2 is '5', the statement is false.
It needs to be done PRIMITIVELY, without arrays and whatnot.
I need any help I can get with the algorithm.
int numsub(int haystack, int needle)
{
for (; haystack; haystack /= 10)
if (haystack % 10 == needle)
return 1;
return 0;
}
fairly simple, works by keeping dividing the number by 10 and each time
checking if currentNumber % 10 == the digit checked.
that's all.
example:
int i;
int num;
int flag;
int digit;
flag = 1;
num = 1234;
digit = 2;
while(num != 0 && flag)
{
if(num % 10 == digit)
{
flag = 0;
}
else
{
num = num / 10;
}
}
if(flag == 1)
{
//flag stays set,which means that digit is not inside num
}
else
{
//flag is not set, which means that digit is indeed a part of num.
}

Resources