Three short questions C-ers

This is a discussion on Three short questions C-ers within the C Programming forums, part of the General Programming Boards category; Hi guys I have three separate, non-related code that each give out a certain value that I can't just figure ...

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    25

    Three short questions C-ers

    Hi guys

    I have three separate, non-related code that each give out a certain value that I can't just figure why....

    could you help me with them?

    Code:
    int arr[] = {5,6,7,8,9,10};
    
    int x = 1;
    
    int *p = arr + 2 ; //I have mainly problem with definition of this line
    
    p--;
    
    x = p[x]
    this one gives you 7.


    the other is a segment : it's to give you 15...why???

    Code:
    for( i= 3; i != 15; i= i + 2);
    and the last gives you just zero. I'm not sure if I totally understand the while(0) loop?

    Code:
    int main(void) {
    
    int r = -1 ;
    
    while (r++) {
    
       printf("r = %d \n", r);
    
    }
      return 0;
    
    }
    I'd be grateful for any help

  2. #2
    Registered User
    Join Date
    Nov 2012
    Posts
    1,067
    Rewrite each one in a way that makes sense to you.

    1.
    Code:
    int arr[] = {5,6,7,8,9,10}; 
    int x = 1;
    int *p = &arr[2];  // p points to the 7
    p--;               // p points to the 6
    x = p[x]           // p[1] points to the element one spot after the 6
    So x is 7, like you would expect. Notice &arr[2] is the same as arr + 2

    2. A general for loop... for(INIT; COND; INCR) STAT; can be rewritten as
    Code:
    INIT;
    while (COND) {
        STAT;
        INCR;
    }
    So, using this transformation, your for loop is the same as
    Code:
    i = 3;
    while (i != 15)
        i = i + 2;
    So the final value is 15. It says in English "Start the loop at i=3. Loop until i becomes 15, then stop. Each time through the loop, increment i by 2"

    3. An expression like VAR++ is the same as saying this:
    VAR;
    VAR = VAR + 1;
    So rewrite your third snippet like this
    Code:
    int r = -1 ;
     
    while (r) {
       r = r + 1;
       printf("r = %d \n", r);
     
    }
    r = r + 1;

  3. #3
    Registered User
    Join Date
    Oct 2012
    Posts
    25
    wow!! thanks a lot!! now I see them all. Very helpful

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 10-01-2012, 10:57 PM
  2. 5 short questions ٩(͡๏̯͡๏)۶
    By Minty in forum C# Programming
    Replies: 6
    Last Post: 05-30-2011, 04:00 PM
  3. Replies: 14
    Last Post: 03-08-2010, 05:32 PM
  4. Short questions...
    By Devil Panther in forum C++ Programming
    Replies: 7
    Last Post: 09-03-2005, 02:47 PM
  5. A Few Short Questions....
    By SithVegeta in forum C Programming
    Replies: 6
    Last Post: 11-14-2004, 10:52 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21