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 2 of 4.

Vinay yadav said:   1 decade ago
In Turbo C, Compiler return garbage value if the a[0] is not initialized but in GCC it return 0 so output is different.

Mayank said:   1 decade ago
++ has greater preference than assignment, rest you will understand automatically. Its better hint!

Abhishek said:   1 decade ago
In DevC++.

Output are:
2358963,1,2,3,4

Hotcpu said:   1 decade ago
I try the online gcc compiler by adding the following code,

while(i<5)
{
arr[i]=++i;
printf("i=%d arr[%d]=%d,%d \n",i,i,arr[i],arr[i-1]);
}

The interesting thing is that in the first step,
it actually did: arr[0]=++0;

So, here is the question should ++ operator affect both side of "="?

Vik said:   1 decade ago
In second for loop the condition not satisfied at last step so it prints garbage value.

Kyaw win thu said:   1 decade ago
I want to know the definition of garbage value with example please.

Gurjar said:   1 decade ago
In GCC compiler (Linux (Fedora 20)) it will give output

4195728, 1, 2, 3, 4,

Where 4195728 is garbage value.

Thanvi said:   1 decade ago
Can any one explain the difference between a++, ++a ?

Azhar said:   1 decade ago
a++ and ++a is same when we are not assigning any variable to it.

Suppose given int a=1;

Then a++ = 2.
& ++a = also 2.

But give int a = 1, b = 1;

Find.
a = b++.
a = ++b.

Here b++ is post increment and ++b is pre increment, in ++b first increment the value of b by 1 then evaluate it & in b++ (post increment) first evaluate then increment it.

Eg: Pre increment value of b is 1 after increment it becomes 2, now evaluate, evaluate means a=b, the value of b is assign to a, so a=2.

So o/p is 1 = 2 b = 2.
Eg: For post increment.

First evaluate the value i.e a = b then increment the b value. O/p a = 1, b = 2.
Same for decrement.

Note: The value will change a/c to compiler.

Nandhinivijayan said:   1 decade ago
What is meant by garbage value? How it is identified? Any one explain me clearly ASAP?


Post your comments here:

Your comments will be displayed after verification.