C programming question ... for loop?

2009-07-12 9:04 am
case 1:

#include<stdio.h>
#include<conio.h>
int main()
{
int i,j;
for (i = 4; i >= 0; i--)
{
for (j = 4;j >= i; j--)
printf ("*");
printf ("\n");
}
getch();
return 0;
}


case 2:

#include<stdio.h>
#include<conio.h>
int main()
{
int i,j;
for (i = 4; i >= 0; i--)
{
for (j = i;j >= 0; j--)
printf ("*");
printf ("\n");
}
getch();
return 0;
}


may i know what is the difference between this two codes? Why both output that i print out is not the same??
so confusing...
Anyone can help me ??? can explain to me why??


thanks so much!!

回答 (5)

2009-07-12 9:19 am
✔ 最佳答案
Sure, the difference between the two is:

Case 1 - for (j = 4;j >= i; j--)
Case 2 - for (j = i;j >= 0; j--)

These two statements act different.

Case 1, j starts at 4 and is compared to i, and the lower i goes, the more *'s are printed out.

Case 2, j is set to i, and will print as many stars as i is equal to. (Because it starts at 4 and counts down, you see ****\n***\n**\n*\n)

Case 1 will produce the following effect:
*
**
***
****

Case 2 will produce the following effect:
****
***
**
*
2016-12-16 10:12 pm
Sorry. you will desire to no longer strengthen such an impressions. that's an persons decision to apply i, j as loop administration variables. it actual relies upon on the loop shape. for(i=0;i<n-a million;i++) for(j=0;j<n-a million-i;j++) right here, i loop runs for n-a million cases on the same time as j loop runs for n-a million-i cases. it is, when I is 0, inner loop runs for n-a million cases, when I is a million it runs for n-2 cases .....when I fee is n-2 inner loop runs for a million time
2009-07-12 9:12 am
On the case one the (J) should be larger than (I) as loop repeating
But
In case of second case (J) is independent of the (I) value.
2009-07-12 9:20 am
hm.. that's odd i get the same results for both cases
2009-07-12 9:14 am
in the first code.. j = 4, in the second, j = 1..


收錄日期: 2021-04-29 00:11:34
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090712010448AAUDuqH

檢視 Wayback Machine 備份