Thread: C program wierdness

  1. #1
    Registered User
    Join Date
    Feb 2004
    Posts
    2

    C program wierdness

    ok i'm trying to learn c before moving on to c++ and this is what i get when compiling this in dev-c++

    Code:
    #include<stdio.h>
    
    int main()
    {
        int a,b,c;
        a;
        b;
        c = a + b;
        
        printf("Enter the value of the first number: ");
        scanf("%d", &a);
        printf("Enter the value of the second number: ");
        scanf("%d", &b);
    
        printf("%d + %d = %d\n", a,  b, c);
        
        system("pause");
        return 0;
    }
    the output (say i enter 5 and 7) is

    5 + 7 = 8413188

    anyone know what the deal is

  2. #2
    'AlHamdulillah
    Join Date
    Feb 2003
    Posts
    790
    well, you never actually get a real value in the variable c. You declare c as

    Code:
    int c = a + b;
    at the beginning of the program, you want that after you accept the input, because when you do the above, you are putting the values of a and b AT THAT time, which are garbage values

    EDIT:
    also,
    Code:
    a;
    b;
    does nothing, you are looking for
    Code:
    a = 0;
    b = 0;
    I would really recommend you read some of the tutorials on this site and others.

  3. #3
    Registered User
    Join Date
    Feb 2004
    Posts
    46
    Code:
    c = a + b;
    Local variables aren't initialized to anything in particular, so there is no way to predict what the value of c will be after this statement. Move it down in your code to a place after you give values to a and b but before you print.
    Code:
    a;
    b;
    These don't do anything of use to you. All each statement does is evaluate the contents of a or b and do nothing with it. You can safely remove these two statements.
    Code:
    system("pause");
    You must include stdlib.h to make the system function available.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int a,b,c;
    
        printf("Enter the value of the first number: ");
        scanf("%d", &a);
        printf("Enter the value of the second number: ");
        scanf("%d", &b);
        c = a + b;
        printf("%d + %d = %d\n", a,  b, c);
    
        system("pause");
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with a program, theres something in it for you
    By engstudent363 in forum C Programming
    Replies: 1
    Last Post: 02-29-2008, 01:41 PM
  2. Replies: 4
    Last Post: 02-21-2008, 10:39 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM