Program to find amount of water in a given glass | Program to find the amount of water in j - th glass of i - th row ; Returns the amount of water in jth glass of ith row ; A row number i has maximum i columns . So input column number must be less than i ; There will be i * ( i + 1 ) / 2 glasses till ith row ( including ith row ) ; Initialize all glasses as empty ; Put all water in first glass ; Now let the water flow to the downward glasses till the row number is less than or / equal to i ( given row ) correction : X can be zero for side glasses as they have lower rate to fill ; Fill glasses in a given row . Number of columns in a row is equal to row number ; Get the water from current glass ; Keep the amount less than or equal to capacity in current glass ; Get the remaining amount ; Distribute the remaining amount to the down two glasses ; The index of jth glass in ith row will be i * ( i - 1 ) / 2 + j - 1 ; Driver program to test above function ; Total amount of water
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE float findWater ( int i , int j , float X ) { if ( j > i ) { printf ( " Incorrect ▁ Inputn " ) ; exit ( 0 ) ; } float glass [ i * ( i + 1 ) / 2 ] ; memset ( glass , 0 , sizeof ( glass ) ) ; int index = 0 ; glass [ index ] = X ; for ( int row = 1 ; row <= i ; ++ row ) { for ( int col = 1 ; col <= row ; ++ col , ++ index ) { X = glass [ index ] ; glass [ index ] = ( X >= 1.0f ) ? 1.0f : X ; X = ( X >= 1.0f ) ? ( X - 1 ) : 0.0f ; glass [ index + row ] += X / 2 ; glass [ index + row + 1 ] += X / 2 ; } } return glass [ i * ( i - 1 ) / 2 + j - 1 ] ; } int main ( ) { int i = 2 , j = 2 ; float X = 2.0 ; printf ( " Amount ▁ of ▁ water ▁ in ▁ jth ▁ glass ▁ of ▁ ith ▁ row ▁ is : ▁ % f " , findWater ( i , j , X ) ) ; return 0 ; }