Hello, I am currently taking an intro course to C programming, and have a few questions about an assignment I'm working on. I've Googled for this, and searched these forums, but have not been able to find anything to help thus far.
The program I have to write has to accept a five digit integer as input, print out each digit with three spaces between them, and then print the largest and smallest digit. After searching, I was able to read the digits and print them like this:
Code:
int c1;
int c2;
int c3;
int c4;
int c5;
printf( "Input a five-digit integer:\n" );
scanf( "%c%c%c%c%c", &c1, &c2, &c3, &c4, &c5 );
printf( "\nThe separated digits are:\n" );
printf( "%c %c %c %c %c\n", c1, c2, c3, c4, c5 );
This works fine, except that I next need to use Boolean logic to find the greatest and least digit. I played with a few different ways to get the smallest and largest digits, but none of them seemed to work (ie, they'd report the wrong number as being the largest). Finally, I tried to debug things by just using one if statement to compare the first two integers, and assign the value of the greater one to the variable greatest (which has its own int greatest;, which is not shown in the listing above).
Code:
if ( c1 > c2 ) {
greatest = c1;
}
else greatest = c2;
printf( "Greatest: %c\n", greatest )
The code above did not give any compile errors (with gcc on a Linux system, if it matters). However, no matter if c1 > c2 is true or not, the variable greatest always gets assigned the value of c1. So, if c2 is greater, greatest still gets the value of c1.
After looking at it, I realized that it might have something to do with using %c rather than %d; ie, it was looking for ASCII rather than integers. (I think; correct me if I'm wrong.) So, I'm thinking this could be why the conditional wasn't working. I'm reading up on the atoi function. I attempted it as follows, first creating a new set of variables set up as character strings, for instance:
Code:
char c1; /*I used one for each of the c variables respectively.*/
int d1; /*I used this for the integer values.*/
d1 = atoi( c1);
I then used the d variables (d1, d2, etc.) in the conditionals, and compiled. However, I got compilation errors:
Code:
digits.c:41: warning: passing arg 1 of `atoi' makes pointer from integer without a cast
I had one of those for each of the five atoi functions I used.
Any thoughts on this? I have a few more days for this program, and so will continue to mess with it. Thanks for any insight!