Can you give me some suggestions on my problem? - c

I want to solve the problem. The problem is to check whether the number is palindrome or not.
There has been a lot of solutions that exist online. But I am trying to solve this problem through my approach without seeing any solution from the internet. I am trying this way->
#include <stdio.h>
int main(){
//Declaring variables for further proceed
int number,reminder,quotient=1;
//Just take the input from the user
printf("Input : ");
scanf("%d",&number);
while(quotient!=0){
quotient=number/10;
reminder=number%10;
printf("%d",reminder);
number=quotient;
}
return 0;
}
The problem is : My code is work for displaying the reverse order of any given number. But I could not check with this reverse order with the given number. If you can then you are most welcome. Thank you in advance.

//Write a program to check the number whether it is palindrome or not
#include <stdio.h>
int
main(void){
//Put variables for the further proceed
int number, quotient=1, remainder,i=0;
//To declare a character array
char text[100];
//To show the message to the user
printf("Enter an integer number :");
//Taking input from the user
scanf("%d",&number);
//For finding escape the integer number in the reverse order specifically
int number_update=number;
//To find out the integer number in the reverse order
while(quotient!=0){
quotient=number_update/10;
remainder=number_update%10;
number_update=quotient;
text[i] = remainder + '0';//Converts integer to character and store to the array
i++;
}
//Converts the string to a whole integer
int result_of_reverse=atoi(text);
//Check the result of reverse order with the given integer number
if(result_of_reverse==number){
//To display the result
printf("This is a palindrome number");
}
else{
//To display the result
printf("This is not a palindrome number");
}
}
Eventually, I have solve my problem. Thank you all for your suggestions.

I applaud your decision to follow your approach through.
Allow me to start a step-by-step answer according to the compromise described here (applicable to homework, challenges and very disciplined self-learners like you):
How do I ask and answer homework questions?
Step 1:
You program is able to look at digit by digit of the number in the right order (you can output them). But it does not get an overview of them. You do not store them. Neither separatly nor as a whole (string or number). Consider how to change that.
Do you know a way to store several seperate digits?
Do you know a way to store a string of characters?
Aleternatively, if you do not want to store the reordered digits, i.e. if you want to continue looking at single digits, then you need to always look at two single digits, one pair after the other. Each pair needs to consist of one digit from the high end and one digit from the low end. Maybe you can think of a way to start the number from both ends while looping. More variables to store intermediate results might help with this.
Step 2:
You "know a little bit of the way how to store a string of characters", so do that. Store the characters which you output. If you do not know how to get from digit to character read up on sprintf(). This is a little complex, because the goal is to have a single string, not several strings with one digit each. So ...
Alternatively, to store single digits as their own integers, read up on "arrays". You specifically need an array of int.
If both seems to complicated do not forget the alternative from first step, to look at pairs of digits, from both ends of the number. For that try to print for example for the input "654321" the output "6:1, 5:2, 4:3". If you can do that, things get much easier.

Related

Limiting the type length of the user on C

My code asks a the 10 digit number, it reads it as a string, pass it to another function that checks if the user's input is a real number and has no characters or symbols with ASCII, and then if it's good, with atof it changes the string into a number for a variable.
I want the user to only introduce 10 digits/characters on the input console, I mean, if the user would put a 11 character for example, the console just don't grab it, or in the case this is impossible for C, make that if the user put more than 12 characters on the input, then the program launches an error message saying it exceeds the limit, the problem is, when i tried to use this method, for example if i put some big numbers like a 40 digit number, then the program goes crazy and send just incomprehensible results like "1.#J", or if I put a character in middle of the numbers, then it sends the corresponding error message i set for the user to not put characters, but it still grabs part of the number and accept it as it is nothing wrong, here's the main of code I tried:
int main() {
char chain[10];
float N;
int valid=0;
do{
printf("introduce real numbers: ");
fgets(chain, sizeof(chain), stdin);
if( chain[strlen(chain)-1] == '\n')
chain[strlen(chain)-1] = '\0';
valid=validate_numbers(chain);
}while(valid==0);
N=atof(chain);
printf("float number is: %.2f", N);
getche();
return 0;
}
Here's the rest of the code for more extense check: Pastebin
And sorry if there's some novice errors or the question is plain simple, im quite new programing.
Change this:
char chain[10];
to this:
char chain[11]; // +1 for the NULL terminator
since C-strings should be NULL terminated, thus we need one cell reserved for the NULL-terminator in our array (which will store our string).
I mean, if the user would put a 11 character for example, the console just don't grab it
Not possible in C.
or in the case this is impossible for C, make that if the user put more than 12 characters on the input, then the program launches an error message saying it exceeds the limit.
Yes, let's do that! Read the string, and if the length of it is more than 10 characters, then print an error message.
Allow chain array to be of size 12 (10 for the maximum length of the valid input, 1 for an extra character (if any) and 1 for the NULL-terminator), so that we can store the extra character, if any.
Example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char chain[12];
printf("introduce real numbers:\n");
fgets(chain, sizeof(chain), stdin);
chain[strcspn(chain, "\n")] = '\0';
if(strlen(chain) > 10)
{
printf("Error: Maximum length of chain is 10! Exiting..\n");
return 1;
}
return 0;
}
Note: You could use EXIT_SUCCESS and EXIT_FAILURE, instead of plain numbers (1 and 0 respectively): Should I return 0 or 1 for successful function?
Irrelevant to OP's question: In the full version of your code though, there is a plethora of problems, such as this top line of code int valid=validate_numbers(char number[]);, which wishes to declare the method. It should be just validate_numbers(char number[]);. The same holds true for the definition of the method too. Make sure you go through all your code again, and read the messages the compiler gifts to you. :)
What about using scanf instead of fgets? This should read 9 characters and save them as a string:
scanf("%9s" , &chain)
I'd suggest reading https://en.m.wikipedia.org/wiki/Scanf_format_string and man pages as well.

Print number with zero on first place

How i can print for example?
int a = 0145236
When I want to use it, it always gives me a octal number.
Whenever you put zero in front of your number it is printed in octal only. That is the way c works.
However, if you take input from the user and supposing user entered 0123456 it is stored in your variable as 123456 so just don't add 0 in the beginning of your integer number when hard coding.
In case you need to add leading zeros in your number this may help Printing leading 0's in C?

Identyfying prefix in the same string as a suffix

Eg-
maabcma is valid because it contains ma as a proper prefix as well as a proper suffix.
panaba is not.
How do I find out if a word is valid or not as above in C language?
I'm not very good at string operations. So, please help me out with a pseudocode.
Thanks in advance.
I'm completely lost. T=number of test cases.
EDIT: New code. My best code so far-
#include<stdio.h>
#include<string.h>
void main()
{
int i,T,flag=0;
int j,k,len=0;
char W[10],X[10];
scanf("%d",&T);
for(i=0;i<T;i++)
{
scanf("%s",W);
for(len=0;W[len]!='\0';len++)
X[len]=W[len];
X[len]='\0';
for(j=len-1;j>=0;j--)
for(k=0;k<len;k++)
{
if(X[k]!=W[j])
flag=0;
else if((j-k)==(len-1))
flag==1;
}
if (flag == 1)
printf("NICE\n");
else
printf("NOT\n");
}
}
Still not getting the proper results. Where am I going wrong?
The thing is you are only setting the value of flag if a match exists, otherwise you must set it to 0. because see, if I have:
pammbap
my prefix is pam and suffix is bap.
According to the final for loop,
p and a match so flag is set to 1.
but when it comes to b and m it does not become zero. Hence, it returns true.
First, void is not a valid return type for main, unless you are developing for Plan 9.
Second, you should get into the habit of checking the return value of scanf() and all input functions in general. You can't rely on the value of T if the user does not input a number, because T is uninitialised. On that same note, you shouldn't use scanf with an unbounded %s scan operation. If the user enters 20 characters, this isn't going to fit into the ten character buffer that you have. An alternative approach is to use fgets to get a whole line of text at once, or, to use a bounded scan operation. If your array fits 10 characters (including the null terminator) then you can use scanf("%9s", W).
Third, single-character variable names are often very hard to understand. Instead of W, use word, instead of T, use testCount or something similar. This means that someone looking at your code for the first time can more easily work out what each variable is used for.
Most importantly, think about the process in your head, and maybe jot it down on paper. How would you solve this problem yourself? As an example, starting with n = 1,
Take the first n characters from the string.
Compare it to the last n characters from the string
Do they match?
If yes, print out the first n characters as the suffix and stop processing.
If no, increment n and try again. Try until n is in the middle of the string.
There are a few other things to think about as well, do you want the biggest match? For example, in the input string ababcdabab, the prefix ab is also the suffix, but the same can be said about abab. In this case, you don't want to stop processing, you want to keep going even if you find a prefix, so, you should just store the length of the largest prefix that is also the suffix.
Second-most-importantly, running into hurdles like this is incredibly common when learning C, so don't let this put a dampener on your enthusiasm, just keep trying!

which method is fast, comparing two number strings or converting them into nunber's and then comparing

I have a simple C code which needs to compare to numbers. But the numbers are array of characters. which method will be fast to compare these numbers
1) Compare to array of numbers using strcmp function.
2) convert each number string back to number using atoi function and then compare both.
In last, I have to put back these numbers into text file.
int main(int argc, char* argv[]){
char nubmer1[] = "12823423";
char number2[] = "12453453";
//compare logic here. and need help with this.
//print to .txt file logic here. i have this with me.
}
If by "compare" you only need to know if they are not equal, strcmp is the fastest since converting them to integers will include scanning the strings and doing some multiplications before doing the comparison.
But it wont be correct. What if you have leading 0's? strcmp will not match it, but converting to numbers will.
You should think whether that matters before deciding. If the numbers are always guaranteed to be pure integers, stripping leading zeros and then strcmp would work.
strcmp will check if both numbers are equal or not. it will not check for greater than or less than in case if both numbers are not of equal lenght. So first check using strlen, if their lengths are equal then check using strcmp.
First you need to have a uniform,pre-defined format of number representation. This simplifies the following logic.
You can check if two numbers are equal or not, using strncmp() == 0 is advisable.(Avoid strcmp for security reasons, though).
If you want to check if a number is greater or less than another number:
1. First check if both of them are positive or both are negative .
2. If condition 1 is true, check string length. The one that has greater length is obviously greater.
Else check whichever has a -ve sign, is smaller than the positive or unsigned number.
3. If both strings are of same length, then compare byte by byte and find out which one is greater or lesser. NOTE when comparing negative number and positive numbers, the logic is different.
-2<-1, but +2>+1
You can optimize further in the above given logic as much as you want based on your design.
You do not need to convert them to integers for operations like >,<,= and stuff, unless you are dealing with really large numbers and have to do some arithmetic calculations.
I think you can do a experiment on this, write a test program, nice thing for your.

Provide integer arrays as input from command line

I'm writing a program to access a bin packing algorithm function from a library, I haven't done much with it since college so my C is a bit rusty. The function I'm calling requires I pass in 3 different integer arrays. I'll be calling this from the command line. Should I use argv? Or STDIN? The input arrays could potentially be 50 to 100 elements each. Either way I suppose I will have to write something to parse the strings and get them into arrays, is there an easy way to do that?
For big arrays, I'd rather use standard input, as there are usually operating system limits to how many arguments you can have.
You will also need some kind of input format. Let's say the first number n is the number of elements in the first array, followed by the element values, and so on. Then I'd do something like:
#include <stdlib.h>
#include <stdio.h>
int main()
{
// you need to implement read_number yourself
int n = read_number(stdin);
// allocate array
int *array = (int*) malloc(n*sizeof(int));
// read n numbers into array
for ( int i=0; i < n; ++i )
array[i] = read_number(stdin);
// and so on...
}
You get the general idea. You'd either have to implement read_number yourself or find examples on the net on how to do it. You will need to discern individual numbers somehow, e.g. by parsing each digit up to the next white space character. Then you can separate each digit on stdin by space characters.
For instance, you can use #ypnos suggested scanf solution below.
For that amount of elements you should use stdin. Nobody will type them in by hand anyway and ./program < file is as easy as it gets.
The parsing is no big deal with scanf. Just define that your input should include the number of elements before all the numbers forming an array. Then you can scanf("%d", &elemcount), and then for-loop over elemcount, again using scanf.
The beauty of it is that scanf will deal with all the whitespaces, newlines etc. the user may put in between the numbers of elements and the other numbers.

Resources