BLOGGER TEMPLATES AND TWITTER BACKGROUNDS

25 January, 2011

Java: Reverse a number

This program will reverse a long and store it in another.

class NumRev
{
public static void main(String ar[])
{
long num = 1357912; /* Try with diff values */
long rev = 0;
int i = (((Long)num).toString()).length(); /* No of digits */


System.out.println("Original Number: " + num);
for(i-=1; num!=0; i--)
{
long rem = num % 10;
rev += (rem * Math.pow(10, i));
num /= 10;
}


System.out.println("Reversed Number: " + rev);
}
}


Difficulty Rating: 2.5/10
For creative minds: This program gets the number of digits in a number by converting it to a string. Can you do it without the string portion? Is it possible to reverse without using the number of digits at all?

04 August, 2009

Accept a Password string, displaying it as *

This program will accept a string from the user as a password, displaying *'s instead of the data entered by the user.
Lang: C

#include(stdio.h)
#include(conio.h)
#include(string.h)
void main() /* Or int main() with return 0 */
{
char pass[20];
int i;

printf("Enter password: ");
for(i=0; i<20; i+=1)
{
pass[i] = getch();
if(pass[i] == '\r') /* The carriage return escape sequence */
break;
printf("*");
}

pass[i] = '\0';
printf("\n");
if(strcmp(pass, "123")) /* Assume "123" is the correct password */
printf("Correct Password");
else
printf("Wrong Password");

getch();
}

Difficulty Rating: 3/10
For Creative Minds: Try using this with getche() instead of getch(). What changes will you have to make?