Thread: scanf returns random character

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    2

    scanf returns random character

    Hi all,

    I am trying to run a simple program in order to learn c but the scanf gives me some trouble.

    Below is the code:
    Code:
        int count,num,total;
        
        for (count = 1; count < 7;count++) {
            printf("Num %d:",count);
            scanf("%d",num);
            printf("%d\n",num);
            total = total + num;     
        }
        printf("total is:%d\n",total);
        char ch;
        
        scanf("%d",ch);
    now whenever i run the code, and give 1 as input, the printf statement which is inside the loop gives me this number: 2621256.

    Could someone please explain me what it this number?

    Kind Regards,
    Ioannis

  2. #2
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    that's the garbage that was in num when you started the program, you need to do
    scanf("%d", &num);

    also, total = total + num is the same as total += num
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    2
    this is a very quick reply i have to say
    thanks very much honestly.

    one more question .

    why the print of total at the end of the code prints 15727538 instead of 15727536 which is the actual sum?

    again thanks a lot for your help.

    Regards,
    Ioannis

  4. #4
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    Quote Originally Posted by giannisapi View Post
    this is a very quick reply i have to say
    thanks very much honestly.

    one more question .

    why the print of total at the end of the code prints 15727538 instead of 15727536 which is the actual sum?

    again thanks a lot for your help.

    Regards,
    Ioannis
    because total contains the garbage that was in it when you started the program, total = total + sum
    set total to 0 before you use it
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. about wide character and multiple byte character
    By George2 in forum C Programming
    Replies: 3
    Last Post: 05-22-2006, 08:11 PM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  4. Random character generator algorithm
    By m712 in forum C++ Programming
    Replies: 7
    Last Post: 12-09-2002, 04:28 AM
  5. Best way to generate a random double?
    By The V. in forum C Programming
    Replies: 3
    Last Post: 10-16-2001, 04:11 PM