Home > OS >  How the code output is different when you compute it mentally? when the j = 2 the output should be 1
How the code output is different when you compute it mentally? when the j = 2 the output should be 1

Time:08-25

I was searching a method to print a pascal triangle, but when I tried to compute mentally it doesn't look right.

the output of this is 1 3 3 1. but when you mentally calculate the iteration one by one the output is 1 3 1 0. is there something that I was missing?

        #include <iostream>
        using namespace std;

        int main()
        {
           coef = 1;
           int i = 3;
           int j = 0;

             while (j <= i)
             {
               if (j == 0)
                 coef = 1;
               else
                 coef = coef * (i - j   1)/j;
  
               cout << coef << "   ";

               j  ;
             }


            return 0;
        }

CodePudding user response:

Your mental computation is bit wrong as I am sure you are not updating the value of "coef" mentally which is being changed to 3 rather than 1 which you seem to have missed after the 2nd iteration of the loop.

  •  Tags:  
  • c
  • Related