Amession
Amession

Reputation: 249

C programming printf not printing when used nested loop

I'm learning about multidimensional array in C programming. But the printf function is not working. Here is my code:

#include <stdio.h>
int main (void)
{
  int array[2][3][4]; 
  for (int i = 0; i < 3; i++)
  {
    for (int j = 0; j < 4; j++)
     {
        for (int k = 0; k < 5; k++)
        {
            array[i][j][k] = k;
            printf("array[%d][%d][%d] = %d\n", i, j, k, array[i][j][k]);
        };
    };

};
printf("Loop is finished!");
return 0;
}

Upvotes: 1

Views: 714

Answers (2)

Suji
Suji

Reputation: 1326

This program will not give result since it having lots of Syntax errors. you need not to be give ;- semicolon after for loop

syntax for For Loop is:

FOR( initialization expression;condition expression;update expression)
{
\\Loop content comes here
}

And also C will not permit Instant Declaration, variables should be declare @ the declaration section.

Your Program can be improved by applying these changes, then it gives output. the code snippet will be like the following:

#include <stdio.h>
int main ()
{
  int array[3][4][5]; 
  int i,j,k;
  for ( i = 0; i < 3; i++)
   {
     for ( j = 0; j < 4; j++)
      {
        for (k = 0; k < 5; k++)
        {
            array[i][j][k] = k;
            printf("array[%d][%d][%d] = %d\n", i, j, k, array[i][j][k]);
        }
      }
  }
  printf("Loop is finished!");
  return 0;
} 

Upvotes: 0

Keith Nicholas
Keith Nicholas

Reputation: 44298

You are going to loop out of bounds.

Take the first dimension, 2, your loop is < 3.... so its going to use indexes 0 1 2. only 0 and 1 are valid. change your loops to i < 2, j < 3 and k < 4 respectively.

Upvotes: 4

Related Questions