Thread: Help with explaining a C program

  1. #1
    Registered User
    Join Date
    May 2018
    Posts
    1

    Question Help with explaining a C program

    Hello.I am having trouble of understanding why this codes outputs these numbers: 9,1,9,3,8,5. Can someone please explain how the program works?
    Code:
    :
    
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
    int arr[6]={9,7,9,8,8,9};
    int i=-1;
    while(i<5){
        i=i+2;
        arr[i]=i;
    }
    for(i=0;i<6;i++){
        printf("%d, ",arr[i]);
    }
    return 0;
    }

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Why don't you take your best guess, and explain what you think happens, then let us help you with the parts you don't know.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Through an additive process, a position in the array is chosen, and then assigned, such that the position number and the number stored are the same.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Try adding debug print statements where you're confused.

    Say
    Code:
    while(i<5){
        i=i+2;
        arr[i]=i;
        printf("arr[%d]=%d\n", i, i );
    }
    When you get bored of editing code to find out what variables contain, learn how to use a debugger to really get control of how your program behaves.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help explaining
    By witt in forum C++ Programming
    Replies: 1
    Last Post: 10-11-2011, 03:06 PM
  2. help in explaining the program
    By jazzz in forum C Programming
    Replies: 2
    Last Post: 05-23-2006, 12:42 AM
  3. I need help explaining something...
    By deathstryke in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 01-08-2003, 12:02 PM
  4. Help in explaining this short program
    By sturm100 in forum C Programming
    Replies: 22
    Last Post: 05-30-2002, 05:06 AM
  5. need graphics.h explaining.
    By will bushnell in forum C Programming
    Replies: 17
    Last Post: 03-28-2002, 11:18 PM

Tags for this Thread