Hi everyone. I started coding in C yesterday. This is my first language, except some java during highschool some 8 years ago. I was reading Arthur C. Clarkes book "The last theorem", where a theorem was presented (don't remember the name); For any whole number, using the following two rules, you will always end up with "1".
1 If even number, divide by two
2 If odd number, multiply by 3, and add 1.
I figured this would be a good challenge after my first "Hello World", and here is what I came up with.
If anyone has some constructive criticism or comments, it would be greatly appreciated. Maybe someone could show me how to check if the input parameter is an integer?
Best regards,
Jonas
1 If even number, divide by two
2 If odd number, multiply by 3, and add 1.
I figured this would be a good challenge after my first "Hello World", and here is what I came up with.
Code:
#include <stdio.h>
int num;
int main ( int argc, char *argv[] )
{
if (argc != 2)
{
printf("Usage: %s N\n",argv[0]);
printf("N - integer");
return 0;
}
{
int num = atoi(argv[1]);
printf("%d\n",num);
while (num != 1)
{
if (num % 2)
{
/* Odd number. Multiply with 3 and add 1*/
num = (num * 3)+1;
printf("%d\n",num);
}
else
{
/* even number. divide by 2 */
num = num / 2;
printf("%d\n",num);
}
}
}
getchar();
}
Best regards,
Jonas
Comment