Thread: Cannot understand this FOR statement!

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    2

    Cannot understand this FOR statement!

    Code:
    char a[] = {21,12,5,7,1,9};
    int size = 6;
    int i,j,temp;
    for(i=1;i<size;i++)
    {
    temp=a[i];
    for(j=i; (j>0) && (a[j-1]>temp); j--)
    {
    a[j]=a[j-1];
    }
    a[j]=temp;
    }
    After this code is executed what values are stored in the array a?

    The answer is:
    {1,5,7,9,12,21}

    However, I do not understand the steps undertaken to get to this solution.
    IF somebody can show how they reached the FIRST array I could work from there.

  2. #2
    Registered User
    Join Date
    Sep 2010
    Posts
    25
    I wrapped that code in a main and added in two printfs. It compiles with one warning, but works well enough to show the values. Example below. Maybe this will help you.

    Code:
    main()
    {
    char a[] = {21,12,5,7,1,9};
    int size = 6;
    int i,j,temp;
    for(i=1;i<size;i++)
    {
    temp=a[i];
    printf ("value of temp  is: %d \n", temp);
    printf ("value of i in temp's a[i] is: %d \n", i);
    for(j=i; (j>0) && (a[j-1]>temp); j--)
    {
    a[j]=a[j-1];
    }
    a[j]=temp;
    }
    return 0;
    }

  3. #3
    Registered User
    Join Date
    Dec 2010
    Posts
    2
    I have tried it using your method however the answers are different.
    Code:
    C:\MyPrograms>q1.exe
    value of temp  is: 12
    value of i in temp's a[i] is: 1
    value of temp  is: 5
    value of i in temp's a[i] is: 2
    value of temp  is: 7
    value of i in temp's a[i] is: 3
    value of temp  is: 1
    value of i in temp's a[i] is: 4
    value of temp  is: 9
    value of i in temp's a[i] is: 5

  4. #4
    Registered User
    Join Date
    Nov 2010
    Posts
    42
    i will use my code to explain you. it get the same result as yours too.

    Code:
    main()
    {
    	int i,j;
    	int temp;
    	int number[]={21,12,5,7,1,9};
    for(i=0;i<6;i++)
    {
    	for(j=i+1;j<6;j++)
    	{
    		if(number[i]>number[j])
    		{
    			temp=number[i];
    			number[i]=number[j];
    			number[j]=temp;
    		}
    	}
    }
    
    for(i=0;i<6;i++)
    printf("%d\n",number[i]);
    
    }

Popular pages Recent additions subscribe to a feed