C Programming - Command Line Arguments - Discussion

Discussion Forum : Command Line Arguments - Find Output of Program (Q.No. 10)
10.
What will be the output of the program (sample.c) given below if it is executed from the command line?
cmd> sample one two three
/* sample.c */
#include<stdio.h>

int main(int argc, char *argv[])
{
    int i=0;
    i+=strlen(argv[1]);
    while(i>0)
    {
        printf("%c", argv[1][--i]);
    }
    return 0;
}
three two one
owt
eno
eerht
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
18 comments Page 1 of 2.

Maris said:   1 decade ago
i=i+strlen(argv[1]); //i=0+3;
while(i>0) //while(3>0)
argv[1][--i] //argv[1][3] =>e and
i value decremented to 2[--i]
// argv[1][2]=>n

and i=1[--i] //argv[1][1]=>o

o/p:eno

Siva said:   1 decade ago
@maris...small mistake

while(3>0)
argv[1][--i] .. its predecrement ..so argv[1][2]->e..and so on..

Vishyy said:   1 decade ago
How does this program will execute. ?

Somebody please tell the process.

Pallavi said:   1 decade ago
In printf statement %c is used.
And if argv[1][--i]=argv[1][2]=e then i am expecting only 'e' to be printed as output then how option 'c' i.e 'eno' can be the answer?

Chandra said:   1 decade ago
@pallavi: While loop will be continue.

Ani said:   1 decade ago
@maris has explained it right..only it shud b decremented first..argv[1][--i])// argv[1][2]..argv[1][1]..argv[1][0]

Please Note: Loop runs for 0 also bcoz at the time of entry check while first check i>0 ie 1>0 and then inside loop it decrements it to 0.

Vaibhav sharma said:   1 decade ago
i=i+strlen(argv[1]); //i=0+3;
while(i>0) //while(3>0)
argv[1][--i] //argv[1][2] =>e and
i value decremented to 2[--i]
// argv[1][1]=>n

and i=1[--i] //argv[1][0]=>o

o/p:eno

Rajat Jain said:   1 decade ago
i=i+strlen(argv[1]); //i=0+3;
while(i>0) //while(3>0)
argv[1][--i] //argv[1][2] =>e and
i value decremented to 2[--i]
// argv[1][2]=>n

and i=1[--i] //argv[1][1]=>o

How is it ??? argv[1]=3
argv[1][2] =>e

Vaibhav said:   1 decade ago
Explanation-.
0th row - sample.
1st row - one.
2nd row- second.
3rd row - third.

Now argv[1][2] means 1st row and 2nd column which is e.

0 1 2 3 4 5
S a m p l e
O n e
S e c o n d

Please correct me if I am wrong. Thanks.

Nitin said:   1 decade ago
Can anybody Tell me How argument is passed in a main function ?

What this argv, *argv means.


Post your comments here:

Your comments will be displayed after verification.