C program with array 2D problem explanation included.

 Firstly we need to define array size as 4 using #define size 4 that can use to mention value as a example when declare array we can use #define size 4 to mention as size in array not only for array. Okay lets go! now we prepare an integer variable i and j with assign 0 and also we need char type array to store char value we store only "R","G","B" if add any other values the program should terminate now we need get user input before check the user input we store all value 4 by 4 matrix because we consider it as bulb panel(4 by 4) other thing is program should display all the build with color as matrix (that the reason to I use array) and also we need show where the red bulb position (print index of 2d array where red color bulb store) we get user input inside the 2 for loop first bulb we mention with variable i  for(i=0;i<size;i++) we use size to indicate #define size 4 so size value is 4 so first loop run 4 times because size value is 4 and i value is 0(0,1,2,3 not 4 because i<size)  now we going to create second loop we should want second loop because this based on the 2d array second loop we create with j ([i][j]) now for(j=0;j<size;j++) now i and j value is 0 (row index metion by i loop colum index mention by j loop).

now we need get input both loop inside because that help to store value to index 0,0 in the 2d array we get String value to store like below "%s" we use to get string value and it store inside the arr[i][j](i=0,j=0)  when execute j loop or second loop that i value is 0 but j loop run until it over but i not change because still we in first row of the colum j index increase like ([i=0][j=0],[i=0][j=1],[i=0][j=2],[i=0][j=3]) when j loop terminate then i loop index enhance by one now we in second row (i=1) this is the process.

ADS

printf("input bulb color= ");  scanf("%s",&arr[i][j]);

if user enter "R","G","B" then no error if enter any other value without that value then you get error we use return -1 for that.

      if(arr[i][j]!='R' && arr[i][j]!='G' && arr[i][j]!='B')

         {

            return -1; 

         }

  when print all bulb we do like previous using 2 loops like below

 for(i=0;i<size;i++)

   {

      for(j=0;j<size;j++)

      {

         printf("%c  ",arr[i][j]);

      }

      printf("\n\n");

   }

eventually we need display red bulb color positions as well as previous we use 2 loops and only deferent is we check it is red or green or blue with condition like below  if(arr[i][j]=='R') if it is red the that index print  printf("[%d%d]",i,j); if not then no any value print.

Post a Comment

0 Comments