Comments on my code?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • warbird
    New Member
    • Feb 2010
    • 1

    Comments on my code?

    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.

    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();
    }
    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
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    scanf(argv[1],"%d",&value ) will return 0 if failed to convert the value. You may also check that num*3 is still within integer range (INT_MAX in limits.h).

    Comment

    • grayMist
      New Member
      • Feb 2010
      • 12

      #3
      scanf(argv[1],"%d",&value )
      Should rather be
      sscanf(argv[1],"%d",&value ) ...

      Comment

      Working...