C Programming - Arrays - Discussion

Discussion Forum : Arrays - Find Output of Program (Q.No. 7)
7.
What will be the output of the program in Turb C (under DOS)?
#include<stdio.h>

int main()
{
    int arr[5], i=0;
    while(i<5)
        arr[i]=++i;

    for(i=0; i<5; i++)
        printf("%d, ", arr[i]);

    return 0;
}
1, 2, 3, 4, 5,
Garbage value, 1, 2, 3, 4,
0, 1, 2, 3, 4,
2, 3, 4, 5, 6,
Answer: Option
Explanation:

Since C is a compiler dependent language, it may give different outputs at different platforms. We have given the TurboC Compiler (Windows) output.

Please try the above programs in Windows (Turbo-C Compiler) and Linux (GCC Compiler), you will understand the difference better.

Discussion:
38 comments Page 1 of 4.

Zishu said:   1 decade ago
Why this program doesn't give the first option as output?

Rajendra Singh said:   1 decade ago
The output depends upon compiler to compiler.
Under Turbo C output will "Gabage, 1, 2, 3, 4,"
Under Dev-C++ output will "1, 2, 3, 4, 5,"

But in statement "arr[i]=++i;" operator '++' has higher precedence than operator '='. So first pre-increment will take place then assignment operator. So the assignment will be as following.

arr[i]=++i; --> arr[1]=1;
arr[i]=++i; --> arr[2]=2;
arr[i]=++i; --> arr[3]=3;
arr[i]=++i; --> arr[4]=4;
arr[i]=++i; --> arr[5]=5;

But at arr[0], there will be garbage value. and arr[5] is out of bound.

Nishitha said:   1 decade ago
But why it will give garbage value?

Jorge said:   1 decade ago
It will be garbage value because the array is not initialized with any value at the beginning, the memory allocated by the array could contain random data from the ram.

Sundar said:   1 decade ago
I have tested the above program in Turbo C and GCC.

The output of the program in Turbo C (DOS 16 bit OS):

816, 1, 2, 3, 4,

[Note: Here 816 is a garbage value.]

The output of the program in GCC (Linux 32 bit OS):

1, 2, 3, 4, 5,

I hope this will help you. Have a nice day!

Rupinderjit said:   1 decade ago
Many thanks jorge for the explanation

Karthick said:   1 decade ago
@rajendra singh
Thanks a lot..

Maikal said:   1 decade ago
Rajendra singh & JORGE thanks for discuss this question, I WILL HOPE TO U FOR OTHER QUESTION EXPLANATION

Abhimanyu said:   1 decade ago
How it will give garbege value?

Ecc29 said:   1 decade ago
Can anyone explain the output difference between Turbo C and GCC please?


Post your comments here:

Your comments will be displayed after verification.