Thread: Question about For (Loop)

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    1

    Question about For (Loop)

    Hi,,
    I really confuse about a part of this program using for loop :

    for(i=0; i<3; i++) {
    for(j=0; j<3; j++)
    if(matrix[i][j]==0) matrix[i][j]=no;
    if(matrix[i][j]==0) matrix[i][j]=55;
    ++no;
    }

    Code:
    #include <stdio.h>
    
    int main(){
    	int matrix[3][3];
    	int i,j, no=1;
    
    	for(i=0; i<3; i++) {
    		for(j=0; j<3; j++){
    			matrix[i][j]=0;
    		}
    	}
    
    	
    	
    	for(i=0; i<3; i++) {
    		for(j=0; j<3; j++)
    			if(matrix[i][j]==0) matrix[i][j]=no;
    		if(matrix[i][j]==0) matrix[i][j]=55;
    		++no;
    	}
    	
    	for(i=0; i<3; i++) {
    		for(j=0; j<3; j++) {
    			printf("%d   ", matrix[i][j]);
    		if (j==2) printf("\n");
    		}
    	}
    
    	return 0;
    }
    it will output 1 1 1
    55 2 2
    55 3 3

    I really confuse about the output >_< can you please explain to me how is the process in for loop so we get that output?

    I think it must be 55 1 1
    55 2 2
    55 3 3

    I really need the explanation ASAP XD ^^
    Thank you ^^

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Sorry, you don't get off that easy!

    Add some print statements into your code, and print out the array. You'll see what it's doing, and learn something about C, and basic troubleshooting, (a valuable skill to cultivate), as well.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You have a buffer overrun in that code. The value of a loop variable after the loop is the first value that made the condition false.
    The first thing that makes j<3 false is when j is 3.
    You then proceed to use j, so bad things can happen.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question bout my work
    By SirTalksAlots in forum C Programming
    Replies: 4
    Last Post: 07-18-2010, 03:23 PM
  2. A question about a question
    By hausburn in forum C++ Programming
    Replies: 3
    Last Post: 04-25-2010, 05:24 AM
  3. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM

Tags for this Thread