Thread: C program

  1. #1
    Registered User NiĀz's Avatar
    Join Date
    Apr 2014
    Location
    India
    Posts
    4

    C program

    Code:
    Hi can you plz explain me the below program :
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    int a=6,b=4;
    int c=a+b;
    printf("%d",c);
    return 0;
    }
    Out put >> 10
    
    I f i scan the input's like below i get variable answers on every debug why so
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    int a,b;
    int c=a+b;
    scanf("%d%d",&a,&b);
    printf("%d",c);
    return 0;
    }
    
    i.e, if i give i/p as 6 & 4 i get output as : 4341809 sometimes 8732171 its varies >>> check my output online too > C code - 11 lines - codepad

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    In C, values are calculated as they are encountered during code execution.

    "c=a+b" does not set up a formula that automatically updates the value of 'c' whenever 'a' and 'b' change values.

    Instead, the line "c=a+b" calculates the sum once. At that point, 'a' and 'b' aren't initialized, or given meaningful values, so they contain random values. These random values are added and stored into 'c'.

    So you have to move the "c=a+b" line after 'a' and 'b' are given values.

  3. #3
    Registered User Alpo's Avatar
    Join Date
    Apr 2014
    Posts
    877
    If I understand you correctly, I think the problem is that you are assigning c before values are stored in a or b. Try declaring c first, and moving the assignment below scanf.

  4. #4
    Registered User
    Join Date
    Apr 2014
    Posts
    1
    use c = a+b; only if and b has the values that you want store in it.

  5. #5
    Registered User NiĀz's Avatar
    Join Date
    Apr 2014
    Location
    India
    Posts
    4
    Awesome understanding..got your point thanQ so much

  6. #6
    Registered User NiĀz's Avatar
    Join Date
    Apr 2014
    Location
    India
    Posts
    4
    Ya i knew that but still i wan to know why this happens..Thanx for your reply got my answer

  7. #7
    Registered User NiĀz's Avatar
    Join Date
    Apr 2014
    Location
    India
    Posts
    4
    ThanQ

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to return to the start of a program/ a specific point of a program
    By ē¦ę©ä½• in forum C++ Programming
    Replies: 1
    Last Post: 01-21-2013, 07:15 AM
  2. Replies: 2
    Last Post: 12-11-2012, 12:25 AM
  3. Replies: 1
    Last Post: 03-03-2009, 04:47 PM
  4. Replies: 5
    Last Post: 08-16-2007, 11:43 PM
  5. Replies: 18
    Last Post: 11-13-2006, 01:11 PM